diff --git a/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg b/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg new file mode 100644 index 0000000000..5457b3f1ca --- /dev/null +++ b/AutomatedTesting/AssetProcessorGamePlatformConfig.setreg @@ -0,0 +1,19 @@ +{ + "Amazon": { + "AssetProcessor": { + "Settings": { + "RC cgf": { + "ignore": true + }, + "RC fbx": { + "ignore": true + }, + "ScanFolder AtomTestData": { + "watch": "@ENGINEROOT@/Gems/Atom/TestData", + "recursive": 1, + "order": 1000 + } + } + } + } +} diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py index 3004b9ec7d..3d4d9ea419 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py @@ -29,7 +29,7 @@ def teardown_editor(editor): def launch_and_validate_results(request, test_directory, editor, editor_script, expected_lines, unexpected_lines=[], halt_on_unexpected=False, run_python="--runpythontest", auto_test_mode=True, null_renderer=True, cfg_args=[], - timeout=300): + timeout=300, log_file_name="Editor.log"): """ Runs the Editor with the specified script, and monitors for expected log lines. :param request: Special fixture providing information of the requesting test function. @@ -44,6 +44,7 @@ def launch_and_validate_results(request, test_directory, editor, editor_script, :param null_renderer: Specifies the test does not require the renderer. Defaults to True. :param cfg_args: Additional arguments for CFG, such as LevelName. :param timeout: Length of time for test to run. Default is 60. + :param log_file_name: Name of the log file created by the editor. Defaults to 'Editor.log' """ test_case = os.path.join(test_directory, editor_script) request.addfinalizer(lambda: teardown_editor(editor)) @@ -58,7 +59,17 @@ def launch_and_validate_results(request, test_directory, editor, editor_script, with editor.start(): - editorlog_file = os.path.join(editor.workspace.paths.project_log(), 'Editor.log') + editorlog_file = os.path.join(editor.workspace.paths.project_log(), log_file_name) + + # Log monitor requires the file to exist. + logger.debug(f"Waiting until log file <{editorlog_file}> exists...") + waiter.wait_for( + lambda: os.path.exists(editorlog_file), + timeout=60, + exc=f"Log file '{editorlog_file}' was never created by another process.", + interval=1, + ) + logger.debug(f"Done! log file <{editorlog_file}> exists.") # Initialize the log monitor and set time to wait for log creation log_monitor = ly_test_tools.log.log_monitor.LogMonitor(launcher=editor, log_file_path=editorlog_file) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py new file mode 100644 index 0000000000..b3c51ca912 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py @@ -0,0 +1,183 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +import azlmbr.materialeditor will fail with a ModuleNotFound error when using this script with Editor.exe +This is because azlmbr.materialeditor only binds to MaterialEditor.exe and not Editor.exe +You need to launch this script with MaterialEditor.exe in order for azlmbr.materialeditor to appear. +""" + +import os +import sys +import time + +import azlmbr.math as math +import azlmbr.paths + +sys.path.append(os.path.join(azlmbr.paths.devassets, "Gem", "PythonTests")) + +import atom_renderer.atom_utils.material_editor_utils as material_editor + +NEW_MATERIAL = "test_material.material" +NEW_MATERIAL_1 = "test_material_1.material" +NEW_MATERIAL_2 = "test_material_2.material" +TEST_MATERIAL_1 = "001_DefaultWhite.material" +TEST_MATERIAL_2 = "002_BaseColorLerp.material" +TEST_MATERIAL_3 = "003_MetalMatte.material" +TEST_DATA_PATH = os.path.join( + azlmbr.paths.devroot, "Gems", "Atom", "TestData", "TestData", "Materials", "StandardPbrTestCases" +) +MATERIAL_TYPE_PATH = os.path.join( + azlmbr.paths.devroot, "Gems", "Atom", "Feature", "Common", "Assets", + "Materials", "Types", "StandardPBR.materialtype", +) + + +def run(): + """ + Summary: + Material Editor basic tests including the below + 1. Opening an Existing Asset + 2. Creating a New Asset + 3. Closing Selected Material + 4. Closing All Materials + 5. Closing all but Selected Material + 6. Saving Material + 7. Saving as a New Material + 8. Saving as a Child Material + 9. Saving all Open Materials + + Expected Result: + All the above functions work as expected in Material Editor. + + :return: None + """ + + # 1) Test Case: Opening an Existing Asset + document_id = material_editor.open_material(MATERIAL_TYPE_PATH) + print(f"Material opened: {material_editor.is_open(document_id)}") + + # Verify if the test material exists initially + target_path = os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Materials", NEW_MATERIAL) + print(f"Test asset doesn't exist initially: {not os.path.exists(target_path)}") + + # 2) Test Case: Creating a New Material Using Existing One + material_editor.save_document_as_child(document_id, target_path) + material_editor.wait_for_condition(lambda: os.path.exists(target_path), 2.0) + print(f"New asset created: {os.path.exists(target_path)}") + + # Verify if the newly created document is open + new_document_id = material_editor.open_material(target_path) + material_editor.wait_for_condition(lambda: material_editor.is_open(new_document_id)) + print(f"New Material opened: {material_editor.is_open(new_document_id)}") + + # 3) Test Case: Closing Selected Material + print(f"Material closed: {material_editor.close_document(new_document_id)}") + + # Open materials initially + document1_id, document2_id, document3_id = ( + material_editor.open_material(os.path.join(TEST_DATA_PATH, material)) + for material in [TEST_MATERIAL_1, TEST_MATERIAL_2, TEST_MATERIAL_3] + ) + + # 4) Test Case: Closing All Materials + print(f"All documents closed: {material_editor.close_all_documents()}") + + # 5) Test Case: Closing all but Selected Material + document1_id, document2_id, document3_id = ( + material_editor.open_material(os.path.join(TEST_DATA_PATH, material)) + for material in [TEST_MATERIAL_1, TEST_MATERIAL_2, TEST_MATERIAL_3] + ) + result = material_editor.close_all_except_selected(document1_id) + print(f"Close All Except Selected worked as expected: {result and material_editor.is_open(document1_id)}") + + # 6) Test Case: Saving Material + document_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + property_name = azlmbr.name.Name("baseColor.color") + initial_color = material_editor.get_property(document_id, property_name) + # Assign new color to the material file and save the actual material + expected_color = math.Color(0.25, 0.25, 0.25, 1.0) + material_editor.set_property(document_id, property_name, expected_color) + material_editor.save_document(document_id) + + # 7) Test Case: Saving as a New Material + # Assign new color to the material file and save the document as copy + expected_color_1 = math.Color(0.5, 0.5, 0.5, 1.0) + material_editor.set_property(document_id, property_name, expected_color_1) + target_path_1 = os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Materials", NEW_MATERIAL_1) + material_editor.save_document_as_copy(document_id, target_path_1) + time.sleep(2.0) + + # 8) Test Case: Saving as a Child Material + # Assign new color to the material file save the document as child + expected_color_2 = math.Color(0.75, 0.75, 0.75, 1.0) + material_editor.set_property(document_id, property_name, expected_color_2) + target_path_2 = os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Materials", NEW_MATERIAL_2) + material_editor.save_document_as_child(document_id, target_path_2) + time.sleep(2.0) + + # Close/Reopen documents + material_editor.close_all_documents() + document_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + document1_id = material_editor.open_material(target_path_1) + document2_id = material_editor.open_material(target_path_2) + + # Verify if the changes are saved in the actual document + actual_color = material_editor.get_property(document_id, property_name) + print(f"Actual Document saved with changes: {material_editor.compare_colors(actual_color, expected_color)}") + + # Verify if the changes are saved in the document saved as copy + actual_color = material_editor.get_property(document1_id, property_name) + result_copy = material_editor.compare_colors(actual_color, expected_color_1) + print(f"Document saved as copy is saved with changes: {result_copy}") + + # Verify if the changes are saved in the document saved as child + actual_color = material_editor.get_property(document2_id, property_name) + result_child = material_editor.compare_colors(actual_color, expected_color_2) + print(f"Document saved as child is saved with changes: {result_child}") + + # Revert back the changes in the actual document + material_editor.set_property(document_id, property_name, initial_color) + material_editor.save_document(document_id) + material_editor.close_all_documents() + + # 9) Test Case: Saving all Open Materials + # Open first material and make change to the values + document1_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + property1_name = azlmbr.name.Name("metallic.factor") + initial_metallic_factor = material_editor.get_property(document1_id, property1_name) + expected_metallic_factor = 0.444 + material_editor.set_property(document1_id, property1_name, expected_metallic_factor) + + # Open second material and make change to the values + document2_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_2)) + property2_name = azlmbr.name.Name("baseColor.color") + initial_color = material_editor.get_property(document2_id, property2_name) + expected_color = math.Color(0.4156, 0.0196, 0.6862, 1.0) + material_editor.set_property(document2_id, property2_name, expected_color) + + # Save all and close all documents + material_editor.save_all() + material_editor.close_all_documents() + + # Reopen materials and verify values + document1_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_1)) + result = material_editor.is_close( + material_editor.get_property(document1_id, property1_name), expected_metallic_factor, 0.00001 + ) + document2_id = material_editor.open_material(os.path.join(TEST_DATA_PATH, TEST_MATERIAL_2)) + result = result and material_editor.compare_colors( + expected_color, material_editor.get_property(document2_id, property2_name)) + print(f"Save All worked as expected: {result}") + + # Revert the changes made + material_editor.set_property(document1_id, property1_name, initial_metallic_factor) + material_editor.set_property(document2_id, property2_name, initial_color) + material_editor.save_all() + material_editor.close_all_documents() + + +if __name__ == "__main__": + run() diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py new file mode 100644 index 0000000000..77d1285188 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/material_editor_utils.py @@ -0,0 +1,274 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +import azlmbr.materialeditor will fail with a ModuleNotFound error when using this script with Editor.exe +This is because azlmbr.materialeditor only binds to MaterialEditor.exe and not Editor.exe +You need to launch this script with MaterialEditor.exe in order for azlmbr.materialeditor to appear. +""" + +import os +import sys +import time +import azlmbr.atom +import azlmbr.materialeditor as materialeditor +import azlmbr.bus as bus +import azlmbr.atomtools.general as general + + +def is_close(actual, expected, buffer=sys.float_info.min): + """ + :param actual: actual value + :param expected: expected value + :param buffer: acceptable variation from expected + :return: bool + """ + return abs(actual - expected) < buffer + + +def compare_colors(color1, color2, buffer=0.00001): + """ + Compares the red, green and blue properties of a color allowing a slight variance of buffer + :param color1: first color to compare + :param color2: second color + :param buffer: allowed variance in individual color value + :return: bool + """ + return ( + is_close(color1.r, color2.r, buffer) + and is_close(color1.g, color2.g, buffer) + and is_close(color1.b, color2.b, buffer) + ) + + +def open_material(file_path): + """ + :return: uuid of material document opened + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "OpenDocument", file_path) + + +def is_open(document_id): + """ + :return: bool + """ + return materialeditor.MaterialDocumentRequestBus(bus.Event, "IsOpen", document_id) + + +def save_document(document_id): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "SaveDocument", document_id) + + +def save_document_as_copy(document_id, target_path): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus( + bus.Broadcast, "SaveDocumentAsCopy", document_id, target_path + ) + + +def save_document_as_child(document_id, target_path): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus( + bus.Broadcast, "SaveDocumentAsChild", document_id, target_path + ) + + +def save_all(): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "SaveAllDocuments") + + +def close_document(document_id): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseDocument", document_id) + + +def close_all_documents(): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseAllDocuments") + + +def close_all_except_selected(document_id): + """ + :return: bool success + """ + return materialeditor.MaterialDocumentSystemRequestBus(bus.Broadcast, "CloseAllDocumentsExcept", document_id) + + +def get_property(document_id, property_name): + """ + :return: property value or invalid value if the document is not open or the property_name can't be found + """ + return materialeditor.MaterialDocumentRequestBus(bus.Event, "GetPropertyValue", document_id, property_name) + + +def set_property(document_id, property_name, value): + materialeditor.MaterialDocumentRequestBus(bus.Event, "SetPropertyValue", document_id, property_name, value) + + +def is_pane_visible(pane_name): + """ + :return: bool + """ + return materialeditor.MaterialEditorWindowRequestBus(bus.Broadcast, "IsDockWidgetVisible", pane_name) + + +def set_pane_visibility(pane_name, value): + materialeditor.MaterialEditorWindowRequestBus(bus.Broadcast, "SetDockWidgetVisible", pane_name, value) + + +def select_lighting_config(config_name): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SelectLightingPresetByName", config_name) + + +def set_grid_enable_disable(value): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SetGridEnabled", value) + + +def get_grid_enable_disable(): + """ + :return: bool + """ + return azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "GetGridEnabled") + + +def set_shadowcatcher_enable_disable(value): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SetShadowCatcherEnabled", value) + + +def get_shadowcatcher_enable_disable(): + """ + :return: bool + """ + return azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "GetShadowCatcherEnabled") + + +def select_model_config(configname): + azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SelectModelPresetByName", configname) + + +def wait_for_condition(function, timeout_in_seconds=1.0): + # type: (function, float) -> bool + """ + Function to run until it returns True or timeout is reached + the function can have no parameters and + waiting idle__wait_* is handled here not in the function + + :param function: a function that returns a boolean indicating a desired condition is achieved + :param timeout_in_seconds: when reached, function execution is abandoned and False is returned + """ + with Timeout(timeout_in_seconds) as t: + while True: + try: + general.idle_wait_frames(1) + except Exception: + print("WARNING: Couldn't wait for frame") + + if t.timed_out: + return False + + ret = function() + if not isinstance(ret, bool): + raise TypeError("return value for wait_for_condition function must be a bool") + if ret: + return True + + +class Timeout: + # type: (float) -> None + """ + contextual timeout + :param seconds: float seconds to allow before timed_out is True + """ + + def __init__(self, seconds): + self.seconds = seconds + + def __enter__(self): + self.die_after = time.time() + self.seconds + return self + + def __exit__(self, type, value, traceback): + pass + + @property + def timed_out(self): + return time.time() > self.die_after + + +screenshotsFolder = os.path.join(azlmbr.paths.devroot, "AtomTest", "Cache" "pc", "Screenshots") + + +class ScreenshotHelper: + """ + A helper to capture screenshots and wait for them. + """ + + def __init__(self, idle_wait_frames_callback): + super().__init__() + self.done = False + self.capturedScreenshot = False + self.max_frames_to_wait = 60 + + self.idle_wait_frames_callback = idle_wait_frames_callback + + def capture_screenshot_blocking(self, filename): + """ + Capture a screenshot and block the execution until the screenshot has been written to the disk. + """ + self.handler = azlmbr.atom.FrameCaptureNotificationBusHandler() + self.handler.connect() + self.handler.add_callback("OnCaptureFinished", self.on_screenshot_captured) + + self.done = False + self.capturedScreenshot = False + success = azlmbr.atom.FrameCaptureRequestBus(azlmbr.bus.Broadcast, "CaptureScreenshot", filename) + if success: + self.wait_until_screenshot() + print("Screenshot taken.") + else: + print("screenshot failed") + return self.capturedScreenshot + + def on_screenshot_captured(self, parameters): + # the parameters come in as a tuple + if parameters[0]: + print("screenshot saved: {}".format(parameters[1])) + self.capturedScreenshot = True + else: + print("screenshot failed: {}".format(parameters[1])) + self.done = True + self.handler.disconnect() + + def wait_until_screenshot(self): + frames_waited = 0 + while self.done == False: + self.idle_wait_frames_callback(1) + if frames_waited > self.max_frames_to_wait: + print("timeout while waiting for the screenshot to be written") + self.handler.disconnect() + break + else: + frames_waited = frames_waited + 1 + print("(waited {} frames)".format(frames_waited)) + + +def capture_screenshot(file_path): + return ScreenshotHelper(azlmbr.atomtools.general.idle_wait_frames).capture_screenshot_blocking( + os.path.join(file_path) + ) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index 39689816b8..be75801b63 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -11,6 +11,7 @@ import os import pytest +import ly_test_tools.environment.file_system as file_system import editor_python_test_tools.hydra_test_utils as hydra from atom_renderer.atom_utils.atom_constants import LIGHT_TYPES @@ -242,3 +243,65 @@ class TestAtomEditorComponentsMain(object): null_renderer=True, cfg_args=cfg_args, ) + + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("launcher_platform", ['windows_generic']) +@pytest.mark.system +class TestMaterialEditorBasicTests(object): + @pytest.fixture(autouse=True) + def setup_teardown(self, request, workspace, project): + def delete_files(): + file_system.delete( + [ + os.path.join(workspace.paths.project(), "Materials", "test_material.material"), + os.path.join(workspace.paths.project(), "Materials", "test_material_1.material"), + os.path.join(workspace.paths.project(), "Materials", "test_material_2.material"), + ], + True, + True, + ) + # Cleanup our newly created materials + delete_files() + + def teardown(): + # Cleanup our newly created materials + delete_files() + + request.addfinalizer(teardown) + + @pytest.mark.parametrize("exe_file_name", ["MaterialEditor"]) + def test_MaterialEditorBasicTests( + self, request, workspace, project, launcher_platform, generic_launcher, exe_file_name): + + expected_lines = [ + "Material opened: True", + "Test asset doesn't exist initially: True", + "New asset created: True", + "New Material opened: True", + "Material closed: True", + "All documents closed: True", + "Close All Except Selected worked as expected: True", + "Actual Document saved with changes: True", + "Document saved as copy is saved with changes: True", + "Document saved as child is saved with changes: True", + "Save All worked as expected: True", + ] + unexpected_lines = [ + # "Trace::Assert", + # "Trace::Error", + "Traceback (most recent call last):" + ] + + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + generic_launcher, + "hydra_AtomMaterialEditor_BasicTests.py", + run_python="--runpython", + timeout=80, + expected_lines=expected_lines, + unexpected_lines=unexpected_lines, + halt_on_unexpected=True, + log_file_name="MaterialEditor.log", + ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py old mode 100755 new mode 100644 index d191a82a58..4ab5a41b85 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py @@ -105,7 +105,7 @@ class TestGeneralGraphFunctionality(object): @pytest.mark.test_case_id("C17488412") @pytest.mark.SUITE_periodic - @pytest.mark.xfail # https://github.com/o3de/o3de/issues/2201 + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2201") def test_LandscapeCanvas_GraphClosed_OnEntityDelete(self, request, editor, level, launcher_platform): cfg_args = [level] diff --git a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py new file mode 100644 index 0000000000..44b7dc2ee4 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py @@ -0,0 +1,66 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt:off +class Tests(): + create_new_entity = ("Entity: 'CreateNewEntity' passed", "Entity: 'CreateNewEntity' failed") + create_prefab = ("Prefab: 'CreatePrefab' passed", "Prefab: 'CreatePrefab' failed") + instantiate_prefab = ("Prefab: 'InstantiatePrefab' passed", "Prefab: 'InstantiatePrefab' failed") + new_prefab_position = ("Prefab: new prefab's position is at the expected position", "Prefab: new prefab's position is *not* at the expected position") +# fmt:on + +def PrefabLevel_BasicWorkflow(): + """ + This test will help verify if the following functions related to Prefab work as expected: + - CreatePrefab + - InstantiatePrefab + """ + + import os + import sys + + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + import editor_python_test_tools.hydra_editor_utils as hydra + + import azlmbr.bus as bus + import azlmbr.entity as entity + from azlmbr.entity import EntityId + import azlmbr.editor as editor + import azlmbr.prefab as prefab + from azlmbr.math import Vector3 + import azlmbr.legacy.general as general + + EXPECTED_NEW_PREFAB_POSITION = Vector3(10.00, 20.0, 30.0) + + helper.init_idle() + helper.open_level("Prefab", "Base") + +# Create a new Entity at the root level + new_entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', EntityId()) + Report.result(Tests.create_new_entity, new_entity_id.IsValid()) + +# Checks for prefab creation passed or not + new_prefab_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'new_prefab.prefab') + create_prefab_result = prefab.PrefabPublicRequestBus(bus.Broadcast, 'CreatePrefabInMemory', [new_entity_id], new_prefab_file_path) + Report.result(Tests.create_prefab, create_prefab_result) + +# Checks for prefab instantiation passed or not + container_entity_id = prefab.PrefabPublicRequestBus(bus.Broadcast, 'InstantiatePrefab', new_prefab_file_path, EntityId(), EXPECTED_NEW_PREFAB_POSITION) + Report.result(Tests.instantiate_prefab, container_entity_id.IsValid()) + +# Checks if the new prefab is at the correct position and if it fails, it will provide the expected postion and the actual postion of the entity in the Editor log + new_prefab_position = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", container_entity_id) + is_at_position = new_prefab_position.IsClose(EXPECTED_NEW_PREFAB_POSITION) + Report.result(Tests.new_prefab_position, is_at_position) + if not is_at_position: + Report.info(f'Expected position: {EXPECTED_NEW_PREFAB_POSITION.ToString()}, actual position: {new_prefab_position.ToString()}') + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(PrefabLevel_BasicWorkflow) diff --git a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py index acd8f60b07..4e3d6ba77f 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py @@ -16,6 +16,7 @@ from ly_test_tools import LAUNCHERS sys.path.append (os.path.dirname (os.path.abspath (__file__)) + '/../automatedtesting_shared') +import ly_test_tools.environment.file_system as file_system from base import TestAutomationBase @pytest.mark.SUITE_main @@ -29,3 +30,8 @@ class TestAutomation(TestAutomationBase): def test_PrefabLevel_OpensLevelWithEntities(self, request, workspace, editor, launcher_platform): from . import PrefabLevel_OpensLevelWithEntities as test_module self._run_prefab_test(request, workspace, editor, test_module) + + def test_PrefabLevel_BasicWorkflow(self, request, workspace, editor, launcher_platform): + from . import PrefabLevel_BasicWorkflow as test_module + self._run_prefab_test(request, workspace, editor, test_module) + diff --git a/AutomatedTesting/Levels/Prefab/Base/Base.prefab b/AutomatedTesting/Levels/Prefab/Base/Base.prefab new file mode 100644 index 0000000000..f7e42e7731 --- /dev/null +++ b/AutomatedTesting/Levels/Prefab/Base/Base.prefab @@ -0,0 +1,53 @@ +{ + "ContainerEntity": { + "Id": "Entity_[1146574390643]", + "Name": "Level", + "Components": { + "Component_[10641544592923449938]": { + "$type": "EditorInspectorComponent", + "Id": 10641544592923449938 + }, + "Component_[12039882709170782873]": { + "$type": "EditorOnlyEntityComponent", + "Id": 12039882709170782873 + }, + "Component_[12265484671603697631]": { + "$type": "EditorPendingCompositionComponent", + "Id": 12265484671603697631 + }, + "Component_[14126657869720434043]": { + "$type": "EditorEntitySortComponent", + "Id": 14126657869720434043 + }, + "Component_[15230859088967841193]": { + "$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent", + "Id": 15230859088967841193, + "Parent Entity": "" + }, + "Component_[16239496886950819870]": { + "$type": "EditorDisabledCompositionComponent", + "Id": 16239496886950819870 + }, + "Component_[5688118765544765547]": { + "$type": "EditorEntityIconComponent", + "Id": 5688118765544765547 + }, + "Component_[6545738857812235305]": { + "$type": "SelectionComponent", + "Id": 6545738857812235305 + }, + "Component_[7247035804068349658]": { + "$type": "EditorPrefabComponent", + "Id": 7247035804068349658 + }, + "Component_[9307224322037797205]": { + "$type": "EditorLockComponent", + "Id": 9307224322037797205 + }, + "Component_[9562516168917670048]": { + "$type": "EditorVisibilityComponent", + "Id": 9562516168917670048 + } + } + } +} \ No newline at end of file diff --git a/Code/Editor/GameEngine.h b/Code/Editor/GameEngine.h index 84df8bf002..829baec55a 100644 --- a/Code/Editor/GameEngine.h +++ b/Code/Editor/GameEngine.h @@ -20,6 +20,7 @@ #include "LogFile.h" #include "CryListenerSet.h" #include "Util/ModalWindowDismisser.h" +#include #endif class CStartupLogoDialog; diff --git a/Code/Editor/Include/IFileUtil.h b/Code/Editor/Include/IFileUtil.h index 746a81b87c..700e04f6d3 100644 --- a/Code/Editor/Include/IFileUtil.h +++ b/Code/Editor/Include/IFileUtil.h @@ -9,6 +9,7 @@ #pragma once #include "../Include/SandboxAPI.h" +#include class QWidget; diff --git a/Code/Editor/Include/IObjectManager.h b/Code/Editor/Include/IObjectManager.h index ce9d69681b..360cc8fe34 100644 --- a/Code/Editor/Include/IObjectManager.h +++ b/Code/Editor/Include/IObjectManager.h @@ -12,8 +12,10 @@ #pragma once #include +#include #include #include +#include // forward declarations. class CEntityObject; diff --git a/Code/Editor/Objects/ObjectLoader.h b/Code/Editor/Objects/ObjectLoader.h index 9410a4845a..a491e50da0 100644 --- a/Code/Editor/Objects/ObjectLoader.h +++ b/Code/Editor/Objects/ObjectLoader.h @@ -15,6 +15,8 @@ #include "Util/GuidUtil.h" #include "ErrorReport.h" +#include + class CPakFile; class CErrorRecord; struct IObjectManager; diff --git a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp index 581f9a576d..1ea70e8c22 100644 --- a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp +++ b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp @@ -9,6 +9,7 @@ #include "CryFile.h" #include "PerforceSourceControl.h" #include "PasswordDlg.h" +#include #include #include diff --git a/Code/Editor/QtUtil.h b/Code/Editor/QtUtil.h index 380f4dfa4a..195340ecb7 100644 --- a/Code/Editor/QtUtil.h +++ b/Code/Editor/QtUtil.h @@ -10,6 +10,7 @@ #pragma once #include +#include #include #include diff --git a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp index 148b1cbdfe..4099443913 100644 --- a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp +++ b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h index 0ba10d7388..f6046b9f25 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/ToolsApplicationAPI.h @@ -600,8 +600,8 @@ namespace AzToolsFramework * Open 3D Engine Internal use only. * * Run a specific redo command separate from the undo/redo system. - * In many cases before a modifcation on an entity takes place, it is first packaged into - * undo/redo commands. Running the modification's redo command separete from the undo/redo + * In many cases before a modification on an entity takes place, it is first packaged into + * undo/redo commands. Running the modification's redo command separate from the undo/redo * system simulates its execution, and avoids some code duplication. */ virtual void RunRedoSeparately(UndoSystem::URSequencePoint* redoCommand) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp index 970f5aa28c..56ef749247 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp @@ -1781,5 +1781,4 @@ namespace AzToolsFramework { appType.m_maskValue = AZ::ApplicationTypeQuery::Masks::Tool; }; - } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index bb394720c9..7af953efca 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -61,7 +61,7 @@ namespace AzToolsFramework m_prefabUndoCache.Destroy(); } - PrefabOperationResult PrefabPublicHandler::CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) + PrefabOperationResult PrefabPublicHandler::CreatePrefabInMemory(const AZStd::vector& entityIds, AZ::IO::PathView filePath) { EntityList inputEntityList, topLevelEntities; AZ::EntityId commonRootEntityId; @@ -73,8 +73,6 @@ namespace AzToolsFramework return findCommonRootOutcome; } - AZ_Assert(absolutePath.IsAbsolute(), "CreatePrefab requires an absolute path for saving the initial prefab file."); - InstanceOptionalReference instanceToCreate; { // Initialize Undo Batch object @@ -125,7 +123,7 @@ namespace AzToolsFramework PrefabDom linkPatchesCopy; linkPatchesCopy.CopyFrom(linkPatches->get(), linkPatchesCopy.GetAllocator()); nestedInstanceLinkPatchesMap.emplace(nestedInstance, AZStd::move(linkPatchesCopy)); - + RemoveLink(outInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch()); instancePtrs.emplace_back(AZStd::move(outInstance)); @@ -139,18 +137,20 @@ namespace AzToolsFramework if (!prefabEditorEntityOwnershipInterface) { return AZ::Failure(AZStd::string("Could not create a new prefab out of the entities provided - internal error " - "(PrefabEditorEntityOwnershipInterface unavailable).")); + "(PrefabEditorEntityOwnershipInterface unavailable).")); } // Create the Prefab + AZ_Assert(filePath.IsAbsolute(), "CreatePrefabInMemory requires an absolute file path."); + instanceToCreate = prefabEditorEntityOwnershipInterface->CreatePrefab( - entities, AZStd::move(instancePtrs), m_prefabLoaderInterface->GenerateRelativePath(absolutePath), + entities, AZStd::move(instancePtrs), m_prefabLoaderInterface->GenerateRelativePath(filePath), commonRootEntityOwningInstance); if (!instanceToCreate) { return AZ::Failure(AZStd::string("Could not create a new prefab out of the entities provided - internal error " - "(A null instance is returned).")); + "(A null instance is returned).")); } AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); @@ -218,7 +218,7 @@ namespace AzToolsFramework linkUpdate.Redo(); } }); - + // Create a link between the templates of the newly created instance and the instance it's being parented under. CreateLink( instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(), @@ -255,18 +255,35 @@ namespace AzToolsFramework // Select Container Entity { - auto selectionUndo = aznew SelectionCommand({containerEntityId}, "Select Prefab Container Entity"); + auto selectionUndo = aznew SelectionCommand({ containerEntityId }, "Select Prefab Container Entity"); selectionUndo->SetParent(undoBatch.GetUndoBatch()); ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequestBus::Events::RunRedoSeparately, selectionUndo); } } - // Save Template to file - m_prefabLoaderInterface->SaveTemplateToFile(instanceToCreate->get().GetTemplateId(), absolutePath); - return AZ::Success(); } + PrefabOperationResult PrefabPublicHandler::CreatePrefabInDisk(const AZStd::vector& entityIds, AZ::IO::PathView filePath) + { + auto result = CreatePrefabInMemory(entityIds, filePath); + if (result.IsSuccess()) + { + // Save Template to file + auto relativePath = m_prefabLoaderInterface->GenerateRelativePath(filePath); + Prefab::TemplateId templateId = m_prefabSystemComponentInterface->GetTemplateIdFromFilePath(relativePath); + if (!m_prefabLoaderInterface->SaveTemplateToFile(templateId, filePath)) + { + AZStd::string_view filePathString(filePath); + return AZ::Failure(AZStd::string::format( + "Could not save the newly created prefab to file path %.*s - internal error ", + AZ_STRING_ARG(filePathString))); + } + } + + return result; + } + PrefabDom PrefabPublicHandler::ApplyContainerTransformAndGeneratePatch(AZ::EntityId containerEntityId, AZ::EntityId parentEntityId, const EntityList& childEntities) { AZ::Entity* containerEntity = GetEntityById(containerEntityId); @@ -301,7 +318,7 @@ namespace AzToolsFramework return AZStd::move(patch); } - PrefabOperationResult PrefabPublicHandler::InstantiatePrefab( + InstantiatePrefabResult PrefabPublicHandler::InstantiatePrefab( AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) { auto prefabEditorEntityOwnershipInterface = AZ::Interface::Get(); @@ -347,6 +364,7 @@ namespace AzToolsFramework relativePath.Native().c_str(), instanceToParentUnder->get().GetTemplateSourcePath().Native().c_str())); } + AZ::EntityId containerEntityId; { // Initialize Undo Batch object ScopedUndoBatch undoBatch("Instantiate Prefab"); @@ -367,7 +385,7 @@ namespace AzToolsFramework instanceToParentUnder->get(), "Update prefab instance", instanceToParentUnderDomBeforeCreate, undoBatch.GetUndoBatch()); // Create Link with correct container patches - AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); + containerEntityId = instanceToCreate->get().GetContainerEntityId(); AZ::Entity* containerEntity = GetEntityById(containerEntityId); AZ_Assert(containerEntity, "Invalid container entity detected in InstantiatePrefab."); @@ -394,7 +412,7 @@ namespace AzToolsFramework &AzToolsFramework::ToolsApplicationRequestBus::Events::ClearDirtyEntities); } - return AZ::Success(); + return AZ::Success(containerEntityId); } PrefabOperationResult PrefabPublicHandler::FindCommonRootOwningInstance( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 0e24b0841d..8f124e8edd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -42,8 +42,11 @@ namespace AzToolsFramework void UnregisterPrefabPublicHandlerInterface(); // PrefabPublicInterface... - PrefabOperationResult CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) override; - PrefabOperationResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) override; + PrefabOperationResult CreatePrefabInDisk( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) override; + PrefabOperationResult CreatePrefabInMemory( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) override; + InstantiatePrefabResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) override; PrefabOperationResult SavePrefab(AZ::IO::Path filePath) override; PrefabEntityResult CreateEntity(AZ::EntityId parentId, const AZ::Vector3& position) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h index 6b3fdcd391..67d65dfca6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h @@ -25,6 +25,7 @@ namespace AzToolsFramework namespace Prefab { typedef AZ::Outcome PrefabOperationResult; + typedef AZ::Outcome InstantiatePrefabResult; typedef AZ::Outcome PrefabRequestResult; typedef AZ::Outcome PrefabEntityResult; @@ -39,22 +40,34 @@ namespace AzToolsFramework AZ_RTTI(PrefabPublicInterface, "{931AAE9D-C775-4818-9070-A2DA69489CBE}"); /** - * Create a prefab out of the entities provided, at the path provided. + * Create a prefab out of the entities provided, at the path provided, and save it in disk immediately. * Automatically detects descendants of entities, and discerns between entities and child instances. * @param entityIds The entities that should form the new prefab (along with their descendants). * @param filePath The absolute path for the new prefab file. * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. */ - virtual PrefabOperationResult CreatePrefab(const AZStd::vector& entityIds, AZ::IO::PathView absolutePath) = 0; + virtual PrefabOperationResult CreatePrefabInDisk( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) = 0; + + /** + * Create a prefab out of the entities provided, at the path provided, and keep it in memory. + * Automatically detects descendants of entities, and discerns between entities and child instances. + * @param entityIds The entities that should form the new prefab (along with their descendants). + * @param filePath The absolute path for the new prefab file. + * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. + */ + virtual PrefabOperationResult CreatePrefabInMemory( + const AZStd::vector& entityIds, AZ::IO::PathView filePath) = 0; /** * Instantiate a prefab from a prefab file. * @param filePath The path to the prefab file to instantiate. * @param parent The entity the prefab should be a child of in the transform hierarchy. * @param position The position in world space the prefab should be instantiated in. - * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. + * @return An outcome object with an entityId of the new prefab's container entity; + * on failure, it comes with an error message detailing the cause of the error. */ - virtual PrefabOperationResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) = 0; + virtual InstantiatePrefabResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) = 0; /** * Saves changes to prefab to disk. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h new file mode 100644 index 0000000000..1b86d3cd4e --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace AzToolsFramework +{ + namespace Prefab + { + /** + * The primary purpose of this bus is to facilitate writing automated tests for prefabs. + * It calls PrefabPublicInterface internally to talk to the prefab system. + * If you would like to integrate prefabs into your system, please call PrefabPublicInterface + * directly for better performance. + */ + class PrefabPublicRequests + : public AZ::EBusTraits + { + public: + using Bus = AZ::EBus; + + ////////////////////////////////////////////////////////////////////////// + // EBusTraits overrides + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + ////////////////////////////////////////////////////////////////////////// + + virtual ~PrefabPublicRequests() = default; + + /** + * Create a prefab out of the entities provided, at the path provided, and keep it in memory. + * Automatically detects descendants of entities, and discerns between entities and child instances. + */ + virtual bool CreatePrefabInMemory( + const AZStd::vector& entityIds, AZStd::string_view filePath) = 0; + + /** + * Instantiate a prefab from a prefab file. + */ + virtual AZ::EntityId InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) = 0; + }; + + using PrefabPublicRequestBus = AZ::EBus; + + } // namespace Prefab +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp new file mode 100644 index 0000000000..0e68a286a6 --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +#include + +namespace AzToolsFramework +{ + namespace Prefab + { + void PrefabPublicRequestHandler::Reflect(AZ::ReflectContext* context) + { + AZ::BehaviorContext* behaviorContext = azrtti_cast(context); + if (behaviorContext) + { + behaviorContext->EBus("PrefabPublicRequestBus") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) + ->Attribute(AZ::Script::Attributes::Category, "Prefab") + ->Attribute(AZ::Script::Attributes::Module, "prefab") + ->Event("CreatePrefabInMemory", &PrefabPublicRequests::CreatePrefabInMemory) + ->Event("InstantiatePrefab", &PrefabPublicRequests::InstantiatePrefab) + ; + } + } + + void PrefabPublicRequestHandler::Connect() + { + m_prefabPublicInterface = AZ::Interface::Get(); + AZ_Assert(m_prefabPublicInterface, "PrefabPublicRequestHandler - Could not retrieve instance of PrefabPublicInterface"); + + PrefabPublicRequestBus::Handler::BusConnect(); + } + + void PrefabPublicRequestHandler::Disconnect() + { + PrefabPublicRequestBus::Handler::BusDisconnect(); + + m_prefabPublicInterface = nullptr; + } + + bool PrefabPublicRequestHandler::CreatePrefabInMemory(const AZStd::vector& entityIds, AZStd::string_view filePath) + { + auto createPrefabOutcome = m_prefabPublicInterface->CreatePrefabInMemory(entityIds, filePath); + if (!createPrefabOutcome.IsSuccess()) + { + AZ_Error("CreatePrefabInMemory", false, + "Failed to create Prefab on file path '%.*s'. Error message: %s.", + AZ_STRING_ARG(filePath), + createPrefabOutcome.GetError().c_str()); + + return false; + } + + return true; + } + + AZ::EntityId PrefabPublicRequestHandler::InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) + { + auto instantiatePrefabOutcome = m_prefabPublicInterface->InstantiatePrefab(filePath, parent, position); + if (!instantiatePrefabOutcome.IsSuccess()) + { + AZ_Error("InstantiatePrefab", false, + "Failed to instantiate Prefab on file path '%.*s'. Error message: %s.", + AZ_STRING_ARG(filePath), + instantiatePrefabOutcome.GetError().c_str()); + + return AZ::EntityId(); + } + + return instantiatePrefabOutcome.GetValue(); + } + } // namespace Prefab +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h new file mode 100644 index 0000000000..548bc8e04a --- /dev/null +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include + +#include + +namespace AzToolsFramework +{ + namespace Prefab + { + class PrefabPublicInterface; + + class PrefabPublicRequestHandler final + : public PrefabPublicRequestBus::Handler + { + public: + AZ_CLASS_ALLOCATOR(PrefabPublicRequestHandler, AZ::SystemAllocator, 0); + AZ_RTTI(PrefabPublicRequestHandler, "{83FBDDF9-10BE-4373-B1DC-44B47EE4805C}"); + + static void Reflect(AZ::ReflectContext* context); + + void Connect(); + void Disconnect(); + + bool CreatePrefabInMemory(const AZStd::vector& entityIds, AZStd::string_view filePath) override; + AZ::EntityId InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) override; + + private: + PrefabPublicInterface* m_prefabPublicInterface = nullptr; + }; + } // namespace Prefab +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index bfdb6b79f2..1051e530c8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -35,12 +35,14 @@ namespace AzToolsFramework m_instanceUpdateExecutor.RegisterInstanceUpdateExecutorInterface(); m_instanceToTemplatePropagator.RegisterInstanceToTemplateInterface(); m_prefabPublicHandler.RegisterPrefabPublicHandlerInterface(); + m_prefabPublicRequestHandler.Connect(); AZ::SystemTickBus::Handler::BusConnect(); } void PrefabSystemComponent::Deactivate() { AZ::SystemTickBus::Handler::BusDisconnect(); + m_prefabPublicRequestHandler.Disconnect(); m_prefabPublicHandler.UnregisterPrefabPublicHandlerInterface(); m_instanceToTemplatePropagator.UnregisterInstanceToTemplateInterface(); m_instanceUpdateExecutor.UnregisterInstanceUpdateExecutorInterface(); @@ -54,6 +56,7 @@ namespace AzToolsFramework AzToolsFramework::Prefab::PrefabConversionUtils::PrefabConversionPipeline::Reflect(context); AzToolsFramework::Prefab::PrefabConversionUtils::PrefabCatchmentProcessor::Reflect(context); AzToolsFramework::Prefab::PrefabConversionUtils::EditorInfoRemover::Reflect(context); + PrefabPublicRequestHandler::Reflect(context); AZ::SerializeContext* serialize = azrtti_cast(context); if (serialize) @@ -62,7 +65,6 @@ namespace AzToolsFramework } AZ::JsonRegistrationContext* jsonRegistration = azrtti_cast(context); - if (jsonRegistration) { jsonRegistration->Serializer()->HandlesType(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h index 04457b5a97..b07ccbada6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -369,6 +370,9 @@ namespace AzToolsFramework // Used for updating Templates when Instances are modified InstanceToTemplatePropagator m_instanceToTemplatePropagator; + + // Handler of the public Prefab requests + PrefabPublicRequestHandler m_prefabPublicRequestHandler; }; } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp index 5bf9b15abe..eb9cf2b65f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp @@ -256,11 +256,11 @@ namespace AzToolsFramework void PrefabIntegrationManager::HandleSourceFileType(AZStd::string_view sourceFilePath, AZ::EntityId parentId, AZ::Vector3 position) const { - auto createPrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(sourceFilePath, parentId, position); + auto instantiatePrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(sourceFilePath, parentId, position); - if (!createPrefabOutcome.IsSuccess()) + if (!instantiatePrefabOutcome.IsSuccess()) { - WarnUserOfError("Prefab Instantiation Error", createPrefabOutcome.GetError()); + WarnUserOfError("Prefab Instantiation Error", instantiatePrefabOutcome.GetError()); } } @@ -348,7 +348,7 @@ namespace AzToolsFramework } } - auto createPrefabOutcome = s_prefabPublicInterface->CreatePrefab(selectedEntities, prefabFilePath.data()); + auto createPrefabOutcome = s_prefabPublicInterface->CreatePrefabInDisk(selectedEntities, prefabFilePath.data()); if (!createPrefabOutcome.IsSuccess()) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index 53173f83af..14c5f34f90 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -657,6 +657,9 @@ set(FILES Prefab/PrefabPublicHandler.cpp Prefab/PrefabPublicInterface.h Prefab/PrefabPublicNotificationBus.h + Prefab/PrefabPublicRequestBus.h + Prefab/PrefabPublicRequestHandler.h + Prefab/PrefabPublicRequestHandler.cpp Prefab/PrefabUndo.h Prefab/PrefabUndo.cpp Prefab/PrefabUndoCache.cpp diff --git a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp index 6acf778798..08c5408848 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp +++ b/Code/Framework/GridMate/GridMate/Carrier/SocketDriver.cpp @@ -1527,7 +1527,7 @@ namespace GridMate if (0 != WSAIoctl( m_socket, SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER, &functionTableId, sizeof(GUID), (void**)&m_RIO_FN_TABLE, sizeof(m_RIO_FN_TABLE), &dwBytes, 0, 0)) { - AZ_Error("GridMate", false, "Could not initialize RIO: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not initialize RIO: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } else @@ -1542,13 +1542,13 @@ namespace GridMate if ((m_events[WakeupOnSend] = WSACreateEvent()) == WSA_INVALID_EVENT) { - AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if ((m_events[ReceiveEvent] = WSACreateEvent()) == WSA_INVALID_EVENT) { - AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } RIO_NOTIFICATION_COMPLETION typeRecv; @@ -1558,13 +1558,13 @@ namespace GridMate m_RIORecvQueue = m_RIO_FN_TABLE.RIOCreateCompletionQueue(maxOutstandingReceive, &typeRecv); if (m_RIORecvQueue == RIO_INVALID_CQ) { - AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if ((m_events[SendEvent] = WSACreateEvent()) == WSA_INVALID_EVENT) { - AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Failed WSACreateEvent(): %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } RIO_NOTIFICATION_COMPLETION typeSend; @@ -1574,7 +1574,7 @@ namespace GridMate m_RIOSendQueue = m_RIO_FN_TABLE.RIOCreateCompletionQueue(maxOutstandingSend, &typeSend); if (m_RIOSendQueue == RIO_INVALID_CQ) { - AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not RIOCreateCompletionQueue: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } @@ -1582,7 +1582,7 @@ namespace GridMate maxReceiveDataBuffers, maxOutstandingSend, maxSendDataBuffers, m_RIORecvQueue, m_RIOSendQueue, pContext); if (m_requestQueue == RIO_INVALID_RQ) { - AZ_Error("GridMate", m_requestQueue != NULL, "Could not RIOCreateRequestQueue: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", m_requestQueue != NULL, "Could not RIOCreateRequestQueue: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } @@ -1595,24 +1595,24 @@ namespace GridMate //Setup Recv raw buffer and RIO record if (nullptr == (m_rawRecvBuffer = AllocRIOBuffer(bufferSize, m_RIORecvBufferCount, &recvAllocated))) { - AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if (RIO_INVALID_BUFFERID == (recvBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawRecvBuffer, bufferSize * m_RIORecvBufferCount))) { - AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } //Setup Recv address raw buffer and RIO record if (nullptr == (m_rawRecvAddressBuffer = AllocRIOBuffer(sizeof(SOCKADDR_INET), m_RIORecvBufferCount, &recvAddrsAllocated))) { - AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not allocate buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if (RIO_INVALID_BUFFERID == (recvAddressBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawRecvAddressBuffer, sizeof(SOCKADDR_INET) * m_RIORecvBufferCount))) { - AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } @@ -1639,7 +1639,7 @@ namespace GridMate //Start Receive Handler if (false == m_RIO_FN_TABLE.RIOReceiveEx(m_requestQueue, &m_RIORecvBuffer[i], 1, NULL, &m_RIORecvAddressBuffer[i], NULL, NULL, 0, pBuffer)) { - AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } } @@ -1649,25 +1649,25 @@ namespace GridMate //setup send raw buffer and RIO record if (nullptr == (m_rawSendBuffer = AllocRIOBuffer(bufferSize, m_RIOSendBufferCount, &sendAllocated))) { - AZ_Error("GridMate", false, "Could not allocate buffer: %u", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not allocate buffer: %u", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if (RIO_INVALID_BUFFERID == (sendBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawSendBuffer, m_RIOSendBufferCount * bufferSize))) { - AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } //setup send address raw buffer and RIO record if (nullptr == (m_rawSendAddressBuffer = AllocRIOBuffer(sizeof(SOCKADDR_INET), m_RIOSendBufferCount, &sendAddrsAllocated))) { - AZ_Error("GridMate", false, "Could not allocate send address buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not allocate send address buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } if (RIO_INVALID_BUFFERID == (sendAddressBufferId = m_RIO_FN_TABLE.RIORegisterBuffer(m_rawSendAddressBuffer, m_RIOSendBufferCount * sizeof(SOCKADDR_INET)))) { - AZ_Error("GridMate", false, "Could not register buffer: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not register buffer: %u\n", GridMate::Platform::GetSocketError()); return EC_SOCKET_CREATE; } @@ -1725,7 +1725,7 @@ namespace GridMate if (!m_RIO_FN_TABLE.RIOSendEx(m_requestQueue, &m_RIOSendBuffer[m_workerNextSendBuffer], bufferCount, NULL, &m_RIOSendAddressBuffer[m_workerNextSendBuffer], NULL, NULL, 0, 0)) { - const DWORD lastError = ::WSAGetLastError(); + const DWORD lastError = GridMate::Platform::GetSocketError(); if (lastError == WSAENOBUFS) { continue; //spin until free @@ -1835,7 +1835,7 @@ namespace GridMate if (false == m_RIO_FN_TABLE.RIOReceiveEx(m_requestQueue, &m_RIORecvBuffer[m_RIONextRecvBuffer], bufferCount, NULL, &m_RIORecvAddressBuffer[m_RIONextRecvBuffer], NULL, NULL, 0, 0)) { - AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", ::WSAGetLastError()); + AZ_Error("GridMate", false, "Could not RIOReceive: %u\n", GridMate::Platform::GetSocketError()); } if (recvd) @@ -1866,7 +1866,7 @@ namespace GridMate { if (!WSAResetEvent(m_events[Index - WSA_WAIT_EVENT_0])) { - AZ_Assert(false, "WSAResetEvent failed with error = %d\n", ::WSAGetLastError()); + AZ_Assert(false, "WSAResetEvent failed with error = %d\n", GridMate::Platform::GetSocketError()); } }; @@ -1925,7 +1925,7 @@ namespace GridMate } else if (isFailed(Index)) { - AZ_Assert(false, "WSAWaitForMultipleEvents failed with error = %d\n", ::WSAGetLastError()); + AZ_Assert(false, "WSAWaitForMultipleEvents failed with error = %d\n", GridMate::Platform::GetSocketError()); return false; } else @@ -1944,7 +1944,7 @@ namespace GridMate { if (!SetEvent(m_events[WakeupOnSend])) //Wake thread { - AZ_Assert(false, "SetEvent failed with error = %d\n", ::WSAGetLastError()); + AZ_Assert(false, "SetEvent failed with error = %d\n", GridMate::Platform::GetSocketError()); } } diff --git a/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp b/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp index 1e87b902a6..3030dcc740 100644 --- a/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp +++ b/Code/LauncherUnified/Platform/Linux/Launcher_Linux.cpp @@ -10,6 +10,7 @@ #include #include // for AZ_MAX_PATH_LEN +#include #include diff --git a/Code/Legacy/CryCommon/AndroidSpecific.h b/Code/Legacy/CryCommon/AndroidSpecific.h index 0cb4a6786c..cf4359ba47 100644 --- a/Code/Legacy/CryCommon/AndroidSpecific.h +++ b/Code/Legacy/CryCommon/AndroidSpecific.h @@ -30,16 +30,6 @@ #define MOBILE #endif -// Force all allocations to be aligned to TARGET_DEFAULT_ALIGN. -// This is because malloc on Android 32 bit returns memory that is not aligned -// to what some structs/classes need. -#define CRY_FORCE_MALLOC_NEW_ALIGN - -#define DEBUG_BREAK raise(SIGTRAP) -#define RC_EXECUTABLE "rc" -#define USE_CRT 1 -#define SIZEOF_PTR 4 - ////////////////////////////////////////////////////////////////////////// // Standard includes. ////////////////////////////////////////////////////////////////////////// @@ -121,10 +111,6 @@ typedef unsigned char byte; #define DEFINE_ALIGNED_DATA(type, name, alignment) \ type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; #include "LinuxSpecific.h" // these functions do not exist int the wchar.h header diff --git a/Code/Legacy/CryCommon/AppleSpecific.h b/Code/Legacy/CryCommon/AppleSpecific.h index caf85a8f44..c572250b26 100644 --- a/Code/Legacy/CryCommon/AppleSpecific.h +++ b/Code/Legacy/CryCommon/AppleSpecific.h @@ -17,10 +17,6 @@ #pragma diagnostic ignore "-W#pragma-messages" #endif - -#define DEBUG_BREAK __builtin_trap() -#define RC_EXECUTABLE "rc" - ////////////////////////////////////////////////////////////////////////// // Standard includes. ////////////////////////////////////////////////////////////////////////// @@ -52,12 +48,6 @@ #define __COUNTER__ __LINE__ #endif -#ifdef __FUNC__ -#undef __FUNC__ -#endif - -#define __FUNC__ __func__ - typedef void* LPVOID; #define VOID void #define PVOID void* @@ -262,10 +252,6 @@ typedef uint64 __uint64; #define DEFINE_ALIGNED_DATA(type, name, alignment) \ type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; #define BST_UNCHECKED 0x0000 @@ -298,17 +284,6 @@ enum IDCONTINUE = 11 }; -#define ES_MULTILINE 0x0004L -#define ES_AUTOVSCROLL 0x0040L -#define ES_AUTOHSCROLL 0x0080L -#define ES_WANTRETURN 0x1000L - -#define LB_ERR (-1) - -#define LB_ADDSTRING 0x0180 -#define LB_GETCOUNT 0x018B -#define LB_SETTOPINDEX 0x0197 - #define MB_OK 0x00000000L #define MB_OKCANCEL 0x00000001L #define MB_ABORTRETRYIGNORE 0x00000002L @@ -328,22 +303,16 @@ enum #define MB_APPLMODAL 0x00000000L -#define MF_STRING 0x00000000L - #define MK_LBUTTON 0x0001 #define MK_RBUTTON 0x0002 #define MK_SHIFT 0x0004 #define MK_CONTROL 0x0008 #define MK_MBUTTON 0x0010 -#define MK_ALT ( 0x20 ) - #define SM_MOUSEPRESENT 0x00000000L #define SM_CMOUSEBUTTONS 43 -#define USER_TIMER_MINIMUM 0x0000000A - #define VK_TAB 0x09 #define VK_SHIFT 0x10 #define VK_MENU 0x12 @@ -351,11 +320,6 @@ enum #define VK_SPACE 0x20 #define VK_DELETE 0x2E -#define VK_NUMPAD1 0x61 -#define VK_NUMPAD2 0x62 -#define VK_NUMPAD3 0x63 -#define VK_NUMPAD4 0x64 - #define VK_OEM_COMMA 0xBC // ',' any country #define VK_OEM_PERIOD 0xBE // '.' any country #define VK_OEM_3 0xC0 // '`~' for US @@ -386,13 +350,9 @@ enum #define wcsnicmp wcsncasecmp //#define memcpy_s(dest,bytes,src,n) memcpy(dest,src,n) #define _isnan ISNAN -#define _wtof(str) wcstod(str, 0) - #define TARGET_DEFAULT_ALIGN (0x8U) - - #define _msize malloc_size @@ -498,36 +458,6 @@ typedef HANDLE HMENU; #endif //__cplusplus -inline char* _fullpath(char* absPath, const char* relPath, size_t maxLength) -{ - char path[PATH_MAX]; - - if (realpath(relPath, path) == NULL) - { - return NULL; - } - const size_t len = std::min(strlen(path), maxLength - 1); - memcpy(absPath, path, len); - absPath[len] = 0; - return absPath; -} - -typedef union _LARGE_INTEGER -{ - struct - { - DWORD LowPart; - LONG HighPart; - }; - struct - { - DWORD LowPart; - LONG HighPart; - } u; - - long long QuadPart; -} LARGE_INTEGER; - extern bool QueryPerformanceCounter(LARGE_INTEGER*); extern bool QueryPerformanceFrequency(LARGE_INTEGER* frequency); @@ -568,14 +498,6 @@ inline int closesocket(int s) return ::close(s); } -inline int WSAGetLastError() -{ - return errno; -} - -//we take the definition of the pthread_t type directly from the pthread file -#define THREADID_NULL 0 - template char (*RtlpNumberOf( T (&)[N] ))[N]; diff --git a/Code/Legacy/CryCommon/BaseTypes.h b/Code/Legacy/CryCommon/BaseTypes.h index e8b6ae8ab7..0c588184a5 100644 --- a/Code/Legacy/CryCommon/BaseTypes.h +++ b/Code/Legacy/CryCommon/BaseTypes.h @@ -11,12 +11,9 @@ #define CRYINCLUDE_CRYCOMMON_BASETYPES_H #pragma once -#include "CompileTimeAssert.h" - - -COMPILE_TIME_ASSERT(sizeof(char) == 1); -COMPILE_TIME_ASSERT(sizeof(float) == 4); -COMPILE_TIME_ASSERT(sizeof(int) >= 4); +static_assert(sizeof(char) == 1); +static_assert(sizeof(float) == 4); +static_assert(sizeof(int) >= 4); typedef unsigned char uchar; @@ -36,35 +33,35 @@ typedef signed long slong; typedef unsigned long long ulonglong; typedef signed long long slonglong; -COMPILE_TIME_ASSERT(sizeof(uchar) == sizeof(schar)); -COMPILE_TIME_ASSERT(sizeof(ushort) == sizeof(sshort)); -COMPILE_TIME_ASSERT(sizeof(uint) == sizeof(sint)); -COMPILE_TIME_ASSERT(sizeof(ulong) == sizeof(slong)); -COMPILE_TIME_ASSERT(sizeof(ulonglong) == sizeof(slonglong)); +static_assert(sizeof(uchar) == sizeof(schar)); +static_assert(sizeof(ushort) == sizeof(sshort)); +static_assert(sizeof(uint) == sizeof(sint)); +static_assert(sizeof(ulong) == sizeof(slong)); +static_assert(sizeof(ulonglong) == sizeof(slonglong)); -COMPILE_TIME_ASSERT(sizeof(uchar) <= sizeof(ushort)); -COMPILE_TIME_ASSERT(sizeof(ushort) <= sizeof(uint)); -COMPILE_TIME_ASSERT(sizeof(uint) <= sizeof(ulong)); -COMPILE_TIME_ASSERT(sizeof(ulong) <= sizeof(ulonglong)); +static_assert(sizeof(uchar) <= sizeof(ushort)); +static_assert(sizeof(ushort) <= sizeof(uint)); +static_assert(sizeof(uint) <= sizeof(ulong)); +static_assert(sizeof(ulong) <= sizeof(ulonglong)); typedef schar int8; typedef schar sint8; typedef uchar uint8; -COMPILE_TIME_ASSERT(sizeof(uint8) == 1); -COMPILE_TIME_ASSERT(sizeof(sint8) == 1); +static_assert(sizeof(uint8) == 1); +static_assert(sizeof(sint8) == 1); typedef sshort int16; typedef sshort sint16; typedef ushort uint16; -COMPILE_TIME_ASSERT(sizeof(uint16) == 2); -COMPILE_TIME_ASSERT(sizeof(sint16) == 2); +static_assert(sizeof(uint16) == 2); +static_assert(sizeof(sint16) == 2); typedef sint int32; typedef sint sint32; typedef uint uint32; -COMPILE_TIME_ASSERT(sizeof(uint32) == 4); -COMPILE_TIME_ASSERT(sizeof(sint32) == 4); +static_assert(sizeof(uint32) == 4); +static_assert(sizeof(sint32) == 4); typedef slonglong int64; @@ -72,14 +69,14 @@ typedef slonglong int64; #define O3DE_INT64_DEFINED typedef slonglong sint64; typedef ulonglong uint64; -COMPILE_TIME_ASSERT(sizeof(uint64) == 8); -COMPILE_TIME_ASSERT(sizeof(sint64) == 8); +static_assert(sizeof(uint64) == 8); +static_assert(sizeof(sint64) == 8); #endif typedef float f32; typedef double f64; -COMPILE_TIME_ASSERT(sizeof(f32) == 4); -COMPILE_TIME_ASSERT(sizeof(f64) == 8); +static_assert(sizeof(f32) == 4); +static_assert(sizeof(f64) == 8); #endif // CRYINCLUDE_CRYCOMMON_BASETYPES_H diff --git a/Code/Legacy/CryCommon/BitFiddling.h b/Code/Legacy/CryCommon/BitFiddling.h index 901dd0a49a..36173c5e53 100644 --- a/Code/Legacy/CryCommon/BitFiddling.h +++ b/Code/Legacy/CryCommon/BitFiddling.h @@ -12,7 +12,6 @@ #pragma once -#include "CompileTimeAssert.h" #include // Section dictionary @@ -36,7 +35,6 @@ ILINE uint32 countLeadingZeros32(uint32 x) { DWORD result = 32 ^ 31; // assumes result is unmodified if _BitScanReverse returns 0 _BitScanReverse(&result, x); - PREFAST_SUPPRESS_WARNING(6102); result ^= 31; // needed because the index is from LSB (whereas all other implementations are from MSB) return result; } @@ -73,16 +71,6 @@ inline bool IsPowerOfTwo(TInteger x) return (x & (x - 1)) == 0; } -// compile time version of IsPowerOfTwo, useful for STATIC_CHECK -template -struct IsPowerOfTwoCompileTime -{ - enum - { - IsPowerOfTwo = ((nValue & (nValue - 1)) == 0) - }; -}; - inline uint32 NextPower2(uint32 n) { n--; @@ -199,45 +187,6 @@ ILINE int32 Isel32(int32 v, int32 alt) return ((static_cast(v) >> 31) & alt) | ((static_cast(~v) >> 31) & v); } -template -struct CompileTimeIntegerLog2 -{ - static const uint32 result = 1 + CompileTimeIntegerLog2<(ILOG >> 1)>::result; -}; -template <> -struct CompileTimeIntegerLog2<1> -{ - static const uint32 result = 0; -}; -template <> -struct CompileTimeIntegerLog2<0>; // keep it undefined, we cannot represent "minus infinity" result - -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<1>::result == 0); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<2>::result == 1); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<3>::result == 1); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<4>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<5>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<255>::result == 7); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<256>::result == 8); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<257>::result == 8); - -template -struct CompileTimeIntegerLog2_RoundUp -{ - static const uint32 result = CompileTimeIntegerLog2::result + ((ILOG & (ILOG - 1)) != 0); -}; -template <> -struct CompileTimeIntegerLog2_RoundUp<0>; // we can return 0, but let's keep it undefined (same as CompileTimeIntegerLog2<0>) - -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<1>::result == 0); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<2>::result == 1); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<3>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<4>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<5>::result == 3); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<255>::result == 8); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<256>::result == 8); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<257>::result == 9); - // Character-to-bitfield mapping inline uint32 AlphaBit(char c) diff --git a/Code/Legacy/CryCommon/CompileTimeAssert.h b/Code/Legacy/CryCommon/CompileTimeAssert.h deleted file mode 100644 index 80a2ecf6bf..0000000000 --- a/Code/Legacy/CryCommon/CompileTimeAssert.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -// Inspired by the Boost library's BOOST_STATIC_ASSERT(), -// see http://www.boost.org/doc/libs/1_49_0/doc/html/boost_staticassert/how.html -// or http://www.boost.org/libs/static_assert - -#ifndef CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H -#define CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H -#pragma once - -#if defined(__cplusplus) -/* -template -struct COMPILE_TIME_ASSERT_FAIL; - -template <> -struct COMPILE_TIME_ASSERT_FAIL -{ -}; - -template -struct COMPILE_TIME_ASSERT_TEST -{ - enum { dummy = i }; -}; - -#define COMPILE_TIME_ASSERT_BUILD_NAME2(x, y) x##y -#define COMPILE_TIME_ASSERT_BUILD_NAME1(x, y) COMPILE_TIME_ASSERT_BUILD_NAME2(x, y) -#define COMPILE_TIME_ASSERT_BUILD_NAME(x, y) COMPILE_TIME_ASSERT_BUILD_NAME1(x, y) - -#ifndef __RECODE__ - #define COMPILE_TIME_ASSERT(expr) \ - typedef COMPILE_TIME_ASSERT_TEST)> \ - COMPILE_TIME_ASSERT_BUILD_NAME(compile_time_assert_test_, __LINE__) - // note: for MS Visual Studio we could use __COUNTER__ instead of __LINE__ -#else - #define COMPILE_TIME_ASSERT(expr) -#endif // __RECODE__ - -#else - -#define COMPILE_TIME_ASSERT(expr) -*/ -#endif - -#define COMPILE_TIME_ASSERT_MSG(expr, msg) static_assert(expr, msg) -#define COMPILE_TIME_ASSERT(expr) COMPILE_TIME_ASSERT_MSG(expr, "Compile Time Assert") - - -#endif // CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H diff --git a/Code/Legacy/CryCommon/CryArray.h b/Code/Legacy/CryCommon/CryArray.h index 61224784a2..b4878ec25a 100644 --- a/Code/Legacy/CryCommon/CryArray.h +++ b/Code/Legacy/CryCommon/CryArray.h @@ -16,24 +16,10 @@ //--------------------------------------------------------------------------- // Convenient iteration macros -#define for_iter(IT, it, b, e) for (IT it = (b), _e = (e); it != _e; ++it) -#define for_container(CT, it, cont) for_iter (CT::iterator, it, (cont).begin(), (cont).end()) #define for_ptr(T, it, b, e) for (T* it = (b), * _e = (e); it != _e; ++it) -#define for_array_ptr(T, it, arr) for_ptr (T, it, (arr).begin(), (arr).end()) - -#define for_array(i, arr) for (int i = 0, _e = (arr).size(); i < _e; i++) -#define for_all(cont) for_array (_i, cont) cont[_i] - -//--------------------------------------------------------------------------- -// Stack array helper -#define ALIGNED_STACK_ARRAY(T, name, size, alignment) \ - PREFAST_SUPPRESS_WARNING(6255) \ - T * name = (T*) alloca((size) * sizeof(T) + alignment - 1); \ - name = Align(name, alignment); - -#define STACK_ARRAY(T, name, size) \ - ALIGNED_STACK_ARRAY(T, name, size, alignof(T)) \ +#define for_array_ptr(T, it, arr) for_ptr (T, it, (arr).begin(), (arr).end()) +#define for_array(i, arr) for (int i = 0, _e = (arr).size(); i < _e; i++) //--------------------------------------------------------------------------- // Specify semantics for moving objects. @@ -774,7 +760,7 @@ namespace NArray AP& allocator() { - COMPILE_TIME_ASSERT(sizeof(AP) == sizeof(A)); + static_assert(sizeof(AP) == sizeof(A)); return *(AP*)this; } const AP& allocator() const diff --git a/Code/Legacy/CryCommon/CryAssert.h b/Code/Legacy/CryCommon/CryAssert.h index 1cb5d37c43..1494654d87 100644 --- a/Code/Legacy/CryCommon/CryAssert.h +++ b/Code/Legacy/CryCommon/CryAssert.h @@ -71,7 +71,6 @@ #if defined(USE_CRY_ASSERT) && CRYASSERT_H_TRAIT_USE_CRY_ASSERT_MESSAGE void CryAssertTrace(const char*, ...); bool CryAssert(const char*, const char*, unsigned int, bool*); -void CryDebugBreak(); #define CRY_ASSERT(condition) CRY_ASSERT_MESSAGE(condition, NULL) @@ -86,7 +85,7 @@ void CryDebugBreak(); CryAssertTrace parenthese_message; \ if (CryAssert(#condition, __FILE__, __LINE__, &s_bIgnoreAssert)) \ { \ - DEBUG_BREAK; \ + AZ::Debug::Trace::Break(); \ } \ } \ } while (0) diff --git a/Code/Legacy/CryCommon/CryCustomTypes.h b/Code/Legacy/CryCommon/CryCustomTypes.h index 74f3cbc9dc..58a6bc9306 100644 --- a/Code/Legacy/CryCommon/CryCustomTypes.h +++ b/Code/Legacy/CryCommon/CryCustomTypes.h @@ -708,8 +708,8 @@ protected: static inline S FromFloat(float fIn) { - COMPILE_TIME_ASSERT(sizeof(S) <= 4); - COMPILE_TIME_ASSERT(nEXP_BITS > 0 && nEXP_BITS <= 8 && nEXP_BITS < sizeof(S) * 8 - 4); + static_assert(sizeof(S) <= 4); + static_assert(nEXP_BITS > 0 && nEXP_BITS <= 8 && nEXP_BITS < sizeof(S) * 8 - 4); // Clamp to allowed range. float fClamped = clamp_tpl(fIn * fROUNDER(), fMIN(), fMAX()); diff --git a/Code/Legacy/CryCommon/CryHeaders.h b/Code/Legacy/CryCommon/CryHeaders.h index 6b4ea0ba3a..4d037b52d9 100644 --- a/Code/Legacy/CryCommon/CryHeaders.h +++ b/Code/Legacy/CryCommon/CryHeaders.h @@ -17,7 +17,7 @@ #ifdef MAX_SUB_MATERIALS // This checks that the values are in sync in the different files. -COMPILE_TIME_ASSERT(MAX_SUB_MATERIALS == 128); +static_assert(MAX_SUB_MATERIALS == 128); #else #define MAX_SUB_MATERIALS 128 #endif diff --git a/Code/Legacy/CryCommon/CryLibrary.h b/Code/Legacy/CryCommon/CryLibrary.h index ca1ca5d067..787085af00 100644 --- a/Code/Legacy/CryCommon/CryLibrary.h +++ b/Code/Legacy/CryCommon/CryLibrary.h @@ -63,7 +63,6 @@ using DetachEnvironmentFunction = void(*)(); #if !defined(WIN32_LEAN_AND_MEAN) #define WIN32_LEAN_AND_MEAN #endif - #include HMODULE CryLoadLibrary(const char* libName); diff --git a/Code/Legacy/CryCommon/CryRandomInternal.h b/Code/Legacy/CryCommon/CryRandomInternal.h index 9499ba0774..ca74041189 100644 --- a/Code/Legacy/CryCommon/CryRandomInternal.h +++ b/Code/Legacy/CryCommon/CryRandomInternal.h @@ -13,7 +13,6 @@ #include // std::numeric_limits #include // std::make_unsigned #include "BaseTypes.h" // uint32, uint64 -#include "CompileTimeAssert.h" #include "Cry_Vector2.h" #include "Cry_Vector3.h" #include "Cry_Vector4.h" @@ -24,10 +23,10 @@ namespace CryRandom_Internal template struct BoundedRandomUint { - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); - COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed); - COMPILE_TIME_ASSERT(sizeof(T) == size); - COMPILE_TIME_ASSERT(sizeof(T) <= sizeof(uint32)); + static_assert(std::numeric_limits::is_integer); + static_assert(!std::numeric_limits::is_signed); + static_assert(sizeof(T) == size); + static_assert(sizeof(T) <= sizeof(uint32)); inline static T Get(R& randomGenerator, const T maxValue) { @@ -41,9 +40,9 @@ namespace CryRandom_Internal template struct BoundedRandomUint { - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); - COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed); - COMPILE_TIME_ASSERT(sizeof(T) == sizeof(uint64)); + static_assert(std::numeric_limits::is_integer); + static_assert(!std::numeric_limits::is_signed); + static_assert(sizeof(T) == sizeof(uint64)); inline static T Get(R& randomGenerator, const T maxValue) { @@ -65,11 +64,11 @@ namespace CryRandom_Internal template struct BoundedRandom { - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); + static_assert(std::numeric_limits::is_integer); typedef typename std::make_unsigned::type UT; - COMPILE_TIME_ASSERT(sizeof(T) == sizeof(UT)); - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); - COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed); + static_assert(sizeof(T) == sizeof(UT)); + static_assert(std::numeric_limits::is_integer); + static_assert(!std::numeric_limits::is_signed); inline static T Get(R& randomGenerator, T minValue, T maxValue) { @@ -84,7 +83,7 @@ namespace CryRandom_Internal template struct BoundedRandom { - COMPILE_TIME_ASSERT(!std::numeric_limits::is_integer); + static_assert(!std::numeric_limits::is_integer); inline static T Get(R& randomGenerator, const T minValue, const T maxValue) { @@ -139,7 +138,7 @@ namespace CryRandom_Internal inline VT GetRandomUnitVector(R& randomGenerator) { typedef typename VT::value_type T; - COMPILE_TIME_ASSERT(!std::numeric_limits::is_integer); + static_assert(!std::numeric_limits::is_integer); VT res; T lenSquared; diff --git a/Code/Legacy/CryCommon/CrySizer.h b/Code/Legacy/CryCommon/CrySizer.h index add2cdd397..3f9eed84f6 100644 --- a/Code/Legacy/CryCommon/CrySizer.h +++ b/Code/Legacy/CryCommon/CrySizer.h @@ -30,6 +30,7 @@ #include #include #include +#include // forward declarations for overloads struct AABB; @@ -579,7 +580,7 @@ protected: // use this to push (and automatically pop) the sizer component name at the beginning of the // getSize() function -#define SIZER_COMPONENT_NAME(pSizerPointer, szComponentName) PREFAST_SUPPRESS_WARNING(6246) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, false) -#define SIZER_SUBCOMPONENT_NAME(pSizerPointer, szComponentName) PREFAST_SUPPRESS_WARNING(6246) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, true) +#define SIZER_COMPONENT_NAME(pSizerPointer, szComponentName) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, false) +#define SIZER_SUBCOMPONENT_NAME(pSizerPointer, szComponentName) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, true) #endif // CRYINCLUDE_CRYCOMMON_CRYSIZER_H diff --git a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h index c94d4fca90..c3dee7339f 100644 --- a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h +++ b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h @@ -14,13 +14,7 @@ #include "CryThread_pthreads.h" -#if PLATFORM_SUPPORTS_THREADLOCAL -THREADLOCAL CrySimpleThreadSelf -* CrySimpleThreadSelf::m_Self = NULL; -#else -TLS_DEFINE(CrySimpleThreadSelf*, g_CrySimpleThreadSelf) -#endif - +AZ_THREAD_LOCAL CrySimpleThreadSelf* CrySimpleThreadSelf::m_Self = NULL; ////////////////////////////////////////////////////////////////////////// // CryEvent(Timed) implementation diff --git a/Code/Legacy/CryCommon/CryThreadImpl_windows.h b/Code/Legacy/CryCommon/CryThreadImpl_windows.h index 5cf970414d..4ddbaedac5 100644 --- a/Code/Legacy/CryCommon/CryThreadImpl_windows.h +++ b/Code/Legacy/CryCommon/CryThreadImpl_windows.h @@ -20,7 +20,7 @@ struct SThreadNameDesc DWORD dwFlags; }; -THREADLOCAL CrySimpleThreadSelf* CrySimpleThreadSelf::m_Self = NULL; +AZ_THREAD_LOCAL CrySimpleThreadSelf* CrySimpleThreadSelf::m_Self = NULL; ////////////////////////////////////////////////////////////////////////// CryEvent::CryEvent() diff --git a/Code/Legacy/CryCommon/CryThread_pthreads.h b/Code/Legacy/CryCommon/CryThread_pthreads.h index 72b29344ec..17f7e5d2a0 100644 --- a/Code/Legacy/CryCommon/CryThread_pthreads.h +++ b/Code/Legacy/CryCommon/CryThread_pthreads.h @@ -653,15 +653,9 @@ private: typedef CryEventTimed CryEvent; -#if !PLATFORM_SUPPORTS_THREADLOCAL -TLS_DECLARE(class CrySimpleThreadSelf*, g_CrySimpleThreadSelf); -#endif - class CrySimpleThreadSelf { protected: -#if PLATFORM_SUPPORTS_THREADLOCAL - static CrySimpleThreadSelf* GetSelf() { return m_Self; @@ -672,21 +666,7 @@ protected: m_Self = pSelf; } private: - static THREADLOCAL CrySimpleThreadSelf* m_Self; - -#else - - static CrySimpleThreadSelf* GetSelf() - { - return TLS_GET(CrySimpleThreadSelf*, g_CrySimpleThreadSelf); - } - - static void SetSelf(CrySimpleThreadSelf* pSelf) - { - TLS_SET(g_CrySimpleThreadSelf, pSelf); - } - -#endif + static AZ_THREAD_LOCAL CrySimpleThreadSelf* m_Self; }; template diff --git a/Code/Legacy/CryCommon/CryThread_windows.h b/Code/Legacy/CryCommon/CryThread_windows.h index dee99ee66f..bf28435317 100644 --- a/Code/Legacy/CryCommon/CryThread_windows.h +++ b/Code/Legacy/CryCommon/CryThread_windows.h @@ -189,7 +189,7 @@ public: virtual ~CrySimpleThreadSelf(); protected: void StartThread(unsigned (__stdcall * func)(void*), void* argList); - static THREADLOCAL CrySimpleThreadSelf* m_Self; + static AZ_THREAD_LOCAL CrySimpleThreadSelf* m_Self; private: CrySimpleThreadSelf(const CrySimpleThreadSelf&); CrySimpleThreadSelf& operator = (const CrySimpleThreadSelf&); diff --git a/Code/Legacy/CryCommon/CryWindows.h b/Code/Legacy/CryCommon/CryWindows.h deleted file mode 100644 index 77684384c6..0000000000 --- a/Code/Legacy/CryCommon/CryWindows.h +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Specific header to handle Windows.h include - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H -#define CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H -#pragma once - -#include - -#endif // CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H diff --git a/Code/Legacy/CryCommon/IFunctorBase.h b/Code/Legacy/CryCommon/IFunctorBase.h index 2a8af50d33..1ac37a0e47 100644 --- a/Code/Legacy/CryCommon/IFunctorBase.h +++ b/Code/Legacy/CryCommon/IFunctorBase.h @@ -14,6 +14,7 @@ #define CRYINCLUDE_CRYCOMMON_IFUNCTORBASE_H #pragma once +#include // Base class for functor storage. // Not intended for direct usage. diff --git a/Code/Legacy/CryCommon/IMaterial.h b/Code/Legacy/CryCommon/IMaterial.h index 1faee0eef9..c5cd5712dc 100644 --- a/Code/Legacy/CryCommon/IMaterial.h +++ b/Code/Legacy/CryCommon/IMaterial.h @@ -37,10 +37,11 @@ struct IRenderMesh; #include #include #include +#include #ifdef MAX_SUB_MATERIALS // This checks that the values are in sync in the different files. -COMPILE_TIME_ASSERT(MAX_SUB_MATERIALS == 128); +static_assert(MAX_SUB_MATERIALS == 128); #else #define MAX_SUB_MATERIALS 128 #endif diff --git a/Code/Legacy/CryCommon/ISystem.h b/Code/Legacy/CryCommon/ISystem.h index 46c359730b..e0996fc927 100644 --- a/Code/Legacy/CryCommon/ISystem.h +++ b/Code/Legacy/CryCommon/ISystem.h @@ -24,7 +24,6 @@ #endif #include "CryAssert.h" -#include "CompileTimeAssert.h" #include @@ -1416,7 +1415,7 @@ namespace Detail } DummyStaticInstance; \ if (!(gEnv->pConsole != 0 ? gEnv->pConsole->Register(&DummyStaticInstance) : 0)) \ { \ - DEBUG_BREAK; \ + AZ::Debug::Trace::Break(); \ CryFatalError("Can not register dummy CVar"); \ } \ } while (0) @@ -1425,10 +1424,10 @@ namespace Detail # define DeclareConstIntCVar(name, defaultValue) enum : int { name = (defaultValue) } # define DeclareStaticConstIntCVar(name, defaultValue) enum : int { name = (defaultValue) } -# define DefineConstIntCVarName(strname, name, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, strname, defaultValue); } -# define DefineConstIntCVar(name, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, (#name), defaultValue); } +# define DefineConstIntCVarName(strname, name, defaultValue, flags, help) { static_assert((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, strname, defaultValue); } +# define DefineConstIntCVar(name, defaultValue, flags, help) { static_assert((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, (#name), defaultValue); } // DefineConstIntCVar2 is deprecated, any such instance can be converted to the 3 variant by removing the quotes around the first parameter -# define DefineConstIntCVar3(name, _var_, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(_var_)); REGISTER_DUMMY_CVAR(int, name, defaultValue); } +# define DefineConstIntCVar3(name, _var_, defaultValue, flags, help) { static_assert((int)(defaultValue) == (int)(_var_)); REGISTER_DUMMY_CVAR(int, name, defaultValue); } # define AllocateConstIntCVar(scope, name) # define DefineConstFloatCVar(name, flags, help) { REGISTER_DUMMY_CVAR(float, (#name), name ## Default); } @@ -1540,33 +1539,33 @@ static void AssertConsoleExists(void) #define ILLEGAL_DEV_FLAGS (VF_NET_SYNCED | VF_CHEAT | VF_CHEAT_ALWAYS_CHECK | VF_CHEAT_NOCHECK | VF_READONLY | VF_CONST_CVAR) #if defined(_RELEASE) -#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val -#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val /* _onchangefunction consumed; callback not available */ -#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val -#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val -#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val -#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val +#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val +#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val /* _onchangefunction consumed; callback not available */ +#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ +#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val +#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val +#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val +#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) NULL; static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val #define REGISTER_COMMAND_DEV_ONLY(_name, _func, _flags, _comment) /* consumed; command not available */ #else -#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_COMMAND_DEV_ONLY(_name, _func, _flags, _comment) REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_COMMAND_DEV_ONLY(_name, _func, _flags, _comment) REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEV_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) #endif // defined(_RELEASE) // //////////////////////////////////////////////////////////////////////////////// @@ -1583,19 +1582,19 @@ static void AssertConsoleExists(void) // TODO Registering all cvars for Dedicated server as well. Currently CrySystems have no concept of Dedicated server with cmake. // If we introduce server specific targets for CrySystems, we can add DEDICATED_SERVER flags to those and add the flag back in here. #if defined(_RELEASE) -#define REGISTER_CVAR_DEDI_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR_CB_DEDI_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT64_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_FLOAT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_COMMAND_DEDI_ONLY(_name, _func, _flags, _comment) REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR_DEDI_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR_CB_DEDI_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_STRING_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_STRING_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_INT64_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_FLOAT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR2_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR2_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR3_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_CVAR3_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) +#define REGISTER_COMMAND_DEDI_ONLY(_name, _func, _flags, _comment) REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEDI_ONLY), _comment); static_assert(((_flags) & ILLEGAL_DEV_FLAGS) == 0) #else #define REGISTER_CVAR_DEDI_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR_DEV_ONLY(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment) #define REGISTER_CVAR_CB_DEDI_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction) diff --git a/Code/Legacy/CryCommon/ITexture.h b/Code/Legacy/CryCommon/ITexture.h index 5b9b43ceb5..170e3b6709 100644 --- a/Code/Legacy/CryCommon/ITexture.h +++ b/Code/Legacy/CryCommon/ITexture.h @@ -314,8 +314,8 @@ public: void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { - COMPILE_TIME_ASSERT(eTT_MaxTexType <= 255); - COMPILE_TIME_ASSERT(eTF_MaxFormat <= 255); + static_assert(eTT_MaxTexType <= 255); + static_assert(eTF_MaxFormat <= 255); /*LATER*/ } diff --git a/Code/Legacy/CryCommon/Linux32Specific.h b/Code/Legacy/CryCommon/Linux32Specific.h index b3f06a80b7..6812ddb818 100644 --- a/Code/Legacy/CryCommon/Linux32Specific.h +++ b/Code/Legacy/CryCommon/Linux32Specific.h @@ -18,11 +18,6 @@ #define _CPU_X86 //#define _CPU_SSE -#define DEBUG_BREAK raise(SIGTRAP) -#define RC_EXECUTABLE "rc" -#define USE_CRT 1 -#define SIZEOF_PTR 4 - ////////////////////////////////////////////////////////////////////////// // Standard includes. ////////////////////////////////////////////////////////////////////////// @@ -98,10 +93,6 @@ typedef unsigned char byte; #define DEFINE_ALIGNED_DATA(type, name, alignment) \ type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; #include "LinuxSpecific.h" diff --git a/Code/Legacy/CryCommon/Linux64Specific.h b/Code/Legacy/CryCommon/Linux64Specific.h index 11b526ee4b..4dcb5f1e84 100644 --- a/Code/Legacy/CryCommon/Linux64Specific.h +++ b/Code/Legacy/CryCommon/Linux64Specific.h @@ -20,11 +20,6 @@ #define _CPU_AMD64 #define _CPU_SSE -#define DEBUG_BREAK ::raise(SIGTRAP) -#define RC_EXECUTABLE "rc" -#define USE_CRT 1 -#define SIZEOF_PTR 8 - ////////////////////////////////////////////////////////////////////////// // Standard includes. ////////////////////////////////////////////////////////////////////////// @@ -104,10 +99,6 @@ typedef uint8 byte; #define DEFINE_ALIGNED_DATA(type, name, alignment) \ type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; #include "LinuxSpecific.h" diff --git a/Code/Legacy/CryCommon/LinuxSpecific.h b/Code/Legacy/CryCommon/LinuxSpecific.h index 72673cafe3..17b465d4cb 100644 --- a/Code/Legacy/CryCommon/LinuxSpecific.h +++ b/Code/Legacy/CryCommon/LinuxSpecific.h @@ -42,23 +42,6 @@ #include #include -#ifdef __FUNC__ -#undef __FUNC__ -#endif -#if defined(__GNUC__) || defined(__clang__) -#define __FUNC__ __func__ -#else -#define __FUNC__ \ - ({ \ - static char __f[sizeof(__PRETTY_FUNCTION__) + 1]; \ - strcpy(__f, __PRETTY_FUNCTION__); \ - char* __p = (char*)strchr(__f, '('); \ - *__p = 0; \ - while (*(__p) != ' ' && __p != (__f - 1)) {--__p; } \ - (__p + 1); \ - }) -#endif - typedef void* LPVOID; #define VOID void #define PVOID void* @@ -194,7 +177,6 @@ typedef int64 __int64; typedef uint64 __uint64; #endif -#define THREADID_NULL -1 typedef unsigned long int threadID; #define TRUE 1 @@ -222,14 +204,6 @@ typedef unsigned long int threadID; #define wcsicmp wcscasecmp #define wcsnicmp wcsncasecmp - -#define _wtof(str) wcstod(str, 0) - -/*static unsigned char toupper(unsigned char c) -{ - return c & ~0x40; -} -*/ typedef union _LARGE_INTEGER { struct @@ -245,7 +219,6 @@ typedef union _LARGE_INTEGER long long QuadPart; } LARGE_INTEGER; - // stdlib.h stuff #define _MAX_DRIVE 3 // max. length of drive component #define _MAX_DIR 256 // max. length of path component @@ -269,21 +242,6 @@ typedef union _LARGE_INTEGER #define _O_SEQUENTIAL 0x0020 /* file access is primarily sequential */ #define _O_RANDOM 0x0010 /* file access is primarily random */ -// curses.h stubs for PDcurses keys -#define PADENTER KEY_MAX + 1 -#define CTL_HOME KEY_MAX + 2 -#define CTL_END KEY_MAX + 3 -#define CTL_PGDN KEY_MAX + 4 -#define CTL_PGUP KEY_MAX + 5 - -// stubs for virtual keys, isn't used on Linux -#define VK_UP 0 -#define VK_DOWN 0 -#define VK_RIGHT 0 -#define VK_LEFT 0 -#define VK_CONTROL 0 -#define VK_SCROLL 0 - enum { IDOK = 1, @@ -297,17 +255,6 @@ enum IDCONTINUE = 11 }; -#define ES_MULTILINE 0x0004L -#define ES_AUTOVSCROLL 0x0040L -#define ES_AUTOHSCROLL 0x0080L -#define ES_WANTRETURN 0x1000L - -#define LB_ERR (-1) - -#define LB_ADDSTRING 0x0180 -#define LB_GETCOUNT 0x018B -#define LB_SETTOPINDEX 0x0197 - #define MB_OK 0x00000000L #define MB_OKCANCEL 0x00000001L #define MB_ABORTRETRYIGNORE 0x00000002L @@ -327,22 +274,16 @@ enum #define MB_APPLMODAL 0x00000000L -#define MF_STRING 0x00000000L - #define MK_LBUTTON 0x0001 #define MK_RBUTTON 0x0002 #define MK_SHIFT 0x0004 #define MK_CONTROL 0x0008 #define MK_MBUTTON 0x0010 -#define MK_ALT ( 0x20 ) - #define SM_MOUSEPRESENT 0x00000000L #define SM_CMOUSEBUTTONS 43 -#define USER_TIMER_MINIMUM 0x0000000A - #define VK_TAB 0x09 #define VK_SHIFT 0x10 #define VK_MENU 0x12 @@ -350,11 +291,6 @@ enum #define VK_SPACE 0x20 #define VK_DELETE 0x2E -#define VK_NUMPAD1 0x61 -#define VK_NUMPAD2 0x62 -#define VK_NUMPAD3 0x63 -#define VK_NUMPAD4 0x64 - #define VK_OEM_COMMA 0xBC // ',' any country #define VK_OEM_PERIOD 0xBE // '.' any country #define VK_OEM_3 0xC0 // '`~' for US @@ -541,36 +477,11 @@ inline int64 CryGetTicksPerSec() inline int _CrtCheckMemory() { return 1; }; -inline char* _fullpath(char* absPath, const char* relPath, size_t maxLength) -{ - char path[PATH_MAX]; - - if (realpath(relPath, path) == NULL) - { - return NULL; - } - const size_t len = std::min(strlen(path), maxLength - 1); - memcpy(absPath, path, len); - absPath[len] = 0; - return absPath; -} - typedef void* HGLRC; typedef void* HDC; typedef void* PROC; typedef void* PIXELFORMATDESCRIPTOR; -#define SCOPED_ENABLE_FLOAT_EXCEPTIONS - -// Linux_Win32Wrapper.h now included directly by platform.h -//#include "Linux_Win32Wrapper.h" - -#define closesocket close -inline int WSAGetLastError() -{ - return errno; -} - template char (*RtlpNumberOf( T (&)[N] ))[N]; diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h index 8a1004a066..7b556b0f62 100644 --- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h +++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h @@ -326,8 +326,6 @@ inline uint32 GetTickCount() #define _strlwr_s(BUF, SIZE) strlwr(BUF) #define _strups strupr -#define _wtof(str) wcstod(str, 0) - typedef struct __finddata64_t { //!< atributes set by find request @@ -489,8 +487,6 @@ extern void adaptFilenameToLinux(char* rAdjustedFilename); extern const int comparePathNames(const char* cpFirst, const char* cpSecond, unsigned int len);//returns 0 if identical extern void replaceDoublePathFilename(char* szFileName);//removes "\.\" to "\" and "/./" to "/" -////////////////////////////////////////////////////////////////////////// -extern char* _fullpath(char* absPath, const char* relPath, size_t maxLength); ////////////////////////////////////////////////////////////////////////// extern void _makepath(char* path, const char* drive, const char* dir, const char* filename, const char* ext); diff --git a/Code/Legacy/CryCommon/MTPseudoRandom.cpp b/Code/Legacy/CryCommon/MTPseudoRandom.cpp index 6f163e682f..f8a3950ff0 100644 --- a/Code/Legacy/CryCommon/MTPseudoRandom.cpp +++ b/Code/Legacy/CryCommon/MTPseudoRandom.cpp @@ -63,7 +63,7 @@ void CMTRand_int32::seed(const uint32* array, int size) // init by array } for (int k = n - 1; k; --k) { - PREFAST_SUPPRESS_WARNING(6385) PREFAST_SUPPRESS_WARNING(6386) m_nState[i] = (m_nState[i] ^ ((m_nState[i - 1] ^ (m_nState[i - 1] >> 30)) * 1566083941UL)) - i; + m_nState[i] = (m_nState[i] ^ ((m_nState[i - 1] ^ (m_nState[i - 1] >> 30)) * 1566083941UL)) - i; if ((++i) == n) { m_nState[0] = m_nState[n - 1]; diff --git a/Code/Legacy/CryCommon/MacSpecific.h b/Code/Legacy/CryCommon/MacSpecific.h index 30bcd6c6db..0533a1b556 100644 --- a/Code/Legacy/CryCommon/MacSpecific.h +++ b/Code/Legacy/CryCommon/MacSpecific.h @@ -24,40 +24,6 @@ #define _CPU_SSE #define PLATFORM_64BIT -#define USE_CRT 1 -#define SIZEOF_PTR 8 - typedef uint64_t threadID; - -// curses.h stubs for PDcurses keys -#define PADENTER KEY_MAX + 1 -#define CTL_HOME KEY_MAX + 2 -#define CTL_END KEY_MAX + 3 -#define CTL_PGDN KEY_MAX + 4 -#define CTL_PGUP KEY_MAX + 5 - -// stubs for virtual keys, isn't used on Mac -#define VK_UP 0 -#define VK_DOWN 0 -#define VK_RIGHT 0 -#define VK_LEFT 0 -#define VK_CONTROL 0 -#define VK_SCROLL 0 - -#define MAC_NOT_IMPLEMENTED assert(false); - - -typedef enum -{ - eDAContinue, - eDAIgnore, - eDAIgnoreAll, - eDABreak, - eDAStop, - eDAReportAsBug -} EDialogAction; - -extern EDialogAction MacOSXHandleAssert(const char* condition, const char* file, int line, const char* reason, bool); - #endif // CRYINCLUDE_CRYCOMMON_MACSPECIFIC_H diff --git a/Code/Legacy/CryCommon/Options.h b/Code/Legacy/CryCommon/Options.h index 925f1f747e..935c8bd371 100644 --- a/Code/Legacy/CryCommon/Options.h +++ b/Code/Legacy/CryCommon/Options.h @@ -80,7 +80,7 @@ private: typedef Struc TThis; typedef Int TInt; \ TInt Mask() const { return *(const TInt*)this; } \ TInt& Mask() { return *(TInt*)this; } \ - Struc(TInt init = 0) { COMPILE_TIME_ASSERT(sizeof(TThis) == sizeof(TInt)); Mask() = init; } \ + Struc(TInt init = 0) { static_assert(sizeof(TThis) == sizeof(TInt)); Mask() = init; } \ #define BIT_VAR(Var) \ TInt _##Var : 1; \ diff --git a/Code/Legacy/CryCommon/ProjectDefines.h b/Code/Legacy/CryCommon/ProjectDefines.h index e359fe669b..18b4665fab 100644 --- a/Code/Legacy/CryCommon/ProjectDefines.h +++ b/Code/Legacy/CryCommon/ProjectDefines.h @@ -16,10 +16,6 @@ #include "BaseTypes.h" #include -#if defined(_RELEASE) && !defined(RELEASE) - #define RELEASE -#endif - // Section dictionary #if defined(AZ_RESTRICTED_PLATFORM) #define PROJECTDEFINES_H_SECTION_STATS_AGENT 1 @@ -31,54 +27,48 @@ #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_STATS_AGENT #include AZ_RESTRICTED_FILE(ProjectDefines_h) #elif defined(WIN32) || defined(WIN64) -#if !defined(_RELEASE) || defined(PERFORMANCE_BUILD) -#define ENABLE_STATS_AGENT -#endif + #if !defined(_RELEASE) || defined(PERFORMANCE_BUILD) + #define ENABLE_STATS_AGENT + #endif #endif -// The following definitions are used by Sandbox and RC to determine which platform support is needed -#define TOOLS_SUPPORT_POWERVR -#define TOOLS_SUPPORT_ETC2COMP // Type used for vertex indices // WARNING: If you change this typedef, you need to update AssetProcessorPlatformConfig.ini to convert cgf and abc files to the proper index format. #if defined(MOBILE) -typedef uint16 vtx_idx; -#define AZ_RESTRICTED_SECTION_IMPLEMENTED + typedef uint16 vtx_idx; + #define AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_VTX_IDX #include AZ_RESTRICTED_FILE(ProjectDefines_h) #endif #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #else -// Uncomment one of the two following typedefs: -typedef uint32 vtx_idx; -//typedef uint16 vtx_idx; + // Uncomment one of the two following typedefs: + typedef uint32 vtx_idx; + //typedef uint16 vtx_idx; #endif -// 0=off, 1=on -#define TERRAIN_USE_CIE_COLORSPACE 0 - // When non-zero, const cvar accesses (by name) are logged in release-mode on consoles. // This can be used to find non-optimal usage scenario's, where the constant should be used directly instead. // Since read accesses tend to be used in flow-control logic, constants allow for better optimization by the compiler. #define LOG_CONST_CVAR_ACCESS 0 #if defined(WIN32) || defined(WIN64) || LOG_CONST_CVAR_ACCESS -#define RELEASE_LOGGING + #define RELEASE_LOGGING #endif #if defined(_RELEASE) && !defined(RELEASE_LOGGING) -#define EXCLUDE_NORMAL_LOG + #define EXCLUDE_NORMAL_LOG #endif // Add the "REMOTE_ASSET_PROCESSOR" define except in release // this makes it so that asset processor functions. Without this, all assets must be present and on local media // with this, the asset processor can be used to remotely process assets. #if !defined(_RELEASE) -# define REMOTE_ASSET_PROCESSOR + #define REMOTE_ASSET_PROCESSOR #endif #if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) @@ -90,132 +80,68 @@ typedef uint32 vtx_idx; #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_TRAITS #include AZ_RESTRICTED_FILE(ProjectDefines_h) #else -#define PROJECTDEFINES_H_TRAIT_DISABLE_MONOLITHIC_PROFILING_MARKERS 1 -#if !defined(LINUX) && !defined(APPLE) -#define PROJECTDEFINES_H_TRAIT_ENABLE_SOFTCODE_SYSTEM 1 -#endif -#if defined(WIN32) || defined(WIN64) || defined(LINUX) || defined(APPLE) -#define PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES 1 -#endif -#define PROJECTDEFINES_H_TRAIT_USE_MESH_TESSELLATION 1 -#if defined(WIN32) -#define PROJECTDEFINES_H_TRAIT_USE_SVO_GI 1 -#endif -#if defined(APPLE) || defined(LINUX) -#define AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS 1 -#define AZ_LEGACY_CRYCOMMON_TRAIT_USE_UNIX_PATHS 1 -#endif -#endif - -#define USE_GLOBAL_BUCKET_ALLOCATOR - -#ifdef IS_PROSDK -# define USING_TAGES_SECURITY // Wrapper for TGVM security -# if defined(LINUX) || defined(APPLE) -# error LINUX and Mac does not support evaluation version -# endif -#endif - -#ifdef USING_TAGES_SECURITY -# define TAGES_EXPORT __declspec(dllexport) -#else -# define TAGES_EXPORT -#endif // USING_TAGES_SECURITY -// test ------------------------------------- - -#define _DATAPROBE - - - -//This feature allows automatic crash submission to JIRA, but does not work outside of O3DE -//Note: This #define will be commented out during code export -#define ENABLE_CRASH_HANDLER - -#if !defined(PHYSICS_STACK_SIZE) -# define PHYSICS_STACK_SIZE (128U << 10) + #define PROJECTDEFINES_H_TRAIT_DISABLE_MONOLITHIC_PROFILING_MARKERS 1 + #if !defined(LINUX) && !defined(APPLE) + #define PROJECTDEFINES_H_TRAIT_ENABLE_SOFTCODE_SYSTEM 1 + #endif + #if defined(WIN32) || defined(WIN64) || defined(LINUX) || defined(APPLE) + #define PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES 1 + #endif + #define PROJECTDEFINES_H_TRAIT_USE_MESH_TESSELLATION 1 + #if defined(WIN32) + #define PROJECTDEFINES_H_TRAIT_USE_SVO_GI 1 + #endif + #if defined(APPLE) || defined(LINUX) + #define AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS 1 + #define AZ_LEGACY_CRYCOMMON_TRAIT_USE_UNIX_PATHS 1 + #endif #endif #if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) -#ifndef ENABLE_PROFILING_CODE - #define ENABLE_PROFILING_CODE -#endif -#if !(defined(SANDBOX_EXPORTS) || defined(PLUGIN_EXPORTS) || (defined(AZ_MONOLITHIC_BUILD) && PROJECTDEFINES_H_TRAIT_DISABLE_MONOLITHIC_PROFILING_MARKERS)) - #define ENABLE_PROFILING_MARKERS -#endif + #ifndef ENABLE_PROFILING_CODE + #define ENABLE_PROFILING_CODE + #endif -//lightweight profilers, disable for submissions, disables displayinfo inside 3dengine as well -#ifndef ENABLE_LW_PROFILERS - #define ENABLE_LW_PROFILERS -#endif -#endif - -#if defined(ENABLE_PROFILING_CODE) -#define ENABLE_ART_RT_TIME_ESTIMATE -#endif - -#if defined(ENABLE_PROFILING_CODE) && !defined(_RELEASE) - #define FMOD_STREAMING_DEBUGGING 1 -#endif - -#if defined(WIN32) || defined(WIN64) || defined(APPLE) || defined(AZ_PLATFORM_LINUX) -#define FLARES_SUPPORT_EDITING + //lightweight profilers, disable for submissions, disables displayinfo inside 3dengine as well + #ifndef ENABLE_LW_PROFILERS + #define ENABLE_LW_PROFILERS + #endif #endif // Reflect texture slot information - only used in the editor #if defined(WIN32) || defined(WIN64) || defined(AZ_PLATFORM_MAC) -#define SHADER_REFLECT_TEXTURE_SLOTS 1 + #define SHADER_REFLECT_TEXTURE_SLOTS 1 #else -#define SHADER_REFLECT_TEXTURE_SLOTS 0 + #define SHADER_REFLECT_TEXTURE_SLOTS 0 #endif -// these enable and disable certain net features to give compatibility between PCs and consoles / profile and performance builds -#define PC_CONSOLE_NET_COMPATIBLE 0 -#define PROFILE_PERFORMANCE_NET_COMPATIBLE 0 - -#if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) && !PROFILE_PERFORMANCE_NET_COMPATIBLE -#define USE_LAGOMETER (1) -#else -#define USE_LAGOMETER (0) -#endif - -// enable this in order to support old style material names in old data ("engine/material.mtl" or "mygame/material.mtl" as opposed to just "material.mtl") -// previously, material names could have the game folder in it, but this is not necessary anymore and would not work with things like gems -// note that if you use any older projects such as GameSDK this should remain enabled -#define SUPPORT_LEGACY_MATERIAL_NAMES - -// Enable additional structures and code for sprite motion blur. Currently non-functional and disabled -// #define PARTICLE_MOTION_BLUR - -// a special ticker thread to run during load and unload of levels -#define USE_NETWORK_STALL_TICKER_THREAD - #if !defined(MOBILE) -//--------------------------------------------------------------------- -// Enable Tessellation Features -// (displacement mapping, subdivision, water tessellation) -//--------------------------------------------------------------------- -// Modules : 3DEngine, Renderer -// Depends on: DX11 + //--------------------------------------------------------------------- + // Enable Tessellation Features + // (displacement mapping, subdivision, water tessellation) + //--------------------------------------------------------------------- + // Modules : 3DEngine, Renderer + // Depends on: DX11 -// Global tessellation feature flag + // Global tessellation feature flag #define TESSELLATION #ifdef TESSELLATION -// Specific features flags + // Specific features flags #define WATER_TESSELLATION #define PARTICLES_TESSELLATION #if PROJECTDEFINES_H_TRAIT_USE_MESH_TESSELLATION -// Mesh tessellation (displacement, smoothing, subd) + // Mesh tessellation (displacement, smoothing, subd) #define MESH_TESSELLATION -// Mesh tessellation also in motion blur passes + // Mesh tessellation also in motion blur passes #define MOTIONBLUR_TESSELLATION #endif -// Dependencies + // Dependencies #ifdef MESH_TESSELLATION #define MESH_TESSELLATION_ENGINE #endif - #ifndef NULL_RENDERER + #ifndef NULL_RENDERER #ifdef WATER_TESSELLATION #define WATER_TESSELLATION_RENDERER #endif @@ -227,7 +153,7 @@ typedef uint32 vtx_idx; #endif #if defined(WATER_TESSELLATION_RENDERER) || defined(PARTICLES_TESSELLATION_RENDERER) || defined(MESH_TESSELLATION_RENDERER) -// Common tessellation flag enabling tessellation stages in renderer + // Common tessellation flag enabling tessellation stages in renderer #define TESSELLATION_RENDERER #endif #endif // !NULL_RENDERER @@ -246,14 +172,8 @@ typedef uint32 vtx_idx; #endif #if defined(ENABLE_PROFILING_CODE) -# define USE_DISK_PROFILER -# define ENABLE_LOADING_PROFILER // requires AZ_PROFILE_TELEMETRY to also be defined -#endif - -#if PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES && !defined(NULL_RENDERER) - #define GPU_PARTICLES 1 -#else - #define GPU_PARTICLES 0 + #define USE_DISK_PROFILER + #define ENABLE_LOADING_PROFILER // requires AZ_PROFILE_TELEMETRY to also be defined #endif // The maximum number of joints in an animation diff --git a/Code/Legacy/CryCommon/VectorMap.h b/Code/Legacy/CryCommon/VectorMap.h index 1a42f0e48f..75b1562c4d 100644 --- a/Code/Legacy/CryCommon/VectorMap.h +++ b/Code/Legacy/CryCommon/VectorMap.h @@ -14,6 +14,7 @@ #define CRYINCLUDE_CRYCOMMON_VECTORMAP_H #pragma once +#include //-------------------------------------------------------------------------- // VectorMap diff --git a/Code/Legacy/CryCommon/Win32specific.h b/Code/Legacy/CryCommon/Win32specific.h index 650a4946a0..62d32138b4 100644 --- a/Code/Legacy/CryCommon/Win32specific.h +++ b/Code/Legacy/CryCommon/Win32specific.h @@ -23,11 +23,7 @@ #define ILINE __forceinline #endif -#define DEBUG_BREAK _asm { int 3 } -#define RC_EXECUTABLE "rc.exe" #define DEPRECATED __declspec(deprecated) -#define TYPENAME(x) typeid(x).name() -#define SIZEOF_PTR 4 #ifndef _WIN32_WINNT # define _WIN32_WINNT 0x501 @@ -55,8 +51,6 @@ ////////////////////////////////////////////////////////////////////////// #include "BaseTypes.h" -#define THREADID_NULL -1 - typedef unsigned char BYTE; typedef unsigned int threadID; typedef unsigned long DWORD; @@ -112,14 +106,11 @@ int64 CryGetTicksPerSec(); __declspec(align(num)) #define DEFINE_ALIGNED_DATA(type, name, alignment) _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) static _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) const _declspec(align(alignment)) type name; #ifndef FILE_ATTRIBUTE_NORMAL #define FILE_ATTRIBUTE_NORMAL 0x00000080 #endif -#define FP16_TERRAIN #define TARGET_DEFAULT_ALIGN (0x4U) diff --git a/Code/Legacy/CryCommon/Win64specific.h b/Code/Legacy/CryCommon/Win64specific.h index a3cb11ce32..47c9c1aad9 100644 --- a/Code/Legacy/CryCommon/Win64specific.h +++ b/Code/Legacy/CryCommon/Win64specific.h @@ -19,11 +19,7 @@ #define _CPU_SSE #define ILINE __forceinline -#define DEBUG_BREAK CryDebugBreak() -#define RC_EXECUTABLE "rc.exe" #define DEPRECATED __declspec(deprecated) -#define TYPENAME(x) typeid(x).name() -#define SIZEOF_PTR 8 #ifndef _WIN32_WINNT # define _WIN32_WINNT 0x501 @@ -52,7 +48,6 @@ ////////////////////////////////////////////////////////////////////////// #include "BaseTypes.h" -#define THREADID_NULL -1 typedef long LONG; typedef unsigned char BYTE; typedef unsigned long threadID; @@ -94,10 +89,6 @@ int64 CryGetTicksPerSec(); __declspec(align(num)) #define DEFINE_ALIGNED_DATA(type, name, alignment) _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) static _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) const _declspec(align(alignment)) type name; - -#define SIZEOF_PTR 8 #ifndef FILE_ATTRIBUTE_NORMAL #define FILE_ATTRIBUTE_NORMAL 0x00000080 diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp index d1b2d370a0..a2b4056a56 100644 --- a/Code/Legacy/CryCommon/WinBase.cpp +++ b/Code/Legacy/CryCommon/WinBase.cpp @@ -12,6 +12,7 @@ #include "platform.h" // Note: This should be first to get consistent debugging definitions +#include #include #if defined(AZ_RESTRICTED_PLATFORM) @@ -29,7 +30,7 @@ #include AZ_RESTRICTED_FILE(WinBase_cpp) #endif #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #else #include #endif @@ -1126,20 +1127,6 @@ void CrySleep(unsigned int dwMilliseconds) Sleep(dwMilliseconds); } -////////////////////////////////////////////////////////////////////////// -void CryLowLatencySleep(unsigned int dwMilliseconds) -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION WINBASE_CPP_SECTION_6 - #include AZ_RESTRICTED_FILE(WinBase_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - CrySleep(dwMilliseconds); -#endif -} - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// int CryMessageBox(const char* lpText, const char* lpCaption, unsigned int uType) @@ -1283,14 +1270,6 @@ int CryMessageBox(const char* lpText, const char* lpCaption, unsigned int uType) #endif } -////////////////////////////////////////////////////////////////////////// -short CryGetAsyncKeyState(int vKey) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "CryGetAsyncKeyState not implemented yet"); - return 0; -} - #if defined(LINUX) || defined(APPLE) || defined(DEFINE_CRY_INTERLOCKED_INCREMENT) //[K01]: http://www.memoryhole.net/kyle/2007/05/atomic_incrementing.html //http://forums.devx.com/archive/index.php/t-160558.html @@ -1381,10 +1360,6 @@ threadID CryGetCurrentThreadId() return GetCurrentThreadId(); } -void CryDebugBreak() -{ - __builtin_trap(); -} #endif//LINUX APPLE #if defined(APPLE) || defined(LINUX) @@ -1397,11 +1372,6 @@ DLL_EXPORT void OutputDebugString(const char* outputString) #endif } -DLL_EXPORT void DebugBreak() -{ - CryDebugBreak(); -} - #endif // This code does not have a long life span and will be replaced soon @@ -1627,37 +1597,6 @@ DWORD GetFileAttributes(LPCWSTR lpFileNameW) return (ret == 0) ? FILE_ATTRIBUTE_NORMAL : ret;//return file attribute normal as the default value, must only be set if no other attributes have been found } -uint32 CryGetFileAttributes(const char* lpFileName) -{ - AZStd::string fn = lpFileName; - adaptFilenameToLinux(fn); - const char* buffer = fn.c_str(); - - struct stat fileStats; - const int success = stat(buffer, &fileStats); - if (success == -1) - { - char adjustedFilename[MAX_PATH]; - GetFilenameNoCase(buffer, adjustedFilename); - if (stat(adjustedFilename, &fileStats) == -1) - { - return (DWORD)INVALID_FILE_ATTRIBUTES; - } - } - DWORD ret = 0; - - const int acc = (fileStats.st_mode & S_IWRITE); - - if (acc != 0) - { - if (S_ISDIR(fileStats.st_mode) != 0) - { - ret |= FILE_ATTRIBUTE_DIRECTORY; - } - } - return (ret == 0) ? FILE_ATTRIBUTE_NORMAL : ret;//return file attribute normal as the default value, must only be set if no other attributes have been found -} - __finddata64_t::~__finddata64_t() { if (m_Dir != FS_DIR_NULL) diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake index c78a6a4df0..8d33b85eff 100644 --- a/Code/Legacy/CryCommon/crycommon_files.cmake +++ b/Code/Legacy/CryCommon/crycommon_files.cmake @@ -68,7 +68,6 @@ set(FILES LCGRandom.h CryTypeInfo.cpp BaseTypes.h - CompileTimeAssert.h MemoryAccess.h AnimKey.h BitFiddling.h @@ -158,7 +157,6 @@ set(FILES CryThread_windows.h CryThreadImpl_pthreads.h CryThreadImpl_windows.h - CryWindows.h Linux32Specific.h Linux64Specific.h Linux_Win32Wrapper.h diff --git a/Code/Legacy/CryCommon/iOSSpecific.h b/Code/Legacy/CryCommon/iOSSpecific.h index d2503a7441..ac2461b55b 100644 --- a/Code/Legacy/CryCommon/iOSSpecific.h +++ b/Code/Legacy/CryCommon/iOSSpecific.h @@ -47,11 +47,9 @@ #define VK_SCROLL 0 -//#define USE_CRT 1 #if !defined(PLATFORM_64BIT) #error "IOS build only supports the 64bit architecture" #else -#define SIZEOF_PTR 8 typedef uint64_t threadID; #endif diff --git a/Code/Legacy/CryCommon/platform.h b/Code/Legacy/CryCommon/platform.h index 12f732a729..1333553184 100644 --- a/Code/Legacy/CryCommon/platform.h +++ b/Code/Legacy/CryCommon/platform.h @@ -7,22 +7,18 @@ */ -// Description : Platform dependend stuff. +// Description : Platform dependent stuff. // Include this file instead of windows h #pragma once #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION -#define PLATFORM_H_SECTION_1 1 -#define PLATFORM_H_SECTION_2 2 #define PLATFORM_H_SECTION_3 3 -#define PLATFORM_H_SECTION_4 4 #define PLATFORM_H_SECTION_5 5 #define PLATFORM_H_SECTION_6 6 #define PLATFORM_H_SECTION_7 7 #define PLATFORM_H_SECTION_8 8 -#define PLATFORM_H_SECTION_9 9 #define PLATFORM_H_SECTION_10 10 #define PLATFORM_H_SECTION_11 11 #define PLATFORM_H_SECTION_12 12 @@ -31,112 +27,12 @@ #define PLATFORM_H_SECTION_15 15 #endif -// certain C++ features are not available in some compiler versions -// turn them off here: -// #define _ALLOW_KEYWORD_MACROS -// #define _DISALLOW_INITIALIZER_LISTS -// #define _DISALLOW_ENUM_CLASS - -#if defined(_MSC_VER) - #define _ALLOW_KEYWORD_MACROS - - #define alignof _alignof - #if !defined(_HAS_EXCEPTIONS) - #define _HAS_EXCEPTIONS 0 - #endif -#elif defined(__GNUC__) - #define alignof __alignof__ -#endif - -// Alignment|InitializerList support. -#define _ALLOW_INITIALIZER_LISTS - #if (defined(LINUX) && !defined(ANDROID)) || defined(APPLE) -#define _FILE_OFFSET_BITS 64 // define large file support > 2GB + #define _FILE_OFFSET_BITS 64 // define large file support > 2GB #endif #include -#include - -#if defined(_MSC_VER) // We want the class name to be included, but __FUNCTION__ doesn't contain that on GCC/clang - #define __FUNC__ __FUNCTION__ -#else - #define __FUNC__ __PRETTY_FUNCTION__ -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_1 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(_DEBUG) && !defined(LINUX) && !defined(APPLE) - #include -#endif - -#define RESTRICT_POINTER __restrict - -// we have to use it because of VS doesn't support restrict reference variables -#if defined(APPLE) || defined(LINUX) - #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) - #define GCC411_OR_LATER - #endif - #define RESTRICT_REFERENCE __restrict -#else - #define RESTRICT_REFERENCE -#endif - - -#ifndef CHECK_REFERENCE_COUNTS //define that in your StdAfx.h to override per-project -# define CHECK_REFERENCE_COUNTS 0 //default value -#endif - -#if CHECK_REFERENCE_COUNTS -# define CHECK_REFCOUNT_CRASH(x) { if (!(x)) {*((int*)0) = 0; } \ -} -#else -# define CHECK_REFCOUNT_CRASH(x) -#endif - -#ifndef GARBAGE_MEMORY_ON_FREE //define that in your StdAfx.h to override per-project -# define GARBAGE_MEMORY_ON_FREE 0 //default value -#endif - -#if GARBAGE_MEMORY_ON_FREE -# ifndef GARBAGE_MEMORY_RANDOM //define that in your StdAfx.h to override per-project -# define GARBAGE_MEMORY_RANDOM 1 //0 to change it to progressive pattern -# endif -#endif - -////////////////////////////////////////////////////////////////////////// -// Available predefined compiler macros for Visual C++. -// _MSC_VER // Indicates MS Visual C compiler version -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_2 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -// _WIN32, _WIN64 // Indicates target OS -#endif -// _M_IX86, _M_PPC // Indicates target processor -// _DEBUG // Building in Debug mode -// _DLL // Linking with DLL runtime libs -// _MT // Linking with multi-threaded runtime libs -////////////////////////////////////////////////////////////////////////// - -// -// Translate some predefined macros. -// - -// NDEBUG disables std asserts, etc. -// Define it automatically if not compiling with Debug libs, or with ADEBUG flag. -#if !defined(_DEBUG) && !defined(ADEBUG) && !defined(NDEBUG) - #define NDEBUG -#endif - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_3 #include AZ_RESTRICTED_FILE(platform_h) @@ -147,44 +43,6 @@ #define CONSOLE #endif -//render thread settings, as this is accessed inside 3dengine and renderer and needs to be compile time defined, we need to do it here -//enable this macro to strip out the overhead for render thread -// #define STRIP_RENDER_THREAD -#ifdef STRIP_RENDER_THREAD - #define RT_COMMAND_BUF_COUNT 1 -#else -//can be enhanced to triple buffering, FlushFrame needs to be adjusted and RenderObj would become 132 bytes - #define RT_COMMAND_BUF_COUNT 2 -#endif - - -// We use WIN macros without _. -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_4 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -#if defined(_WIN32) && !defined(LINUX32) && !defined(LINUX64) && !defined(APPLE) && !defined(WIN32) - #define WIN32 -#endif -#if defined(_WIN64) && !defined(WIN64) - #define WIN64 -#endif -#endif - -// In Win32 Release we use static linkage -#ifdef WIN32 - #if !defined(_RELEASE) || defined(EDITOR) || defined(_FORCEDLL) -// All windows targets not in Release built as DLLs. - #ifndef _USRDLL - #define _USRDLL - #endif - #endif - -#endif //WIN32 - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_5 #include AZ_RESTRICTED_FILE(platform_h) @@ -205,19 +63,17 @@ #define PRId64 "lld" #define PRIu64 "llu" #endif - #define PLATFORM_I64(x) x##ll #else #include - #define PLATFORM_I64(x) x##i64 #endif #if !defined(PRISIZE_T) -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_6 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #if defined(AZ_RESTRICTED_PLATFORM) + #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_6 + #include AZ_RESTRICTED_FILE(platform_h) + #endif + #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(WIN64) #define PRISIZE_T "I64u" //size_t defined as unsigned __int64 #elif defined(WIN32) || defined(LINUX32) @@ -228,13 +84,14 @@ #error "Please defined PRISIZE_T for this platform" #endif #endif + #if !defined(PRI_THREADID) -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_7 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #if defined(AZ_RESTRICTED_PLATFORM) + #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_7 + #include AZ_RESTRICTED_FILE(platform_h) + #endif + #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(MAC) || defined(IOS) && defined(__LP64__) && defined(__LP64__) #define PRI_THREADID "lld" #elif defined(LINUX64) || defined(ANDROID) @@ -243,6 +100,7 @@ #define PRI_THREADID "d" #endif #endif + #include "ProjectDefines.h" // to get some defines available in every CryEngine project // Function attribute for printf/scanf-style parameters. @@ -277,47 +135,6 @@ #define PRINTF_EMPTY_FORMAT "" #endif -#if defined(IOS) -#define USE_PTHREAD_TLS -#endif - -// Storage class modifier for thread local storage. -// THEADLOCAL should NOT be defined to empty because that creates some -// really hard to find issues. -#if !defined(USE_PTHREAD_TLS) -# define THREADLOCAL AZ_TRAIT_COMPILER_THREAD_LOCAL -#endif //!defined(USE_PTHREAD_TLS) - - - -////////////////////////////////////////////////////////////////////////// -// define Read Write Barrier macro needed for lockless programming -////////////////////////////////////////////////////////////////////////// -#if defined(__arm__) -/** - * (ARMv7) Full memory barriar. - * - * None of GCC 4.6/4.8 or clang 3.3/3.4 have a builtin intrinsic for ARM's ldrex/strex or dmb - * instructions. This is a placeholder until supplied by the toolchain. - */ -inline void __dmb() -{ - // The linux kernel uses "dmb ish" to only sync with local monitor (arch/arm/include/asm/barrier.h): - //#define dmb(option) __asm__ __volatile__ ("dmb " #option : : : "memory") - //#define smp_mb() dmb(ish) - __asm__ __volatile__ ("dmb ish" : : : "memory"); -} - -#define READ_WRITE_BARRIER {__dmb(); } -#else - #define READ_WRITE_BARRIER -#endif -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// define macro to prevent memory reoderings of reads/and writes -//TODO implement for all GCC platforms, else there are potential crashes with strict aliasing - #define MEMORY_RW_REORDERING_BARRIER do { /*not implemented*/} while (0) //default stack size for threads, currently only used on pthread platforms #if defined(AZ_RESTRICTED_PLATFORM) @@ -325,7 +142,7 @@ inline void __dmb() #include AZ_RESTRICTED_FILE(platform_h) #endif #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #elif defined(LINUX) || defined(APPLE) #if !defined(_DEBUG) #define SIMPLE_THREAD_STACK_SIZE_KB (256) @@ -362,22 +179,6 @@ inline void __dmb() #else #define _HELP(x) "" #endif -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Globally Used Defines. -////////////////////////////////////////////////////////////////////////// -// CPU Types: _CPU_X86,_CPU_AMD64,_CPU_G5 -// Platform: WIN23,WIN64,LINUX32,LINUX64,MAC -// CPU supported functionality: _CPU_SSE -////////////////////////////////////////////////////////////////////////// - - - #if defined(_MSC_VER) - #define PREFAST_SUPPRESS_WARNING(W) __pragma(warning(suppress: W)) - #else - #define PREFAST_SUPPRESS_WARNING(W) - #endif #ifdef _PREFAST_ # define PREFAST_ASSUME(cond) __analysis_assume(cond) @@ -385,47 +186,21 @@ inline void __dmb() # define PREFAST_ASSUME(cond) #endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_9 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - #if defined(WIN32) && !defined(WIN64) - #include "Win32specific.h" - #endif - - #if defined(WIN64) - #include "Win64specific.h" - #endif -#endif - -#if defined(LINUX64) && !defined(ANDROID) -#include "Linux64Specific.h" -#endif - -#if defined(LINUX32) && !defined(ANDROID) -#include "Linux32Specific.h" -#endif - -#if defined(ANDROID) -#include "AndroidSpecific.h" -#endif - - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_10 #include AZ_RESTRICTED_FILE(platform_h) -#endif - -#if defined(MAC) -#include "MacSpecific.h" -#endif - -#if defined(IOS) -#include "iOSSpecific.h" +#else + #if defined(WIN64) + #include "Win64specific.h" + #elif defined(LINUX64) && !defined(ANDROID) + #include "Linux64Specific.h" + #elif defined(MAC) + #include "MacSpecific.h" + #elif defined(ANDROID) + #include "AndroidSpecific.h" + #elif defined(IOS) + #include "iOSSpecific.h" + #endif #endif @@ -480,12 +255,6 @@ ILINE DestinationType alias_cast(SourceType pPtr) #define DEPRECATED #endif -////////////////////////////////////////////////////////////////////////// -// compile time error stuff -////////////////////////////////////////////////////////////////////////// -#undef STATIC_CHECK -#define STATIC_CHECK(expr, msg) static_assert(expr, #msg) - // Assert dialog box macros #include "CryAssert.h" @@ -495,35 +264,12 @@ ILINE DestinationType alias_cast(SourceType pPtr) #define assert CRY_ASSERT #endif -#include "CompileTimeAssert.h" ////////////////////////////////////////////////////////////////////////// // Platform dependent functions that emulate Win32 API. // Mostly used only for debugging! ////////////////////////////////////////////////////////////////////////// -void CryDebugBreak(); void CrySleep(unsigned int dwMilliseconds); -void CryLowLatencySleep(unsigned int dwMilliseconds); int CryMessageBox(const char* lpText, const char* lpCaption, unsigned int uType); -short CryGetAsyncKeyState(int vKey); -unsigned int CryGetFileAttributes(const char* lpFileName); - -inline void CryHeapCheck() -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_11 - #include AZ_RESTRICTED_FILE(platform_h) -#elif !defined(LINUX) && !defined(APPLE) // todo: this might be readded with later xdks? -#if !defined(NDEBUG) - int Result = -#endif - _heapchk(); - assert(Result != _HEAPBADBEGIN); - assert(Result != _HEAPBADNODE); - assert(Result != _HEAPBADPTR); - assert(Result != _HEAPEMPTY); - assert(Result == _HEAPOK); -#endif -} //--------------------------------------------------------------------------- // Useful function to clean the structure. @@ -554,77 +300,6 @@ inline D check_cast(S const& s) return d; } -// Convert one type to another, asserting there is no conversion loss. -// Usage: DestType dest; check_convert(dest, src); -template -inline D& check_convert(D& d, S const& s) -{ - d = D(s); - assert(S(d) == s); - return d; -} - -// Convert one type to another, asserting there is no conversion loss. -// Usage: DestType dest; check_convert(dest) = src; -template -struct CheckConvert -{ - CheckConvert(D& d) - : dest(&d) {} - - template - D& operator=(S const& s) - { - return check_convert(*dest, s); - } - -protected: - D* dest; -}; - -template -inline CheckConvert check_convert(D& d) -{ - return d; -} - -//--------------------------------------------------------------------------- -// Use NoCopy as a base class to easily prevent copy init & assign for any class. -struct NoCopy -{ - NoCopy() {} -private: - NoCopy(const NoCopy&); - NoCopy& operator =(const NoCopy&); -}; - -//--------------------------------------------------------------------------- -// ZeroInit: base class to zero the memory of the derived class before initialization, so local objects initialize the same as static. -// Usage: -// class MyClass: ZeroInit {...} -// class MyChild: public MyClass, ZeroInit {...} // ZeroInit must be the last base class - -template -struct ZeroInit -{ -#if defined(__clang__) || defined(__GNUC__) - bool __dummy; // Dummy var to create non-zero size, ensuring proper placement in TDerived -#endif - - ZeroInit(bool bZero = true) - { - // Optional bool arg to selectively disable zeroing. - if (bZero) - { - // Infer offset of this base class by static casting to derived class. - // Zero only the additional memory of the derived class. - TDerived* struct_end = static_cast(this) + 1; - size_t memory_size = (char*)struct_end - (char*)this; - memset(this, 0, memory_size); - } - } -}; - //--------------------------------------------------------------------------- // Quick const-manipulation macros @@ -696,29 +371,19 @@ void SetFlags(T& dest, U flags, bool b) bool CrySetFileAttributes(const char* lpFileName, uint32 dwFileAttributes); threadID CryGetCurrentThreadId(); -// need this in a common header file and any other file would be too misleading -enum ETriState -{ - eTS_false, - eTS_true, - eTS_maybe -}; - - #ifdef __GNUC__ - #define NO_INLINE __attribute__ ((noinline)) -# define NO_INLINE_WEAK __attribute__ ((noinline)) __attribute__((weak)) // marks a function as no_inline, but also as weak to prevent multiple-defined errors - -# define __PACKED __attribute__ ((packed)) - #else - #define NO_INLINE _declspec(noinline) -# define NO_INLINE_WEAK _declspec(noinline) inline - -# define __PACKED - #endif +#ifdef __GNUC__ + #define NO_INLINE __attribute__ ((noinline)) + #define NO_INLINE_WEAK __attribute__ ((noinline)) __attribute__((weak)) // marks a function as no_inline, but also as weak to prevent multiple-defined errors + #define __PACKED __attribute__ ((packed)) +#else + #define NO_INLINE _declspec(noinline) + #define NO_INLINE_WEAK _declspec(noinline) inline + #define __PACKED +#endif // Fallback for Alignment macro of GCC/CLANG (must be after the class definition) #if !defined(_ALIGN) - #define _ALIGN(num) AZ_POP_DISABLE_WARNING + #define _ALIGN(num) AZ_POP_DISABLE_WARNING #endif // Fallback for Alignment macro of MSVC (must be before the class definition) @@ -726,60 +391,13 @@ enum ETriState #define _MS_ALIGN(num) AZ_PUSH_DISABLE_WARNING(4324, "-Wunknown-warning-option") #endif -#if defined(WIN32) || defined(WIN64) -extern "C" { -__declspec(dllimport) unsigned long __stdcall TlsAlloc(); -__declspec(dllimport) void* __stdcall TlsGetValue(unsigned long dwTlsIndex); -__declspec(dllimport) int __stdcall TlsSetValue(unsigned long dwTlsIndex, void* lpTlsValue); -} - - #define TLS_DECLARE(type, var) extern int var##idx; - #define TLS_DEFINE(type, var) \ - int var##idx; \ - struct Init##var { \ - Init##var() { var##idx = TlsAlloc(); } \ - }; \ - Init##var g_init##var; - #define TLS_DEFINE_DEFAULT_VALUE(type, var, value) \ - int var##idx; \ - struct Init##var { \ - Init##var() { var##idx = TlsAlloc(); TlsSetValue(var##idx, reinterpret_cast(value)); } \ - }; \ - Init##var g_init##var; - #define TLS_GET(type, var) (type)TlsGetValue(var##idx) - #define TLS_SET(var, val) TlsSetValue(var##idx, reinterpret_cast(val)) -#elif defined(USE_PTHREAD_TLS) - #define TLS_DECLARE(_TYPE, _VAR) extern SCryPthreadTLS<_TYPE> _VAR##TLSKey; - #define TLS_DEFINE(_TYPE, _VAR) SCryPthreadTLS<_TYPE> _VAR##TLSKey; - #define TLS_DEFINE_DEFAULT_VALUE(_TYPE, _VAR, _DEFAULT) SCryPthreadTLS<_TYPE> _VAR##TLSKey = _DEFAULT; - #define TLS_GET(_TYPE, _VAR) _VAR##TLSKey.Get() - #define TLS_SET(_VAR, _VALUE) _VAR##TLSKey.Set(_VALUE) -#elif defined(THREADLOCAL) - #define TLS_DECLARE(type, var) extern THREADLOCAL type var; -#if defined(LINUX) || defined(MAC) - #define TLS_DEFINE(type, var) THREADLOCAL type var = 0; -#else - #define TLS_DEFINE(type, var) THREADLOCAL type var; -#endif // defined(LINUX) || defined(MAC) - #define TLS_DEFINE_DEFAULT_VALUE(type, var, value) THREADLOCAL type var = value; - #define TLS_GET(type, var) (var) - #define TLS_SET(var, val) (var = (val)) -#else // defined(THREADLOCAL) - #error "There's no support for thread local storage" -#endif - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_13 #include AZ_RESTRICTED_FILE(platform_h) #elif !defined(LINUX) && !defined(APPLE) -typedef int socklen_t; + typedef int socklen_t; #endif - -// Include MultiThreading support. -#include "CryThread.h" -#include "MultiThread.h" - // In RELEASE disable printf and fprintf #if defined(_RELEASE) && !defined(RELEASE_LOGGING) #if defined(AZ_RESTRICTED_PLATFORM) @@ -788,19 +406,9 @@ typedef int socklen_t; #endif #endif -#define _STRINGIFY(x) #x -#define STRINGIFY(x) _STRINGIFY(x) - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_15 #include AZ_RESTRICTED_FILE(platform_h) #endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) || defined(WIN64) - #define MESSAGE(msg) message(__FILE__ "(" STRINGIFY(__LINE__) "): " msg) -#else - #define MESSAGE(msg) -#endif void InitRootDir(char szExeFileName[] = nullptr, uint nExeSize = 0, char szExeRootName[] = nullptr, uint nRootSize = 0); diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index 3d23d8783e..2f377a5928 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -204,17 +204,6 @@ void __stl_debug_message(const char* format_str, ...) #include "CryAssert_impl.h" -////////////////////////////////////////////////////////////////////////// -void CryDebugBreak() -{ -#if defined(WIN32) && !defined(RELEASE) - if (IsDebuggerPresent()) -#endif - { - DebugBreak(); - } -} - ////////////////////////////////////////////////////////////////////////// void CrySleep(unsigned int dwMilliseconds) { @@ -222,21 +211,6 @@ void CrySleep(unsigned int dwMilliseconds) Sleep(dwMilliseconds); } -////////////////////////////////////////////////////////////////////////// -void CryLowLatencySleep(unsigned int dwMilliseconds) -{ - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_CRYLOWLATENCYSLEEP - #include AZ_RESTRICTED_FILE(platform_impl_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - CrySleep(dwMilliseconds); -#endif -} - ////////////////////////////////////////////////////////////////////////// int CryMessageBox([[maybe_unused]] const char* lpText, [[maybe_unused]] const char* lpCaption, [[maybe_unused]] unsigned int uType) { @@ -304,16 +278,6 @@ void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], uint } } -////////////////////////////////////////////////////////////////////////// -short CryGetAsyncKeyState([[maybe_unused]] int vKey) -{ -#ifdef WIN32 - return GetAsyncKeyState(vKey); -#else - return 0; -#endif -} - ////////////////////////////////////////////////////////////////////////// LONG CryInterlockedIncrement(int volatile* lpAddend) { @@ -419,25 +383,6 @@ void CryLeaveCriticalSection(void* cs) LeaveCriticalSection((CRITICAL_SECTION*)cs); } -////////////////////////////////////////////////////////////////////////// -uint32 CryGetFileAttributes(const char* lpFileName) -{ - WIN32_FILE_ATTRIBUTE_DATA data; - BOOL res; -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_CRYGETFILEATTRIBUTES - #include AZ_RESTRICTED_FILE(platform_impl_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - AZStd::wstring lpFileNameW; - AZStd::to_wstring(lpFileNameW, lpFileName); - res = GetFileAttributesExW(lpFileNameW.c_str(), GetFileExInfoStandard, &data); -#endif - return res ? data.dwFileAttributes : -1; -} - ////////////////////////////////////////////////////////////////////////// bool CrySetFileAttributes(const char* lpFileName, uint32 dwFileAttributes) { diff --git a/Code/Legacy/CryCommon/smartptr.h b/Code/Legacy/CryCommon/smartptr.h index 246e18d541..6953348d47 100644 --- a/Code/Legacy/CryCommon/smartptr.h +++ b/Code/Legacy/CryCommon/smartptr.h @@ -13,6 +13,7 @@ #include #include +#include void CryFatalError(const char*, ...) PRINTF_PARAMS(1, 2); #if defined(APPLE) @@ -171,13 +172,13 @@ public: void AddRef() { - CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0); + AZ_Assert(m_nRefCounter >= 0, "Invalid ref count"); ++m_nRefCounter; } void Release() { - CHECK_REFCOUNT_CRASH(m_nRefCounter > 0); + AZ_Assert(m_nRefCounter > 0, "Invalid ref count"); if (--m_nRefCounter == 0) { delete static_cast(this); @@ -215,13 +216,13 @@ public: void AddRef() { - CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0); + AZ_Assert(m_nRefCounter >= 0, "Invalid ref count"); ++m_nRefCounter; } void Release() { - CHECK_REFCOUNT_CRASH(m_nRefCounter > 0); + AZ_Assert(m_nRefCounter > 0, "Invalid ref count"); if (--m_nRefCounter == 0) { delete this; @@ -272,13 +273,13 @@ public: void AddRef() { - CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0); + AZ_Assert(m_nRefCounter >= 0, "Invalid ref count"); ++m_nRefCounter; } void Release() { - CHECK_REFCOUNT_CRASH(m_nRefCounter > 0); + AZ_Assert(m_nRefCounter > 0, "Invalid ref count"); if (--m_nRefCounter == 0) { assert(m_pDeleteFnc); diff --git a/Code/Legacy/CryCommon/stridedptr.h b/Code/Legacy/CryCommon/stridedptr.h index 737a1e40b7..8a74aa97b1 100644 --- a/Code/Legacy/CryCommon/stridedptr.h +++ b/Code/Legacy/CryCommon/stridedptr.h @@ -66,9 +66,9 @@ private: # if !defined(eLittleEndian) # error eLittleEndian is not defined, please include CryEndian.h. # endif - COMPILE_TIME_ASSERT(metautils::is_const::value || !metautils::is_const::value); + static_assert(metautils::is_const::value || !metautils::is_const::value); // note: we allow xint32 -> xint16 converting - COMPILE_TIME_ASSERT( + static_assert( (metautils::is_same::type, typename metautils::remove_const::type>::value || ((metautils::is_same::type, sint32>::value || metautils::is_same::type, uint32>::value || diff --git a/Code/Legacy/CrySystem/CrySystem_precompiled.h b/Code/Legacy/CrySystem/CrySystem_precompiled.h index f59adccb7b..daf1c335e4 100644 --- a/Code/Legacy/CrySystem/CrySystem_precompiled.h +++ b/Code/Legacy/CrySystem/CrySystem_precompiled.h @@ -68,7 +68,7 @@ #endif #ifdef WIN32 -#include +#include #include #undef GetCharWidth #undef GetUserName diff --git a/Code/Legacy/CrySystem/IDebugCallStack.cpp b/Code/Legacy/CrySystem/IDebugCallStack.cpp index 1176c15f0e..deb9c11581 100644 --- a/Code/Legacy/CrySystem/IDebugCallStack.cpp +++ b/Code/Legacy/CrySystem/IDebugCallStack.cpp @@ -227,7 +227,7 @@ void IDebugCallStack::FatalError(const char* description) #if defined(WIN32) || !defined(_RELEASE) int* p = 0x0; - PREFAST_SUPPRESS_WARNING(6011) * p = 1; // we're intentionally crashing here + *p = 1; // we're intentionally crashing here #endif } diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp index d816fa4980..ee747bc936 100644 --- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp @@ -33,10 +33,6 @@ #include -#ifdef WIN32 -#include -#endif - namespace LegacyLevelSystem { static constexpr const char* ArchiveExtension = ".pak"; diff --git a/Code/Legacy/CrySystem/SystemInit.cpp b/Code/Legacy/CrySystem/SystemInit.cpp index d1ccb56c05..08292a6353 100644 --- a/Code/Legacy/CrySystem/SystemInit.cpp +++ b/Code/Legacy/CrySystem/SystemInit.cpp @@ -251,7 +251,7 @@ static void CmdCrashTest(IConsoleCmdArgs* pArgs) case 1: { int* p = 0; - PREFAST_SUPPRESS_WARNING(6011) * p = 0xABCD; + *p = 0xABCD; } break; case 2: diff --git a/Code/Legacy/CrySystem/SystemWin32.cpp b/Code/Legacy/CrySystem/SystemWin32.cpp index 6c9b210c80..20f4d7ef65 100644 --- a/Code/Legacy/CrySystem/SystemWin32.cpp +++ b/Code/Legacy/CrySystem/SystemWin32.cpp @@ -338,32 +338,25 @@ void CSystem::FatalError(const char* format, ...) IDebugCallStack::instance()->FatalError(szBuffer); #endif - CryDebugBreak(); - // app can not continue + AZ::Debug::Trace::Break(); + #ifdef _DEBUG + #if defined(WIN32) || defined(WIN64) + _flushall(); + // on windows, _exit does all sorts of things which can cause cleanup to fail during a crash, we need to terminate instead. + TerminateProcess(GetCurrentProcess(), 1); + #endif -#if defined(WIN32) && !defined(WIN64) - DEBUG_BREAK; -#endif - -#else - -#if defined(WIN32) || defined(WIN64) - _flushall(); - // on windows, _exit does all sorts of things which can cause cleanup to fail during a crash, we need to terminate instead. - TerminateProcess(GetCurrentProcess(), 1); -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMWIN32_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(SystemWin32_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - _exit(1); -#endif + #if defined(AZ_RESTRICTED_PLATFORM) + #define AZ_RESTRICTED_SECTION SYSTEMWIN32_CPP_SECTION_2 + #include AZ_RESTRICTED_FILE(SystemWin32_cpp) + #endif + #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) + #undef AZ_RESTRICTED_SECTION_IMPLEMENTED + #else + _exit(1); + #endif #endif } diff --git a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp index 28cf0eb07a..c5df4f6570 100644 --- a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp +++ b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp @@ -26,7 +26,7 @@ if (count > 0) \ { \ const size_t memSize = count * sizeof(IViewSystemListener*); \ - PREFAST_SUPPRESS_WARNING(6255) IViewSystemListener * *pArray = (IViewSystemListener**) alloca(memSize); \ + IViewSystemListener* *pArray = (IViewSystemListener**) alloca(memSize); \ memcpy(pArray, &*m_listeners.begin(), memSize); \ while (count--) \ { \ diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp index c86c0691a9..615db0c777 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryReader.cpp @@ -194,7 +194,7 @@ void XMLBinary::XMLBinaryReader::CheckHeader(const BinaryFileHeader& header, siz // Check the signature of the file to make sure that it is a binary XML file. { static const char signature[] = "CryXmlB"; - COMPILE_TIME_ASSERT(sizeof(signature) == sizeof(header.szSignature)); + static_assert(sizeof(signature) == sizeof(header.szSignature)); if (memcmp(header.szSignature, signature, sizeof(header.szSignature)) != 0) { result = eResult_NotBinXml; diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp index f55f792516..a2a35cfe8b 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp @@ -109,7 +109,7 @@ bool XMLBinary::CXMLBinaryWriter::WriteNode(IDataWriter* pFile, XmlNodeRef node, BinaryFileHeader header; static const char signature[] = "CryXmlB"; - COMPILE_TIME_ASSERT(sizeof(signature) == sizeof(header.szSignature)); + static_assert(sizeof(signature) == sizeof(header.szSignature)); memcpy(header.szSignature, signature, sizeof(header.szSignature)); nTheoreticalPosition += sizeof(header); align(nTheoreticalPosition, nAlignment); diff --git a/Code/Legacy/CrySystem/XML/xml.cpp b/Code/Legacy/CrySystem/XML/xml.cpp index 8eb13c5247..7a9bb4bc36 100644 --- a/Code/Legacy/CrySystem/XML/xml.cpp +++ b/Code/Legacy/CrySystem/XML/xml.cpp @@ -1390,7 +1390,7 @@ protected: { ((XmlParserImp*)userData)->onEndElement(name); } - static void characterData(void* userData, const char* s, int len) PREFAST_SUPPRESS_WARNING(6262) + static void characterData(void* userData, const char* s, int len) { char str[32700]; if (len > sizeof(str) - 1) diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h index 3f79392403..4232658980 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h @@ -8,6 +8,7 @@ #pragma once +#include #include #include #include @@ -140,6 +141,9 @@ namespace AZ //! Get the memory requirements for allocating a buffer resource. virtual ResourceMemoryRequirements GetResourceMemoryRequirements(const BufferDescriptor& descriptor) = 0; + //! Notifies after all objects currently in the platform release queue are released + virtual void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) = 0; + protected: DeviceFeatures m_features; DeviceLimits m_limits; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h index cb66225286..cd8a85a385 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ObjectCollector.h @@ -34,6 +34,8 @@ namespace AZ using MutexType = NullMutex; }; + using ObjectCollectorNotifyFunction = AZStd::function; + /** * Deferred-releases reference-counted objects at a specific latency. Example: Use to batch-release * objects that exist on the GPU timeline at the end of the frame after syncing the oldest GPU frame. @@ -85,6 +87,9 @@ namespace AZ /// Must not be called at collection time. size_t GetObjectCount() const; + /// Notifies after the current set of pending objects is released. + void Notify(ObjectCollectorNotifyFunction notifyFunction); + private: void QueueForCollectInternal(ObjectPtrType object); @@ -92,6 +97,7 @@ namespace AZ { AZStd::vector m_objects; uint64_t m_collectIteration; + AZStd::vector m_notifies; }; inline bool IsGarbageReady(size_t collectIteration) @@ -106,6 +112,7 @@ namespace AZ mutable typename Traits::MutexType m_mutex; AZStd::vector m_pendingObjects; AZStd::vector m_pendingGarbage; + AZStd::vector m_pendingNotifies; }; template @@ -172,6 +179,39 @@ namespace AZ { m_pendingGarbage.push_back({ AZStd::move(m_pendingObjects), m_currentIteration }); } + + if (!m_pendingNotifies.empty()) + { + if (!m_pendingGarbage.empty()) + { + // find the newest garbage entry and add any pending notifies + Garbage& latestGarbage = m_pendingGarbage.front(); + size_t latestGarbageAge = m_currentIteration - latestGarbage.m_collectIteration; + + // check the rest of the entries to see if they are newer + for (size_t i = 1; i < m_pendingGarbage.size(); ++i) + { + size_t age = m_currentIteration - m_pendingGarbage[i].m_collectIteration; + if (age < latestGarbageAge) + { + latestGarbage = m_pendingGarbage[i]; + latestGarbageAge = age; + } + } + + latestGarbage.m_notifies.insert(latestGarbage.m_notifies.end(), m_pendingNotifies.begin(), m_pendingNotifies.end()); + } + else + { + // garbage queue is empty, notify now + for (auto& notifyFunction : m_pendingNotifies) + { + notifyFunction(); + } + } + + m_pendingNotifies.clear(); + } m_mutex.unlock(); size_t objectCount = 0; @@ -189,6 +229,12 @@ namespace AZ } } objectCount += garbage.m_objects.size(); + + for (auto& notifyFunction : garbage.m_notifies) + { + notifyFunction(); + } + garbage = AZStd::move(m_pendingGarbage.back()); m_pendingGarbage.pop_back(); } @@ -215,5 +261,13 @@ namespace AZ return objectCount; } + + template + void ObjectCollector::Notify(ObjectCollectorNotifyFunction notifyFunction) + { + m_mutex.lock(); + m_pendingNotifies.push_back(notifyFunction); + m_mutex.unlock(); + } } } diff --git a/Gems/Atom/RHI/Code/Tests/Device.h b/Gems/Atom/RHI/Code/Tests/Device.h index 3a7c513c8b..e11bd75983 100644 --- a/Gems/Atom/RHI/Code/Tests/Device.h +++ b/Gems/Atom/RHI/Code/Tests/Device.h @@ -60,6 +60,8 @@ namespace UnitTest AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::ImageDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::BufferDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; + + void ObjectCollectionNotify(AZ::RHI::ObjectCollectorNotifyFunction notifyFunction) override {} }; AZ::RHI::Ptr MakeTestDevice(); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp index 88c9098952..9d23dfa43d 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp @@ -292,6 +292,11 @@ namespace AZ return memoryRequirements; } + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + m_releaseQueue.Notify(notifyFunction); + } + //AZStd::vector Device::GetValidSwapChainImageFormats(const RHI::WindowHandle& windowHandle) const //{ // AZStd::vector formatsList; diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h index 149508307a..9119545342 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h @@ -162,6 +162,7 @@ namespace AZ void PreShutdown() override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::ImageDescriptor & descriptor) override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::BufferDescriptor & descriptor) override; + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; ////////////////////////////////////////////////////////////////////////// RHI::ResultCode InitSubPlatform(RHI::PhysicalDevice& physicalDevice); diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp index f0771d7c45..dbd2204e93 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp @@ -315,7 +315,12 @@ namespace AZ memoryRequirements.m_sizeInBytes = bufferSizeAndAlign.size; return memoryRequirements; } - + + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + m_releaseQueue.Notify(notifyFunction); + } + void Device::InitFeatures() { diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h index d8c3092c59..9cdeee7eae 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h @@ -151,7 +151,8 @@ namespace AZ NullDescriptorManager& GetNullDescriptorManager(); RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::ImageDescriptor & descriptor) override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::BufferDescriptor & descriptor) override; - + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; + private: Device() = default; diff --git a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp index 7b94efb69f..08a2c4f411 100644 --- a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp @@ -20,5 +20,10 @@ namespace AZ { formatsCapabilities.fill(static_cast(~0)); } + + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + notifyFunction(); + } } } diff --git a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h index 3aa045212b..cd44135e62 100644 --- a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h @@ -42,6 +42,7 @@ namespace AZ void PreShutdown() override {} RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const RHI::ImageDescriptor& descriptor) override { return RHI::ResourceMemoryRequirements();} RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const RHI::BufferDescriptor& descriptor) override { return RHI::ResourceMemoryRequirements();} + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; ////////////////////////////////////////////////////////////////////////// }; } diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp index 6d3080dce8..05ff8bb2a6 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp @@ -652,6 +652,11 @@ namespace AZ return RHI::ResourceMemoryRequirements{ vkRequirements.alignment, vkRequirements.size }; } + void Device::ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) + { + m_releaseQueue.Notify(notifyFunction); + } + void Device::InitFeaturesAndLimits(const PhysicalDevice& physicalDevice) { m_features.m_tessellationShader = (m_enabledDeviceFeatures.tessellationShader == VK_TRUE); diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h index d5f055f4cd..28e56d1fa9 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h @@ -134,6 +134,7 @@ namespace AZ void PreShutdown() override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::ImageDescriptor& descriptor) override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::BufferDescriptor& descriptor) override; + void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; ////////////////////////////////////////////////////////////////////////// void InitFeaturesAndLimits(const PhysicalDevice& physicalDevice); diff --git a/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h b/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h index 1de06802b1..be362c60d6 100644 --- a/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h +++ b/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h @@ -70,6 +70,7 @@ namespace UnitTest void PreShutdown() override {} AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::ImageDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::BufferDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; + void ObjectCollectionNotify(AZ::RHI::ObjectCollectorNotifyFunction notifyFunction) override {} }; class ImageView diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl index ffc9a60c00..a24fdbf1d8 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl @@ -329,7 +329,7 @@ namespace AZ ImGui::Text("Viewport width: %.3f ms", CpuProfilerImGuiHelper::TicksToMs(GetViewportTickWidth())); ImGui::Text("Ticks [%lld , %lld]", m_viewportStartTick, m_viewportEndTick); - ImGui::Text("Recording %ld threads", RHI::CpuProfiler::Get()->GetTimeRegionMap().size()); + ImGui::Text("Recording %zu threads", m_savedData.size()); ImGui::Text("%llu profiling events saved", m_savedRegionCount); ImGui::NextColumn(); @@ -389,6 +389,11 @@ namespace AZ return wrapper.m_startTick < target; }); + if (regionItr == singleThreadData.end()) + { + continue; + } + // Draw all of the blocks for a given thread/row u64 maxDepth = 0; while (regionItr != singleThreadData.end()) @@ -559,6 +564,14 @@ namespace AZ m_savedRegionCount -= sizeBeforeRemove - savedRegions.size(); } + + // Remove any threads from the top-level map that no longer hold data + AZStd::erase_if( + m_savedData, + [](const auto& singleThreadDataEntry) + { + return singleThreadDataEntry.second.empty(); + }); } inline void ImGuiCpuProfiler::DrawBlock(const TimeRegion& block, u64 targetRow) diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h index 7636b45060..9d5861c433 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont.h @@ -20,6 +20,7 @@ #include #include #include +#include #include #include diff --git a/Gems/EMotionFX/Assets/Editor/Layouts/AnimGraph.layout b/Gems/EMotionFX/Assets/Editor/Layouts/AnimGraph.layout index 85fa2f2253..e85d6054a3 100644 Binary files a/Gems/EMotionFX/Assets/Editor/Layouts/AnimGraph.layout and b/Gems/EMotionFX/Assets/Editor/Layouts/AnimGraph.layout differ diff --git a/Gems/EMotionFX/Assets/Editor/Layouts/SimulatedObjects.layout b/Gems/EMotionFX/Assets/Editor/Layouts/SimulatedObjects.layout index 9deac32edb..a7879584a9 100644 Binary files a/Gems/EMotionFX/Assets/Editor/Layouts/SimulatedObjects.layout and b/Gems/EMotionFX/Assets/Editor/Layouts/SimulatedObjects.layout differ diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp index ac824bfc4d..3dd49574fd 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNewSequenceDialog.cpp @@ -43,7 +43,7 @@ void CUiAVNewSequenceDialog::OnOK() return; } - for (int k = 0; k < CUiAnimViewSequenceManager::GetSequenceManager()->GetCount(); ++k) + for (unsigned int k = 0; k < CUiAnimViewSequenceManager::GetSequenceManager()->GetCount(); ++k) { CUiAnimViewSequence* pSequence = CUiAnimViewSequenceManager::GetSequenceManager()->GetSequenceByIndex(k); QString fullname = pSequence->GetName(); diff --git a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp index 324f32b414..35fde93e83 100644 --- a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp +++ b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp @@ -26,12 +26,12 @@ ////////////////////////////////////////////////////////////////////////// // Serialization for anim nodes & param types #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(eUiAnimNodeType_ ## name) == g_animNodeEnumToStringMap.end()); \ - g_animNodeEnumToStringMap[eUiAnimNodeType_ ## name] = STRINGIFY(name); \ - g_animNodeStringToEnumMap[AZStd::string(STRINGIFY(name))] = eUiAnimNodeType_ ## name; + g_animNodeEnumToStringMap[eUiAnimNodeType_ ## name] = AZ_STRINGIZE(name); \ + g_animNodeStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = eUiAnimNodeType_ ## name; #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(eUiAnimParamType_ ## name) == g_animParamEnumToStringMap.end()); \ - g_animParamEnumToStringMap[eUiAnimParamType_ ## name] = STRINGIFY(name); \ - g_animParamStringToEnumMap[AZStd::string(STRINGIFY(name))] = eUiAnimParamType_ ## name; + g_animParamEnumToStringMap[eUiAnimParamType_ ## name] = AZ_STRINGIZE(name); \ + g_animParamStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = eUiAnimParamType_ ## name; namespace { diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp index bd586a12c1..cf51ef3729 100644 --- a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp @@ -74,12 +74,12 @@ static SMovieSequenceAutoComplete s_movieSequenceAutoComplete; ////////////////////////////////////////////////////////////////////////// // Serialization for anim nodes & param types #define REGISTER_NODE_TYPE(name) assert(g_animNodeEnumToStringMap.find(AnimNodeType::name) == g_animNodeEnumToStringMap.end()); \ - g_animNodeEnumToStringMap[AnimNodeType::name] = STRINGIFY(name); \ - g_animNodeStringToEnumMap[AZStd::string(STRINGIFY(name))] = AnimNodeType::name; + g_animNodeEnumToStringMap[AnimNodeType::name] = AZ_STRINGIZE(name); \ + g_animNodeStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = AnimNodeType::name; #define REGISTER_PARAM_TYPE(name) assert(g_animParamEnumToStringMap.find(AnimParamType::name) == g_animParamEnumToStringMap.end()); \ - g_animParamEnumToStringMap[AnimParamType::name] = STRINGIFY(name); \ - g_animParamStringToEnumMap[AZStd::string(STRINGIFY(name))] = AnimParamType::name; + g_animParamEnumToStringMap[AnimParamType::name] = AZ_STRINGIZE(name); \ + g_animParamStringToEnumMap[AZStd::string(AZ_STRINGIZE(name))] = AnimParamType::name; namespace { diff --git a/cmake/Packaging.cmake b/cmake/Packaging.cmake index c4d5be534c..477a5f24ea 100644 --- a/cmake/Packaging.cmake +++ b/cmake/Packaging.cmake @@ -129,7 +129,7 @@ install(FILES ${_cmake_package_dest} # the version string and git tags are intended to be synchronized so it should be safe to use that instead # of directly calling into git which could get messy in certain scenarios if(${CPACK_PACKAGE_VERSION} VERSION_GREATER "0.0.0.0") - set(_3rd_party_license_filename SPDX-Licenses.txt) + set(_3rd_party_license_filename NOTICES.txt) set(_3rd_party_license_url "https://raw.githubusercontent.com/o3de/3p-package-source/${CPACK_PACKAGE_VERSION}/${_3rd_party_license_filename}") set(_3rd_party_license_dest ${CPACK_BINARY_DIR}/${_3rd_party_license_filename}) diff --git a/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in b/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in index b340d23467..eea1adc11b 100644 --- a/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in +++ b/cmake/Platform/Windows/Packaging/BootstrapperTheme.xml.in @@ -4,15 +4,15 @@ #(loc.WindowTitle) - Open Sans + Segoe UI - Open Sans + Segoe UI - Open Sans + Segoe UI - Open Sans + Segoe UI - Open Sans + Segoe UI diff --git a/scripts/build/Platform/Windows/deploy_cdk_applications.cmd b/scripts/build/Platform/Windows/deploy_cdk_applications.cmd new file mode 100644 index 0000000000..2845707923 --- /dev/null +++ b/scripts/build/Platform/Windows/deploy_cdk_applications.cmd @@ -0,0 +1,105 @@ +@ECHO OFF +REM +REM Copyright (c) Contributors to the Open 3D Engine Project. +REM For complete copyright and license terms please see the LICENSE at the root of this distribution. +REM +REM SPDX-License-Identifier: Apache-2.0 OR MIT +REM +REM + +REM Deploy the CDK applcations for AWS gems (Windows only) +REM Prerequisites: +REM 1) Node.js is installed +REM 2) Node.js version >= 10.13.0, except for versions 13.0.0 - 13.6.0. A version in active long-term support is recommended. +SETLOCAL EnableDelayedExpansion + +SET SOURCE_DIRECTORY=%CD% +SET PATH=%SOURCE_DIRECTORY%\python;%PATH% +SET GEM_DIRECTORY=%SOURCE_DIRECTORY%\Gems + +REM Create and activate a virtualenv for the CDK deployment +CALL python -m venv .env +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to create a virtualenv for the CDK deployment + exit /b 1 +) +CALL .env\Scripts\activate.bat +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to activate the virtualenv for the CDK deployment + exit /b 1 +) + +ECHO [cdk_installation] Install the latest version of CDK +CALL npm uninstall -g aws-cdk +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to uninstall the current version of CDK + exit /b 1 +) +CALL npm install -g aws-cdk@latest +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to install the latest version of CDK + exit /b 1 +) + +REM Set temporary AWS credentials from the assume role +FOR /f "tokens=1,2,3" %%a IN ('CALL aws sts assume-role --query Credentials.[SecretAccessKey^,SessionToken^,AccessKeyId] --output text --role-arn %ASSUME_ROLE_ARN% --role-session-name o3de-Automation-session') DO ( + SET AWS_SECRET_ACCESS_KEY=%%a + SET AWS_SESSION_TOKEN=%%b + SET AWS_ACCESS_KEY_ID=%%c +) +FOR /F "tokens=4 delims=:" %%a IN ("%ASSUME_ROLE_ARN%") DO SET O3DE_AWS_DEPLOY_ACCOUNT=%%a + +REM Bootstrap and deploy the CDK applications +ECHO [cdk_bootstrap] Bootstrap CDK +CALL cdk bootstrap aws://%O3DE_AWS_DEPLOY_ACCOUNT%/%O3DE_AWS_DEPLOY_REGION% +IF ERRORLEVEL 1 ( + ECHO [cdk_bootstrap] Failed to bootstrap CDK + exit /b 1 +) + +CALL :DeployCDKApplication AWSCore --all +IF ERRORLEVEL 1 ( + exit /b 1 +) +CALL :DeployCDKApplication AWSClientAuth +IF ERRORLEVEL 1 ( + exit /b 1 +) +CALL :DeployCDKApplication AWSMetrics "-c batch_processing=true" +IF ERRORLEVEL 1 ( + exit /b 1 +) + +EXIT /b 0 + +:DeployCDKApplication +REM Deploy the CDK application for a specific AWS gem +SET GEM_NAME=%~1 +SET ADDITIONAL_ARGUMENTS=%~2 +ECHO [cdk_deployment] Deploy the CDK application for the %GEM_NAME% gem +PUSHD %GEM_DIRECTORY%\%GEM_NAME%\cdk + +REM Revert the CDK application code to a stable state using the provided commit ID +CALL git checkout %COMMIT_ID% -- . +IF ERRORLEVEL 1 ( + ECHO [git_checkout] Failed to checkout the CDK application for the %GEM_NAME% gem using commit ID %COMMIT_ID% + POPD + exit /b 1 +) + +REM Install required packages for the CDK application +CALL python -m pip install -r requirements.txt +IF ERRORLEVEL 1 ( + ECHO [cdk_deployment] Failed to install required packages for the %GEM_NAME% gem + POPD + exit /b 1 +) + +REM Deploy the CDK application +CALL cdk deploy %ADDITIONAL_ARGUMENTS% --require-approval never +IF ERRORLEVEL 1 ( + ECHO [cdk_deployment] Failed to deploy the CDK application for the %GEM_NAME% gem + POPD + exit /b 1 +) +POPD diff --git a/scripts/license_scanner/license_scanner.py b/scripts/license_scanner/license_scanner.py new file mode 100644 index 0000000000..c0e3c1f1ba --- /dev/null +++ b/scripts/license_scanner/license_scanner.py @@ -0,0 +1,129 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +import argparse +import fnmatch +import json +import os +import pathlib +import re +import sys + + +class LicenseScanner: + """Class to contain license scanner. + + Scans source tree for license files using provided filename patterns and generates a file + with the contents of all the licenses. + + :param config_file: Config file with license patterns and scanner settings + """ + + DEFAULT_CONFIG_FILE = 'scanner_config.json' + + def __init__(self, config_file=None): + self.config_file = config_file + self.config_data = self._load_config() + self.license_regex = self._load_license_regex() + + def _load_config(self): + """Load config from the provided file. Sets default file if one is not provided.""" + if self.config_file is None: + script_directory = os.path.dirname(os.path.abspath(__file__)) # Default file expected in same dir as script + self.config_file = os.path.join(script_directory, self.DEFAULT_CONFIG_FILE) + + try: + with open(self.config_file) as f: + return json.load(f) + except FileNotFoundError: + print('Config file cannot be found') + raise + + def _load_license_regex(self): + """Returns regex object with case-insensitive matching from the list of filename patterns.""" + regex_patterns = [] + for pattern in self.config_data['license_patterns']: + regex_patterns.append(fnmatch.translate(pattern)) + return re.compile('|'.join(regex_patterns), re.IGNORECASE) + + def scan(self, path=os.curdir): + """Scan directory tree for filenames matching license_regex. + + :param path: Path of the directory to run scanner + :return: Package paths and their corresponding license file contents + :rtype: dict + """ + licenses = 0 + license_files = {} + + for dirpath, dirnames, filenames in os.walk(path): + for file in filenames: + if self.license_regex.match(file): + license_file_content = self._get_license_file_contents(os.path.join(dirpath, file)) + rel_dirpath = os.path.relpath(dirpath, path) # Limit path inside scanned directory + license_files[rel_dirpath] = license_file_content + licenses += 1 + print(f'License file: {os.path.join(dirpath, file)}') + + # Remove directories that should not be scanned + for dir in self.config_data['excluded_directories']: + if dir in dirnames: + dirnames.remove(dir) + print(f'{licenses} license files found.') + return license_files + + def _get_license_file_contents(self, filepath): + try: + with open(filepath, encoding='utf8') as f: + return f.read() + except UnicodeDecodeError: + print(f'Unable to read license file: {filepath}') + pass + + def create_license_file(self, licenses, filepath='NOTICES.txt'): + """Creates file with all the provided license file contents. + + :param licenses: Dict with package paths and their corresponding license file contents + :param filepath: Path to write the file + """ + package_separator = '------------------------------------' + with open(filepath, 'w', encoding='utf8') as f: + for directory, license in licenses.items(): + license_output = '\n\n'.join([ + f'{package_separator}', + f'Package path: {directory}', + 'License:', + f'{license}\n' + ]) + f.write(license_output) + return None + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Script to run LicenseScanner and generate license file') + parser.add_argument('--config-file', '-c', type=pathlib.Path, help='Config file for LicenseScanner') + parser.add_argument('--license-file-path', '-l', type=pathlib.Path, help='Create license file in the provided path') + parser.add_argument('--scan-path', '-s', default=os.curdir, type=pathlib.Path, help='Path to scan') + return parser.parse_args() + + +def main(): + try: + args = parse_args() + ls = LicenseScanner(args.config_file) + licenses = ls.scan(args.scan_path) + + if args.license_file_path: + ls.create_license_file(licenses, args.license_file_path) + except FileNotFoundError as e: + print(f'Type: {type(e).__name__}, Error: {e}') + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/license_scanner/scanner_config.json b/scripts/license_scanner/scanner_config.json new file mode 100644 index 0000000000..b5863a7d31 --- /dev/null +++ b/scripts/license_scanner/scanner_config.json @@ -0,0 +1,12 @@ +{ + "excluded_directories": [ + ".git", + ".venv", + "build", + "license_scanner" + ], + "license_patterns": [ + "LICENSE*", + "COPYING*" + ] +}