diff --git a/AutomatedTesting/Gem/PythonTests/AWS/README.md b/AutomatedTesting/Gem/PythonTests/AWS/README.md new file mode 100644 index 0000000000..8b5e65d6d7 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/AWS/README.md @@ -0,0 +1,26 @@ +# AWS Gem Automation Tests + +## Prerequisites +1. Build the O3DE Editor and AutomatedTesting.GameLauncher in Profile. +2. AWS CLI is installed and configured following [Configuration and Credential File Settings](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html). +3. [AWS Cloud Development Kit (CDK)](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html#getting_started_install) is installed. + +## Deploy CDK Applications +1. Go to the AWS IAM console and create an IAM role called o3de-automation-tests which adds your own account as as a trusted entity and uses the "AdministratorAccess" permissions policy. +2. Copy {engine_root}\scripts\build\Platform\Windows\deploy_cdk_applications.cmd to your engine root folder. +3. Open a Command Prompt window at the engine root and set the following environment variables: + Set O3DE_AWS_PROJECT_NAME=AWSAUTO + Set O3DE_AWS_DEPLOY_REGION=us-east-1 + Set ASSUME_ROLE_ARN="arn:aws:iam::{your_aws_account_id}:role/o3de-automation-tests" + Set COMMIT_ID=HEAD +4. Deploy the CDK applications for AWS gems by running deploy_cdk_applications.cmd in the same Command Prompt window. +5. Edit AWS\common\constants.py to replace the assume role ARN with your own: + arn:aws:iam::{your_aws_account_id}:role/o3de-automation-tests + +## Run Automation Tests +### CLI +Open a Command Prompt window at the engine root and run the following CLI command: +python\python.cmd -m pytest {path_to_the_test_file} --build-directory {directory_to_the_profile_build} + +### Pycharm +You can also run any specific automation test directly from Pycharm by providing the "--build-directory" argument in the Run Configuration. \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py index cd8858e7f2..061db991cf 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py @@ -9,18 +9,18 @@ import logging import os import pytest import typing - from datetime import datetime + import ly_test_tools.log.log_monitor +from AWS.common import constants +from .aws_metrics_custom_thread import AWSMetricsThread + # fixture imports from assetpipeline.ap_fixtures.asset_processor_fixture import asset_processor from .aws_metrics_utils import aws_metrics_utils -from .aws_metrics_custom_thread import AWSMetricsThread AWS_METRICS_FEATURE_NAME = 'AWSMetrics' -GAME_LOG_NAME = 'Game.log' -CONTEXT_VARIABLE = ['-c', 'batch_processing=true'] logger = logging.getLogger(__name__) @@ -36,7 +36,7 @@ def setup(launcher: pytest.fixture, asset_processor.start() asset_processor.wait_for_idle() - file_to_monitor = os.path.join(launcher.workspace.paths.project_log(), GAME_LOG_NAME) + file_to_monitor = os.path.join(launcher.workspace.paths.project_log(), constants.GAME_LOG_NAME) # Initialize the log monitor. log_monitor = ly_test_tools.log.log_monitor.LogMonitor(launcher=launcher, log_file_path=file_to_monitor) @@ -73,23 +73,26 @@ def monitor_metrics_submission(log_monitor: pytest.fixture) -> None: f'unexpected_lines values: {unexpected_lines}') -def query_metrics_from_s3(aws_metrics_utils: pytest.fixture, stack_name: str) -> None: +def query_metrics_from_s3(aws_metrics_utils: pytest.fixture, resource_mappings: pytest.fixture, stack_name: str) -> None: """ Verify that the metrics events are delivered to the S3 bucket and can be queried. - aws_metrics_utils: aws_metrics_utils fixture. - stack_name: name of the CloudFormation stack. + :param aws_metrics_utils: aws_metrics_utils fixture. + :param resource_mappings: resource_mappings fixture. + :param stack_name: name of the CloudFormation stack. """ - analytics_bucket_name = aws_metrics_utils.get_analytics_bucket_name(stack_name) - aws_metrics_utils.verify_s3_delivery(analytics_bucket_name) + aws_metrics_utils.verify_s3_delivery( + resource_mappings.get_resource_name_id('AWSMetrics.AnalyticsBucketName') + ) logger.info('Metrics are sent to S3.') - aws_metrics_utils.run_glue_crawler(f'{stack_name}-EventsCrawler') + aws_metrics_utils.run_glue_crawler( + resource_mappings.get_resource_name_id('AWSMetrics.EventsCrawlerName')) + + # Remove the events_json table if exists so that the sample query can create a table with the same name. + aws_metrics_utils.delete_table(f'{stack_name}-eventsdatabase', 'events_json') aws_metrics_utils.run_named_queries(f'{stack_name}-AthenaWorkGroup') logger.info('Query metrics from S3 successfully.') - # Empty the S3 bucket. S3 buckets can only be deleted successfully when it doesn't contain any object. - aws_metrics_utils.empty_batch_analytics_bucket(analytics_bucket_name) - def verify_operational_metrics(aws_metrics_utils: pytest.fixture, stack_name: str, start_time: datetime) -> None: """ @@ -102,7 +105,7 @@ def verify_operational_metrics(aws_metrics_utils: pytest.fixture, stack_name: st 'AWS/Lambda', 'Invocations', [{'Name': 'FunctionName', - 'Value': f'{stack_name}-AnalyticsProcessingLambdaName'}], + 'Value': f'{stack_name}-AnalyticsProcessingLambda'}], start_time) logger.info('AnalyticsProcessingLambda metrics are sent to CloudWatch.') @@ -115,50 +118,59 @@ def verify_operational_metrics(aws_metrics_utils: pytest.fixture, stack_name: st logger.info('EventsProcessingLambda metrics are sent to CloudWatch.') -def start_kinesis_analytics_application(aws_metrics_utils: pytest.fixture, stack_name: str) -> None: +def update_kinesis_analytics_application_status(aws_metrics_utils: pytest.fixture, + resource_mappings: pytest.fixture, start_application: bool) -> None: """ - Start the Kinesis analytics application for real-time analytics. - aws_metrics_utils: aws_metrics_utils fixture. - stack_name: name of the CloudFormation stack. + Update the Kinesis analytics application to start or stop it. + :param aws_metrics_utils: aws_metrics_utils fixture. + :param resource_mappings: resource_mappings fixture. + :param start_application: whether to start or stop the application. """ - analytics_application_name = f'{stack_name}-AnalyticsApplication' - aws_metrics_utils.start_kinesis_data_analytics_application(analytics_application_name) + if start_application: + aws_metrics_utils.start_kinesis_data_analytics_application( + resource_mappings.get_resource_name_id('AWSMetrics.AnalyticsApplicationName')) + else: + aws_metrics_utils.stop_kinesis_data_analytics_application( + resource_mappings.get_resource_name_id('AWSMetrics.AnalyticsApplicationName')) @pytest.mark.SUITE_periodic @pytest.mark.usefixtures('automatic_process_killer') -@pytest.mark.parametrize('project', ['AutomatedTesting']) -@pytest.mark.parametrize('level', ['AWS/Metrics']) -@pytest.mark.parametrize('feature_name', [AWS_METRICS_FEATURE_NAME]) -@pytest.mark.usefixtures('resource_mappings') -@pytest.mark.parametrize('resource_mappings_filename', ['default_aws_resource_mappings.json']) @pytest.mark.usefixtures('aws_credentials') +@pytest.mark.usefixtures('resource_mappings') +@pytest.mark.parametrize('assume_role_arn', [constants.ASSUME_ROLE_ARN]) +@pytest.mark.parametrize('feature_name', [AWS_METRICS_FEATURE_NAME]) +@pytest.mark.parametrize('level', ['AWS/Metrics']) @pytest.mark.parametrize('profile_name', ['AWSAutomationTest']) -@pytest.mark.parametrize('region_name', ['us-west-2']) -@pytest.mark.parametrize('assume_role_arn', ['arn:aws:iam::645075835648:role/o3de-automation-tests']) -@pytest.mark.usefixtures('cdk') -@pytest.mark.parametrize('session_name', ['o3de-Automation-session']) -@pytest.mark.parametrize('deployment_params', [CONTEXT_VARIABLE]) +@pytest.mark.parametrize('project', ['AutomatedTesting']) +@pytest.mark.parametrize('region_name', [constants.AWS_REGION]) +@pytest.mark.parametrize('resource_mappings_filename', [constants.AWS_RESOURCE_MAPPING_FILE_NAME]) +@pytest.mark.parametrize('session_name', [constants.SESSION_NAME]) +@pytest.mark.parametrize('stacks', [[f'{constants.AWS_PROJECT_NAME}-{AWS_METRICS_FEATURE_NAME}-{constants.AWS_REGION}']]) class TestAWSMetricsWindows(object): """ Test class to verify the real-time and batch analytics for metrics. """ - - @pytest.mark.parametrize('destroy_stacks_on_teardown', [False]) def test_realtime_and_batch_analytics(self, level: str, launcher: pytest.fixture, asset_processor: pytest.fixture, workspace: pytest.fixture, aws_utils: pytest.fixture, - cdk: pytest.fixture, + resource_mappings: pytest.fixture, + stacks: typing.List, aws_metrics_utils: pytest.fixture): """ Verify that the metrics events are sent to CloudWatch and S3 for analytics. """ # Start Kinesis analytics application on a separate thread to avoid blocking the test. - kinesis_analytics_application_thread = AWSMetricsThread(target=start_kinesis_analytics_application, - args=(aws_metrics_utils, cdk.stacks[0])) + kinesis_analytics_application_thread = AWSMetricsThread(target=update_kinesis_analytics_application_status, + args=(aws_metrics_utils, resource_mappings, True)) kinesis_analytics_application_thread.start() + + # Clear the analytics bucket objects before sending new metrics. + aws_metrics_utils.empty_bucket( + resource_mappings.get_resource_name_id('AWSMetrics.AnalyticsBucketName')) + log_monitor = setup(launcher, asset_processor) # Kinesis analytics application needs to be in the running state before we start the game launcher. @@ -177,18 +189,22 @@ class TestAWSMetricsWindows(object): start_time) logger.info('Real-time metrics are sent to CloudWatch.') - # Run time-consuming verifications on separate threads to avoid blocking the test. - verification_threads = list() - verification_threads.append( - AWSMetricsThread(target=query_metrics_from_s3, args=(aws_metrics_utils, cdk.stacks[0]))) - verification_threads.append( - AWSMetricsThread(target=verify_operational_metrics, args=(aws_metrics_utils, cdk.stacks[0], start_time))) - for thread in verification_threads: + # Run time-consuming operations on separate threads to avoid blocking the test. + operational_threads = list() + operational_threads.append( + AWSMetricsThread(target=query_metrics_from_s3, + args=(aws_metrics_utils, resource_mappings, stacks[0]))) + operational_threads.append( + AWSMetricsThread(target=verify_operational_metrics, + args=(aws_metrics_utils, stacks[0], start_time))) + operational_threads.append( + AWSMetricsThread(target=update_kinesis_analytics_application_status, + args=(aws_metrics_utils, resource_mappings, False))) + for thread in operational_threads: thread.start() - for thread in verification_threads: + for thread in operational_threads: thread.join() - @pytest.mark.parametrize('destroy_stacks_on_teardown', [True]) def test_unauthorized_user_request_rejected(self, level: str, launcher: pytest.fixture, diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py index 97cd563651..e7eb486d02 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py @@ -198,7 +198,7 @@ class AWSMetricsUtils: assert state == 'SUCCEEDED', f'Failed to run the named query {named_query.get("Name", {})}' - def empty_batch_analytics_bucket(self, bucket_name: str) -> None: + def empty_bucket(self, bucket_name: str) -> None: """ Empty the S3 bucket following: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/migrations3.html @@ -211,25 +211,18 @@ class AWSMetricsUtils: for key in bucket.objects.all(): key.delete() - def get_analytics_bucket_name(self, stack_name: str) -> str: + def delete_table(self, database_name: str, table_name: str) -> None: """ - Get the name of the deployed S3 bucket. - :param stack_name: Name of the CloudFormation stack. - :return: Name of the deployed S3 bucket. + Delete an existing Glue table. + + :param database_name: Name of the Glue database. + :param table_name: Name of the table to delete. """ - - client = self._aws_util.client('cloudformation') - - response = client.describe_stack_resources( - StackName=stack_name + client = self._aws_util.client('glue') + client.delete_table( + DatabaseName=database_name, + Name=table_name ) - resources = response.get('StackResources', []) - - for resource in resources: - if resource.get('ResourceType') == 'AWS::S3::Bucket': - return resource.get('PhysicalResourceId', '') - - return '' @pytest.fixture(scope='function') diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py index abfeaec076..46070a3a64 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py @@ -45,7 +45,8 @@ class KinesisAnalyticsApplicationUpdatedWaiter(CustomWaiter): class GlueCrawlerReadyWaiter(CustomWaiter): """ Subclass of the base custom waiter class. - Wait for the Glue crawler to finish its processing. + Wait for the Glue crawler to finish its processing. Return when the crawler is in the "Stopping" status + to avoid wasting too much time in the automation tests on its shutdown process. """ def __init__(self, client: botocore.client): """ @@ -57,7 +58,7 @@ class GlueCrawlerReadyWaiter(CustomWaiter): 'GlueCrawlerReady', 'GetCrawler', 'Crawler.State', - {'READY': WaitState.SUCCESS}, + {'STOPPING': WaitState.SUCCESS}, client) def wait(self, crawler_name): diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/__init__.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/__init__.py deleted file mode 100644 index bbcbcf1807..0000000000 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/__init__.py +++ /dev/null @@ -1,7 +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 -""" - diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk_utils.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk_utils.py deleted file mode 100644 index 3643c3bb36..0000000000 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk_utils.py +++ /dev/null @@ -1,248 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import pytest -import boto3 -import uuid -import logging -import subprocess -import botocore - -import ly_test_tools.environment.process_utils as process_utils -from typing import List - -BOOTSTRAP_STACK_NAME = 'CDKToolkit' -BOOTSTRAP_STAGING_BUCKET_LOGIC_ID = 'StagingBucket' - -logger = logging.getLogger(__name__) - - -class Cdk: - """ - Cdk class that provides methods to run cdk application commands. - Expects system to have NodeJS, AWS CLI and CDK installed globally and have their paths setup as env variables. - """ - - def __init__(self): - self._cdk_env = '' - self._stacks = [] - self._cdk_path = os.path.dirname(os.path.realpath(__file__)) - self._session = '' - - cdk_npm_latest_version_cmd = ['npm', 'view', 'aws-cdk', 'version'] - - output = process_utils.check_output( - cdk_npm_latest_version_cmd, - cwd=self._cdk_path, - shell=True) - cdk_npm_latest_version = output.split()[0] - - cdk_version_cmd = ['cdk', 'version'] - output = process_utils.check_output( - cdk_version_cmd, - cwd=self._cdk_path, - shell=True) - cdk_version = output.split()[0] - logger.info(f'Current CDK version {cdk_version}') - - if cdk_version != cdk_npm_latest_version: - try: - logger.info(f'Updating CDK to latest') - # uninstall and reinstall cdk in case npm has been updated. - output = process_utils.check_output( - 'npm uninstall -g aws-cdk', - cwd=self._cdk_path, - shell=True) - - logger.info(f'Uninstall CDK output: {output}') - - output = process_utils.check_output( - 'npm install -g aws-cdk@latest', - cwd=self._cdk_path, - shell=True) - - logger.info(f'Install CDK output: {output}') - except subprocess.CalledProcessError as error: - logger.warning(f'Failed reinstalling latest CDK on npm' - f'\nError:{error.stderr}') - - def setup(self, cdk_path: str, project: str, account_id: str, - workspace: pytest.fixture, session: boto3.session.Session): - """ - :param cdk_path: Path where cdk app.py is stored. - :param project: Project name used for cdk project name env variable. - :param account_id: AWS account id to use with cdk application. - :param workspace: ly_test_tools workspace fixture. - :param session: Current boto3 session, provides credentials and region. - """ - self._cdk_env = os.environ.copy() - unique_id = uuid.uuid4().hex[-4:] - self._cdk_env['O3DE_AWS_PROJECT_NAME'] = project[:4] + unique_id if len(project) > 4 else project + unique_id - self._cdk_env['O3DE_AWS_DEPLOY_REGION'] = session.region_name - self._cdk_env['O3DE_AWS_DEPLOY_ACCOUNT'] = account_id - self._cdk_env['PATH'] = f'{workspace.paths.engine_root()}\\python;' + self._cdk_env['PATH'] - - credentials = session.get_credentials().get_frozen_credentials() - self._cdk_env['AWS_ACCESS_KEY_ID'] = credentials.access_key - self._cdk_env['AWS_SECRET_ACCESS_KEY'] = credentials.secret_key - self._cdk_env['AWS_SESSION_TOKEN'] = credentials.token - self._cdk_path = cdk_path - - self._session = session - - output = process_utils.check_output( - 'python -m pip install -r requirements.txt', - cwd=self._cdk_path, - env=self._cdk_env, - shell=True) - - logger.info(f'Installing cdk python dependencies: {output}') - - self.bootstrap() - - def bootstrap(self) -> None: - """ - Deploy the bootstrap stack. - """ - try: - bootstrap_cmd = ['cdk', 'bootstrap', - f'aws://{self._cdk_env["O3DE_AWS_DEPLOY_ACCOUNT"]}/{self._cdk_env["O3DE_AWS_DEPLOY_REGION"]}'] - - process_utils.check_call( - bootstrap_cmd, - cwd=self._cdk_path, - env=self._cdk_env, - shell=True) - except botocore.exceptions.ClientError as clientError: - logger.warning(f'Failed creating Bootstrap stack {BOOTSTRAP_STACK_NAME} not found. ' - f'\nError:{clientError["Error"]["Message"]}') - - def list(self, deployment_params: List[str] = None) -> List[str]: - """ - lists cdk stack names. - :param deployment_params: Deployment parameters like --all can be passed in this way. - :return List of cdk stack names. - """ - if not self._cdk_path: - return [] - - list_cdk_application_cmd = ['cdk', 'list'] - if deployment_params: - list_cdk_application_cmd.extend(deployment_params) - - output = process_utils.check_output( - list_cdk_application_cmd, - cwd=self._cdk_path, - env=self._cdk_env, - shell=True) - - return output.splitlines() - - def synthesize(self, deployment_params: List[str] = None) -> None: - """ - Synthesizes all cdk stacks. - :param deployment_params: Deployment parameters like --all can be passed in this way. - """ - if not self._cdk_path: - return - - synth_cdk_application_cmd = ['cdk', 'synth'] - if deployment_params: - synth_cdk_application_cmd.extend(deployment_params) - - process_utils.check_output( - synth_cdk_application_cmd, - cwd=self._cdk_path, - env=self._cdk_env, - shell=True) - - def deploy(self, deployment_params: List[str] = None) -> List[str]: - """ - Deploys all the CDK stacks. - :param deployment_params: Deployment parameters like --all can be passed in this way. - :return List of deployed stack arns. - """ - if not self._cdk_path: - return [] - - deploy_cdk_application_cmd = ['cdk', 'deploy', '--require-approval', 'never'] - if deployment_params: - deploy_cdk_application_cmd.extend(deployment_params) - - output = process_utils.check_output( - deploy_cdk_application_cmd, - cwd=self._cdk_path, - env=self._cdk_env, - shell=True) - - for line in output.splitlines(): - line_sections = line.split('/') - assert len(line_sections), 3 - self._stacks.append(line.split('/')[-2]) - - return self._stacks - - def destroy(self, deployment_params: List[str] = None) -> None: - """ - Destroys the cdk application. - :param deployment_params: Deployment parameters like --all can be passed in this way. - """ - - logger.info(f'CDK Path {self._cdk_path}') - destroy_cdk_application_cmd = ['cdk', 'destroy', '-f'] - if deployment_params: - destroy_cdk_application_cmd.extend(deployment_params) - - try: - process_utils.check_output( - destroy_cdk_application_cmd, - cwd=self._cdk_path, - env=self._cdk_env, - shell=True) - - except subprocess.CalledProcessError as e: - logger.error(e.output) - raise e - - self._stacks = [] - - def remove_bootstrap_stack(self) -> None: - """ - Remove the CDK bootstrap stack. - :param aws_utils: aws_utils fixture. - """ - # Check if the bootstrap stack exists. - response = self._session.client('cloudformation').describe_stacks( - StackName=BOOTSTRAP_STACK_NAME - ) - stacks = response.get('Stacks', []) - if not stacks or len(stacks) is 0: - return - - # Clear the bootstrap staging bucket before deleting the bootstrap stack. - response = self._session.client('cloudformation').describe_stack_resource( - StackName=BOOTSTRAP_STACK_NAME, - LogicalResourceId=BOOTSTRAP_STAGING_BUCKET_LOGIC_ID - ) - - staging_bucket_name = response.get('StackResourceDetail', {}).get('PhysicalResourceId', '') - if staging_bucket_name: - s3 = self._session.resource('s3') - bucket = s3.Bucket(staging_bucket_name) - for key in bucket.objects.all(): - key.delete() - - # Delete the bootstrap stack. - # Should not need to delete the stack if S3 bucket can be cleaned. - # self._session.client('cloudformation').delete_stack( - # StackName=BOOTSTRAP_STACK_NAME - # ) - - @property - def stacks(self): - return self._stacks diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/aws_client_auth_automation_test.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/aws_client_auth_automation_test.py index bdd1eea469..b56d3f88f5 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/aws_client_auth_automation_test.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/aws_client_auth_automation_test.py @@ -4,45 +4,42 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import pytest -import os + import logging +import os +import pytest + import ly_test_tools.log.log_monitor +from AWS.common import constants + # fixture imports from assetpipeline.ap_fixtures.asset_processor_fixture import asset_processor -AWS_PROJECT_NAME = 'AWS-AutomationTest' AWS_CLIENT_AUTH_FEATURE_NAME = 'AWSClientAuth' -AWS_CLIENT_AUTH_DEFAULT_PROFILE_NAME = 'default' - -GAME_LOG_NAME = 'Game.log' logger = logging.getLogger(__name__) @pytest.mark.SUITE_periodic -@pytest.mark.usefixtures('automatic_process_killer') @pytest.mark.usefixtures('asset_processor') -@pytest.mark.usefixtures('workspace') -@pytest.mark.parametrize('project', ['AutomatedTesting']) -@pytest.mark.usefixtures('cdk') -@pytest.mark.parametrize('feature_name', [AWS_CLIENT_AUTH_FEATURE_NAME]) -@pytest.mark.usefixtures('resource_mappings') -@pytest.mark.parametrize('resource_mappings_filename', ['default_aws_resource_mappings.json']) +@pytest.mark.usefixtures('automatic_process_killer') @pytest.mark.usefixtures('aws_utils') -@pytest.mark.parametrize('region_name', ['us-west-2']) -@pytest.mark.parametrize('assume_role_arn', ['arn:aws:iam::645075835648:role/o3de-automation-tests']) -@pytest.mark.parametrize('session_name', ['o3de-Automation-session']) -@pytest.mark.usefixtures('cdk') -@pytest.mark.parametrize('deployment_params', [[]]) +@pytest.mark.usefixtures('workspace') +@pytest.mark.parametrize('assume_role_arn', [constants.ASSUME_ROLE_ARN]) +@pytest.mark.parametrize('feature_name', [AWS_CLIENT_AUTH_FEATURE_NAME]) +@pytest.mark.parametrize('project', ['AutomatedTesting']) +@pytest.mark.usefixtures('resource_mappings') +@pytest.mark.parametrize('resource_mappings_filename', [constants.AWS_RESOURCE_MAPPING_FILE_NAME]) +@pytest.mark.parametrize('region_name', [constants.AWS_REGION]) +@pytest.mark.parametrize('session_name', [constants.SESSION_NAME]) +@pytest.mark.parametrize('stacks', [[f'{constants.AWS_PROJECT_NAME}-{AWS_CLIENT_AUTH_FEATURE_NAME}-Stack-{constants.AWS_REGION}']]) class TestAWSClientAuthWindows(object): """ Test class to verify AWS Client Auth gem features on Windows. """ @pytest.mark.parametrize('level', ['AWS/ClientAuth']) - @pytest.mark.parametrize('destroy_stacks_on_teardown', [False]) def test_anonymous_credentials(self, level: str, launcher: pytest.fixture, @@ -53,14 +50,14 @@ class TestAWSClientAuthWindows(object): """ Test to verify AWS Cognito Identity pool anonymous authorization. - Setup: Deploys cdk and updates resource mapping file. + Setup: Updates resource mapping file using existing CloudFormation stacks. Tests: Getting credentials when no credentials are configured Verification: Log monitor looks for success credentials log. """ asset_processor.start() asset_processor.wait_for_idle() - file_to_monitor = os.path.join(launcher.workspace.paths.project_log(), GAME_LOG_NAME) + file_to_monitor = os.path.join(launcher.workspace.paths.project_log(), constants.GAME_LOG_NAME) log_monitor = ly_test_tools.log.log_monitor.LogMonitor(launcher=launcher, log_file_path=file_to_monitor) launcher.args = ['+LoadLevel', level] @@ -74,10 +71,8 @@ class TestAWSClientAuthWindows(object): ) assert result, 'Anonymous credentials fetched successfully.' - @pytest.mark.parametrize('destroy_stacks_on_teardown', [True]) def test_password_signin_credentials(self, launcher: pytest.fixture, - cdk: pytest.fixture, resource_mappings: pytest.fixture, workspace: pytest.fixture, asset_processor: pytest.fixture, @@ -86,16 +81,29 @@ class TestAWSClientAuthWindows(object): """ Test to verify AWS Cognito IDP Password sign in and Cognito Identity pool authenticated authorization. - Setup: Deploys cdk and updates resource mapping file. + Setup: Updates resource mapping file using existing CloudFormation stacks. Tests: Sign up new test user, admin confirm the user, sign in and get aws credentials. Verification: Log monitor looks for success credentials log. """ asset_processor.start() asset_processor.wait_for_idle() - file_to_monitor = os.path.join(launcher.workspace.paths.project_log(), GAME_LOG_NAME) + file_to_monitor = os.path.join(launcher.workspace.paths.project_log(), constants.GAME_LOG_NAME) log_monitor = ly_test_tools.log.log_monitor.LogMonitor(launcher=launcher, log_file_path=file_to_monitor) + cognito_idp = aws_utils.client('cognito-idp') + user_pool_id = resource_mappings.get_resource_name_id(f'{AWS_CLIENT_AUTH_FEATURE_NAME}.CognitoUserPoolId') + logger.info(f'UserPoolId:{user_pool_id}') + + # Remove the user if already exists + try: + cognito_idp.admin_delete_user( + UserPoolId=user_pool_id, + Username='test1' + ) + except cognito_idp.exceptions.UserNotFoundException: + pass + launcher.args = ['+LoadLevel', 'AWS/ClientAuthPasswordSignUp'] launcher.args.extend(['-rhi=null']) @@ -109,9 +117,6 @@ class TestAWSClientAuthWindows(object): launcher.stop() - cognito_idp = aws_utils.client('cognito-idp') - user_pool_id = resource_mappings.get_resource_name_id(f'{AWS_CLIENT_AUTH_FEATURE_NAME}.CognitoUserPoolId') - print(f'UserPoolId:{user_pool_id}') cognito_idp.admin_confirm_sign_up( UserPoolId=user_pool_id, Username='test1' diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/core/test_aws_resource_interaction.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/core/test_aws_resource_interaction.py index 55f06660e8..529151f3f6 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/core/test_aws_resource_interaction.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/core/test_aws_resource_interaction.py @@ -5,10 +5,11 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os import logging -import typing +import os import shutil +import typing +from botocore.exceptions import ClientError import pytest import ly_test_tools @@ -16,16 +17,15 @@ import ly_test_tools.log.log_monitor import ly_test_tools.environment.process_utils as process_utils import ly_test_tools.o3de.asset_processor_utils as asset_processor_utils -from botocore.exceptions import ClientError +from AWS.common import constants + +# fixture imports from assetpipeline.ap_fixtures.asset_processor_fixture import asset_processor AWS_CORE_FEATURE_NAME = 'AWSCore' -AWS_RESOURCE_MAPPING_FILE_NAME = 'default_aws_resource_mappings.json' process_utils.kill_processes_named("o3de", ignore_extensions=True) # Kill ProjectManager windows -GAME_LOG_NAME = 'Game.log' - logger = logging.getLogger(__name__) @@ -46,7 +46,7 @@ def setup(launcher: pytest.fixture, asset_processor: pytest.fixture) -> typing.T asset_processor.start() asset_processor.wait_for_idle() - file_to_monitor = os.path.join(launcher.workspace.paths.project_log(), GAME_LOG_NAME) + file_to_monitor = os.path.join(launcher.workspace.paths.project_log(), constants.GAME_LOG_NAME) log_monitor = ly_test_tools.log.log_monitor.LogMonitor(launcher=launcher, log_file_path=file_to_monitor) return log_monitor, s3_download_dir @@ -58,7 +58,7 @@ def write_test_data_to_dynamodb_table(resource_mappings: pytest.fixture, aws_uti :param resource_mappings: resource_mappings fixture. :param aws_utils: aws_utils fixture. """ - table_name = resource_mappings.get_resource_name_id("AWSCore.ExampleDynamoTableOutput") + table_name = resource_mappings.get_resource_name_id(f'{AWS_CORE_FEATURE_NAME}.ExampleDynamoTableOutput') try: aws_utils.client('dynamodb').put_item( TableName=table_name, @@ -77,21 +77,19 @@ def write_test_data_to_dynamodb_table(resource_mappings: pytest.fixture, aws_uti @pytest.mark.SUITE_periodic @pytest.mark.usefixtures('automatic_process_killer') @pytest.mark.usefixtures('asset_processor') -@pytest.mark.usefixtures('cdk') @pytest.mark.parametrize('feature_name', [AWS_CORE_FEATURE_NAME]) -@pytest.mark.parametrize('region_name', ['us-west-2']) -@pytest.mark.parametrize('assume_role_arn', ['arn:aws:iam::645075835648:role/o3de-automation-tests']) -@pytest.mark.parametrize('session_name', ['o3de-Automation-session']) +@pytest.mark.parametrize('region_name', [constants.AWS_REGION]) +@pytest.mark.parametrize('assume_role_arn', [constants.ASSUME_ROLE_ARN]) +@pytest.mark.parametrize('session_name', [constants.SESSION_NAME]) @pytest.mark.usefixtures('workspace') @pytest.mark.parametrize('project', ['AutomatedTesting']) @pytest.mark.parametrize('level', ['AWS/Core']) @pytest.mark.usefixtures('resource_mappings') -@pytest.mark.parametrize('resource_mappings_filename', [AWS_RESOURCE_MAPPING_FILE_NAME]) +@pytest.mark.parametrize('resource_mappings_filename', [constants.AWS_RESOURCE_MAPPING_FILE_NAME]) +@pytest.mark.parametrize('stacks', [[f'{constants.AWS_PROJECT_NAME}-{AWS_CORE_FEATURE_NAME}', + f'{constants.AWS_PROJECT_NAME}-{AWS_CORE_FEATURE_NAME}-Example-{constants.AWS_REGION}']]) @pytest.mark.usefixtures('aws_credentials') @pytest.mark.parametrize('profile_name', ['AWSAutomationTest']) -@pytest.mark.usefixtures('cdk') -@pytest.mark.parametrize('deployment_params', [['--all']]) -@pytest.mark.parametrize('destroy_stacks_on_teardown', [True]) class TestAWSCoreAWSResourceInteraction(object): """ Test class to verify the scripting behavior for the AWSCore gem. @@ -119,7 +117,7 @@ class TestAWSCoreAWSResourceInteraction(object): expected_lines: typing.List[str], unexpected_lines: typing.List[str]): """ - Setup: Deploys cdk and updates resource mapping file. + Setup: Updates resource mapping file using existing CloudFormation stacks. Tests: Interact with AWS S3, DynamoDB and Lambda services. Verification: Script canvas nodes can communicate with AWS services successfully. """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/__init__.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/__init__.py deleted file mode 100644 index e01850f919..0000000000 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/__init__.py +++ /dev/null @@ -1,6 +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 -""" \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/AWS/common/constants.py b/AutomatedTesting/Gem/PythonTests/AWS/common/constants.py new file mode 100644 index 0000000000..be143547a7 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/AWS/common/constants.py @@ -0,0 +1,19 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# ARN of the IAM role to assume for retrieving temporary AWS credentials +ASSUME_ROLE_ARN = 'arn:aws:iam::645075835648:role/o3de-automation-tests' +# Name of the AWS project deployed by the CDK applications +AWS_PROJECT_NAME = 'AWSAUTO' +# Region for the existing CloudFormation stacks used by the automation tests +AWS_REGION = 'us-east-1' +# Name of the default resource mapping config file used by the automation tests +AWS_RESOURCE_MAPPING_FILE_NAME = 'default_aws_resource_mappings.json' +# Name of the game launcher log +GAME_LOG_NAME = 'Game.log' +# Name of the IAM role session for retrieving temporary AWS credentials +SESSION_NAME = 'o3de-Automation-session' diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/resource_mappings.py b/AutomatedTesting/Gem/PythonTests/AWS/common/resource_mappings.py similarity index 90% rename from AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/resource_mappings.py rename to AutomatedTesting/Gem/PythonTests/AWS/common/resource_mappings.py index fd679de99d..5f01ecdbf8 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/resource_mappings.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/common/resource_mappings.py @@ -6,9 +6,9 @@ SPDX-License-Identifier: Apache-2.0 OR MIT """ import os -import pytest import json import logging +from AWS.common import constants logger = logging.getLogger(__name__) @@ -22,18 +22,14 @@ class ResourceMappings: ResourceMappings class that handles writing Cloud formation outputs to resource mappings json file in a project. """ - def __init__(self, file_path: str, region: str, feature_name: str, account_id: str, workspace: pytest.fixture, - cloud_formation_client): + def __init__(self, file_path: str, region: str, feature_name: str, account_id: str, cloud_formation_client): """ :param file_path: Path for the resource mapping file. :param region: Region value for the resource mapping file. :param feature_name: Feature gem name to use to append name to mappings key. :param account_id: AWS account id value for the resource mapping file. - :param workspace: ly_test_tools workspace fixture. :param cloud_formation_client: AWS cloud formation client. """ - self._cdk_env = os.environ.copy() - self._cdk_env['PATH'] = f'{workspace.paths.engine_root()}\\python;' + self._cdk_env['PATH'] self._resource_mapping_file_path = file_path self._region = region self._feature_name = feature_name @@ -44,7 +40,7 @@ class ResourceMappings: f'Invalid resource mapping file path {self._resource_mapping_file_path}' self._client = cloud_formation_client - def populate_output_keys(self, stacks=[]) -> None: + def populate_output_keys(self, stacks=None) -> None: """ Calls describe stacks on cloud formation service and persists outputs to resource mappings file. :param stacks List of stack arns to describe and populate resource mappings with. @@ -58,7 +54,7 @@ class ResourceMappings: self._write_resource_mappings(stacks[0].get('Outputs', [])) - def _write_resource_mappings(self, outputs, append_feature_name = True) -> None: + def _write_resource_mappings(self, outputs, append_feature_name=True) -> None: with open(self._resource_mapping_file_path) as file_content: resource_mappings = json.load(file_content) @@ -91,7 +87,7 @@ class ResourceMappings: resource_mappings = json.load(file_content) resource_mappings[AWS_RESOURCE_MAPPINGS_ACCOUNT_ID_KEY] = '' - resource_mappings[AWS_RESOURCE_MAPPINGS_REGION_KEY] = 'us-west-2' + resource_mappings[AWS_RESOURCE_MAPPINGS_REGION_KEY] = constants.AWS_REGION # Append new mappings. resource_mappings[AWS_RESOURCE_MAPPINGS_KEY] = resource_mappings.get(AWS_RESOURCE_MAPPINGS_KEY, {}) diff --git a/AutomatedTesting/Gem/PythonTests/AWS/conftest.py b/AutomatedTesting/Gem/PythonTests/AWS/conftest.py index 6ad495ab66..df65aa7a5c 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/conftest.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/conftest.py @@ -11,8 +11,7 @@ import typing from AWS.common.aws_utils import AwsUtils from AWS.common.aws_credentials import AwsCredentials -from AWS.Windows.cdk.cdk_utils import Cdk -from AWS.Windows.resource_mappings.resource_mappings import ResourceMappings +from AWS.common.resource_mappings import ResourceMappings logger = logging.getLogger(__name__) @@ -52,6 +51,7 @@ def resource_mappings( project: str, feature_name: str, resource_mappings_filename: str, + stacks: typing.List, workspace: pytest.fixture, aws_utils: pytest.fixture) -> ResourceMappings: """ @@ -61,6 +61,7 @@ def resource_mappings( :param project: Project to find resource mapping file. :param feature_name: AWS Gem name that is prepended to resource mapping keys. :param resource_mappings_filename: Name of resource mapping file. + :param stacks: List of stack names to describe and populate resource mappings with. :param workspace: ly_test_tools workspace fixture. :param aws_utils: AWS utils fixture. :return: ResourceMappings class object. @@ -70,8 +71,8 @@ def resource_mappings( logger.info(f'Resource mapping path : {path}') logger.info(f'Resource mapping resolved path : {abspath(path)}') resource_mappings_obj = ResourceMappings(abspath(path), aws_utils.assume_session().region_name, feature_name, - aws_utils.assume_account_id(), workspace, - aws_utils.client('cloudformation')) + aws_utils.assume_account_id(), aws_utils.client('cloudformation')) + resource_mappings_obj.populate_output_keys(stacks) def teardown(): resource_mappings_obj.clear_output_keys() @@ -81,56 +82,6 @@ def resource_mappings( return resource_mappings_obj -@pytest.fixture(scope='function') -def cdk( - request: pytest.fixture, - project: str, - feature_name: str, - workspace: pytest.fixture, - aws_utils: pytest.fixture, - resource_mappings: pytest.fixture, - deployment_params: typing.List[str], - destroy_stacks_on_teardown: bool) -> Cdk: - """ - Fixture for setting up a Cdk - :param request: _pytest.fixtures.SubRequest class that handles getting - a pytest fixture from a pytest function/fixture. - :param project: Project name used for cdk project name env variable. - :param feature_name: Feature gem name to expect cdk folder in. - :param workspace: ly_test_tools workspace fixture. - :param aws_utils: aws_utils fixture. - :param resource_mappings: resource_mappings fixture. - :param deployment_params: Parameters for the CDK application deployment. - :param destroy_stacks_on_teardown: option to control calling destroy ot the end of test. - :return Cdk class object. - """ - - cdk_path = f'{workspace.paths.engine_root()}/Gems/{feature_name}/cdk' - logger.info(f'CDK Path {cdk_path}') - - if pytest.cdk_obj is None: - pytest.cdk_obj = Cdk() - pytest.cdk_obj.setup(cdk_path, project, aws_utils.assume_account_id(), workspace, aws_utils.assume_session()) - - stacks = pytest.cdk_obj.deploy(deployment_params=deployment_params) - - logger.info(f'Cdk stack names:\n{stacks}') - resource_mappings.populate_output_keys(stacks) - - def teardown(): - if destroy_stacks_on_teardown: - pytest.cdk_obj.destroy(deployment_params=deployment_params) - # Enable after https://github.com/aws/aws-cdk/issues/986 is fixed. - # Until then clean the bootstrap bucket manually. - # pytest.cdk_obj.remove_bootstrap_stack() - - pytest.cdk_obj = None - - request.addfinalizer(teardown) - - return pytest.cdk_obj - - @pytest.fixture(scope='function') def aws_credentials(request: pytest.fixture, aws_utils: pytest.fixture, profile_name: str): """ diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py index a543527ed7..ff362c732c 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py @@ -342,7 +342,7 @@ def bundler_batch_setup_fixture(request, workspace, asset_processor, timeout) -> # Run a full scan to ENSURE that both caches (pc and osx) are COMPLETELY POPULATED # Needed for asset bundling # fmt:off - assert asset_processor.batch_process(fastscan=False, timeout=timeout * len(platforms), platforms=platforms_list), \ + assert asset_processor.batch_process(fastscan=True, timeout=timeout * len(platforms), platforms=platforms_list), \ "AP Batch failed to process in bundler_batch_fixture" # fmt:on diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt index 3d7a9204e2..5a5809595e 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt @@ -92,25 +92,12 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AssetProcessor ) - # Issue #3017 - #ly_add_pytest( - # NAME AssetPipelineTests.AssetBundler - # PATH ${CMAKE_CURRENT_LIST_DIR}/asset_bundler_batch_tests.py - # EXCLUDE_TEST_RUN_TARGET_FROM_IDE - # TEST_SERIAL - # TEST_SUITE periodic - # RUNTIME_DEPENDENCIES - # AZ::AssetProcessor - # AZ::AssetBundlerBatch - #) - ly_add_pytest( - NAME AssetPipelineTests.AssetBundler_SandBox - TEST_SUITE sandbox + NAME AssetPipelineTests.AssetBundler PATH ${CMAKE_CURRENT_LIST_DIR}/asset_bundler_batch_tests.py - PYTEST_MARKS "SUITE_sandbox" # run only sandbox tests in this file EXCLUDE_TEST_RUN_TARGET_FROM_IDE TEST_SERIAL + TEST_SUITE periodic RUNTIME_DEPENDENCIES AZ::AssetProcessor AZ::AssetBundlerBatch diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt index 043485d869..f133780fbc 100644 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt @@ -130,8 +130,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ NAME AutomatedTesting::LandscapeCanvasTests_Main TEST_SERIAL TEST_SUITE main - PATH ${CMAKE_CURRENT_LIST_DIR}/landscape_canvas - PYTEST_MARKS "not SUITE_sandbox and not SUITE_periodic and not SUITE_benchmark" + PATH ${CMAKE_CURRENT_LIST_DIR}/landscape_canvas/test_LandscapeCanvas_Main.py RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -144,8 +143,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ NAME AutomatedTesting::LandscapeCanvasTests_Periodic TEST_SERIAL TEST_SUITE periodic - PATH ${CMAKE_CURRENT_LIST_DIR}/landscape_canvas - PYTEST_MARKS "SUITE_periodic" + PATH ${CMAKE_CURRENT_LIST_DIR}/landscape_canvas/test_LandscapeCanvas_Periodic.py RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor @@ -159,7 +157,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ NAME AutomatedTesting::GradientSignalTests_Periodic TEST_SERIAL TEST_SUITE periodic - PATH ${CMAKE_CURRENT_LIST_DIR}/gradient_signal + PATH ${CMAKE_CURRENT_LIST_DIR}/gradient_signal/test_GradientSignal_Periodic.py RUNTIME_DEPENDENCIES AZ::AssetProcessor Legacy::Editor diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py index beb5c2af72..2052c59a94 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py @@ -10,6 +10,7 @@ import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) import azlmbr.asset as asset +import azlmbr.editor as editor import azlmbr.legacy.general as general import azlmbr.bus as bus import azlmbr.math as math @@ -107,7 +108,7 @@ class TestPhysXColliderSurfaceTagEmitter(EditorTestHelper): # Create an entity with a PhysX Collider and our PhysX Collider Surface Tag Emitter collider_entity = hydra.Entity("Collider Surface") collider_entity.create_entity( - entity_center_point, + entity_center_point, ["PhysX Collider", "PhysX Collider Surface Tag Emitter"] ) if collider_entity.id.IsValid(): @@ -153,23 +154,29 @@ class TestPhysXColliderSurfaceTagEmitter(EditorTestHelper): self.test_success = self.test_success and baseline_success # Setup collider entity with a PhysX Mesh - test_physx_mesh_asset_path = asset.AssetCatalogRequestBus( + test_physx_mesh_asset_id = asset.AssetCatalogRequestBus( bus.Broadcast, "GetAssetIdByPath", os.path.join("levels", "physics", "c4044697_material_perfacematerialvalidation", "test.pxmesh"), math.Uuid(), False) - hydra.get_set_test(collider_entity, 0, "Shape Configuration|Shape", 7) - hydra.get_set_test(collider_entity, 0, "Shape Configuration|Asset|PhysX Mesh", test_physx_mesh_asset_path) + + # Remove/re-add component due to LYN-5496 + collider_entity.remove_component("PhysX Collider") + collider_entity.add_component("PhysX Collider") + self.wait_for_condition(lambda: editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', + collider_entity.components[1]), 5.0) + hydra.get_set_test(collider_entity, 1, "Shape Configuration|Shape", 7) + hydra.get_set_test(collider_entity, 1, "Shape Configuration|Asset|PhysX Mesh", test_physx_mesh_asset_id) # Set the asset scale to match the test heights of the shapes tested asset_scale = math.Vector3(1.0, 1.0, 9.0) - collider_entity.get_set_test(0, "Shape Configuration|Asset|Configuration|Asset Scale", asset_scale) + collider_entity.get_set_test(1, "Shape Configuration|Asset|Configuration|Asset Scale", asset_scale) # Test: Generate a new surface on the collider. # There should be one instance at the very top of the collider mesh, and none on the baseline surface # (We use a small query box to only check for one placed instance point) self.log("Starting PhysX Mesh Collider Test") - hydra.get_set_test(collider_entity, 1, "Configuration|Generated Tags", [surface_tag]) - hydra.get_set_test(collider_entity, 1, "Configuration|Extended Tags", [invalid_tag]) + hydra.get_set_test(collider_entity, 0, "Configuration|Generated Tags", [surface_tag]) + hydra.get_set_test(collider_entity, 0, "Configuration|Extended Tags", [invalid_tag]) top_point_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, 0.25, 1), 5.0) self.test_success = self.test_success and top_point_success baseline_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(baseline_surface_point, @@ -180,8 +187,8 @@ class TestPhysXColliderSurfaceTagEmitter(EditorTestHelper): # There should be no instances at the very top of the collider mesh, and none on the baseline surface within # our query box as PhysX meshes are treated as hollow shells, not solid volumes. # (We use a small query box to only check for one placed instance point) - hydra.get_set_test(collider_entity, 1, "Configuration|Generated Tags", [invalid_tag]) - hydra.get_set_test(collider_entity, 1, "Configuration|Extended Tags", [surface_tag]) + hydra.get_set_test(collider_entity, 0, "Configuration|Generated Tags", [invalid_tag]) + hydra.get_set_test(collider_entity, 0, "Configuration|Extended Tags", [surface_tag]) top_point_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(top_point, 0.25, 0), 5.0) self.test_success = self.test_success and top_point_success baseline_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(baseline_surface_point, diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py index 37679d34ef..09cd760647 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py @@ -4,124 +4,118 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys - -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.entity as entity -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -class TestGradientGeneratorIncompatibilities(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientGeneratorIncompatibilities", args=["level"]) +def GradientGenerators_Incompatibilities(): + """ + Summary: + This test verifies that components are disabled when conflicting components are present on the same entity. - def run_test(self): - """ - Summary: - This test verifies that components are disabled when conflicting components are present on the same entity. + Expected Behavior: + Gradient Generator components are incompatible with Vegetation area components. - Expected Behavior: - Gradient Generator components are incompatible with Vegetation area components. + Test Steps: + 1) Open a simple level + 2) Create a new entity in the level + 3) Add each Gradient Generator component to an entity, and add a Vegetation Area component to the same entity + 4) Verify that components are only enabled when entity is free of a conflicting component - Test Steps: - 1) Create a new level - 2) Create a new entity in the level - 3) Add each Gradient Generator component to an entity, and add a Vegetation Area component to the same entity - 4) Verify that components are only enabled when entity is free of a conflicting component + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.entity as entity - gradient_generators = [ - 'Altitude Gradient', - 'Constant Gradient', - 'FastNoise Gradient', - 'Image Gradient', - 'Perlin Noise Gradient', - 'Random Noise Gradient', - 'Shape Falloff Gradient', - 'Slope Gradient', - 'Surface Mask Gradient' - ] - require_transform_modifiers = [ - 'FastNoise Gradient', - 'Image Gradient', - 'Perlin Noise Gradient', - 'Random Noise Gradient' - ] - vegetation_areas = [ - 'Vegetation Layer Spawner', - 'Vegetation Layer Blender', - 'Vegetation Layer Blocker', - 'Vegetation Layer Blocker (Mesh)' - ] - area_dependencies = { - 'Vegetation Layer Spawner': 'Vegetation Asset List', - 'Vegetation Layer Blocker (Mesh)': 'Mesh' - } + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + gradient_generators = [ + 'Altitude Gradient', + 'Constant Gradient', + 'FastNoise Gradient', + 'Image Gradient', + 'Perlin Noise Gradient', + 'Random Noise Gradient', + 'Shape Falloff Gradient', + 'Slope Gradient', + 'Surface Mask Gradient' + ] + require_transform_modifiers = [ + 'FastNoise Gradient', + 'Image Gradient', + 'Perlin Noise Gradient', + 'Random Noise Gradient' + ] + vegetation_areas = [ + 'Vegetation Layer Spawner', + 'Vegetation Layer Blender', + 'Vegetation Layer Blocker', + 'Vegetation Layer Blocker (Mesh)' + ] + area_dependencies = { + 'Vegetation Layer Spawner': 'Vegetation Asset List', + 'Vegetation Layer Blocker (Mesh)': 'Mesh' + } - # For every gradient generator component, verify that they are incompatible - # which each vegetation area component - for component_name in gradient_generators: - for vegetation_area_name in vegetation_areas: - # Create a new Entity in the level - entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Most of these need a shape, so use a Box Shape - hydra.add_component('Box Shape', entity_id) + # For every gradient generator component, verify that they are incompatible + # which each vegetation area component + for component_name in gradient_generators: + for vegetation_area_name in vegetation_areas: + # Create a new Entity in the level + entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) - # Add the specific vegetation area dependencies (if necessary) - if vegetation_area_name in area_dependencies: - hydra.add_component(area_dependencies[vegetation_area_name], entity_id) + # Most of these need a shape, so use a Box Shape + hydra.add_component('Box Shape', entity_id) - # Add the vegetation area component we are validating against, then add the - # gradient generator afterwards, so that the gradient generator will actually - # be disabled (if it was present before, it would only get deactivated instead of disabled - # by the vegetation area) - area_component = hydra.add_component(vegetation_area_name, entity_id) - gradient_component = hydra.add_component(component_name, entity_id) + # Add the specific vegetation area dependencies (if necessary) + if vegetation_area_name in area_dependencies: + hydra.add_component(area_dependencies[vegetation_area_name], entity_id) - # Verify the gradient generator component is disabled since the vegetation area is incompatible - active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) - self.test_success = self.test_success and not active - if not active: - self.log(f"{component_name} is disabled before removing {vegetation_area_name} component") + # Add the vegetation area component we are validating against, then add the + # gradient generator afterwards, so that the gradient generator will actually + # be disabled (if it was present before, it would only get deactivated instead of disabled + # by the vegetation area) + area_component = hydra.add_component(vegetation_area_name, entity_id) + gradient_component = hydra.add_component(component_name, entity_id) - # Remove the vegetation area component - editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', [area_component]) + # Verify the gradient generator component is disabled since the vegetation area is incompatible + active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) + component_is_disabled = ( + f"{component_name} is disabled before removing {vegetation_area_name} component", + f"{component_name} is unexpectedly enabled before removing {vegetation_area_name} component" + ) + Report.result(component_is_disabled, not active) - # Add required dependencies for our gradient generators after the vegetation - # area has been removed, because the transform modifier is also incompatible - # with the vegetation areas - if component_name in require_transform_modifiers: - hydra.add_component('Gradient Transform Modifier', entity_id) + # Remove the vegetation area component + editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', [area_component]) - # Verify the gradient generator component is enabled now that the vegetation area is gone - active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) - self.test_success = self.test_success and active - if active: - self.log(f"{component_name} is enabled after removing {vegetation_area_name} component") + # Add required dependencies for our gradient generators after the vegetation + # area has been removed, because the transform modifier is also incompatible + # with the vegetation areas + if component_name in require_transform_modifiers: + hydra.add_component('Gradient Transform Modifier', entity_id) + + # Verify the gradient generator component is enabled now that the vegetation area is gone + active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) + component_is_enabled = ( + f"{component_name} is enabled after removing {vegetation_area_name} component", + f"{component_name} is unexpectedly disabled after removing {vegetation_area_name} component" + ) + Report.result(component_is_enabled, active) -test = TestGradientGeneratorIncompatibilities() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientGenerators_Incompatibilities) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py index 8908493187..a4d9181744 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py @@ -4,164 +4,162 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys - -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.entity as entity -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -class TestGradientModifiersIncompatibilities(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientModifiersIncompatibilities", args=["level"]) +def GradientModifiers_Incompatibilities(): + """ + Summary: + This test verifies that components are disabled when conflicting components are present on the same entity. - def run_test(self): - """ - Summary: - This test verifies that components are disabled when conflicting components are present on the same entity. + Expected Behavior: + Gradient Modifier components are incompatible with Vegetation area components. - Expected Behavior: - Gradient Modifier components are incompatible with Vegetation area components. + Test Steps: + 1) Open a simple level + 2) Create a new entity in the level + 3) Add each Gradient Modifier component to an entity, and add a Vegetation Area component to the same entity + 4) Verify that components are only enabled when entity is free of a conflicting component - Test Steps: - 1) Create a new level - 2) Create a new entity in the level - 3) Add each Gradient Modifier component to an entity, and add a Vegetation Area component to the same entity - 4) Verify that components are only enabled when entity is free of a conflicting component + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.entity as entity - gradient_generators = [ - 'Altitude Gradient', - 'Constant Gradient', - 'FastNoise Gradient', - 'Image Gradient', - 'Perlin Noise Gradient', - 'Random Noise Gradient', - 'Shape Falloff Gradient', - 'Slope Gradient', - 'Surface Mask Gradient' - ] - require_transform_modifiers = [ - 'FastNoise Gradient', - 'Image Gradient', - 'Perlin Noise Gradient', - 'Random Noise Gradient' - ] - gradient_modifiers = [ - 'Dither Gradient Modifier', - 'Gradient Mixer', - 'Invert Gradient Modifier', - 'Levels Gradient Modifier', - 'Posterize Gradient Modifier', - 'Smooth-Step Gradient Modifier', - 'Threshold Gradient Modifier' - ] - vegetation_areas = [ - 'Vegetation Layer Spawner', - 'Vegetation Layer Blender', - 'Vegetation Layer Blocker', - 'Vegetation Layer Blocker (Mesh)' - ] - area_dependencies = { - 'Vegetation Layer Spawner': 'Vegetation Asset List', - 'Vegetation Layer Blocker (Mesh)': 'Mesh' - } + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + gradient_generators = [ + 'Altitude Gradient', + 'Constant Gradient', + 'FastNoise Gradient', + 'Image Gradient', + 'Perlin Noise Gradient', + 'Random Noise Gradient', + 'Shape Falloff Gradient', + 'Slope Gradient', + 'Surface Mask Gradient' + ] + require_transform_modifiers = [ + 'FastNoise Gradient', + 'Image Gradient', + 'Perlin Noise Gradient', + 'Random Noise Gradient' + ] + gradient_modifiers = [ + 'Dither Gradient Modifier', + 'Gradient Mixer', + 'Invert Gradient Modifier', + 'Levels Gradient Modifier', + 'Posterize Gradient Modifier', + 'Smooth-Step Gradient Modifier', + 'Threshold Gradient Modifier' + ] + vegetation_areas = [ + 'Vegetation Layer Spawner', + 'Vegetation Layer Blender', + 'Vegetation Layer Blocker', + 'Vegetation Layer Blocker (Mesh)' + ] + area_dependencies = { + 'Vegetation Layer Spawner': 'Vegetation Asset List', + 'Vegetation Layer Blocker (Mesh)': 'Mesh' + } - # For every gradient modifier component, verify that they are incompatible - # which each vegetation area and gradient generator/modifier component - all_gradients = gradient_modifiers + gradient_generators - for component_name in gradient_modifiers: - for vegetation_area_name in vegetation_areas: - # Create a new Entity in the level - entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Most of these need a shape, so use a Box Shape - hydra.add_component('Box Shape', entity_id) + # For every gradient modifier component, verify that they are incompatible + # which each vegetation area and gradient generator/modifier component + all_gradients = gradient_modifiers + gradient_generators + for component_name in gradient_modifiers: + for vegetation_area_name in vegetation_areas: + # Create a new Entity in the level + entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) - # Add the specific vegetation area dependencies (if necessary) - if vegetation_area_name in area_dependencies: - hydra.add_component(area_dependencies[vegetation_area_name], entity_id) + # Most of these need a shape, so use a Box Shape + hydra.add_component('Box Shape', entity_id) - # Add the vegetation area component we are validating against, then add the - # gradient modifier afterwards, so that the gradient modifier will actually - # be disabled (if it was present before, it would only get deactivated instead of disabled - # by the vegetation area) - area_component = hydra.add_component(vegetation_area_name, entity_id) - gradient_component = hydra.add_component(component_name, entity_id) + # Add the specific vegetation area dependencies (if necessary) + if vegetation_area_name in area_dependencies: + hydra.add_component(area_dependencies[vegetation_area_name], entity_id) - # Verify the gradient modifier component is disabled since the vegetation area is incompatible - active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) - self.test_success = self.test_success and not active - if not active: - self.log("{gradient} is disabled before removing {vegetation_area} component".format(gradient=component_name, vegetation_area=vegetation_area_name)) + # Add the vegetation area component we are validating against, then add the + # gradient modifier afterwards, so that the gradient modifier will actually + # be disabled (if it was present before, it would only get deactivated instead of disabled + # by the vegetation area) + area_component = hydra.add_component(vegetation_area_name, entity_id) + gradient_component = hydra.add_component(component_name, entity_id) - # Remove the vegetation area component - editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', [area_component]) + # Verify the gradient modifier component is disabled since the vegetation area is incompatible + active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) + component_is_disabled = ( + f"{component_name} is disabled before removing {vegetation_area_name} component", + f"{component_name} is unexpectedly enabled before removing {vegetation_area_name} component" + ) + Report.result(component_is_disabled, not active) - # Verify the gradient modifier component is enabled now that the vegetation area is gone - active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) - self.test_success = self.test_success and active - if active: - self.log("{gradient} is enabled after removing {vegetation_area} component".format(gradient=component_name, vegetation_area=vegetation_area_name)) + # Remove the vegetation area component + editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', [area_component]) - for gradient_name in all_gradients: - # Create a new Entity in the level - entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) + # Verify the gradient modifier component is enabled now that the vegetation area is gone + active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) + component_is_enabled = ( + f"{component_name} is enabled after removing {vegetation_area_name} component", + f"{component_name} is unexpectedly disabled after removing {vegetation_area_name} component" + ) + Report.result(component_is_enabled, active) - # Most of these need a shape, so use a Box Shape - hydra.add_component('Box Shape', entity_id) + for gradient_name in all_gradients: + # Create a new Entity in the level + entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) - # Add the specific gradient generator dependencies (if necessary) - conflicting_components = [] - if gradient_name in require_transform_modifiers: - component = hydra.add_component('Gradient Transform Modifier', entity_id) - conflicting_components.append(component) + # Most of these need a shape, so use a Box Shape + hydra.add_component('Box Shape', entity_id) - # Add the gradient component we are validating against, then add the - # gradient modifier afterwards, so that the gradient modifier will actually - # be disabled (if it was present before, it would only get deactivated instead of disabled - # by the other gradient) - component = hydra.add_component(gradient_name, entity_id) + # Add the specific gradient generator dependencies (if necessary) + conflicting_components = [] + if gradient_name in require_transform_modifiers: + component = hydra.add_component('Gradient Transform Modifier', entity_id) conflicting_components.append(component) - gradient_component = hydra.add_component(component_name, entity_id) - # Verify the gradient modifier component is disabled since the other gradient is incompatible - active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) - self.test_success = self.test_success and not active - if not active: - self.log("{gradient} is disabled before removing {conflicting_gradient} component".format(gradient=component_name, conflicting_gradient=gradient_name)) + # Add the gradient component we are validating against, then add the + # gradient modifier afterwards, so that the gradient modifier will actually + # be disabled (if it was present before, it would only get deactivated instead of disabled + # by the other gradient) + component = hydra.add_component(gradient_name, entity_id) + conflicting_components.append(component) + gradient_component = hydra.add_component(component_name, entity_id) - # Remove the conflicting gradient component (and transform modifier if it was added) - editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', conflicting_components) + # Verify the gradient modifier component is disabled since the other gradient is incompatible + active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) + component_is_disabled = ( + f"{component_name} is disabled before removing {gradient_name} component", + f"{component_name} is unexpectedly enabled before removing {gradient_name} component" + ) + Report.result(component_is_disabled, not active) - # Verify the gradient modifier component is enabled now that the other gradient is gone - active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) - self.test_success = self.test_success and active - if active: - self.log("{gradient} is enabled after removing {conflicting_gradient} component".format(gradient=component_name, conflicting_gradient=gradient_name)) + # Remove the conflicting gradient component (and transform modifier if it was added) + editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', conflicting_components) + + # Verify the gradient modifier component is enabled now that the other gradient is gone + active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_component) + component_is_enabled = ( + f"{component_name} is enabled after removing {gradient_name} component", + f"{component_name} is unexpectedly disabled after removing {gradient_name} component" + ) + Report.result(component_is_enabled, active) -test = TestGradientModifiersIncompatibilities() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientModifiers_Incompatibilities) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py index 73e8b95823..3749f93bf5 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py @@ -5,129 +5,125 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.math as math -import azlmbr.paths -import azlmbr.entity as EntityId +def GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin(): + """ + Summary: + A temporary level is created. An entity for each test case is created and added with the corresponding + components to verify if the gradient transform is set to the world origin. -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper + Expected Behavior: + 1) Preview image updates to reflect change in transform of the gradient sampler. + 2) New Preview Position property is exposed, and set to 0,0,0 (world origin). + 3) Preview Size is set to 1,1,1 by default. + Test Steps: + 1) Open level + 2) Create entity with Random Noise gradient and verify gradient position after clearing pinned entity + 3) Create entity with Levels Gradient Modifier and verify gradient position after clearing pinned entity + 4) Create entity with Posterize Gradient Modifier and verify gradient position after clearing pinned entity + 5) Create entity with Smooth-Step Gradient Modifier and verify gradient position after clearing pinned entity + 6) Create entity with Threshold Gradient Modifier and verify gradient position after clearing pinned entity + 7) Create entity with FastNoise Gradient and verify gradient position after clearing pinned entity + 8) Create entity with Dither Gradient Modifier and verify gradient position after clearing pinned entity + 9) Create entity with Invert Gradient Modifier and verify gradient position after clearing pinned entity + 10) Create entity with Perlin Noise Gradient and verify gradient position after clearing pinned entity -class TestGradientPreviewSettings(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientPreviewSettings_ClearPinnedEntity", args=["level"]) + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - def run_test(self): - """ - Summary: - A temporary level is created. An entity for each test case is created and added with the corresponding - components to verify if the gradient transform is set to the world origin. + :return: None + """ - Expected Behavior: - 1) Preview image updates to reflect change in transform of the gradient sampler. - 2) New Preview Position property is exposed, and set to 0,0,0 (world origin). - 3) Preview Size is set to 1,1,1 by default. + import sys - Test Steps: - 1) Open level - 2) Create entity with Random Noise gradient and verify gradient position after clearing pinned entity - 3) Create entity with Levels Gradient Modifier and verify gradient position after clearing pinned entity - 4) Create entity with Posterize Gradient Modifier and verify gradient position after clearing pinned entity - 5) Create entity with Smooth-Step Gradient Modifier and verify gradient position after clearing pinned entity - 6) Create entity with Threshold Gradient Modifier and verify gradient position after clearing pinned entity - 7) Create entity with FastNoise Gradient and verify gradient position after clearing pinned entity - 8) Create entity with Dither Gradient Modifier and verify gradient position after clearing pinned entity - 9) Create entity with Invert Gradient Modifier and verify gradient position after clearing pinned entity - 10) Create entity with Perlin Noise Gradient and verify gradient position after clearing pinned entity + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.math as math + import azlmbr.entity as EntityId - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - :return: None - """ + WORLD_ORIGIN = math.Vector3(0.0, 0.0, 0.0) + EXPECTED_SIZE = math.Vector3(1.0, 1.0, 1.0) + CLOSE_THRESHOLD = sys.float_info.min - WORLD_ORIGIN = math.Vector3(0.0, 0.0, 0.0) - EXPECTED_SIZE = math.Vector3(1.0, 1.0, 1.0) - CLOSE_THRESHOLD = sys.float_info.min + def create_entity(entity_name, components_to_add): + entity_position = math.Vector3(125.0, 136.0, 32.0) + entity_id = editor.ToolsApplicationRequestBus( + bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() + ) + entity = hydra.Entity(entity_name, entity_id) + if entity_id.IsValid(): + print(f"{entity_name} entity Created") + entity.components = [] + for component in components_to_add: + entity.components.append(hydra.add_component(component, entity_id)) + return entity - def create_entity(enity_name, components_to_add): - entity_position = math.Vector3(125.0, 136.0, 32.0) - entity_id = editor.ToolsApplicationRequestBus( - bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() + def clear_entityid_check_position(entity_name, components_to_add, check_preview_size=False): + entity = create_entity(entity_name, components_to_add) + hydra.get_set_test(entity, 0, "Preview Settings|Pin Preview to Shape", EntityId.EntityId()) + preview_position = hydra.get_component_property_value( + entity.components[0], "Preview Settings|Preview Position" + ) + preview_set_to_origin = ( + f"{entity_name}: Preview Position set to world origin", + f"{entity_name}: Preview Position set to unexpected coords" + ) + Report.result(preview_set_to_origin, preview_position.IsClose(WORLD_ORIGIN, CLOSE_THRESHOLD)) + if check_preview_size: + preview_size = hydra.get_component_property_value(entity.components[0], "Preview Settings|Preview Size") + preview_size_default_set = ( + f"{entity_name}: Preview Size set as expected", + f"{entity_name}: Preview Size set to unexpected value. Expected {EXPECTED_SIZE}, Found {preview_size}" ) - entity = hydra.Entity(enity_name, entity_id) - if entity_id.IsValid(): - print(f"{enity_name} entity Created") - entity.components = [] - for component in components_to_add: - entity.components.append(hydra.add_component(component, entity_id)) - return entity + Report.result(preview_size_default_set, preview_size.IsClose(EXPECTED_SIZE, CLOSE_THRESHOLD)) + return entity - def clear_entityid_check_position(entity_name, components_to_add, check_preview_size=False): - entity = create_entity(entity_name, components_to_add) - hydra.get_set_test(entity, 0, "Preview Settings|Pin Preview to Shape", EntityId.EntityId()) - preview_position = hydra.get_component_property_value( - entity.components[0], "Preview Settings|Preview Position" - ) - if preview_position.IsClose(WORLD_ORIGIN, CLOSE_THRESHOLD): - print(f"{entity_name} --- Preview Position set to world origin") - if check_preview_size: - preview_size = hydra.get_component_property_value(entity.components[0], "Preview Settings|Preview Size") - if preview_size.IsClose(EXPECTED_SIZE, CLOSE_THRESHOLD): - print(f"{entity_name} --- Preview Size set to (1, 1, 1)") - return entity + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 1) Open level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + # 2) Create entity with Random Noise gradient and verify gradient position after clearing pinned entity + clear_entityid_check_position( + "Random Noise Gradient", ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"], True + ) - # 2) Create entity with Random Noise gradient and verify gradient position after clearing pinned entity - clear_entityid_check_position( - "Random Noise Gradient", ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"], True - ) + # 3) Create entity with Levels Gradient Modifier and verify gradient position after clearing pinned entity + clear_entityid_check_position("Levels Gradient Modifier", ["Levels Gradient Modifier"]) - # 3) Create entity with Levels Gradient Modifier and verify gradient position after clearing pinned entity - clear_entityid_check_position("Levels Gradient Modifier", ["Levels Gradient Modifier"]) + # 4) Create entity with Posterize Gradient Modifier and verify gradient position after clearing pinned entity + clear_entityid_check_position("Posterize Gradient Modifier", ["Posterize Gradient Modifier"]) - # 4) Create entity with Posterize Gradient Modifier and verify gradient position after clearing pinned entity - clear_entityid_check_position("Posterize Gradient Modifier", ["Posterize Gradient Modifier"]) + # 5) Create entity with Smooth-Step Gradient Modifier and verify gradient position after clearing pinned entity + clear_entityid_check_position("Smooth-Step Gradient Modifier", ["Smooth-Step Gradient Modifier"]) - # 5) Create entity with Smooth-Step Gradient Modifier and verify gradient position after clearing pinned entity - clear_entityid_check_position("Smooth-Step Gradient Modifier", ["Smooth-Step Gradient Modifier"]) + # 6) Create entity with Threshold Gradient Modifier and verify gradient position after clearing pinned entity + clear_entityid_check_position("Threshold Gradient Modifier", ["Threshold Gradient Modifier"]) - # 6) Create entity with Threshold Gradient Modifier and verify gradient position after clearing pinned entity - clear_entityid_check_position("Threshold Gradient Modifier", ["Threshold Gradient Modifier"]) + # 7) Create entity with FastNoise Gradient and verify gradient position after clearing pinned entity + clear_entityid_check_position( + "FastNoise Gradient", ["FastNoise Gradient", "Gradient Transform Modifier", "Box Shape"], True + ) - # 7) Create entity with FastNoise Gradient and verify gradient position after clearing pinned entity - clear_entityid_check_position( - "FastNoise Gradient", ["FastNoise Gradient", "Gradient Transform Modifier", "Box Shape"], True - ) + # 8) Create entity with Dither Gradient Modifier and verify gradient position after clearing pinned entity + clear_entityid_check_position("Dither Gradient Modifier", ["Dither Gradient Modifier"], True) - # 8) Create entity with Dither Gradient Modifier and verify gradient position after clearing pinned entity - clear_entityid_check_position("Dither Gradient Modifier", ["Dither Gradient Modifier"], True) + # 9) Create entity with Invert Gradient Modifier and verify gradient position after clearing pinned entity + clear_entityid_check_position("Invert Gradient Modifier", ["Invert Gradient Modifier"]) - # 9) Create entity with Invert Gradient Modifier and verify gradient position after clearing pinned entity - clear_entityid_check_position("Invert Gradient Modifier", ["Invert Gradient Modifier"]) - - # 10) Create entity with Perlin Noise Gradient and verify gradient position after clearing pinned entity - clear_entityid_check_position( - "Perlin Noise Gradient", ["Perlin Noise Gradient", "Gradient Transform Modifier", "Box Shape"], True - ) + # 10) Create entity with Perlin Noise Gradient and verify gradient position after clearing pinned entity + clear_entityid_check_position( + "Perlin Noise Gradient", ["Perlin Noise Gradient", "Gradient Transform Modifier", "Box Shape"], True + ) -test = TestGradientPreviewSettings() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py index 99a54f614a..3756452710 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py @@ -5,18 +5,6 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys - -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.entity as entity -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper - class Scoped: def __init__(self, constructor, destructor, *args): @@ -33,81 +21,84 @@ class TestParams: self.accessed_component = accessed_component -class TestGradientPreviewSettings(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientPreviewSettings_DefaultPinnedEntity", args=["level"]) +def GradientPreviewSettings_DefaultPinnedEntityIsSelf(): + """ + Summary: + This test verifies default values for the pinned entity for Gradient Preview settings. - def run_test(self): - """ - Summary: - This test verifies default values for the pinned entity for Gradient Preview settings. + Expected Behavior: + Pinned entity is self for all gradient generator/modifiers. - Expected Behavior: - Pinned entity is self for all gradient generator/modifiers. + Test Steps: + 1) Open a simple level + 2) Create a new entity in the level + 3) Add each Gradient Generator component to an entity, and verify the Pin Preview to Shape property is set to + self - Test Steps: - 1) Create a new level - 2) Create a new entity in the level - 3) Add each Gradient Generator component to an entity, and verify the Pin Preview to Shape property is set to - self + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.entity as entity - def execute_test(test_id, function, *args): - if function(*args): - self.log(test_id + ' has Preview pinned to own Entity result: SUCCESS') + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - def create_entity(): - return editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) - - def delete_entity(entity_id): - editor.ToolsApplicationRequestBus(bus.Broadcast, 'DeleteEntityAndAllDescendants', entity_id) - - def attach_components(component_list, entity_id): - components = [] - for i in component_list: - components.append(hydra.add_component(i, entity_id)) - return components - - def validate_id_is_current(param): - entity_ptr = Scoped(create_entity, delete_entity) - added_components = attach_components(param.required_components, entity_ptr.data) - value = hydra.get_component_property_value(added_components[param.accessed_component], - 'Preview Settings|Pin Preview to Shape') - self.test_success = self.test_success and entity_ptr.data.Equal(value) - return entity_ptr.data.Equal(value) - - param_list = [ - TestParams(['Gradient Transform Modifier', 'Box Shape', 'Perlin Noise Gradient'], 2), - TestParams(['Random Noise Gradient', 'Gradient Transform Modifier', 'Box Shape'], 0), - TestParams(['FastNoise Gradient', 'Gradient Transform Modifier', 'Box Shape'], 0), - TestParams(['Dither Gradient Modifier'], 0), - TestParams(['Invert Gradient Modifier'], 0), - TestParams(['Levels Gradient Modifier'], 0), - TestParams(['Posterize Gradient Modifier'], 0), - TestParams(['Smooth-Step Gradient Modifier'], 0), - TestParams(['Threshold Gradient Modifier'], 0) - ] - - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, + def execute_test(test_id, function, *args): + pinned_to_self = ( + f"{test_id} has Preview pinned to self", + f"{test_id} has Preview pinned to a different entity" ) + Report.result(pinned_to_self, function(*args)) - for param in param_list: - execute_test(param.required_components[param.accessed_component], - validate_id_is_current, param) + def create_entity(): + return editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) + + def delete_entity(entity_id): + editor.ToolsApplicationRequestBus(bus.Broadcast, 'DeleteEntityAndAllDescendants', entity_id) + + def attach_components(component_list, entity_id): + components = [] + for i in component_list: + components.append(hydra.add_component(i, entity_id)) + return components + + def validate_id_is_current(param): + entity_ptr = Scoped(create_entity, delete_entity) + added_components = attach_components(param.required_components, entity_ptr.data) + value = hydra.get_component_property_value(added_components[param.accessed_component], + 'Preview Settings|Pin Preview to Shape') + return entity_ptr.data.Equal(value) + + param_list = [ + TestParams(['Gradient Transform Modifier', 'Box Shape', 'Perlin Noise Gradient'], 2), + TestParams(['Random Noise Gradient', 'Gradient Transform Modifier', 'Box Shape'], 0), + TestParams(['FastNoise Gradient', 'Gradient Transform Modifier', 'Box Shape'], 0), + TestParams(['Dither Gradient Modifier'], 0), + TestParams(['Invert Gradient Modifier'], 0), + TestParams(['Levels Gradient Modifier'], 0), + TestParams(['Posterize Gradient Modifier'], 0), + TestParams(['Smooth-Step Gradient Modifier'], 0), + TestParams(['Threshold Gradient Modifier'], 0) + ] + + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + for param in param_list: + execute_test(param.required_components[param.accessed_component], + validate_id_is_current, param) -test = TestGradientPreviewSettings() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientPreviewSettings_DefaultPinnedEntityIsSelf) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSampling_GradientReferencesAddRemoveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSampling_GradientReferencesAddRemoveSuccessfully.py index 6d88f43d5a..8e85345a6f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSampling_GradientReferencesAddRemoveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSampling_GradientReferencesAddRemoveSuccessfully.py @@ -5,92 +5,82 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.math as math -import azlmbr.paths -import azlmbr.entity as EntityId +def GradientSampling_GradientReferencesAddRemoveSuccessfully(): + """ + Summary: + An existing gradient generator can be pinned and cleared to/from the Gradient Entity Id field -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper + Expected Behavior: + Gradient generator is assigned to the Gradient Entity Id field. + Gradient generator is removed from the field. + Test Steps: + 1) Open level + 2) Create a new entity with components "Random Noise Gradient", "Gradient Transform Modifier" and "Box Shape" + 3) Create a new entity with Gradient Modifier's, pin and clear the random noise entity id to the Gradient Id + field in Gradient Modifier -class TestGradientSampling(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientSampling_GradientReferences", args=["level"]) + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - def run_test(self): - """ - Summary: - An existing gradient generator can be pinned and cleared to/from the Gradient Entity Id field + :return: None + """ - Expected Behavior: - Gradient generator is assigned to the Gradient Entity Id field. - Gradient generator is removed from the field. + import azlmbr.math as math + import azlmbr.entity as EntityId - Test Steps: - 1) Open level - 2) Create a new entity with components "Random Noise Gradient", "Gradient Transform Modifier" and "Box Shape" - 3) Create a new entity with Gradient Modifier's, pin and clear the random noise entity id to the Gradient Id - field in Gradient Modifier + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. - - :return: None - """ - - def modifier_pin_clear_to_gradiententityid(modifier): - entity_position = math.Vector3(125.0, 136.0, 32.0) - component_to_add = [modifier] - gradient_modifier = hydra.Entity(modifier) - gradient_modifier.create_entity(entity_position, component_to_add) - gradient_modifier.get_set_test(0, "Configuration|Gradient|Gradient Entity Id", random_noise.id) - entity = hydra.get_component_property_value( - gradient_modifier.components[0], "Configuration|Gradient|Gradient Entity Id" - ) - if entity.Equal(random_noise.id): - print(f"Gradient Generator is pinned to the {modifier} successfully") - else: - print(f"Failed to pin Gradient Generator to the {modifier}") - hydra.get_set_test(gradient_modifier, 0, "Configuration|Gradient|Gradient Entity Id", EntityId.EntityId()) - entity = hydra.get_component_property_value( - gradient_modifier.components[0], "Configuration|Gradient|Gradient Entity Id" - ) - if entity.Equal(EntityId.EntityId()): - print(f"Gradient Generator is cleared from the {modifier} successfully") - else: - print(f"Failed to clear Gradient Generator from the {modifier}") - - # 1) Open level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - # 2) Create a new entity with components "Random Noise Gradient", "Gradient Transform Modifier" and "Box Shape" + def modifier_pin_clear_to_gradiententityid(modifier): entity_position = math.Vector3(125.0, 136.0, 32.0) - components_to_add = ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"] - random_noise = hydra.Entity("Random_Noise") - random_noise.create_entity(entity_position, components_to_add) + component_to_add = [modifier] + gradient_modifier = hydra.Entity(modifier) + gradient_modifier.create_entity(entity_position, component_to_add) + gradient_modifier.get_set_test(0, "Configuration|Gradient|Gradient Entity Id", random_noise.id) + entity = hydra.get_component_property_value( + gradient_modifier.components[0], "Configuration|Gradient|Gradient Entity Id" + ) + gradient_pinned_to_modifier = ( + f"Gradient Generator is pinned to the {modifier} successfully", + f"Failed to pin Gradient Generator to the {modifier}" + ) + Report.result(gradient_pinned_to_modifier, entity.Equal(random_noise.id)) + hydra.get_set_test(gradient_modifier, 0, "Configuration|Gradient|Gradient Entity Id", EntityId.EntityId()) + entity = hydra.get_component_property_value( + gradient_modifier.components[0], "Configuration|Gradient|Gradient Entity Id" + ) + gradient_cleared_from_modifier = ( + f"Gradient Generator is cleared from the {modifier} successfully", + f"Failed to clear Gradient Generator from the {modifier}" + ) + Report.result(gradient_cleared_from_modifier, entity.Equal(EntityId.EntityId())) - # 3) Create a new entity with Gradient Modifier's, pin and clear the random noise entity id to the Gradient Id - # field in Gradient Modifier - modifier_pin_clear_to_gradiententityid("Dither Gradient Modifier") - modifier_pin_clear_to_gradiententityid("Invert Gradient Modifier") - modifier_pin_clear_to_gradiententityid("Levels Gradient Modifier") - modifier_pin_clear_to_gradiententityid("Posterize Gradient Modifier") - modifier_pin_clear_to_gradiententityid("Smooth-Step Gradient Modifier") - modifier_pin_clear_to_gradiententityid("Threshold Gradient Modifier") + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + # 2) Create a new entity with components "Random Noise Gradient", "Gradient Transform Modifier" and "Box Shape" + entity_position = math.Vector3(125.0, 136.0, 32.0) + components_to_add = ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"] + random_noise = hydra.Entity("Random_Noise") + random_noise.create_entity(entity_position, components_to_add) + + # 3) Create a new entity with Gradient Modifier's, pin and clear the random noise entity id to the Gradient Id + # field in Gradient Modifier + modifier_pin_clear_to_gradiententityid("Dither Gradient Modifier") + modifier_pin_clear_to_gradiententityid("Invert Gradient Modifier") + modifier_pin_clear_to_gradiententityid("Levels Gradient Modifier") + modifier_pin_clear_to_gradiententityid("Posterize Gradient Modifier") + modifier_pin_clear_to_gradiententityid("Smooth-Step Gradient Modifier") + modifier_pin_clear_to_gradiententityid("Threshold Gradient Modifier") -test = TestGradientSampling() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientSampling_GradientReferencesAddRemoveSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py index 26d791495a..f653515a39 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py @@ -5,114 +5,104 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.math as math -import azlmbr.bus as bus -import azlmbr.entity as entity -import azlmbr.paths -import azlmbr.editor as editor - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -class TestGradientSurfaceTagEmitterDependencies(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__( - self, log_prefix="GradientSurfaceTagEmitter_ComponentDependencies", args=["level"] +def GradientSurfaceTagEmitter_ComponentDependencies(): + """ + Summary: + This test verifies that the Gradient Surface Tag Emitter component is dependent on a gradient component. + + Expected Result: + Gradient Surface Tag Emitter component is disabled until a Gradient Generator, Modifier or Gradient Reference + component (and any sub-dependencies) is added to the entity. + + Test Steps: + 1) Open level + 2) Create a new entity with a Gradient Surface Tag Emitter component + 3) Verify the component is disabled until a dependent component is also added to the entity + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + import azlmbr.math as math + import azlmbr.bus as bus + import azlmbr.entity as entity + import azlmbr.editor as editor + + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + def is_enabled(EntityComponentIdPair): + return editor.EditorComponentAPIBus(bus.Broadcast, "IsComponentEnabled", EntityComponentIdPair) + + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + # Create an entity with Gradient Surface Tag Emitter component + position = math.Vector3(512.0, 512.0, 32.0) + gradient = hydra.Entity("gradient") + gradient.create_entity(position, ["Gradient Surface Tag Emitter"]) + + # Make sure Gradient Surface Tag Emitter is disabled + gradient_surface_tag_disabled = ( + "Gradient Surface Tag Emitter is Disabled", + "Gradient Surface Tag Emitter is Enabled, but should be Disabled without dependencies met" + ) + Report.result(gradient_surface_tag_disabled, not is_enabled(gradient.components[0])) + + # Verify Gradient Surface Tag Emitter component is enabled after adding Gradient, Generator, Modifier + # or Reference component + new_components_to_add = [ + "Dither Gradient Modifier", + "Gradient Mixer", + "Invert Gradient Modifier", + "Levels Gradient Modifier", + "Posterize Gradient Modifier", + "Smooth-Step Gradient Modifier", + "Threshold Gradient Modifier", + "Altitude Gradient", + "Constant Gradient", + "FastNoise Gradient", + "Image Gradient", + "Perlin Noise Gradient", + "Random Noise Gradient", + "Reference Gradient", + "Shape Falloff Gradient", + "Slope Gradient", + "Surface Mask Gradient", + ] + for component in new_components_to_add: + component_list = ["FastNoise Gradient", "Image Gradient", "Perlin Noise Gradient", "Random Noise Gradient"] + if component in component_list: + for Component in ["Gradient Transform Modifier", "Box Shape"]: + hydra.add_component(Component, gradient.id) + typeIdsList = editor.EditorComponentAPIBus(bus.Broadcast, 'FindComponentTypeIdsByEntityType', [component], + entity.EntityType().Game) + ComponentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentsOfType', gradient.id, [typeIdsList[0]]) + Components = ComponentOutcome.GetValue() + ComponentIdPair = Components[0] + gradient_enabled = is_enabled(gradient.components[0]) + new_components_enabled = is_enabled(ComponentIdPair) + dependencies_met = ( + f"{component} and Gradient Surface Tag Emitter are enabled", + f"{component} and Gradient Surface Tag Emitter are disabled" ) + Report.result(dependencies_met, new_components_enabled and gradient_enabled) - def run_test(self): - """ - Summary: - This test verifies that the Gradient Surface Tag Emitter component is dependent on a gradient component. - - Expected Result: - Gradient Surface Tag Emitter component is disabled until a Gradient Generator, Modifier or Gradient Reference - component (and any sub-dependencies) is added to the entity. - - Test Steps: - 1) Open level - 2) Create a new entity with a Gradient Surface Tag Emitter component - 3) Verify the component is disabled until a dependent component is also added to the entity - - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. - - :return: None - """ - - def is_enabled(EntityComponentIdPair): - return editor.EditorComponentAPIBus(bus.Broadcast, "IsComponentEnabled", EntityComponentIdPair) - - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - # Create an entity with Gradient Surface Tag Emitter component - position = math.Vector3(512.0, 512.0, 32.0) - gradient = hydra.Entity("gradient") - gradient.create_entity(position, ["Gradient Surface Tag Emitter"]) - - # Make sure Gradient Surface Tag Emitter is disabled - is_enable = is_enabled(gradient.components[0]) - if not is_enable: - self.log("Gradient Surface Tag Emitter is Disabled") - elif not is_enable: - self.log("Gradient Surface Tag Emitter is Enabled, but should be Disabled without dependencies met") - - # Verify Gradient Surface Tag Emitter component is enabled after adding Gradient, Generator, Modifier - # or Reference component - new_components_to_add = [ - "Dither Gradient Modifier", - "Gradient Mixer", - "Invert Gradient Modifier", - "Levels Gradient Modifier", - "Posterize Gradient Modifier", - "Smooth-Step Gradient Modifier", - "Threshold Gradient Modifier", - "Altitude Gradient", - "Constant Gradient", - "FastNoise Gradient", - "Image Gradient", - "Perlin Noise Gradient", - "Random Noise Gradient", - "Reference Gradient", - "Shape Falloff Gradient", - "Slope Gradient", - "Surface Mask Gradient", - ] - for component in new_components_to_add: - component_list = ["FastNoise Gradient", "Image Gradient", "Perlin Noise Gradient", "Random Noise Gradient"] - if component in component_list: - for Component in ["Gradient Transform Modifier", "Box Shape"]: - hydra.add_component(Component, gradient.id) - typeIdsList = editor.EditorComponentAPIBus(bus.Broadcast, 'FindComponentTypeIdsByEntityType', [component], - entity.EntityType().Game) - ComponentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentsOfType', gradient.id, [typeIdsList[0]]) - Components = ComponentOutcome.GetValue() - ComponentIdPair = Components[0] - gradient_enabled = new_components_enabled = False - gradient_enabled = is_enabled(gradient.components[0]) - new_components_enabled = is_enabled(ComponentIdPair) - if new_components_enabled and gradient_enabled: - self.log(f"{component} and Gradient Surface Tag Emitter are enabled") - else: - self.log(f"{component} and Gradient Surface Tag Emitter are disabled") - if component in component_list: - hydra.remove_component("Gradient Transform Modifier", gradient.id) - hydra.remove_component("Box Shape", gradient.id) - hydra.remove_component(component, gradient.id) + if component in component_list: + hydra.remove_component("Gradient Transform Modifier", gradient.id) + hydra.remove_component("Box Shape", gradient.id) + hydra.remove_component(component, gradient.id) -test = TestGradientSurfaceTagEmitterDependencies() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientSurfaceTagEmitter_ComponentDependencies) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py index 44c9792296..90840a135d 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py @@ -5,75 +5,69 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.math as math -import azlmbr.paths -import azlmbr.surface_data as surface_data +def GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully(): + """ + Summary: + Entity with Gradient Surface Tag Emitter and Reference Gradient components is created. + And new surface tag has been added and removed. -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper + Expected Behavior: + A new Surface Tag can be added and removed from the component + + Test Steps: + 1) Open level + 2) Create an entity with Gradient Surface Tag Emitter and Reference Gradient components. + 3) Add/ remove Surface Tags + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + import azlmbr.math as math + import azlmbr.surface_data as surface_data + + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + # 2) Create an entity with Gradient Surface Tag Emitter and Reference Gradient components. + entity_position = math.Vector3(125.0, 136.0, 32.0) + components_to_add = ["Gradient Surface Tag Emitter", "Reference Gradient"] + entity = hydra.Entity("entity") + entity.create_entity(entity_position, components_to_add) + + # 3) Add/ remove Surface Tags + tag = surface_data.SurfaceTag() + tag.SetTag("water") + pte = hydra.get_property_tree(entity.components[0]) + path = "Configuration|Extended Tags" + pte.add_container_item(path, 0, tag) + success = helper.wait_for_condition(lambda: pte.get_container_count(path).GetValue() == 1, 1.0) + tag_added_to_container = ( + "Successfully added surface tag", + "Failed to add surface tag" + ) + Report.result(tag_added_to_container, success) + pte.remove_container_item(path, 0) + success = helper.wait_for_condition(lambda: pte.get_container_count(path).GetValue() == 0, 1.0) + tag_removed_from_container = ( + "Successfully removed surface tag", + "Failed to remove surface tag" + ) + Report.result(tag_removed_from_container, success) -class TestGradientSurfaceTagEmitter(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSucessfully", - args=["level"]) +if __name__ == "__main__": - def run_test(self): - """ - Summary: - Entity with Gradient Surface Tag Emitter and Reference Gradient components is created. - And new surface tag has been added and removed. - - Expected Behavior: - A new Surface Tag can be added and removed from the component + from editor_python_test_tools.utils import Report + Report.start_test(GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully) - Test Steps: - 1) Open level - 2) Create an entity with Gradient Surface Tag Emitter and Reference Gradient components. - 3) Add/ remove Surface Tags - - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. - - :return: None - """ - - # 1) Open level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - # 2) Create an entity with Gradient Surface Tag Emitter and Reference Gradient components. - entity_position = math.Vector3(125.0, 136.0, 32.0) - components_to_add = ["Gradient Surface Tag Emitter", "Reference Gradient"] - entity = hydra.Entity("entity") - entity.create_entity(entity_position, components_to_add) - - # 3) Add/ remove Surface Tags - tag = surface_data.SurfaceTag() - tag.SetTag("water") - pte = hydra.get_property_tree(entity.components[0]) - path = "Configuration|Extended Tags" - pte.add_container_item(path, 0, tag) - success = self.wait_for_condition(lambda: pte.get_container_count(path).GetValue() == 1) - self.test_success = self.test_success and success - print(f"Added SurfaceTag: container count is {pte.get_container_count(path).GetValue()}") - pte.remove_container_item(path, 0) - success = self.wait_for_condition(lambda: pte.get_container_count(path).GetValue() == 0) - self.test_success = self.test_success and success - print(f"Removed SurfaceTag: container count is {pte.get_container_count(path).GetValue()}") - - -test = TestGradientSurfaceTagEmitter() -test.run() diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithExpectedGradients.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithExpectedGradients.py index b5f342a15f..5e6df4d52f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithExpectedGradients.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithExpectedGradients.py @@ -5,118 +5,102 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.math as math -import azlmbr.entity as EntityId +def GradientTransform_ComponentIncompatibleWithExpectedGradients(): + """ + Summary: + A New level is created. A New entity is created with components Gradient Transform Modifier and Box Shape. + Adding components Constant Gradient, Altitude Gradient, Gradient Mixer, Reference Gradient, Shape + Falloff Gradient, Slope Gradient and Surface Mask Gradient to the same entity. -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper + Expected Behavior: + All added components are disabled and inform the user that they are incompatible with the Gradient Transform + Modifier + Test Steps: + 1) Create level + 2) Create a new entity with components Gradient Transform Modifier and Box Shape + 3) Make sure all components are enabled in Entity + 4) Add Constant Gradient, Altitude Gradient, Gradient Mixer, Reference Gradient, Shape + Falloff Gradient, Slope Gradient and Surface Mask Gradient to the same entity + 5) Make sure all newly added components are disabled -class TestGradientTransform_ComponentIncompatibleWithExpectedGradients(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientTransform_ComponentIncompatibleWithExpectedGradients", - args=["level"]) + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - def run_test(self): - """ - Summary: - A New level is created. A New entity is created with components Gradient Transform Modifier and Box Shape. - Adding components Constant Gradient, Altitude Gradient, Gradient Mixer, Reference Gradient, Shape - Falloff Gradient, Slope Gradient and Surface Mask Gradient to the same entity. + :return: None + """ - Expected Behavior: - All added components are disabled and inform the user that they are incompatible with the Gradient Transform - Modifier + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.math as math + import azlmbr.entity as EntityId - Test Steps: - 1) Create level - 2) Create a new entity with components Gradient Transform Modifier and Box Shape - 3) Make sure all components are enabled in Entity - 4) Add Constant Gradient, Altitude Gradient, Gradient Mixer, Reference Gradient, Shape - Falloff Gradient, Slope Gradient and Surface Mask Gradient to the same entity - 5) Make sure all newly added components are disabled + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + def is_enabled(EntityComponentIdPair): + return editor.EditorComponentAPIBus(bus.Broadcast, "IsComponentEnabled", EntityComponentIdPair) - :return: None - """ + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - def is_enabled(EntityComponentIdPair): - return editor.EditorComponentAPIBus(bus.Broadcast, "IsComponentEnabled", EntityComponentIdPair) + # 2) Create a new entity with components Gradient Transform Modifier and Box Shape + entity_position = math.Vector3(125.0, 136.0, 32.0) + components_to_add = ["Gradient Transform Modifier", "Box Shape"] + gradient_id = editor.ToolsApplicationRequestBus( + bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() + ) + gradient = hydra.Entity("gradient", gradient_id) - # 1) Create level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, + gradient.components = [] + + for component in components_to_add: + gradient.components.append(hydra.add_component(component, gradient_id)) + entity_created = ( + "Entity created successfully", + "Failed to create entity" + ) + Report.critical_result(entity_created, gradient_id.isValid()) + + # 3) Make sure all components are enabled in Entity + index = 0 + for component in components_to_add: + components_enabled = ( + f"{component} is enabled", + f"{component} is unexpectedly disabled" ) + Report.critical_result(components_enabled, is_enabled(gradient.components[index])) + index += 1 - # 2) Create a new entity with components Gradient Transform Modifier and Box Shape - entity_position = math.Vector3(125.0, 136.0, 32.0) - components_to_add = ["Gradient Transform Modifier", "Box Shape"] - gradient_id = editor.ToolsApplicationRequestBus( - bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() + # 4) Add Constant Gradient, Altitude Gradient, Gradient Mixer, Reference Gradient, Shape + # Falloff Gradient, Slope Gradient and Surface Mask Gradient to the same entity + new_components_to_add = [ + "Constant Gradient", + "Altitude Gradient", + "Gradient Mixer", + "Reference Gradient", + "Shape Falloff Gradient", + "Slope Gradient", + "Surface Mask Gradient", + ] + new_components_enabled = False + for component in new_components_to_add: + gradient.components.append(hydra.add_component(component, gradient_id)) + gradient_components_disabled = ( + f"{component} is disabled", + f"{component} is enabled, but should be disabled" ) - gradient = hydra.Entity("gradient", gradient_id) - - gradient.components = [] - - for component in components_to_add: - gradient.components.append(hydra.add_component(component, gradient_id)) - if gradient_id.isValid(): - self.log("New Entity Created") - - # 3) Make sure all components are enabled in Entity - index = 0 - for component in components_to_add: - is_enable = is_enabled(gradient.components[index]) - if is_enable: - self.log(f"{component} is Enabled") - self.test_success = self.test_success and is_enable - elif not is_enable: - self.log(f"{component} is disabled, but it should be enabled") - self.test_success = self.test_success and is_enable - break - index += 1 - - # 4) Add Constant Gradient, Altitude Gradient, Gradient Mixer, Reference Gradient, Shape - # Falloff Gradient, Slope Gradient and Surface Mask Gradient to the same entity - new_components_to_add = [ - "Constant Gradient", - "Altitude Gradient", - "Gradient Mixer", - "Reference Gradient", - "Shape Falloff Gradient", - "Slope Gradient", - "Surface Mask Gradient", - ] - index = 2 - new_components_enabled = False - for component in new_components_to_add: - gradient.components.append(hydra.add_component(component, gradient_id)) - new_components_enabled = is_enabled(gradient.components[index]) - if new_components_enabled: - self.log(f"{component} is enabled, but should be disabled") - break + Report.result(gradient_components_disabled, not is_enabled(gradient.components[2])) + if not is_enabled(gradient.components[2]): editor.EditorComponentAPIBus(bus.Broadcast, "RemoveComponents", component) - # 5) Make sure all newly added components are disabled - if not new_components_enabled: - self.log("All newly added components are incompatible and disabled") - self.test_success = self.test_success and not new_components_enabled +if __name__ == "__main__": -test = TestGradientTransform_ComponentIncompatibleWithExpectedGradients() -test.run() + from editor_python_test_tools.utils import Report + Report.start_test(GradientTransform_ComponentIncompatibleWithExpectedGradients) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithSpawners.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithSpawners.py index 54270c5ee5..fd65996fdd 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithSpawners.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithSpawners.py @@ -5,104 +5,88 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.math as math -import azlmbr.entity as EntityId +def GradientTransform_ComponentIncompatibleWithSpawners(): + """ + Summary: + A simple level is opened. A New entity is created with components Gradient Transform Modifier and Box Shape. + Adding a component Vegetation Layer Spawner to the same entity. -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper + Expected Behavior: + The Vegetation Layer Spawner is deactivated and it is communicated that it is incompatible with Gradient + Transform Modifier + Test Steps: + 1) Open a simple level + 2) Create a new entity with components Gradient Transform Modifier and Box Shape + 3) Make sure all components are enabled in Entity + 4) Add Vegetation Layer Spawner to the same entity + 5) Make sure newly added component is disabled -class TestGradientTransform_ComponentIncompatibleWithSpawners(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientTransform_ComponentIncompatibleWithSpawners", - args=["level"]) + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - def run_test(self): - """ - Summary: - A New level is created. A New entity is created with components Gradient Transform Modifier and Box Shape. - Adding a component Vegetation Layer Spawner to the same entity. + :return: None + """ - Expected Behavior: - The Vegetation Layer Spawner is deactivated and it is communicated that it is incompatible with Gradient - Transform Modifier + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.math as math + import azlmbr.entity as EntityId - Test Steps: - 1) Create level - 2) Create a new entity with components Gradient Transform Modifier and Box Shape - 3) Make sure all components are enabled in Entity - 4) Add Vegetation Layer Spawner to the same entity - 5) Make sure newly added component is disabled + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + def is_enabled(EntityComponentIdPair): + return editor.EditorComponentAPIBus(bus.Broadcast, "IsComponentEnabled", EntityComponentIdPair) - :return: None - """ + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - def is_enabled(EntityComponentIdPair): - return editor.EditorComponentAPIBus(bus.Broadcast, "IsComponentEnabled", EntityComponentIdPair) + # 2) Create a new entity with components Gradient Transform Modifier and Box Shape + entity_position = math.Vector3(125.0, 136.0, 32.0) + components_to_add = ["Gradient Transform Modifier", "Box Shape"] + gradient_id = editor.ToolsApplicationRequestBus( + bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() + ) + gradient = hydra.Entity("gradient", gradient_id) - # 1) Create level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, + gradient.components = [] + + for component in components_to_add: + gradient.components.append(hydra.add_component(component, gradient_id)) + entity_created = ( + "Entity created successfully", + "Failed to create entity" + ) + Report.critical_result(entity_created, gradient_id.isValid()) + + # 3) Make sure all components are enabled in Entity + index = 0 + for component in components_to_add: + components_enabled = ( + f"{component} is enabled", + f"{component} is unexpectedly disabled" ) + Report.critical_result(components_enabled, is_enabled(gradient.components[index])) + index += 1 - # 2) Create a new entity with components Gradient Transform Modifier and Box Shape - entity_position = math.Vector3(125.0, 136.0, 32.0) - components_to_add = ["Gradient Transform Modifier", "Box Shape"] - gradient_id = editor.ToolsApplicationRequestBus( - bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() - ) - gradient = hydra.Entity("gradient", gradient_id) + # 4) Add Vegetation Layer Spawner to the same entity + gradient.components.append(hydra.add_component("Vegetation Layer Spawner", gradient_id)) - gradient.components = [] - - for component in components_to_add: - gradient.components.append(hydra.add_component(component, gradient_id)) - if gradient_id.isValid(): - self.log("New Entity Created") - - # 3) Make sure all components are enabled in Entity - index = 0 - for component in components_to_add: - is_enable = is_enabled(gradient.components[index]) - if is_enable: - self.log(f"{component} is Enabled") - self.test_success = self.test_success and is_enable - elif not is_enable: - self.log(f"{component} is Disabled. But It should be Enabled in an Entity") - self.test_success = self.test_success and is_enable - break - index += 1 - - # 4) Add Vegetation Layer Spawner to the same entity - new_component_to_add = "Vegetation Layer Spawner" - index = 2 - gradient.components.append(hydra.add_component(new_component_to_add, gradient_id)) - new_component_enabled = is_enabled(gradient.components[index]) - - # 5) Make sure newly added component is disabled - if not new_component_enabled: - self.log(f"{new_component_to_add} is incompatible and disabled") - self.test_success = self.test_success and not new_component_enabled - elif new_component_enabled: - self.log(f"{new_component_to_add} is compatible and enabled. But It should be Incompatible and disabled") - self.test_success = self.test_success and new_component_enabled + # 5) Make sure newly added component is disabled + spawner_component_disabled = ( + "Spawner component is disabled", + "Spawner component is unexpectedly enabled" + ) + Report.result(spawner_component_disabled, not is_enabled(gradient.components[2])) -test = TestGradientTransform_ComponentIncompatibleWithSpawners() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientTransform_ComponentIncompatibleWithSpawners) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange.py index 94647a0b6f..530503db86 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange.py @@ -5,87 +5,82 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -""" -C3430292: Frequency Zoom can manually be set higher than 8. -""" -import os -import sys - -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.math as math -import azlmbr.paths -import azlmbr.entity as EntityId - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper +class Tests: + entity_created = ( + "Entity created successfully", + "Failed to create entity" + ) + components_added = ( + "All expected components added to entity", + "Failed to add expected components to entity" + ) + higher_zoom_value_set = ( + "Frequency Zoom is equal to expected value", + "Frequency Zoom is not equal to expected value" + ) -class TestGradientTransformFrequencyZoom(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientTransform_FrequencyZoomBeyondSliders", args=["level"]) +def GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange(): + """ + Summary: + Frequency Zoom can manually be set higher than 8 in a random noise gradient - def run_test(self): - """ - Summary: - Frequency Zoom can manually be set higher than 8 in a random noise gradient + Expected Behavior: + The value properly changes, despite the value being outside of the slider limit - Expected Behavior: - The value properly changes, despite the value being outside of the slider limit + Test Steps: + 1) Open level + 2) Create entity + 3) Add components to the entity + 4) Set the frequency value of the component + 5) Verify if the frequency value is set to higher value - Test Steps: - 1) Open level - 2) Create entity - 3) Add components to the entity - 4) Set the frequency value of the component - 5) Verify if the frequency value is set to higher value + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.math as math + import azlmbr.entity as EntityId - # 1) Open level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # 2) Create entity - entity_position = math.Vector3(125.0, 136.0, 32.0) - entity_id = editor.ToolsApplicationRequestBus( - bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() - ) - if entity_id.IsValid(): - print("Entity Created") + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # 3) Add components to the entity - components_to_add = ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"] - entity = hydra.Entity("entity", entity_id) - entity.components = [] - for component in components_to_add: - entity.components.append(hydra.add_component(component, entity_id)) - print("Components added to the entity") + # 2) Create entity + entity_position = math.Vector3(125.0, 136.0, 32.0) + entity_id = editor.ToolsApplicationRequestBus( + bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() + ) + Report.critical_result(Tests.entity_created, entity_id.IsValid()) - # 4) Set the frequency value of the component - hydra.get_set_test(entity, 1, "Configuration|Frequency Zoom", 10) + # 3) Add components to the entity + components_to_add = ["Random Noise Gradient", "Gradient Transform Modifier", "Box Shape"] + entity = hydra.Entity("entity", entity_id) + entity.components = [] + for component in components_to_add: + entity.components.append(hydra.add_component(component, entity_id)) + Report.critical_result(Tests.components_added, len(entity.components) == 3) - # 5) Verify if the frequency value is set to higher value - curr_value = hydra.get_component_property_value(entity.components[1], "Configuration|Frequency Zoom") - if curr_value == 10.0: - print("Frequency Zoom is equal to expected value") - else: - print("Frequency Zoom is not equal to expected value") + # 4) Set the frequency value of the component + hydra.get_set_test(entity, 1, "Configuration|Frequency Zoom", 10) + + # 5) Verify if the frequency value is set to higher value + curr_value = hydra.get_component_property_value(entity.components[1], "Configuration|Frequency Zoom") + Report.result(Tests.higher_zoom_value_set, curr_value == 10.0) -test = TestGradientTransformFrequencyZoom() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py index c9cfc225d1..09cce359d5 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py @@ -4,73 +4,71 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys - -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.entity as entity -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -class TestGradientTransformRequiresShape(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientTransformRequiresShape", args=["level"]) - - def run_test(self): - """ - Summary: - This test verifies that the Gradient Transform Modifier component is dependent on a shape component. - - Expected Result: - Gradient Transform Modifier component is disabled until a shape component is added to the entity. - - Test Steps: - 1) Open level - 2) Create a new entity with a Gradient Transform Modifier component - 3) Verify the component is disabled until a shape component is also added to the entity - - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. - - :return: None - """ - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - # Create a new Entity in the level - entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) - - # Add a Gradient Transform Component (that will be disabled since there is no shape on the Entity) - gradient_transform_component = hydra.add_component('Gradient Transform Modifier', entity_id) - - # Verify the Gradient Transform Component is not active before adding the Shape - active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_transform_component) - self.test_success = self.test_success and not active - if not active: - self.log("Gradient Transform component is not active without a Shape component on the Entity") - - # Add a Shape component to the same Entity - hydra.add_component('Box Shape', entity_id) - - # Check if the Gradient Transform Component is active now after adding the Shape - active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_transform_component) - self.test_success = self.test_success and active - if active: - self.log("Gradient Transform Modifier component is active now that the Entity has a Shape") +class Tests: + disabled_without_shape = ( + "Gradient Transform Modifier component is disabled without a Shape component on the Entity", + "Gradient Transform Modifier component is unexpectedly enabled without a Shape component on the Entity", + ) + enabled_with_shape = ( + "Gradient Transform Modifier component is enabled now that the Entity has a Shape", + "Gradient Transform Modifier component is still disabled alongside a Shape component", + ) -test = TestGradientTransformRequiresShape() -test.run() +def GradientTransform_RequiresShape(): + """ + Summary: + This test verifies that the Gradient Transform Modifier component is dependent on a shape component. + + Expected Result: + Gradient Transform Modifier component is disabled until a shape component is added to the entity. + + Test Steps: + 1) Open level + 2) Create a new entity with a Gradient Transform Modifier component + 3) Verify the component is disabled until a shape component is also added to the entity + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.entity as entity + + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + # Create a new Entity in the level + entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) + + # Add a Gradient Transform Component (that will be disabled since there is no shape on the Entity) + gradient_transform_component = hydra.add_component('Gradient Transform Modifier', entity_id) + + # Verify the Gradient Transform Component is not active before adding the Shape + active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_transform_component) + Report.result(Tests.disabled_without_shape, not active) + + # Add a Shape component to the same Entity + hydra.add_component('Box Shape', entity_id) + + # Check if the Gradient Transform Component is active now after adding the Shape + active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', gradient_transform_component) + Report.result(Tests.enabled_with_shape, active) + + +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientTransform_RequiresShape) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py index 1063260550..42458665e1 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py @@ -5,89 +5,91 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -import azlmbr.asset as asset -import azlmbr.bus as bus -import azlmbr.entity as EntityId -import azlmbr.editor as editor -import azlmbr.math as math -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper +class Tests: + image_gradient_entity_created = ( + "Image Gradient entity created", + "Failed to create Image Gradient entity", + ) + image_gradient_asset_found = ( + "image_grad_test_gsi.png was found in the workspace", + "image_grad_test_gsi.png was not found in the workspace" + ) + image_gradient_assigned = ( + "Successfully assigned image gradient asset", + "Failed to assign image gradient asset" + ) -class TestImageGradient(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="ImageGradient_ProcessedImageAssignedSucessfully", - args=["level"]) +def ImageGradient_ProcessedImageAssignedSuccessfully(): + """ + Summary: + Level created with Entity having Image Gradient and Gradient Transform Modifier components. + Save any new image to your workspace with the suffix "_gsi" and assign as image asset. - def run_test(self): - """ - Summary: - Level created with Entity having Image Gradient and Gradient Transform Modifier components. - Save any new image to your workspace with the suffix "_gsi" and assign as image asset. - - Expected Behavior: - Image can be assigned as the Image Asset for the Image as Gradient component. + Expected Behavior: + Image can be assigned as the Image Asset for the Image as Gradient component. - Test Steps: - 1) Create level - 2) Create an entity with Image Gradient and Gradient Transform Modifier components. - 3) Assign the newly processed gradient image as Image asset. + Test Steps: + 1) Open a level + 2) Create an entity with Image Gradient and Gradient Transform Modifier components. + 3) Assign the newly processed gradient image as Image asset. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - :return: None - """ + :return: None + """ - # 1) Create level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + import os - # 2) Create an entity with Image Gradient and Gradient Transform Modifier components - components_to_add = ["Image Gradient", "Gradient Transform Modifier", "Box Shape"] - entity_position = math.Vector3(512.0, 512.0, 32.0) - new_entity_id = editor.ToolsApplicationRequestBus( - bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() - ) - if new_entity_id.IsValid(): - print("Image Gradient Entity created") - image_gradient_entity = hydra.Entity("Image Gradient Entity", new_entity_id) - image_gradient_entity.components = [] - for component in components_to_add: - image_gradient_entity.add_component(component) + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.entity as EntityId + import azlmbr.editor as editor + import azlmbr.math as math - # 3) Assign the processed gradient signal image as the Image Gradient's image asset and verify success + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # First, check for the base image in the workspace - base_image = "image_grad_test_gsi.png" - base_image_path = os.path.join("AutomatedTesting", "Assets", "ImageGradients", base_image) - if os.path.isfile(base_image_path): - print(f"{base_image} was found in the workspace") + # 1) Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Next, assign the processed image to the Image Gradient's Image Asset property - processed_image_path = os.path.join("Assets", "ImageGradients", "image_grad_test_gsi.gradimage") - asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", processed_image_path, math.Uuid(), - False) - hydra.get_set_test(image_gradient_entity, 0, "Configuration|Image Asset", asset_id) + # 2) Create an entity with Image Gradient and Gradient Transform Modifier components + components_to_add = ["Image Gradient", "Gradient Transform Modifier", "Box Shape"] + entity_position = math.Vector3(512.0, 512.0, 32.0) + new_entity_id = editor.ToolsApplicationRequestBus( + bus.Broadcast, "CreateNewEntityAtPosition", entity_position, EntityId.EntityId() + ) + Report.critical_result(Tests.image_gradient_entity_created, new_entity_id.IsValid()) + image_gradient_entity = hydra.Entity("Image Gradient Entity", new_entity_id) + image_gradient_entity.components = [] + for component in components_to_add: + image_gradient_entity.add_component(component) - # Finally, verify if the gradient image is assigned as the Image Asset - success = hydra.get_component_property_value(image_gradient_entity.components[0], "Configuration|Image Asset") == asset_id - self.test_success = self.test_success and success + # 3) Assign the processed gradient signal image as the Image Gradient's image asset and verify success + + # First, check for the base image in the workspace + base_image = "image_grad_test_gsi.png" + base_image_path = os.path.join("AutomatedTesting", "Assets", "ImageGradients", base_image) + Report.critical_result(Tests.image_gradient_asset_found, os.path.isfile(base_image_path)) + + # Next, assign the processed image to the Image Gradient's Image Asset property + processed_image_path = os.path.join("Assets", "ImageGradients", "image_grad_test_gsi.gradimage") + asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", processed_image_path, math.Uuid(), + False) + hydra.get_set_test(image_gradient_entity, 0, "Configuration|Image Asset", asset_id) + + # Finally, verify if the gradient image is assigned as the Image Asset + success = hydra.get_component_property_value(image_gradient_entity.components[0], "Configuration|Image Asset") == asset_id + Report.result(Tests.image_gradient_assigned, success) -test = TestImageGradient() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(ImageGradient_ProcessedImageAssignedSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py index 2c6ac8d15b..3b832d160a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py @@ -4,74 +4,72 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys - -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.entity as entity -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -class TestImageGradientRequiresShape(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="ImageGradientRequiresShape", args=["level"]) - - def run_test(self): - """ - Summary: - This test verifies that the Image Gradient component is dependent on a shape component. - - Expected Result: - Gradient Transform Modifier component is disabled until a shape component is added to the entity. - - Test Steps: - 1) Open level - 2) Create a new entity with a Image Gradient component - 3) Verify the component is disabled until a shape component is also added to the entity - - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. - - :return: None - """ - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - # Create a new Entity in the level - entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) - - # Add an Image Gradient and Gradient Transform Component (should be disabled until a Shape exists on the Entity) - image_gradient_component = hydra.add_component('Image Gradient', entity_id) - hydra.add_component('Gradient Transform Modifier', entity_id) - - # Verify the Image Gradient Component is not active before adding the Shape - active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', image_gradient_component) - self.test_success = self.test_success and not active - if not active: - self.log("Image Gradient component is not active without a Shape component on the Entity") - - # Add a Shape component to the same Entity - hydra.add_component('Box Shape', entity_id) - - # Check if the Image Gradient Component is active now after adding the Shape - active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', image_gradient_component) - self.test_success = self.test_success and active - if active: - self.log("Image Gradient component is active now that the Entity has a Shape") +class Tests: + disabled_without_shape = ( + "Image Gradient component is disabled without a Shape component on the Entity", + "Image Gradient component is unexpectedly enabled without a Shape component on the Entity", + ) + enabled_with_shape = ( + "Image Gradient component is enabled now that the Entity has a Shape", + "Image Gradient component is still disabled alongside a Shape component", + ) -test = TestImageGradientRequiresShape() -test.run() +def ImageGradient_RequiresShape(): + """ + Summary: + This test verifies that the Image Gradient component is dependent on a shape component. + + Expected Result: + Gradient Transform Modifier component is disabled until a shape component is added to the entity. + + Test Steps: + 1) Open level + 2) Create a new entity with a Image Gradient component + 3) Verify the component is disabled until a shape component is also added to the entity + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.entity as entity + + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + # Create a new Entity in the level + entity_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) + + # Add an Image Gradient and Gradient Transform Component (should be disabled until a Shape exists on the Entity) + image_gradient_component = hydra.add_component('Image Gradient', entity_id) + hydra.add_component('Gradient Transform Modifier', entity_id) + + # Verify the Image Gradient Component is not active before adding the Shape + active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', image_gradient_component) + Report.result(Tests.disabled_without_shape, not active) + + # Add a Shape component to the same Entity + hydra.add_component('Box Shape', entity_id) + + # Check if the Image Gradient Component is active now after adding the Shape + active = editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', image_gradient_component) + Report.result(Tests.enabled_with_shape, active) + + +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(ImageGradient_RequiresShape) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSignal_Periodic.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSignal_Periodic.py new file mode 100644 index 0000000000..21eecf642c --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSignal_Periodic.py @@ -0,0 +1,71 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +import os +import pytest +import sys + +sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../automatedtesting_shared') +from base import TestAutomationBase + + +@pytest.mark.SUITE_periodic +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(TestAutomationBase): + + def test_GradientGenerators_Incompatibilities(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientGenerators_Incompatibilities as test_module + self._run_test(request, workspace, editor, test_module) + + def test_GradientModifiers_Incompatibilities(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientModifiers_Incompatibilities as test_module + self._run_test(request, workspace, editor, test_module) + + def test_GradientPreviewSettings_DefaultPinnedEntityIsSelf(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientPreviewSettings_DefaultPinnedEntityIsSelf as test_module + self._run_test(request, workspace, editor, test_module) + + def test_GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin as test_module + self._run_test(request, workspace, editor, test_module) + + def test_GradientSampling_GradientReferencesAddRemoveSuccessfully(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientSampling_GradientReferencesAddRemoveSuccessfully as test_module + self._run_test(request, workspace, editor, test_module) + + def test_GradientSurfaceTagEmitter_ComponentDependencies(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientSurfaceTagEmitter_ComponentDependencies as test_module + self._run_test(request, workspace, editor, test_module) + + def test_GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully as test_module + self._run_test(request, workspace, editor, test_module) + + def test_GradientTransform_RequiresShape(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientTransform_RequiresShape as test_module + self._run_test(request, workspace, editor, test_module) + + def test_GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange as test_module + self._run_test(request, workspace, editor, test_module) + + def test_GradientTransform_ComponentIncompatibleWithSpawners(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientTransform_ComponentIncompatibleWithSpawners as test_module + self._run_test(request, workspace, editor, test_module) + + def test_GradientTransform_ComponentIncompatibleWithExpectedGradients(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientTransform_ComponentIncompatibleWithExpectedGradients as test_module + self._run_test(request, workspace, editor, test_module) + + def test_ImageGradient_RequiresShape(self, request, workspace, editor, launcher_platform): + from .EditorScripts import ImageGradient_RequiresShape as test_module + self._run_test(request, workspace, editor, test_module) + + def test_ImageGradient_ProcessedImageAssignedSuccessfully(self, request, workspace, editor, launcher_platform): + from .EditorScripts import ImageGradient_ProcessedImageAssignedSuccessfully as test_module + self._run_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSignal_Periodic_Optimized.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSignal_Periodic_Optimized.py new file mode 100644 index 0000000000..514504d324 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSignal_Periodic_Optimized.py @@ -0,0 +1,55 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +import pytest + +from ly_test_tools.o3de.editor_test import EditorSingleTest, EditorSharedTest, EditorParallelTest, EditorTestSuite + + +@pytest.mark.SUITE_periodic +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(EditorTestSuite): + + class test_GradientGenerators_Incompatibilities(EditorSharedTest): + from .EditorScripts import GradientGenerators_Incompatibilities as test_module + + class test_GradientModifiers_Incompatibilities(EditorSharedTest): + from .EditorScripts import GradientModifiers_Incompatibilities as test_module + + class test_GradientPreviewSettings_DefaultPinnedEntityIsSelf(EditorSharedTest): + from .EditorScripts import GradientPreviewSettings_DefaultPinnedEntityIsSelf as test_module + + class test_GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin(EditorSharedTest): + from .EditorScripts import GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin as test_module + + class test_GradientSampling_GradientReferencesAddRemoveSuccessfully(EditorSharedTest): + from .EditorScripts import GradientSampling_GradientReferencesAddRemoveSuccessfully as test_module + + class test_GradientSurfaceTagEmitter_ComponentDependencies(EditorSharedTest): + from .EditorScripts import GradientSurfaceTagEmitter_ComponentDependencies as test_module + + class test_GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully(EditorSharedTest): + from .EditorScripts import GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully as test_module + + class test_GradientTransform_RequiresShape(EditorSharedTest): + from .EditorScripts import GradientTransform_RequiresShape as test_module + + class test_GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange(EditorSharedTest): + from .EditorScripts import GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange as test_module + + class test_GradientTransform_ComponentIncompatibleWithSpawners(EditorSharedTest): + from .EditorScripts import GradientTransform_ComponentIncompatibleWithSpawners as test_module + + class test_GradientTransform_ComponentIncompatibleWithExpectedGradients(EditorSharedTest): + from .EditorScripts import GradientTransform_ComponentIncompatibleWithExpectedGradients as test_module + + class test_ImageGradient_RequiresShape(EditorSharedTest): + from .EditorScripts import ImageGradient_RequiresShape as test_module + + class test_ImageGradient_ProcessedImageAssignedSuccessfully(EditorSharedTest): + from .EditorScripts import ImageGradient_ProcessedImageAssignedSuccessfully as test_module diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py index 913dc46fa5..9703423901 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py @@ -5,144 +5,147 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + dependencies_added = ( + "Node created new Entity with all required components", + "Failed to create node with all required components" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newEntityId = None -class TestAreaNodeComponentDependency(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="AreaNodeComponentDependency", args=["level"]) +def AreaNodes_DependentComponentsAdded(): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities with + proper dependent components. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities with - proper dependent components. + Expected Behavior: + All expected component dependencies are met when adding an area node to a graph. - Expected Behavior: - All expected component dependencies are met when adding an area node to a graph. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the area nodes to the graph area, and ensure the proper dependent components are added - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Drag each of the area nodes to the graph area, and ensure the proper dependent components are added + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math - def onEntityCreated(parameters): - global newEntityId - newEntityId = parameters[0] + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + def onEntityCreated(parameters): + global newEntityId + newEntityId = parameters[0] - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Listen for entity creation notifications so we can check if the entity created - # from adding these vegetation area nodes has the main target Vegetation Layer Component - # as well as automatically adding all required dependency components - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Vegetation area mapping with the key being the node name and the value is the - # expected Components that should be added to the Entity created for the node - areas = { - 'SpawnerAreaNode': [ - 'Vegetation Layer Spawner', - 'Vegetation Asset List', - 'Vegetation Reference Shape' - ], - 'MeshBlockerAreaNode': [ - 'Vegetation Layer Blocker (Mesh)', - 'Mesh' - ], - 'BlockerAreaNode': [ - 'Vegetation Layer Blocker', - 'Vegetation Reference Shape' - ] - } + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Retrieve a mapping of the TypeIds for all the components - # we will be checking for - componentNames = [] - for name in areas: - componentNames.extend(areas[name]) - componentTypeIds = hydra.get_component_type_id_map(componentNames) + # Listen for entity creation notifications so we can check if the entity created + # from adding these vegetation area nodes has the main target Vegetation Layer Component + # as well as automatically adding all required dependency components + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) - # Create nodes for the vegetation areas that have additional required dependencies and check if - # the Entity created by adding the node has the appropriate component and required - # additional components added automatically to it - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for nodeName in areas: - nodePosition = math.Vector2(x, y) - node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', - newGraph, nodeName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + # Vegetation area mapping with the key being the node name and the value is the + # expected Components that should be added to the Entity created for the node + areas = { + 'SpawnerAreaNode': [ + 'Vegetation Layer Spawner', + 'Vegetation Asset List', + 'Vegetation Reference Shape' + ], + 'MeshBlockerAreaNode': [ + 'Vegetation Layer Blocker (Mesh)', + 'Mesh' + ], + 'BlockerAreaNode': [ + 'Vegetation Layer Blocker', + 'Vegetation Reference Shape' + ] + } - components = areas[nodeName] - success = False - for component in components: - componentTypeId = componentTypeIds[component] - success = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, - componentTypeId) - if not success: - break - self.test_success = self.test_success and success - if success: - self.log("{node} created new Entity with all required components".format(node=nodeName)) + # Retrieve a mapping of the TypeIds for all the components + # we will be checking for + componentNames = [] + for name in areas: + componentNames.extend(areas[name]) + componentTypeIds = hydra.get_component_type_id_map(componentNames) - x += 40.0 - y += 40.0 + # Create nodes for the vegetation areas that have additional required dependencies and check if + # the Entity created by adding the node has the appropriate component and required + # additional components added automatically to it + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for nodeName in areas: + nodePosition = math.Vector2(x, y) + node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', + newGraph, nodeName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) - # Stop listening for entity creation notifications - handler.disconnect() + components = areas[nodeName] + success = False + for component in components: + componentTypeId = componentTypeIds[component] + success = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, + componentTypeId) + if not success: + break + Report.info(nodeName) + Report.result(Tests.dependencies_added, success) + + x += 40.0 + y += 40.0 + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestAreaNodeComponentDependency() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(AreaNodes_DependentComponentsAdded) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py index 2ee0c60a7d..f3f4a1862d 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py @@ -5,125 +5,129 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + component_added = ( + "New entity created with the expected component", + "Expected component was not found on entity" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newEntityId = None -class TestGradientNodeEntityCreate(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="AreaNodeEntityCreate", args=["level"]) +def AreaNodes_EntityCreatedOnNodeAdd(): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. + Expected Behavior: + New entities are created when dragging area nodes to graph area. - Expected Behavior: - New entities are created when dragging area nodes to graph area. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the area nodes to the graph area, and ensure a new entity is created - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Drag each of the area nodes to the graph area, and ensure a new entity is created + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ - def onEntityCreated(parameters): - global newEntityId - newEntityId = parameters[0] + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + def onEntityCreated(parameters): + global newEntityId + newEntityId = parameters[0] - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Listen for entity creation notifications so we can check if the entity created - # from adding vegetation area nodes has the appropriate Vegetation Layer Component - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Vegetation Area mapping with the key being the node name and the value is the - # expected Component that should be added to the Entity created for the node - areas = { - 'AreaBlenderNode': 'Vegetation Layer Blender', - 'BlockerAreaNode': 'Vegetation Layer Blocker', - 'MeshBlockerAreaNode': 'Vegetation Layer Blocker (Mesh)', - 'SpawnerAreaNode': 'Vegetation Layer Spawner' - } + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Retrieve a mapping of the TypeIds for all the components - # we will be checking for - componentNames = [] - for name in areas: - componentNames.append(areas[name]) - componentTypeIds = hydra.get_component_type_id_map(componentNames) + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Create nodes for all the vegetation areas we support and check if the Entity created by - # adding the node has the appropriate Component added automatically to it - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for nodeName in areas: - nodePosition = math.Vector2(x, y) - node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + # Listen for entity creation notifications so we can check if the entity created + # from adding vegetation area nodes has the appropriate Vegetation Layer Component + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) - areaComponent = areas[nodeName] - componentTypeId = componentTypeIds[areaComponent] - hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, componentTypeId) - self.test_success = self.test_success and hasComponent - if hasComponent: - self.log("{node} created new Entity with {component} Component".format(node=nodeName, component=areaComponent)) + # Vegetation Area mapping with the key being the node name and the value is the + # expected Component that should be added to the Entity created for the node + areas = { + 'AreaBlenderNode': 'Vegetation Layer Blender', + 'BlockerAreaNode': 'Vegetation Layer Blocker', + 'MeshBlockerAreaNode': 'Vegetation Layer Blocker (Mesh)', + 'SpawnerAreaNode': 'Vegetation Layer Spawner' + } - x += 40.0 - y += 40.0 + # Retrieve a mapping of the TypeIds for all the components + # we will be checking for + componentNames = [] + for name in areas: + componentNames.append(areas[name]) + componentTypeIds = hydra.get_component_type_id_map(componentNames) - # Stop listening for entity creation notifications - handler.disconnect() + # Create nodes for all the vegetation areas we support and check if the Entity created by + # adding the node has the appropriate Component added automatically to it + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for nodeName in areas: + nodePosition = math.Vector2(x, y) + node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + + areaComponent = areas[nodeName] + componentTypeId = componentTypeIds[areaComponent] + hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, componentTypeId) + Report.info(f"Node: {nodeName} | Component: {areaComponent}") + Report.result(Tests.component_added, hasComponent) + + x += 40.0 + y += 40.0 + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestGradientNodeEntityCreate() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(AreaNodes_EntityCreatedOnNodeAdd) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py index b9960447c6..f8b0539759 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py @@ -5,123 +5,128 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + entity_deleted = ( + "Entity was deleted when node was removed", + "Entity was not deleted as expected when node was removed" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID createdEntityId = None deletedEntityId = None -class TestAreaNodeEntityDelete(EditorTestHelper): +def AreaNodes_EntityRemovedOnNodeDelete(): + """ + Summary: + This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="AreaNodeEntityDelete", args=["level"]) + Expected Behavior: + Entities are removed when area nodes are deleted from a graph. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the area nodes to the graph area, and ensure a new entity is created + 4) Delete the nodes, and ensure the newly created entities are removed - Expected Behavior: - Entities are removed when area nodes are deleted from a graph. + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Drag each of the area nodes to the graph area, and ensure a new entity is created - 4) Delete the nodes, and ensure the newly created entities are removed + :return: None + """ - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.paths - :return: None - """ - def onEntityCreated(parameters): - global createdEntityId - createdEntityId = parameters[0] + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - def onEntityDeleted(parameters): - global deletedEntityId - deletedEntityId = parameters[0] + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) + def onEntityCreated(parameters): + global createdEntityId + createdEntityId = parameters[0] - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + def onEntityDeleted(parameters): + global deletedEntityId + deletedEntityId = parameters[0] - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Listen for entity creation notifications so we can check if the entity created - # from adding gradient nodes has the appropriate Gradient Component - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) - handler.add_callback('OnEditorEntityDeleted', onEntityDeleted) + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Vegetation Area mapping with the key being the node name and the value is the - # expected Component that should be added to the Entity created for the node - areas = [ - 'AreaBlenderNode', - 'BlockerAreaNode', - 'MeshBlockerAreaNode', - 'SpawnerAreaNode', - ] + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Create nodes for all the gradients we support and check if the Entity created by - # adding the node has the appropriate Component added automatically to it - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for nodeName in areas: - nodePosition = math.Vector2(x, y) - node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + # Listen for entity creation notifications so we can check if the entity created + # from adding gradient nodes has the appropriate Gradient Component + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) + handler.add_callback('OnEditorEntityDeleted', onEntityDeleted) - removed = graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', newGraphId, node) + # Vegetation Area mapping with the key being the node name and the value is the + # expected Component that should be added to the Entity created for the node + areas = [ + 'AreaBlenderNode', + 'BlockerAreaNode', + 'MeshBlockerAreaNode', + 'SpawnerAreaNode', + ] - # Verify that the created Entity for this node matches the Entity that gets - # deleted when the node is removed - self.test_success = self.test_success and removed and createdEntityId.invoke("Equal", deletedEntityId) - if removed and createdEntityId.invoke("Equal", deletedEntityId): - self.log("{node} corresponding Entity was deleted when node is removed".format(node=nodeName)) + # Create nodes for all the gradients we support and check if the Entity created by + # adding the node has the appropriate Component added automatically to it + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for nodeName in areas: + nodePosition = math.Vector2(x, y) + node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, + nodeName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) - # Stop listening for entity creation notifications - handler.disconnect() + removed = graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', newGraphId, node) + + # Verify that the created Entity for this node matches the Entity that gets + # deleted when the node is removed + Report.info(f"Node: {nodeName}") + Report.result(Tests.entity_deleted, removed and createdEntityId.invoke("Equal", deletedEntityId)) + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestAreaNodeEntityDelete() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(AreaNodes_EntityRemovedOnNodeDelete) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py index a704cc9dab..cc40d8b861 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py @@ -5,197 +5,209 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.asset as asset -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.entity as entity -import azlmbr.legacy.general as general -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.math as math -import azlmbr.slice as slice -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper +class Tests: + slice_instantiated = ( + "Slice instantiated successfully", + "Failed to instantiate slice" + ) + lc_entity_found = ( + "LandscapeCanvas entity found", + "Failed to find LandscapeCanvas entity" + ) + spawner_entity_found = ( + "BushSpawner entity found", + "Failed to find BushSpawner entity" + ) + dist_filter_component_found = ( + "Vegetation Distribution Filter component on BushSpawner entity found", + "Failed to find Distribution Filter component on BushSpawner entity" + ) + existing_graph_opened = ( + "Opened existing graph from slice", + "Failed to open existing graph" + ) + dist_filter_node_found = ( + "Vegetation Distribution Filter node found on graph", + "Failed to find Distribution Filter node on graph" + ) + alt_filter_component_found = ( + "Vegetation Altitude Filter component on BushSpawner entity found", + "Failed to find Altitude Filter component on BushSpawner entity" + ) + alt_filter_node_found = ( + "Vegetation Altitude Filter node found on graph", + "Failed to find Altitude Filter node on graph" + ) + dist_filter_component_removed = ( + "Vegetation Distribution Filter component removed from BushSpawner entity", + "Failed to remove Distribution Filter component from BushSpawner entity" + ) + dist_filter_node_removed = ( + "Vegetation Distribution Filter node removed from graph", + "Failed to remove Distribution Filter node from graph" + ) + child_entity_added = ( + "New entity successfully added as a child of the BushSpawner entity", + "New entity added with an unexpected parent" + ) + box_shape_component_found = ( + "Box Shape component on Box entity found", + "Failed to find Box Shape component on Box entity" + ) + box_shape_node_found = ( + "Box Shape node found on graph", + "Failed to find Box Shape node on graph" + ) -class TestComponentUpdatesUpdateGraph(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="ComponentUpdatesUpdateGraph", args=["level"]) +def ComponentUpdates_UpdateGraph(): + """ + Summary: + This test verifies that the Landscape Canvas graphs update properly when components are added/removed outside of + Landscape Canvas. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas graphs update properly when components are added/removed outside of - Landscape Canvas. + Expected Behavior: + Graphs properly reflect component changes made to entities outside of Landscape Canvas. - Expected Behavior: - Graphs properly reflect component changes made to entities outside of Landscape Canvas. + Test Steps: + 1. Open Level + 2. Find LandscapeCanvas named entity + 3. Ensure Vegetation Distribution Component is present on the BushSpawner entity + 4. Open graph and ensure Distribution Filter wrapped node is present + 5. Delete the Vegetation Distribution Filter component from the BushSpawner entity via Entity Inspector + 6. Ensure the Vegetation Distribution Filter component was deleted from the BushSpawner entity and node is + no longer present in the graph + 7. Add Vegetation Altitude Filter to the BushSpawner entity through Entity Inspector + 8. Ensure Altitude Filter was added to the BushSpawner node in the open graph + 9. Add a new entity with unique name as a child of the Landscape Canvas entity + 10. Add a Box Shape component to the new child entity + 11. Ensure Box Shape node is present on the open graph - Test Steps: - 1. Open Level - 2. Find LandscapeCanvas named entity - 3. Ensure Vegetation Distribution Component is present on the BushSpawner entity - 4. Open graph and ensure Distribution Filter wrapped node is present - 5. Delete the Vegetation Distribution Filter component from the BushSpawner entity via Entity Inspector - 6. Ensure the Vegetation Distribution Filter component was deleted from the BushSpawner entity and node is - no longer present in the graph - 7. Add Vegetation Altitude Filter to the BushSpawner entity through Entity Inspector - 8. Ensure Altitude Filter was added to the BushSpawner node in the open graph - 9. Add a new entity with unique name as a child of the Landscape Canvas entity - 10. Add a Box Shape component to the new child entity - 11. Ensure Box Shape node is present on the open graph + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import os - # Create a new empty level and instantiate LC_BushFlowerBlender.slice - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) - transform = math.Transform_CreateIdentity() - position = math.Vector3(64.0, 64.0, 32.0) - transform.invoke('SetPosition', position) - test_slice_path = os.path.join("Slices", "LC_BushFlowerBlender.slice") - test_slice_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", test_slice_path, math.Uuid(), - False) - test_slice = slice.SliceRequestBus(bus.Broadcast, 'InstantiateSliceFromAssetId', test_slice_id, transform) - self.test_success = self.test_success and test_slice.IsValid() - if test_slice.IsValid(): - self.log("Slice spawned!") + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.entity as entity + import azlmbr.legacy.general as general + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.math as math + import azlmbr.slice as slice - # Find root entity in the loaded level - search_filter = entity.SearchFilter() - search_filter.names = ["LandscapeCanvas"] + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Allow a few seconds for matching entity to be found - self.wait_for_condition(lambda: len(entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter)) > 0, 5.0) - lc_matching_entities = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) - slice_root_id = lc_matching_entities[0] #Entity with Landscape Canvas component - self.test_success = self.test_success and slice_root_id.IsValid() - if slice_root_id.IsValid(): - self.log("LandscapeCanvas entity found") + # Open a simple level and instantiate LC_BushFlowerBlender.slice + helper.init_idle() + helper.open_level("Physics", "Base") + transform = math.Transform_CreateIdentity() + position = math.Vector3(64.0, 64.0, 32.0) + transform.invoke('SetPosition', position) + test_slice_path = os.path.join("Slices", "LC_BushFlowerBlender.slice") + test_slice_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", test_slice_path, math.Uuid(), + False) + test_slice = slice.SliceRequestBus(bus.Broadcast, 'InstantiateSliceFromAssetId', test_slice_id, transform) + Report.critical_result(Tests.slice_instantiated, test_slice.IsValid()) - # Find the BushSpawner entity - search_filter.names = ["BushSpawner"] - spawner_matching_entities = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) - spawner_id = spawner_matching_entities[0] #Entity with Vegetation Layer Spawner component - self.test_success = self.test_success and spawner_id.IsValid() - if spawner_id.IsValid(): - self.log("BushSpawner entity found") + # Find root entity in the loaded level + search_filter = entity.SearchFilter() + search_filter.names = ["LandscapeCanvas"] - # Get needed component type ids - distribution_filter_type_id = hydra.get_component_type_id("Vegetation Distribution Filter") - altitude_filter_type_id = hydra.get_component_type_id("Vegetation Altitude Filter") - box_shape_type_id = hydra.get_component_type_id("Box Shape") + # Allow a few seconds for matching entity to be found + helper.wait_for_condition(lambda: len(entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter)) > 0, 5.0) + lc_matching_entities = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) + slice_root_id = lc_matching_entities[0] #Entity with Landscape Canvas component + Report.critical_result(Tests.lc_entity_found, slice_root_id.IsValid()) - # Verify the BushSpawner entity has a Distribution Filter - has_distribution_filter = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', spawner_id, - distribution_filter_type_id) - self.test_success = self.test_success and has_distribution_filter - if has_distribution_filter: - self.log("Vegetation Distribution Filter on BushSpawner entity found") + # Find the BushSpawner entity + search_filter.names = ["BushSpawner"] + spawner_matching_entities = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) + spawner_id = spawner_matching_entities[0] #Entity with Vegetation Layer Spawner component + Report.critical_result(Tests.spawner_entity_found, spawner_id.IsValid()) - # Open Landscape Canvas and the existing graph - general.open_pane('Landscape Canvas') - open_graph = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'OnGraphEntity', slice_root_id) - self.test_success = self.test_success and open_graph.IsValid() - if open_graph.IsValid(): - self.log("Graph opened") + # Get needed component type ids + distribution_filter_type_id = hydra.get_component_type_id("Vegetation Distribution Filter") + altitude_filter_type_id = hydra.get_component_type_id("Vegetation Altitude Filter") + box_shape_type_id = hydra.get_component_type_id("Box Shape") - # Verify that Distribution Filter node is present on the graph - spawner_distribution_filter_component = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', spawner_id, - distribution_filter_type_id) - spawner_distribution_filter_component_id = spawner_distribution_filter_component.GetValue() - distribution_filter_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, - 'GetNodeMatchingEntityComponentInGraph', - open_graph, - spawner_distribution_filter_component_id) - self.test_success = self.test_success and distribution_filter_node is not None - if distribution_filter_node is not None: - self.log("Distribution Filter node found on graph") - else: - self.log("Distribution Filter node not found on graph") + # Verify the BushSpawner entity has a Distribution Filter + has_distribution_filter = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', spawner_id, + distribution_filter_type_id) + Report.critical_result(Tests.dist_filter_component_found, has_distribution_filter) - # Add a Vegetation Altitude Filter component to the BushSpawner entity, and verify the node is added to the graph - spawner_altitude_filter_component = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', spawner_id, - altitude_filter_type_id) - spawner_altitude_filter_component_id = spawner_altitude_filter_component.GetValue() - editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentOfType', spawner_id, altitude_filter_type_id) - has_altitude_filter = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', spawner_id, - altitude_filter_type_id) - altitude_filter_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'GetNodeMatchingEntityComponentInGraph', - open_graph, spawner_altitude_filter_component_id) - self.test_success = self.test_success and has_altitude_filter and altitude_filter_node is not None - if has_altitude_filter: - self.log("Vegetation Altitude Filter on BushSpawner entity found") + # Open Landscape Canvas and the existing graph + general.open_pane('Landscape Canvas') + open_graph = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'OnGraphEntity', slice_root_id) + Report.critical_result(Tests.existing_graph_opened, open_graph.IsValid()) - if altitude_filter_node is not None: - self.log("Altitude Filter node found on graph") - else: - self.log("Altitude Filter node not found on graph") + # Verify that Distribution Filter node is present on the graph + spawner_distribution_filter_component = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', spawner_id, + distribution_filter_type_id) + spawner_distribution_filter_component_id = spawner_distribution_filter_component.GetValue() + distribution_filter_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, + 'GetNodeMatchingEntityComponentInGraph', + open_graph, + spawner_distribution_filter_component_id) + Report.critical_result(Tests.dist_filter_node_found, distribution_filter_node is not None) - # Remove the Distribution Filter - editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', [spawner_distribution_filter_component_id]) - general.idle_wait(1.0) + # Add a Vegetation Altitude Filter component to the BushSpawner entity, and verify the node is added to the graph + spawner_altitude_filter_component = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', spawner_id, + altitude_filter_type_id) + spawner_altitude_filter_component_id = spawner_altitude_filter_component.GetValue() + editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentOfType', spawner_id, altitude_filter_type_id) + has_altitude_filter = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', spawner_id, + altitude_filter_type_id) + altitude_filter_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'GetNodeMatchingEntityComponentInGraph', + open_graph, spawner_altitude_filter_component_id) + Report.result(Tests.dist_filter_component_found, has_altitude_filter) + Report.result(Tests.dist_filter_node_found, altitude_filter_node is not None) - # Verify the Distribution Filter was successfully removed from entity and the node was likewise removed - has_distribution_filter = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', spawner_id, - distribution_filter_type_id) - self.test_success = self.test_success and not has_distribution_filter - if not has_distribution_filter: - self.log("Vegetation Distribution Filter removed from BushSpawner entity") + # Remove the Distribution Filter + editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', [spawner_distribution_filter_component_id]) + general.idle_wait(1.0) - distribution_filter_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, - 'GetAllNodesMatchingEntityComponent', - spawner_distribution_filter_component_id) - self.test_success = self.test_success and not distribution_filter_node - if distribution_filter_node: - self.log("Distribution Filter node is still present on the graph") - else: - self.log("Distribution Filter node was removed from the graph") + # Verify the Distribution Filter was successfully removed from entity and the node was likewise removed + has_distribution_filter = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', spawner_id, + distribution_filter_type_id) + Report.result(Tests.dist_filter_component_removed, not has_distribution_filter) - # Add a new child entity of BushSpawner entity - box_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', spawner_id) - if editor.EditorEntityInfoRequestBus(bus.Event, 'GetParent', box_id) == spawner_id: - self.log("New entity successfully added as a child of the BushSpawner entity") - else: - self.log("New entity added with an unexpected parent") + distribution_filter_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, + 'GetAllNodesMatchingEntityComponent', + spawner_distribution_filter_component_id) + Report.result(Tests.dist_filter_node_removed, not distribution_filter_node) - # Add a Box Shape component to the new entity and verify it was properly added - editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentOfType', box_id, box_shape_type_id) - has_box_shape = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', box_id, - box_shape_type_id) - self.test_success = self.test_success and has_box_shape - if has_box_shape: - self.log("Box Shape on Box entity found") + # Add a new child entity of BushSpawner entity + box_id = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', spawner_id) + Report.result(Tests.child_entity_added, editor.EditorEntityInfoRequestBus(bus.Event, 'GetParent', box_id) == + spawner_id) - # Verify the Box Shape node appear on the graph - box_shape_component = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', box_id, - box_shape_type_id) + # Add a Box Shape component to the new entity and verify it was properly added + editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentOfType', box_id, box_shape_type_id) + has_box_shape = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', box_id, + box_shape_type_id) + Report.result(Tests.box_shape_component_found, has_box_shape) - box_shape_component_id = box_shape_component.GetValue() - box_shape_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'GetAllNodesMatchingEntityComponent', - box_shape_component_id) - self.test_success = self.test_success and box_shape_node is not None - if box_shape_node is not None: - self.log("Box Shape node found on graph") - else: - self.log("Box Shape node not found on graph") + # Verify the Box Shape node appears on the graph + box_shape_component = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', box_id, + box_shape_type_id) + + box_shape_component_id = box_shape_component.GetValue() + box_shape_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'GetAllNodesMatchingEntityComponent', + box_shape_component_id) + Report.result(Tests.box_shape_node_found, box_shape_node is not None) -test = TestComponentUpdatesUpdateGraph() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(ComponentUpdates_UpdateGraph) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Component_AddedRemoved.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Component_AddedRemoved.py new file mode 100644 index 0000000000..7f21a26595 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Component_AddedRemoved.py @@ -0,0 +1,80 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + + +class Tests: + lc_component_added = ( + "Landscape Canvas component successfully added to entity", + "Failed to add Landscape Canvas component to entity" + ) + lc_component_removed = ( + "Landscape Canvas component successfully removed from entity", + "Failed to remove Landscape Canvas component from entity" + ) + + +def Component_AddedRemoved(): + """ + Summary: + This test verifies that the Landscape Canvas component can be added to/removed from an entity. + + Expected Behavior: + Closing a tabbed graph only closes the appropriate graph. + + Test Steps: + 1) Open a simple level + 2) Create a new entity + 3) Add a Landscape Canvas component to the entity + 4) Remove the Landscape Canvas component from the entity + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.entity as entity + + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + # Create an Entity at the root of the level + newEntityId = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) + + # Find the component TypeId for our Landscape Canvas component + landscape_canvas_type_id = hydra.get_component_type_id("Landscape Canvas") + + # Add the Landscape Canvas Component to our Entity + componentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentsOfType', newEntityId, [landscape_canvas_type_id]) + components = componentOutcome.GetValue() + landscapeCanvasComponent = components[0] + + # Validate the Landscape Canvas Component exists + hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, landscape_canvas_type_id) + Report.result(Tests.lc_component_added, hasComponent) + + # Remove the Landscape Canvas Component + editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', [landscapeCanvasComponent]) + + # Validate the Landscape Canvas Component is no longer on our Entity + hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, landscape_canvas_type_id) + Report.result(Tests.lc_component_removed, not hasComponent) + + +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(Component_AddedRemoved) \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/CreateNewGraph.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/CreateNewGraph.py deleted file mode 100755 index 971134becf..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/CreateNewGraph.py +++ /dev/null @@ -1,106 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import sys - -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.legacy.general as general -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper - -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID -new_root_entity_id = None - - -class TestCreateNewGraph(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="CreateNewGraph", args=["level"]) - - def on_entity_created(self, parameters): - global new_root_entity_id - new_root_entity_id = parameters[0] - - print("New root entity created") - - def run_test(self): - """ - Summary: - This test verifies that new graphs can be created in Landscape Canvas. - - Expected Behavior: - New graphs can be created, and proper entity is created to hold graph data with a Landscape Canvas component. - - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Ensures the root entity created contains a Landscape Canvas component - - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. - - :return: None - """ - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) - # Open Landscape Canvas tool and verify - general.open_pane("Landscape Canvas") - self.test_success = self.test_success and general.is_pane_visible("Landscape Canvas") - if general.is_pane_visible("Landscape Canvas"): - self.log("Landscape Canvas pane is open") - - # Listen for entity creation notifications so we can check if the entity created - # with the new graph has our Landscape Canvas component automatically added - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback("OnEditorEntityCreated", self.on_entity_created) - - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, "CreateNewGraph", editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") - - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, "ContainsGraph", editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") - - # Check if the entity created when we create a new graph has the - # Landscape Canvas component already added to it - landscape_canvas_type_id = hydra.get_component_type_id("Landscape Canvas") - success = editor.EditorComponentAPIBus(bus.Broadcast, "HasComponentOfType", new_root_entity_id, - landscape_canvas_type_id) - self.test_success = self.test_success and success - if success: - self.log("Root entity has Landscape Canvas component") - - # Close Landscape Canvas tool and verify - general.close_pane("Landscape Canvas") - self.test_success = self.test_success and not general.is_pane_visible("Landscape Canvas") - if not general.is_pane_visible("Landscape Canvas"): - self.log("Landscape Canvas pane is closed") - - # Stop listening for entity creation notifications - handler.disconnect() - - -test = TestCreateNewGraph() -test.run() diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py index b2b9e63a56..417e093567 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py @@ -5,131 +5,132 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newEntityId = None -class TestDisabledNodeDuplication(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="DisabledNodeDuplication", args=["level"]) +def Edit_DisabledNodeDuplication(): + """ + Summary: + This test verifies Editor stability after duplicating disabled Landscape Canvas nodes. - def run_test(self): - """ - Summary: - This test verifies Editor stability after duplicating disabled Landscape Canvas nodes. + Expected Behavior: + Editor remains stable and free of crashes. - Expected Behavior: - Editor remains stable and free of crashes. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Create several new nodes, disable the nodes via disabling/deleting components, and duplicate the nodes - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Create several new nodes, disable the nodes via disabling/deleting components, and duplicate the nodes + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ - def onEntityCreated(parameters): - global newEntityId - newEntityId = parameters[0] + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + def onEntityCreated(parameters): + global newEntityId + newEntityId = parameters[0] - # Listen for entity creation notifications so when we add a new node - # we can access the corresponding Entity that was created so that we - # can disable/remove components on that Entity - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Mapping of our Landscape Canvas nodes with corresponding dependent components - # that we can disable/remove to reproduce the crash - nodes = { - 'SpawnerAreaNode': 'Vegetation Asset List', - 'MeshBlockerAreaNode': 'Mesh', - 'BlockerAreaNode': 'Vegetation Reference Shape', - 'FastNoiseGradientNode': 'Gradient Transform Modifier', - 'ImageGradientNode': 'Gradient Transform Modifier', - 'PerlinNoiseGradientNode': 'Gradient Transform Modifier', - 'RandomNoiseGradientNode': 'Gradient Transform Modifier' - } + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Retrieve a mapping of the TypeIds for all the components - # we will be checking for - componentNames = list(set(nodes.values())) # Convert to set then back to list to remove any duplicates - componentTypeIds = hydra.get_component_type_id_map(componentNames) + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Iterate through creating our nodes and then disabling/deleting required components - # and then duplicating the node to reproduce the crash - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for nodeName in nodes: - nodePosition = math.Vector2(x, y) - node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + # Listen for entity creation notifications so when we add a new node + # we can access the corresponding Entity that was created so that we + # can disable/remove components on that Entity + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) - dependentComponentName = nodes[nodeName] - componentTypeId = componentTypeIds[dependentComponentName] - componentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', newEntityId, componentTypeId) - component = componentOutcome.GetValue() + # Mapping of our Landscape Canvas nodes with corresponding dependent components + # that we can disable/remove to reproduce the crash + nodes = { + 'SpawnerAreaNode': 'Vegetation Asset List', + 'MeshBlockerAreaNode': 'Mesh', + 'BlockerAreaNode': 'Vegetation Reference Shape', + 'FastNoiseGradientNode': 'Gradient Transform Modifier', + 'ImageGradientNode': 'Gradient Transform Modifier', + 'PerlinNoiseGradientNode': 'Gradient Transform Modifier', + 'RandomNoiseGradientNode': 'Gradient Transform Modifier' + } - # First make sure we can duplicate a node with a dependent component that is disabled - editor.EditorComponentAPIBus(bus.Broadcast, 'DisableComponents', [component]) - general.idle_wait(1.0) - graph.SceneRequestBus(bus.Event, 'DuplicateSelection', newGraphId) # This duplication would cause a crash without the fix - self.log("{node} duplicated with disabled component".format(node=nodeName)) + # Retrieve a mapping of the TypeIds for all the components + # we will be checking for + componentNames = list(set(nodes.values())) # Convert to set then back to list to remove any duplicates + componentTypeIds = hydra.get_component_type_id_map(componentNames) - # Then, make sure we can duplicate the node with a dependent component that is deleted - editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', [component]) - general.idle_wait(1.0) - graph.SceneRequestBus(bus.Event, 'DuplicateSelection', newGraphId) # This duplication would cause a crash without the fix - self.log("{node} duplicated with deleted component".format(node=nodeName)) + # Iterate through creating our nodes and then disabling/deleting required components + # and then duplicating the node to reproduce the crash + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for nodeName in nodes: + nodePosition = math.Vector2(x, y) + node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) - x += 40.0 - y += 40.0 + dependentComponentName = nodes[nodeName] + componentTypeId = componentTypeIds[dependentComponentName] + componentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', newEntityId, componentTypeId) + component = componentOutcome.GetValue() - # Stop listening for entity creation notifications - handler.disconnect() + # First make sure we can duplicate a node with a dependent component that is disabled + editor.EditorComponentAPIBus(bus.Broadcast, 'DisableComponents', [component]) + helper.wait_for_condition(lambda: not editor.EditorComponentAPIBus(bus.Broadcast, 'IsComponentEnabled', + [component]), 1.0) + graph.SceneRequestBus(bus.Event, 'DuplicateSelection', newGraphId) # This duplication would cause a crash without the fix + Report.info("{node} duplicated with disabled component".format(node=nodeName)) + + # Then, make sure we can duplicate the node with a dependent component that is deleted + editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', [component]) + helper.wait_for_condition(lambda: not editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', + componentTypeIds[dependentComponentName]), 1.0) + graph.SceneRequestBus(bus.Event, 'DuplicateSelection', newGraphId) # This duplication would cause a crash without the fix + Report.info("{node} duplicated with deleted component".format(node=nodeName)) + + x += 40.0 + y += 40.0 + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestDisabledNodeDuplication() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(Edit_DisabledNodeDuplication) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py index a651567f85..a26e16755f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py @@ -5,133 +5,134 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.asset as asset -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.entity as entity -import azlmbr.legacy.general as general -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.math as math -import azlmbr.slice as slice -import azlmbr.paths +class Tests: + slice_spawned = ( + "Slice instantiated successfully", + "Failed to instantiate slice" + ) + lc_entity_found = ( + "Landscape Canvas entity found", + "Failed to find Landscape Canvas entity" + ) + spawner_entity_found = ( + "Spawner entity found", + "Failed to find Spawner entity" + ) + graph_opened = ( + "Graph successfully opened", + "Graph failed to open" + ) + spawner_node_found = ( + "Vegetation Layer Spawner node found on graph", + "Failed to find Vegetation Layer Spawner node on graph" + ) + spawner_node_removed = ( + "Vegetation Layer Spawner node was successfully removed", + "Failed to remove Vegetation Layer Spawner node" + ) +def Edit_UndoNodeDelete_SliceEntity(): + """ + Summary: + This test verifies Editor stability after undoing the deletion of nodes on a slice entity. -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper + Expected Behavior: + Editor remains stable and free of crashes. + + Test Steps: + 1) Open a simple level + 2) Instantiate a slice with a Landscape Canvas setup + 3) Find a specific node on the graph, and delete it + 4) Restore the node with Undo + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + import os + + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.entity as entity + import azlmbr.legacy.general as general + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.math as math + import azlmbr.slice as slice + + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + # Instantiate slice + transform = math.Transform_CreateIdentity() + position = math.Vector3(64.0, 64.0, 32.0) + transform.invoke('SetPosition', position) + test_slice_path = os.path.join("Slices", "LC_BushFlowerBlender.slice") + test_slice_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", test_slice_path, math.Uuid(), + False) + test_slice = slice.SliceRequestBus(bus.Broadcast, 'InstantiateSliceFromAssetId', test_slice_id, transform) + Report.result(Tests.slice_spawned, test_slice.IsValid()) + + # Find root entity in the loaded level + search_filter = entity.SearchFilter() + search_filter.names = ["LandscapeCanvas"] + + # Allow a few seconds for matching entity to be found + helper.wait_for_condition(lambda: len(entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter)) > 0, 5.0) + lc_matching_entities = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) + slice_root_id = lc_matching_entities[0] # Entity with Landscape Canvas component + Report.result(Tests.lc_entity_found, slice_root_id.IsValid()) + + # Find the BushSpawner entity + search_filter.names = ["BushSpawner"] + spawner_matching_entities = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) + spawner_id = spawner_matching_entities[0] # Entity with Vegetation Layer Spawner component + Report.result(Tests.spawner_entity_found, spawner_id.IsValid()) + + # Open Landscape Canvas and the existing graph + general.open_pane('Landscape Canvas') + open_graph = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'OnGraphEntity', slice_root_id) + Report.result(Tests.graph_opened, open_graph.IsValid()) + + # Get needed component type ids + layer_spawner_type_id = hydra.get_component_type_id("Vegetation Layer Spawner") + + # Find the Vegetation Layer Spawner node on the BushSpawner entity + layer_spawner_component = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', spawner_id, + layer_spawner_type_id) + layer_spawner_component_component_id = layer_spawner_component.GetValue() + layer_spawner_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'GetAllNodesMatchingEntityComponent', + layer_spawner_component_component_id) + Report.result(Tests.spawner_node_found, layer_spawner_node is not None) + + # Remove the Layer Spawner node + graph.GraphControllerRequestBus(bus.Event, "RemoveNode", open_graph, layer_spawner_node[0]) + + # Verify node was removed + layer_spawner_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'GetAllNodesMatchingEntityComponent', + layer_spawner_component_component_id) + Report.result(Tests.spawner_node_removed, not layer_spawner_node) + + # Undo the Node deletion. This is required to be executed twice to hit the node removal. + general.undo() + general.undo() + + # self.log a line to the Console to verify the Editor is still active + Report.info("Editor is still responsive") -class TestUndoNodeDeleteSlice(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="UndoNodeDeleteSlice", args=["level"]) +if __name__ == "__main__": - def run_test(self): - """ - Summary: - This test verifies Editor stability after undoing the deletion of nodes on a slice entity. + from editor_python_test_tools.utils import Report + Report.start_test(Edit_UndoNodeDelete_SliceEntity) - Expected Behavior: - Editor remains stable and free of crashes. - - Test Steps: - 1) Create a new level - 2) Instantiate a slice with a Landscape Canvas setup - 3) Find a specific node on the graph, and delete it - 4) Restore the node with Undo - - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. - - :return: None - """ - # Create a new empty level and instantiate LC_BushFlowerBlender.slice - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) - transform = math.Transform_CreateIdentity() - position = math.Vector3(64.0, 64.0, 32.0) - transform.invoke('SetPosition', position) - test_slice_path = os.path.join("Slices", "LC_BushFlowerBlender.slice") - test_slice_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", test_slice_path, math.Uuid(), - False) - test_slice = slice.SliceRequestBus(bus.Broadcast, 'InstantiateSliceFromAssetId', test_slice_id, transform) - self.test_success = self.test_success and test_slice.IsValid() - if test_slice.IsValid(): - self.log("Slice spawned!") - - # Find root entity in the loaded level - search_filter = entity.SearchFilter() - search_filter.names = ["LandscapeCanvas"] - - # Allow a few seconds for matching entity to be found - self.wait_for_condition(lambda: len(entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter)) > 0, - 5.0) - lc_matching_entities = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) - slice_root_id = lc_matching_entities[0] # Entity with Landscape Canvas component - self.test_success = self.test_success and slice_root_id.IsValid() - if slice_root_id.IsValid(): - self.log("LandscapeCanvas entity found") - - # Find the BushSpawner entity - search_filter.names = ["BushSpawner"] - spawner_matching_entities = entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter) - spawner_id = spawner_matching_entities[0] # Entity with Vegetation Layer Spawner component - self.test_success = self.test_success and spawner_id.IsValid() - if spawner_id.IsValid(): - self.log("BushSpawner entity found") - - # Open Landscape Canvas and the existing graph - general.open_pane('Landscape Canvas') - open_graph = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'OnGraphEntity', slice_root_id) - self.test_success = self.test_success and open_graph.IsValid() - if open_graph.IsValid(): - self.log("Graph opened") - - # Get needed component type ids - layer_spawner_type_id = hydra.get_component_type_id("Vegetation Layer Spawner") - - # Find the Vegetation Layer Spawner node on the BushSpawner entity - layer_spawner_component = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', spawner_id, - layer_spawner_type_id) - layer_spawner_component_component_id = layer_spawner_component.GetValue() - layer_spawner_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'GetAllNodesMatchingEntityComponent', - layer_spawner_component_component_id) - - self.test_success = self.test_success and layer_spawner_node - if layer_spawner_node: - self.log("Vegetation Layer Spawner node found on graph") - else: - self.log("Vegetation Layer Spawner node not found") - - # Remove the Layer Spawner node - graph.GraphControllerRequestBus(bus.Event, "RemoveNode", open_graph, layer_spawner_node[0]) - - # Verify node was removed - layer_spawner_node = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'GetAllNodesMatchingEntityComponent', - layer_spawner_component_component_id) - - self.test_success = self.test_success and not layer_spawner_node - if not layer_spawner_node: - self.log("Vegetation Layer Spawner node was removed") - else: - self.log("Vegetation Layer Spawner node was not removed") - - # Undo the Node deletion. This is required to be executed twice to hit the node removal. - general.undo() - general.undo() - - # self.log a line to the Console to verify the Editor is still active - self.log("Editor is still responsive") - - -test = TestUndoNodeDeleteSlice() -test.run() diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py index 341e6d3367..c390df7c61 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py @@ -5,190 +5,205 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.entity as entity -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + preview_entity_set = ( + "Perlin Noise Gradient component Preview Entity property set to Box Shape EntityId", + "Unexpected entity set in Perlin Noise Gradient Preview Entity property" + ) + mixer_inbound_gradient_set_a = ( + "Gradient Mixer component Inbound Gradient extendable property set to Perlin Noise Gradient EntityId", + "Unexpected entity set in Gradient Mixer's Inbound Gradient property" + ) + mixer_inbound_gradient_set_b = ( + "Gradient Mixer component Inbound Gradient extendable property set to FastNoise Gradient EntityId", + "Unexpected entity set in Gradient Mixer's Inbound Gradient property" + ) + mixer_operation_a = ( + "Layer 1 Operation is set to Initialize", + "Layer 1 Operation is not set to Initialize as expected" + ) + mixer_operation_b = ( + "Layer 2 Operation is set to Average", + "Layer 2 Operation is not set to Average as expected" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper - -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newEntityId = None -class TestGradientMixerNodeConstruction(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientMixerNodeConstruction", args=["level"]) +def GradientMixer_NodeConstruction(): + """ + Summary: + This test verifies a Gradient Mixer vegetation setup can be constructed through Landscape Canvas. - def run_test(self): - """ - Summary: - This test verifies a Gradient Mixer vegetation setup can be constructed through Landscape Canvas. + Expected Behavior: + Entities contain all required components and component references after creating nodes and setting connections + on a Landscape Canvas graph. - Expected Behavior: - Entities contain all required components and component references after creating nodes and setting connections - on a Landscape Canvas graph. + Test Steps: + 1) Create a new level + 2) Open Landscape Canvas and create a new graph + 3) Add all necessary nodes to the graph and set connections to form a Gradient Mixer setup + 4) Verify all components and component references were properly set during graph construction - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Add all necessary nodes to the graph and set connections to form a Gradient Mixer setup - 4) Verify all components and component references were properly set during graph construction + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.paths - def onEntityCreated(parameters): - global newEntityId - newEntityId = parameters[0] + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + def onEntityCreated(parameters): + global newEntityId + newEntityId = parameters[0] - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Listen for entity creation notifications so we can verify the component EntityId - # references are set correctly when connecting slots on the nodes - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - positionX = 10.0 - positionY = 10.0 - offsetX = 340.0 - offsetY = 100.0 + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Add a Box Shape node to the graph - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - boxShapeNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, - 'BoxShapeNode') - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, boxShapeNode, math.Vector2(positionX, positionY)) - boxShapeEntityId = newEntityId + # Listen for entity creation notifications so we can verify the component EntityId + # references are set correctly when connecting slots on the nodes + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) - positionX += offsetX - positionY += offsetY + positionX = 10.0 + positionY = 10.0 + offsetX = 340.0 + offsetY = 100.0 - # Add a Random Noise Gradient node to the graph - perlinNoiseNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, - 'PerlinNoiseGradientNode') - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, perlinNoiseNode, math.Vector2(positionX, positionY)) - perlinNoiseEntityId = newEntityId + # Add a Box Shape node to the graph + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + boxShapeNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, + 'BoxShapeNode') + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, boxShapeNode, math.Vector2(positionX, positionY)) + boxShapeEntityId = newEntityId - positionX += offsetX - positionY += offsetY + positionX += offsetX + positionY += offsetY - # Add a FastNoise Gradient node to the graph - fastNoiseNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, - 'FastNoiseGradientNode') - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, fastNoiseNode, math.Vector2(positionX, positionY)) - fastNoiseEntityId = newEntityId + # Add a Random Noise Gradient node to the graph + perlinNoiseNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, + 'PerlinNoiseGradientNode') + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, perlinNoiseNode, math.Vector2(positionX, positionY)) + perlinNoiseEntityId = newEntityId - positionX += offsetX - positionY += offsetY + positionX += offsetX + positionY += offsetY - # Add a Gradient Mixer node to the graph - gradientMixerNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, - 'GradientMixerNode') - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, gradientMixerNode, math.Vector2(positionX, positionY)) - gradientMixerEntityId = newEntityId + # Add a FastNoise Gradient node to the graph + fastNoiseNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, + 'FastNoiseGradientNode') + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, fastNoiseNode, math.Vector2(positionX, positionY)) + fastNoiseEntityId = newEntityId - boundsSlotId = graph.GraphModelSlotId('Bounds') - previewBoundsSlotId = graph.GraphModelSlotId('PreviewBounds') - inboundGradientSlotId = graph.GraphModelSlotId('InboundGradient') - outboundGradientSlotId = graph.GraphModelSlotId('OutboundGradient') - inboundGradientSlotId2 = graph.GraphControllerRequestBus(bus.Event, 'ExtendSlot', newGraphId, gradientMixerNode, - 'InboundGradient') + positionX += offsetX + positionY += offsetY - # Connect slots on our nodes to construct a Gradient Mixer hierarchy - graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, boxShapeNode, boundsSlotId, - perlinNoiseNode, previewBoundsSlotId) - graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, boxShapeNode, boundsSlotId, - fastNoiseNode, previewBoundsSlotId) - graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, boxShapeNode, boundsSlotId, - gradientMixerNode, previewBoundsSlotId) - graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, perlinNoiseNode, outboundGradientSlotId, - gradientMixerNode, inboundGradientSlotId) - graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, fastNoiseNode, outboundGradientSlotId, - gradientMixerNode, inboundGradientSlotId2) + # Add a Gradient Mixer node to the graph + gradientMixerNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, + 'GradientMixerNode') + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, gradientMixerNode, math.Vector2(positionX, positionY)) + gradientMixerEntityId = newEntityId - # Delay to allow all the underlying component properties to be updated after the slot connections are made - general.idle_wait(1.0) + boundsSlotId = graph.GraphModelSlotId('Bounds') + previewBoundsSlotId = graph.GraphModelSlotId('PreviewBounds') + inboundGradientSlotId = graph.GraphModelSlotId('InboundGradient') + outboundGradientSlotId = graph.GraphModelSlotId('OutboundGradient') + inboundGradientSlotId2 = graph.GraphControllerRequestBus(bus.Event, 'ExtendSlot', newGraphId, gradientMixerNode, + 'InboundGradient') - # Get component info - gradientMixerTypeId = hydra.get_component_type_id("Gradient Mixer") - perlinNoiseTypeId = hydra.get_component_type_id("Perlin Noise Gradient") - gradientMixerOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', gradientMixerEntityId, - gradientMixerTypeId) - gradientMixerComponent = gradientMixerOutcome.GetValue() - perlinNoiseOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', perlinNoiseEntityId, - perlinNoiseTypeId) - perlinNoiseComponent = perlinNoiseOutcome.GetValue() + # Connect slots on our nodes to construct a Gradient Mixer hierarchy + graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, boxShapeNode, boundsSlotId, + perlinNoiseNode, previewBoundsSlotId) + graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, boxShapeNode, boundsSlotId, + fastNoiseNode, previewBoundsSlotId) + graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, boxShapeNode, boundsSlotId, + gradientMixerNode, previewBoundsSlotId) + graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, perlinNoiseNode, outboundGradientSlotId, + gradientMixerNode, inboundGradientSlotId) + graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, fastNoiseNode, outboundGradientSlotId, + gradientMixerNode, inboundGradientSlotId2) - # Verify the Preview EntityId property on our Perlin Noise Gradient component has been set to our Box Shape's EntityId - previewEntityId = hydra.get_component_property_value(perlinNoiseComponent, 'Preview Settings|Pin Preview to Shape') - self.test_success = self.test_success and previewEntityId and boxShapeEntityId.invoke("Equal", previewEntityId) - if previewEntityId and boxShapeEntityId.invoke("Equal", previewEntityId): - self.log("Perlin Noise Gradient component Preview Entity property set to Box Shape EntityId") + # Delay to allow all the underlying component properties to be updated after the slot connections are made + general.idle_wait(1.0) - # Verify the 1st Inbound Gradient EntityId property on our Gradient Mixer component has been set to our Perlin Noise - # Gradient's EntityId - inboundGradientEntityId = hydra.get_component_property_value(gradientMixerComponent, - 'Configuration|Layers|[0]|Gradient|Gradient Entity Id') - self.test_success = self.test_success and inboundGradientEntityId and perlinNoiseEntityId.invoke("Equal", inboundGradientEntityId) - if inboundGradientEntityId and perlinNoiseEntityId.invoke("Equal", inboundGradientEntityId): - self.log("Gradient Mixer component Inbound Gradient extendable property set to Perlin Noise Gradient EntityId") + # Get component info + gradientMixerTypeId = hydra.get_component_type_id("Gradient Mixer") + perlinNoiseTypeId = hydra.get_component_type_id("Perlin Noise Gradient") + gradientMixerOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', gradientMixerEntityId, + gradientMixerTypeId) + gradientMixerComponent = gradientMixerOutcome.GetValue() + perlinNoiseOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', perlinNoiseEntityId, + perlinNoiseTypeId) + perlinNoiseComponent = perlinNoiseOutcome.GetValue() - # Verify the 2nd Inbound Gradient EntityId property on our Gradient Mixer component has been set to our FastNoise - # Gradient Modifier's EntityId - inboundGradientEntityId2 = hydra.get_component_property_value(gradientMixerComponent, - 'Configuration|Layers|[1]|Gradient|Gradient Entity Id') - self.test_success = self.test_success and inboundGradientEntityId2 and fastNoiseEntityId.invoke("Equal", inboundGradientEntityId2) - if inboundGradientEntityId2 and fastNoiseEntityId.invoke("Equal", inboundGradientEntityId2): - self.log("Gradient Mixer component Inbound Gradient extendable property set to FastNoise Gradient EntityId") + # Verify the Preview EntityId property on our Perlin Noise Gradient component has been set to our Box Shape's EntityId + previewEntityId = hydra.get_component_property_value(perlinNoiseComponent, 'Preview Settings|Pin Preview to Shape') + Report.result(Tests.preview_entity_set, previewEntityId and boxShapeEntityId.invoke("Equal", previewEntityId)) - # Verify that Gradient Mixer Layer Operations are properly set - hydra.get_component_property_value(gradientMixerComponent, 'Configuration|Layers|[0]|Operation') - hydra.get_component_property_value(gradientMixerComponent, 'Configuration|Layers|[1]|Operation') + # Verify the 1st Inbound Gradient EntityId property on our Gradient Mixer component has been set to our Perlin Noise + # Gradient's EntityId + inboundGradientEntityId = hydra.get_component_property_value(gradientMixerComponent, + 'Configuration|Layers|[0]|Gradient|Gradient Entity Id') + Report.result(Tests.mixer_inbound_gradient_set_a, inboundGradientEntityId and perlinNoiseEntityId.invoke("Equal", inboundGradientEntityId)) - # Stop listening for entity creation notifications - handler.disconnect() + # Verify the 2nd Inbound Gradient EntityId property on our Gradient Mixer component has been set to our FastNoise + # Gradient Modifier's EntityId + inboundGradientEntityId2 = hydra.get_component_property_value(gradientMixerComponent, + 'Configuration|Layers|[1]|Gradient|Gradient Entity Id') + Report.result(Tests.mixer_inbound_gradient_set_b, inboundGradientEntityId2 and fastNoiseEntityId.invoke("Equal", inboundGradientEntityId2)) + + # Verify that Gradient Mixer Layer Operations are properly set + mixer_operation_a = hydra.get_component_property_value(gradientMixerComponent, 'Configuration|Layers|[0]|Operation') + mixer_operation_b = hydra.get_component_property_value(gradientMixerComponent, 'Configuration|Layers|[1]|Operation') + Report.result(Tests.mixer_operation_a, mixer_operation_a == 0) + Report.result(Tests.mixer_operation_b, mixer_operation_b == 6) + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestGradientMixerNodeConstruction() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientMixer_NodeConstruction) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py index 43d39602be..c3952fe34b 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py @@ -5,132 +5,134 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + component_added = ( + "New entity created with the expected component", + "Expected component was not found on entity" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newEntityId = None -class TestGradientModifierNodeEntityCreate(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientModifierNodeEntityCreate", args=["level"]) +def GradientModifierNodes_EntityCreatedOnNodeAdd(): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. + Expected Behavior: + New entities are created when dragging Gradient Modifier nodes to graph area. - Expected Behavior: - New entities are created when dragging Gradient Modifier nodes to graph area. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the Gradient Modifier nodes to the graph area, and ensure a new entity is created - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Drag each of the Gradient Modifier nodes to the graph area, and ensure a new entity is created + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math - def onEntityCreated(parameters): - global newEntityId - newEntityId = parameters[0] + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + def onEntityCreated(parameters): + global newEntityId + newEntityId = parameters[0] - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Listen for entity creation notifications so we can check if the entity created - # from adding gradient modifier nodes has the appropriate Gradient Modifier Component - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Gradient modifier mapping with the key being the node name and the value is the - # expected Component that should be added to the Entity created for the node - gradientModifiers = { - 'DitherGradientModifierNode': 'Dither Gradient Modifier', - 'GradientMixerNode': 'Gradient Mixer', - 'InvertGradientModifierNode': 'Invert Gradient Modifier', - 'LevelsGradientModifierNode': 'Levels Gradient Modifier', - 'PosterizeGradientModifierNode': 'Posterize Gradient Modifier', - 'SmoothStepGradientModifierNode': 'Smooth-Step Gradient Modifier', - 'ThresholdGradientModifierNode': 'Threshold Gradient Modifier' - } + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Retrieve a mapping of the TypeIds for all the components - # we will be checking for - componentNames = [] - for name in gradientModifiers: - componentNames.append(gradientModifiers[name]) - componentTypeIds = hydra.get_component_type_id_map(componentNames) + # Listen for entity creation notifications so we can check if the entity created + # from adding gradient modifier nodes has the appropriate Gradient Modifier Component + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) - # Create nodes for all the gradients modifiers we support and check if the Entity created by - # adding the node has the appropriate Component added automatically to it - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for nodeName in gradientModifiers: - nodePosition = math.Vector2(x, y) - node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', - newGraph, nodeName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + # Gradient modifier mapping with the key being the node name and the value is the + # expected Component that should be added to the Entity created for the node + gradientModifiers = { + 'DitherGradientModifierNode': 'Dither Gradient Modifier', + 'GradientMixerNode': 'Gradient Mixer', + 'InvertGradientModifierNode': 'Invert Gradient Modifier', + 'LevelsGradientModifierNode': 'Levels Gradient Modifier', + 'PosterizeGradientModifierNode': 'Posterize Gradient Modifier', + 'SmoothStepGradientModifierNode': 'Smooth-Step Gradient Modifier', + 'ThresholdGradientModifierNode': 'Threshold Gradient Modifier' + } - gradientComponent = gradientModifiers[nodeName] - componentTypeId = componentTypeIds[gradientComponent] - hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, - componentTypeId) - self.test_success = self.test_success and hasComponent - if hasComponent: - self.log("{node} created new Entity with {component} Component".format(node=nodeName, - component=gradientComponent)) + # Retrieve a mapping of the TypeIds for all the components + # we will be checking for + componentNames = [] + for name in gradientModifiers: + componentNames.append(gradientModifiers[name]) + componentTypeIds = hydra.get_component_type_id_map(componentNames) - x += 40.0 - y += 40.0 + # Create nodes for all the gradients modifiers we support and check if the Entity created by + # adding the node has the appropriate Component added automatically to it + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for nodeName in gradientModifiers: + nodePosition = math.Vector2(x, y) + node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', + newGraph, nodeName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) - # Stop listening for entity creation notifications - handler.disconnect() + gradientComponent = gradientModifiers[nodeName] + componentTypeId = componentTypeIds[gradientComponent] + hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, + componentTypeId) + Report.info(f"Node: {nodeName} | Component: {gradientComponent}") + Report.result(Tests.component_added, hasComponent) + + x += 40.0 + y += 40.0 + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestGradientModifierNodeEntityCreate() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientModifierNodes_EntityCreatedOnNodeAdd) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py index f7b4dcf557..d7789a21fb 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py @@ -5,126 +5,129 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + entity_deleted = ( + "Entity was deleted when node was removed", + "Entity was not deleted as expected when node was removed" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID createdEntityId = None deletedEntityId = None -class TestGradientModifierNodeEntityDelete(EditorTestHelper): +def GradientModifierNodes_EntityRemovedOnNodeDelete(): + """ + Summary: + This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientModifierNodeEntityDelete", args=["level"]) + Expected Behavior: + Entities are removed when Gradient Modifier nodes are deleted from a graph. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the Gradient Modifier nodes to the graph area, and ensure a new entity is created + 4) Delete the nodes, and ensure the newly created entities are removed - Expected Behavior: - Entities are removed when Gradient Modifier nodes are deleted from a graph. + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Drag each of the Gradient Modifier nodes to the graph area, and ensure a new entity is created - 4) Delete the nodes, and ensure the newly created entities are removed + :return: None + """ - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math - :return: None - """ - def onEntityCreated(parameters): - global createdEntityId - createdEntityId = parameters[0] + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - def onEntityDeleted(parameters): - global deletedEntityId - deletedEntityId = parameters[0] + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) + def onEntityCreated(parameters): + global createdEntityId + createdEntityId = parameters[0] - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + def onEntityDeleted(parameters): + global deletedEntityId + deletedEntityId = parameters[0] - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Listen for entity creation notifications so we can check if the entity created - # from adding gradient nodes has the appropriate Gradient Component - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) - handler.add_callback('OnEditorEntityDeleted', onEntityDeleted) + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Vegetation Area mapping with the key being the node name and the value is the - # expected Component that should be added to the Entity created for the node - gradientModifiers = [ - 'DitherGradientModifierNode', - 'GradientMixerNode', - 'InvertGradientModifierNode', - 'LevelsGradientModifierNode', - 'PosterizeGradientModifierNode', - 'SmoothStepGradientModifierNode', - 'ThresholdGradientModifierNode' - ] + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Create nodes for all the gradients we support and check if the Entity created by - # adding the node has the appropriate Component added automatically to it - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for nodeName in gradientModifiers: - nodePosition = math.Vector2(x, y) - node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + # Listen for entity creation notifications so we can check if the entity created + # from adding gradient nodes has the appropriate Gradient Component + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) + handler.add_callback('OnEditorEntityDeleted', onEntityDeleted) - removed = graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', newGraphId, node) + # Vegetation Area mapping with the key being the node name and the value is the + # expected Component that should be added to the Entity created for the node + gradientModifiers = [ + 'DitherGradientModifierNode', + 'GradientMixerNode', + 'InvertGradientModifierNode', + 'LevelsGradientModifierNode', + 'PosterizeGradientModifierNode', + 'SmoothStepGradientModifierNode', + 'ThresholdGradientModifierNode' + ] - # Verify that the created Entity for this node matches the Entity that gets - # deleted when the node is removed - self.test_success = self.test_success and removed and createdEntityId.invoke("Equal", deletedEntityId) - if removed and createdEntityId.invoke("Equal", deletedEntityId): - self.log("{node} corresponding Entity was deleted when node is removed".format(node=nodeName)) + # Create nodes for all the gradients we support and check if the Entity created by + # adding the node has the appropriate Component added automatically to it + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for nodeName in gradientModifiers: + nodePosition = math.Vector2(x, y) + node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) - # Stop listening for entity creation notifications - handler.disconnect() + removed = graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', newGraphId, node) + + # Verify that the created Entity for this node matches the Entity that gets + # deleted when the node is removed + Report.info(f"Node: {nodeName}") + Report.result(Tests.entity_deleted, removed and createdEntityId.invoke("Equal", deletedEntityId)) + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestGradientModifierNodeEntityDelete() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientModifierNodes_EntityRemovedOnNodeDelete) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py index 96eac887cd..c04f9f05f6 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py @@ -5,141 +5,143 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + dependencies_added = ( + "Node created new Entity with all required components", + "Failed to create node with all required components" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newEntityId = None -class TestGradientNodeComponentDependency(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientNodeComponentDependency", args=["level"]) +def GradientNodes_DependentComponentsAdded(): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities with + proper dependent components. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities with - proper dependent components. + Expected Behavior: + All expected component dependencies are met when adding a Gradient Modifier node to a graph. - Expected Behavior: - All expected component dependencies are met when adding a Gradient Modifier node to a graph. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the Gradient Modifier nodes to the graph area, and ensure the proper dependent components are + added - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Drag each of the Gradient Modifier nodes to the graph area, and ensure the proper dependent components are - added + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math - def onEntityCreated(parameters): - global newEntityId - newEntityId = parameters[0] + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + def onEntityCreated(parameters): + global newEntityId + newEntityId = parameters[0] - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Listen for entity creation notifications so we can check if the entity created - # from adding these gradients nodes has the main target Gradient Component - # as well as automatically adding all required dependency components - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Gradient mapping with the key being the node name and the value is the - # expected Component that should be added to the Entity created for the node - gradients = { - 'FastNoiseGradientNode': 'FastNoise Gradient', - 'ImageGradientNode': 'Image Gradient', - 'PerlinNoiseGradientNode': 'Perlin Noise Gradient', - 'RandomNoiseGradientNode': 'Random Noise Gradient' - } + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Retrieve a mapping of the TypeIds for all the components - # we will be checking for - commonComponents = [ - 'Gradient Transform Modifier', - 'Vegetation Reference Shape' - ] - componentNames = [] - for name in gradients: - componentNames.append(gradients[name]) - componentNames.extend(commonComponents) - componentTypeIds = hydra.get_component_type_id_map(componentNames) + # Listen for entity creation notifications so we can check if the entity created + # from adding these gradients nodes has the main target Gradient Component + # as well as automatically adding all required dependency components + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) - # Create nodes for the gradients that have additional required dependencies and check if - # the Entity created by adding the node has the appropriate Component and required - # Gradient Transform Modifier and Vegetation Reference Shape components added automatically to it - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for nodeName in gradients: - nodePosition = math.Vector2(x, y) - node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + # Gradient mapping with the key being the node name and the value is the + # expected Component that should be added to the Entity created for the node + gradients = { + 'FastNoiseGradientNode': 'FastNoise Gradient', + 'ImageGradientNode': 'Image Gradient', + 'PerlinNoiseGradientNode': 'Perlin Noise Gradient', + 'RandomNoiseGradientNode': 'Random Noise Gradient' + } - gradientComponent = gradients[nodeName] - components = [gradientComponent] + commonComponents - success = False - for component in components: - componentTypeId = componentTypeIds[component] - success = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, componentTypeId) - self.test_success = self.test_success and success - if not success: - break + # Retrieve a mapping of the TypeIds for all the components + # we will be checking for + commonComponents = [ + 'Gradient Transform Modifier', + 'Vegetation Reference Shape' + ] + componentNames = [] + for name in gradients: + componentNames.append(gradients[name]) + componentNames.extend(commonComponents) + componentTypeIds = hydra.get_component_type_id_map(componentNames) - if success: - self.log("{node} created new Entity with all required components".format(node=nodeName)) + # Create nodes for the gradients that have additional required dependencies and check if + # the Entity created by adding the node has the appropriate Component and required + # Gradient Transform Modifier and Vegetation Reference Shape components added automatically to it + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for nodeName in gradients: + nodePosition = math.Vector2(x, y) + node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) - x += 40.0 - y += 40.0 + gradientComponent = gradients[nodeName] + components = [gradientComponent] + commonComponents + success = False + for component in components: + componentTypeId = componentTypeIds[component] + success = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, componentTypeId) + if not success: + break + Report.info(nodeName) + Report.result(Tests.dependencies_added, success) - # Stop listening for entity creation notifications - handler.disconnect() + x += 40.0 + y += 40.0 + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestGradientNodeComponentDependency() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientNodes_DependentComponentsAdded) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py index a484de8d2a..d5595e342c 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py @@ -5,130 +5,134 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os, sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + component_added = ( + "New entity created with the expected component", + "Expected component was not found on entity" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newEntityId = None -class TestGradientNodeEntityCreate(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientNodeEntityCreate", args=["level"]) +def GradientNodes_EntityCreatedOnNodeAdd(): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. + Expected Behavior: + New entities are created when dragging Gradient nodes to graph area. - Expected Behavior: - New entities are created when dragging Gradient nodes to graph area. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the Gradient nodes to the graph area, and ensure a new entity is created - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Drag each of the Gradient nodes to the graph area, and ensure a new entity is created + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math - def onEntityCreated(parameters): - global newEntityId - newEntityId = parameters[0] + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + def onEntityCreated(parameters): + global newEntityId + newEntityId = parameters[0] - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Listen for entity creation notifications so we can check if the entity created - # from adding gradient nodes has the appropriate Gradient Component - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Gradient mapping with the key being the node name and the value is the - # expected Component that should be added to the Entity created for the node - gradients = { - 'AltitudeGradientNode': 'Altitude Gradient', - 'ConstantGradientNode': 'Constant Gradient', - 'FastNoiseGradientNode': 'FastNoise Gradient', - 'ImageGradientNode': 'Image Gradient', - 'PerlinNoiseGradientNode': 'Perlin Noise Gradient', - 'RandomNoiseGradientNode': 'Random Noise Gradient', - 'ShapeAreaFalloffGradientNode': 'Shape Falloff Gradient', - 'SlopeGradientNode': 'Slope Gradient', - 'SurfaceMaskGradientNode': 'Surface Mask Gradient', - } + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Retrieve a mapping of the TypeIds for all the components - # we will be checking for - componentNames = [] - for name in gradients: - componentNames.append(gradients[name]) - componentTypeIds = hydra.get_component_type_id_map(componentNames) + # Listen for entity creation notifications so we can check if the entity created + # from adding gradient nodes has the appropriate Gradient Component + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) - # Create nodes for all the gradients we support and check if the Entity created by - # adding the node has the appropriate Component added automatically to it - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for nodeName in gradients: - nodePosition = math.Vector2(x, y) - node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + # Gradient mapping with the key being the node name and the value is the + # expected Component that should be added to the Entity created for the node + gradients = { + 'AltitudeGradientNode': 'Altitude Gradient', + 'ConstantGradientNode': 'Constant Gradient', + 'FastNoiseGradientNode': 'FastNoise Gradient', + 'ImageGradientNode': 'Image Gradient', + 'PerlinNoiseGradientNode': 'Perlin Noise Gradient', + 'RandomNoiseGradientNode': 'Random Noise Gradient', + 'ShapeAreaFalloffGradientNode': 'Shape Falloff Gradient', + 'SlopeGradientNode': 'Slope Gradient', + 'SurfaceMaskGradientNode': 'Surface Mask Gradient', + } - gradientComponent = gradients[nodeName] - componentTypeId = componentTypeIds[gradientComponent] - hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, componentTypeId) - self.test_success = self.test_success and hasComponent - if hasComponent: - self.log("{node} created new Entity with {component} Component".format(node=nodeName, component=gradientComponent)) + # Retrieve a mapping of the TypeIds for all the components + # we will be checking for + componentNames = [] + for name in gradients: + componentNames.append(gradients[name]) + componentTypeIds = hydra.get_component_type_id_map(componentNames) - x += 40.0 - y += 40.0 + # Create nodes for all the gradients we support and check if the Entity created by + # adding the node has the appropriate Component added automatically to it + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for nodeName in gradients: + nodePosition = math.Vector2(x, y) + node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) - # Stop listening for entity creation notifications - handler.disconnect() + gradientComponent = gradients[nodeName] + componentTypeId = componentTypeIds[gradientComponent] + hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, componentTypeId) + Report.info(f"Node: {nodeName} | Component: {gradientComponent}") + Report.result(Tests.component_added, hasComponent) + + x += 40.0 + y += 40.0 + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestGradientNodeEntityCreate() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientNodes_EntityCreatedOnNodeAdd) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py index 2e289ff41b..e5bfbfc7f1 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py @@ -5,129 +5,131 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + entity_deleted = ( + "Entity was deleted when node was removed", + "Entity was not deleted as expected when node was removed" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID createdEntityId = None deletedEntityId = None -class TestGradientNodeEntityDelete(EditorTestHelper): +def GradientNodes_EntityRemovedOnNodeDelete(): + """ + Summary: + This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GradientNodeEntityDelete", args=["level"]) + Expected Behavior: + Entities are removed when Gradient nodes are deleted from a graph. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the Gradient nodes to the graph area, and ensure a new entity is created + 4) Delete the nodes, and ensure the newly created entities are removed - Expected Behavior: - Entities are removed when Gradient nodes are deleted from a graph. + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Drag each of the Gradient nodes to the graph area, and ensure a new entity is created - 4) Delete the nodes, and ensure the newly created entities are removed + :return: None + """ - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math - :return: None - """ + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - def onEntityCreated(parameters): - global createdEntityId - createdEntityId = parameters[0] + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - def onEntityDeleted(parameters): - global deletedEntityId - deletedEntityId = parameters[0] + def onEntityCreated(parameters): + global createdEntityId + createdEntityId = parameters[0] - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + def onEntityDeleted(parameters): + global deletedEntityId + deletedEntityId = parameters[0] - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Listen for entity creation notifications so we can check if the entity created - # from adding gradient nodes has the appropriate Gradient Component - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) - handler.add_callback('OnEditorEntityDeleted', onEntityDeleted) + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Gradient mapping with the key being the node name and the value is the - # expected Component that should be added to the Entity created for the node - gradients = [ - 'AltitudeGradientNode', - 'ConstantGradientNode', - 'FastNoiseGradientNode', - 'ImageGradientNode', - 'PerlinNoiseGradientNode', - 'RandomNoiseGradientNode', - 'ShapeAreaFalloffGradientNode', - 'SlopeGradientNode', - 'SurfaceMaskGradientNode', - ] + # Listen for entity creation notifications so we can check if the entity created + # from adding gradient nodes has the appropriate Gradient Component + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) + handler.add_callback('OnEditorEntityDeleted', onEntityDeleted) - # Create nodes for all the gradients we support and check if the Entity created by - # adding the node has the appropriate Component added automatically to it - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for nodeName in gradients: - nodePosition = math.Vector2(x, y) - node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + # Gradient mapping with the key being the node name and the value is the + # expected Component that should be added to the Entity created for the node + gradients = [ + 'AltitudeGradientNode', + 'ConstantGradientNode', + 'FastNoiseGradientNode', + 'ImageGradientNode', + 'PerlinNoiseGradientNode', + 'RandomNoiseGradientNode', + 'ShapeAreaFalloffGradientNode', + 'SlopeGradientNode', + 'SurfaceMaskGradientNode', + ] - removed = graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', newGraphId, node) + # Create nodes for all the gradients we support and check if the Entity created by + # adding the node has the appropriate Component added automatically to it + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for nodeName in gradients: + nodePosition = math.Vector2(x, y) + node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) - # Verify that the created Entity for this node matches the Entity that gets - # deleted when the node is removed - self.test_success = self.test_success and removed and createdEntityId.invoke("Equal", deletedEntityId) - if removed and createdEntityId.invoke("Equal", deletedEntityId): - self.log("{node} corresponding Entity was deleted when node is removed".format(node=nodeName)) + removed = graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', newGraphId, node) - # Stop listening for entity creation notifications - handler.disconnect() + # Verify that the created Entity for this node matches the Entity that gets + # deleted when the node is removed + Report.info(f"Node: {nodeName}") + Report.result(Tests.entity_deleted, removed and createdEntityId.invoke("Equal", deletedEntityId)) + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestGradientNodeEntityDelete() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GradientNodes_EntityRemovedOnNodeDelete) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py index 0ad1549b60..0f83688206 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py @@ -5,100 +5,99 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.legacy.general as general -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + graph_closed = ( + "Graph closed on entity delete", + "Graph is still open after entity delete" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newRootEntityId = None -class TestGraphClosedOnEntityDelete(EditorTestHelper): +def GraphClosed_OnEntityDelete(): + """ + Summary: + This test verifies that Landscape Canvas graphs are auto-closed when the corresponding entity is deleted. - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GraphClosedOnEntityDelete", args=["level"]) + Expected Behavior: + When a Landscape Canvas root entity is deleted, the corresponding graph automatically closes. - def run_test(self): - """ - Summary: - This test verifies that Landscape Canvas graphs are auto-closed when the corresponding entity is deleted. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Delete the automatically created entity + 4) Verify the open graph is closed - Expected Behavior: - When a Landscape Canvas root entity is deleted, the corresponding graph automatically closes. + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Delete the automatically created entity - 4) Verify the open graph is closed + :return: None + """ - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.legacy.general as general - :return: None - """ + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - def onEntityCreated(parameters): - global newRootEntityId - newRootEntityId = parameters[0] + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) + def onEntityCreated(parameters): + global newRootEntityId + newRootEntityId = parameters[0] - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Listen for entity creation notifications so we can store the top-level Entity created - # when a new graph is created, and then delete it to test if the graph is closed - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Create a new graph in Landscape Canvas and verify - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - graphIsOpen = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and graphIsOpen - if graphIsOpen: - self.log("Graph registered with Landscape Canvas") + # Listen for entity creation notifications so we can store the top-level Entity created + # when a new graph is created, and then delete it to test if the graph is closed + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) - # Delete the top-level Entity created by the new graph - editor.ToolsApplicationRequestBus(bus.Broadcast, 'DeleteEntityById', newRootEntityId) + # Create a new graph in Landscape Canvas and verify + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + graphIsOpen = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graphIsOpen) - # We need to delay here because the closing of the graph due to Entity deletion - # is actually queued in order to workaround an undo/redo issue - # Alternatively, we could add a notifications bus for AssetEditorRequests - # that could trigger when graphs are opened/closed and then do the check there - general.idle_enable(True) - general.idle_wait(1.0) + # Delete the top-level Entity created by the new graph + editor.ToolsApplicationRequestBus(bus.Broadcast, 'DeleteEntityById', newRootEntityId) - # Verify that the corresponding graph is no longer open - graphIsClosed = not graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and graphIsClosed - if graphIsClosed: - self.log("The graph is no longer open after deleting the Entity") + # We need to delay here because the closing of the graph due to Entity deletion + # is actually queued in order to workaround an undo/redo issue + # Alternatively, we could add a notifications bus for AssetEditorRequests + # that could trigger when graphs are opened/closed and then do the check there + general.idle_enable(True) + general.idle_wait(1.0) - # Stop listening for entity creation notifications - handler.disconnect() + # Verify that the corresponding graph is no longer open + graphIsClosed = not graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_closed, graphIsClosed) + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestGraphClosedOnEntityDelete() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GraphClosed_OnEntityDelete) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py index 374f26d3a4..67c2ec6908 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py @@ -5,82 +5,82 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor.graph as graph -import azlmbr.legacy.general as general -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -from editor_python_test_tools.editor_test_helper import EditorTestHelper - -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + graph_closed = ( + "Graph closed on level change", + "Graph is still open after level change" + ) -class TestGraphClosedOnLevelChange(EditorTestHelper): +def GraphClosed_OnLevelChange(): + """ + Summary: + This test verifies that Landscape Canvas graphs are auto-closed when the currently open level changes. - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GraphClosedOnLevelChange", args=["level"]) + Expected Behavior: + When a new level is loaded in the Editor, open Landscape Canvas graphs are automatically closed. - def run_test(self): - """ - Summary: - This test verifies that Landscape Canvas graphs are auto-closed when the currently open level changes. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Open a different level + 4) Verify the open graph is closed - Expected Behavior: - When a new level is loaded in the Editor, open Landscape Canvas graphs are automatically closed. + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Open a different level - 4) Verify the open graph is closed + :return: None + """ - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + import azlmbr.bus as bus + import azlmbr.editor.graph as graph + import azlmbr.legacy.general as general - :return: None - """ - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Make sure the graph we created is in Landscape Canvas - graphIsOpen = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and graphIsOpen - if graphIsOpen: - self.log("Graph registered with Landscape Canvas") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Open a different level, which should close any open Landscape Canvas graphs - general.open_level_no_prompt('WhiteBox/EmptyLevel') + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Make sure the graph we created is now closed - graphIsOpen = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and not graphIsOpen - if not graphIsOpen: - self.log("Graph is no longer open in Landscape Canvas") + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) + + # Open a different level, which should close any open Landscape Canvas graphs + general.open_level_no_prompt('WhiteBox/EmptyLevel') + + # Make sure the graph we created is now closed + graphIsOpen = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_closed, not graphIsOpen) -test = TestGraphClosedOnLevelChange() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GraphClosed_OnLevelChange) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py index f8b0cfdb44..83762e0afb 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py @@ -5,95 +5,93 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor.graph as graph -import azlmbr.legacy.general as general -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -from editor_python_test_tools.editor_test_helper import EditorTestHelper - -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_open = ( + "Graph is open in Landscape Canvas", + "Graph is not open in Landscape Canvas" + ) + tabbed_graph_closed = ( + "Tabbed graph closed independently", + "Closing tabbed graph resulted in unexpected graphs closing" + ) -class TestGraphClosedTabbedGraph(EditorTestHelper): +def GraphClosed_TabbedGraphClosesIndependently(): + """ + Summary: + This test verifies that Landscape Canvas tabbed graphs can be independently closed. - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GraphClosedTabbedGraph", args=["level"]) + Expected Behavior: + Closing a tabbed graph only closes the appropriate graph. - def run_test(self): - """ - Summary: - This test verifies that Landscape Canvas tabbed graphs can be independently closed. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create several new graphs + 3) Close one of the open graphs + 4) Ensure the graph properly closed, and other open graphs remain open - Expected Behavior: - Closing a tabbed graph only closes the appropriate graph. + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create several new graphs - 3) Close one of the open graphs - 4) Ensure the graph properly closed, and other open graphs remain open + :return: None + """ - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + import azlmbr.bus as bus + import azlmbr.editor.graph as graph + import azlmbr.legacy.general as general - :return: None - """ + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) + editor_id = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + def create_new_graph(): + new_graph_id = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editor_id) + return new_graph_id - # Create 3 new graphs in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + def is_graph_open(graph_id): + graph_open = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editor_id, graph_id) + return graph_open - newGraphId2 = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId2 - if newGraphId2: - self.log("2nd new graph created") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - newGraphId3 = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId3 - if newGraphId3: - self.log("3rd new graph created") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Make sure the graphs we created are open in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - success2 = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId2) - success3 = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId3) - self.test_success = self.test_success and success and success2 and success3 - if success and success2 and success3: - self.log("Graphs registered with Landscape Canvas") + # Create 3 new graphs in Landscape Canvas and make sure the graphs we created are open in Landscape Canvas + graph1 = create_new_graph() + Report.result(Tests.new_graph_created, graph1 is not None) + Report.result(Tests.graph_open, is_graph_open(graph1)) - # Close a single graph and verify it was properly closed and other graphs remain open - success4 = graph.AssetEditorRequestBus(bus.Event, 'CloseGraph', editorId, newGraphId2) - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - success2 = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId2) - success3 = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId3) - self.test_success = self.test_success and success and success3 and success4 and not success2 - if success and success3 and success4 and not success2: - self.log("Graph 2 was successfully closed") + graph2 = create_new_graph() + Report.result(Tests.new_graph_created, graph2 is not None) + Report.result(Tests.graph_open, is_graph_open(graph2)) + + graph3 = create_new_graph() + Report.result(Tests.new_graph_created, graph3 is not None) + Report.result(Tests.graph_open, is_graph_open(graph3)) + + # Close a single graph and verify it was properly closed and other graphs remain open + graph.AssetEditorRequestBus(bus.Event, 'CloseGraph', editor_id, graph2) + Report.result(Tests.tabbed_graph_closed, not is_graph_open(graph2) and is_graph_open(graph1) and + is_graph_open(graph3)) -test = TestGraphClosedTabbedGraph() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GraphClosed_TabbedGraphClosesIndependently) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py index cc7c2ca7dd..c489c738d5 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py @@ -5,155 +5,151 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.asset as asset -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.entity as entity -import azlmbr.legacy.general as general -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.math as math -import azlmbr.slice as slice -import azlmbr.paths - -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import automatedtesting_shared.landscape_canvas_utils as lc +class Tests: + slice_instantiated = ( + "Slice instantiated successfully", + "Failed to instantiate slice" + ) + existing_graph_opened = ( + "Opened existing graph from slice", + "Failed to open existing graph" + ) + node_removed = ( + "Rotation Modifier node was removed", + "Failed to remove Rotation Modifier node" + ) + component_removed = ( + "Rotation Modifier component was removed from entity", + "Rotation Modifier component is still present on entity" + ) + entity_deleted = ( + "BushSpawner entity was deleted", + "Failed to delete BushSpawner entity" + ) + entity_reference_updated = ( + "Gradient Entity Id reference was properly updated", + "Gradient Entity Id reference was not updated properly" + ) -class TestGraphUpdatesUpdateComponents(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="GraphUpdatesUpdateComponents", args=["level"]) +def GraphUpdates_UpdateComponent(): + """ + Summary: + This test verifies that components are properly updated as nodes are added/removed/updated. - def run_test(self): - """ - Summary: - This test verifies that components are properly updated as nodes are added/removed/updated. + Expected Behavior: + Landscape Canvas node CRUD properly updates component entities. - Expected Behavior: - Landscape Canvas node CRUD properly updates component entities. + Test Steps: + 1. Open Level. + 2. Open the graph on LC_BushFlowerBlender.slice + 3. Find the Rotation Modifier node on the BushSpawner entity + 4. Delete the Rotation Modifier node + 5. Ensure the Vegetation Rotation Modifier component is removed from the BushSpawner entity + 6. Delete the Vegetation Layer Spawner node from the graph + 7. Ensure BushSpawner entity is deleted + 8. Change connection from second Rotation Modifier node to a different Gradient + 9. Ensure Gradient reference on component is updated - Test Steps: - 1. Open Level. - 2. Open the graph on LC_BushFlowerBlender.slice - 3. Find the Rotation Modifier node on the BushSpawner entity - 4. Delete the Rotation Modifier node - 5. Ensure the Vegetation Rotation Modifier component is removed from the BushSpawner entity - 6. Delete the Vegetation Layer Spawner node from the graph - 7. Ensure BushSpawner entity is deleted - 8. Change connection from second Rotation Modifier node to a different Gradient - 9. Ensure Gradient reference on component is updated + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ - # Create a new empty level and instantiate LC_BushFlowerBlender.slice - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) - transform = math.Transform_CreateIdentity() - position = math.Vector3(64.0, 64.0, 32.0) - transform.invoke('SetPosition', position) - test_slice_path = os.path.join("Slices", "LC_BushFlowerBlender.slice") - test_slice_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", test_slice_path, math.Uuid(), - False) - test_slice = slice.SliceRequestBus(bus.Broadcast, 'InstantiateSliceFromAssetId', test_slice_id, transform) - self.test_success = self.test_success and test_slice.IsValid() - if test_slice.IsValid(): - self.log("Slice spawned!") + import os - # Search for root entity to ensure slice is loaded - search_filter = entity.SearchFilter() - search_filter.names = ["LandscapeCanvas"] - self.wait_for_condition(lambda: len(entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter)) > 0, 5.0) + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.entity as entity + import azlmbr.legacy.general as general + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.math as math + import azlmbr.slice as slice - # Find needed entities in the loaded level - slice_root_id = hydra.find_entity_by_name('LandscapeCanvas') - bush_spawner_id = hydra.find_entity_by_name('BushSpawner') - flower_spawner_id = hydra.find_entity_by_name('FlowerSpawner') - inverted_perlin_noise_id = hydra.find_entity_by_name('Invert') + import automatedtesting_shared.landscape_canvas_utils as lc + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Open Landscape Canvas and the existing graph - general.open_pane('Landscape Canvas') - open_graph_id = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'OnGraphEntity', slice_root_id) - self.test_success = self.test_success and open_graph_id.IsValid() - if open_graph_id.IsValid(): - self.log('Graph opened') + # Open a simple level and instantiate LC_BushFlowerBlender.slice + helper.init_idle() + helper.open_level("Physics", "Base") + transform = math.Transform_CreateIdentity() + position = math.Vector3(64.0, 64.0, 32.0) + transform.invoke('SetPosition', position) + test_slice_path = os.path.join("Slices", "LC_BushFlowerBlender.slice") + test_slice_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", test_slice_path, math.Uuid(), + False) + test_slice = slice.SliceRequestBus(bus.Broadcast, 'InstantiateSliceFromAssetId', test_slice_id, transform) + Report.critical_result(Tests.slice_instantiated, test_slice.IsValid()) - # Find the Rotation Modifier node on the BushSpawner entity - rotation_modifier_node = lc.find_nodes_matching_entity_component('Vegetation Rotation Modifier', bush_spawner_id) + # Search for root entity to ensure slice is loaded + search_filter = entity.SearchFilter() + search_filter.names = ["LandscapeCanvas"] + helper.wait_for_condition(lambda: len(entity.SearchBus(bus.Broadcast, 'SearchEntities', search_filter)) > 0, 5.0) - # Remove the Rotation Modifier node - graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', open_graph_id, rotation_modifier_node[0]) + # Find needed entities in the loaded level + slice_root_id = hydra.find_entity_by_name('LandscapeCanvas') + bush_spawner_id = hydra.find_entity_by_name('BushSpawner') + flower_spawner_id = hydra.find_entity_by_name('FlowerSpawner') + inverted_perlin_noise_id = hydra.find_entity_by_name('Invert') - # Verify node was removed - rotation_modifier_node = lc.find_nodes_matching_entity_component('Vegetation Rotation Modifier', bush_spawner_id) - self.test_success = self.test_success and not rotation_modifier_node - if not rotation_modifier_node: - self.log('Rotation Modifier node was removed') - else: - self.log('Rotation Modifier node was not removed') + # Open Landscape Canvas and the existing graph + general.open_pane('Landscape Canvas') + open_graph_id = landscapecanvas.LandscapeCanvasRequestBus(bus.Broadcast, 'OnGraphEntity', slice_root_id) + Report.critical_result(Tests.existing_graph_opened, open_graph_id.IsValid()) - # Verify the component was removed from the BushSpawner entity - has_rotation_modifier = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', bush_spawner_id, - hydra.get_component_type_id('Vegetation Rotation Modifier')) - self.test_success = self.test_success and not has_rotation_modifier - if not has_rotation_modifier: - self.log('Rotation Modifier component was removed from entity') - else: - self.log('Rotation Modifier component is still present on entity') + # Find the Rotation Modifier node on the BushSpawner entity + rotation_modifier_node = lc.find_nodes_matching_entity_component('Vegetation Rotation Modifier', bush_spawner_id) - # Find the Vegetation Layer Spawner node on the BushSpawner entity - layer_spawner_node = lc.find_nodes_matching_entity_component('Vegetation Layer Spawner', bush_spawner_id) + # Remove the Rotation Modifier node + graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', open_graph_id, rotation_modifier_node[0]) - # Remove the Vegetation Layer Spawner node and verify the corresponding entity is deleted - graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', open_graph_id, layer_spawner_node[0]) - bush_spawner_id = hydra.find_entity_by_name('BushSpawner') - self.test_success = self.test_success and not bush_spawner_id - if not bush_spawner_id: - self.log('BushSpawner entity was deleted') - else: - self.log('Failed to delete BushSpawner entity') + # Verify node was removed + rotation_modifier_node = lc.find_nodes_matching_entity_component('Vegetation Rotation Modifier', bush_spawner_id) + Report.result(Tests.node_removed, not rotation_modifier_node) - # Connect the FlowerSpawner's Rotation Modifier node to the Invert Gradient Modifier node - rotation_modifier_node = lc.find_nodes_matching_entity_component('Vegetation Rotation Modifier', flower_spawner_id) - invert_node = lc.find_nodes_matching_entity_component('Invert Gradient Modifier', inverted_perlin_noise_id) + # Verify the component was removed from the BushSpawner entity + has_rotation_modifier = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', bush_spawner_id, + hydra.get_component_type_id('Vegetation Rotation Modifier')) + Report.result(Tests.component_removed, not has_rotation_modifier) - inbound_gradient_z_slot = graph.GraphModelSlotId('InboundGradientZ') - outbound_gradient_slot = graph.GraphModelSlotId('OutboundGradient') - graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', open_graph_id, invert_node[0], - outbound_gradient_slot, rotation_modifier_node[0], inbound_gradient_z_slot) + # Find the Vegetation Layer Spawner node on the BushSpawner entity + layer_spawner_node = lc.find_nodes_matching_entity_component('Vegetation Layer Spawner', bush_spawner_id) - general.idle_wait(1.0) # Add a small wait to ensure component property has time to update + # Remove the Vegetation Layer Spawner node and verify the corresponding entity is deleted + graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', open_graph_id, layer_spawner_node[0]) + bush_spawner_id = hydra.find_entity_by_name('BushSpawner') + Report.result(Tests.entity_deleted, not bush_spawner_id) - # Verify the Gradient Entity Id reference on the Rotation Modifier component was properly set - rotation_type_id = hydra.get_component_type_id('Vegetation Rotation Modifier') - rotation_outcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', flower_spawner_id, - rotation_type_id) - rotation_component = rotation_outcome.GetValue() - gradient_reference = hydra.get_component_property_value(rotation_component, - 'Configuration|Rotation Z|Gradient|Gradient Entity Id') - gradient_reference_success = gradient_reference == inverted_perlin_noise_id - self.test_success = self.test_success and gradient_reference_success - if gradient_reference_success: - self.log('Gradient Entity Id reference was properly updated') - else: - self.log(f'Gradient Entity Id was not updated properly: Expected {inverted_perlin_noise_id.ToString()} -- Got ' - f'{gradient_reference.ToString()}.') + # Connect the FlowerSpawner's Rotation Modifier node to the Invert Gradient Modifier node + rotation_modifier_node = lc.find_nodes_matching_entity_component('Vegetation Rotation Modifier', flower_spawner_id) + invert_node = lc.find_nodes_matching_entity_component('Invert Gradient Modifier', inverted_perlin_noise_id) + + inbound_gradient_z_slot = graph.GraphModelSlotId('InboundGradientZ') + outbound_gradient_slot = graph.GraphModelSlotId('OutboundGradient') + graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', open_graph_id, invert_node[0], + outbound_gradient_slot, rotation_modifier_node[0], inbound_gradient_z_slot) + + general.idle_wait(1.0) # Add a small wait to ensure component property has time to update + + # Verify the Gradient Entity Id reference on the Rotation Modifier component was properly set + rotation_type_id = hydra.get_component_type_id('Vegetation Rotation Modifier') + rotation_outcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', flower_spawner_id, + rotation_type_id) + rotation_component = rotation_outcome.GetValue() + gradient_reference = hydra.get_component_property_value(rotation_component, + 'Configuration|Rotation Z|Gradient|Gradient Entity Id') + Report.result(Tests.entity_reference_updated, gradient_reference == inverted_perlin_noise_id) -test = TestGraphUpdatesUpdateComponents() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(GraphUpdates_UpdateComponent) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvasComponent_AddedRemoved.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvasComponent_AddedRemoved.py deleted file mode 100755 index ed6f23ae24..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvasComponent_AddedRemoved.py +++ /dev/null @@ -1,87 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import sys - -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.entity as entity -import azlmbr.paths - -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper - -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - - -class TestLandscapeCanvasComponentAddedRemoved(EditorTestHelper): - - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="LandscapeCanvasComponentAddedRemoved", args=["level"]) - - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas component can be added to/removed from an entity. - - Expected Behavior: - Closing a tabbed graph only closes the appropriate graph. - - Test Steps: - 1) Create a new level - 2) Create a new entity - 3) Add a Landscape Canvas component to the entity - 4) Remove the Landscape Canvas component from the entity - - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. - - :return: None - """ - - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) - - # Create an Entity at the root of the level - newEntityId = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', entity.EntityId()) - - # Find the component TypeId for our Landscape Canvas component - landscape_canvas_type_id = hydra.get_component_type_id("Landscape Canvas") - - # Add the Landscape Canvas Component to our Entity - componentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentsOfType', newEntityId, [landscape_canvas_type_id]) - components = componentOutcome.GetValue() - landscapeCanvasComponent = components[0] - - # Validate the Landscape Canvas Component exists - hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, landscape_canvas_type_id) - self.test_success = self.test_success and hasComponent - if hasComponent: - self.log("Landscape Canvas Component added to Entity") - - # Remove the Landscape Canvas Component - editor.EditorComponentAPIBus(bus.Broadcast, 'RemoveComponents', [landscapeCanvasComponent]) - - # Validate the Landscape Canvas Component is no longer on our Entity - hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, landscape_canvas_type_id) - self.test_success = self.test_success and not hasComponent - if not hasComponent: - self.log("Landscape Canvas Component removed from Entity") - - -test = TestLandscapeCanvasComponentAddedRemoved() -test.run() diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvas_SliceCreateInstantiate.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvas_SliceCreateInstantiate.py deleted file mode 100755 index 95da5aa7dd..0000000000 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvas_SliceCreateInstantiate.py +++ /dev/null @@ -1,82 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" - -import os -import sys - -import azlmbr.math as math -import azlmbr.paths -import azlmbr.bus as bus -import azlmbr.asset as asset -import azlmbr.slice as slice - -sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper - - -class TestLandscapeCanvasSliceCreateInstantiate(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="LandscapeCanvas_SliceCreateInstantiate", args=["level"]) - - def run_test(self): - """ - Summary: - A slice containing the LandscapeCanvas component can be created/instantiated. - - Expected Result: - Slice is created/processed/instantiated successfully and free of errors/warnings. - - Test Steps: - 1) Create a new level - 2) Create a new entity with a Landscape Canvas component - 3) Create a slice of the new entity - 4) Instantiate a new copy of the slice - - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. - :return: None - """ - - def path_is_valid_asset(asset_path): - asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) - return asset_id.invoke("IsValid") - - # Create empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) - - # Create entity with LandScape Canvas component - position = math.Vector3(512.0, 512.0, 32.0) - landscape_canvas = hydra.Entity("landscape_canvas_entity") - landscape_canvas.create_entity(position, ["Landscape Canvas"]) - - # Create slice from the created entity - slice_path = os.path.join("slices", "TestSlice.slice") - slice.SliceRequestBus(bus.Broadcast, "CreateNewSlice", landscape_canvas.id, slice_path) - - # Verify if slice is created - self.wait_for_condition(lambda: path_is_valid_asset(slice_path), 5.0) - self.log(f"Slice has been created successfully: {path_is_valid_asset(slice_path)}") - - # Instantiate slice - transform = math.Transform_CreateIdentity() - asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", slice_path, math.Uuid(), False) - test_slice = slice.SliceRequestBus(bus.Broadcast, "InstantiateSliceFromAssetId", asset_id, transform) - self.wait_for_condition(lambda: test_slice.IsValid(), 3.0) - self.log(f"Slice instantiated: {test_slice.IsValid()}") - - -test = TestLandscapeCanvasSliceCreateInstantiate() -test.run() diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py index f68bfd91a6..b2bf20411b 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py @@ -5,157 +5,160 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.entity as entity -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + blender_first_layer_set = ( + "Spawner entity set as the first layer of the Vegetation Layer Blender component", + "Unexpected entity set as the first layer of the Vegetation Layer Blender component" + ) + blender_second_layer_set = ( + "Blocker entity set as the second layer of the Vegetation Layer Blender component", + "Unexpected entity set as the second layer of the Vegetation Layer Blender component" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newEntityId = None -class TestLayerBlenderNodeConstruction(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="LayerBlenderNodeConstruction", args=["level"]) +def LayerBlender_NodeConstruction(): + """ + Summary: + This test verifies a Layer Blender vegetation setup can be constructed through Landscape Canvas. - def run_test(self): - """ - Summary: - This test verifies a Layer Blender vegetation setup can be constructed through Landscape Canvas. + Expected Behavior: + Entities contain all required components and component references after creating nodes and setting connections + on a Landscape Canvas graph. - Expected Behavior: - Entities contain all required components and component references after creating nodes and setting connections - on a Landscape Canvas graph. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Add all necessary nodes to the graph and set connections to form a Layer Blender setup + 4) Verify all components and component references were properly set during graph construction - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Add all necessary nodes to the graph and set connections to form a Layer Blender setup - 4) Verify all components and component references were properly set during graph construction + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math - def onEntityCreated(parameters): - global newEntityId - newEntityId = parameters[0] + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=1024, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=4096, - use_terrain=False, - ) + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + def onEntityCreated(parameters): + global newEntityId + newEntityId = parameters[0] - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Listen for entity creation notifications so we can verify the component EntityId - # references are set correctly when connecting slots on the nodes - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - positionX = 10.0 - positionY = 10.0 - offsetX = 340.0 - offsetY = 100.0 + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Add a Vegetation Layer Spawner node to the graph - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - layerSpawnerNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', - newGraph, 'SpawnerAreaNode') - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, layerSpawnerNode, math.Vector2(positionX, positionY)) - layerSpawnerEntityId = newEntityId + # Listen for entity creation notifications so we can verify the component EntityId + # references are set correctly when connecting slots on the nodes + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) - positionX += offsetX - positionY += offsetY + positionX = 10.0 + positionY = 10.0 + offsetX = 340.0 + offsetY = 100.0 - # Add a Vegetation Layer Blocker node to the graph - layerBlockerNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', - newGraph, 'BlockerAreaNode') - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, layerBlockerNode, math.Vector2(positionX, positionY)) - layerBlockerEntityId = newEntityId + # Add a Vegetation Layer Spawner node to the graph + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + layerSpawnerNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', + newGraph, 'SpawnerAreaNode') + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, layerSpawnerNode, math.Vector2(positionX, positionY)) + layerSpawnerEntityId = newEntityId - positionX += offsetX - positionY += offsetY + positionX += offsetX + positionY += offsetY - # Add a Vegetation Layer Blender node to the graph - layerBlenderNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', - newGraph, 'AreaBlenderNode') - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, layerBlenderNode, math.Vector2(positionX, positionY)) - layerBlenderNodeEntityId = newEntityId + # Add a Vegetation Layer Blocker node to the graph + layerBlockerNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', + newGraph, 'BlockerAreaNode') + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, layerBlockerNode, math.Vector2(positionX, positionY)) + layerBlockerEntityId = newEntityId - positionX += offsetX - positionY += offsetY + positionX += offsetX + positionY += offsetY - outboundAreaSlotId = graph.GraphModelSlotId('OutboundArea') - inboundAreaSlotId = graph.GraphModelSlotId('InboundArea') - inboundAreaSlotId2 = graph.GraphControllerRequestBus(bus.Event, 'ExtendSlot', newGraphId, layerBlenderNode, - 'InboundArea') + # Add a Vegetation Layer Blender node to the graph + layerBlenderNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', + newGraph, 'AreaBlenderNode') + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, layerBlenderNode, math.Vector2(positionX, positionY)) + layerBlenderNodeEntityId = newEntityId - # Connect slots on our nodes to construct a Vegetation Layer Blender hierarchy - graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, layerSpawnerNode, outboundAreaSlotId, - layerBlenderNode, inboundAreaSlotId) - graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, layerBlockerNode, outboundAreaSlotId, - layerBlenderNode, inboundAreaSlotId2) + positionX += offsetX + positionY += offsetY - # Delay to allow all the underlying component properties to be updated after the slot connections are made - general.idle_wait(1.0) + outboundAreaSlotId = graph.GraphModelSlotId('OutboundArea') + inboundAreaSlotId = graph.GraphModelSlotId('InboundArea') + inboundAreaSlotId2 = graph.GraphControllerRequestBus(bus.Event, 'ExtendSlot', newGraphId, layerBlenderNode, + 'InboundArea') - # Get component info - layerBlenderTypeId = hydra.get_component_type_id("Vegetation Layer Blender") - vegetationLayerBlenderOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', - layerBlenderNodeEntityId, layerBlenderTypeId) - layerBlenderComponent = vegetationLayerBlenderOutcome.GetValue() + # Connect slots on our nodes to construct a Vegetation Layer Blender hierarchy + graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, layerSpawnerNode, outboundAreaSlotId, + layerBlenderNode, inboundAreaSlotId) + graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, layerBlockerNode, outboundAreaSlotId, + layerBlenderNode, inboundAreaSlotId2) - # Verify the Vegetation Areas properties on our Vegetation Layer Blender component have been set to our area EntityIds - area1EntityId = hydra.get_component_property_value(layerBlenderComponent, 'Configuration|Vegetation Areas|[0]') - self.test_success = self.test_success and area1EntityId and layerSpawnerEntityId.invoke("Equal", area1EntityId) - if area1EntityId and layerSpawnerEntityId.invoke("Equal", area1EntityId): - self.log("Vegetation Layer Blender component Vegetation Areas[0] property set to Vegetation Layer Spawner EntityId") + # Delay to allow all the underlying component properties to be updated after the slot connections are made + general.idle_wait(1.0) - area2EntityId = hydra.get_component_property_value(layerBlenderComponent, 'Configuration|Vegetation Areas|[1]') - self.test_success = self.test_success and area2EntityId and layerBlockerEntityId.invoke("Equal", area2EntityId) - if area2EntityId and layerBlockerEntityId.invoke("Equal", area2EntityId): - self.log("Vegetation Layer Blender component Vegetation Areas[1] property set to Vegetation Layer Blocker EntityId") + # Get component info + layerBlenderTypeId = hydra.get_component_type_id("Vegetation Layer Blender") + vegetationLayerBlenderOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', + layerBlenderNodeEntityId, layerBlenderTypeId) + layerBlenderComponent = vegetationLayerBlenderOutcome.GetValue() - # Stop listening for entity creation notifications - handler.disconnect() + # Verify the Vegetation Areas properties on our Vegetation Layer Blender component have been set to our area EntityIds + area1EntityId = hydra.get_component_property_value(layerBlenderComponent, 'Configuration|Vegetation Areas|[0]') + Report.result(Tests.blender_first_layer_set, area1EntityId and layerSpawnerEntityId.invoke("Equal", area1EntityId)) + + area2EntityId = hydra.get_component_property_value(layerBlenderComponent, 'Configuration|Vegetation Areas|[1]') + Report.result(Tests.blender_second_layer_set, area2EntityId and layerBlockerEntityId.invoke("Equal", area2EntityId)) + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestLayerBlenderNodeConstruction() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(LayerBlender_NodeConstruction) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py index 5b523e0b38..510c404614 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py @@ -5,164 +5,170 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + component_added = ( + "Expected component is present on entity", + "Expected component was not found on entity" + ) + component_removed = ( + "Expected component was removed from entity", + "Component is unexpectedly still present on entity" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newEntityId = None -class TestLayerExtenderNodeComponentEntitySync(EditorTestHelper): +def LayerExtenderNodes_ComponentEntitySync(): + """ + Summary: + This test verifies that all wrapped nodes can be successfully added to/removed from parent nodes. - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="LayerExtenderNodeComponentEntitySync", args=["level"]) + Expected Behavior: + All wrapped extender nodes can be added to/removed from appropriate parent nodes. - def run_test(self): - """ - Summary: - This test verifies that all wrapped nodes can be successfully added to/removed from parent nodes. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Add Area Blender and Layer Spawner nodes to the graph, and add/remove each extender node to/from each - Expected Behavior: - All wrapped extender nodes can be added to/removed from appropriate parent nodes. + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Add Area Blender and Layer Spawner nodes to the graph, and add/remove each extender node to/from each + :return: None + """ - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.paths - :return: None - """ + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - def onEntityCreated(parameters): - global newEntityId - newEntityId = parameters[0] + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) + def onEntityCreated(parameters): + global newEntityId + newEntityId = parameters[0] - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Listen for entity creation notifications so we can check if the - # proper components are added when we add nodes - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Extender mapping with the key being the node name and the value is the - # expected Component that should be added to the layer Entity for that wrapped node - extenders = { - 'AltitudeFilterNode': 'Vegetation Altitude Filter', - 'DistanceBetweenFilterNode': 'Vegetation Distance Between Filter', - 'DistributionFilterNode': 'Vegetation Distribution Filter', - 'ShapeIntersectionFilterNode': 'Vegetation Shape Intersection Filter', - 'SlopeFilterNode': 'Vegetation Slope Filter', - 'SurfaceMaskDepthFilterNode': 'Vegetation Surface Mask Depth Filter', - 'SurfaceMaskFilterNode': 'Vegetation Surface Mask Filter', - 'PositionModifierNode': 'Vegetation Position Modifier', - 'RotationModifierNode': 'Vegetation Rotation Modifier', - 'ScaleModifierNode': 'Vegetation Scale Modifier', - 'SlopeAlignmentModifierNode': 'Vegetation Slope Alignment Modifier', - 'AssetWeightSelectorNode': 'Vegetation Asset Weight Selector' - } + # Listen for entity creation notifications so we can check if the + # proper components are added when we add nodes + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) - # Retrieve a mapping of the TypeIds for all the components - # we will be checking for - componentNames = [] - for name in extenders: - componentNames.append(extenders[name]) - componentTypeIds = hydra.get_component_type_id_map(componentNames) + # Extender mapping with the key being the node name and the value is the + # expected Component that should be added to the layer Entity for that wrapped node + extenders = { + 'AltitudeFilterNode': 'Vegetation Altitude Filter', + 'DistanceBetweenFilterNode': 'Vegetation Distance Between Filter', + 'DistributionFilterNode': 'Vegetation Distribution Filter', + 'ShapeIntersectionFilterNode': 'Vegetation Shape Intersection Filter', + 'SlopeFilterNode': 'Vegetation Slope Filter', + 'SurfaceMaskDepthFilterNode': 'Vegetation Surface Mask Depth Filter', + 'SurfaceMaskFilterNode': 'Vegetation Surface Mask Filter', + 'PositionModifierNode': 'Vegetation Position Modifier', + 'RotationModifierNode': 'Vegetation Rotation Modifier', + 'ScaleModifierNode': 'Vegetation Scale Modifier', + 'SlopeAlignmentModifierNode': 'Vegetation Slope Alignment Modifier', + 'AssetWeightSelectorNode': 'Vegetation Asset Weight Selector' + } - areas = [ - 'AreaBlenderNode', - 'SpawnerAreaNode' - ] + # Retrieve a mapping of the TypeIds for all the components + # we will be checking for + componentNames = [] + for name in extenders: + componentNames.append(extenders[name]) + componentTypeIds = hydra.get_component_type_id_map(componentNames) - # Add/remove all our supported extender nodes to the Layer Areas and check if the appropriate - # Components are added/removed to the wrapper node's Entity - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for areaName in areas: - nodePosition = math.Vector2(x, y) - areaNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', - newGraph, areaName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, areaNode, nodePosition) + areas = [ + 'AreaBlenderNode', + 'SpawnerAreaNode' + ] - success = True - for extenderName in extenders: - # Add the wrapped node for the extender - extenderNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, - 'CreateNodeForTypeName', newGraph, - extenderName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, extenderNode, nodePosition) - graph.GraphControllerRequestBus(bus.Event, 'WrapNode', newGraphId, areaNode, extenderNode) + # Add/remove all our supported extender nodes to the Layer Areas and check if the appropriate + # Components are added/removed to the wrapper node's Entity + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for areaName in areas: + nodePosition = math.Vector2(x, y) + areaNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', + newGraph, areaName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, areaNode, nodePosition) - # Check that the appropriate Component was added when the extender node was added - extenderComponent = extenders[extenderName] - componentTypeId = componentTypeIds[extenderComponent] - success = success and editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, + success = True + for extenderName in extenders: + # Add the wrapped node for the extender + extenderNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, + 'CreateNodeForTypeName', newGraph, + extenderName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, extenderNode, nodePosition) + graph.GraphControllerRequestBus(bus.Event, 'WrapNode', newGraphId, areaNode, extenderNode) + + # Check that the appropriate Component was added when the extender node was added + extenderComponent = extenders[extenderName] + componentTypeId = componentTypeIds[extenderComponent] + success = success and editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, + componentTypeId) + Report.info(f"Component: {extenderComponent}") + Report.result(Tests.component_added, success) + if not success: + break + + # Check that the appropriate Component was removed when the extender node was removed + graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', newGraphId, extenderNode) + success = success and not editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, componentTypeId) - self.test_success = self.test_success and success - if not success: - self.log("{node} failed to add {component} Component".format(node=areaName, - component=extenderComponent)) - break + Report.info(f"Component: {extenderComponent}") + Report.result(Tests.component_removed, success) + if not success: + break - # Check that the appropriate Component was removed when the extender node was removed - graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', newGraphId, extenderNode) - success = success and not editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, - componentTypeId) - self.test_success = self.test_success and success - if not success: - self.log("{node} failed to remove {component} Component".format(node=areaName, - component=extenderComponent)) - break + if success: + Report.info(f"{areaName} successfully added and removed all filters/modifiers/selectors") - if success: - self.log("{node} successfully added and removed all filters/modifiers/selectors".format(node=areaName)) - - # Stop listening for entity creation notifications - handler.disconnect() + # Stop listening for entity creation notifications + handler.disconnect() -test = TestLayerExtenderNodeComponentEntitySync() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(LayerExtenderNodes_ComponentEntitySync) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/NewGraph_CreatedSuccessfully.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/NewGraph_CreatedSuccessfully.py new file mode 100644 index 0000000000..d13c5dfa2f --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/NewGraph_CreatedSuccessfully.py @@ -0,0 +1,111 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + + +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + lc_component_added = ( + "Root entity created with the Landscape Canvas component", + "Landscape Canvas component was not found on the root entity" + ) + lc_tool_closed = ( + "Landscape Canvas tool closed", + "Failed to close Landscape Canvas tool" + ) + + +new_root_entity_id = None + + +def NewGraph_CreatedSuccessfully(): + """ + Summary: + This test verifies that new graphs can be created in Landscape Canvas. + + Expected Behavior: + New graphs can be created, and proper entity is created to hold graph data with a Landscape Canvas component. + + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Ensures the root entity created contains a Landscape Canvas component + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.legacy.general as general + + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID + + def on_entity_created(parameters): + global new_root_entity_id + new_root_entity_id = parameters[0] + + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + # Listen for entity creation notifications so we can check if the entity created + # with the new graph has our Landscape Canvas component automatically added + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback("OnEditorEntityCreated", on_entity_created) + + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) + + # Create a new graph in Landscape Canvas + new_graph_id = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, new_graph_id is not None) + + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, new_graph_id) + Report.result(Tests.graph_registered, graph_registered) + + # Check if the entity created when we create a new graph has the + # Landscape Canvas component already added to it + landscape_canvas_type_id = hydra.get_component_type_id("Landscape Canvas") + success = editor.EditorComponentAPIBus(bus.Broadcast, "HasComponentOfType", new_root_entity_id, + landscape_canvas_type_id) + Report.result(Tests.lc_component_added, success) + + # Close Landscape Canvas tool and verify + general.close_pane("Landscape Canvas") + Report.result(Tests.lc_tool_closed, not general.is_pane_visible("Landscape Canvas")) + + # Stop listening for entity creation notifications + handler.disconnect() + + +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(NewGraph_CreatedSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py index 0c877535a9..93464c7ad3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py @@ -5,133 +5,136 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + component_added = ( + "New entity created with the expected component", + "Expected component was not found on entity" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newEntityId = None -class TestShapeNodeEntityCreate(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="ShapeNodeEntityCreate", args=["level"]) +def ShapeNodes_EntityCreatedOnNodeAdd(): + """ + Summary: + This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas nodes can be added to a graph, and correctly create entities. + Expected Behavior: + New entities are created when dragging shape nodes to graph area. - Expected Behavior: - New entities are created when dragging shape nodes to graph area. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the shape nodes to the graph area, and ensure a new entity is created - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Drag each of the shape nodes to the graph area, and ensure a new entity is created + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ - :return: None - """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math - def onEntityCreated(parameters): - global newEntityId - newEntityId = parameters[0] + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') + def onEntityCreated(parameters): + global newEntityId + newEntityId = parameters[0] - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") + # Open an existing simple level - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") + helper.init_idle() + helper.open_level("Physics", "Base") - # Listen for entity creation notifications so we can check if the entity created - # from adding shape nodes has the appropriate Shape Component - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) - # Shape mapping with the key being the node name and the value is the - # expected Component that should be added to the Entity created for the node - shapes = { - 'BoxShapeNode': 'Box Shape', - 'CapsuleShapeNode': 'Capsule Shape', - 'CompoundShapeNode': 'Compound Shape', - 'CylinderShapeNode': 'Cylinder Shape', - 'PolygonPrismShapeNode': 'Polygon Prism Shape', - 'SphereShapeNode': 'Sphere Shape', - 'TubeShapeNode': 'Tube Shape', - 'DiskShapeNode': 'Disk Shape' - } + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) - # Retrieve a mapping of the TypeIds for all the components - # we will be checking for - componentNames = [] - for name in shapes: - componentNames.append(shapes[name]) - componentTypeIds = hydra.get_component_type_id_map(componentNames) + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) - # Create nodes for all the shapes we support and check if the Entity created by - # adding the node has the appropriate Component added automatically to it - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for nodeName in shapes: - nodePosition = math.Vector2(x, y) - node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', - newGraph, nodeName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + # Listen for entity creation notifications so we can check if the entity created + # from adding shape nodes has the appropriate Shape Component + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) - shapeComponent = shapes[nodeName] - componentTypeId = componentTypeIds[shapeComponent] - hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, - componentTypeId) - self.test_success = self.test_success and hasComponent - if hasComponent: - self.log("{node} created new Entity with {component} Component".format(node=nodeName, - component=shapeComponent)) + # Shape mapping with the key being the node name and the value is the + # expected Component that should be added to the Entity created for the node + shapes = { + 'BoxShapeNode': 'Box Shape', + 'CapsuleShapeNode': 'Capsule Shape', + 'CompoundShapeNode': 'Compound Shape', + 'CylinderShapeNode': 'Cylinder Shape', + 'PolygonPrismShapeNode': 'Polygon Prism Shape', + 'SphereShapeNode': 'Sphere Shape', + 'TubeShapeNode': 'Tube Shape', + 'DiskShapeNode': 'Disk Shape' + } - x += 40.0 - y += 40.0 + # Retrieve a mapping of the TypeIds for all the components + # we will be checking for + componentNames = [] + for name in shapes: + componentNames.append(shapes[name]) + componentTypeIds = hydra.get_component_type_id_map(componentNames) - # Stop listening for entity creation notifications - handler.disconnect() + # Create nodes for all the shapes we support and check if the Entity created by + # adding the node has the appropriate Component added automatically to it + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for nodeName in shapes: + nodePosition = math.Vector2(x, y) + node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', + newGraph, nodeName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + + shapeComponent = shapes[nodeName] + componentTypeId = componentTypeIds[shapeComponent] + hasComponent = editor.EditorComponentAPIBus(bus.Broadcast, 'HasComponentOfType', newEntityId, + componentTypeId) + Report.info(f"Node: {nodeName} | Component: {shapeComponent}") + Report.result(Tests.component_added, hasComponent) + + x += 40.0 + y += 40.0 + + # Stop listening for entity creation notifications + handler.disconnect() -test = TestShapeNodeEntityCreate() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(ShapeNodes_EntityCreatedOnNodeAdd) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py index 2416e05fdf..d2708f643d 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py @@ -5,127 +5,129 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + entity_deleted = ( + "Entity was deleted when node was removed", + "Entity was not deleted as expected when node was removed" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID createdEntityId = None deletedEntityId = None -class TestShapeNodeEntityDelete(EditorTestHelper): +def ShapeNodes_EntityRemovedOnNodeDelete(): + """ + Summary: + This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="ShapeNodeEntityDelete", args=["level"]) + Expected Behavior: + Entities are removed when shape nodes are deleted from a graph. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas node deletion properly cleans up entities in the Editor. + Test Steps: + 1) Open a simple level + 2) Open Landscape Canvas and create a new graph + 3) Drag each of the shape nodes to the graph area, and ensure a new entity is created + 4) Delete the nodes, and ensure the newly created entities are removed - Expected Behavior: - Entities are removed when shape nodes are deleted from a graph. + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Drag each of the shape nodes to the graph area, and ensure a new entity is created - 4) Delete the nodes, and ensure the newly created entities are removed + :return: None + """ - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math - :return: None - """ + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - def onEntityCreated(parameters): - global createdEntityId - createdEntityId = parameters[0] - - def onEntityDeleted(parameters): - global deletedEntityId - deletedEntityId = parameters[0] + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) - - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') - - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") - - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") - - # Listen for entity creation/deletion notifications so we can verify the - # Entity created when adding a new also gets deleted when the node is deleted - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) - handler.add_callback('OnEditorEntityDeleted', onEntityDeleted) - - # All of the shape nodes that we support - shapes = [ - 'BoxShapeNode', - 'CapsuleShapeNode', - 'CompoundShapeNode', - 'CylinderShapeNode', - 'PolygonPrismShapeNode', - 'SphereShapeNode', - 'TubeShapeNode', - 'DiskShapeNode' - ] - - # Create nodes for all the shapes we support and check if the Entity is created - # and then deleted when the node is removed - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - x = 10.0 - y = 10.0 - for nodeName in shapes: - nodePosition = math.Vector2(x, y) - node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) - - removed = graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', newGraphId, node) - - # Verify that the created Entity for this node matches the Entity that gets - # deleted when the node is removed - self.test_success = self.test_success and removed and createdEntityId.invoke("Equal", deletedEntityId) - if removed and createdEntityId.invoke("Equal", deletedEntityId): - self.log("{node} corresponding Entity was deleted when node is removed".format(node=nodeName)) - - # Stop listening for entity creation/deletion notifications - handler.disconnect() + def onEntityCreated(parameters): + global createdEntityId + createdEntityId = parameters[0] + + def onEntityDeleted(parameters): + global deletedEntityId + deletedEntityId = parameters[0] + + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) + + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) + + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) + + # Listen for entity creation/deletion notifications so we can verify the + # Entity created when adding a new also gets deleted when the node is deleted + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) + handler.add_callback('OnEditorEntityDeleted', onEntityDeleted) + + # All of the shape nodes that we support + shapes = [ + 'BoxShapeNode', + 'CapsuleShapeNode', + 'CompoundShapeNode', + 'CylinderShapeNode', + 'PolygonPrismShapeNode', + 'SphereShapeNode', + 'TubeShapeNode', + 'DiskShapeNode' + ] + + # Create nodes for all the shapes we support and check if the Entity is created + # and then deleted when the node is removed + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + x = 10.0 + y = 10.0 + for nodeName in shapes: + nodePosition = math.Vector2(x, y) + node = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', newGraph, nodeName) + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, node, nodePosition) + + removed = graph.GraphControllerRequestBus(bus.Event, 'RemoveNode', newGraphId, node) + + # Verify that the created Entity for this node matches the Entity that gets + # deleted when the node is removed + Report.info(f"Node: {nodeName}") + Report.result(Tests.entity_deleted, removed and createdEntityId.invoke("Equal", deletedEntityId)) + + # Stop listening for entity creation/deletion notifications + handler.disconnect() -test = TestShapeNodeEntityDelete() -test.run() +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(ShapeNodes_EntityRemovedOnNodeDelete) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Slice_CreateInstantiate.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Slice_CreateInstantiate.py new file mode 100644 index 0000000000..c5ab08f99a --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Slice_CreateInstantiate.py @@ -0,0 +1,84 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + + +class Tests: + slice_created = ( + "Slice created successfully", + "Failed to create slice" + ) + slice_instantiated = ( + "Slice instantiated successfully", + "Failed to instantiate slice" + ) + + +def Slice_CreateInstantiate(): + """ + Summary: + A slice containing the LandscapeCanvas component can be created/instantiated. + + Expected Result: + Slice is created/processed/instantiated successfully and free of errors/warnings. + + Test Steps: + 1) Open a simple level + 2) Create a new entity with a Landscape Canvas component + 3) Create a slice of the new entity + 4) Instantiate a new copy of the slice + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ + + import os + + import azlmbr.math as math + import azlmbr.bus as bus + import azlmbr.asset as asset + import azlmbr.slice as slice + + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + def path_is_valid_asset(asset_path): + asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) + return asset_id.invoke("IsValid") + + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + # Create entity with Landscape Canvas component + position = math.Vector3(512.0, 512.0, 32.0) + landscape_canvas = hydra.Entity("landscape_canvas_entity") + landscape_canvas.create_entity(position, ["Landscape Canvas"]) + + # Create slice from the created entity + slice_path = os.path.join("slices", "TestSlice.slice") + slice.SliceRequestBus(bus.Broadcast, "CreateNewSlice", landscape_canvas.id, slice_path) + + # Verify if slice is created + helper.wait_for_condition(lambda: path_is_valid_asset(slice_path), 5.0) + Report.result(Tests.slice_created, path_is_valid_asset(slice_path)) + + # Instantiate slice + transform = math.Transform_CreateIdentity() + asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", slice_path, math.Uuid(), False) + test_slice = slice.SliceRequestBus(bus.Broadcast, "InstantiateSliceFromAssetId", asset_id, transform) + helper.wait_for_condition(lambda: test_slice.IsValid(), 5.0) + Report.result(Tests.slice_instantiated, test_slice.IsValid()) + + +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(Slice_CreateInstantiate) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py index 2156795b1a..3169908621 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py @@ -5,210 +5,217 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ -import os -import sys -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.editor.graph as graph -import azlmbr.landscapecanvas as landscapecanvas -import azlmbr.legacy.general as general -import azlmbr.math as math -import azlmbr.paths +class Tests: + lc_tool_opened = ( + "Landscape Canvas tool opened", + "Failed to open Landscape Canvas tool" + ) + new_graph_created = ( + "Successfully created new graph", + "Failed to create new graph" + ) + graph_registered = ( + "Graph registered with Landscape Canvas", + "Failed to register graph" + ) + preview_entity_set = ( + "Random Noise Gradient component Preview Entity property set to Box Shape EntityId", + "Unexpected entity set in Random Noise Gradient Preview Entity property" + ) + dither_inbound_gradient_set = ( + "Dither Gradient Modifier component Inbound Gradient property set to Random Noise Gradient EntityId", + "Unexpected entity set in Dither Gradient's Inbound Gradient property" + ) + mixer_inbound_gradient_set = ( + "Gradient Mixer component Inbound Gradient extendable property set to Dither Gradient Modifier EntityId", + "Unexpected entity set in Gradient Mixer's Inbound Gradient property" + ) -sys.path.append(os.path.join(azlmbr.paths.devroot, 'AutomatedTesting', 'Gem', 'PythonTests')) -import editor_python_test_tools.hydra_editor_utils as hydra -from editor_python_test_tools.editor_test_helper import EditorTestHelper -editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID newEntityId = None -class TestSlotConnectionsUpdateComponents(EditorTestHelper): - def __init__(self): - EditorTestHelper.__init__(self, log_prefix="SlotConnectionsUpdateComponents", args=["level"]) +def SlotConnections_UpdateComponentReferences(): + """ + Summary: + This test verifies that the Landscape Canvas slot connections properly update component references. - def run_test(self): - """ - Summary: - This test verifies that the Landscape Canvas slot connections properly update component references. + Expected Behavior: + A reference created through slot connections in Landscape Canvas is reflected in the Entity Inspector. - Expected Behavior: - A reference created through slot connections in Landscape Canvas is reflected in the Entity Inspector. + Test Steps: + 1) Open an existing level + 2) Open Landscape Canvas and create a new graph + 3) Several nodes are added to a graph, and connections are set between the nodes + 4) Component references are verified via Entity Inspector - Test Steps: - 1) Create a new level - 2) Open Landscape Canvas and create a new graph - 3) Several nodes are added to a graph, and connections are set between the nodes - 4) Component references are verified via Entity Inspector + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. - Note: - - This test file must be called from the Open 3D Engine Editor command terminal - - Any passed and failed tests are written to the Editor.log file. - Parsing the file or running a log_monitor are required to observe the test results. + :return: None + """ + import azlmbr.bus as bus + import azlmbr.editor as editor + import azlmbr.editor.graph as graph + import azlmbr.landscapecanvas as landscapecanvas + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.paths - :return: None - """ + import editor_python_test_tools.hydra_editor_utils as hydra + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper - # Retrieve the proper component TypeIds per component name - componentNames = [ - 'Random Noise Gradient', - 'Dither Gradient Modifier', - 'Gradient Mixer' - ] - componentTypeIds = hydra.get_component_type_id_map(componentNames) - - # Helper method for retrieving an EntityId from a specific property on a component - def getEntityIdFromComponentProperty(targetEntityId, componentTypeName, propertyPath): - componentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', targetEntityId, - componentTypeIds[componentTypeName]) - if not componentOutcome.IsSuccess(): - return None - - component = componentOutcome.GetValue() - propertyOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentProperty', component, - propertyPath) - if not propertyOutcome.IsSuccess(): - return None - - return propertyOutcome.GetValue() - - def onEntityCreated(parameters): - global newEntityId - newEntityId = parameters[0] - - # Create a new empty level - self.test_success = self.create_level( - self.args["level"], - heightmap_resolution=128, - heightmap_meters_per_pixel=1, - terrain_texture_resolution=128, - use_terrain=False, - ) - - # Open Landscape Canvas tool and verify - general.open_pane('Landscape Canvas') - self.test_success = self.test_success and general.is_pane_visible('Landscape Canvas') - if general.is_pane_visible('Landscape Canvas'): - self.log('Landscape Canvas pane is open') - - # Create a new graph in Landscape Canvas - newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) - self.test_success = self.test_success and newGraphId - if newGraphId: - self.log("New graph created") - - # Make sure the graph we created is in Landscape Canvas - success = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) - self.test_success = self.test_success and success - if success: - self.log("Graph registered with Landscape Canvas") - - # Listen for entity creation notifications so we can verify the component EntityId - # references are set correctly when connecting slots on the nodes - handler = editor.EditorEntityContextNotificationBusHandler() - handler.connect() - handler.add_callback('OnEditorEntityCreated', onEntityCreated) - - positionX = 10.0 - positionY = 10.0 - offsetX = 340.0 - offsetY = 100.0 - - # Add a box shape node to the graph - newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) - boxShapeNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', - newGraph, 'BoxShapeNode') - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, boxShapeNode, math.Vector2(positionX, - positionY)) - boxShapeEntityId = newEntityId - - positionX += offsetX - positionY += offsetY - - # Add a random noise gradient node to the graph - randomNoiseNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', - newGraph, 'RandomNoiseGradientNode') - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, randomNoiseNode, math.Vector2(positionX, - positionY)) - randomNoiseEntityId = newEntityId - - positionX += offsetX - positionY += offsetY - - # Add a dither gradient modifier node to the graph - ditherNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', - newGraph, 'DitherGradientModifierNode') - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, ditherNode, math.Vector2(positionX, - positionY)) - ditherEntityId = newEntityId - - positionX += offsetX - positionY += offsetY - - # Add a gradient mixer node to the graph - gradientMixerNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', - newGraph, 'GradientMixerNode') - graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, gradientMixerNode, math.Vector2(positionX, - positionY)) - gradientMixerEntityId = newEntityId - - boundsSlotId = graph.GraphModelSlotId('Bounds') - previewBoundsSlotId = graph.GraphModelSlotId('PreviewBounds') - inboundGradientSlotId = graph.GraphModelSlotId('InboundGradient') - outboundGradientSlotId = graph.GraphModelSlotId('OutboundGradient') - - # Connect slots on our nodes to test all slot types like so: - # Shape -> Gradient -> Gradient Modifier -> Gradient Mixer - # - # Which tests the following slot types: - # * Shape -> Preview Bounds - # * Gradient Output -> Gradient Modifier - # * Gradient Output -> Gradient Mixer (extendable slots) - graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, boxShapeNode, boundsSlotId, - randomNoiseNode, previewBoundsSlotId) - graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, randomNoiseNode, - outboundGradientSlotId, ditherNode, inboundGradientSlotId) - graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, ditherNode, - outboundGradientSlotId, gradientMixerNode, inboundGradientSlotId) - - # Delay to allow all the underlying component properties to be updated after the slot connections are made - general.idle_wait(1.0) - - # Verify the Preview EntityId property on our Random Noise Gradient component has been set to our Box Shape's - # EntityId - previewEntityId = getEntityIdFromComponentProperty(randomNoiseEntityId, 'Random Noise Gradient', - 'Preview Settings|Pin Preview to Shape') - random_gradient_success = previewEntityId and boxShapeEntityId.invoke("Equal", previewEntityId) - self.test_success = self.test_success and random_gradient_success - if random_gradient_success: - self.log("Random Noise Gradient component Preview Entity property set to Box Shape EntityId") - - # Verify the Inbound Gradient EntityId property on our Dither Gradient Modifier component has been set to our - # Random Noise Gradient's EntityId - inboundGradientEntityId = getEntityIdFromComponentProperty(ditherEntityId, 'Dither Gradient Modifier', - 'Configuration|Gradient|Gradient Entity Id') - dither_gradient_success = inboundGradientEntityId and randomNoiseEntityId.invoke("Equal", - inboundGradientEntityId) - self.test_success = self.test_success and dither_gradient_success - if dither_gradient_success: - self.log("Dither Gradient Modifier component Inbound Gradient property set to Random Noise Gradient " - "EntityId") - - # Verify the Inbound Gradient Mixer EntityId property on our Gradient Mixer component has been set to our - # Dither Gradient Modifier's EntityId - inboundGradientMixerEntityId = getEntityIdFromComponentProperty(gradientMixerEntityId, 'Gradient Mixer', - 'Configuration|Layers|[0]|Gradient|Gradient Entity Id') - gradient_mixer_success = inboundGradientMixerEntityId and ditherEntityId.invoke("Equal", - inboundGradientMixerEntityId) - self.test_success = self.test_success and gradient_mixer_success - if gradient_mixer_success: - self.log("Gradient Mixer component Inbound Gradient extendable property set to Dither Gradient Modifier " - "EntityId") - - # Stop listening for entity creation notifications - handler.disconnect() + editorId = azlmbr.globals.property.LANDSCAPE_CANVAS_EDITOR_ID -test = TestSlotConnectionsUpdateComponents() -test.run() + # Retrieve the proper component TypeIds per component name + componentNames = [ + 'Random Noise Gradient', + 'Dither Gradient Modifier', + 'Gradient Mixer' + ] + componentTypeIds = hydra.get_component_type_id_map(componentNames) + + # Helper method for retrieving an EntityId from a specific property on a component + def getEntityIdFromComponentProperty(targetEntityId, componentTypeName, propertyPath): + componentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentOfType', targetEntityId, + componentTypeIds[componentTypeName]) + + if not componentOutcome.IsSuccess(): + return None + + component = componentOutcome.GetValue() + propertyOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'GetComponentProperty', component, + propertyPath) + if not propertyOutcome.IsSuccess(): + return None + + return propertyOutcome.GetValue() + + def onEntityCreated(parameters): + global newEntityId + newEntityId = parameters[0] + + # Open an existing simple level + helper.init_idle() + helper.open_level("Physics", "Base") + + # Open Landscape Canvas tool and verify + general.open_pane('Landscape Canvas') + Report.critical_result(Tests.lc_tool_opened, general.is_pane_visible('Landscape Canvas')) + + # Create a new graph in Landscape Canvas + newGraphId = graph.AssetEditorRequestBus(bus.Event, 'CreateNewGraph', editorId) + Report.critical_result(Tests.new_graph_created, newGraphId is not None) + + # Make sure the graph we created is in Landscape Canvas + graph_registered = graph.AssetEditorRequestBus(bus.Event, 'ContainsGraph', editorId, newGraphId) + Report.result(Tests.graph_registered, graph_registered) + + # Listen for entity creation notifications so we can verify the component EntityId + # references are set correctly when connecting slots on the nodes + handler = editor.EditorEntityContextNotificationBusHandler() + handler.connect() + handler.add_callback('OnEditorEntityCreated', onEntityCreated) + + positionX = 10.0 + positionY = 10.0 + offsetX = 340.0 + offsetY = 100.0 + + # Add a box shape node to the graph + newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId) + boxShapeNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', + newGraph, 'BoxShapeNode') + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, boxShapeNode, math.Vector2(positionX, + positionY)) + boxShapeEntityId = newEntityId + + positionX += offsetX + positionY += offsetY + + # Add a random noise gradient node to the graph + randomNoiseNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', + newGraph, 'RandomNoiseGradientNode') + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, randomNoiseNode, math.Vector2(positionX, + positionY)) + randomNoiseEntityId = newEntityId + + positionX += offsetX + positionY += offsetY + + # Add a dither gradient modifier node to the graph + ditherNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', + newGraph, 'DitherGradientModifierNode') + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, ditherNode, math.Vector2(positionX, + positionY)) + ditherEntityId = newEntityId + + positionX += offsetX + positionY += offsetY + + # Add a gradient mixer node to the graph + gradientMixerNode = landscapecanvas.LandscapeCanvasNodeFactoryRequestBus(bus.Broadcast, 'CreateNodeForTypeName', + newGraph, 'GradientMixerNode') + graph.GraphControllerRequestBus(bus.Event, 'AddNode', newGraphId, gradientMixerNode, math.Vector2(positionX, + positionY)) + gradientMixerEntityId = newEntityId + + boundsSlotId = graph.GraphModelSlotId('Bounds') + previewBoundsSlotId = graph.GraphModelSlotId('PreviewBounds') + inboundGradientSlotId = graph.GraphModelSlotId('InboundGradient') + outboundGradientSlotId = graph.GraphModelSlotId('OutboundGradient') + + # Connect slots on our nodes to test all slot types like so: + # Shape -> Gradient -> Gradient Modifier -> Gradient Mixer + # + # Which tests the following slot types: + # * Shape -> Preview Bounds + # * Gradient Output -> Gradient Modifier + # * Gradient Output -> Gradient Mixer (extendable slots) + graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, boxShapeNode, boundsSlotId, + randomNoiseNode, previewBoundsSlotId) + graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, randomNoiseNode, + outboundGradientSlotId, ditherNode, inboundGradientSlotId) + graph.GraphControllerRequestBus(bus.Event, 'AddConnectionBySlotId', newGraphId, ditherNode, + outboundGradientSlotId, gradientMixerNode, inboundGradientSlotId) + + # Delay to allow all the underlying component properties to be updated after the slot connections are made + general.idle_wait(1.0) + + + # Verify the Preview EntityId property on our Random Noise Gradient component has been set to our Box Shape's + # EntityId + previewEntityId = getEntityIdFromComponentProperty(randomNoiseEntityId, 'Random Noise Gradient', + 'Preview Settings|Pin Preview to Shape') + random_gradient_success = previewEntityId and boxShapeEntityId.invoke("Equal", previewEntityId) + Report.result(Tests.preview_entity_set, random_gradient_success) + + # Verify the Inbound Gradient EntityId property on our Dither Gradient Modifier component has been set to our + # Random Noise Gradient's EntityId + inboundGradientEntityId = getEntityIdFromComponentProperty(ditherEntityId, 'Dither Gradient Modifier', + 'Configuration|Gradient|Gradient Entity Id') + dither_gradient_success = inboundGradientEntityId and randomNoiseEntityId.invoke("Equal", + inboundGradientEntityId) + Report.result(Tests.dither_inbound_gradient_set, dither_gradient_success) + + # Verify the Inbound Gradient Mixer EntityId property on our Gradient Mixer component has been set to our + # Dither Gradient Modifier's EntityId + inboundGradientMixerEntityId = getEntityIdFromComponentProperty(gradientMixerEntityId, 'Gradient Mixer', + 'Configuration|Layers|[0]|Gradient|Gradient Entity Id') + gradient_mixer_success = inboundGradientMixerEntityId and ditherEntityId.invoke("Equal", + inboundGradientMixerEntityId) + Report.result(Tests.mixer_inbound_gradient_set, gradient_mixer_success) + + # Stop listening for entity creation notifications + handler.disconnect() + + +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test(SlotConnections_UpdateComponentReferences) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Main.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Main.py new file mode 100644 index 0000000000..af4855a546 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Main.py @@ -0,0 +1,29 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +import os +import pytest +import sys + +import ly_test_tools.environment.file_system as file_system + +sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../automatedtesting_shared') +from base import TestAutomationBase + + +@pytest.mark.SUITE_main +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(TestAutomationBase): + + def test_LandscapeCanvas_SlotConnections_UpdateComponentReferences(self, request, workspace, editor, launcher_platform): + from .EditorScripts import SlotConnections_UpdateComponentReferences as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_GradientMixer_NodeConstruction(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientMixer_NodeConstruction as test_module + self._run_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Main_Optimized.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Main_Optimized.py new file mode 100644 index 0000000000..68bac24452 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Main_Optimized.py @@ -0,0 +1,22 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +import pytest + +from ly_test_tools.o3de.editor_test import EditorSingleTest, EditorSharedTest, EditorParallelTest, EditorTestSuite + + +@pytest.mark.SUITE_periodic +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(EditorTestSuite): + + class test_LandscapeCanvas_SlotConnections_UpdateComponentReferences(EditorSharedTest): + from .EditorScripts import SlotConnections_UpdateComponentReferences as test_module + + class test_LandscapeCanvas_GradientMixer_NodeConstruction(EditorSharedTest): + from .EditorScripts import GradientMixer_NodeConstruction as test_module diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Periodic.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Periodic.py new file mode 100644 index 0000000000..ef8b3e492b --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Periodic.py @@ -0,0 +1,121 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +import os +import pytest +import sys + +import ly_test_tools.environment.file_system as file_system + +sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../automatedtesting_shared') +from base import TestAutomationBase + + +@pytest.fixture +def remove_test_slice(request, workspace, project): + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "slices", "TestSlice.slice")], True, True) + + def teardown(): + file_system.delete([os.path.join(workspace.paths.engine_root(), project, "slices", "TestSlice.slice")], True, + True) + + request.addfinalizer(teardown) + + +@pytest.mark.SUITE_periodic +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(TestAutomationBase): + + def test_LandscapeCanvas_AreaNodes_DependentComponentsAdded(self, request, workspace, editor, launcher_platform): + from .EditorScripts import AreaNodes_DependentComponentsAdded as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_AreaNodes_EntityCreatedOnNodeAdd(self, request, workspace, editor, launcher_platform): + from .EditorScripts import AreaNodes_EntityCreatedOnNodeAdd as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_AreaNodes_EntityRemovedOnNodeDelete(self, request, workspace, editor, launcher_platform): + from .EditorScripts import AreaNodes_EntityRemovedOnNodeDelete as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_LayerExtenderNodes_ComponentEntitySync(self, request, workspace, editor, launcher_platform): + from .EditorScripts import LayerExtenderNodes_ComponentEntitySync as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_Edit_DisabledNodeDuplication(self, request, workspace, editor, launcher_platform): + from .EditorScripts import Edit_DisabledNodeDuplication as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_Edit_UndoNodeDelete_SliceEntity(self, request, workspace, editor, launcher_platform): + from .EditorScripts import Edit_UndoNodeDelete_SliceEntity as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_NewGraph_CreatedSuccessfully(self, request, workspace, editor, launcher_platform): + from .EditorScripts import NewGraph_CreatedSuccessfully as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_Component_AddedRemoved(self, request, workspace, editor, launcher_platform): + from .EditorScripts import Component_AddedRemoved as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_GraphClosed_OnLevelChange(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GraphClosed_OnLevelChange as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2201") + def test_LandscapeCanvas_GraphClosed_OnEntityDelete(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GraphClosed_OnEntityDelete as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_GraphClosed_TabbedGraphClosesIndependently(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GraphClosed_TabbedGraph as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_Slice_CreateInstantiate(self, request, workspace, editor, remove_test_slice, launcher_platform): + from .EditorScripts import Slice_CreateInstantiate as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_GradientModifierNodes_EntityCreatedOnNodeAdd(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientModifierNodes_EntityCreatedOnNodeAdd as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_GradientModifierNodes_EntityRemovedOnNodeDelete(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientModifierNodes_EntityRemovedOnNodeDelete as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_GradientNodes_DependentComponentsAdded(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientNodes_DependentComponentsAdded as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_GradientNodes_EntityCreatedOnNodeAdd(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientNodes_EntityCreatedOnNodeAdd as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_GradientNodes_EntityRemovedOnNodeDelete(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GradientNodes_EntityRemovedOnNodeDelete as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_GraphUpdates_UpdateComponents(self, request, workspace, editor, launcher_platform): + from .EditorScripts import GraphUpdates_UpdateComponents as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_ComponentUpdates_UpdateGraph(self, request, workspace, editor, launcher_platform): + from .EditorScripts import ComponentUpdates_UpdateGraph as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_LayerBlender_NodeConstruction(self, request, workspace, editor, launcher_platform): + from .EditorScripts import LayerBlender_NodeConstruction as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_ShapeNodes_EntityCreatedOnNodeAdd(self, request, workspace, editor, launcher_platform): + from .EditorScripts import ShapeNodes_EntityCreatedOnNodeAdd as test_module + self._run_test(request, workspace, editor, test_module) + + def test_LandscapeCanvas_ShapeNodes_EntityRemovedOnNodeDelete(self, request, workspace, editor, launcher_platform): + from .EditorScripts import ShapeNodes_EntityRemovedOnNodeDelete as test_module + self._run_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Periodic_Optimized.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Periodic_Optimized.py new file mode 100644 index 0000000000..59e8b1fe90 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_LandscapeCanvas_Periodic_Optimized.py @@ -0,0 +1,89 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +import os +import pytest + +import ly_test_tools.environment.file_system as file_system +from ly_test_tools.o3de.editor_test import EditorSingleTest, EditorSharedTest, EditorParallelTest, EditorTestSuite + + +@pytest.mark.SUITE_periodic +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(EditorTestSuite): + + class test_LandscapeCanvas_AreaNodes_DependentComponentsAdded(EditorSharedTest): + from .EditorScripts import AreaNodes_DependentComponentsAdded as test_module + + class test_LandscapeCanvas_AreaNodes_EntityCreatedOnNodeAdd(EditorSharedTest): + from .EditorScripts import AreaNodes_EntityCreatedOnNodeAdd as test_module + + class test_LandscapeCanvas_AreaNodes_EntityRemovedOnNodeDelete(EditorSharedTest): + from .EditorScripts import AreaNodes_EntityRemovedOnNodeDelete as test_module + + class test_LandscapeCanvas_LayerExtenderNodes_ComponentEntitySync(EditorSharedTest): + from .EditorScripts import LayerExtenderNodes_ComponentEntitySync as test_module + + class test_LandscapeCanvas_Edit_DisabledNodeDuplication(EditorSharedTest): + from .EditorScripts import Edit_DisabledNodeDuplication as test_module + + class test_LandscapeCanvas_Edit_UndoNodeDelete_SliceEntity(EditorSharedTest): + from .EditorScripts import Edit_UndoNodeDelete_SliceEntity as test_module + + class test_LandscapeCanvas_NewGraph_CreatedSuccessfully(EditorSharedTest): + from .EditorScripts import NewGraph_CreatedSuccessfully as test_module + + class test_LandscapeCanvas_Component_AddedRemoved(EditorSharedTest): + from .EditorScripts import Component_AddedRemoved as test_module + + class test_LandscapeCanvas_GraphClosed_OnLevelChange(EditorSharedTest): + from .EditorScripts import GraphClosed_OnLevelChange as test_module + + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/2201") + class test_LandscapeCanvas_GraphClosed_OnEntityDelete(EditorSharedTest): + from .EditorScripts import GraphClosed_OnEntityDelete as test_module + + class test_LandscapeCanvas_GraphClosed_TabbedGraphClosesIndependently(EditorSharedTest): + from .EditorScripts import GraphClosed_TabbedGraph as test_module + + class test_LandscapeCanvas_Slice_CreateInstantiate(EditorSingleTest): + # Custom teardown to remove slice asset created during test + def teardown(self, request, workspace, editor, editor_test_results, launcher_platform): + file_system.delete([os.path.join(workspace.paths.engine_root(), "AutomatedTesting", "slices", + "TestSlice.slice")], True, True) + from .EditorScripts import Slice_CreateInstantiate as test_module + + class test_LandscapeCanvas_GradientModifierNodes_EntityCreatedOnNodeAdd(EditorSharedTest): + from .EditorScripts import GradientModifierNodes_EntityCreatedOnNodeAdd as test_module + + class test_LandscapeCanvas_GradientModifierNodes_EntityRemovedOnNodeDelete(EditorSharedTest): + from .EditorScripts import GradientModifierNodes_EntityRemovedOnNodeDelete as test_module + + class test_LandscapeCanvas_GradientNodes_DependentComponentsAdded(EditorSharedTest): + from .EditorScripts import GradientNodes_DependentComponentsAdded as test_module + + class test_LandscapeCanvas_GradientNodes_EntityCreatedOnNodeAdd(EditorSharedTest): + from .EditorScripts import GradientNodes_EntityCreatedOnNodeAdd as test_module + + class test_LandscapeCanvas_GradientNodes_EntityRemovedOnNodeDelete(EditorSharedTest): + from .EditorScripts import GradientNodes_EntityRemovedOnNodeDelete as test_module + + class test_LandscapeCanvas_GraphUpdates_UpdateComponents(EditorSharedTest): + from .EditorScripts import GraphUpdates_UpdateComponents as test_module + + class test_LandscapeCanvas_ComponentUpdates_UpdateGraph(EditorSharedTest): + from .EditorScripts import ComponentUpdates_UpdateGraph as test_module + + class test_LandscapeCanvas_LayerBlender_NodeConstruction(EditorSharedTest): + from .EditorScripts import LayerBlender_NodeConstruction as test_module + + class test_LandscapeCanvas_ShapeNodes_EntityCreatedOnNodeAdd(EditorSharedTest): + from .EditorScripts import ShapeNodes_EntityCreatedOnNodeAdd as test_module + + class test_LandscapeCanvas_ShapeNodes_EntityRemovedOnNodeDelete(EditorSharedTest): + from .EditorScripts import ShapeNodes_EntityRemovedOnNodeDelete as test_module diff --git a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py index 44b7dc2ee4..7a600f7976 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_BasicWorkflow.py @@ -7,10 +7,14 @@ 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") + create_new_entity = ("'CreateNewEntity' passed", "'CreateNewEntity' failed") + create_prefab = ("'CreatePrefab' passed", "'CreatePrefab' failed") + instantiate_prefab = ("'InstantiatePrefab' passed", "'InstantiatePrefab' failed") + has_one_child = ("instantiated prefab contains only one child as expected", "instantiated prefab does *not* contain only one child as expected") + instantiated_prefab_position = ("instantiated prefab's position is at the expected position", "instantiated prefab's position is *not* at the expected position") + delete_prefab = ("'DeleteEntitiesAndAllDescendantsInInstance' passed", "'DeleteEntitiesAndAllDescendantsInInstance' failed") + instantiated_prefab_removed = ("instantiated prefab's container entity has been removed", "instantiated prefab's container entity has *not* been removed") + instantiated_child_removed = ("instantiated prefab's child entity has been removed", "instantiated prefab's child entity has *not* been removed") # fmt:on def PrefabLevel_BasicWorkflow(): @@ -18,6 +22,7 @@ def PrefabLevel_BasicWorkflow(): This test will help verify if the following functions related to Prefab work as expected: - CreatePrefab - InstantiatePrefab + - DeleteEntitiesAndAllDescendantsInInstance """ import os @@ -35,31 +40,68 @@ def PrefabLevel_BasicWorkflow(): from azlmbr.math import Vector3 import azlmbr.legacy.general as general - EXPECTED_NEW_PREFAB_POSITION = Vector3(10.00, 20.0, 30.0) + NEW_PREFAB_NAME = "new_prefab" + NEW_PREFAB_FILE_NAME = NEW_PREFAB_NAME + ".prefab" + NEW_PREFAB_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), NEW_PREFAB_FILE_NAME) + INSTANTIATED_PREFAB_POSITION = Vector3(10.00, 20.0, 30.0) + INSTANTIATED_PREFAB_NAME = "instantiated_prefab" + INSTANTIATED_CHILD_ENTITY_NAME = "child_1" + TEST_LEVEL_FOLDER = "Prefab" + TEST_LEVEL_NAME = "Base" + def find_entity_by_name(entity_name): + searchFilter = entity.SearchFilter() + searchFilter.names = [entity_name] + entityIds = entity.SearchBus(bus.Broadcast, 'SearchEntities', searchFilter) + if entityIds and entityIds[0].IsValid(): + return entityIds[0] + return None + + def print_error_if_failed(prefab_operation_result): + if not prefab_operation_result.IsSuccess(): + Report.info(f'Error message: {prefab_operation_result.GetError()}') + + +# Open the test level helper.init_idle() - helper.open_level("Prefab", "Base") + helper.open_level(TEST_LEVEL_FOLDER, TEST_LEVEL_NAME) # 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) + create_prefab_result = prefab.PrefabPublicRequestBus(bus.Broadcast, 'CreatePrefabInMemory', [new_entity_id], NEW_PREFAB_FILE_PATH) + Report.result(Tests.create_prefab, create_prefab_result.IsSuccess()) + print_error_if_failed(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()) + instantiate_prefab_result = prefab.PrefabPublicRequestBus(bus.Broadcast, 'InstantiatePrefab', NEW_PREFAB_FILE_PATH, EntityId(), INSTANTIATED_PREFAB_POSITION) + Report.result(Tests.instantiate_prefab, instantiate_prefab_result.IsSuccess() and instantiate_prefab_result.GetValue().IsValid()) + print_error_if_failed(instantiate_prefab_result) + + container_entity_id = instantiate_prefab_result.GetValue() + editor.EditorEntityAPIBus(bus.Event, 'SetName', container_entity_id, INSTANTIATED_PREFAB_NAME) + + children_entity_ids = editor.EditorEntityInfoRequestBus(bus.Event, 'GetChildren', container_entity_id) + Report.result(Tests.has_one_child, len(children_entity_ids) is 1) + + child_entity_id = children_entity_ids[0] + editor.EditorEntityAPIBus(bus.Event, 'SetName', child_entity_id, INSTANTIATED_CHILD_ENTITY_NAME) # 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) + actual_prefab_position = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", container_entity_id) + is_at_position = actual_prefab_position.IsClose(INSTANTIATED_PREFAB_POSITION) + Report.result(Tests.instantiated_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()}') - + Report.info(f'Expected position: {INSTANTIATED_PREFAB_POSITION.ToString()}, actual position: {actual_prefab_position.ToString()}') + +# Checks for prefab deletion passed or not + delete_prefab_result = prefab.PrefabPublicRequestBus(bus.Broadcast, 'DeleteEntitiesAndAllDescendantsInInstance', [container_entity_id]) + Report.result(Tests.delete_prefab, delete_prefab_result.IsSuccess()) + print_error_if_failed(delete_prefab_result) + Report.result(Tests.instantiated_prefab_removed, find_entity_by_name(INSTANTIATED_PREFAB_NAME) is None) + Report.result(Tests.instantiated_child_removed, find_entity_by_name(INSTANTIATED_CHILD_ENTITY_NAME) is None) if __name__ == "__main__": from editor_python_test_tools.utils import Report diff --git a/AutomatedTesting/Registry/C15556261_PhysXMaterials_CharacterControllerMaterialAssignment.setreg_override b/AutomatedTesting/Registry/C15556261_PhysXMaterials_CharacterControllerMaterialAssignment.setreg_override index a329434623..aa82265c98 100644 --- a/AutomatedTesting/Registry/C15556261_PhysXMaterials_CharacterControllerMaterialAssignment.setreg_override +++ b/AutomatedTesting/Registry/C15556261_PhysXMaterials_CharacterControllerMaterialAssignment.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C18977601_Material_FrictionCombinePriority.setreg_override b/AutomatedTesting/Registry/C18977601_Material_FrictionCombinePriority.setreg_override index 44a91c67cb..7050a57206 100644 --- a/AutomatedTesting/Registry/C18977601_Material_FrictionCombinePriority.setreg_override +++ b/AutomatedTesting/Registry/C18977601_Material_FrictionCombinePriority.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C18981526_Material_RestitutionCombinePriority.setreg_override b/AutomatedTesting/Registry/C18981526_Material_RestitutionCombinePriority.setreg_override index 8de10787f1..c78018bdbb 100644 --- a/AutomatedTesting/Registry/C18981526_Material_RestitutionCombinePriority.setreg_override +++ b/AutomatedTesting/Registry/C18981526_Material_RestitutionCombinePriority.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C3510644_Collider_CollisionGroups.setreg_override b/AutomatedTesting/Registry/C3510644_Collider_CollisionGroups.setreg_override index e4ea71f652..b82acaf0ae 100644 --- a/AutomatedTesting/Registry/C3510644_Collider_CollisionGroups.setreg_override +++ b/AutomatedTesting/Registry/C3510644_Collider_CollisionGroups.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C4044456_Material_FrictionCombine.setreg_override b/AutomatedTesting/Registry/C4044456_Material_FrictionCombine.setreg_override index 83f7079e1f..806d71a158 100644 --- a/AutomatedTesting/Registry/C4044456_Material_FrictionCombine.setreg_override +++ b/AutomatedTesting/Registry/C4044456_Material_FrictionCombine.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C4044457_Material_RestitutionCombine.setreg_override b/AutomatedTesting/Registry/C4044457_Material_RestitutionCombine.setreg_override index 96836b6ae4..fa77daac9f 100644 --- a/AutomatedTesting/Registry/C4044457_Material_RestitutionCombine.setreg_override +++ b/AutomatedTesting/Registry/C4044457_Material_RestitutionCombine.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C4044459_Material_DynamicFriction.setreg_override b/AutomatedTesting/Registry/C4044459_Material_DynamicFriction.setreg_override index 88a7b5c309..5deb5635d1 100644 --- a/AutomatedTesting/Registry/C4044459_Material_DynamicFriction.setreg_override +++ b/AutomatedTesting/Registry/C4044459_Material_DynamicFriction.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C4044461_Material_Restitution.setreg_override b/AutomatedTesting/Registry/C4044461_Material_Restitution.setreg_override index 21b285506b..b70e0f1326 100644 --- a/AutomatedTesting/Registry/C4044461_Material_Restitution.setreg_override +++ b/AutomatedTesting/Registry/C4044461_Material_Restitution.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C4044697_Material_PerfaceMaterialValidation.setreg_override b/AutomatedTesting/Registry/C4044697_Material_PerfaceMaterialValidation.setreg_override index d585a4c468..5a93ae2314 100644 --- a/AutomatedTesting/Registry/C4044697_Material_PerfaceMaterialValidation.setreg_override +++ b/AutomatedTesting/Registry/C4044697_Material_PerfaceMaterialValidation.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C4976227_Collider_NewGroup.setreg_override b/AutomatedTesting/Registry/C4976227_Collider_NewGroup.setreg_override index e53d3893f8..7065f0dfeb 100644 --- a/AutomatedTesting/Registry/C4976227_Collider_NewGroup.setreg_override +++ b/AutomatedTesting/Registry/C4976227_Collider_NewGroup.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C4976244_Collider_SameGroupSameLayerCollision.setreg_override b/AutomatedTesting/Registry/C4976244_Collider_SameGroupSameLayerCollision.setreg_override index e4ea71f652..b82acaf0ae 100644 --- a/AutomatedTesting/Registry/C4976244_Collider_SameGroupSameLayerCollision.setreg_override +++ b/AutomatedTesting/Registry/C4976244_Collider_SameGroupSameLayerCollision.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C4976245_PhysXCollider_CollisionLayerTest.setreg_override b/AutomatedTesting/Registry/C4976245_PhysXCollider_CollisionLayerTest.setreg_override index e4ea71f652..b82acaf0ae 100644 --- a/AutomatedTesting/Registry/C4976245_PhysXCollider_CollisionLayerTest.setreg_override +++ b/AutomatedTesting/Registry/C4976245_PhysXCollider_CollisionLayerTest.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/AutomatedTesting/Registry/C4982593_PhysXCollider_CollisionLayer.setreg_override b/AutomatedTesting/Registry/C4982593_PhysXCollider_CollisionLayer.setreg_override index e4ea71f652..b82acaf0ae 100644 --- a/AutomatedTesting/Registry/C4982593_PhysXCollider_CollisionLayer.setreg_override +++ b/AutomatedTesting/Registry/C4982593_PhysXCollider_CollisionLayer.setreg_override @@ -69,7 +69,7 @@ {}, {}, {}, - "TouchBend" + {} ] }, "Groups": { diff --git a/Code/Editor/2DViewport.cpp b/Code/Editor/2DViewport.cpp index 838d30e0b3..ed810aea29 100644 --- a/Code/Editor/2DViewport.cpp +++ b/Code/Editor/2DViewport.cpp @@ -70,9 +70,9 @@ static void OnMenuGrid() inline Vec3 SnapToSize(Vec3 v, double size) { Vec3 snapped; - snapped.x = floor((v.x / size) + 0.5) * size; - snapped.y = floor((v.y / size) + 0.5) * size; - snapped.z = floor((v.z / size) + 0.5) * size; + snapped.x = static_cast(floor((v.x / size) + 0.5) * size); + snapped.y = static_cast(floor((v.y / size) + 0.5) * size); + snapped.z = static_cast(floor((v.z / size) + 0.5) * size); return snapped; } @@ -479,8 +479,8 @@ void Q2DViewport::SetZoom(float fZoomFactor, const QPoint& center) SetZoomFactor(fZoomFactor); // Calculate new offset to center zoom on mouse. - float x2 = center.x(); - float y2 = m_rcClient.height() - center.y(); + float x2 = static_cast(center.x()); + float y2 = static_cast(m_rcClient.height() - center.y()); ofsx = -(x2 / s2 - x2 / s1 - ofsx); ofsy = -(y2 / s2 - y2 / s1 - ofsy); SetScrollOffset(ofsx, ofsy, true); @@ -544,21 +544,21 @@ void Q2DViewport::Update() QPoint Q2DViewport::WorldToView(const Vec3& wp) const { Vec3 sp = m_screenTM.TransformPoint(wp); - QPoint p = QPoint(sp.x, sp.y); + QPoint p = QPoint(static_cast(sp.x), static_cast(sp.y)); return p; } ////////////////////////////////////////////////////////////////////////// QPoint Q2DViewport::WorldToViewParticleEditor(const Vec3& wp, [[maybe_unused]] int width, [[maybe_unused]] int height) const //Eric@conffx implement for the children class of IDisplayViewport { Vec3 sp = m_screenTM.TransformPoint(wp); - QPoint p = QPoint(sp.x, sp.y); + QPoint p = QPoint(static_cast(sp.x), static_cast(sp.y)); return p; } ////////////////////////////////////////////////////////////////////////// Vec3 Q2DViewport::ViewToWorld(const QPoint& vp, [[maybe_unused]] bool* collideWithTerrain, [[maybe_unused]] bool onlyTerrain, [[maybe_unused]] bool bSkipVegetation, [[maybe_unused]] bool bTestRenderMesh, [[maybe_unused]] bool* collideWithObject) const { - Vec3 wp = m_screenTM_Inverted.TransformPoint(Vec3(vp.x(), vp.y(), 0)); + Vec3 wp = m_screenTM_Inverted.TransformPoint(Vec3(static_cast(vp.x()), static_cast(vp.y()), 0.0f)); switch (m_axis) { case VPA_XY: @@ -694,10 +694,10 @@ void Q2DViewport::DrawGrid(DisplayContext& dc, bool bNoXNumbers) Matrix34 viewTM = GetViewTM().GetInverted() * m_screenTM_Inverted; Matrix34 viewTM_Inv = m_screenTM * GetViewTM(); - Vec3 viewP0 = viewTM.TransformPoint(Vec3(0, 0, 0)); - Vec3 viewP1 = viewTM.TransformPoint(Vec3(m_rcClient.width(), m_rcClient.height(), 0)); + Vec3 viewP0 = viewTM.TransformPoint(Vec3(0.0f, 0.0f, 0.0f)); + Vec3 viewP1 = viewTM.TransformPoint(Vec3(static_cast(m_rcClient.width()), static_cast(m_rcClient.height()), 0.0f)); - Vec3 viewP_Text = viewTM.TransformPoint(Vec3(0, m_rcClient.height(), 0)); + Vec3 viewP_Text = viewTM.TransformPoint(Vec3(0.0f, static_cast(m_rcClient.height()), 0.0f)); if (m_bShowMinorGridLines && (!m_bAutoAdjustGrids || pixelsPerGrid > 5)) { @@ -806,8 +806,8 @@ void Q2DViewport::DrawGrid(DisplayContext& dc, bool bNoXNumbers) { Vec3 org = m_screenTM.TransformPoint(Vec3(0, 0, 0)); dc.SetColor(AXIS_GRID_COLOR); - dc.DrawLine(Vec3(org.x, 0, fZ), Vec3(org.x, height, fZ)); - dc.DrawLine(Vec3(0, org.y, fZ), Vec3(width, org.y, fZ)); + dc.DrawLine(Vec3(org.x, 0.0f, fZ), Vec3(org.x, static_cast(height), fZ)); + dc.DrawLine(Vec3(0.0f, org.y, fZ), Vec3(static_cast(width), org.y, fZ)); } ////////////////////////////////////////////////////////////////////////// } @@ -860,18 +860,18 @@ void Q2DViewport::DrawAxis(DisplayContext& dc) int height = m_rcClient.height(); int size = 25; - Vec3 pos(30, height - 15, 1); + Vec3 pos(30.0f, static_cast(height - 15), 1.0f); dc.SetColor(colx.x, colx.y, colx.z, 1); - dc.DrawLine(pos, pos + Vec3(size, 0, 0)); + dc.DrawLine(pos, pos + Vec3(static_cast(size), 0.0f, 0.0f)); - dc.SetColor(coly.x, coly.y, coly.z, 1); - dc.DrawLine(pos, pos - Vec3(0, size, 0)); + dc.SetColor(coly.x, coly.y, coly.z, 1.0f); + dc.DrawLine(pos, pos - Vec3(0.0f, static_cast(size), 0.0f)); dc.SetColor(m_colorAxisText); - pos.x -= 3; - pos.y -= 4; - pos.z = 2; + pos.x -= 3.0f; + pos.y -= 4.0f; + pos.z = 2.0f; dc.Draw2dTextLabel(pos.x + size + 4, pos.y - 2, 1, xstr); dc.Draw2dTextLabel(pos.x + 3, pos.y - size, 1, ystr); dc.Draw2dTextLabel(pos.x - 5, pos.y + 5, 1, zstr); @@ -910,10 +910,14 @@ void Q2DViewport::DrawSelection(DisplayContext& dc) dc.SetColor(SELECTION_RECT_COLOR.x, SELECTION_RECT_COLOR.y, SELECTION_RECT_COLOR.z, 1); QPoint p1(m_selectedRect.left(), m_selectedRect.top()); QPoint p2(m_selectedRect.right() + 1, m_selectedRect.bottom() +1); - dc.DrawLine(Vec3(p1.x(), p1.y(), 0), Vec3(p2.x(), p1.y(), 0)); - dc.DrawLine(Vec3(p1.x(), p2.y(), 0), Vec3(p2.x(), p2.y(), 0)); - dc.DrawLine(Vec3(p1.x(), p1.y(), 0), Vec3(p1.x(), p2.y(), 0)); - dc.DrawLine(Vec3(p2.x(), p1.y(), 0), Vec3(p2.x(), p2.y(), 0)); + dc.DrawLine( + Vec3(static_cast(p1.x()), static_cast(p1.y()), 0.0f), Vec3(static_cast(p2.x()), static_cast(p1.y()), 0.0f)); + dc.DrawLine( + Vec3(static_cast(p1.x()), static_cast(p2.y()), 0.0f), Vec3(static_cast(p2.x()), static_cast(p2.y()), 0.0f)); + dc.DrawLine( + Vec3(static_cast(p1.x()), static_cast(p1.y()), 0.0f), Vec3(static_cast(p1.x()), static_cast(p2.y()), 0.0f)); + dc.DrawLine( + Vec3(static_cast(p2.x()), static_cast(p1.y()), 0.0f), Vec3(static_cast(p2.x()), static_cast(p2.y()), 0.0f)); } } @@ -1038,16 +1042,16 @@ AABB Q2DViewport::GetWorldBounds(const QPoint& pnt1, const QPoint& pnt2) { case VPA_XY: case VPA_YX: - box.min.z = -maxSize; - box.max.z = maxSize; + box.min.z = static_cast(-maxSize); + box.max.z = static_cast(maxSize); break; case VPA_XZ: - box.min.y = -maxSize; - box.max.y = maxSize; + box.min.y = static_cast(-maxSize); + box.max.y = static_cast(maxSize); break; case VPA_YZ: - box.min.x = -maxSize; - box.max.x = maxSize; + box.min.x = static_cast(-maxSize); + box.max.x = static_cast(maxSize); break; } return box; @@ -1076,32 +1080,32 @@ void Q2DViewport::OnDragSelectRectangle(const QRect &rect, [[maybe_unused]] bool switch (m_axis) { case VPA_XY: - box.min.z = -maxSize; - box.max.z = maxSize; + box.min.z = static_cast(-maxSize); + box.max.z = static_cast(maxSize); w = box.max.x - box.min.x; h = box.max.y - box.min.y; sprintf_s(szNewStatusText, "X:%g Y:%g W:%g H:%g", org.x, org.y, w, h); break; case VPA_YX: - box.min.z = -maxSize; - box.max.z = maxSize; + box.min.z = static_cast(-maxSize); + box.max.z = static_cast(maxSize); w = box.max.y - box.min.y; h = box.max.x - box.min.x; sprintf_s(szNewStatusText, "X:%g Y:%g W:%g H:%g", org.x, org.y, w, h); break; case VPA_XZ: - box.min.y = -maxSize; - box.max.y = maxSize; + box.min.y = static_cast(-maxSize); + box.max.y = static_cast(maxSize); w = box.max.x - box.min.x; h = box.max.z - box.min.z; sprintf_s(szNewStatusText, "X:%g Z:%g W:%g H:%g", org.x, org.z, w, h); break; case VPA_YZ: - box.min.x = -maxSize; - box.max.x = maxSize; + box.min.x = static_cast(-maxSize); + box.max.x = static_cast(maxSize); w = box.max.y - box.min.y; h = box.max.z - box.min.z; diff --git a/Code/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp b/Code/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp index cb97632e07..b164323238 100644 --- a/Code/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp +++ b/Code/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp @@ -675,14 +675,14 @@ void AzAssetBrowserRequestHandler::OpenAssetInAssociatedEditor(const AZ::Data::A firstValidOpener = &openerDetails; } // bind a callback such that when the menu item is clicked, it sets that as the opener to use. - menu.addAction(openerDetails.m_iconToUse, QObject::tr(openerDetails.m_displayText.c_str()), mainWindow, AZStd::bind(switchToOpener, &openerDetails)); + menu.addAction(openerDetails.m_iconToUse, QObject::tr(openerDetails.m_displayText.c_str()), mainWindow, [switchToOpener, details = &openerDetails] { return switchToOpener(details); }); } } if (numValidOpeners > 1) // more than one option was added { menu.addSeparator(); - menu.addAction(QObject::tr("Cancel"), AZStd::bind(switchToOpener, nullptr)); // just something to click on to avoid doing anything. + menu.addAction(QObject::tr("Cancel"), [switchToOpener] { return switchToOpener(nullptr); }); // just something to click on to avoid doing anything. menu.exec(QCursor::pos()); } else if (numValidOpeners == 1) diff --git a/Code/Editor/BaseLibraryItem.cpp b/Code/Editor/BaseLibraryItem.cpp index 252510c951..b1fba91fad 100644 --- a/Code/Editor/BaseLibraryItem.cpp +++ b/Code/Editor/BaseLibraryItem.cpp @@ -43,7 +43,7 @@ public: //evaluate size XmlString xmlStr = m_undoCtx.node->getXML(); m_size = sizeof(CUndoBaseLibraryItem); - m_size += xmlStr.GetAllocatedMemory(); + m_size += static_cast(xmlStr.GetAllocatedMemory()); m_size += m_itemPath.length(); m_size += m_description.length(); } @@ -87,7 +87,7 @@ protected: libItem->Serialize(m_redoCtx); XmlString xmlStr = m_redoCtx.node->getXML(); - m_size += xmlStr.GetAllocatedMemory(); + m_size += static_cast(xmlStr.GetAllocatedMemory()); } //load previous saved data diff --git a/Code/Editor/BaseLibraryManager.h b/Code/Editor/BaseLibraryManager.h index 05f370e632..6f0b905760 100644 --- a/Code/Editor/BaseLibraryManager.h +++ b/Code/Editor/BaseLibraryManager.h @@ -73,7 +73,7 @@ public: virtual IDataBaseLibrary* AddLibrary(const QString& library, bool bIsLevelLibrary = false, bool bIsLoading = true) override; virtual void DeleteLibrary(const QString& library, bool forceDeleteLevel = false) override; //! Get number of libraries. - virtual int GetLibraryCount() const override { return m_libs.size(); }; + virtual int GetLibraryCount() const override { return static_cast(m_libs.size()); }; //! Get number of modified libraries. virtual int GetModifiedLibraryCount() const override; diff --git a/Code/Editor/CMakeLists.txt b/Code/Editor/CMakeLists.txt index 9baa83179b..9256fd041f 100644 --- a/Code/Editor/CMakeLists.txt +++ b/Code/Editor/CMakeLists.txt @@ -242,6 +242,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) Legacy::CryCommon AZ::AzToolsFramework AZ::AzToolsFramework.Tests + AZ::AzFrameworkTestShared AZ::AzToolsFrameworkTestCommon Legacy::EditorLib Gem::AtomToolsFramework.Static diff --git a/Code/Editor/Commands/CommandManager.cpp b/Code/Editor/Commands/CommandManager.cpp index f28ca96ac8..5f194971f5 100644 --- a/Code/Editor/Commands/CommandManager.cpp +++ b/Code/Editor/Commands/CommandManager.cpp @@ -529,8 +529,8 @@ QString CEditorCommandManager::ExecuteAndLogReturn(CCommand* pCommand, const CCo void CEditorCommandManager::GetArgsFromString(const AZStd::string& argsTxt, CCommand::CArgs& argList) { const char quoteSymbol = '\''; - int curPos = 0; - int prevPos = 0; + size_t curPos = 0; + size_t prevPos = 0; AZStd::vector tokens; AZ::StringFunc::Tokenize(argsTxt, tokens, ' '); for(AZStd::string& arg : tokens) diff --git a/Code/Editor/ConfigGroup.cpp b/Code/Editor/ConfigGroup.cpp index b18edf1142..74fe6f7b5c 100644 --- a/Code/Editor/ConfigGroup.cpp +++ b/Code/Editor/ConfigGroup.cpp @@ -33,7 +33,7 @@ namespace Config uint32 CConfigGroup::GetVarCount() { - return m_vars.size(); + return static_cast(m_vars.size()); } IConfigVar* CConfigGroup::GetVar(const char* szName) diff --git a/Code/Editor/Controls/ColorGradientCtrl.cpp b/Code/Editor/Controls/ColorGradientCtrl.cpp index 3bd3b11690..446e5810c5 100644 --- a/Code/Editor/Controls/ColorGradientCtrl.cpp +++ b/Code/Editor/Controls/ColorGradientCtrl.cpp @@ -72,7 +72,7 @@ void CColorGradientCtrl::resizeEvent(QResizeEvent* event) m_grid.rect = m_rcGradient; if (m_bNoZoom) { - m_grid.zoom.x = m_grid.rect.width(); + m_grid.zoom.x = static_cast(m_grid.rect.width()); } m_rcKeys = rc; @@ -106,11 +106,6 @@ QPoint CColorGradientCtrl::KeyToPoint(int nKey) QPoint CColorGradientCtrl::TimeToPoint(float time) { return QPoint(m_grid.WorldToClient(Vec2(time, 0)).x(), m_rcGradient.height() / 2); - - QPoint point; - point.rx() = (time - m_fMinTime) * (m_rcGradient.width() / (m_fMaxTime - m_fMinTime)) + m_rcGradient.left(); - point.ry() = m_rcGradient.height() / 2; - return point; } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/Controls/ConsoleSCB.cpp b/Code/Editor/Controls/ConsoleSCB.cpp index 093575d445..dbe7ba3472 100644 --- a/Code/Editor/Controls/ConsoleSCB.cpp +++ b/Code/Editor/Controls/ConsoleSCB.cpp @@ -220,7 +220,7 @@ void ConsoleLineEdit::keyPressEvent(QKeyEvent* ev) } // If a history command was reused directly via up arrow enter, do not reset history index - if (m_history.size() > 0 && m_historyIndex < m_history.size() && m_history[m_historyIndex] == str) + if (m_history.size() > 0 && m_historyIndex < static_cast(m_history.size()) && m_history[m_historyIndex] == str) { m_bReusedHistory = true; } @@ -833,15 +833,15 @@ static void SetEditorRange(EditorType* editor, IVariable* var) // If this variable has custom limits set, then use that as the min/max // Otherwise, the min/max for the input box will be bounded by the type // limit, but the slider will be constricted to a smaller default range - static const double defaultMin = -100.0f; - static const double defaultMax = 100.0f; + static const float defaultMin = -100.0f; + static const float defaultMax = 100.0f; if (var->HasCustomLimits()) { - editor->setRange(min, max); + editor->setRange(static_cast(min), static_cast(max)); } else { - editor->setSoftRange(defaultMin, defaultMax); + editor->setSoftRange(static_cast(defaultMin), static_cast(defaultMax)); } // Set the step size. The default variable step is 0, so if it's @@ -850,7 +850,7 @@ static void SetEditorRange(EditorType* editor, IVariable* var) // use that for the int values if (step > 0) { - editor->spinbox()->setSingleStep(step); + editor->spinbox()->setSingleStep(static_cast(step)); } else if (auto doubleSpinBox = qobject_cast(editor->spinbox())) { diff --git a/Code/Editor/Controls/ImageHistogramCtrl.cpp b/Code/Editor/Controls/ImageHistogramCtrl.cpp index 7218c0cd38..252bf4f09b 100644 --- a/Code/Editor/Controls/ImageHistogramCtrl.cpp +++ b/Code/Editor/Controls/ImageHistogramCtrl.cpp @@ -175,7 +175,7 @@ void CImageHistogramDisplay::paintEvent([[maybe_unused]] QPaintEvent* event) penSpikes = penColor; painter.setPen(Qt::black); painter.setBrush(Qt::white); - rcGraph = QRect(QPoint(m_graphMargin, m_graphMargin), QPoint(abs(rc.width() - m_graphMargin), abs(rc.height() * m_graphHeightPercent))); + rcGraph = QRect(QPoint(m_graphMargin, m_graphMargin), QPoint(abs(rc.width() - m_graphMargin), static_cast(abs(rc.height() * m_graphHeightPercent)))); painter.drawRect(rcGraph); painter.setPen(penSpikes); @@ -193,7 +193,7 @@ void CImageHistogramDisplay::paintEvent([[maybe_unused]] QPaintEvent* event) { float scale = 0; - i = ((float)x / graphWidth) * (kNumColorLevels - 1); + i = static_cast(((float)x / graphWidth) * (kNumColorLevels - 1)); i = CLAMP(i, 0, kNumColorLevels - 1); switch (m_drawMode) @@ -244,8 +244,8 @@ void CImageHistogramDisplay::paintEvent([[maybe_unused]] QPaintEvent* event) } } - crtX = rcGraph.left() + x + 1; - painter.drawLine(crtX, graphBottom, crtX, graphBottom - scale * graphHeight); + crtX = static_cast(rcGraph.left() + x + 1); + painter.drawLine(crtX, graphBottom, crtX, static_cast(graphBottom - scale * graphHeight)); } } else @@ -258,9 +258,9 @@ void CImageHistogramDisplay::paintEvent([[maybe_unused]] QPaintEvent* event) for (size_t x = 0, xCount = abs(rcGraph.width()); x < xCount; ++x) { - i = ((float)x / graphWidth) * (kNumColorLevels - 1); + i = static_cast(((float)x / graphWidth) * (kNumColorLevels - 1)); i = CLAMP(i, 0, kNumColorLevels - 1); - crtX = rcGraph.left() + x + 1; + crtX = static_cast(rcGraph.left() + x + 1); scaleR = scaleG = scaleB = scaleA = 0; if (m_maxCount[0]) @@ -283,10 +283,10 @@ void CImageHistogramDisplay::paintEvent([[maybe_unused]] QPaintEvent* event) scaleA = (float)m_count[3][i] / m_maxCount[3]; } - heightR = graphBottom - scaleR * graphHeight; - heightG = graphBottom - scaleG * graphHeight; - heightB = graphBottom - scaleB * graphHeight; - heightA = graphBottom - scaleA * graphHeight; + heightR = static_cast(graphBottom - scaleR * graphHeight); + heightG = static_cast(graphBottom - scaleG * graphHeight); + heightB = static_cast(graphBottom - scaleB * graphHeight); + heightA = static_cast(graphBottom - scaleA * graphHeight); if (lastHeight[0] == INT_MAX) { @@ -350,7 +350,7 @@ void CImageHistogramDisplay::paintEvent([[maybe_unused]] QPaintEvent* event) for (size_t x = 0, xCount = abs(rcGraph.width()); x < xCount; ++x) { pos = (float)x / graphWidth; - i = (float)((int)(pos * kNumColorLevels) % aThirdOfNumColorLevels) / aThirdOfNumColorLevels * kNumColorLevels; + i = static_cast((float)((int)(pos * kNumColorLevels) % aThirdOfNumColorLevels) / aThirdOfNumColorLevels * kNumColorLevels); i = CLAMP(i, 0, kNumColorLevels - 1); scale = 0; @@ -385,7 +385,7 @@ void CImageHistogramDisplay::paintEvent([[maybe_unused]] QPaintEvent* event) } painter.setPen(pPen); - painter.drawLine(rcGraph.left() + x + 1, graphBottom, rcGraph.left() + x + 1, graphBottom - scale * graphHeight); + painter.drawLine(rcGraph.left() + static_cast(x) + 1, graphBottom, rcGraph.left() + static_cast(x) + 1, static_cast(graphBottom - scale * graphHeight)); } // then draw 3 lines so we separate the channels diff --git a/Code/Editor/Controls/QBitmapPreviewDialogImp.cpp b/Code/Editor/Controls/QBitmapPreviewDialogImp.cpp index c438858e81..b47a535d2a 100644 --- a/Code/Editor/Controls/QBitmapPreviewDialogImp.cpp +++ b/Code/Editor/Controls/QBitmapPreviewDialogImp.cpp @@ -422,7 +422,7 @@ void QBitmapPreviewDialogImp::paintEvent(QPaintEvent* e) curr_x = histogramRect.left() + x + 1; - int i = ((float)x / (graphWidth - 1)) * (CImageHistogram::kNumColorLevels - 1); + int i = static_cast(((float)x / (graphWidth - 1)) * (CImageHistogram::kNumColorLevels - 1)); if (m_histrogramMode == eHistogramMode_SplitRGB) { // Filter out to area which we are interested @@ -446,7 +446,7 @@ void QBitmapPreviewDialogImp::paintEvent(QPaintEvent* e) scale = (float)m_histogram.m_count[c][i] / m_histogram.m_maxCount[c]; } - int height = graphBottom - graphHeight * scale; + int height = static_cast(graphBottom - graphHeight * scale); if (last_height == INT_MAX) { last_height = height; diff --git a/Code/Editor/Controls/ReflectedPropertyControl/PropertyAnimationCtrl.cpp b/Code/Editor/Controls/ReflectedPropertyControl/PropertyAnimationCtrl.cpp index fde5642b05..4fb18e438c 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/PropertyAnimationCtrl.cpp +++ b/Code/Editor/Controls/ReflectedPropertyControl/PropertyAnimationCtrl.cpp @@ -56,8 +56,8 @@ CReflectedVarAnimation AnimationPropertyCtrl::value() const void AnimationPropertyCtrl::OnApplyClicked() { QStringList cSelectedAnimations; - size_t nTotalAnimations(0); - size_t nCurrentAnimation(0); + int nTotalAnimations(0); + int nCurrentAnimation(0); QString combinedString = GetIEditor()->GetResourceSelectorHost()->GetGlobalSelection("animation"); SplitString(combinedString, cSelectedAnimations, ','); diff --git a/Code/Editor/Controls/ReflectedPropertyControl/PropertyMiscCtrl.cpp b/Code/Editor/Controls/ReflectedPropertyControl/PropertyMiscCtrl.cpp index 92c33aefc2..b9f7e12e95 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/PropertyMiscCtrl.cpp +++ b/Code/Editor/Controls/ReflectedPropertyControl/PropertyMiscCtrl.cpp @@ -145,7 +145,7 @@ bool UserPopupWidgetHandler::ReadValuesIntoGUI(size_t index, UserPropertyEditor* QWidget* FloatCurveHandler::CreateGUI(QWidget *pParent) { CSplineCtrl *cSpline = new CSplineCtrl(pParent); - cSpline->SetUpdateCallback(AZStd::bind(&FloatCurveHandler::OnSplineChange, this, AZStd::placeholders::_1)); + cSpline->SetUpdateCallback([this](CSplineCtrl* spl) { OnSplineChange(spl); }); cSpline->SetTimeRange(0, 1); cSpline->SetValueRange(0, 1); cSpline->SetGrid(12, 12); diff --git a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.cpp b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.cpp index 1a7060aa8d..40ea71f577 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.cpp +++ b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.cpp @@ -203,7 +203,7 @@ void ReflectedPropertyControl::CreateItems(XmlNodeRef node, CVarBlockPtr& outBlo outBlockPtr = new CVarBlock; for (size_t i = 0, iGroupCount(node->getChildCount()); i < iGroupCount; ++i) { - XmlNodeRef groupNode = node->getChild(i); + XmlNodeRef groupNode = node->getChild(static_cast(i)); if (groupNode->haveAttr("hidden")) { @@ -308,7 +308,7 @@ void ReflectedPropertyControl::CreateItems(XmlNodeRef node, CVarBlockPtr& outBlo int nMin(0), nMax(0); if (child->getAttr("min", nMin) && child->getAttr("max", nMax)) { - intVar->SetLimits(nMin, nMax); + intVar->SetLimits(static_cast(nMin), static_cast(nMax)); } } else if (!azstricmp(type, "float")) @@ -560,7 +560,7 @@ void ReflectedPropertyControl::RequestPropertyContextMenu(AzToolsFramework::Inst // Popup Menu with Event selection. QMenu menu; - UINT i = 0; + unsigned int i = 0; const int ePPA_CustomItemBase = 10; // reserved from 10 to 99 const int ePPA_CustomPopupBase = 100; // reserved from 100 to x*100+100 where x is size of m_customPopupMenuPopups @@ -595,12 +595,12 @@ void ReflectedPropertyControl::RequestPropertyContextMenu(AzToolsFramework::Inst action->setData(ePPA_CustomItemBase + i); } - for (UINT j = 0; j < m_customPopupMenuPopups.size(); ++j) + for (unsigned int j = 0; j < m_customPopupMenuPopups.size(); ++j) { SCustomPopupMenu* pMenuInfo = &m_customPopupMenuPopups[j]; QMenu* pSubMenu = menu.addMenu(pMenuInfo->m_text); - for (UINT k = 0; k < pMenuInfo->m_subMenuText.size(); ++k) + for (UINT k = 0; k < static_cast(pMenuInfo->m_subMenuText.size()); ++k) { const UINT uID = ePPA_CustomPopupBase + ePPA_CustomPopupBase * j + k; QAction *action = pSubMenu->addAction(pMenuInfo->m_subMenuText[k]); diff --git a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp index 303f86d270..af418c6e0d 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp +++ b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp @@ -172,8 +172,8 @@ ReflectedPropertyItem::ReflectedPropertyItem(ReflectedPropertyControl *control, if (parent) parent->AddChild(this); - m_onSetCallback = AZStd::bind(&ReflectedPropertyItem::OnVariableChange, this, AZStd::placeholders::_1); - m_onSetEnumCallback = AZStd::bind(&ReflectedPropertyItem::OnVariableEnumChange, this, AZStd::placeholders::_1); + m_onSetCallback = [this](IVariable* var) { OnVariableChange(var); }; + m_onSetEnumCallback = [this](IVariable* var) { OnVariableEnumChange(var); }; } ReflectedPropertyItem::~ReflectedPropertyItem() diff --git a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp index aba346ce6a..b3f1b35461 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp +++ b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp @@ -39,20 +39,20 @@ namespace { hardMin = desc.m_bHardMin; hardMax = desc.m_bHardMax; } - reflectedVar->m_softMinVal = min; - reflectedVar->m_softMaxVal = max; + reflectedVar->m_softMinVal = static_cast(min); + reflectedVar->m_softMaxVal = static_cast(max); if (hardMin) { - reflectedVar->m_minVal = min; + reflectedVar->m_minVal = static_cast(min); } else { - reflectedVar->m_minVal = std::numeric_limits::lowest(); + reflectedVar->m_minVal = std::numeric_limits::lowest(); } if (hardMax) { - reflectedVar->m_maxVal = max; + reflectedVar->m_maxVal = static_cast(max); } else { @@ -64,9 +64,9 @@ namespace { ../Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp:59:38: error: implicit conversion from 'int' to 'float' changes value from 2147483647 to 2147483648 [-Werror,-Wimplicit-int-float-conversion] reflectedVar->m_maxVal = std::numeric_limits::max(); */ - reflectedVar->m_maxVal = static_cast(std::numeric_limits::max()); + reflectedVar->m_maxVal = static_cast(std::numeric_limits::max()); } - reflectedVar->m_stepSize = step; + reflectedVar->m_stepSize = static_cast(step); } } @@ -95,9 +95,9 @@ void ReflectedVarIntAdapter::SyncReflectedVarToIVar(IVariable *pVariable) { int intValue; pVariable->Get(intValue); - value = intValue; + value = static_cast(intValue); } - m_reflectedVar->m_value = std::round(value * m_valueMultiplier); + m_reflectedVar->m_value = static_cast(std::round(value * m_valueMultiplier)); } void ReflectedVarIntAdapter::SyncIVarToReflectedVar(IVariable *pVariable) @@ -362,14 +362,14 @@ void ReflectedVarColorAdapter::SyncReflectedVarToIVar(IVariable *pVariable) Vec3 v(0, 0, 0); pVariable->Get(v); const QColor col = ColorLinearToGamma(ColorF(v.x, v.y, v.z)); - m_reflectedVar->m_color.Set(col.redF(), col.greenF(), col.blueF()); + m_reflectedVar->m_color.Set(static_cast(col.redF()), static_cast(col.greenF()), static_cast(col.blueF())); } else { int col(0); pVariable->Get(col); const QColor qcolor = ColorToQColor((uint32)col); - m_reflectedVar->m_color.Set(qcolor.redF(), qcolor.greenF(), qcolor.blueF()); + m_reflectedVar->m_color.Set(static_cast(qcolor.redF()), static_cast(qcolor.greenF()), static_cast(qcolor.blueF())); } } @@ -382,9 +382,9 @@ void ReflectedVarColorAdapter::SyncIVarToReflectedVar(IVariable *pVariable) } else { - int ir = m_reflectedVar->m_color.GetX() * 255.0f; - int ig = m_reflectedVar->m_color.GetY() * 255.0f; - int ib = m_reflectedVar->m_color.GetZ() * 255.0f; + int ir = static_cast(m_reflectedVar->m_color.GetX() * 255.0f); + int ig = static_cast(m_reflectedVar->m_color.GetY() * 255.0f); + int ib = static_cast(m_reflectedVar->m_color.GetZ() * 255.0f); pVariable->Set(static_cast(RGB(ir, ig, ib))); } diff --git a/Code/Editor/Controls/SplineCtrl.cpp b/Code/Editor/Controls/SplineCtrl.cpp index d66fc16ade..80d30b37ad 100644 --- a/Code/Editor/Controls/SplineCtrl.cpp +++ b/Code/Editor/Controls/SplineCtrl.cpp @@ -86,13 +86,13 @@ QPoint CSplineCtrl::KeyToPoint(int nKey) QPoint CSplineCtrl::TimeToPoint(float time) { QPoint point; - point.setX((time - m_fMinTime) * (m_rcSpline.width() / (m_fMaxTime - m_fMinTime)) + m_rcSpline.left()); + point.setX(static_cast((time - m_fMinTime) * (m_rcSpline.width() / (m_fMaxTime - m_fMinTime)) + m_rcSpline.left())); float val = 0; if (m_pSpline) { m_pSpline->InterpolateFloat(time, val); } - point.setY((floor((m_fMaxValue - val) * (m_rcSpline.height() / (m_fMaxValue - m_fMinValue)) + 0.5f) + m_rcSpline.top())); + point.setY(static_cast((floor((m_fMaxValue - val) * (m_rcSpline.height() / (m_fMaxValue - m_fMinValue)) + 0.5f) + m_rcSpline.top()))); return point; } diff --git a/Code/Editor/Controls/SplineCtrlEx.cpp b/Code/Editor/Controls/SplineCtrlEx.cpp index 5977aff105..f299ce185d 100644 --- a/Code/Editor/Controls/SplineCtrlEx.cpp +++ b/Code/Editor/Controls/SplineCtrlEx.cpp @@ -641,7 +641,7 @@ QPoint AbstractSplineWidget::TimeToPoint(float time, ISplineInterpolator* pSplin ////////////////////////////////////////////////////////////////////////// float AbstractSplineWidget::TimeToXOfs(float x) { - return WorldToClient(Vec2(float(x), 0.0f)).x(); + return static_cast(WorldToClient(Vec2(float(x), 0.0f)).x()); } ////////////////////////////////////////////////////////////////////////// @@ -832,8 +832,8 @@ void SplineWidget::DrawSpline(QPainter* painter, SSplineInfo& splineInfo, float int nTotalNumberOfDimensions(0); int nCurrentDimension(0); - int left = TimeToXOfs(startTime);//rcClip.left; - int right = TimeToXOfs(endTime);//rcClip.right; + int left = static_cast(TimeToXOfs(startTime));//rcClip.left; + int right = static_cast(TimeToXOfs(endTime));//rcClip.right; QPoint p0 = TimeToPoint(pSpline->GetKeyTime(0), pSpline); QPoint p1 = TimeToPoint(pSpline->GetKeyTime(pSpline->GetKeyCount() - 1), pSpline); @@ -898,7 +898,7 @@ void SplineWidget::DrawSpline(QPainter* painter, SSplineInfo& splineInfo, float if ((x == right && pointsInLine >= 0) || (pointsInLine > 0 && fabs(lineStart.y() + gradient * (pt.x() - lineStart.x()) - pt.y()) > 1.0f)) { - lineStart = QPoint(pt.x() - 1, lineStart.y() + gradient * (pt.x() - 1 - lineStart.x())); + lineStart = QPoint(pt.x() - 1, static_cast(lineStart.y() + gradient * (pt.x() - 1 - lineStart.x()))); path.lineTo(lineStart); gradient = float(pt.y() - lineStart.y()) / (pt.x() - lineStart.x()); pointsInLine = 1; @@ -1063,7 +1063,7 @@ void SplineWidget::DrawTimeMarker(QPainter* painter) float x = TimeToXOfs(m_fTimeMarker); if (x >= m_rcSpline.left() && x <= m_rcSpline.right() + 1) { - painter->drawLine(x, m_rcSpline.top(), x, m_rcSpline.bottom() + 1); + painter->drawLine(static_cast(x), m_rcSpline.top(), static_cast(x), m_rcSpline.bottom() + 1); } painter->setPen(pOldPen); } @@ -1583,7 +1583,7 @@ bool AbstractSplineWidget::IsKeySelected(ISplineInterpolator* pSpline, int nKey, int AbstractSplineWidget::GetNumSelected() { int nSelected = 0; - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { if (ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline) { @@ -1818,7 +1818,7 @@ AbstractSplineWidget::EHitCode AbstractSplineWidget::HitTest(const QPoint& point } // For each Spline... - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; ISplineInterpolator* pDetailSpline = m_splines[splineIndex].pDetailSpline; @@ -1856,7 +1856,7 @@ AbstractSplineWidget::EHitCode AbstractSplineWidget::HitTest(const QPoint& point // Check tangent handles first. { QPoint incomingHandlePt, outgoingHandlePt, pt; - if (GetTangentHandlePts(incomingHandlePt, pt, outgoingHandlePt, splineIndex, i, nCurrentDimension)) + if (GetTangentHandlePts(incomingHandlePt, pt, outgoingHandlePt, static_cast(splineIndex), static_cast(i), nCurrentDimension)) { // For the incoming handle if (abs(incomingHandlePt.x() - point.x()) < 4 && abs(incomingHandlePt.y() - point.y()) < 4) @@ -1973,7 +1973,7 @@ void AbstractSplineWidget::ScaleAmplitudeKeys(float time, float startValue, floa m_nHitKeyIndex = -1; m_nHitDimension = -1; - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; @@ -2077,7 +2077,7 @@ void AbstractSplineWidget::TimeScaleKeys(float time, float startTime, float endT float affectedRangeMin = FLT_MAX; float affectedRangeMax = -FLT_MAX; - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; @@ -2145,8 +2145,8 @@ void AbstractSplineWidget::TimeScaleKeys(float time, float startTime, float endT } } - int rangeMin = TimeToXOfs(affectedRangeMin); - int rangeMax = TimeToXOfs(affectedRangeMax); + int rangeMin = static_cast(TimeToXOfs(affectedRangeMin)); + int rangeMax = static_cast(TimeToXOfs(affectedRangeMax)); if (m_timeRange.start == affectedRangeMin) { @@ -2184,7 +2184,7 @@ void AbstractSplineWidget::ValueScaleKeys(float startValue, float endValue) m_nHitKeyIndex = -1; m_nHitDimension = -1; - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; @@ -2223,7 +2223,7 @@ void AbstractSplineWidget::MoveSelectedKeys(Vec2 offset, bool copyKeys) } // For each spline... - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; @@ -2298,7 +2298,7 @@ void AbstractSplineWidget::RemoveSelectedKeys() m_pHitDetailSpline = nullptr; m_nHitKeyIndex = -1; - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; @@ -2338,7 +2338,7 @@ void AbstractSplineWidget::RemoveSelectedKeyTimesImpl() StoreUndo(); SendNotifyEvent(SPLN_BEFORE_CHANGE); - for (int splineIndex = 0, end = m_splines.size(); splineIndex < end; ++splineIndex) + for (size_t splineIndex = 0, end = m_splines.size(); splineIndex < end; ++splineIndex) { std::vector::iterator itTime = m_keyTimes.begin(), endTime = m_keyTimes.end(); for (int keyIndex = 0, endIndex = m_splines[splineIndex].pSpline->GetKeyCount(); keyIndex < endIndex; ) @@ -2376,9 +2376,9 @@ void AbstractSplineWidget::RedrawWindowAroundMarker() { UpdateKeyTimes(); std::vector::iterator itKeyTime = std::lower_bound(m_keyTimes.begin(), m_keyTimes.end(), KeyTime(m_fTimeMarker, 0)); - int keyTimeIndex = (itKeyTime != m_keyTimes.end() ? itKeyTime - m_keyTimes.begin() : m_keyTimes.size()); - int redrawRangeStart = (keyTimeIndex >= 2 ? TimeToXOfs(m_keyTimes[keyTimeIndex - 2].time) : m_rcSpline.left()); - int redrawRangeEnd = (keyTimeIndex < int(m_keyTimes.size()) - 2 ? TimeToXOfs(m_keyTimes[keyTimeIndex + 2].time) : m_rcSpline.right() + 1); + size_t keyTimeIndex = (itKeyTime != m_keyTimes.end() ? itKeyTime - m_keyTimes.begin() : m_keyTimes.size()); + int redrawRangeStart = (keyTimeIndex >= 2 ? static_cast(TimeToXOfs(m_keyTimes[keyTimeIndex - 2].time)) : m_rcSpline.left()); + int redrawRangeEnd = (keyTimeIndex < m_keyTimes.size() - 2 ? static_cast(TimeToXOfs(m_keyTimes[keyTimeIndex + 2].time)) : m_rcSpline.right() + 1); QRect rc(QPoint(redrawRangeStart, m_rcSpline.top()), QPoint(redrawRangeEnd, m_rcSpline.bottom() + 1) - QPoint(1, 1)); rc = rc.normalized().intersected(m_rcSpline); @@ -2478,7 +2478,7 @@ void AbstractSplineWidget::ClearSelection() { ConditionalStoreUndo(); - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; @@ -2521,7 +2521,7 @@ void AbstractSplineWidget::StoreUndo() if (CUndo::IsRecording() && !m_pCurrentUndo) { std::vector splines(m_splines.size()); - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { splines[splineIndex] = m_splines[splineIndex].pSpline; } @@ -2564,7 +2564,7 @@ void AbstractSplineWidget::DuplicateSelectedKeys() using KeysToAddContainer = std::vector; KeysToAddContainer keysToInsert; - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; @@ -2664,7 +2664,7 @@ void AbstractSplineWidget::KeyAll() ////////////////////////////////////////////////////////////////////////// void AbstractSplineWidget::SelectAll() { - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; @@ -2815,7 +2815,7 @@ void AbstractSplineWidget::SelectRectangle(const QRect& rc, bool bSelect) { std::swap(t0, t1); } - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; ISplineInterpolator* pDetailSpline = m_splines[splineIndex].pDetailSpline; @@ -3031,7 +3031,7 @@ void AbstractSplineWidget::ModifySelectedKeysFlags(int nRemoveFlags, int nAddFla SendNotifyEvent(SPLN_BEFORE_CHANGE); - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; @@ -3188,7 +3188,7 @@ void AbstractSplineWidget::GotoNextKey(bool previousKey) { bool boFoundTheSelectedKey(false); - for (int splineIndex = 0, endSpline = m_splines.size(); splineIndex < endSpline; ++splineIndex) + for (size_t splineIndex = 0, endSpline = m_splines.size(); splineIndex < endSpline; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; for (int i = 0; i < pSpline->GetKeyCount(); i++) @@ -3230,7 +3230,7 @@ void AbstractSplineWidget::GotoNextKey(bool previousKey) } else { - for (int splineIndex = 0, endSpline = m_splines.size(); splineIndex < endSpline; ++splineIndex) + for (size_t splineIndex = 0, endSpline = m_splines.size(); splineIndex < endSpline; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; @@ -3281,7 +3281,7 @@ void AbstractSplineWidget::RemoveAllKeysButThis() { std::vector keys; - for (int splineIndex = 0, endSpline = m_splines.size(); splineIndex < endSpline; ++splineIndex) + for (size_t splineIndex = 0, endSpline = m_splines.size(); splineIndex < endSpline; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; diff --git a/Code/Editor/Controls/SplineCtrlEx.h b/Code/Editor/Controls/SplineCtrlEx.h index add4bcb0a9..711cbcf8d4 100644 --- a/Code/Editor/Controls/SplineCtrlEx.h +++ b/Code/Editor/Controls/SplineCtrlEx.h @@ -98,7 +98,7 @@ public: void AddSpline(ISplineInterpolator * pSpline, ISplineInterpolator * pDetailSpline, QColor anColorArray[4]); void RemoveSpline(ISplineInterpolator* pSpline); void RemoveAllSplines(); - int GetSplineCount() const { return m_splines.size(); } + int GetSplineCount() const { return static_cast(m_splines.size()); } ISplineInterpolator* GetSpline(int nIndex) const { return m_splines[nIndex].pSpline; } void SetTimeMarker(float fTime); diff --git a/Code/Editor/Controls/TextEditorCtrl.cpp b/Code/Editor/Controls/TextEditorCtrl.cpp index 5961c9d9a3..c372138d80 100644 --- a/Code/Editor/Controls/TextEditorCtrl.cpp +++ b/Code/Editor/Controls/TextEditorCtrl.cpp @@ -53,7 +53,7 @@ void CTextEditorCtrl::LoadFile(const QString& sFileName) size_t length = file.GetLength(); QByteArray text; - text.resize(length); + text.resize(static_cast(length)); file.ReadRaw(text.data(), length); setPlainText(text); diff --git a/Code/Editor/Controls/TimelineCtrl.cpp b/Code/Editor/Controls/TimelineCtrl.cpp index a5a941fc78..8159084784 100644 --- a/Code/Editor/Controls/TimelineCtrl.cpp +++ b/Code/Editor/Controls/TimelineCtrl.cpp @@ -25,9 +25,9 @@ static const QColor ltgrayCol = QColor(110, 110, 110); QColor InterpolateColor(const QColor& c1, const QColor& c2, float fraction) { - const int r = (c2.red() - c1.red()) * fraction + c1.red(); - const int g = (c2.green() - c1.green()) * fraction + c1.green(); - const int b = (c2.blue() - c1.blue()) * fraction + c1.blue(); + const int r = static_cast(static_cast(c2.red() - c1.red()) * fraction + c1.red()); + const int g = static_cast(static_cast(c2.green() - c1.green()) * fraction + c1.green()); + const int b = static_cast(static_cast(c2.blue() - c1.blue()) * fraction + c1.blue()); return QColor(r, g, b); } @@ -120,7 +120,7 @@ float TimelineWidget::SnapTime(float time) { double t = floor((double)time * m_ticksStep + 0.5); t = t / m_ticksStep; - return t; + return static_cast(t); } ////////////////////////////////////////////////////////////////////////// @@ -153,10 +153,10 @@ void TimelineWidget::DrawTicks(QPainter* painter) painter->setPen(redpen); int x = TimeToClient(m_fTimeMarker); painter->setBrush(Qt::NoBrush); - painter->drawRect(QRect(QPoint(x - 3, rc.top()), QPoint(x + 2, rc.bottom()))); + painter->drawRect(QRect(QPoint(x - 3, static_cast(rc.top())), QPoint(x + 2, static_cast(rc.bottom())))); painter->setPen(redpen); - painter->drawLine(x, rc.top(), x, rc.bottom()); + painter->drawLine(x, static_cast(rc.top()), x, static_cast(rc.bottom())); painter->setBrush(Qt::NoBrush); // Draw vertical line showing current time. @@ -190,7 +190,7 @@ void TimelineWidget::DrawTicks(QPainter* painter) float keyTime = (m_pKeyTimeSet ? m_pKeyTimeSet->GetKeyTime(keyTimeIndex) : 0.0f); int x2 = TimeToClient(keyTime); - painter->drawRect(QRect(QPoint(x2 - 1, rc.top()), QPoint(x2 + 2, rc.bottom()))); + painter->drawRect(QRect(QPoint(x2 - 1, static_cast(rc.top())), QPoint(x2 + 2, static_cast(rc.bottom())))); } painter->setPen(pOldPen); diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index 8444f81317..280613815e 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -613,7 +613,7 @@ public: } // Get boolean options - const int numOptions = options.size(); + const int numOptions = static_cast(options.size()); for (int i = 0; i < numOptions; ++i) { options[i].second = parser.isSet(options[i].first); @@ -3240,7 +3240,7 @@ bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled) { QFileInfo info(fullyQualifiedLevelName); const AZStd::string rawProjectDirectory = Path::GetEditingGameDataFolder(); - const QString projectDirectory = QDir::toNativeSeparators(QString::fromUtf8(rawProjectDirectory.data(), rawProjectDirectory.size())); + const QString projectDirectory = QDir::toNativeSeparators(QString::fromUtf8(rawProjectDirectory.data(), static_cast(rawProjectDirectory.size()))); const QString elidedLevelName = QStringLiteral("%1...%2").arg(levelName.left(10)).arg(levelName.right(10)); const QString elidedLevelFileName = QStringLiteral("%1...%2").arg(info.fileName().left(10)).arg(info.fileName().right(10)); const QString message = QObject::tr( @@ -3380,7 +3380,7 @@ CCryEditDoc* CCryEditApp::OpenDocumentFile(const char* lpszFileName) void CCryEditApp::OnResourcesReduceworkingset() { #ifdef WIN32 // no such thing on macOS - SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1); + SetProcessWorkingSetSize(GetCurrentProcess(), std::numeric_limits::max(), std::numeric_limits::max()); #endif } @@ -3922,7 +3922,7 @@ void CCryEditApp::OpenLUAEditor(const char* files) void CCryEditApp::PrintAlways(const AZStd::string& output) { - m_stdoutRedirection.WriteBypassingRedirect(output.c_str(), output.size()); + m_stdoutRedirection.WriteBypassingRedirect(output.c_str(), static_cast(output.size())); } QString CCryEditApp::GetRootEnginePath() const diff --git a/Code/Editor/CryEditDoc.cpp b/Code/Editor/CryEditDoc.cpp index 90b020f452..e5988918f5 100644 --- a/Code/Editor/CryEditDoc.cpp +++ b/Code/Editor/CryEditDoc.cpp @@ -1047,7 +1047,7 @@ static bool TryRenameFile(const QString& oldPath, const QString& newPath, int re bool CCryEditDoc::SaveLevel(const QString& filename) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); QWaitCursor wait; CAutoCheckOutDialogEnableForAll enableForAll; @@ -1067,7 +1067,7 @@ bool CCryEditDoc::SaveLevel(const QString& filename) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "CCryEditDoc::SaveLevel BackupBeforeSave"); + AZ_PROFILE_SCOPE(AzToolsFramework, "CCryEditDoc::SaveLevel BackupBeforeSave"); BackupBeforeSave(); } @@ -1178,7 +1178,7 @@ bool CCryEditDoc::SaveLevel(const QString& filename) CPakFile pakFile; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "CCryEditDoc::SaveLevel Open PakFile"); + AZ_PROFILE_SCOPE(AzToolsFramework, "CCryEditDoc::SaveLevel Open PakFile"); if (!pakFile.Open(tempSaveFile.toUtf8().data(), false)) { gEnv->pLog->LogWarning("Unable to open pack file %s for writing", tempSaveFile.toUtf8().data()); @@ -1209,7 +1209,7 @@ bool CCryEditDoc::SaveLevel(const QString& filename) AZ::IO::ByteContainerStream> entitySaveStream(&entitySaveBuffer); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "CCryEditDoc::SaveLevel Save Entities To Stream"); + AZ_PROFILE_SCOPE(AzToolsFramework, "CCryEditDoc::SaveLevel Save Entities To Stream"); EBUS_EVENT_RESULT( savedEntities, AzToolsFramework::EditorEntityContextRequestBus, SaveToStreamForEditor, entitySaveStream, layerEntities, instancesInLayers); @@ -1223,8 +1223,8 @@ bool CCryEditDoc::SaveLevel(const QString& filename) if (savedEntities) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "CCryEditDoc::SaveLevel Updated PakFile levelEntities.editor_xml"); - pakFile.UpdateFile("LevelEntities.editor_xml", entitySaveBuffer.begin(), entitySaveBuffer.size()); + AZ_PROFILE_SCOPE(AzToolsFramework, "CCryEditDoc::SaveLevel Updated PakFile levelEntities.editor_xml"); + pakFile.UpdateFile("LevelEntities.editor_xml", entitySaveBuffer.begin(), static_cast(entitySaveBuffer.size())); // Save XML archive to pak file. bool bSaved = xmlAr.SaveToPak(Path::GetPath(tempSaveFile), pakFile); @@ -2055,7 +2055,7 @@ void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar) } // QVariant will not convert a void * to int, so do it manually. - int nKey = reinterpret_cast(pVar->GetUserData().value()); + int nKey = static_cast(reinterpret_cast(pVar->GetUserData().value())); int nGroup = (nKey & 0xFFFF0000) >> 16; int nChild = (nKey & 0x0000FFFF); diff --git a/Code/Editor/DisplaySettings.cpp b/Code/Editor/DisplaySettings.cpp index dc4cf083a9..ed4ca180b4 100644 --- a/Code/Editor/DisplaySettings.cpp +++ b/Code/Editor/DisplaySettings.cpp @@ -46,7 +46,7 @@ void CDisplaySettings::SaveRegistry() SaveValue("Settings", "RenderFlags", m_renderFlags); SaveValue("Settings", "DisplayFlags", m_flags & SETTINGS_SERIALIZABLE_FLAGS_MASK); SaveValue("Settings", "DebugFlags", m_debugFlags); - SaveValue("Settings", "LabelsDistance", m_labelsDistance); + SaveValue("Settings", "LabelsDistance", static_cast(m_labelsDistance)); } void CDisplaySettings::LoadRegistry() @@ -56,9 +56,9 @@ void CDisplaySettings::LoadRegistry() LoadValue("Settings", "DisplayFlags", m_flags); m_flags &= SETTINGS_SERIALIZABLE_FLAGS_MASK; LoadValue("Settings", "DebugFlags", m_debugFlags); - int temp = m_labelsDistance; + int temp = static_cast(m_labelsDistance); LoadValue("Settings", "LabelsDistance", temp); - m_labelsDistance = temp; + m_labelsDistance = static_cast(temp); gSettings.objectHideMask = m_objectHideMask; } diff --git a/Code/Editor/EditMode/SubObjectSelectionReferenceFrameCalculator.cpp b/Code/Editor/EditMode/SubObjectSelectionReferenceFrameCalculator.cpp index cf7cf5e959..80368d3ec1 100644 --- a/Code/Editor/EditMode/SubObjectSelectionReferenceFrameCalculator.cpp +++ b/Code/Editor/EditMode/SubObjectSelectionReferenceFrameCalculator.cpp @@ -44,14 +44,14 @@ bool SubObjectSelectionReferenceFrameCalculator::GetFrame(Matrix34& refFrame) if (this->nNormals > 0) { - this->normal = this->normal / this->nNormals; + this->normal = this->normal / static_cast(this->nNormals); if (!this->normal.IsZero()) { this->normal.Normalize(); } // Average position. - this->pos = this->pos / this->nNormals; + this->pos = this->pos / static_cast(this->nNormals); refFrame.SetTranslation(this->pos); } diff --git a/Code/Editor/EditorDefs.h b/Code/Editor/EditorDefs.h index 6614fa4d72..423f4c5f73 100644 --- a/Code/Editor/EditorDefs.h +++ b/Code/Editor/EditorDefs.h @@ -33,18 +33,6 @@ #include #include -// Warnings in STL -#pragma warning (disable : 4786) // identifier was truncated to 'number' characters in the debug information. -#pragma warning (disable : 4244) // conversion from 'long' to 'float', possible loss of data -#pragma warning (disable : 4018) // signed/unsigned mismatch - -// Disable warning when a function returns a value inside an __asm block -#pragma warning (disable : 4035) - -////////////////////////////////////////////////////////////////////////// -// 64-bits related warnings. -#pragma warning (disable : 4267) // conversion from 'size_t' to 'int', possible loss of data - ////////////////////////////////////////////////////////////////////////// // Simple type definitions. ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/EditorPreferencesPageViewportGeneral.cpp b/Code/Editor/EditorPreferencesPageViewportGeneral.cpp index 1fc0d14988..a9eec22e69 100644 --- a/Code/Editor/EditorPreferencesPageViewportGeneral.cpp +++ b/Code/Editor/EditorPreferencesPageViewportGeneral.cpp @@ -201,20 +201,24 @@ void CEditorPreferencesPage_ViewportGeneral::OnApply() ds->SetLabelsDistance(m_textLabels.m_labelsDistance); gSettings.objectColorSettings.fChildGeomAlpha = m_selectionPreviewColor.m_childObjectGeomAlpha; - gSettings.objectColorSettings.entityHighlight = QColor(m_selectionPreviewColor.m_colorEntityBBox.GetR() * 255.0f, - m_selectionPreviewColor.m_colorEntityBBox.GetG() * 255.0f, - m_selectionPreviewColor.m_colorEntityBBox.GetB() * 255.0f); - gSettings.objectColorSettings.groupHighlight = QColor(m_selectionPreviewColor.m_colorGroupBBox.GetR() * 255.0f, - m_selectionPreviewColor.m_colorGroupBBox.GetG() * 255.0f, - m_selectionPreviewColor.m_colorGroupBBox.GetB() * 255.0f); + gSettings.objectColorSettings.entityHighlight = QColor( + static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetR() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetG() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetB() * 255.0f)); + gSettings.objectColorSettings.groupHighlight = QColor( + static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetR() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetG() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetB() * 255.0f)); gSettings.objectColorSettings.fBBoxAlpha = m_selectionPreviewColor.m_fBBoxAlpha; gSettings.objectColorSettings.fGeomAlpha = m_selectionPreviewColor.m_fgeomAlpha; - gSettings.objectColorSettings.geometryHighlightColor = QColor(m_selectionPreviewColor.m_geometryHighlightColor.GetR() * 255.0f, - m_selectionPreviewColor.m_geometryHighlightColor.GetG() * 255.0f, - m_selectionPreviewColor.m_geometryHighlightColor.GetB() * 255.0f); - gSettings.objectColorSettings.solidBrushGeometryColor = QColor(m_selectionPreviewColor.m_solidBrushGeometryColor.GetR() * 255.0f, - m_selectionPreviewColor.m_solidBrushGeometryColor.GetG() * 255.0f, - m_selectionPreviewColor.m_solidBrushGeometryColor.GetB() * 255.0f); + gSettings.objectColorSettings.geometryHighlightColor = QColor( + static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetR() * 255.0f), + static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetG() * 255.0f), + static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetB() * 255.0f)); + gSettings.objectColorSettings.solidBrushGeometryColor = QColor( + static_cast(m_selectionPreviewColor.m_solidBrushGeometryColor.GetR() * 255.0f), + static_cast(m_selectionPreviewColor.m_solidBrushGeometryColor.GetG() * 255.0f), + static_cast(m_selectionPreviewColor.m_solidBrushGeometryColor.GetB() * 255.0f)); } void CEditorPreferencesPage_ViewportGeneral::InitializeSettings() @@ -252,10 +256,10 @@ void CEditorPreferencesPage_ViewportGeneral::InitializeSettings() m_textLabels.m_labelsDistance = ds->GetLabelsDistance(); m_selectionPreviewColor.m_childObjectGeomAlpha = gSettings.objectColorSettings.fChildGeomAlpha; - m_selectionPreviewColor.m_colorEntityBBox.Set(gSettings.objectColorSettings.entityHighlight.redF(), gSettings.objectColorSettings.entityHighlight.greenF(), gSettings.objectColorSettings.entityHighlight.blueF(), 1.0f); - m_selectionPreviewColor.m_colorGroupBBox.Set(gSettings.objectColorSettings.groupHighlight.redF(), gSettings.objectColorSettings.groupHighlight.greenF(), gSettings.objectColorSettings.groupHighlight.blueF(), 1.0f); + m_selectionPreviewColor.m_colorEntityBBox.Set(static_cast(gSettings.objectColorSettings.entityHighlight.redF()), static_cast(gSettings.objectColorSettings.entityHighlight.greenF()), static_cast(gSettings.objectColorSettings.entityHighlight.blueF()), 1.0f); + m_selectionPreviewColor.m_colorGroupBBox.Set(static_cast(gSettings.objectColorSettings.groupHighlight.redF()), static_cast(gSettings.objectColorSettings.groupHighlight.greenF()), static_cast(gSettings.objectColorSettings.groupHighlight.blueF()), 1.0f); m_selectionPreviewColor.m_fBBoxAlpha = gSettings.objectColorSettings.fBBoxAlpha; m_selectionPreviewColor.m_fgeomAlpha = gSettings.objectColorSettings.fGeomAlpha; - m_selectionPreviewColor.m_geometryHighlightColor.Set(gSettings.objectColorSettings.geometryHighlightColor.redF(), gSettings.objectColorSettings.geometryHighlightColor.greenF(), gSettings.objectColorSettings.geometryHighlightColor.blueF(), 1.0f); - m_selectionPreviewColor.m_solidBrushGeometryColor.Set(gSettings.objectColorSettings.solidBrushGeometryColor.redF(), gSettings.objectColorSettings.solidBrushGeometryColor.greenF(), gSettings.objectColorSettings.solidBrushGeometryColor.blueF(), 1.0f); + m_selectionPreviewColor.m_geometryHighlightColor.Set(static_cast(gSettings.objectColorSettings.geometryHighlightColor.redF()), static_cast(gSettings.objectColorSettings.geometryHighlightColor.greenF()), static_cast(gSettings.objectColorSettings.geometryHighlightColor.blueF()), 1.0f); + m_selectionPreviewColor.m_solidBrushGeometryColor.Set(static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.redF()), static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.greenF()), static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.blueF()), 1.0f); } diff --git a/Code/Editor/EditorViewportSettings.cpp b/Code/Editor/EditorViewportSettings.cpp index 680592a597..6e0ed86d2a 100644 --- a/Code/Editor/EditorViewportSettings.cpp +++ b/Code/Editor/EditorViewportSettings.cpp @@ -31,6 +31,8 @@ namespace SandboxEditor constexpr AZStd::string_view CameraPanSpeedSetting = "/Amazon/Preferences/Editor/Camera/PanSpeed"; constexpr AZStd::string_view CameraRotateSmoothnessSetting = "/Amazon/Preferences/Editor/Camera/RotateSmoothness"; constexpr AZStd::string_view CameraTranslateSmoothnessSetting = "/Amazon/Preferences/Editor/Camera/TranslateSmoothness"; + constexpr AZStd::string_view CameraTranslateSmoothingSetting = "/Amazon/Preferences/Editor/Camera/TranslateSmoothing"; + constexpr AZStd::string_view CameraRotateSmoothingSetting = "/Amazon/Preferences/Editor/Camera/RotateSmoothing"; constexpr AZStd::string_view CameraTranslateForwardIdSetting = "/Amazon/Preferences/Editor/Camera/CameraTranslateForwardId"; constexpr AZStd::string_view CameraTranslateBackwardIdSetting = "/Amazon/Preferences/Editor/Camera/CameraTranslateBackwardId"; constexpr AZStd::string_view CameraTranslateLeftIdSetting = "/Amazon/Preferences/Editor/Camera/CameraTranslateLeftId"; @@ -259,6 +261,26 @@ namespace SandboxEditor SetRegistry(CameraTranslateSmoothnessSetting, smoothness); } + bool CameraRotateSmoothingEnabled() + { + return GetRegistry(CameraRotateSmoothingSetting, true); + } + + void SetCameraRotateSmoothingEnabled(const bool enabled) + { + SetRegistry(CameraRotateSmoothingSetting, enabled); + } + + bool CameraTranslateSmoothingEnabled() + { + return GetRegistry(CameraTranslateSmoothingSetting, true); + } + + void SetCameraTranslateSmoothingEnabled(const bool enabled) + { + SetRegistry(CameraTranslateSmoothingSetting, enabled); + } + AzFramework::InputChannelId CameraTranslateForwardChannelId() { return AzFramework::InputChannelId( diff --git a/Code/Editor/EditorViewportSettings.h b/Code/Editor/EditorViewportSettings.h index b1488c5528..1aca51395f 100644 --- a/Code/Editor/EditorViewportSettings.h +++ b/Code/Editor/EditorViewportSettings.h @@ -80,6 +80,12 @@ namespace SandboxEditor SANDBOX_API float CameraTranslateSmoothness(); SANDBOX_API void SetCameraTranslateSmoothness(float smoothness); + SANDBOX_API bool CameraRotateSmoothingEnabled(); + SANDBOX_API void SetCameraRotateSmoothingEnabled(bool enabled); + + SANDBOX_API bool CameraTranslateSmoothingEnabled(); + SANDBOX_API void SetCameraTranslateSmoothingEnabled(bool enabled); + SANDBOX_API AzFramework::InputChannelId CameraTranslateForwardChannelId(); SANDBOX_API void SetCameraTranslateForwardChannelId(AZStd::string_view cameraTranslateForwardId); diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 28e8cce33e..ec965cc51f 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -132,12 +132,11 @@ namespace AZ::ViewportHelpers { static const char TextCantCreateCameraNoLevel[] = "Cannot create camera when no level is loaded."; - class EditorEntityNotifications - : public AzToolsFramework::EditorEntityContextNotificationBus::Handler + class EditorEntityNotifications : public AzToolsFramework::EditorEntityContextNotificationBus::Handler { public: - EditorEntityNotifications(EditorViewportWidget& renderViewport) - : m_renderViewport(renderViewport) + EditorEntityNotifications(EditorViewportWidget& editorViewportWidget) + : m_editorViewportWidget(editorViewportWidget) { AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusConnect(); } @@ -147,22 +146,24 @@ namespace AZ::ViewportHelpers AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusDisconnect(); } - // AzToolsFramework::EditorEntityContextNotificationBus + // AzToolsFramework::EditorEntityContextNotificationBus overrides ... void OnStartPlayInEditor() override { - m_renderViewport.OnStartPlayInEditor(); + m_editorViewportWidget.OnStartPlayInEditor(); } + void OnStopPlayInEditor() override { - m_renderViewport.OnStopPlayInEditor(); + m_editorViewportWidget.OnStopPlayInEditor(); } + void OnStartPlayInEditorBegin() override { - m_renderViewport.OnStartPlayInEditorBegin(); + m_editorViewportWidget.OnStartPlayInEditorBegin(); } private: - EditorViewportWidget& m_renderViewport; + EditorViewportWidget& m_editorViewportWidget; }; } // namespace AZ::ViewportHelpers @@ -284,7 +285,7 @@ void EditorViewportWidget::paintEvent([[maybe_unused]] QPaintEvent* event) const char* kFontName = "Arial"; const QColor kTextColor(255, 255, 255); const QColor kTextShadowColor(0, 0, 0); - const QFont font(kFontName, kFontSize / 10.0); + const QFont font(kFontName, static_cast(kFontSize / 10.0f)); painter.setFont(font); QString friendlyName = QFileInfo(GetIEditor()->GetLevelName()).fileName(); @@ -815,29 +816,35 @@ void EditorViewportWidget::UpdateSafeFrame() float maxSafeFrameWidth = m_safeFrame.height() * targetAspectRatio; float widthDifference = m_safeFrame.width() - maxSafeFrameWidth; - m_safeFrame.setLeft(m_safeFrame.left() + widthDifference * 0.5); - m_safeFrame.setRight(m_safeFrame.right() - widthDifference * 0.5); + m_safeFrame.setLeft(static_cast(m_safeFrame.left() + widthDifference * 0.5f)); + m_safeFrame.setRight(static_cast(m_safeFrame.right() - widthDifference * 0.5f)); } else { float maxSafeFrameHeight = m_safeFrame.width() / targetAspectRatio; float heightDifference = m_safeFrame.height() - maxSafeFrameHeight; - m_safeFrame.setTop(m_safeFrame.top() + heightDifference * 0.5); - m_safeFrame.setBottom(m_safeFrame.bottom() - heightDifference * 0.5); + m_safeFrame.setTop(static_cast(m_safeFrame.top() + heightDifference * 0.5f)); + m_safeFrame.setBottom(static_cast(m_safeFrame.bottom() - heightDifference * 0.5f)); } m_safeFrame.adjust(0, 0, -1, -1); // <-- aesthetic improvement. const float SAFE_ACTION_SCALE_FACTOR = 0.05f; m_safeAction = m_safeFrame; - m_safeAction.adjust(m_safeFrame.width() * SAFE_ACTION_SCALE_FACTOR, m_safeFrame.height() * SAFE_ACTION_SCALE_FACTOR, - -m_safeFrame.width() * SAFE_ACTION_SCALE_FACTOR, -m_safeFrame.height() * SAFE_ACTION_SCALE_FACTOR); + m_safeAction.adjust( + static_cast(m_safeFrame.width() * SAFE_ACTION_SCALE_FACTOR), + static_cast(m_safeFrame.height() * SAFE_ACTION_SCALE_FACTOR), + static_cast(-m_safeFrame.width() * SAFE_ACTION_SCALE_FACTOR), + static_cast(-m_safeFrame.height() * SAFE_ACTION_SCALE_FACTOR)); const float SAFE_TITLE_SCALE_FACTOR = 0.1f; m_safeTitle = m_safeFrame; - m_safeTitle.adjust(m_safeFrame.width() * SAFE_TITLE_SCALE_FACTOR, m_safeFrame.height() * SAFE_TITLE_SCALE_FACTOR, - -m_safeFrame.width() * SAFE_TITLE_SCALE_FACTOR, -m_safeFrame.height() * SAFE_TITLE_SCALE_FACTOR); + m_safeTitle.adjust( + static_cast(m_safeFrame.width() * SAFE_TITLE_SCALE_FACTOR), + static_cast(m_safeFrame.height() * SAFE_TITLE_SCALE_FACTOR), + static_cast(-m_safeFrame.width() * SAFE_TITLE_SCALE_FACTOR), + static_cast(-m_safeFrame.height() * SAFE_TITLE_SCALE_FACTOR)); } ////////////////////////////////////////////////////////////////////////// @@ -856,8 +863,8 @@ void EditorViewportWidget::RenderSafeFrame(const QRect& frame, float r, float g, const int LINE_WIDTH = 2; for (int i = 0; i < LINE_WIDTH; i++) { - AZ::Vector3 topLeft(frame.left() + i, frame.top() + i, 0); - AZ::Vector3 bottomRight(frame.right() - i, frame.bottom() - i, 0); + AZ::Vector3 topLeft(static_cast(frame.left() + i), static_cast(frame.top() + i), 0.0f); + AZ::Vector3 bottomRight(static_cast(frame.right() - i), static_cast(frame.bottom() - i), 0.0f); m_debugDisplay->DrawWireBox(topLeft, bottomRight); } } @@ -1027,10 +1034,16 @@ bool EditorViewportWidget::ShowingWorldSpace() } AZStd::shared_ptr CreateModularViewportCameraController( - AzFramework::ViewportId viewportId) + const AzFramework::ViewportId viewportId) { auto controller = AZStd::make_shared(); + controller->SetCameraViewportContextBuilderCallback( + [viewportId](AZStd::unique_ptr& cameraViewportContext) + { + cameraViewportContext = AZStd::make_unique(viewportId); + }); + controller->SetCameraPriorityBuilderCallback( [](AtomToolsFramework::CameraControllerPriorityFn& cameraControllerPriorityFn) { @@ -1049,6 +1062,16 @@ AZStd::shared_ptr CreateMod { return SandboxEditor::CameraTranslateSmoothness(); }; + + cameraProps.m_rotateSmoothingEnabledFn = [] + { + return SandboxEditor::CameraRotateSmoothingEnabled(); + }; + + cameraProps.m_translateSmoothingEnabledFn = [] + { + return SandboxEditor::CameraTranslateSmoothingEnabled(); + }; }); controller->SetCameraListBuilderCallback( @@ -1477,7 +1500,7 @@ bool EditorViewportWidget::AddCameraMenuItems(QMenu* menu) Camera::CameraBus::BroadcastResult(getCameraResults, &Camera::CameraRequests::GetCameras); QVector additionalCameras; - additionalCameras.reserve(getCameraResults.values.size()); + additionalCameras.reserve(static_cast(getCameraResults.values.size())); for (const AZ::EntityId& entityId : getCameraResults.values) { @@ -1899,7 +1922,7 @@ void EditorViewportWidget::RenderSelectedRegion() // Draw volume dc.DepthWriteOff(); dc.CullOff(); - dc.pRenderAuxGeom->DrawTriangles(&verts[0], verts.size(), &inds[0], numInds, &colors[0]); + dc.pRenderAuxGeom->DrawTriangles(&verts[0], static_cast(verts.size()), &inds[0], numInds, &colors[0]); dc.CullOn(); dc.DepthWriteOn(); } @@ -1915,8 +1938,8 @@ Vec3 EditorViewportWidget::WorldToView3D(const Vec3& wp, [[maybe_unused]] int nF { out.x = (x / 100) * m_rcClient.width(); out.y = (y / 100) * m_rcClient.height(); - out.x /= QHighDpiScaling::factor(windowHandle()->screen()); - out.y /= QHighDpiScaling::factor(windowHandle()->screen()); + out.x /= static_cast(QHighDpiScaling::factor(windowHandle()->screen())); + out.y /= static_cast(QHighDpiScaling::factor(windowHandle()->screen())); out.z = z; } return out; @@ -1936,8 +1959,8 @@ QPoint EditorViewportWidget::WorldToViewParticleEditor(const Vec3& wp, int width ProjectToScreen(wp.x, wp.y, wp.z, &x, &y, &z); if (_finite(x) || _finite(y)) { - p.rx() = (x / 100) * width; - p.ry() = (y / 100) * height; + p.rx() = static_cast((x / 100) * width); + p.ry() = static_cast((y / 100) * height); } else { @@ -1950,7 +1973,7 @@ QPoint EditorViewportWidget::WorldToViewParticleEditor(const Vec3& wp, int width Vec3 EditorViewportWidget::ViewToWorld( const QPoint& vp, bool* collideWithTerrain, bool onlyTerrain, bool bSkipVegetation, bool bTestRenderMesh, bool* collideWithObject) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); AZ_UNUSED(collideWithTerrain) AZ_UNUSED(onlyTerrain) @@ -1985,7 +2008,7 @@ Vec3 EditorViewportWidget::ViewToWorldNormal(const QPoint& vp, bool onlyTerrain, AZ_UNUSED(onlyTerrain) AZ_UNUSED(bTestRenderMesh) - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); return Vec3(0, 0, 1); } @@ -2091,8 +2114,8 @@ void EditorViewportWidget::UnProjectFromScreen(float sx, float sy, float sz, flo void EditorViewportWidget::ProjectToScreen(float ptx, float pty, float ptz, float* sx, float* sy, float* sz) const { AzFramework::ScreenPoint screenPosition = m_renderViewport->ViewportWorldToScreen(AZ::Vector3{ptx, pty, ptz}); - *sx = screenPosition.m_x; - *sy = screenPosition.m_y; + *sx = static_cast(screenPosition.m_x); + *sy = static_cast(screenPosition.m_y); *sz = 0.f; } @@ -2103,7 +2126,7 @@ void EditorViewportWidget::ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& Vec3 pos0, pos1; float wx, wy, wz; - UnProjectFromScreen(vp.x(), rc.bottom() - vp.y(), 0, &wx, &wy, &wz); + UnProjectFromScreen(static_cast(vp.x()), static_cast(rc.bottom() - vp.y()), 0.0f, &wx, &wy, &wz); if (!_finite(wx) || !_finite(wy) || !_finite(wz)) { return; @@ -2113,7 +2136,7 @@ void EditorViewportWidget::ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& return; } pos0(wx, wy, wz); - UnProjectFromScreen(vp.x(), rc.bottom() - vp.y(), 1, &wx, &wy, &wz); + UnProjectFromScreen(static_cast(vp.x()), static_cast(rc.bottom() - vp.y()), 1.0f, &wx, &wy, &wz); if (!_finite(wx) || !_finite(wy) || !_finite(wz)) { return; @@ -2611,7 +2634,6 @@ void EditorViewportWidget::ShowCursor() ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::PushDisableRendering() { - assert(m_disableRenderingCount >= 0); ++m_disableRenderingCount; } diff --git a/Code/Editor/EditorViewportWidget.h b/Code/Editor/EditorViewportWidget.h index 33ed001735..a75928b353 100644 --- a/Code/Editor/EditorViewportWidget.h +++ b/Code/Editor/EditorViewportWidget.h @@ -54,7 +54,8 @@ namespace AZ::ViewportHelpers namespace AtomToolsFramework { class RenderViewportWidget; -} + class ModularViewportCameraController; +} // namespace AtomToolsFramework namespace AzToolsFramework { @@ -389,3 +390,7 @@ private: AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING }; + +//! Creates a modular camera controller in the configuration used by the editor viewport. +SANDBOX_API AZStd::shared_ptr CreateModularViewportCameraController( + const AzFramework::ViewportId viewportId); diff --git a/Code/Editor/ErrorReportTableModel.cpp b/Code/Editor/ErrorReportTableModel.cpp index c0c24bb7ce..f5dce1a86d 100644 --- a/Code/Editor/ErrorReportTableModel.cpp +++ b/Code/Editor/ErrorReportTableModel.cpp @@ -45,7 +45,7 @@ bool GetPositionFromString(QString er, float* x, float* y, float* z) } if (ind > 0) { - *x = er.mid(0, ind).toDouble(); + *x = er.mid(0, ind).toFloat(); er = er.mid(ind); er.remove(QRegExp("^[ ,]*")); @@ -57,12 +57,12 @@ bool GetPositionFromString(QString er, float* x, float* y, float* z) } if (ind > 0) { - *y = er.mid(0, ind).toDouble(); + *y = er.mid(0, ind).toFloat(); er = er.mid(ind); er.remove(QRegExp("^[ ,]*")); if (er.length()) { - *z = er.toDouble(); + *z = er.toFloat(); return true; } } @@ -119,7 +119,7 @@ void CErrorReportTableModel::setErrorReport(CErrorReport* report) int CErrorReportTableModel::rowCount(const QModelIndex& parent) const { - return parent.isValid() ? 0 : m_errorRecords.size(); + return parent.isValid() ? 0 : static_cast(m_errorRecords.size()); } int CErrorReportTableModel::columnCount(const QModelIndex& parent) const diff --git a/Code/Editor/Export/ExportManager.cpp b/Code/Editor/Export/ExportManager.cpp index 5abd3ab5d0..7601740033 100644 --- a/Code/Editor/Export/ExportManager.cpp +++ b/Code/Editor/Export/ExportManager.cpp @@ -40,15 +40,6 @@ namespace { - void SetTexture(Export::TPath& outName, IRenderShaderResources* pRes, int nSlot) - { - SEfResTexture* pTex = pRes->GetTextureResource(nSlot); - if (pTex) - { - azstrcat(outName, AZ_ARRAY_SIZE(outName), Path::GamePathToFullPath(pTex->m_Name.c_str()).toUtf8().data()); - } - } - inline Export::Vector3D Vec3ToVector3D(const Vec3& vec) { Export::Vector3D ret; @@ -302,7 +293,7 @@ void CExportManager::ProcessEntityAnimationTrack( return; } - for (int trackNumber = 0; trackNumber < pEntityTrack->GetChildCount(); ++trackNumber) + for (unsigned int trackNumber = 0; trackNumber < pEntityTrack->GetChildCount(); ++trackNumber) { CTrackViewTrack* pSubTrack = static_cast(pEntityTrack->GetChild(trackNumber)); @@ -964,7 +955,7 @@ bool CExportManager::AddObjectsFromSequence(CTrackViewSequence* pSequence, XmlNo } const uint numKeys = pSequenceTrack->GetKeyCount(); - for (int keyIndex = 0; keyIndex < numKeys; ++keyIndex) + for (uint keyIndex = 0; keyIndex < numKeys; ++keyIndex) { const CTrackViewKeyHandle& keyHandle = pSequenceTrack->GetKey(keyIndex); ISequenceKey sequenceKey; @@ -1043,7 +1034,7 @@ bool CExportManager::AddSelectedRegionObjects() std::vector objects; GetIEditor()->GetObjectManager()->FindObjectsInAABB(box, objects); - int numObjects = objects.size(); + const size_t numObjects = objects.size(); if (numObjects > m_data.m_objects.size()) { m_data.m_objects.reserve(numObjects + 1); // +1 for terrain @@ -1164,7 +1155,7 @@ bool CExportManager::Export(const char* defaultName, const char* defaultExt, con // Export the whole sequence with baked keys if (ShowFBXExportDialog()) { - m_numberOfExportFrames = pSequence->GetTimeRange().end * m_FBXBakedExportFPS; + m_numberOfExportFrames = static_cast(pSequence->GetTimeRange().end * m_FBXBakedExportFPS); if (!m_bExportOnlyPrimaryCamera) { diff --git a/Code/Editor/Export/ExportManager.h b/Code/Editor/Export/ExportManager.h index 698ad3ad5d..be81591e56 100644 --- a/Code/Editor/Export/ExportManager.h +++ b/Code/Editor/Export/ExportManager.h @@ -36,7 +36,7 @@ namespace Export public: CMesh(); - virtual int GetFaceCount() const { return m_faces.size(); } + virtual int GetFaceCount() const { return static_cast(m_faces.size()); } virtual const Face* GetFaceBuffer() const { return m_faces.size() ? &m_faces[0] : 0; } private: @@ -53,22 +53,22 @@ namespace Export public: CObject(const char* pName); - virtual int GetVertexCount() const { return m_vertices.size(); } - virtual const Vector3D* GetVertexBuffer() const{ return m_vertices.size() ? &m_vertices[0] : 0; } + int GetVertexCount() const override { return static_cast(m_vertices.size()); } + const Vector3D* GetVertexBuffer() const override { return m_vertices.size() ? &m_vertices[0] : nullptr; } - virtual int GetNormalCount() const { return m_normals.size(); } - virtual const Vector3D* GetNormalBuffer() const { return m_normals.size() ? &m_normals[0] : 0; } + int GetNormalCount() const override { return static_cast(m_normals.size()); } + const Vector3D* GetNormalBuffer() const override { return m_normals.size() ? &m_normals[0] : nullptr; } - virtual int GetTexCoordCount() const { return m_texCoords.size(); } - virtual const UV* GetTexCoordBuffer() const { return m_texCoords.size() ? &m_texCoords[0] : 0; } + int GetTexCoordCount() const override { return static_cast(m_texCoords.size()); } + const UV* GetTexCoordBuffer() const override { return m_texCoords.size() ? &m_texCoords[0] : nullptr; } - virtual int GetMeshCount() const { return m_meshes.size(); } - virtual Mesh* GetMesh(int index) const { return m_meshes[index]; } + int GetMeshCount() const override { return static_cast(m_meshes.size()); } + Mesh* GetMesh(int index) const override { return m_meshes[index]; } - virtual size_t MeshHash() const{return m_MeshHash; } + size_t MeshHash() const override{return m_MeshHash; } void SetMaterialName(const char* pName); - virtual int GetEntityAnimationDataCount() const {return m_entityAnimData.size(); } + virtual int GetEntityAnimationDataCount() const {return static_cast(m_entityAnimData.size()); } virtual const EntityAnimData* GetEntityAnimationData(int index) const {return &m_entityAnimData[index]; } virtual void SetEntityAnimationData(EntityAnimData entityData){ m_entityAnimData.push_back(entityData); }; void SetLastPtr(CBaseObject* pObject){m_pLastObject = pObject; }; @@ -92,7 +92,7 @@ namespace Export : public IData { public: - virtual int GetObjectCount() const { return m_objects.size(); } + virtual int GetObjectCount() const { return static_cast(m_objects.size()); } virtual Object* GetObject(int index) const { return m_objects[index]; } virtual Object* AddObject(const char* objectName); void Clear(); diff --git a/Code/Editor/Export/OBJExporter.cpp b/Code/Editor/Export/OBJExporter.cpp index bd2696090e..6ce40f8cd3 100644 --- a/Code/Editor/Export/OBJExporter.cpp +++ b/Code/Editor/Export/OBJExporter.cpp @@ -227,7 +227,7 @@ QString COBJExporter::MakeRelativePath(const char* pMainFileName, const char* pF const char* ch = strrchr(pMainFileName, '\\'); if (ch) { - if (strlen(pFileName) > ch - pMainFileName && !_strnicmp(pMainFileName, pFileName, ch - pMainFileName)) + if (strlen(pFileName) > static_cast(ch - pMainFileName) && !_strnicmp(pMainFileName, pFileName, ch - pMainFileName)) { return QString(pFileName + (ch - pMainFileName) + 1); } @@ -256,7 +256,7 @@ const char* COBJExporter::TrimFloat(float fValue) const ++nCurBuf; sprintf_s(pBuf, bufSize, "%f", fValue); - for (int i = strlen(pBuf) - 1; i > 0; --i) + for (int i = static_cast(strlen(pBuf)) - 1; i > 0; --i) { if (pBuf[i] == '0') { diff --git a/Code/Editor/Export/OCMExporter.cpp b/Code/Editor/Export/OCMExporter.cpp index 653dc28dd3..ba5c343d0d 100644 --- a/Code/Editor/Export/OCMExporter.cpp +++ b/Code/Editor/Export/OCMExporter.cpp @@ -215,7 +215,7 @@ bool COCMExporter::ExportToFile(const char* filename, const Export::IData* pExpo for (size_t a = 0; a < MeshCount; a++) { SOCMeshInfo MeshInfo; - MeshInfo.m_MeshHash = pExportData->GetObject(a)->MeshHash(); + MeshInfo.m_MeshHash = pExportData->GetObject(static_cast(a))->MeshHash(); const tdMeshOffset::iterator it = std::find(MeshOffsets.begin(), MeshOffsets.end(), MeshInfo); if (it != MeshOffsets.end()) { @@ -223,15 +223,15 @@ bool COCMExporter::ExportToFile(const char* filename, const Export::IData* pExpo } else { - MeshInfo.m_Offset = Offset; - Offset += SaveMesh(Writer, pExportData->GetObject(a), MeshInfo.m_OBBMat); + MeshInfo.m_Offset = static_cast(Offset); + Offset += SaveMesh(Writer, pExportData->GetObject(static_cast(a)), MeshInfo.m_OBBMat); } MeshOffsets.push_back(MeshInfo); } - OffsetInstances = Offset; + OffsetInstances = static_cast(Offset); for (size_t a = 0; a < InstCount; a++) { - SaveInstance(Writer, pExportData->GetObject(a), MeshOffsets[a]); + SaveInstance(Writer, pExportData->GetObject(static_cast(a)), MeshOffsets[a]); } Writer.Seek(4); Writer.Write(static_cast(MeshOffsets.size())); @@ -263,7 +263,7 @@ const char* COCMExporter::TrimFloat(float fValue) const ++nCurBuf; sprintf_s(pBuf, bufSize, "%f", fValue); - for (int i = strlen(pBuf) - 1; i > 0; --i) + for (int i = static_cast(strlen(pBuf)) - 1; i > 0; --i) { if (pBuf[i] == '0') { diff --git a/Code/Editor/FBXExporterDialog.cpp b/Code/Editor/FBXExporterDialog.cpp index 86e7843ca1..bae4b9bf7e 100644 --- a/Code/Editor/FBXExporterDialog.cpp +++ b/Code/Editor/FBXExporterDialog.cpp @@ -20,7 +20,7 @@ AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING namespace { - const uint kDefaultFPS = 30.0f; + const uint kDefaultFPS = 30u; } CFBXExporterDialog::CFBXExporterDialog(bool bDisplayOnlyFPSSetting, QWidget* pParent) @@ -43,7 +43,7 @@ CFBXExporterDialog::~CFBXExporterDialog() float CFBXExporterDialog::GetFPS() const { - return m_ui->m_fpsCombo->currentText().toDouble(); + return m_ui->m_fpsCombo->currentText().toFloat(); } bool CFBXExporterDialog::GetExportCoordsLocalToTheSelectedObject() const diff --git a/Code/Editor/GameExporter.cpp b/Code/Editor/GameExporter.cpp index 415103e10d..1fc980fdac 100644 --- a/Code/Editor/GameExporter.cpp +++ b/Code/Editor/GameExporter.cpp @@ -252,11 +252,11 @@ void CGameExporter::ExportOcclusionMesh(const char* pszGamePath) { CMemoryBlock Temp; const size_t Size = FileIn.size(); - Temp.Allocate(Size); + Temp.Allocate(static_cast(Size)); FileIn.read(reinterpret_cast(Temp.GetBuffer()), Size); FileIn.close(); CCryMemFile FileOut; - FileOut.Write(Temp.GetBuffer(), Size); + FileOut.Write(Temp.GetBuffer(), static_cast(Size)); m_levelPak.m_pakFile.UpdateFile(levelDataFile.toUtf8().data(), FileOut); } } @@ -281,13 +281,13 @@ void CGameExporter::ExportLevelData(const QString& path, bool /*bExportMission*/ QString levelDataFile = path + "LevelData.xml"; XmlString xmlData = root->getXML(); CCryMemFile file; - file.Write(xmlData.c_str(), xmlData.length()); + file.Write(xmlData.c_str(), static_cast(xmlData.length())); m_levelPak.m_pakFile.UpdateFile(levelDataFile.toUtf8().data(), file); QString levelDataActionFile = path + "LevelDataAction.xml"; XmlString xmlDataAction = rootAction->getXML(); CCryMemFile fileAction; - fileAction.Write(xmlDataAction.c_str(), xmlDataAction.length()); + fileAction.Write(xmlDataAction.c_str(), static_cast(xmlDataAction.length())); m_levelPak.m_pakFile.UpdateFile(levelDataActionFile.toUtf8().data(), fileAction); AZStd::vector entitySaveBuffer; @@ -298,7 +298,7 @@ void CGameExporter::ExportLevelData(const QString& path, bool /*bExportMission*/ { QString entitiesFile; entitiesFile = QStringLiteral("%1%2.entities_xml").arg(path, "Mission0"); - m_levelPak.m_pakFile.UpdateFile(entitiesFile.toUtf8().data(), entitySaveBuffer.begin(), entitySaveBuffer.size()); + m_levelPak.m_pakFile.UpdateFile(entitiesFile.toUtf8().data(), entitySaveBuffer.begin(), static_cast(entitySaveBuffer.size())); } } @@ -329,7 +329,7 @@ void CGameExporter::ExportLevelInfo(const QString& path) XmlString xmlData = root->getXML(); CCryMemFile file; - file.Write(xmlData.c_str(), xmlData.length()); + file.Write(xmlData.c_str(), static_cast(xmlData.length())); m_levelPak.m_pakFile.UpdateFile(filename.toUtf8().data(), file); } @@ -342,7 +342,7 @@ void CGameExporter::ExportLevelResourceList(const QString& path) CCryMemFile memFile; for (const char* filename = pResList->GetFirst(); filename; filename = pResList->GetNext()) { - memFile.Write(filename, strlen(filename)); + memFile.Write(filename, static_cast(strlen(filename))); memFile.Write("\n", 1); } diff --git a/Code/Editor/GameResourcesExporter.cpp b/Code/Editor/GameResourcesExporter.cpp index dd16b2eca1..b47f8c63a6 100644 --- a/Code/Editor/GameResourcesExporter.cpp +++ b/Code/Editor/GameResourcesExporter.cpp @@ -97,7 +97,7 @@ void CGameResourcesExporter::Save(const QString& outputDirectory) { // Save this file in target folder. QString trgFilename = Path::Make(outputDirectory, srcFilename); - int fsize = file.GetLength(); + int fsize = static_cast(file.GetLength()); if (fsize > data.GetSize()) { data.Allocate(fsize + 16); @@ -123,23 +123,6 @@ void CGameResourcesExporter::Save(const QString& outputDirectory) m_files.clear(); } -#if defined(WIN64) || defined(APPLE) || defined(AZ_PLATFORM_LINUX) -template -void Append(Container1& a, const Container2& b) -{ - a.reserve (a.size() + b.size()); - for (auto it = b.begin(); it != b.end(); ++it) - { - a.insert(a.end(), *it); - } -} -#else -template -void Append(Container1& a, const Container2& b) -{ - a.insert (a.end(), b.begin(), b.end()); -} -#endif ////////////////////////////////////////////////////////////////////////// // // Go through all editor objects and gathers files from thier properties. @@ -150,5 +133,5 @@ void CGameResourcesExporter::GetFilesFromObjects() CUsedResources rs; GetIEditor()->GetObjectManager()->GatherUsedResources(rs); - Append(m_files, rs.files); + AZStd::copy(rs.files.begin(), rs.files.end(), AZStd::back_inserter(m_files)); } diff --git a/Code/Editor/Geometry/TriMesh.cpp b/Code/Editor/Geometry/TriMesh.cpp index 737886cabc..d56aa038b5 100644 --- a/Code/Editor/Geometry/TriMesh.cpp +++ b/Code/Editor/Geometry/TriMesh.cpp @@ -201,7 +201,7 @@ void CTriMesh::SetFromMesh(CMesh& mesh) face.v [j] = numv; face.uv[j] = numv; face.n [j] = mesh.m_pNorms[idx].GetN(); - face.MatID = subset.nMatID; + face.MatID = static_cast(subset.nMatID); face.flags = 0; numv++; @@ -269,7 +269,7 @@ void CTriMesh::SharePositions() for (int i = 0; i < 3; i++) { const Vec3& v = pVertices[face.v[i]].pos; - uint8 nHash = RoundFloatToInt((v.x + v.y + v.z) * fHashScale); + uint8 nHash = static_cast(RoundFloatToInt((v.x + v.y + v.z) * fHashScale)); int find = FindVertexInHash(v, pNewVerts, arrHashTable[nHash], fEpsilon); if (find < 0) @@ -320,7 +320,7 @@ void CTriMesh::ShareUV() for (int i = 0; i < 3; i++) { const Vec2 uv = pUV[face.uv[i]].GetUV(); - uint8 nHash = RoundFloatToInt((uv.x + uv.y) * fHashScale); + uint8 nHash = static_cast(RoundFloatToInt((uv.x + uv.y) * fHashScale)); int find = FindTexCoordInHash(pUV[face.uv[i]], pNewUV, arrHashTable[nHash], fEpsilon); if (find < 0) @@ -380,7 +380,7 @@ void CTriMesh::UpdateIndexedMesh(IIndexedMesh* pIndexedMesh) const // To find really used materials std::vector usedMaterialIds; uint16 MatIdToSubset[MAX_SUB_MATERIALS]; - int nLastSubsetId = 0; + uint16 nLastSubsetId = 0; memset(MatIdToSubset, 0, sizeof(MatIdToSubset)); ////////////////////////////////////////////////////////////////////////// @@ -398,7 +398,7 @@ void CTriMesh::UpdateIndexedMesh(IIndexedMesh* pIndexedMesh) const MatIdToSubset[face.MatID] = 1 + nLastSubsetId++; usedMaterialIds.push_back(face.MatID); // Order of material ids in usedMaterialIds correspond to the indices of chunks. } - meshFace.nSubset = MatIdToSubset[face.MatID] - 1; + meshFace.nSubset = static_cast(MatIdToSubset[face.MatID] - 1); for (int j = 0; j < 3; ++j) { @@ -420,7 +420,7 @@ void CTriMesh::UpdateIndexedMesh(IIndexedMesh* pIndexedMesh) const pIndexedMesh->SetBBox(bb); - pIndexedMesh->SetSubSetCount(usedMaterialIds.size()); + pIndexedMesh->SetSubSetCount(static_cast(usedMaterialIds.size())); for (int i = 0; i < usedMaterialIds.size(); i++) { pIndexedMesh->SetSubsetMaterialId(i, usedMaterialIds[i]); @@ -677,11 +677,11 @@ void CTriMesh::GetEdgesByVertex(MeshElementsArray& inVertices, MeshElementsArray std::sort(inVertices.begin(), inVertices.end()); for (int i = 0; i < GetEdgeCount(); i++) { - if (stl::binary_find(inVertices.begin(), inVertices.end(), pEdges[i].v[0]) != inVertices.end()) + if (stl::binary_find(inVertices.begin(), inVertices.end(), static_cast(pEdges[i].v[0])) != inVertices.end()) { outEdges.push_back(i); } - else if (stl::binary_find(inVertices.begin(), inVertices.end(), pEdges[i].v[1]) != inVertices.end()) + else if (stl::binary_find(inVertices.begin(), inVertices.end(), static_cast(pEdges[i].v[1])) != inVertices.end()) { outEdges.push_back(i); } @@ -696,15 +696,15 @@ void CTriMesh::GetFacesByVertex(MeshElementsArray& inVertices, MeshElementsArray std::sort(inVertices.begin(), inVertices.end()); for (int i = 0; i < GetFacesCount(); i++) { - if (stl::binary_find(inVertices.begin(), inVertices.end(), pFaces[i].v[0]) != inVertices.end()) + if (stl::binary_find(inVertices.begin(), inVertices.end(), static_cast(pFaces[i].v[0])) != inVertices.end()) { outFaces.push_back(i); } - else if (stl::binary_find(inVertices.begin(), inVertices.end(), pFaces[i].v[1]) != inVertices.end()) + else if (stl::binary_find(inVertices.begin(), inVertices.end(), static_cast(pFaces[i].v[1])) != inVertices.end()) { outFaces.push_back(i); } - else if (stl::binary_find(inVertices.begin(), inVertices.end(), pFaces[i].v[2]) != inVertices.end()) + else if (stl::binary_find(inVertices.begin(), inVertices.end(), static_cast(pFaces[i].v[2])) != inVertices.end()) { outFaces.push_back(i); } diff --git a/Code/Editor/GotoPositionDlg.cpp b/Code/Editor/GotoPositionDlg.cpp index aec5f03fbd..84d149de58 100644 --- a/Code/Editor/GotoPositionDlg.cpp +++ b/Code/Editor/GotoPositionDlg.cpp @@ -86,7 +86,7 @@ void GotoPositionDialog::OnChangeEdit() const QStringList parts = m_transform.split(QRegularExpression("[\\s,;\\t]"), Qt::SkipEmptyParts); for (int i = 0; i < argCount && i < parts.count(); ++i) { - transform[i] = parts[i].toDouble(); + transform[i] = parts[i].toFloat(); } m_ui->m_dymX->setValue(transform[0]); diff --git a/Code/Editor/LevelFileDialog.cpp b/Code/Editor/LevelFileDialog.cpp index cefa1330eb..c0c2b96c59 100644 --- a/Code/Editor/LevelFileDialog.cpp +++ b/Code/Editor/LevelFileDialog.cpp @@ -477,7 +477,7 @@ bool CLevelFileDialog::ValidateLevelPath(const QString& levelPath) const QString currentPath = (Path::GetEditingGameDataFolder() + "/" + kLevelsFolder).c_str(); for (size_t i = 0; i < splittedPath.size() - 1; ++i) { - currentPath += "/" + splittedPath[i]; + currentPath += "/" + splittedPath[static_cast(i)]; if (CFileUtil::FileExists(currentPath) || CheckLevelFolder(currentPath)) { diff --git a/Code/Editor/Lib/Tests/test_ModularViewportCameraController.cpp b/Code/Editor/Lib/Tests/test_ModularViewportCameraController.cpp new file mode 100644 index 0000000000..6fcf3faffd --- /dev/null +++ b/Code/Editor/Lib/Tests/test_ModularViewportCameraController.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include +#include + +namespace UnitTest +{ + const QSize WidgetSize = QSize(1920, 1080); + + using AzToolsFramework::ViewportInteraction::MouseInteractionEvent; + + class ModularViewportCameraControllerFixture : public AllocatorsTestFixture + { + public: + static const AzFramework::ViewportId TestViewportId; + + void SetUp() override + { + AllocatorsTestFixture::SetUp(); + + m_rootWidget = AZStd::make_unique(); + m_rootWidget->setFixedSize(WidgetSize); + + m_controllerList = AZStd::make_shared(); + m_controllerList->RegisterViewportContext(TestViewportId); + + m_inputChannelMapper = AZStd::make_unique(m_rootWidget.get(), TestViewportId); + } + + void TearDown() override + { + m_inputChannelMapper.reset(); + + m_controllerList->UnregisterViewportContext(TestViewportId); + m_controllerList.reset(); + m_rootWidget.reset(); + + AllocatorsTestFixture::TearDown(); + } + + AZStd::unique_ptr m_rootWidget; + AzFramework::ViewportControllerListPtr m_controllerList; + AZStd::unique_ptr m_inputChannelMapper; + }; + + const AzFramework::ViewportId ModularViewportCameraControllerFixture::TestViewportId = AzFramework::ViewportId(0); + + class TestModularCameraViewportContextImpl : public AtomToolsFramework::ModularCameraViewportContext + { + public: + AZ::Transform GetCameraTransform() const override + { + return m_cameraTransform; + } + + void SetCameraTransform(const AZ::Transform& transform) override + { + m_cameraTransform = transform; + } + + void ConnectViewMatrixChangedHandler(AZ::RPI::ViewportContext::MatrixChangedEvent::Handler&) override + { + // noop + } + + private: + AZ::Transform m_cameraTransform = AZ::Transform::CreateIdentity(); + }; + + TEST_F(ModularViewportCameraControllerFixture, Mouse_movement_does_not_accumulate_excessive_drift_in_modular_viewport_camera) + { + AzFramework::NativeWindowHandle nativeWindowHandle = nullptr; + + const float deltaTime = 1.0f / 60.0f; // mimic 60fps + + // Given + // listen for events signaled from QtEventToAzInputMapper and forward to the controller list + QObject::connect( + m_inputChannelMapper.get(), &AzToolsFramework::QtEventToAzInputMapper::InputChannelUpdated, m_rootWidget.get(), + [this, nativeWindowHandle](const AzFramework::InputChannel* inputChannel, [[maybe_unused]] QEvent* event) + { + m_controllerList->HandleInputChannelEvent( + AzFramework::ViewportControllerInputEvent{ TestViewportId, nativeWindowHandle, *inputChannel }); + }); + + using ::testing::NiceMock; + using ::testing::Return; + + NiceMock mockWindowRequests; + mockWindowRequests.Connect(nativeWindowHandle); + + // note: WindowRequests is used internally by ModularViewportCameraController, this ensures it returns the viewport size we want + ON_CALL(mockWindowRequests, GetClientAreaSize()) + .WillByDefault(Return(AzFramework::WindowSize(WidgetSize.width(), WidgetSize.height()))); + + // create editor modular camera + auto controller = CreateModularViewportCameraController(TestViewportId); + + // set some overrides for the test + AtomToolsFramework::ModularCameraViewportContext* cameraViewportContextView = nullptr; + controller->SetCameraViewportContextBuilderCallback( + [&cameraViewportContextView](AZStd::unique_ptr& cameraViewportContext) + { + cameraViewportContext = AZStd::make_unique(); + cameraViewportContextView = cameraViewportContext.get(); + }); + + controller->SetCameraPropsBuilderCallback( + [](AzFramework::CameraProps& cameraProps) + { + cameraProps.m_rotateSmoothingEnabledFn = [] + { + return false; + }; + + cameraProps.m_translateSmoothingEnabledFn = [] + { + return false; + }; + }); + + m_controllerList->Add(controller); + + // move to the center of the screen + auto start = QPoint(WidgetSize.width() / 2, WidgetSize.height() / 2); + MouseMove(m_rootWidget.get(), start, QPoint(0, 0)); + m_controllerList->UpdateViewport({ TestViewportId, AzFramework::FloatSeconds(deltaTime), AZ::ScriptTimePoint() }); + + // When + // move mouse diagonally to top right, then to bottom left and back repeatedly + auto current = start; + auto halfDelta = QPoint(200, -200); + const int iterationsPerDiagonal = 50; + for (int diagonals = 0; diagonals < 80; ++diagonals) + { + for (int i = 0; i < iterationsPerDiagonal; ++i) + { + MousePressAndMove(m_rootWidget.get(), current, halfDelta / iterationsPerDiagonal, Qt::MouseButton::RightButton); + m_controllerList->UpdateViewport({ TestViewportId, AzFramework::FloatSeconds(deltaTime), AZ::ScriptTimePoint() }); + current += halfDelta / iterationsPerDiagonal; + } + + if (diagonals % 2 == 0) + { + halfDelta.setX(halfDelta.x() * -1); + halfDelta.setY(halfDelta.y() * -1); + } + } + + QTest::mouseRelease(m_rootWidget.get(), Qt::MouseButton::RightButton, Qt::KeyboardModifier::NoModifier, current); + m_controllerList->UpdateViewport({ TestViewportId, AzFramework::FloatSeconds(deltaTime), AZ::ScriptTimePoint() }); + + // Then + // ensure the camera rotation is the identity (no significant drift has occurred as we moved the mouse) + const AZ::Transform cameraRotation = cameraViewportContextView->GetCameraTransform(); + EXPECT_THAT(cameraRotation.GetRotation(), IsClose(AZ::Quaternion::CreateIdentity())); + + mockWindowRequests.Disconnect(); + } +} // namespace UnitTest diff --git a/Code/Editor/Lib/Tests/test_ViewportManipulatorController.cpp b/Code/Editor/Lib/Tests/test_ViewportManipulatorController.cpp index a2a7617083..8c7023634e 100644 --- a/Code/Editor/Lib/Tests/test_ViewportManipulatorController.cpp +++ b/Code/Editor/Lib/Tests/test_ViewportManipulatorController.cpp @@ -24,10 +24,10 @@ namespace UnitTest void Disconnect(); // EditorInteractionSystemViewportSelectionRequestBus overrides ... - void SetHandler(const AzToolsFramework::ViewportSelectionRequestsBuilderFn& interactionRequestsBuilder); - void SetDefaultHandler(); - bool InternalHandleMouseViewportInteraction(const MouseInteractionEvent& mouseInteraction); - bool InternalHandleMouseManipulatorInteraction(const MouseInteractionEvent& mouseInteraction); + void SetHandler(const AzToolsFramework::ViewportSelectionRequestsBuilderFn& interactionRequestsBuilder) override; + void SetDefaultHandler() override; + bool InternalHandleMouseViewportInteraction(const MouseInteractionEvent& mouseInteraction) override; + bool InternalHandleMouseManipulatorInteraction(const MouseInteractionEvent& mouseInteraction) override; AZStd::function m_internalHandleMouseViewportInteraction; AZStd::function m_internalHandleMouseManipulatorInteraction; @@ -77,7 +77,7 @@ namespace UnitTest class ViewportManipulatorControllerFixture : public AllocatorsTestFixture { public: - static const AzFramework::ViewportId TestViewportId = AzFramework::ViewportId(0); + static const AzFramework::ViewportId TestViewportId; void SetUp() override { @@ -92,7 +92,7 @@ namespace UnitTest m_inputChannelMapper = AZStd::make_unique(m_rootWidget.get(), TestViewportId); } - void TearDown() + void TearDown() override { m_inputChannelMapper.reset(); @@ -108,6 +108,8 @@ namespace UnitTest AZStd::unique_ptr m_inputChannelMapper; }; + const AzFramework::ViewportId ViewportManipulatorControllerFixture::TestViewportId = AzFramework::ViewportId(0); + TEST_F(ViewportManipulatorControllerFixture, An_event_is_not_propagated_to_the_viewport_when_a_manipulator_handles_it_first) { // forward input events to our controller list diff --git a/Code/Editor/LogFile.cpp b/Code/Editor/LogFile.cpp index 2295e1897f..5978356781 100644 --- a/Code/Editor/LogFile.cpp +++ b/Code/Editor/LogFile.cpp @@ -504,7 +504,7 @@ static inline QString CopyAndRemoveColorCode(const char* sText) *d++ = *s++; } - ret.resize(d - ret.data()); + ret.resize(static_cast(d - ret.data())); return QString::fromLatin1(ret); } diff --git a/Code/Editor/MainWindow.cpp b/Code/Editor/MainWindow.cpp index 9560fd0fe7..fa2e792cc8 100644 --- a/Code/Editor/MainWindow.cpp +++ b/Code/Editor/MainWindow.cpp @@ -1672,7 +1672,7 @@ void MainWindow::OnUpdateConnectionStatus() tooltip += m_connectionListener->LastAssetProcessorTask().c_str(); tooltip += "\n"; AZStd::set failedJobs = m_connectionListener->FailedJobsList(); - int failureCount = failedJobs.size(); + int failureCount = static_cast(failedJobs.size()); if (failureCount) { tooltip += "\n Failed Jobs\n"; @@ -1767,7 +1767,7 @@ void MainWindow::RegisterOpenWndCommands() cmdUI.tooltip = (QString("Open ") + className).toUtf8().data(); cmdUI.iconFilename = className.toUtf8().data(); GetIEditor()->GetCommandManager()->RegisterUICommand("editor", openCommandName.toUtf8().data(), - "", "", AZStd::bind(&CEditorOpenViewCommand::Execute, pCmd), cmdUI); + "", "", [pCmd] { pCmd->Execute(); }, cmdUI); GetIEditor()->GetCommandManager()->GetUIInfo("editor", openCommandName.toUtf8().data(), cmdUI); } } diff --git a/Code/Editor/Objects/AxisGizmo.cpp b/Code/Editor/Objects/AxisGizmo.cpp index 8f81ea66b7..a603b2615d 100644 --- a/Code/Editor/Objects/AxisGizmo.cpp +++ b/Code/Editor/Objects/AxisGizmo.cpp @@ -274,7 +274,7 @@ Matrix34 CAxisGizmo::GetTransformation(RefCoordSys coordSys, IDisplayViewport* v ////////////////////////////////////////////////////////////////////////// bool CAxisGizmo::MouseCallback(CViewport* view, EMouseEvent event, QPoint& point, [[maybe_unused]] int nFlags) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (event == eMouseLDown) { diff --git a/Code/Editor/Objects/BaseObject.cpp b/Code/Editor/Objects/BaseObject.cpp index 482055d7ed..c89bd50559 100644 --- a/Code/Editor/Objects/BaseObject.cpp +++ b/Code/Editor/Objects/BaseObject.cpp @@ -840,8 +840,8 @@ void CBaseObject::DrawDefault(DisplayContext& dc, const QColor& labelColor) { dc.DrawLine(GetParentAttachPointWorldTM().GetTranslation(), wp, IsFrozen() ? kLinkColorGray : kLinkColorParent, IsFrozen() ? kLinkColorGray : kLinkColorChild); } - int nChildCount = GetChildCount(); - for (int i = 0; i < nChildCount; ++i) + size_t nChildCount = GetChildCount(); + for (size_t i = 0; i < nChildCount; ++i) { const CBaseObject* pChild = GetChild(i); dc.DrawLine(pChild->GetParentAttachPointWorldTM().GetTranslation(), pChild->GetWorldPos(), pChild->IsFrozen() ? kLinkColorGray : kLinkColorParent, pChild->IsFrozen() ? kLinkColorGray : kLinkColorChild); @@ -1022,10 +1022,10 @@ void CBaseObject::DrawLabel(DisplayContext& dc, const Vec3& pos, const QColor& l if (camDist < dc.settings->GetLabelsDistance() || (dc.flags & DISPLAY_SELECTION_HELPERS)) { float range = maxDist / 2.0f; - Vec3 c(labelColor.redF(), labelColor.greenF(), labelColor.redF()); + Vec3 c(static_cast(labelColor.redF()), static_cast(labelColor.greenF()), static_cast(labelColor.redF())); if (IsSelected()) { - c = Vec3(dc.GetSelectedColor().redF(), dc.GetSelectedColor().greenF(), dc.GetSelectedColor().blueF()); + c = Vec3(static_cast(dc.GetSelectedColor().redF()), static_cast(dc.GetSelectedColor().greenF()), static_cast(dc.GetSelectedColor().blueF())); } float col[4] = { c.x, c.y, c.z, 1 }; @@ -1033,7 +1033,7 @@ void CBaseObject::DrawLabel(DisplayContext& dc, const Vec3& pos, const QColor& l { if (IsHighlighted()) { - c = Vec3(dc.GetSelectedColor().redF(), dc.GetSelectedColor().greenF(), dc.GetSelectedColor().blueF()); + c = Vec3(static_cast(dc.GetSelectedColor().redF()), static_cast(dc.GetSelectedColor().greenF()), static_cast(dc.GetSelectedColor().blueF())); } col[0] = c.x; col[1] = c.y; @@ -1233,7 +1233,7 @@ float CBaseObject::GetCameraVisRatio(const CCamera& camera) ////////////////////////////////////////////////////////////////////////// int CBaseObject::MouseCreateCallback(CViewport* view, EMouseEvent event, QPoint& point, int flags) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (event == eMouseMove || event == eMouseLDown) { @@ -1263,9 +1263,9 @@ int CBaseObject::MouseCreateCallback(CViewport* view, EMouseEvent event, QPoint& if (event == eMouseWheel) { - double angle = 1; + float angle = 1; Quat rot = GetRotation(); - rot.SetRotationXYZ(Ang3(0, 0, rot.GetRotZ() + DEG2RAD(flags > 0 ? angle * (-1) : angle))); + rot.SetRotationXYZ(Ang3(0.f, 0.f, rot.GetRotZ() + DEG2RAD(flags > 0 ? angle * (-1) : angle))); SetRotation(rot); } return MOUSECREATE_CONTINUE; @@ -1375,7 +1375,7 @@ bool CBaseObject::IsHiddenBySpec() const return false; } - return (m_nMinSpec != 0 && gSettings.editorConfigSpec != 0 && m_nMinSpec > gSettings.editorConfigSpec); + return (m_nMinSpec != 0 && gSettings.editorConfigSpec != 0 && m_nMinSpec > static_cast(gSettings.editorConfigSpec)); } ////////////////////////////////////////////////////////////////////////// @@ -1515,8 +1515,8 @@ void CBaseObject::Serialize(CObjectArchive& ar) SetFrozen(bFrozen); SetHidden(bHidden); - ar.SetResolveCallback(this, parentId, AZStd::bind(&CBaseObject::ResolveParent, this, AZStd::placeholders::_1 )); - ar.SetResolveCallback(this, lookatId, AZStd::bind(&CBaseObject::SetLookAt, this, AZStd::placeholders::_1)); + ar.SetResolveCallback(this, parentId, [this](CBaseObject* parent) { ResolveParent(parent); }); + ar.SetResolveCallback(this, lookatId, [this](CBaseObject* target) { SetLookAt(target); }); InvalidateTM(0); SetModified(false); @@ -1857,10 +1857,10 @@ bool CBaseObject::HitTestRectBounds(HitContext& hc, const AABB& box) const int kMaxSizeOfEdgeList0(4); Edge2D edgelist0[kMaxSizeOfEdgeList0] = { - Edge2D(Vec2(hc.rect.left(), hc.rect.top()), Vec2(hc.rect.right(), hc.rect.top())), - Edge2D(Vec2(hc.rect.right(), hc.rect.top()), Vec2(hc.rect.right(), hc.rect.bottom())), - Edge2D(Vec2(hc.rect.right(), hc.rect.bottom()), Vec2(hc.rect.left(), hc.rect.bottom())), - Edge2D(Vec2(hc.rect.left(), hc.rect.bottom()), Vec2(hc.rect.left(), hc.rect.top())) + Edge2D(Vec2(static_cast(hc.rect.left()), static_cast(hc.rect.top())), Vec2(static_cast(hc.rect.right()), static_cast(hc.rect.top()))), + Edge2D(Vec2(static_cast(hc.rect.right()), static_cast(hc.rect.top())), Vec2(static_cast(hc.rect.right()), static_cast(hc.rect.bottom()))), + Edge2D(Vec2(static_cast(hc.rect.right()), static_cast(hc.rect.bottom())), Vec2(static_cast(hc.rect.left()), static_cast(hc.rect.bottom()))), + Edge2D(Vec2(static_cast(hc.rect.left()), static_cast(hc.rect.bottom())), Vec2(static_cast(hc.rect.left()), static_cast(hc.rect.top()))) }; const int kMaxSizeOfEdgeList1(8); @@ -1888,12 +1888,12 @@ bool CBaseObject::HitTestRectBounds(HitContext& hc, const AABB& box) pointsForRegion1.reserve(kMaxSizeOfEdgeList1); for (int i = 0; i < kMaxSizeOfEdgeList1; ++i) { - pointsForRegion1.push_back(Vec3(obb_p[i].x(), obb_p[i].y(), 0)); + pointsForRegion1.push_back(Vec3(static_cast(obb_p[i].x()), static_cast(obb_p[i].y()), 0.0f)); } std::vector convexHullForRegion1; ConvexHull2D(convexHullForRegion1, pointsForRegion1); - nEdgeList1Count = convexHullForRegion1.size(); + nEdgeList1Count = static_cast(convexHullForRegion1.size()); if (nEdgeList1Count < 3 || nEdgeList1Count > kMaxSizeOfEdgeList1) { return true; @@ -1928,7 +1928,7 @@ bool CBaseObject::HitTestRectBounds(HitContext& hc, const AABB& box) ////////////////////////////////////////////////////////////////////////// bool CBaseObject::HitTestRect(HitContext& hc) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AABB box; @@ -1965,7 +1965,7 @@ bool CBaseObject::HitHelperTest(HitContext& hc) ////////////////////////////////////////////////////////////////////////// bool CBaseObject::HitHelperAtTest(HitContext& hc, const Vec3& pos) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); bool bResult = false; @@ -1978,8 +1978,8 @@ bool CBaseObject::HitHelperAtTest(HitContext& hc, const Vec3& pos) { float fScreenScale = hc.view->GetScreenScaleFactor(pos); - iconSizeX *= OBJECT_TEXTURE_ICON_SCALE / fScreenScale; - iconSizeY *= OBJECT_TEXTURE_ICON_SCALE / fScreenScale; + iconSizeX = static_cast(static_cast(iconSizeX) * OBJECT_TEXTURE_ICON_SCALE / fScreenScale); + iconSizeY = static_cast(static_cast(iconSizeY) * OBJECT_TEXTURE_ICON_SCALE / fScreenScale); } // Hit Test icon of this object. @@ -2038,7 +2038,7 @@ bool CBaseObject::HitHelperAtTest(HitContext& hc, const Vec3& pos) ////////////////////////////////////////////////////////////////////////// CBaseObject* CBaseObject::GetChild(size_t const i) const { - assert(i >= 0 && i < m_childs.size()); + assert(i < m_childs.size()); return m_childs[i]; } @@ -2062,7 +2062,7 @@ void CBaseObject::GetAllChildren(TBaseObjects& outAllChildren, CBaseObject* pObj { const CBaseObject* pBaseObj = pObj ? pObj : this; - for (int i = 0, iChildCount(pBaseObj->GetChildCount()); i < iChildCount; ++i) + for (size_t i = 0, iChildCount(pBaseObj->GetChildCount()); i < iChildCount; ++i) { CBaseObject* pChild = pBaseObj->GetChild(i); if (pChild == nullptr) @@ -2078,7 +2078,7 @@ void CBaseObject::GetAllChildren(DynArray< _smart_ptr >& outAllChil { const CBaseObject* pBaseObj = pObj ? pObj : this; - for (int i = 0, iChildCount(pBaseObj->GetChildCount()); i < iChildCount; ++i) + for (size_t i = 0, iChildCount(pBaseObj->GetChildCount()); i < iChildCount; ++i) { CBaseObject* pChild = pBaseObj->GetChild(i); if (pChild == nullptr) @@ -2094,7 +2094,7 @@ void CBaseObject::GetAllChildren(CSelectionGroup& outAllChildren, CBaseObject* p { const CBaseObject* pBaseObj = pObj ? pObj : this; - for (int i = 0, iChildCount(pBaseObj->GetChildCount()); i < iChildCount; ++i) + for (size_t i = 0, iChildCount(pBaseObj->GetChildCount()); i < iChildCount; ++i) { CBaseObject* pChild = pBaseObj->GetChild(i); if (pChild == nullptr) @@ -2114,7 +2114,7 @@ void CBaseObject::CloneChildren(CBaseObject* pFromObject) return; } - for (int i = 0, nChildCount(pFromObject->GetChildCount()); i < nChildCount; ++i) + for (size_t i = 0, nChildCount(pFromObject->GetChildCount()); i < nChildCount; ++i) { CBaseObject* pFromChildObject = pFromObject->GetChild(i); @@ -2729,7 +2729,7 @@ void CBaseObject::SetMinSpec(uint32 nSpec, bool bSetChildren) // Set min spec for all childs. if (bSetChildren) { - for (int i = m_childs.size() - 1; i >= 0; --i) + for (int i = static_cast(m_childs.size()) - 1; i >= 0; --i) { m_childs[i]->SetMinSpec(nSpec, true); } diff --git a/Code/Editor/Objects/DisplayContext.h b/Code/Editor/Objects/DisplayContext.h index 4b09d4afe9..47fd450220 100644 --- a/Code/Editor/Objects/DisplayContext.h +++ b/Code/Editor/Objects/DisplayContext.h @@ -83,12 +83,12 @@ struct SANDBOX_API DisplayContext // Draw functions ////////////////////////////////////////////////////////////////////////// //! Set current materialc color. - void SetColor(float r, float g, float b, float a = 1) { m_color4b = ColorB(int(r * 255.0f), int(g * 255.0f), int(b * 255.0f), int(a * 255.0f)); }; - void SetColor(const Vec3& color, float a = 1) { m_color4b = ColorB(int(color.x * 255.0f), int(color.y * 255.0f), int(color.z * 255.0f), int(a * 255.0f)); }; - void SetColor(const QColor& rgb, float a) { m_color4b = ColorB(rgb.red(), rgb.green(), rgb.blue(), int(a * 255.0f)); }; - void SetColor(const QColor& color) { m_color4b = ColorB(color.red(), color.green(), color.blue(), color.alpha()); }; + void SetColor(float r, float g, float b, float a = 1) { m_color4b = ColorB(static_cast(r * 255.0f), static_cast(g * 255.0f), static_cast(b * 255.0f), static_cast(a * 255.0f)); }; + void SetColor(const Vec3& color, float a = 1) { m_color4b = ColorB(static_cast(color.x * 255.0f), static_cast(color.y * 255.0f), static_cast(color.z * 255.0f), static_cast(a * 255.0f)); }; + void SetColor(const QColor& rgb, float a) { m_color4b = ColorB(static_cast(rgb.red()), static_cast(rgb.green()), static_cast(rgb.blue()), static_cast(a * 255.0f)); }; + void SetColor(const QColor& color) { m_color4b = ColorB(static_cast(color.red()), static_cast(color.green()), static_cast(color.blue()), static_cast(color.alpha())); }; void SetColor(const ColorB& color) { m_color4b = color; }; - void SetAlpha(float a = 1) { m_color4b.a = int(a * 255.0f); }; + void SetAlpha(float a = 1) { m_color4b.a = static_cast(a * 255.0f); }; ColorB GetColor() const { return m_color4b; } void SetSelectedColor(float fAlpha = 1); diff --git a/Code/Editor/Objects/DisplayContextShared.inl b/Code/Editor/Objects/DisplayContextShared.inl index a602d8eca9..5af04d821e 100644 --- a/Code/Editor/Objects/DisplayContextShared.inl +++ b/Code/Editor/Objects/DisplayContextShared.inl @@ -63,7 +63,7 @@ void DisplayContext::InternalDrawLine(const Vec3& v0, const ColorB& colV0, const ////////////////////////////////////////////////////////////////////////// void DisplayContext::DrawPoint(const Vec3& p, int nSize) { - pRenderAuxGeom->DrawPoint(ToWorldSpacePosition(p), m_color4b, nSize); + pRenderAuxGeom->DrawPoint(ToWorldSpacePosition(p), m_color4b, static_cast(nSize)); } ////////////////////////////////////////////////////////////////////////// @@ -856,7 +856,10 @@ void DisplayContext::DrawLine(const Vec3& p1, const Vec3& p2, const ColorF& col1 ////////////////////////////////////////////////////////////////////////// void DisplayContext::DrawLine(const Vec3& p1, const Vec3& p2, const QColor& rgb1, const QColor& rgb2) { - InternalDrawLine(ToWorldSpacePosition(p1), ColorB(rgb1.red(), rgb1.green(), rgb1.blue(), 255), ToWorldSpacePosition(p2), ColorB(rgb2.red(), rgb2.green(), rgb2.blue(), 255)); + InternalDrawLine(ToWorldSpacePosition(p1), + ColorB(static_cast(rgb1.red()), static_cast(rgb1.green()), static_cast(rgb1.blue()), 255), + ToWorldSpacePosition(p2), + ColorB(static_cast(rgb2.red()), static_cast(rgb2.green()), static_cast(rgb2.blue()), 255)); } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/Objects/EntityObject.cpp b/Code/Editor/Objects/EntityObject.cpp index 0f4a17f3ba..68264f9ea4 100644 --- a/Code/Editor/Objects/EntityObject.cpp +++ b/Code/Editor/Objects/EntityObject.cpp @@ -63,7 +63,7 @@ protected: void Undo([[maybe_unused]] bool bUndo) override { - for (int i = 0, iLinkSize(m_Links.size()); i < iLinkSize; ++i) + for (int i = 0, iLinkSize = static_cast(m_Links.size()); i < iLinkSize; ++i) { SLink& link = m_Links[i]; CBaseObject* pObj = GetIEditor()->GetObjectManager()->FindObject(link.entityID); @@ -230,25 +230,25 @@ CEntityObject::CEntityObject() m_attachmentType = eAT_Pivot; // cache all the variable callbacks, must match order of enum defined in header - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnAreaHeightChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnAreaLightChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnAreaLightSizeChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnAreaWidthChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnBoxHeightChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnBoxLengthChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnBoxProjectionChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnBoxSizeXChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnBoxSizeYChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnBoxSizeZChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnBoxWidthChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnColorChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnInnerRadiusChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnOuterRadiusChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnProjectInAllDirsChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnProjectorFOVChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnProjectorTextureChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnPropertyChange, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CEntityObject::OnRadiusChange, this, AZStd::placeholders::_1)); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnAreaHeightChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnAreaLightChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnAreaLightSizeChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnAreaWidthChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnBoxHeightChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnBoxLengthChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnBoxProjectionChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnBoxSizeXChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnBoxSizeYChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnBoxSizeZChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnBoxWidthChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnColorChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnInnerRadiusChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnOuterRadiusChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnProjectInAllDirsChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnProjectorFOVChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnProjectorTextureChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnPropertyChange(var); }); + m_onSetCallbacksCache.emplace_back([this](IVariable* var) { OnRadiusChange(var); }); } CEntityObject::~CEntityObject() @@ -497,7 +497,7 @@ bool CEntityObject::HitTestRect(HitContext& hc) ////////////////////////////////////////////////////////////////////////// int CEntityObject::MouseCreateCallback(CViewport* view, EMouseEvent event, QPoint& point, int flags) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (event == eMouseMove || event == eMouseLDown) { @@ -938,11 +938,14 @@ void CEntityObject::Serialize(CObjectArchive& ar) eventTarget->getAttr("TargetId", targetId); eventTarget->getAttr("Event", et.event); eventTarget->getAttr("SourceEvent", et.sourceEvent); - m_eventTargets.push_back(et); + m_eventTargets.emplace_back(AZStd::move(et)); if (targetId != GUID_NULL) { using namespace AZStd::placeholders; - ar.SetResolveCallback(this, targetId, AZStd::bind(&CEntityObject::ResolveEventTarget, this, _1, _2), i); + ar.SetResolveCallback( + this, targetId, + [this](CBaseObject* object, unsigned int index) { ResolveEventTarget(object, index); }, + i); } } } @@ -1217,7 +1220,7 @@ XmlNodeRef CEntityObject::Export([[maybe_unused]] const QString& levelPath, XmlN if (!m_links.empty()) { XmlNodeRef linksNode = objNode->newChild("EntityLinks"); - for (int i = 0, num = m_links.size(); i < num; i++) + for (size_t i = 0, num = m_links.size(); i < num; i++) { if (m_links[i].target) { @@ -1283,7 +1286,7 @@ void CEntityObject::UpdateVisibility(bool bVisible) CBaseObject::UpdateVisibility(bVisible); bool bVisibleWithSpec = bVisible && !IsHiddenBySpec(); - if (bVisibleWithSpec != m_bVisible) + if (bVisibleWithSpec != static_cast(m_bVisible)) { m_bVisible = bVisibleWithSpec; } @@ -1368,8 +1371,8 @@ void CEntityObject::PostClone(CBaseObject* pFromObject, CObjectCloneContext& ctx // Clone event targets. if (!pFromEntity->m_eventTargets.empty()) { - int numTargets = pFromEntity->m_eventTargets.size(); - for (int i = 0; i < numTargets; i++) + size_t numTargets = pFromEntity->m_eventTargets.size(); + for (size_t i = 0; i < numTargets; i++) { CEntityEventTarget& et = pFromEntity->m_eventTargets[i]; CBaseObject* pClonedTarget = ctx.FindClone(et.target); @@ -1386,7 +1389,7 @@ void CEntityObject::PostClone(CBaseObject* pFromObject, CObjectCloneContext& ctx // Clone links. if (!pFromEntity->m_links.empty()) { - int numTargets = pFromEntity->m_links.size(); + int numTargets = static_cast(pFromEntity->m_links.size()); for (int i = 0; i < numTargets; i++) { CEntityLink& et = pFromEntity->m_links[i]; @@ -1413,7 +1416,7 @@ void CEntityObject::PostClone(CBaseObject* pFromObject, CObjectCloneContext& ctx void CEntityObject::ResolveEventTarget(CBaseObject* object, unsigned int index) { // Find target id. - assert(index >= 0 && index < m_eventTargets.size()); + assert(index < m_eventTargets.size()); if (object) { object->AddEventListener(this); @@ -1437,7 +1440,7 @@ void CEntityObject::RemoveAllEntityLinks() { while (!m_links.empty()) { - RemoveEntityLink(m_links.size() - 1); + RemoveEntityLink(static_cast(m_links.size() - 1)); } m_links.clear(); SetModified(false); @@ -1448,7 +1451,7 @@ void CEntityObject::ReleaseEventTargets() { while (!m_eventTargets.empty()) { - RemoveEventTarget(m_eventTargets.size() - 1, false); + RemoveEventTarget(static_cast(m_eventTargets.size() - 1), false); } m_eventTargets.clear(); SetModified(false); @@ -1518,7 +1521,7 @@ void CEntityObject::SaveLink(XmlNodeRef xmlNode) } XmlNodeRef linksNode = xmlNode->newChild("EntityLinks"); - for (int i = 0, num = m_links.size(); i < num; i++) + for (size_t i = 0, num = m_links.size(); i < num; i++) { XmlNodeRef linkNode = linksNode->newChild("Link"); linkNode->setAttr("TargetId", m_links[i].targetId); @@ -1534,26 +1537,26 @@ void CEntityObject::OnObjectEvent(CBaseObject* target, int event) if (event == CBaseObject::ON_DELETE) { // Find this target in events list and remove. - int numTargets = m_eventTargets.size(); + int numTargets = static_cast(m_eventTargets.size()); for (int i = 0; i < numTargets; i++) { if (m_eventTargets[i].target == target) { RemoveEventTarget(i); - numTargets = m_eventTargets.size(); + numTargets = static_cast(m_eventTargets.size()); i--; } } } else if (event == CBaseObject::ON_PREDELETE) { - int numTargets = m_links.size(); + int numTargets = static_cast(m_links.size()); for (int i = 0; i < numTargets; i++) { if (m_links[i].target == target) { RemoveEntityLink(i); - numTargets = m_eventTargets.size(); + numTargets = static_cast(m_eventTargets.size()); i--; } } @@ -1589,7 +1592,7 @@ int CEntityObject::AddEventTarget(CBaseObject* target, const QString& event, con m_eventTargets.push_back(et); SetModified(false); - return m_eventTargets.size() - 1; + return static_cast(m_eventTargets.size() - 1); } ////////////////////////////////////////////////////////////////////////// @@ -1659,13 +1662,13 @@ int CEntityObject::AddEntityLink(const QString& name, GUID targetEntityId) SetModified(false); - return m_links.size() - 1; + return static_cast(m_links.size() - 1); } ////////////////////////////////////////////////////////////////////////// bool CEntityObject::EntityLinkExists(const QString& name, GUID targetEntityId) { - for (int i = 0, num = m_links.size(); i < num; ++i) + for (size_t i = 0, num = m_links.size(); i < num; ++i) { if (m_links[i].targetId == targetEntityId && name.compare(m_links[i].name, Qt::CaseInsensitive) == 0) { diff --git a/Code/Editor/Objects/ObjectLoader.cpp b/Code/Editor/Objects/ObjectLoader.cpp index 2583eb6230..9596265bb9 100644 --- a/Code/Editor/Objects/ObjectLoader.cpp +++ b/Code/Editor/Objects/ObjectLoader.cpp @@ -126,7 +126,7 @@ void CObjectArchive::ResolveObjects() ////////////////////////////////////////////////////////////////////////// // Serialize All Objects from XML. ////////////////////////////////////////////////////////////////////////// - int numObj = m_loadedObjects.size(); + int numObj = static_cast(m_loadedObjects.size()); for (i = 0; i < numObj; i++) { if (m_bProgressBarEnabled) @@ -143,7 +143,7 @@ void CObjectArchive::ResolveObjects() m_pCurrentErrorReport->SetCurrentValidatorObject(nullptr); // Objects can be added to the list here (from Groups). - numObj = m_loadedObjects.size(); + numObj = static_cast(m_loadedObjects.size()); } m_pCurrentErrorReport->SetCurrentValidatorObject(nullptr); ////////////////////////////////////////////////////////////////////////// @@ -221,7 +221,7 @@ void CObjectArchive::ResolveObjects() ////////////////////////////////////////////////////////////////////////// // Serialize All Objects from XML. ////////////////////////////////////////////////////////////////////////// - int numObj = m_loadedObjects.size(); + int numObj = static_cast(m_loadedObjects.size()); for (i = 0; i < numObj; i++) { if (m_bProgressBarEnabled) @@ -246,7 +246,7 @@ void CObjectArchive::ResolveObjects() // Call PostLoad on all these objects. ////////////////////////////////////////////////////////////////////////// { - int numObj = m_loadedObjects.size(); + int numObj = static_cast(m_loadedObjects.size()); for (i = 0; i < numObj; i++) { SLoadedObjectInfo& obj = m_loadedObjects[i]; diff --git a/Code/Editor/Objects/ObjectManager.cpp b/Code/Editor/Objects/ObjectManager.cpp index fbdd56f080..940ef5b551 100644 --- a/Code/Editor/Objects/ObjectManager.cpp +++ b/Code/Editor/Objects/ObjectManager.cpp @@ -368,7 +368,7 @@ CBaseObject* CObjectManager::NewObject(const QString& typeName, CBaseObject* pre ////////////////////////////////////////////////////////////////////////// void CObjectManager::DeleteObject(CBaseObject* obj) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (m_currEditObject == obj) { EndEditParams(); @@ -414,7 +414,7 @@ void CObjectManager::DeleteObject(CBaseObject* obj) ////////////////////////////////////////////////////////////////////////// void CObjectManager::DeleteSelection(CSelectionGroup* pSelection) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (pSelection == nullptr) { return; @@ -478,7 +478,7 @@ void CObjectManager::DeleteSelection(CSelectionGroup* pSelection) ////////////////////////////////////////////////////////////////////////// void CObjectManager::DeleteAllObjects() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); EndEditParams(); @@ -519,7 +519,7 @@ void CObjectManager::DeleteAllObjects() CBaseObject* CObjectManager::CloneObject(CBaseObject* obj) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); assert(obj); //CRuntimeClass *cls = obj->GetRuntimeClass(); //CBaseObject *clone = (CBaseObject*)cls->CreateObject(); @@ -746,7 +746,7 @@ void CObjectManager::ChangeObjectName(CBaseObject* obj, const QString& newName) ////////////////////////////////////////////////////////////////////////// int CObjectManager::GetObjectCount() const { - return m_objects.size(); + return static_cast(m_objects.size()); } ////////////////////////////////////////////////////////////////////////// @@ -765,7 +765,7 @@ void CObjectManager::GetObjects(DynArray& objects) const CBaseObjectsArray objectArray; GetObjects(objectArray); objects.clear(); - for (int i = 0, iCount(objectArray.size()); i < iCount; ++i) + for (size_t i = 0, iCount(objectArray.size()); i < iCount; ++i) { objects.push_back(objectArray[i]); } @@ -1112,7 +1112,7 @@ void CObjectManager::SerializeNameSelection(XmlNodeRef& rootNode, bool bLoading) ////////////////////////////////////////////////////////////////////////// int CObjectManager::ClearSelection() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); // Make sure to unlock selection. GetIEditor()->LockSelection(false); @@ -1165,7 +1165,7 @@ int CObjectManager::ClearSelection() ////////////////////////////////////////////////////////////////////////// int CObjectManager::InvertSelection() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); int selCount = 0; // iterate all objects. @@ -1189,7 +1189,7 @@ int CObjectManager::InvertSelection() void CObjectManager::SetSelection(const QString& name) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)nullptr); if (selection) { @@ -1202,7 +1202,7 @@ void CObjectManager::SetSelection(const QString& name) void CObjectManager::RemoveSelection(const QString& name) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); QString selName = name; CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)nullptr); @@ -1221,7 +1221,7 @@ void CObjectManager::RemoveSelection(const QString& name) void CObjectManager::SelectCurrent() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); for (int i = 0; i < m_currSelection->GetCount(); i++) { CBaseObject* obj = m_currSelection->GetObject(i); @@ -1236,7 +1236,7 @@ void CObjectManager::SelectCurrent() void CObjectManager::UnselectCurrent() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); // Make sure to unlock selection. GetIEditor()->LockSelection(false); @@ -1260,7 +1260,7 @@ void CObjectManager::UnselectCurrent() ////////////////////////////////////////////////////////////////////////// void CObjectManager::Display(DisplayContext& dc) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); int currentHideMask = GetIEditor()->GetDisplaySettings()->GetObjectHideMask(); if (m_lastHideMask != currentHideMask) @@ -1320,7 +1320,7 @@ void CObjectManager::FindDisplayableObjects(DisplayContext& dc, [[maybe_unused]] return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); auto start = std::chrono::steady_clock::now(); CBaseObjectsCache* pDispayedViewObjects = dc.view->GetVisibleObjectsCache(); @@ -1336,11 +1336,11 @@ void CObjectManager::FindDisplayableObjects(DisplayContext& dc, [[maybe_unused]] bbox.max.zero(); pDispayedViewObjects->ClearObjects(); - pDispayedViewObjects->Reserve(m_visibleObjects.size()); + pDispayedViewObjects->Reserve(static_cast(m_visibleObjects.size())); if (dc.flags & DISPLAY_2D) { - int numVis = m_visibleObjects.size(); + int numVis = static_cast(m_visibleObjects.size()); for (int i = 0; i < numVis; i++) { CBaseObject* obj = m_visibleObjects[i]; @@ -1374,7 +1374,7 @@ void CObjectManager::FindDisplayableObjects(DisplayContext& dc, [[maybe_unused]] pSelection->GetObject(0)->CBaseObject::DrawDimensions(dc, &mergedAABB); } - int numVis = m_visibleObjects.size(); + int numVis = static_cast(m_visibleObjects.size()); for (int i = 0; i < numVis; i++) { CBaseObject* obj = m_visibleObjects[i]; @@ -1451,7 +1451,7 @@ void CObjectManager::EndEditParams([[maybe_unused]] int flags) //! Select objects within specified distance from given position. int CObjectManager::SelectObjects(const AABB& box, bool bUnselect) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); int numSel = 0; AABB objBounds; @@ -1551,7 +1551,7 @@ bool CObjectManager::IsObjectDeletionAllowed(CBaseObject* pObject) ////////////////////////////////////////////////////////////////////////// void CObjectManager::DeleteSelection() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); // Make sure to unlock selection. GetIEditor()->LockSelection(false); @@ -1581,7 +1581,7 @@ void CObjectManager::DeleteSelection() ////////////////////////////////////////////////////////////////////////// bool CObjectManager::HitTestObject(CBaseObject* obj, HitContext& hc) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (obj->IsFrozen()) { @@ -1648,7 +1648,7 @@ bool CObjectManager::HitTestObject(CBaseObject* obj, HitContext& hc) ////////////////////////////////////////////////////////////////////////// bool CObjectManager::HitTest(HitContext& hitInfo) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); hitInfo.object = nullptr; hitInfo.dist = FLT_MAX; @@ -1766,7 +1766,7 @@ bool CObjectManager::HitTest(HitContext& hitInfo) } void CObjectManager::FindObjectsInRect(CViewport* view, const QRect& rect, std::vector& guids) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (rect.width() < 1 || rect.height() < 1) { @@ -1795,7 +1795,7 @@ void CObjectManager::FindObjectsInRect(CViewport* view, const QRect& rect, std:: ////////////////////////////////////////////////////////////////////////// void CObjectManager::SelectObjectsInRect(CViewport* view, const QRect& rect, bool bSelect) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); // Ignore too small rectangles. if (rect.width() < 1 || rect.height() < 1) @@ -2016,7 +2016,7 @@ void CObjectManager::GetClassCategories(QStringList& categories) } } categories.clear(); - categories.reserve(cset.size()); + categories.reserve(static_cast(cset.size())); for (std::set::iterator cit = cset.begin(); cit != cset.end(); ++cit) { categories.push_back(*cit); @@ -2363,7 +2363,7 @@ bool CObjectManager::ConvertToType(CBaseObject* pObject, const QString& typeName ////////////////////////////////////////////////////////////////////////// void CObjectManager::SetObjectSelected(CBaseObject* pObject, bool bSelect) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); // Only select/unselect once. if ((pObject->IsSelected() && bSelect) || (!pObject->IsSelected() && !bSelect)) { @@ -2629,7 +2629,7 @@ void CObjectManager::EnteredComponentMode(const AZStd::vector& /*compo const size_t gizmoCount = static_cast(gizmoManager->GetGizmoCount()); for (size_t i = 0; i < gizmoCount; ++i) { - gizmoManager->RemoveGizmo(gizmoManager->GetGizmoByIndex(i)); + gizmoManager->RemoveGizmo(gizmoManager->GetGizmoByIndex(static_cast(i))); } } diff --git a/Code/Editor/Objects/ObjectManagerLegacyUndo.cpp b/Code/Editor/Objects/ObjectManagerLegacyUndo.cpp index f21ba46e65..08a7f4cf48 100644 --- a/Code/Editor/Objects/ObjectManagerLegacyUndo.cpp +++ b/Code/Editor/Objects/ObjectManagerLegacyUndo.cpp @@ -204,7 +204,7 @@ CUndoBaseObjectBulkSelect::CUndoBaseObjectBulkSelect(const AZStd::unordered_set< void CUndoBaseObjectBulkSelect::Undo(bool bUndo) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (!bUndo) { return; @@ -217,7 +217,7 @@ void CUndoBaseObjectBulkSelect::Undo(bool bUndo) void CUndoBaseObjectBulkSelect::Redo() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); AzToolsFramework::ToolsApplicationRequestBus::Broadcast( &AzToolsFramework::ToolsApplicationRequests::MarkEntitiesSelected, @@ -256,7 +256,7 @@ CUndoBaseObjectClearSelection::CUndoBaseObjectClearSelection(const CSelectionGro void CUndoBaseObjectClearSelection::Undo(bool bUndo) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (!bUndo) { @@ -270,7 +270,7 @@ void CUndoBaseObjectClearSelection::Undo(bool bUndo) void CUndoBaseObjectClearSelection::Redo() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); AzToolsFramework::ToolsApplicationRequestBus::Broadcast( &AzToolsFramework::ToolsApplicationRequests::SetSelectedEntities, diff --git a/Code/Editor/Objects/SelectionGroup.cpp b/Code/Editor/Objects/SelectionGroup.cpp index 027c88172e..f2b7b9ddaf 100644 --- a/Code/Editor/Objects/SelectionGroup.cpp +++ b/Code/Editor/Objects/SelectionGroup.cpp @@ -109,7 +109,7 @@ bool CSelectionGroup::SameObjectType() ////////////////////////////////////////////////////////////////////////// int CSelectionGroup::GetCount() const { - return m_objects.size(); + return static_cast(m_objects.size()); } ////////////////////////////////////////////////////////////////////////// @@ -157,7 +157,7 @@ Vec3 CSelectionGroup::GetCenter() const } if (GetCount() > 0) { - c /= GetCount(); + c /= static_cast(GetCount()); } return c; } @@ -632,7 +632,7 @@ void CSelectionGroup::IndicateSnappingVertex(DisplayContext& dc) const void CSelectionGroup::FinishChanges() { Objects selectedObjects(m_objects); - int iObjectSize(selectedObjects.size()); + int iObjectSize = static_cast(selectedObjects.size()); for (int i = 0; i < iObjectSize; ++i) { CBaseObject* pObject = selectedObjects[i]; diff --git a/Code/Editor/Platform/Common/MSVC/editor_lib_msvc.cmake b/Code/Editor/Platform/Common/MSVC/editor_lib_msvc.cmake index cd72cfb3d8..7a325ca97e 100644 --- a/Code/Editor/Platform/Common/MSVC/editor_lib_msvc.cmake +++ b/Code/Editor/Platform/Common/MSVC/editor_lib_msvc.cmake @@ -5,8 +5,3 @@ # SPDX-License-Identifier: Apache-2.0 OR MIT # # -ly_add_source_properties( - SOURCES MainWindow.cpp CryEdit.cpp - PROPERTY COMPILE_OPTIONS - VALUES -bigobj -) diff --git a/Code/Editor/Plugin.cpp b/Code/Editor/Plugin.cpp index e73b9daa2c..4f6fe0279d 100644 --- a/Code/Editor/Plugin.cpp +++ b/Code/Editor/Plugin.cpp @@ -136,7 +136,7 @@ IClassDesc* CClassFactory::FindClass(const char* pClassName) const return nullptr; } - QString name = QString(pClassName).left(pSubClassName - pClassName); + QString name = QString(pClassName).left(static_cast(pSubClassName - pClassName)); return stl::find_in_map(m_nameToClass, name, (IClassDesc*)nullptr); } diff --git a/Code/Editor/PluginManager.cpp b/Code/Editor/PluginManager.cpp index 350102ead2..494748dc79 100644 --- a/Code/Editor/PluginManager.cpp +++ b/Code/Editor/PluginManager.cpp @@ -262,7 +262,7 @@ void CPluginManager::RegisterPlugin(QLibrary* dllHandle, IPlugin* pPlugin) entry.hLibrary = dllHandle; entry.pPlugin = pPlugin; m_plugins.push_back(entry); - m_uuidPluginMap[m_currentUUID] = pPlugin; + m_uuidPluginMap[static_cast(m_currentUUID)] = pPlugin; ++m_currentUUID; } diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp index 85730d327b..c91bf58074 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp @@ -661,8 +661,8 @@ bool CComponentEntityObject::HitHelperTest(HitContext& hc) if (IsEntityIconVisible()) { const QPoint entityScreenPos = hc.view->WorldToView(GetWorldPos()); - const float screenPosX = entityScreenPos.x(); - const float screenPosY = entityScreenPos.y(); + const float screenPosX = static_cast(entityScreenPos.x()); + const float screenPosY = static_cast(entityScreenPos.y()); const float iconRange = static_cast(s_kIconSize / 2); if ((hc.point2d.x() >= screenPosX - iconRange && hc.point2d.x() <= screenPosX + iconRange) @@ -679,7 +679,7 @@ bool CComponentEntityObject::HitHelperTest(HitContext& hc) bool CComponentEntityObject::HitTest(HitContext& hc) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (m_iconOnlyHitTest) { @@ -705,7 +705,7 @@ bool CComponentEntityObject::HitTest(HitContext& hc) [&hc, &closestDistance, &rayIntersection, &preciseSelectionRequired, viewportId]( AzToolsFramework::EditorComponentSelectionRequests* handler) -> bool { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (handler->SupportsEditorRayIntersect()) { @@ -768,7 +768,7 @@ bool CComponentEntityObject::HitTest(HitContext& hc) void CComponentEntityObject::GetBoundBox(AABB& box) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); box.Reset(); diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index b10fe35513..429fbd923c 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -472,7 +472,7 @@ void SandboxIntegrationManager::EntityParentChanged( const AZ::EntityId newParentId, const AZ::EntityId oldParentId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_unsavedEntities.find(entityId) != m_unsavedEntities.end()) { @@ -626,7 +626,7 @@ void SandboxIntegrationManager::PopulateEditorGlobalContextMenu(QMenu* menu, con { view->GetDimensions(&width, &height); } - m_contextMenuViewPoint.Set(width / 2, height / 2); + m_contextMenuViewPoint.Set(static_cast(width / 2), static_cast(height / 2)); } else { @@ -646,16 +646,27 @@ void SandboxIntegrationManager::PopulateEditorGlobalContextMenu(QMenu* menu, con QAction* action = nullptr; - action = menu->addAction(QObject::tr("Create entity")); - QObject::connect(action, &QAction::triggered, action, [this] { ContextMenu_NewEntity(); }); - - if (selected.size() == 1) + // when nothing is selected, entity is created at root level + if (selected.size() == 0) { - action = menu->addAction(QObject::tr("Create child entity")); - QObject::connect(action, &QAction::triggered, action, [selected] - { - EBUS_EVENT(AzToolsFramework::EditorRequests::Bus, CreateNewEntityAsChild, selected.front()); - }); + action = menu->addAction(QObject::tr("Create entity")); + QObject::connect( + action, &QAction::triggered, action, + [this] + { + ContextMenu_NewEntity(); + }); + } + // when a single entity is selected, entity is created as its child + else if (selected.size() == 1) + { + action = menu->addAction(QObject::tr("Create entity")); + QObject::connect( + action, &QAction::triggered, action, + [selected] + { + EBUS_EVENT(AzToolsFramework::EditorRequests::Bus, CreateNewEntityAsChild, selected.front()); + }); } bool prefabSystemEnabled = false; @@ -847,7 +858,7 @@ void SandboxIntegrationManager::SetupLayerContextMenu(QMenu* menu) void SandboxIntegrationManager::SetupSliceContextMenu(QMenu* menu) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); AzToolsFramework::EntityIdList selectedEntities; GetSelectedOrHighlightedEntities(selectedEntities); @@ -949,7 +960,7 @@ void SandboxIntegrationManager::SetupSliceContextMenu(QMenu* menu) void SandboxIntegrationManager::SetupSliceContextMenu_Modify(QMenu* menu, const AzToolsFramework::EntityIdList& selectedEntities, [[maybe_unused]] const AZ::u32 numEntitiesInSlices) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); using namespace AzToolsFramework; // Gather the set of relevant entities from the selected entities and all descendants @@ -998,7 +1009,7 @@ void SandboxIntegrationManager::HandleObjectModeSelection(const AZ::Vector2& poi if (m_inObjectPickMode) { CViewport* view = GetIEditor()->GetViewManager()->GetGameViewport(); - const QPoint viewPoint(point.GetX(), point.GetY()); + const QPoint viewPoint(static_cast(point.GetX()), static_cast(point.GetY())); HitContext hitInfo; hitInfo.view = view; @@ -1072,7 +1083,7 @@ void SandboxIntegrationManager::CreateEditorRepresentation(AZ::Entity* entity) bool SandboxIntegrationManager::DestroyEditorRepresentation(AZ::EntityId entityId, bool deleteAZEntity) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); IEditor* editor = GetIEditor(); if (editor->GetObjectManager()) @@ -1084,7 +1095,7 @@ bool SandboxIntegrationManager::DestroyEditorRepresentation(AZ::EntityId entityI { static_cast(object)->AssignEntity(nullptr, deleteAZEntity); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SandboxIntegrationManager::DestroyEditorRepresentation:ObjManagerDeleteObject"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SandboxIntegrationManager::DestroyEditorRepresentation:ObjManagerDeleteObject"); editor->GetObjectManager()->DeleteObject(object); } return true; @@ -1206,7 +1217,7 @@ void SandboxIntegrationManager::ClearRedoStack() void SandboxIntegrationManager::CloneSelection(bool& handled) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AzToolsFramework::EntityIdList entities; AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult( @@ -1440,7 +1451,7 @@ void SandboxIntegrationManager::ContextMenu_NewEntity() // will be created at the origin. if (view) { - const QPoint viewPoint(m_contextMenuViewPoint.GetX(), m_contextMenuViewPoint.GetY()); + const QPoint viewPoint(static_cast(m_contextMenuViewPoint.GetX()), static_cast(m_contextMenuViewPoint.GetY())); worldPosition = view->GetHitLocation(viewPoint); } @@ -1630,7 +1641,7 @@ void SandboxIntegrationManager::InstantiateSliceFromAssetId(const AZ::Data::Asse // will be instantiated at the origin. if (view) { - const QPoint viewPoint(m_contextMenuViewPoint.GetX(), m_contextMenuViewPoint.GetY()); + const QPoint viewPoint(static_cast(m_contextMenuViewPoint.GetX()), static_cast(m_contextMenuViewPoint.GetY())); sliceWorldTransform = AZ::Transform::CreateTranslation(LYVec3ToAZVec3(view->SnapToGrid(view->ViewToWorld(viewPoint)))); } @@ -1839,7 +1850,7 @@ AZStd::string SandboxIntegrationManager::GetComponentEditorIcon(const AZ::Uuid& AZStd::string SandboxIntegrationManager::GetComponentIconPath(const AZ::Uuid& componentType, AZ::Crc32 componentIconAttrib, AZ::Component* component) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (componentIconAttrib != AZ::Edit::Attributes::Icon && componentIconAttrib != AZ::Edit::Attributes::ViewportIcon && componentIconAttrib != AZ::Edit::Attributes::HideIcon) diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/AssetCatalogModel.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/AssetCatalogModel.cpp index 0d661349a9..d0091f968e 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/AssetCatalogModel.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/AssetCatalogModel.cpp @@ -472,7 +472,7 @@ void AssetCatalogModel::LoadDatabase() { m_fileCacheCurrentIndex = 0; Q_EMIT UpdateProgress(0); - Q_EMIT SetTotalProgress(m_fileCache.size()); + Q_EMIT SetTotalProgress(static_cast(m_fileCache.size())); }; EBUS_EVENT(AZ::Data::AssetCatalogRequestBus, EnumerateAssets, startCB, enumerateCB, endCB); diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/ComponentDataModel.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/ComponentDataModel.cpp index f7f2b721b7..cd0fba350f 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/ComponentDataModel.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/ComponentDataModel.cpp @@ -262,7 +262,7 @@ QModelIndex ComponentDataModel::parent([[maybe_unused]] const QModelIndex &child int ComponentDataModel::rowCount([[maybe_unused]] const QModelIndex &parent /*= QModelIndex()*/) const { - return m_componentList.size(); + return static_cast(m_componentList.size()); } int ComponentDataModel::columnCount([[maybe_unused]] const QModelIndex &parent /*= QModelIndex()*/) const diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerListModel.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerListModel.cpp index 02d2174fb8..9ec81cdb3b 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerListModel.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerListModel.cpp @@ -1054,7 +1054,7 @@ bool OutlinerListModel::dropMimeDataEntities(const QMimeData* data, Qt::DropActi bool OutlinerListModel::CanReparentEntities(const AZ::EntityId& newParentId, const AzToolsFramework::EntityIdList &selectedEntityIds) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (selectedEntityIds.empty()) { return false; @@ -1143,7 +1143,7 @@ bool OutlinerListModel::CanReparentEntities(const AZ::EntityId& newParentId, con bool OutlinerListModel::ReparentEntities(const AZ::EntityId& newParentId, const AzToolsFramework::EntityIdList &selectedEntityIds, const AZ::EntityId& beforeEntityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!CanReparentEntities(newParentId, selectedEntityIds)) { return false; @@ -1233,7 +1233,7 @@ bool OutlinerListModel::ReparentEntities(const AZ::EntityId& newParentId, const QMimeData* OutlinerListModel::mimeData(const QModelIndexList& indexes) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::TypeId uuid1 = AZ::AzTypeInfo::Uuid(); AZ::TypeId uuid2 = AZ::AzTypeInfo::Uuid(); @@ -1323,7 +1323,7 @@ public: void OutlinerListModel::ProcessEntityUpdates() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); m_entityChangeQueued = false; if (m_layoutResetQueued) { @@ -1331,7 +1331,7 @@ void OutlinerListModel::ProcessEntityUpdates() } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Editor, "OutlinerListModel::ProcessEntityUpdates:ExpandQueue"); + AZ_PROFILE_SCOPE(Editor, "OutlinerListModel::ProcessEntityUpdates:ExpandQueue"); for (auto entityId : m_entityExpandQueue) { emit ExpandEntity(entityId, IsExpanded(entityId)); @@ -1340,7 +1340,7 @@ void OutlinerListModel::ProcessEntityUpdates() } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Editor, "OutlinerListModel::ProcessEntityUpdates:SelectQueue"); + AZ_PROFILE_SCOPE(Editor, "OutlinerListModel::ProcessEntityUpdates:SelectQueue"); for (auto entityId : m_entitySelectQueue) { emit SelectEntity(entityId, AzToolsFramework::IsSelected(entityId)); @@ -1350,7 +1350,7 @@ void OutlinerListModel::ProcessEntityUpdates() if (!m_entityChangeQueue.empty()) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Editor, "OutlinerListModel::ProcessEntityUpdates:ChangeQueue"); + AZ_PROFILE_SCOPE(Editor, "OutlinerListModel::ProcessEntityUpdates:ChangeQueue"); // its faster to just do a bulk data change than to carefully pick out indices // so we'll just merge all ranges into a single range rather than try to make gaps @@ -1383,7 +1383,7 @@ void OutlinerListModel::ProcessEntityUpdates() } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Editor, "OutlinerListModel::ProcessEntityUpdates:LayoutChanged"); + AZ_PROFILE_SCOPE(Editor, "OutlinerListModel::ProcessEntityUpdates:LayoutChanged"); if (m_entityLayoutQueued) { emit layoutAboutToBeChanged(); @@ -1393,7 +1393,7 @@ void OutlinerListModel::ProcessEntityUpdates() } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Editor, "OutlinerListModel::ProcessEntityUpdates:InvalidateFilter"); + AZ_PROFILE_SCOPE(Editor, "OutlinerListModel::ProcessEntityUpdates:InvalidateFilter"); if (m_isFilterDirty) { InvalidateFilter(); @@ -1416,7 +1416,7 @@ void OutlinerListModel::OnEntityInfoResetEnd() void OutlinerListModel::ProcessEntityInfoResetEnd() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_layoutResetQueued = false; m_entityChangeQueued = false; m_entityChangeQueue.clear(); @@ -1437,7 +1437,7 @@ void OutlinerListModel::OnEntityInfoUpdatedAddChildBegin(AZ::EntityId parentId, void OutlinerListModel::OnEntityInfoUpdatedAddChildEnd(AZ::EntityId parentId, AZ::EntityId childId) { (void)parentId; - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); endInsertRows(); //expand ancestors if a new descendant is already selected @@ -1475,7 +1475,7 @@ void OutlinerListModel::OnEntityInfoUpdatedRemoveChildBegin(AZ::EntityId parentI void OutlinerListModel::OnEntityInfoUpdatedRemoveChildEnd(AZ::EntityId parentId, AZ::EntityId childId) { (void)childId; - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); endResetModel(); @@ -1494,7 +1494,7 @@ void OutlinerListModel::OnEntityInfoUpdatedOrderBegin(AZ::EntityId parentId, AZ: void OutlinerListModel::OnEntityInfoUpdatedOrderEnd(AZ::EntityId parentId, AZ::EntityId childId, AZ::u64 index) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); (void)index; m_entityLayoutQueued = true; QueueEntityUpdate(parentId); @@ -1565,7 +1565,7 @@ QString OutlinerListModel::GetSliceAssetName(const AZ::EntityId& entityId) const QModelIndex OutlinerListModel::GetIndexFromEntity(const AZ::EntityId& entityId, int column) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (entityId.IsValid()) { @@ -1727,7 +1727,7 @@ void OutlinerListModel::OnEditorEntityDuplicated(const AZ::EntityId& oldEntity, void OutlinerListModel::ExpandAncestors(const AZ::EntityId& entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //typically to reveal selected entities, expand all parent entities if (entityId.IsValid()) { @@ -1932,7 +1932,7 @@ bool OutlinerListModel::HasSelectedDescendant(const AZ::EntityId& entityId) cons bool OutlinerListModel::AreAllDescendantsSameLockState(const AZ::EntityId& entityId) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //TODO result can be cached in mutable map and cleared when any descendant changes to avoid recursion in deep hierarchies bool isLocked = false; AzToolsFramework::EditorEntityInfoRequestBus::EventResult(isLocked, entityId, &AzToolsFramework::EditorEntityInfoRequestBus::Events::IsJustThisEntityLocked); @@ -1953,7 +1953,7 @@ bool OutlinerListModel::AreAllDescendantsSameLockState(const AZ::EntityId& entit bool OutlinerListModel::AreAllDescendantsSameVisibleState(const AZ::EntityId& entityId) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //TODO result can be cached in mutable map and cleared when any descendant changes to avoid recursion in deep hierarchies bool isVisible = AzToolsFramework::IsEntitySetToBeVisible(entityId); @@ -2476,10 +2476,10 @@ void OutlinerItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& auto backgroundBoxRect = option.rect; - backgroundBoxRect.setX(backgroundBoxRect.x() + 0.5); - backgroundBoxRect.setY(backgroundBoxRect.y() + 2.5); - backgroundBoxRect.setWidth(backgroundBoxRect.width() - 1.0); - backgroundBoxRect.setHeight(backgroundBoxRect.height() - 1.0); + backgroundBoxRect.setX(static_cast(backgroundBoxRect.x() + 0.5f)); + backgroundBoxRect.setY(static_cast(backgroundBoxRect.y() + 2.5f)); + backgroundBoxRect.setWidth(static_cast(backgroundBoxRect.width() - 1.0f)); + backgroundBoxRect.setHeight(static_cast(backgroundBoxRect.height() - 1.0f)); const qreal sliceBorderHeight = 0.8f; @@ -2513,7 +2513,7 @@ void OutlinerItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& else { auto newRect = option.rect; - newRect.setHeight(newRect.height() - 1.0); + newRect.setHeight(static_cast(newRect.height() - 1.0f)); path.addRect(newRect); } @@ -2597,7 +2597,7 @@ void OutlinerItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& QString htmlStripped = layerInfoString; htmlStripped.remove(htmlMarkupRegex); const float layerInfoPadding = 1.2f; - textWidthAvailable -= fontMetrics.horizontalAdvance(htmlStripped) * layerInfoPadding; + textWidthAvailable -= static_cast(fontMetrics.horizontalAdvance(htmlStripped) * layerInfoPadding); } entityNameRichText = fontMetrics.elidedText(optionV4.text, Qt::TextElideMode::ElideRight, textWidthAvailable); diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.cpp index 158e45d6e2..452db49d37 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerTreeView.cpp @@ -274,8 +274,8 @@ void OutlinerTreeView::drawBranches(QPainter* painter, const QRect& rect, const // if the item has children offset the drawn line to compensate for drawn expander buttons bool hasChildren = previousIndex.model()->index(0, 0, previousIndex).isValid(); int horizontalLineY = rect.top() + rectHalfHeight; - int horizontalLineLeft = rect.right() - indentation() * 1.5f; - int horizontalLineRight = hasChildren ? (lineBaseX - indentation()) : (lineBaseX - indentation() * 0.5f); + int horizontalLineLeft = static_cast(rect.right() - indentation() * 1.5f); + int horizontalLineRight = hasChildren ? (lineBaseX - indentation()) : static_cast(lineBaseX - indentation() * 0.5f); painter->drawLine(horizontalLineLeft, horizontalLineY, horizontalLineRight, horizontalLineY); } @@ -284,7 +284,7 @@ void OutlinerTreeView::drawBranches(QPainter* painter, const QRect& rect, const bool hasNext = previousIndex.sibling(previousIndex.row() + 1, previousIndex.column()).isValid(); if (hasNext || previousIndex == index) { - int verticalLineX = lineBaseX - indentation() * 1.5f; + int verticalLineX = static_cast(lineBaseX - indentation() * 1.5f); int verticalLineTop = rect.top(); int verticalLineBottom = hasNext ? rect.bottom() : rect.bottom() - rectHalfHeight; painter->drawLine(verticalLineX, verticalLineTop, verticalLineX, verticalLineBottom); diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerWidget.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerWidget.cpp index 6e16ab6557..9ed7c4a144 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerWidget.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerWidget.cpp @@ -96,7 +96,7 @@ namespace void SortEntityChildren(AZ::EntityId entityId, const EntityIdCompareFunc& comparer, AzToolsFramework::EntityOrderArray* newEntityOrder = nullptr) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AzToolsFramework::EntityOrderArray entityOrderArray = AzToolsFramework::GetEntityChildOrder(entityId); AZStd::sort(entityOrderArray.begin(), entityOrderArray.end(), comparer); @@ -110,7 +110,7 @@ namespace void SortEntityChildrenRecursively(AZ::EntityId entityId, const EntityIdCompareFunc& comparer) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AzToolsFramework::EntityOrderArray entityOrderArray; SortEntityChildren(entityId, comparer, &entityOrderArray); @@ -303,7 +303,7 @@ void OutlinerWidget::OnSelectionChanged(const QItemSelection& selected, const QI return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AzToolsFramework::EntityIdList newlySelected; ExtractEntityIdsFromSelection(selected, newlySelected); @@ -450,7 +450,7 @@ void OutlinerWidget::UpdateSelection() { if (m_selectionChangeQueued) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_selectionChangeInProgress = true; @@ -458,7 +458,7 @@ void OutlinerWidget::UpdateSelection() { // Calling Deselect for a large number of items is very slow, // use a single ClearAndSelect call instead. - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "OutlinerWidget::ModelEntitySelectionChanged:ClearAndSelect"); + AZ_PROFILE_SCOPE(AzToolsFramework, "OutlinerWidget::ModelEntitySelectionChanged:ClearAndSelect"); AzToolsFramework::EntityIdList selectedEntities; AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(selectedEntities, &AzToolsFramework::ToolsApplicationRequests::Bus::Events::GetSelectedEntities); @@ -469,12 +469,12 @@ void OutlinerWidget::UpdateSelection() else { { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "OutlinerWidget::ModelEntitySelectionChanged:Deselect"); + AZ_PROFILE_SCOPE(AzToolsFramework, "OutlinerWidget::ModelEntitySelectionChanged:Deselect"); m_gui->m_objectTree->selectionModel()->select( BuildSelectionFromEntities(m_entitiesToDeselect), QItemSelectionModel::Deselect); } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "OutlinerWidget::ModelEntitySelectionChanged:Select"); + AZ_PROFILE_SCOPE(AzToolsFramework, "OutlinerWidget::ModelEntitySelectionChanged:Select"); m_gui->m_objectTree->selectionModel()->select( BuildSelectionFromEntities(m_entitiesToSelect), QItemSelectionModel::Select); } @@ -497,7 +497,7 @@ void OutlinerWidget::UpdateSelection() template QItemSelection OutlinerWidget::BuildSelectionFromEntities(const EntityIdCollection& entityIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); QItemSelection selection; for (const auto& entityId : entityIds) @@ -517,7 +517,7 @@ QItemSelection OutlinerWidget::BuildSelectionFromEntities(const EntityIdCollecti void OutlinerWidget::contextMenuEvent(QContextMenuEvent* event) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); bool isDocumentOpen = false; EBUS_EVENT_RESULT(isDocumentOpen, AzToolsFramework::EditorRequests::Bus, IsLevelDocumentOpen); @@ -1272,7 +1272,7 @@ void OutlinerWidget::ExtractEntityIdsFromSelection(const QItemSelection& selecti void OutlinerWidget::OnSearchTextChanged(const QString& activeTextFilter) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::string filterString = activeTextFilter.toUtf8().data(); m_listModel->SearchStringChanged(filterString); @@ -1388,7 +1388,7 @@ void OutlinerWidget::QueueContentUpdateSort(const AZ::EntityId& entityId) void OutlinerWidget::SortContent() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_sortContentQueued = false; @@ -1424,7 +1424,7 @@ void OutlinerWidget::OnSortModeChanged(EntityOutliner::DisplaySortMode sortMode) if (sortMode != EntityOutliner::DisplaySortMode::Manually) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto comparer = AZStd::bind(&CompareEntitiesForSorting, AZStd::placeholders::_1, AZStd::placeholders::_2, sortMode); SortEntityChildrenRecursively(AZ::EntityId(), comparer); } diff --git a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterDocument.cpp b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterDocument.cpp index db6e355799..c7e14d9c4e 100644 --- a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterDocument.cpp +++ b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterDocument.cpp @@ -43,7 +43,7 @@ AssetImporterDocument::AssetImporterDocument() bool AssetImporterDocument::LoadScene(const AZStd::string& sceneFullPath) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); namespace SceneEvents = AZ::SceneAPI::Events; SceneEvents::SceneSerializationBus::BroadcastResult(m_scene, &SceneEvents::SceneSerializationBus::Events::LoadScene, sceneFullPath, AZ::Uuid::CreateNull()); return !!m_scene; diff --git a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterWindow.cpp b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterWindow.cpp index f9b2c6c023..98bf228391 100644 --- a/Code/Editor/Plugins/EditorAssetImporter/AssetImporterWindow.cpp +++ b/Code/Editor/Plugins/EditorAssetImporter/AssetImporterWindow.cpp @@ -500,10 +500,10 @@ void AssetImporterWindow::SetTitle(const char* filePath) AZStd::string extension; if (AzFramework::StringFunc::Path::GetExtension(filePath, extension, false)) { - extension[0] = toupper(extension[0]); + extension[0] = static_cast(toupper(extension[0])); for (size_t i = 1; i < extension.size(); ++i) { - extension[i] = tolower(extension[i]); + extension[i] = static_cast(tolower(extension[i])); } } else diff --git a/Code/Editor/Plugins/EditorAssetImporter/ImporterRootDisplay.cpp b/Code/Editor/Plugins/EditorAssetImporter/ImporterRootDisplay.cpp index 34527e598a..4f942a4251 100644 --- a/Code/Editor/Plugins/EditorAssetImporter/ImporterRootDisplay.cpp +++ b/Code/Editor/Plugins/EditorAssetImporter/ImporterRootDisplay.cpp @@ -45,7 +45,7 @@ AZ::SceneAPI::UI::ManifestWidget* ImporterRootDisplay::GetManifestWidget() void ImporterRootDisplay::SetSceneDisplay(const QString& headerText, const AZStd::shared_ptr& scene) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (!scene) { AZ_Assert(scene, "No scene provided to display."); @@ -62,7 +62,7 @@ void ImporterRootDisplay::SetSceneDisplay(const QString& headerText, const AZStd void ImporterRootDisplay::HandleSceneWasReset(const AZStd::shared_ptr& scene) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); // Don't accept updates while the widget is being filled in. BusDisconnect(); m_manifestWidget->BuildFromScene(scene); diff --git a/Code/Editor/Plugins/EditorAssetImporter/SceneSerializationHandler.cpp b/Code/Editor/Plugins/EditorAssetImporter/SceneSerializationHandler.cpp index c087a27ba4..b1d07af41c 100644 --- a/Code/Editor/Plugins/EditorAssetImporter/SceneSerializationHandler.cpp +++ b/Code/Editor/Plugins/EditorAssetImporter/SceneSerializationHandler.cpp @@ -6,6 +6,7 @@ * */ +#include #include #include #include @@ -37,7 +38,7 @@ namespace AZ AZStd::shared_ptr SceneSerializationHandler::LoadScene( const AZStd::string& filePath, Uuid sceneSourceGuid) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); namespace Utilities = AZ::SceneAPI::Utilities; using AZ::SceneAPI::Events::AssetImportRequest; diff --git a/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/TimeSlider.cpp b/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/TimeSlider.cpp index 4774520d0c..291723ff6b 100644 --- a/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/TimeSlider.cpp +++ b/Code/Editor/Plugins/EditorCommon/DrawingPrimitives/TimeSlider.cpp @@ -12,6 +12,8 @@ #include #include +#include + namespace DrawingPrimitives { void DrawTimeSlider(QPainter& painter, const QPalette& palette, const STimeSliderOptions& options) diff --git a/Code/Editor/Plugins/EditorCommon/QtViewPane.cpp b/Code/Editor/Plugins/EditorCommon/QtViewPane.cpp index 7d97e6f580..3deef7e503 100644 --- a/Code/Editor/Plugins/EditorCommon/QtViewPane.cpp +++ b/Code/Editor/Plugins/EditorCommon/QtViewPane.cpp @@ -9,8 +9,6 @@ #include "platform.h" -#pragma warning(disable: 4266) // disabled warning from afk overrides - #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS #include #include @@ -30,13 +28,10 @@ #include "QtUtil.h" // ugly dependencies: -#pragma warning(push) -#pragma warning(disable: 4244) // warning C4244: 'argument' : conversion from 'A' to 'B', possible loss of data #include "Functor.h" class CXmlArchive; #include #include "Util/PathUtil.h" -#pragma warning(pop) // ^^^ // --------------------------------------------------------------------------- diff --git a/Code/Editor/PreferencesStdPages.cpp b/Code/Editor/PreferencesStdPages.cpp index a4b3ee8ba4..b593541a07 100644 --- a/Code/Editor/PreferencesStdPages.cpp +++ b/Code/Editor/PreferencesStdPages.cpp @@ -89,7 +89,7 @@ REFGUID CStdPreferencesClassDesc::ClassID() ////////////////////////////////////////////////////////////////////////// int CStdPreferencesClassDesc::GetPagesCount() { - return m_pageCreators.size(); + return static_cast(m_pageCreators.size()); } IPreferencesPage* CStdPreferencesClassDesc::CreateEditorPreferencesPage(int index) diff --git a/Code/Editor/PythonEditorFuncs.cpp b/Code/Editor/PythonEditorFuncs.cpp index 2b7bca3b0b..dff41c0a86 100644 --- a/Code/Editor/PythonEditorFuncs.cpp +++ b/Code/Editor/PythonEditorFuncs.cpp @@ -76,7 +76,7 @@ namespace } else if (pCVar->GetType() == CVAR_FLOAT) { - PySetCVarFromFloat(pName, std::stod(pValue)); + PySetCVarFromFloat(pName, static_cast(std::stod(pValue))); } else if (pCVar->GetType() != CVAR_STRING) { @@ -152,11 +152,11 @@ namespace } else if (pCVar->GetType() == CVAR_INT) { - PySetCVarFromInt(pName, AZStd::any_cast(value)); + PySetCVarFromInt(pName, static_cast(AZStd::any_cast(value))); } else if (pCVar->GetType() == CVAR_FLOAT) { - PySetCVarFromFloat(pName, AZStd::any_cast(value)); + PySetCVarFromFloat(pName, static_cast(AZStd::any_cast(value))); } else if (pCVar->GetType() == CVAR_STRING) { @@ -548,13 +548,11 @@ namespace if (title.empty()) { throw std::runtime_error("Incorrect title argument passed in. "); - return result; } if (values.size() == 0) { throw std::runtime_error("Empty value list passed in. "); - return result; } QStringList list; diff --git a/Code/Editor/QtUI/PixmapLabelPreview.cpp b/Code/Editor/QtUI/PixmapLabelPreview.cpp index a98c743afb..9c415a6c4d 100644 --- a/Code/Editor/QtUI/PixmapLabelPreview.cpp +++ b/Code/Editor/QtUI/PixmapLabelPreview.cpp @@ -31,7 +31,7 @@ int PixmapLabelPreview::heightForWidth(int width) const return width; } - return ((qreal)m_pixmap.height() * width) / m_pixmap.width(); + return static_cast(((qreal)m_pixmap.height() * width) / m_pixmap.width()); } diff --git a/Code/Editor/QtViewPaneManager.cpp b/Code/Editor/QtViewPaneManager.cpp index f4f18fde83..022bb6ecd9 100644 --- a/Code/Editor/QtViewPaneManager.cpp +++ b/Code/Editor/QtViewPaneManager.cpp @@ -184,7 +184,7 @@ bool QtViewPane::CloseInstance(QDockWidget* dockWidget, CloseModes closeModes) const int numTopLevel = topLevelWidgets.size(); for (size_t i = 0; i < numTopLevel; ++i) { - QWidget* widget = topLevelWidgets[i]; + QWidget* widget = topLevelWidgets[static_cast(i)]; if (widget->isModal() && widget->isVisible()) { widget->activateWindow(); @@ -1102,7 +1102,7 @@ void QtViewPaneManager::RestoreDefaultLayout(bool resetSettings) entityInspectorViewPane->m_dockWidget->setFloating(false); static const float tabWidgetWidthPercentage = 0.2f; - int newWidth = (float)screenWidth * tabWidgetWidthPercentage; + int newWidth = static_cast((float)screenWidth * tabWidgetWidthPercentage); if (levelInspectorPane) { @@ -1139,7 +1139,7 @@ void QtViewPaneManager::RestoreDefaultLayout(bool resetSettings) // so that they get an appropriate default width since the minimum sizes have // been removed from these widgets static const float entityOutlinerWidthPercentage = 0.15f; - int newWidth = (float)screenWidth * entityOutlinerWidthPercentage; + int newWidth = static_cast((float)screenWidth * entityOutlinerWidthPercentage); m_mainWindow->resizeDocks({ entityOutlinerViewPane->m_dockWidget }, { newWidth }, Qt::Horizontal); } diff --git a/Code/Editor/Settings.cpp b/Code/Editor/Settings.cpp index 09b0d0f4f4..8672bad5c4 100644 --- a/Code/Editor/Settings.cpp +++ b/Code/Editor/Settings.cpp @@ -394,7 +394,7 @@ void SEditorSettings::LoadValue(const char* sSection, const char* sKey, float& v { const SettingsGroup sg(sSection); const QString defaultVal = s_editorSettings()->value(sKey, QString::number(value)).toString(); - value = defaultVal.toDouble(); + value = defaultVal.toFloat(); if (GetIEditor()->GetSettingsManager()) { @@ -1061,7 +1061,7 @@ void SEditorSettings::ConvertPath(const AZStd::string_view sourcePath, AZStd::st // The reason for the difference is to have this API be consistent with the path syntax in Open 3D Engine Python APIs. // Find the last pipe separator ("|") in the path - int lastSeparator = sourcePath.find_last_of("|"); + size_t lastSeparator = sourcePath.find_last_of("|"); // Everything before the last separator is the category (since only the category is hierarchical) category = sourcePath.substr(0, lastSeparator); diff --git a/Code/Editor/ToolBox.cpp b/Code/Editor/ToolBox.cpp index d784bc2083..cfebc378f7 100644 --- a/Code/Editor/ToolBox.cpp +++ b/Code/Editor/ToolBox.cpp @@ -60,7 +60,7 @@ void CToolBoxCommand::Execute() const // Toggle the variable. float val = GetIEditor()->GetConsoleVar(m_text.toUtf8().data()); bool bOn = val != 0; - GetIEditor()->SetConsoleVar(m_text.toUtf8().data(), (bOn) ? 0 : 1); + GetIEditor()->SetConsoleVar(m_text.toUtf8().data(), (bOn) ? 0.0f : 1.0f); } else { @@ -186,7 +186,6 @@ const CToolBoxMacro* CToolBoxManager::GetMacro(int iIndex, bool bToolbox) const assert(0 <= iIndex && iIndex < m_shelveMacros.size()); return m_shelveMacros[iIndex]; } - return nullptr; } ////////////////////////////////////////////////////////////////////////// @@ -202,7 +201,6 @@ CToolBoxMacro* CToolBoxManager::GetMacro(int iIndex, bool bToolbox) assert(0 <= iIndex && iIndex < m_shelveMacros.size()); return m_shelveMacros[iIndex]; } - return nullptr; } ////////////////////////////////////////////////////////////////////////// @@ -237,7 +235,7 @@ CToolBoxMacro* CToolBoxManager::NewMacro(const QString& title, bool bToolbox, in { if (bToolbox) { - const int macroCount = m_macros.size(); + const int macroCount = static_cast(m_macros.size()); if (macroCount > ID_TOOL_LAST - ID_TOOL_FIRST + 1) { return nullptr; @@ -261,7 +259,7 @@ CToolBoxMacro* CToolBoxManager::NewMacro(const QString& title, bool bToolbox, in } else { - const int shelveMacroCount = m_shelveMacros.size(); + const int shelveMacroCount = static_cast(m_shelveMacros.size()); if (shelveMacroCount > ID_TOOL_SHELVE_LAST - ID_TOOL_SHELVE_FIRST + 1) { return nullptr; @@ -275,7 +273,6 @@ CToolBoxMacro* CToolBoxManager::NewMacro(const QString& title, bool bToolbox, in m_shelveMacros.push_back(pNewTool); return pNewTool; } - return nullptr; } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/ToolbarManager.cpp b/Code/Editor/ToolbarManager.cpp index d44e794b6a..1831fe6a55 100644 --- a/Code/Editor/ToolbarManager.cpp +++ b/Code/Editor/ToolbarManager.cpp @@ -503,7 +503,7 @@ void ToolbarManager::InitializeStandardToolbars() { auto macroToolbars = GetIEditor()->GetToolBoxManager()->GetToolbars(); - m_standardToolbars.reserve(5 + macroToolbars.size()); + m_standardToolbars.reserve(static_cast(5 + macroToolbars.size())); m_standardToolbars.push_back(GetEditModeToolbar()); m_standardToolbars.push_back(GetObjectToolbar()); m_standardToolbars.push_back(GetPlayConsoleToolbar()); diff --git a/Code/Editor/ToolsConfigPage.cpp b/Code/Editor/ToolsConfigPage.cpp index 965c862554..1871dc763f 100644 --- a/Code/Editor/ToolsConfigPage.cpp +++ b/Code/Editor/ToolsConfigPage.cpp @@ -840,7 +840,7 @@ void CToolsConfigPage::FillScriptCmds() { EditorPythonConsoleInterface::GlobalFunctionCollection globalFunctionCollection; editorPythonConsoleInterface->GetGlobalFunctionList(globalFunctionCollection); - commands.reserve(globalFunctionCollection.size()); + commands.reserve(static_cast(globalFunctionCollection.size())); for (const EditorPythonConsoleInterface::GlobalFunction& globalFunction : globalFunctionCollection) { const QString fullCmd = QString("%1.%2()").arg(globalFunction.m_moduleName.data()).arg(globalFunction.m_functionName.data()); diff --git a/Code/Editor/TrackView/CommentKeyUIControls.cpp b/Code/Editor/TrackView/CommentKeyUIControls.cpp index c7c5f83cbf..6b52efd8f1 100644 --- a/Code/Editor/TrackView/CommentKeyUIControls.cpp +++ b/Code/Editor/TrackView/CommentKeyUIControls.cpp @@ -122,7 +122,7 @@ void CCommentKeyUIControls::OnUIChange(IVariable* pVar, CTrackViewKeyBundle& sel for (size_t keyIndex = 0, num = selectedKeys.GetKeyCount(); keyIndex < num; keyIndex++) { - CTrackViewKeyHandle keyHandle = selectedKeys.GetKey(keyIndex); + CTrackViewKeyHandle keyHandle = selectedKeys.GetKey(static_cast(keyIndex)); CAnimParamType paramType = keyHandle.GetTrack()->GetParameterType(); if (paramType == AnimParamType::CommentText) diff --git a/Code/Editor/TrackView/ScreenFaderKeyUIControls.cpp b/Code/Editor/TrackView/ScreenFaderKeyUIControls.cpp index a62ab17cbf..d8b3a2bdf7 100644 --- a/Code/Editor/TrackView/ScreenFaderKeyUIControls.cpp +++ b/Code/Editor/TrackView/ScreenFaderKeyUIControls.cpp @@ -128,7 +128,7 @@ void CScreenFaderKeyUIControls::OnUIChange(IVariable* pVar, CTrackViewKeyBundle& for (size_t keyIndex = 0, num = selectedKeys.GetKeyCount(); keyIndex < num; ++keyIndex) { - CTrackViewKeyHandle selectedKey = selectedKeys.GetKey(keyIndex); + CTrackViewKeyHandle selectedKey = selectedKeys.GetKey(static_cast(keyIndex)); CAnimParamType paramType = selectedKey.GetTrack()->GetParameterType(); if (paramType == AnimParamType::ScreenFader) diff --git a/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp b/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp index 66c4f63d35..33f1b0d441 100644 --- a/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp +++ b/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp @@ -93,7 +93,7 @@ static void UpdateAtomOutputFrameCaptureView(TrackView::AtomOutputFrameCapture& const AZ::EntityId activeCameraEntityId = TrackView::ActiveCameraEntityId(); atomOutputFrameCapture.UpdateView( TrackView::TransformFromEntityId(activeCameraEntityId), - TrackView::ProjectionFromCameraEntityId(activeCameraEntityId, width, height)); + TrackView::ProjectionFromCameraEntityId(activeCameraEntityId, static_cast(width), static_cast(height))); } CSequenceBatchRenderDialog::CSequenceBatchRenderDialog(float fps, QWidget* pParent /* = nullptr */) @@ -170,10 +170,10 @@ void CSequenceBatchRenderDialog::OnInitDialog() connect(m_ui->m_endFrame, editingFinished, this, &CSequenceBatchRenderDialog::OnEndFrameChange); connect(m_ui->m_imageFormatCombo, static_cast(&QComboBox::currentIndexChanged), this, &CSequenceBatchRenderDialog::OnImageFormatChange); - const float bigEnoughNumber = 1000000.0f; - m_ui->m_startFrame->setRange(0.0f, bigEnoughNumber); + const int bigEnoughNumber = 1000000; + m_ui->m_startFrame->setRange(0, bigEnoughNumber); - m_ui->m_endFrame->setRange(0.0f, bigEnoughNumber); + m_ui->m_endFrame->setRange(0, bigEnoughNumber); // Fill the sequence combo box. bool activeSequenceWasSet = false; @@ -301,8 +301,8 @@ void CSequenceBatchRenderDialog::OnRenderItemSelChange() } } // frame range - m_ui->m_startFrame->setValue(item.frameRange.start * m_fpsForTimeToFrameConversion); - m_ui->m_endFrame->setValue(item.frameRange.end * m_fpsForTimeToFrameConversion); + m_ui->m_startFrame->setValue(static_cast(item.frameRange.start * m_fpsForTimeToFrameConversion)); + m_ui->m_endFrame->setValue(static_cast(item.frameRange.end * m_fpsForTimeToFrameConversion)); // folder m_ui->m_destinationEdit->setText(item.folder); // fps @@ -357,7 +357,7 @@ void CSequenceBatchRenderDialog::OnRenderItemSelChange() QString cvarsText; for (size_t i = 0; i < item.cvars.size(); ++i) { - cvarsText += item.cvars[i]; + cvarsText += item.cvars[static_cast(i)]; cvarsText += "\r\n"; } m_ui->m_cvarsEdit->setPlainText(cvarsText); @@ -580,12 +580,12 @@ void CSequenceBatchRenderDialog::OnSequenceSelected() // Adjust the frame range. float sFrame = pSequence->GetTimeRange().start * m_fpsForTimeToFrameConversion; float eFrame = pSequence->GetTimeRange().end * m_fpsForTimeToFrameConversion; - m_ui->m_startFrame->setRange(0.0f, eFrame); - m_ui->m_endFrame->setRange(0.0f, eFrame); + m_ui->m_startFrame->setRange(0, static_cast(eFrame)); + m_ui->m_endFrame->setRange(0, static_cast(eFrame)); // Set the default start/end frames properly. - m_ui->m_startFrame->setValue(sFrame); - m_ui->m_endFrame->setValue(eFrame); + m_ui->m_startFrame->setValue(static_cast(sFrame)); + m_ui->m_endFrame->setValue(static_cast(eFrame)); m_ui->m_shotCombo->clear(); // Fill the shot combo box with the names of director nodes. @@ -894,7 +894,7 @@ void CSequenceBatchRenderDialog::CaptureItemStart() // Set up the custom config cvars for this item. for (size_t i = 0; i < renderItem.cvars.size(); ++i) { - GetIEditor()->GetSystem()->GetIConsole()->ExecuteString(renderItem.cvars[i].toUtf8().data()); + GetIEditor()->GetSystem()->GetIConsole()->ExecuteString(renderItem.cvars[static_cast(i)].toUtf8().data()); } // Set specific capture options for this item. @@ -1519,7 +1519,7 @@ void CSequenceBatchRenderDialog::OnSaveBatch() // cvars for (size_t k = 0; k < item.cvars.size(); ++k) { - itemNode->newChild("cvar")->setContent(item.cvars[k].toUtf8().data()); + itemNode->newChild("cvar")->setContent(item.cvars[static_cast(k)].toUtf8().data()); } } diff --git a/Code/Editor/TrackView/SequenceKeyUIControls.cpp b/Code/Editor/TrackView/SequenceKeyUIControls.cpp index c3bc39d65d..4199563e10 100644 --- a/Code/Editor/TrackView/SequenceKeyUIControls.cpp +++ b/Code/Editor/TrackView/SequenceKeyUIControls.cpp @@ -84,7 +84,7 @@ bool CSequenceKeyUIControls::OnKeySelectionChange(CTrackViewKeyBundle& selectedK mv_sequence->AddEnumItem(QObject::tr(""), CTrackViewDialog::GetEntityIdAsString(AZ::EntityId(AZ::EntityId::InvalidEntityId))); const CTrackViewSequenceManager* pSequenceManager = GetIEditor()->GetSequenceManager(); - for (int i = 0; i < pSequenceManager->GetCount(); ++i) + for (unsigned int i = 0; i < pSequenceManager->GetCount(); ++i) { CTrackViewSequence* pCurrentSequence = pSequenceManager->GetSequenceByIndex(i); bool bNotMe = pCurrentSequence != pSequence; diff --git a/Code/Editor/TrackView/TVCustomizeTrackColorsDlg.cpp b/Code/Editor/TrackView/TVCustomizeTrackColorsDlg.cpp index e2f8a4f7a2..ae1080a9c1 100644 --- a/Code/Editor/TrackView/TVCustomizeTrackColorsDlg.cpp +++ b/Code/Editor/TrackView/TVCustomizeTrackColorsDlg.cpp @@ -367,7 +367,7 @@ bool CTVCustomizeTrackColorsDlg::Import(const QString& fullPath) { return entry.paramType == paramType; }); - int entryIndex = pEntry - g_trackEntries; + int entryIndex = static_cast(pEntry - g_trackEntries); if (entryIndex >= arraysize(g_trackEntries)) // If not found, skip this. { continue; diff --git a/Code/Editor/TrackView/TVCustomizeTrackColorsDlg.h b/Code/Editor/TrackView/TVCustomizeTrackColorsDlg.h index 23401453d6..d3017d8e83 100644 --- a/Code/Editor/TrackView/TVCustomizeTrackColorsDlg.h +++ b/Code/Editor/TrackView/TVCustomizeTrackColorsDlg.h @@ -56,7 +56,7 @@ private: inline void GetQColorFromXmlNode(QColor& colorOut, const XmlNodeRef& xmlNode) const { - QRgb rgb = -1; + QRgb rgb = std::numeric_limits::max(); xmlNode->getAttr("color", rgb); colorOut.setRgb(rgb); }; diff --git a/Code/Editor/TrackView/TVEventsDialog.cpp b/Code/Editor/TrackView/TVEventsDialog.cpp index c8221b38cd..86b4c1f6bc 100644 --- a/Code/Editor/TrackView/TVEventsDialog.cpp +++ b/Code/Editor/TrackView/TVEventsDialog.cpp @@ -363,7 +363,7 @@ int TVEventsModel::GetNumberOfUsageAndFirstTimeUsed(const char* eventName, float { CTrackViewTrack* pTrack = tracks.GetTrack(currentTrack); - for (int currentKey = 0; currentKey < pTrack->GetKeyCount(); ++currentKey) + for (unsigned int currentKey = 0; currentKey < pTrack->GetKeyCount(); ++currentKey) { CTrackViewKeyHandle keyHandle = pTrack->GetKey(currentKey); diff --git a/Code/Editor/TrackView/TVSequenceProps.cpp b/Code/Editor/TrackView/TVSequenceProps.cpp index 1ac31d7e2b..d4e06d0c94 100644 --- a/Code/Editor/TrackView/TVSequenceProps.cpp +++ b/Code/Editor/TrackView/TVSequenceProps.cpp @@ -106,8 +106,8 @@ void CTVSequenceProps::MoveScaleKeys() // Move/Rescale the sequence to a new time range. Range timeRangeOld = m_pSequence->GetTimeRange(); Range timeRangeNew; - timeRangeNew.start = ui->START_TIME->value(); - timeRangeNew.end = ui->END_TIME->value(); + timeRangeNew.start = static_cast(ui->START_TIME->value()); + timeRangeNew.end = static_cast(ui->END_TIME->value()); if (!(timeRangeNew == timeRangeOld)) { @@ -123,14 +123,14 @@ void CTVSequenceProps::UpdateSequenceProps(const QString& name) } Range timeRange; - timeRange.start = ui->START_TIME->value(); - timeRange.end = ui->END_TIME->value(); + timeRange.start = static_cast(ui->START_TIME->value()); + timeRange.end = static_cast(ui->END_TIME->value()); if (m_timeUnit == Frames) { float invFPS = 1.0f / m_FPS; - timeRange.start = ui->START_TIME->value() * invFPS; - timeRange.end = ui->END_TIME->value() * invFPS; + timeRange.start = static_cast(ui->START_TIME->value()) * invFPS; + timeRange.end = static_cast(ui->END_TIME->value()) * invFPS; } m_pSequence->SetTimeRange(timeRange); diff --git a/Code/Editor/TrackView/TrackViewAnimNode.cpp b/Code/Editor/TrackView/TrackViewAnimNode.cpp index 9edac32da0..4b599859e9 100644 --- a/Code/Editor/TrackView/TrackViewAnimNode.cpp +++ b/Code/Editor/TrackView/TrackViewAnimNode.cpp @@ -452,7 +452,7 @@ CTrackViewAnimNode* CTrackViewAnimNode::CreateSubNode( { // Check for a duplicates CTrackViewAnimNodeBundle azEntityNodesFound = director2->GetAnimNodesByType(AnimNodeType::AzEntity); - for (int x = 0; x < azEntityNodesFound.GetCount(); x++) + for (unsigned int x = 0; x < azEntityNodesFound.GetCount(); x++) { if (azEntityNodesFound.GetNode(x)->GetAzEntityId() == owner) { @@ -1477,7 +1477,7 @@ bool CTrackViewAnimNode::PasteNodesFromClipboard(QWidget* context) AZStd::map copiedIdToNodeMap; const unsigned int numNodes = animNodesRoot->getChildCount(); - for (int i = 0; i < numNodes; ++i) + for (unsigned int i = 0; i < numNodes; ++i) { XmlNodeRef xmlNode = animNodesRoot->getChild(i); @@ -2123,7 +2123,7 @@ bool CTrackViewAnimNode::ContainsComponentWithId(AZ::ComponentId componentId) co if (GetType() == AnimNodeType::AzEntity) { // search for a matching componentId on all children - for (int i = 0; i < GetChildCount(); i++) + for (unsigned int i = 0; i < GetChildCount(); i++) { CTrackViewNode* childNode = GetChild(i); if (childNode->GetNodeType() == eTVNT_AnimNode) diff --git a/Code/Editor/TrackView/TrackViewCurveEditor.cpp b/Code/Editor/TrackView/TrackViewCurveEditor.cpp index 83204f76a6..a757387563 100644 --- a/Code/Editor/TrackView/TrackViewCurveEditor.cpp +++ b/Code/Editor/TrackView/TrackViewCurveEditor.cpp @@ -145,7 +145,7 @@ void CTrackViewCurveEditor::UpdateSplines() std::set newTracks; if (selectedTracks.AreAllOfSameType()) { - for (int i = 0; i < selectedTracks.GetCount(); i++) + for (unsigned int i = 0; i < selectedTracks.GetCount(); i++) { CTrackViewTrack* pTrack = selectedTracks.GetTrack(i); diff --git a/Code/Editor/TrackView/TrackViewDialog.cpp b/Code/Editor/TrackView/TrackViewDialog.cpp index 331daf6730..f1701f9e20 100644 --- a/Code/Editor/TrackView/TrackViewDialog.cpp +++ b/Code/Editor/TrackView/TrackViewDialog.cpp @@ -782,7 +782,7 @@ void CTrackViewDialog::UpdateActions() } bool allSelectedTracksUseMute = true; - for (int i = 0; i < selectedTrackCount; i++) + for (unsigned int i = 0; i < selectedTrackCount; i++) { CTrackViewTrack* pTrack = selectedTracks.GetTrack(i); if (pTrack && !pTrack->UsesMute()) @@ -1121,7 +1121,7 @@ void CTrackViewDialog::ReloadSequencesComboBox() CTrackViewSequenceManager* pSequenceManager = GetIEditor()->GetSequenceManager(); const unsigned int numSequences = pSequenceManager->GetCount(); - for (int k = 0; k < numSequences; ++k) + for (unsigned int k = 0; k < numSequences; ++k) { CTrackViewSequence* sequence = pSequenceManager->GetSequenceByIndex(k); QString entityIdString = GetEntityIdAsString(sequence->GetSequenceComponentEntityId()); @@ -1559,7 +1559,7 @@ void CTrackViewDialog::OnAddSelectedNode() selectedEntitiesCount, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntitiesCount); // check to make sure all nodes were added and notify user if they weren't - if (addedNodes.GetCount() != selectedEntitiesCount) + if (addedNodes.GetCount() != static_cast(selectedEntitiesCount)) { IMovieSystem* movieSystem = GetIEditor()->GetMovieSystem(); @@ -1765,7 +1765,7 @@ void CTrackViewDialog::OnSnapFPS() if (ok) { m_wndDopeSheet->SetSnapFPS(fps); - m_wndCurveEditor->SetFPS(fps); + m_wndCurveEditor->SetFPS(static_cast(fps)); SetCursorPosText(GetIEditor()->GetAnimation()->GetTime()); } @@ -1799,7 +1799,7 @@ void CTrackViewDialog::SaveMiscSettings() const settings.setValue(s_kFrameSnappingFPSEntry, fps); settings.setValue(s_kTickDisplayModeEntry, static_cast(m_wndDopeSheet->GetTickDisplayMode())); settings.setValue(s_kDefaultTracksEntry, QByteArray(reinterpret_cast(m_defaultTracksForEntityNode.data()), - m_defaultTracksForEntityNode.size() * sizeof(AnimParamType))); + static_cast(m_defaultTracksForEntityNode.size() * sizeof(AnimParamType)))); } ////////////////////////////////////////////////////////////////////////// @@ -1828,7 +1828,7 @@ void CTrackViewDialog::ReadMiscSettings() if (settings.contains(s_kFrameSnappingFPSEntry)) { - float fps = settings.value(s_kFrameSnappingFPSEntry).toDouble(); + float fps = settings.value(s_kFrameSnappingFPSEntry).toFloat(); if (fps >= s_kMinimumFrameSnappingFPS && fps <= s_kMaximumFrameSnappingFPS) { m_wndDopeSheet->SetSnapFPS(FloatToIntRet(fps)); @@ -1991,7 +1991,7 @@ void CTrackViewDialog::UpdateTracksToolBar() &Maestro::EditorSequenceComponentRequestBus::Events::GetAllAnimatablePropertiesForComponent, animatableProperties, azEntityId, pAnimNode->GetComponentId()); - paramCount = animatableProperties.size(); + paramCount = static_cast(animatableProperties.size()); } } else @@ -2317,7 +2317,7 @@ void CTrackViewDialog::SaveCurrentSequenceToFBX() CTrackViewTrackBundle allTracks = sequence->GetAllTracks(); - for (int trackID = 0; trackID < allTracks.GetCount(); ++trackID) + for (unsigned int trackID = 0; trackID < allTracks.GetCount(); ++trackID) { CTrackViewTrack* pCurrentTrack = allTracks.GetTrack(trackID); diff --git a/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp b/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp index aa4ef94e9e..d0034b2da4 100644 --- a/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp +++ b/Code/Editor/TrackView/TrackViewDopeSheetBase.cpp @@ -146,8 +146,7 @@ CTrackViewDopeSheetBase::~CTrackViewDopeSheetBase() ////////////////////////////////////////////////////////////////////////// int CTrackViewDopeSheetBase::TimeToClient(float time) const { - int x = m_leftOffset - m_scrollOffset.x() + (time * m_timeScale); - return x; + return static_cast(m_leftOffset - m_scrollOffset.x() + (time * m_timeScale)); } ////////////////////////////////////////////////////////////////////////// @@ -193,7 +192,7 @@ void CTrackViewDopeSheetBase::SetTimeRange(float start, float end) m_timeRange.Set(start, end); - SetHorizontalExtent(-m_leftOffset, m_timeRange.end * m_timeScale - m_leftOffset); + SetHorizontalExtent(-m_leftOffset, static_cast(m_timeRange.end * m_timeScale - m_leftOffset)); } ////////////////////////////////////////////////////////////////////////// @@ -258,12 +257,12 @@ void CTrackViewDopeSheetBase::SetTimeScale(float timeScale, float fAnchorTime) while (fPixelsPerTick >= 12.0 && steps < 100); float fCurrentOffset = -fAnchorTime * m_timeScale; - m_scrollOffset.rx() += fOldOffset - fCurrentOffset; + m_scrollOffset.rx() += static_cast(fOldOffset - fCurrentOffset); m_scrollBar->setValue(m_scrollOffset.x()); update(); - SetHorizontalExtent(-m_leftOffset, m_timeRange.end * m_timeScale); + SetHorizontalExtent(-m_leftOffset, static_cast(m_timeRange.end * m_timeScale)); ComputeFrameSteps(GetVisibleRange()); @@ -353,15 +352,15 @@ float CTrackViewDopeSheetBase::TickSnap(float time) const double tickTime = GetTickTime(); double t = floor(((double)time / tickTime) + 0.5); t *= tickTime; - return t; + return static_cast(t); } ////////////////////////////////////////////////////////////////////////// float CTrackViewDopeSheetBase::TimeFromPoint(const QPoint& point) const { int x = point.x() - m_leftOffset + m_scrollOffset.x(); - double t = (double)x / m_timeScale; - return (float)TickSnap(t); + float t = static_cast(x) / m_timeScale; + return TickSnap(t); } ////////////////////////////////////////////////////////////////////////// @@ -369,7 +368,7 @@ float CTrackViewDopeSheetBase::TimeFromPointUnsnapped(const QPoint& point) const { int x = point.x() - m_leftOffset + m_scrollOffset.x(); double t = (double)x / m_timeScale; - return t; + return static_cast(t); } void CTrackViewDopeSheetBase::mousePressEvent(QMouseEvent* event) @@ -1028,12 +1027,12 @@ void CTrackViewDopeSheetBase::SelectAllKeysWithinTimeFrame(const QRect& rc, cons CTrackViewTrackBundle tracks = sequence->GetAllTracks(); CTrackViewSequenceNotificationContext context(sequence); - for (int i = 0; i < tracks.GetCount(); ++i) + for (unsigned int i = 0; i < tracks.GetCount(); ++i) { CTrackViewTrack* pTrack = tracks.GetTrack(i); // Check which keys we intersect. - for (int j = 0; j < pTrack->GetKeyCount(); j++) + for (unsigned int j = 0; j < pTrack->GetKeyCount(); j++) { CTrackViewKeyHandle keyHandle = pTrack->GetKey(j); const float time = keyHandle.GetTime(); @@ -1429,7 +1428,7 @@ bool CTrackViewDopeSheetBase::IsOkToAddKeyHere(const CTrackViewTrack* pTrack, fl { const float timeEpsilon = 0.05f; - for (int i = 0; i < pTrack->GetKeyCount(); ++i) + for (unsigned int i = 0; i < pTrack->GetKeyCount(); ++i) { const CTrackViewKeyConstHandle& keyHandle = pTrack->GetKey(i); @@ -1556,7 +1555,7 @@ void CTrackViewDopeSheetBase::MouseMoveMove(const QPoint& p, [[maybe_unused]] Qt const TrackMemento& trackMemento = iter->second; pTrack->RestoreFromMemento(trackMemento.m_memento); - const unsigned int numKeys = trackMemento.m_keySelectionStates.size(); + const unsigned int numKeys = static_cast(trackMemento.m_keySelectionStates.size()); for (unsigned int i = 0; i < numKeys; ++i) { pTrack->GetKey(i).Select(trackMemento.m_keySelectionStates[i]); @@ -1764,7 +1763,7 @@ float CTrackViewDopeSheetBase::MagnetSnap(float newTime, const CTrackViewAnimNod newTime = keys.GetKey(0).GetTime(); // But if there is an in-range key in a sibling track, use it instead. // Here a 'sibling' means a track that belongs to a same node. - for (int i = 0; i < keys.GetKeyCount(); ++i) + for (unsigned int i = 0; i < keys.GetKeyCount(); ++i) { CTrackViewKeyHandle keyHandle = keys.GetKey(i); if (keyHandle.GetTrack()->GetAnimNode() == pNode) @@ -1783,7 +1782,7 @@ float CTrackViewDopeSheetBase::FrameSnap(float time) const { double t = floor((double)time / m_snapFrameTime + 0.5); t = t * m_snapFrameTime; - return t; + return static_cast(t); } ////////////////////////////////////////////////////////////////////////// @@ -1946,7 +1945,7 @@ void CTrackViewDopeSheetBase::ChangeSequenceTrackSelection(CTrackViewSequence* s CTrackViewTrackBundle prevSelectedTracks; prevSelectedTracks = sequenceWithTrack->GetSelectedTracks(); - for (int i = 0; i < prevSelectedTracks.GetCount(); i++) + for (unsigned int i = 0; i < prevSelectedTracks.GetCount(); i++) { CTrackViewTrack* prevSelectedTrack = prevSelectedTracks.GetTrack(i); if (prevSelectedTrack != trackToSelect) @@ -2003,9 +2002,10 @@ bool CTrackViewDopeSheetBase::CreateColorKey(CTrackViewTrack* pTrack, float keyT Vec3 vColor(0, 0, 0); pTrack->GetValue(keyTime, vColor); - const AZ::Color defaultColor(clamp_tpl(FloatToIntRet(vColor.x), 0, 255), - clamp_tpl(FloatToIntRet(vColor.y), 0, 255), - clamp_tpl(FloatToIntRet(vColor.z), 0, 255), + const AZ::Color defaultColor( + clamp_tpl(static_cast(FloatToIntRet(vColor.x)), 0, 255), + clamp_tpl(static_cast(FloatToIntRet(vColor.y)), 0, 255), + clamp_tpl(static_cast(FloatToIntRet(vColor.z)), 0, 255), 255); AzQtComponents::ColorPicker dlg(AzQtComponents::ColorPicker::Configuration::RGB, QString(), this); dlg.setWindowTitle(tr("Select Color")); @@ -2023,7 +2023,7 @@ bool CTrackViewDopeSheetBase::CreateColorKey(CTrackViewTrack* pTrack, float keyT AzToolsFramework::ScopedUndoBatch undoBatch("Set Key"); const unsigned int numChildNodes = pTrack->GetChildCount(); - for (int i = 0; i < numChildNodes; ++i) + for (unsigned int i = 0; i < numChildNodes; ++i) { CTrackViewTrack* subTrack = static_cast(pTrack->GetChild(i)); if (IsOkToAddKeyHere(subTrack, keyTime)) @@ -2054,7 +2054,7 @@ void CTrackViewDopeSheetBase::OnCurrentColorChange(const AZ::Color& color) void CTrackViewDopeSheetBase::UpdateColorKey(const QColor& color, bool addToUndo) { - ColorF colArray(color.red(), color.green(), color.blue(), color.alpha()); + ColorF colArray(static_cast(color.redF()), static_cast(color.greenF()), static_cast(color.blueF()), static_cast(color.alphaF())); CTrackViewSequence* sequence = m_colorUpdateTrack->GetSequence(); if (nullptr != sequence) @@ -2083,7 +2083,7 @@ void CTrackViewDopeSheetBase::UpdateColorKey(const QColor& color, bool addToUndo void CTrackViewDopeSheetBase::UpdateColorKeyHelper(const ColorF& color) { const unsigned int numChildNodes = m_colorUpdateTrack->GetChildCount(); - for (int i = 0; i < numChildNodes; ++i) + for (unsigned int i = 0; i < numChildNodes; ++i) { CTrackViewTrack* subTrack = static_cast(m_colorUpdateTrack->GetChild(i)); CTrackViewKeyHandle subTrackKey = subTrack->GetKeyByTime(m_colorUpdateKeyTime); @@ -2119,9 +2119,10 @@ void CTrackViewDopeSheetBase::EditSelectedColorKey(CTrackViewTrack* pTrack) Vec3 color; pTrack->GetValue(m_colorUpdateKeyTime, color); - const AZ::Color defaultColor(clamp_tpl(FloatToIntRet(color.x), 0, 255), - clamp_tpl(FloatToIntRet(color.y), 0, 255), - clamp_tpl(FloatToIntRet(color.z), 0, 255), + const AZ::Color defaultColor( + clamp_tpl(static_cast(FloatToIntRet(color.x)), AZ::u8(0), AZ::u8(255)), + clamp_tpl(static_cast(FloatToIntRet(color.y)), AZ::u8(0), AZ::u8(255)), + clamp_tpl(static_cast(FloatToIntRet(color.z)), AZ::u8(0), AZ::u8(255)), 255); AzQtComponents::ColorPicker picker(AzQtComponents::ColorPicker::Configuration::RGB); @@ -2258,7 +2259,7 @@ void CTrackViewDopeSheetBase::AddKeys(const QPoint& point, const bool bTryAddKey } else // A compound track { - for (int k = 0; k < pCurrTrack->GetChildCount(); ++k) + for (unsigned int k = 0; k < pCurrTrack->GetChildCount(); ++k) { CTrackViewTrack* pSubTrack = static_cast(pCurrTrack->GetChild(k)); if (IsOkToAddKeyHere(pSubTrack, keyTime)) @@ -2293,7 +2294,7 @@ void CTrackViewDopeSheetBase::AddKeys(const QPoint& point, const bool bTryAddKey else { AzToolsFramework::ScopedUndoBatch undoBatch("Create Key"); - for (int i = 0; i < pTrack->GetChildCount(); ++i) + for (unsigned int i = 0; i < pTrack->GetChildCount(); ++i) { CTrackViewTrack* pSubTrack = static_cast(pTrack->GetChild(i)); if (IsOkToAddKeyHere(pSubTrack, keyTime)) @@ -2369,12 +2370,12 @@ void CTrackViewDopeSheetBase::DrawTicks(QPainter* painter, const QRect& rc, Rang nNumberTicks = 8; } - double start = TickSnap(timeRange.start); - double step = 1.0 / m_ticksStep; + float start = TickSnap(timeRange.start); + float step = 1.0f / static_cast(m_ticksStep); - for (double t = 0.0f; t <= timeRange.end + step; t += step) + for (float t = 0.0f; t <= timeRange.end + step; t += step) { - double st = TickSnap(t); + float st = TickSnap(t); if (st > timeRange.end) { st = timeRange.end; @@ -2393,7 +2394,7 @@ void CTrackViewDopeSheetBase::DrawTicks(QPainter* painter, const QRect& rc, Rang continue; } - int k = RoundFloatToInt(st * m_ticksStep); + int k = RoundFloatToInt(st * static_cast(m_ticksStep)); if (k % nNumberTicks == 0) { if (st >= start) @@ -3094,7 +3095,7 @@ void CTrackViewDopeSheetBase::SelectKeys(const QRect& rc, const bool bMultiSelec // note the tracks to select for the keyHandles selected CTrackViewTrackBundle tracksToSelect; - for (int i = 0; i < tracks.GetCount(); ++i) + for (unsigned int i = 0; i < tracks.GetCount(); ++i) { CTrackViewTrack* pTrack = tracks.GetTrack(i); @@ -3108,7 +3109,7 @@ void CTrackViewDopeSheetBase::SelectKeys(const QRect& rc, const bool bMultiSelec (rc.bottom() >= trackRect.top() && rc.bottom() <= trackRect.bottom())) { // Check which keys we intersect. - for (int j = 0; j < pTrack->GetKeyCount(); j++) + for (unsigned int j = 0; j < pTrack->GetKeyCount(); j++) { CTrackViewKeyHandle keyHandle = pTrack->GetKey(j); @@ -3175,7 +3176,7 @@ void CTrackViewDopeSheetBase::DrawSelectedKeyIndicators(QPainter* painter) painter->setPen(Qt::green); CTrackViewKeyBundle keys = pSequence->GetSelectedKeys(); - for (int i = 0; i < keys.GetKeyCount(); ++i) + for (unsigned int i = 0; i < keys.GetKeyCount(); ++i) { const CTrackViewKeyHandle& keyHandle = keys.GetKey(i); int x = TimeToClient(keyHandle.GetTime()); @@ -3218,7 +3219,7 @@ void CTrackViewDopeSheetBase::ComputeFrameSteps(const Range& visRange) float nBIntermediateTicks = 5; m_fFrameLabelStep = fFact * afStepTable[nStepIdx]; - if (TimeToClient(m_fFrameLabelStep) - TimeToClient(0) > 1300) + if (TimeToClient(static_cast(m_fFrameLabelStep)) - TimeToClient(0.0f) > 1300) { nBIntermediateTicks = 10; } @@ -3230,7 +3231,7 @@ void CTrackViewDopeSheetBase::ComputeFrameSteps(const Range& visRange) void CTrackViewDopeSheetBase::DrawTimeLineInFrames(QPainter* painter, const QRect& rc, [[maybe_unused]] const QColor& lineCol, const QColor& textCol, [[maybe_unused]] double step) { float fFramesPerSec = 1.0f / m_snapFrameTime; - float fInvFrameLabelStep = 1.0f / m_fFrameLabelStep; + float fInvFrameLabelStep = 1.0f / static_cast(m_fFrameLabelStep); Range VisRange = GetVisibleRange(); const Range& timeRange = m_timeRange; @@ -3238,9 +3239,9 @@ void CTrackViewDopeSheetBase::DrawTimeLineInFrames(QPainter* painter, const QRec const QPen ltgray(QColor(90, 90, 90)); const QPen black(textCol); - for (double t = TickSnap(timeRange.start); t <= timeRange.end + m_fFrameTickStep; t += m_fFrameTickStep) + for (float t = TickSnap(timeRange.start); t <= timeRange.end + static_cast(m_fFrameTickStep); t += static_cast(m_fFrameTickStep)) { - double st = t; + float st = t; if (st > timeRange.end) { st = timeRange.end; @@ -3285,9 +3286,9 @@ void CTrackViewDopeSheetBase::DrawTimeLineInSeconds(QPainter* painter, const QRe const QPen ltgray(QColor(90, 90, 90)); const QPen black(textCol); - for (double t = TickSnap(timeRange.start); t <= timeRange.end + step; t += step) + for (float t = TickSnap(timeRange.start); t <= timeRange.end + static_cast(step); t += static_cast(step)) { - double st = TickSnap(t); + float st = TickSnap(t); if (st > timeRange.end) { st = timeRange.end; @@ -3306,7 +3307,7 @@ void CTrackViewDopeSheetBase::DrawTimeLineInSeconds(QPainter* painter, const QRe } int x = TimeToClient(st); - int k = RoundFloatToInt(st * m_ticksStep); + int k = RoundFloatToInt(st * static_cast(m_ticksStep)); if (k % nNumberTicks == 0) { painter->setPen(black); @@ -3423,7 +3424,7 @@ void CTrackViewDopeSheetBase::DrawSummary(QPainter* painter, const QRect& rcUpda // Draw a short thick line at each place where there is a key in any tracks. CTrackViewKeyBundle keys = pSequence->GetAllKeys(); - for (int i = 0; i < keys.GetKeyCount(); ++i) + for (unsigned int i = 0; i < keys.GetKeyCount(); ++i) { const CTrackViewKeyHandle& keyHandle = keys.GetKey(i); int x = TimeToClient(keyHandle.GetTime()); @@ -3635,7 +3636,7 @@ void CTrackViewDopeSheetBase::StoreMementoForTracksWithSelectedKeys() std::set tracks; const unsigned int numKeys = selectedKeys.GetKeyCount(); - for (int keyIndex = 0; keyIndex < numKeys; ++keyIndex) + for (unsigned int keyIndex = 0; keyIndex < numKeys; ++keyIndex) { CTrackViewKeyHandle keyHandle = selectedKeys.GetKey(keyIndex); tracks.insert(keyHandle.GetTrack()); diff --git a/Code/Editor/TrackView/TrackViewKeyPropertiesDlg.cpp b/Code/Editor/TrackView/TrackViewKeyPropertiesDlg.cpp index 6a5c5b6427..2fd46b0fc5 100644 --- a/Code/Editor/TrackView/TrackViewKeyPropertiesDlg.cpp +++ b/Code/Editor/TrackView/TrackViewKeyPropertiesDlg.cpp @@ -110,7 +110,7 @@ void CTrackViewKeyPropertiesDlg::PopulateVariables() m_wndProps->RemoveAllItems(); m_wndProps->AddVarBlock(m_pVarBlock); - m_wndProps->SetUpdateCallback(AZStd::bind(&CTrackViewKeyPropertiesDlg::OnVarChange, this, AZStd::placeholders::_1)); + m_wndProps->SetUpdateCallback([this](IVariable* var) { OnVarChange(var); }); //m_wndProps->m_props.ExpandAll(); diff --git a/Code/Editor/TrackView/TrackViewNode.cpp b/Code/Editor/TrackView/TrackViewNode.cpp index 882a23f6b0..d8507d9b0a 100644 --- a/Code/Editor/TrackView/TrackViewNode.cpp +++ b/Code/Editor/TrackView/TrackViewNode.cpp @@ -86,7 +86,7 @@ void CTrackViewKeyHandle::SetTime(float time, bool notifyListeners) if (!m_pTrack->IsSortMarkerKey(m_keyIndex)) { CTrackViewKeyBundle allKeys = m_pTrack->GetAllKeys(); - for (int x = 0; x < allKeys.GetKeyCount(); x++) + for (unsigned int x = 0; x < allKeys.GetKeyCount(); x++) { unsigned int curIndex = allKeys.GetKey(x).GetIndex(); if (m_pTrack->IsSortMarkerKey(curIndex)) diff --git a/Code/Editor/TrackView/TrackViewNodes.cpp b/Code/Editor/TrackView/TrackViewNodes.cpp index 16baa72709..ae38323cc3 100644 --- a/Code/Editor/TrackView/TrackViewNodes.cpp +++ b/Code/Editor/TrackView/TrackViewNodes.cpp @@ -1113,7 +1113,7 @@ void CTrackViewNodesCtrl::OnNMRclick(QPoint point) selectedEntitiesCount, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntitiesCount); // check to make sure all nodes were added and notify user if they weren't - if (addedNodes.GetCount() != selectedEntitiesCount) + if (addedNodes.GetCount() != static_cast(selectedEntitiesCount)) { IMovieSystem* movieSystem = GetIEditor()->GetMovieSystem(); @@ -1419,7 +1419,7 @@ void CTrackViewNodesCtrl::OnNMRclick(QPoint point) { if (animNode) { - UINT_PTR menuId = cmd - eMI_AddTrackBase; + unsigned int menuId = cmd - eMI_AddTrackBase; if (animNode->GetType() != AnimNodeType::AzEntity) { @@ -1765,7 +1765,7 @@ void CTrackViewNodesCtrl::ImportFromFBX() pSpline->SetKeyInTangent(keyIndex, inTangent); } - if (keyIndex < (pTrack->GetKeyCount() - 1)) + if (keyIndex < static_cast(pTrack->GetKeyCount() - 1)) { CTrackViewKeyHandle nextKey = key.GetNextKey(); if (nextKey.IsValid()) @@ -2306,7 +2306,7 @@ bool CTrackViewNodesCtrl::FillAddTrackMenu(STrackMenuTreeNode& menuAddTrack, con &Maestro::EditorSequenceComponentRequestBus::Events::GetAllAnimatablePropertiesForComponent, animatableProperties, azEntityId, animNode->GetComponentId()); - paramCount = animatableProperties.size(); + paramCount = static_cast(animatableProperties.size()); } } else @@ -2352,7 +2352,7 @@ bool CTrackViewNodesCtrl::FillAddTrackMenu(STrackMenuTreeNode& menuAddTrack, con QStringList splittedName = name.split("/", Qt::SkipEmptyParts); STrackMenuTreeNode* pCurrentNode = &menuAddTrack; - for (unsigned int j = 0; j < splittedName.size() - 1; ++j) + for (int j = 0; j < splittedName.size() - 1; ++j) { const QString& segment = splittedName[j]; auto findIter = pCurrentNode->children.find(segment); @@ -2652,7 +2652,7 @@ void CTrackViewNodesCtrl::CreateSetAnimationLayerPopupMenu(QMenu& menuSetLayer, CTrackViewTrackBundle animationTracks = pTrack->GetAnimNode()->GetTracksByParam(AnimParamType::Animation); const unsigned int numAnimationTracks = animationTracks.GetCount(); - for (int i = 0; i < numAnimationTracks; ++i) + for (unsigned int i = 0; i < numAnimationTracks; ++i) { CTrackViewTrack* pAnimationTrack = animationTracks.GetTrack(i); if (pAnimationTrack) diff --git a/Code/Editor/TrackView/TrackViewPythonFuncs.cpp b/Code/Editor/TrackView/TrackViewPythonFuncs.cpp index acabff6827..d50060269b 100644 --- a/Code/Editor/TrackView/TrackViewPythonFuncs.cpp +++ b/Code/Editor/TrackView/TrackViewPythonFuncs.cpp @@ -113,7 +113,7 @@ namespace AZStd::string PyTrackViewGetSequenceName(unsigned int index) { - if (index < PyTrackViewGetNumSequences()) + if (static_cast(index) < PyTrackViewGetNumSequences()) { const CTrackViewSequenceManager* pSequenceManager = GetIEditor()->GetSequenceManager(); return pSequenceManager->GetSequenceByIndex(index)->GetName(); @@ -378,7 +378,7 @@ namespace } CTrackViewAnimNodeBundle foundNodes = pParentDirector->GetAllAnimNodes(); - if (index < 0 || index >= foundNodes.GetCount()) + if (index < 0 || index >= static_cast(foundNodes.GetCount())) { throw std::runtime_error("Invalid node index"); } diff --git a/Code/Editor/TrackView/TrackViewSequence.cpp b/Code/Editor/TrackView/TrackViewSequence.cpp index 3647c554dc..f66e5276cd 100644 --- a/Code/Editor/TrackView/TrackViewSequence.cpp +++ b/Code/Editor/TrackView/TrackViewSequence.cpp @@ -455,7 +455,7 @@ void CTrackViewSequence::OnNodeChanged(CTrackViewNode* node, ITrackViewSequenceL // Make sure to deselect any keys CTrackViewKeyBundle keys = node->GetAllKeys(); - for (int key = 0; key < keys.GetKeyCount(); key++) + for (unsigned int key = 0; key < keys.GetKeyCount(); key++) { CTrackViewKeyHandle keyHandle = keys.GetKey(key); if (keyHandle.IsSelected()) @@ -1249,7 +1249,7 @@ void CTrackViewSequence::DeselectAllKeys() CTrackViewSequenceNotificationContext context(this); CTrackViewKeyBundle selectedKeys = GetSelectedKeys(); - for (int i = 0; i < selectedKeys.GetKeyCount(); ++i) + for (unsigned int i = 0; i < selectedKeys.GetKeyCount(); ++i) { CTrackViewKeyHandle keyHandle = selectedKeys.GetKey(i); keyHandle.Select(false); @@ -1403,7 +1403,7 @@ float CTrackViewSequence::ClipTimeOffsetForSliding(const float timeOffset) for (pTrackIter = tracks.begin(); pTrackIter != tracks.end(); ++pTrackIter) { CTrackViewTrack* pTrack = *pTrackIter; - for (int i = 0; i < pTrack->GetKeyCount(); ++i) + for (unsigned int i = 0; i < pTrack->GetKeyCount(); ++i) { const CTrackViewKeyHandle& keyHandle = pTrack->GetKey(i); @@ -1486,7 +1486,7 @@ void CTrackViewSequence::CloneSelectedKeys() std::vector selectedKeyTimes; for (size_t k = 0; k < selectedKeys.GetKeyCount(); ++k) { - CTrackViewKeyHandle skey = selectedKeys.GetKey(k); + CTrackViewKeyHandle skey = selectedKeys.GetKey(static_cast(k)); if (pTrack != skey.GetTrack()) { pTrack = skey.GetTrack(); @@ -1498,7 +1498,7 @@ void CTrackViewSequence::CloneSelectedKeys() // Now, do the actual cloning. for (size_t k = 0; k < selectedKeyTimes.size(); ++k) { - CTrackViewKeyHandle skey = selectedKeys.GetKey(k); + CTrackViewKeyHandle skey = selectedKeys.GetKey(static_cast(k)); skey = skey.GetTrack()->GetKeyByTime(selectedKeyTimes[k]); assert(skey.IsValid()); diff --git a/Code/Editor/TrackView/TrackViewSequenceManager.cpp b/Code/Editor/TrackView/TrackViewSequenceManager.cpp index 277483691a..780c8f04ce 100644 --- a/Code/Editor/TrackView/TrackViewSequenceManager.cpp +++ b/Code/Editor/TrackView/TrackViewSequenceManager.cpp @@ -227,7 +227,7 @@ void CTrackViewSequenceManager::AddTrackViewSequence(CTrackViewSequence* sequenc //////////////////////////////////////////////////////////////////////////// void CTrackViewSequenceManager::DeleteSequence(CTrackViewSequence* sequence) { - const int numSequences = m_sequences.size(); + const int numSequences = static_cast(m_sequences.size()); for (int sequenceIndex = 0; sequenceIndex < numSequences; ++sequenceIndex) { if (m_sequences[sequenceIndex].get() == sequence) @@ -246,7 +246,7 @@ void CTrackViewSequenceManager::DeleteSequence(CTrackViewSequence* sequence) { AZ::ComponentTypeList requiredComponents; AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult(requiredComponents, &AzToolsFramework::EditorEntityContextRequestBus::Events::GetRequiredComponentTypes); - const int numComponentToDeleteEntity = requiredComponents.size() + 1; + const int numComponentToDeleteEntity = static_cast(requiredComponents.size() + 1); AZ::Entity::ComponentArrayType entityComponents = entity->GetComponents(); if (entityComponents.size() == numComponentToDeleteEntity) @@ -413,9 +413,9 @@ void CTrackViewSequenceManager::OnDataBaseItemEvent([[maybe_unused]] IDataBaseIt { if (event != EDataBaseItemEvent::EDB_ITEM_EVENT_ADD) { - const uint numSequences = m_sequences.size(); + const size_t numSequences = m_sequences.size(); - for (uint i = 0; i < numSequences; ++i) + for (size_t i = 0; i < numSequences; ++i) { m_sequences[i]->UpdateDynamicParams(); } diff --git a/Code/Editor/TrackView/TrackViewSplineCtrl.cpp b/Code/Editor/TrackView/TrackViewSplineCtrl.cpp index c21403d1f5..4911297985 100644 --- a/Code/Editor/TrackView/TrackViewSplineCtrl.cpp +++ b/Code/Editor/TrackView/TrackViewSplineCtrl.cpp @@ -706,7 +706,7 @@ void CTrackViewSplineCtrl::mouseMoveEvent(QMouseEvent* event) QString tipText; bool boFoundTheSelectedKey(false); - for (int splineIndex = 0, endSpline = m_splines.size(); splineIndex < endSpline; ++splineIndex) + for (size_t splineIndex = 0, endSpline = m_splines.size(); splineIndex < endSpline; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; CTrackViewTrack* pTrack = m_tracks[splineIndex]; @@ -796,7 +796,7 @@ void CTrackViewSplineCtrl::AdjustTCB(float d_tension, float d_continuity, float SendNotifyEvent(SPLN_BEFORE_CHANGE); - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; CTrackViewTrack* pTrack = m_tracks[splineIndex]; @@ -892,7 +892,7 @@ void CTrackViewSplineCtrl::OnUserCommand(UINT cmd) bool CTrackViewSplineCtrl::IsUnifiedKeyCurrentlySelected() const { - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; diff --git a/Code/Editor/TrackView/TrackViewUndo.cpp b/Code/Editor/TrackView/TrackViewUndo.cpp index d0b85762a2..c9cdc62bc3 100644 --- a/Code/Editor/TrackView/TrackViewUndo.cpp +++ b/Code/Editor/TrackView/TrackViewUndo.cpp @@ -70,7 +70,7 @@ CTrackViewTrack* CUndoComponentEntityTrackObject::FindTrack(CTrackViewSequence* CTrackViewTrack* track = nullptr; CTrackViewTrackBundle allTracks = sequence->GetAllTracks(); - for (int trackIndex = 0; trackIndex < allTracks.GetCount(); trackIndex++) + for (unsigned int trackIndex = 0; trackIndex < allTracks.GetCount(); trackIndex++) { CTrackViewTrack* curTrack = allTracks.GetTrack(trackIndex); if (curTrack->GetAnimNode() && curTrack->GetAnimNode()->GetComponentId() == m_trackComponentId) diff --git a/Code/Editor/TrackViewNewSequenceDialog.cpp b/Code/Editor/TrackViewNewSequenceDialog.cpp index 0efc7a932e..287f69df47 100644 --- a/Code/Editor/TrackViewNewSequenceDialog.cpp +++ b/Code/Editor/TrackViewNewSequenceDialog.cpp @@ -78,7 +78,7 @@ void CTVNewSequenceDialog::OnOK() return; } - for (int k = 0; k < GetIEditor()->GetSequenceManager()->GetCount(); ++k) + for (unsigned int k = 0; k < GetIEditor()->GetSequenceManager()->GetCount(); ++k) { CTrackViewSequence* pSequence = GetIEditor()->GetSequenceManager()->GetSequenceByIndex(k); QString fullname = pSequence->GetName(); diff --git a/Code/Editor/Undo/Undo.cpp b/Code/Editor/Undo/Undo.cpp index 6af141b9e7..910a670bee 100644 --- a/Code/Editor/Undo/Undo.cpp +++ b/Code/Editor/Undo/Undo.cpp @@ -49,7 +49,7 @@ public: } void Undo(bool bUndo) override { - for (int i = m_undoSteps.size() - 1; i >= 0; i--) + for (int i = static_cast(m_undoSteps.size()) - 1; i >= 0; i--) { m_undoSteps[i]->Undo(bUndo); } @@ -624,13 +624,13 @@ void CUndoManager::SuperCancel() ////////////////////////////////////////////////////////////////////////// int CUndoManager::GetUndoStackLen() const { - return m_undoStack.size(); + return static_cast(m_undoStack.size()); } ////////////////////////////////////////////////////////////////////////// int CUndoManager::GetRedoStackLen() const { - return m_redoStack.size(); + return static_cast(m_redoStack.size()); } ////////////////////////////////////////////////////////////////////////// @@ -817,7 +817,7 @@ void CUndoManager::SignalNumUndoRedoToListeners() { for (IUndoManagerListener* listener : m_listeners) { - listener->SignalNumUndoRedo(m_undoStack.size(), m_redoStack.size()); + listener->SignalNumUndoRedo(static_cast(m_undoStack.size()), static_cast(m_redoStack.size())); } } diff --git a/Code/Editor/UndoDropDown.cpp b/Code/Editor/UndoDropDown.cpp index fbe18d5d52..6bf807ebf4 100644 --- a/Code/Editor/UndoDropDown.cpp +++ b/Code/Editor/UndoDropDown.cpp @@ -68,7 +68,7 @@ public: return 0; } - return m_stackNames.size(); + return static_cast(m_stackNames.size()); } QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override @@ -101,13 +101,13 @@ public: if (fresh.size() < m_stackNames.size()) { - beginRemoveRows(createIndex(-1, -1), fresh.size(), m_stackNames.size() - 1); + beginRemoveRows(createIndex(-1, -1), static_cast(fresh.size()), static_cast(m_stackNames.size() - 1)); m_stackNames = fresh; endRemoveRows(); } else { - beginInsertRows(createIndex(-1, -1), m_stackNames.size(), fresh.size() - 1); + beginInsertRows(createIndex(-1, -1), static_cast(m_stackNames.size()), static_cast(fresh.size() - 1)); m_stackNames = fresh; endInsertRows(); } diff --git a/Code/Editor/Util/3DConnexionDriver.cpp b/Code/Editor/Util/3DConnexionDriver.cpp index c1c3b47c4b..9dc1600185 100644 --- a/Code/Editor/Util/3DConnexionDriver.cpp +++ b/Code/Editor/Util/3DConnexionDriver.cpp @@ -58,36 +58,26 @@ bool C3DConnexionDriver::InitDevice() //Doc says RIM_TYPEHID: Data comes from an HID that is not a keyboard or a mouse. if (m_pRawInputDeviceList[i].dwType == RIM_TYPEHID) { - UINT nchars = 300; - TCHAR deviceName[300]; - if (GetRawInputDeviceInfo(m_pRawInputDeviceList[i].hDevice, - RIDI_DEVICENAME, deviceName, &nchars) >= 0) - { - //_RPT3(_CRT_WARN, "Device[%d]: handle=0x%x name = %S\n", i, g_pRawInputDeviceList[i].hDevice, deviceName); - } - RID_DEVICE_INFO dinfo; UINT sizeofdinfo = sizeof(dinfo); dinfo.cbSize = sizeofdinfo; - if (GetRawInputDeviceInfo(m_pRawInputDeviceList[i].hDevice, - RIDI_DEVICEINFO, &dinfo, &sizeofdinfo) >= 0) + GetRawInputDeviceInfo(m_pRawInputDeviceList[i].hDevice, + RIDI_DEVICEINFO, &dinfo, &sizeofdinfo); + if (dinfo.dwType == RIM_TYPEHID) { - if (dinfo.dwType == RIM_TYPEHID) + RID_DEVICE_INFO_HID* phidInfo = &dinfo.hid; + // Add this one to the list of interesting devices? + // Actually only have to do this once to get input from all usage 1, usagePage 8 devices + // This just keeps out the other usages. + // You might want to put up a list for users to select amongst the different devices. + // In particular, to assign separate functionality to the different devices. + if (phidInfo->usUsagePage == 1 && phidInfo->usUsage == 8) { - RID_DEVICE_INFO_HID* phidInfo = &dinfo.hid; - // Add this one to the list of interesting devices? - // Actually only have to do this once to get input from all usage 1, usagePage 8 devices - // This just keeps out the other usages. - // You might want to put up a list for users to select amongst the different devices. - // In particular, to assign separate functionality to the different devices. - if (phidInfo->usUsagePage == 1 && phidInfo->usUsage == 8) - { - m_pRawInputDevices[m_nUsagePage1Usage8Devices].usUsagePage = phidInfo->usUsagePage; - m_pRawInputDevices[m_nUsagePage1Usage8Devices].usUsage = phidInfo->usUsage; - m_pRawInputDevices[m_nUsagePage1Usage8Devices].dwFlags = 0; - m_pRawInputDevices[m_nUsagePage1Usage8Devices].hwndTarget = nullptr; - m_nUsagePage1Usage8Devices++; - } + m_pRawInputDevices[m_nUsagePage1Usage8Devices].usUsagePage = phidInfo->usUsagePage; + m_pRawInputDevices[m_nUsagePage1Usage8Devices].usUsage = phidInfo->usUsage; + m_pRawInputDevices[m_nUsagePage1Usage8Devices].dwFlags = 0; + m_pRawInputDevices[m_nUsagePage1Usage8Devices].hwndTarget = nullptr; + m_nUsagePage1Usage8Devices++; } } } diff --git a/Code/Editor/Util/AffineParts.cpp b/Code/Editor/Util/AffineParts.cpp index 7e6a1be35b..d83a1986b9 100644 --- a/Code/Editor/Util/AffineParts.cpp +++ b/Code/Editor/Util/AffineParts.cpp @@ -9,8 +9,6 @@ #include "EditorDefs.h" -#pragma warning ( disable : 4244 ) // conversion from 'double' to 'float', possible loss of data. - /**** Decompose.h - Basic declarations ****/ typedef struct { @@ -160,11 +158,11 @@ static Quatern Qt_FromMatrix(HMatrix mat) if (tr >= 0.0) { s = sqrt(tr + mat[W][W]); - qu.w = s * 0.5; + qu.w = static_cast(s * 0.5); s = 0.5 / s; - qu.x = (mat[Z][Y] - mat[Y][Z]) * s; - qu.y = (mat[X][Z] - mat[Z][X]) * s; - qu.z = (mat[Y][X] - mat[X][Y]) * s; + qu.x = static_cast((mat[Z][Y] - mat[Y][Z]) * s); + qu.y = static_cast((mat[X][Z] - mat[Z][X]) * s); + qu.z = static_cast((mat[Y][X] - mat[X][Y]) * s); } else { @@ -182,11 +180,11 @@ static Quatern Qt_FromMatrix(HMatrix mat) #define caseMacro(i, j, k, I, J, K) \ case I: \ s = sqrt((mat[I][I] - (mat[J][J] + mat[K][K])) + mat[W][W]); \ - qu.i = s * 0.5; \ + qu.i = static_cast(s * 0.5); \ s = 0.5 / s; \ - qu.j = (mat[I][J] + mat[J][I]) * s; \ - qu.k = (mat[K][I] + mat[I][K]) * s; \ - qu.w = (mat[K][J] - mat[J][K]) * s; \ + qu.j = static_cast((mat[I][J] + mat[J][I]) * s); \ + qu.k = static_cast((mat[K][I] + mat[I][K]) * s); \ + qu.w = static_cast((mat[K][J] - mat[J][K]) * s); \ break caseMacro(x, y, z, X, Y, Z); caseMacro(y, z, x, Y, Z, X); @@ -265,7 +263,7 @@ static void make_reflector(float* v, float* u) u[0] = v[0]; u[1] = v[1]; u[2] = v[2] + ((v[2] < 0.0) ? -s : s); - s = sqrt(2.0 / vdot(u, u)); + s = static_cast(sqrt(2.0f / vdot(u, u))); u[0] = u[0] * s; u[1] = u[1] * s; u[2] = u[2] * s; @@ -409,8 +407,8 @@ float polar_decomp(HMatrix M, HMatrix Q, HMatrix S) MadjT_one = norm_one(MadjTk); MadjT_inf = norm_inf(MadjTk); gamma = sqrt(sqrt((MadjT_one * MadjT_inf) / (M_one * M_inf)) / fabs(det)); - g1 = gamma * 0.5; - g2 = 0.5 / (gamma * det); + g1 = gamma * 0.5f; + g2 = 0.5f / (gamma * det); mat_copy(Ek, =, Mk, 3); mat_binop(Mk, =, g1 * Mk, +, g2 * MadjTk, 3); mat_copy(Ek, -=, Mk, 3); @@ -426,7 +424,7 @@ float polar_decomp(HMatrix M, HMatrix Q, HMatrix S) { for (int j = i; j < 3; j++) { - S[i][j] = S[j][i] = 0.5 * (S[i][j] + S[j][i]); + S[i][j] = S[j][i] = 0.5f * (S[i][j] + S[j][i]); } } return (det); @@ -456,7 +454,7 @@ HVect spect_decomp(HMatrix S, HMatrix U) OffD[Z] = S[X][Y]; for (sweep = 20; sweep > 0; sweep--) { - float sm = fabs(OffD[X]) + fabs(OffD[Y]) + fabs(OffD[Z]); + float sm = static_cast(fabs(OffD[X]) + fabs(OffD[Y]) + fabs(OffD[Z])); if (sm == 0.0) { break; @@ -498,16 +496,16 @@ HVect spect_decomp(HMatrix S, HMatrix U) { a = U[j][p]; b = U[j][q]; - U[j][p] -= s * (b + tau * a); - U[j][q] += s * (a - tau * b); + U[j][p] -= static_cast(s * (b + tau * a)); + U[j][q] += static_cast(s * (a - tau * b)); } } } } - kv.x = Diag[X]; - kv.y = Diag[Y]; - kv.z = Diag[Z]; - kv.w = 1.0; + kv.x = static_cast(Diag[X]); + kv.y = static_cast(Diag[Y]); + kv.z = static_cast(Diag[Z]); + kv.w = 1.0f; return (kv); } @@ -652,7 +650,7 @@ Quatern snuggle(Quatern q, HVect* k) } qp = Qt_Mul(q, p); t = sqrt(mag[win] + 0.5); - p = Qt_Mul(p, Qt_(0.0, 0.0, -qp.z / t, qp.w / t)); + p = Qt_Mul(p, Qt_(0.0f, 0.0f, static_cast(-qp.z / t), static_cast(qp.w / t))); p = Qt_Mul(qtoz, Qt_Conj(p)); } else @@ -723,14 +721,14 @@ Quatern snuggle(Quatern q, HVect* k) int ii; for (ii = 0; ii < 4; ii++) { - pa[ii] = sgn(neg[ii], 0.5); + pa[ii] = static_cast(sgn(neg[ii], 0.5f)); } } cycle(ka, par) } else { /*big*/ - pa[hi] = sgn(neg[hi], 1.0); + pa[hi] = static_cast(sgn(neg[hi], 1.0f)); } } else @@ -754,7 +752,7 @@ Quatern snuggle(Quatern q, HVect* k) } else { /*big*/ - pa[hi] = sgn(neg[hi], 1.0); + pa[hi] = static_cast(sgn(neg[hi], 1.0f)); } } p.x = -pa[0]; diff --git a/Code/Editor/Util/Contrib/NvFloatMath.inl b/Code/Editor/Util/Contrib/NvFloatMath.inl index 218d77b749..6bd3b9f7c5 100644 --- a/Code/Editor/Util/Contrib/NvFloatMath.inl +++ b/Code/Editor/Util/Contrib/NvFloatMath.inl @@ -103,7 +103,6 @@ it hasn't been integrated into this code drop yet. ** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#pragma warning(disable:4996) class TVec { diff --git a/Code/Editor/Util/FileUtil.cpp b/Code/Editor/Util/FileUtil.cpp index f26ffa60ec..435ec67a99 100644 --- a/Code/Editor/Util/FileUtil.cpp +++ b/Code/Editor/Util/FileUtil.cpp @@ -455,7 +455,7 @@ bool CFileUtil::ExtractDccFilenameUsingNamingConventions(const QString& assetFil ////////////////////////////////////////////////////////////////////////// void CFileUtil::FormatFilterString(QString& filter) { - const int numPipeChars = std::count(filter.begin(), filter.end(), '|'); + const int numPipeChars = static_cast(std::count(filter.begin(), filter.end(), '|')); if (numPipeChars == 1) { filter = QStringLiteral("%1||").arg(filter); @@ -1228,7 +1228,7 @@ bool CFileUtil::CreatePath(const QString& strPath) nTotalPathQueueElements = cstrDirectoryQueue.size(); for (nCurrentPathQueue = 0; nCurrentPathQueue < nTotalPathQueueElements; ++nCurrentPathQueue) { - strCurrentDirectoryPath += cstrDirectoryQueue[nCurrentPathQueue]; + strCurrentDirectoryPath += cstrDirectoryQueue[static_cast(nCurrentPathQueue)]; strCurrentDirectoryPath += "\\"; // The value which will go out of this loop is the result of the attempt to create the // last directory, only. @@ -1368,8 +1368,8 @@ IFileUtil::ECopyTreeResult CFileUtil::CopyTree(const QString& strSourceDirectory return eCopyResult; } - QString sourceName = sourceDir.absoluteFilePath(cFiles[nCurrent]); - QString targetName = targetDir.absoluteFilePath(cFiles[nCurrent]); + QString sourceName = sourceDir.absoluteFilePath(cFiles[static_cast(nCurrent)]); + QString targetName = targetDir.absoluteFilePath(cFiles[static_cast(nCurrent)]); if (boConfirmOverwrite) { @@ -1387,7 +1387,7 @@ IFileUtil::ECopyTreeResult CFileUtil::CopyTree(const QString& strSourceDirectory const int ret = QMessageBox::question(AzToolsFramework::GetActiveWindow(), QObject::tr("Confirm file overwrite?"), QObject::tr("There is already a file named \"%1\" in the target folder. Do you want to move this file anyway replacing the old one?") - .arg(cFiles[nCurrent]), + .arg(cFiles[static_cast(nCurrent)]), QMessageBox::YesToAll | QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); switch (ret) { @@ -1448,8 +1448,8 @@ IFileUtil::ECopyTreeResult CFileUtil::CopyTree(const QString& strSourceDirectory bool bnLastDirectoryWasCreated(false); - QString sourceName = sourceDir.absoluteFilePath(cDirectories[nCurrent]); - QString targetName = targetDir.absoluteFilePath(cDirectories[nCurrent]); + QString sourceName = sourceDir.absoluteFilePath(cDirectories[static_cast(nCurrent)]); + QString targetName = targetDir.absoluteFilePath(cDirectories[static_cast(nCurrent)]); bnLastDirectoryWasCreated = QDir().mkpath(targetName); @@ -1473,7 +1473,7 @@ IFileUtil::ECopyTreeResult CFileUtil::CopyTree(const QString& strSourceDirectory const int ret = QMessageBox::question(AzToolsFramework::GetActiveWindow(), QObject::tr("Confirm directory overwrite?"), QObject::tr("There is already a folder named \"%1\" in the target folder. Do you want to move this folder anyway?") - .arg(cDirectories[nCurrent]), + .arg(cDirectories[static_cast(nCurrent)]), QMessageBox::YesToAll | QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); switch (ret) { @@ -1742,8 +1742,8 @@ IFileUtil::ECopyTreeResult CFileUtil::MoveTree(const QString& strSourceDirecto } bool bnLastFileWasCopied(false); - QString sourceName(sourceDir.absoluteFilePath(cFiles[nCurrent])); - QString targetName(targetDir.absoluteFilePath(cFiles[nCurrent])); + QString sourceName(sourceDir.absoluteFilePath(cFiles[static_cast(nCurrent)])); + QString targetName(targetDir.absoluteFilePath(cFiles[static_cast(nCurrent)])); if (boConfirmOverwrite) { @@ -1761,7 +1761,7 @@ IFileUtil::ECopyTreeResult CFileUtil::MoveTree(const QString& strSourceDirecto const int ret = QMessageBox::question(AzToolsFramework::GetActiveWindow(), QObject::tr("Confirm file overwrite?"), QObject::tr("There is already a file named \"%1\" in the target folder. Do you want to move this file anyway replacing the old one?") - .arg(cFiles[nCurrent]), + .arg(cFiles[static_cast(nCurrent)]), QMessageBox::YesToAll | QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); switch (ret) { @@ -1822,8 +1822,8 @@ IFileUtil::ECopyTreeResult CFileUtil::MoveTree(const QString& strSourceDirecto return eCopyResult; } - QString sourceName(sourceDir.absoluteFilePath(cDirectories[nCurrent])); - QString targetName(targetDir.absoluteFilePath(cDirectories[nCurrent])); + QString sourceName(sourceDir.absoluteFilePath(cDirectories[static_cast(nCurrent)])); + QString targetName(targetDir.absoluteFilePath(cDirectories[static_cast(nCurrent)])); bnLastDirectoryWasCreated = QDir().mkdir(targetName); @@ -1847,7 +1847,7 @@ IFileUtil::ECopyTreeResult CFileUtil::MoveTree(const QString& strSourceDirecto const int ret = QMessageBox::question(AzToolsFramework::GetActiveWindow(), QObject::tr("Confirm directory overwrite?"), QObject::tr("There is already a folder named \"%1\" in the target folder. Do you want to move this folder anyway?") - .arg(cDirectories[nCurrent]), + .arg(cDirectories[static_cast(nCurrent)]), QMessageBox::YesToAll | QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); switch (ret) { diff --git a/Code/Editor/Util/GdiUtil.cpp b/Code/Editor/Util/GdiUtil.cpp index eba5ac8579..1048b5f4dd 100644 --- a/Code/Editor/Util/GdiUtil.cpp +++ b/Code/Editor/Util/GdiUtil.cpp @@ -15,43 +15,6 @@ #include #include -bool ComputeThumbsLayoutInfo(float aContainerWidth, float aThumbWidth, float aMargin, UINT aThumbCount, UINT& rThumbsPerRow, float& rNewMargin) -{ - rThumbsPerRow = 0; - rNewMargin = 0; - - if (aThumbWidth <= 0 || aMargin <= 0 || (aThumbWidth + aMargin * 2) <= 0) - { - return false; - } - - if (aContainerWidth <= 0) - { - return true; - } - - rThumbsPerRow = (int) aContainerWidth / (aThumbWidth + aMargin * 2); - - if ((aThumbWidth + aMargin * 2) * aThumbCount < aContainerWidth) - { - rNewMargin = aMargin; - } - else - { - if (rThumbsPerRow > 0) - { - rNewMargin = (aContainerWidth - rThumbsPerRow * aThumbWidth); - - if (rNewMargin > 0) - { - rNewMargin = (float)rNewMargin / rThumbsPerRow / 2.0f; - } - } - } - - return true; -} - QColor ScaleColor(const QColor& c, float aScale) { QColor aColor = c; @@ -61,15 +24,11 @@ QColor ScaleColor(const QColor& c, float aScale) aColor = QColor(1, 1, 1); } - int r = aColor.red(); - int g = aColor.green(); - int b = aColor.blue(); + const float r = static_cast(aColor.red()) * aScale; + const float g = static_cast(aColor.green()) * aScale; + const float b = static_cast(aColor.blue()) * aScale; - r *= aScale; - g *= aScale; - b *= aScale; - - return QColor(CLAMP(r, 0, 255), CLAMP(g, 0, 255), CLAMP(b, 0, 255)); + return QColor(CLAMP(static_cast(r), 0, 255), CLAMP(static_cast(g), 0, 255), CLAMP(static_cast(b), 0, 255)); } CAlphaBitmap::CAlphaBitmap() diff --git a/Code/Editor/Util/GdiUtil.h b/Code/Editor/Util/GdiUtil.h index 55165b5799..f38cbc0c0e 100644 --- a/Code/Editor/Util/GdiUtil.h +++ b/Code/Editor/Util/GdiUtil.h @@ -14,16 +14,6 @@ #define CRYINCLUDE_EDITOR_UTIL_GDIUTIL_H #pragma once -//! function used to compute thumbs per row and spacing, used in asset browser and other tools where thumb layout is needed and maybe GDI canvas used -//! \param aContainerWidth the thumbs' container width -//! \param aThumbWidth the thumb image width -//! \param aMargin the thumb default minimum horizontal margin -//! \param aThumbCount the thumb count -//! \param rThumbsPerRow returned thumb count per single row -//! \param rNewMargin returned new computed margin between thumbs -//! \note The margin between thumbs will grow/shrink dynamically to keep up with the thumb count per row -bool ComputeThumbsLayoutInfo(float aContainerWidth, float aThumbWidth, float aMargin, UINT aThumbCount, UINT& rThumbsPerRow, float& rNewMargin); - QColor ScaleColor(const QColor& coor, float aScale); //! This class loads alpha-channel bitmaps and holds a DC for use with AlphaBlend function diff --git a/Code/Editor/Util/GuidUtil.h b/Code/Editor/Util/GuidUtil.h index 2a82e3682b..9952d6b4ed 100644 --- a/Code/Editor/Util/GuidUtil.h +++ b/Code/Editor/Util/GuidUtil.h @@ -64,14 +64,14 @@ inline GUID GuidUtil::FromString(const char* guidString) guid.Data3 = 0; azsscanf(guidString, "{%8" SCNx32 "-%4hX-%4hX-%2X%2X-%2X%2X%2X%2X%2X%2X}", &guid.Data1, &guid.Data2, &guid.Data3, &d[0], &d[1], &d[2], &d[3], &d[4], &d[5], &d[6], &d[7]); - guid.Data4[0] = d[0]; - guid.Data4[1] = d[1]; - guid.Data4[2] = d[2]; - guid.Data4[3] = d[3]; - guid.Data4[4] = d[4]; - guid.Data4[5] = d[5]; - guid.Data4[6] = d[6]; - guid.Data4[7] = d[7]; + guid.Data4[0] = static_cast(d[0]); + guid.Data4[1] = static_cast(d[1]); + guid.Data4[2] = static_cast(d[2]); + guid.Data4[3] = static_cast(d[3]); + guid.Data4[4] = static_cast(d[4]); + guid.Data4[5] = static_cast(d[5]); + guid.Data4[6] = static_cast(d[6]); + guid.Data4[7] = static_cast(d[7]); return guid; } diff --git a/Code/Editor/Util/ImageASC.cpp b/Code/Editor/Util/ImageASC.cpp index 11dad7b696..c166917a68 100644 --- a/Code/Editor/Util/ImageASC.cpp +++ b/Code/Editor/Util/ImageASC.cpp @@ -55,9 +55,9 @@ bool CImageASC::Save(const QString& fileName, const CFloatImage& image) fprintf(file, fileHeader.c_str()); // Then print all the pixels. - for (int y = 0; y < height; y++) + for (uint32 y = 0; y < height; y++) { - for (int x = 0; x < width; x++) + for (uint32 x = 0; x < width; x++) { fprintf(file, "%.7f ", pixels[x + y * width]); } @@ -132,7 +132,7 @@ bool CImageASC::Load(const QString& fileName, CFloatImage& image) token = azstrtok(nullptr, 0, seps, &nextToken); validData = validData && (azstricmp(token, "nodata_value") == 0); token = azstrtok(nullptr, 0, seps, &nextToken); - nodataValue = atof(token); + nodataValue = static_cast(atof(token)); if (!validData) { @@ -157,7 +157,7 @@ bool CImageASC::Load(const QString& fileName, CFloatImage& image) if (token != nullptr) { // Negative heights aren't supported, clamp to 0. - pixelValue = max(0.0, atof(token)); + pixelValue = max(0.0f, static_cast(atof(token))); // If this is a location we specifically don't have data for, set it to 0. if (pixelValue == nodataValue) diff --git a/Code/Editor/Util/ImageGif.cpp b/Code/Editor/Util/ImageGif.cpp index 2c07fc9acb..a9ab4efdaf 100644 --- a/Code/Editor/Util/ImageGif.cpp +++ b/Code/Editor/Util/ImageGif.cpp @@ -185,7 +185,7 @@ bool CImageGif::Load(const QString& fileName, CImageEx& outImage) CLogFile::FormatLine("File not found %s", fileName.toUtf8().data()); return false; } - long filesize = file.GetLength(); + long filesize = static_cast(file.GetLength()); data.resize(filesize); uint8* ptr = &data[0]; @@ -411,7 +411,7 @@ bool CImageGif::Load(const QString& fileName, CImageEx& outImage) FreeCode = FirstFree; CurCode = OldCode = Code = ReadCode(); FinChar = CurCode & BitMask; - AddToPixel (FinChar); + AddToPixel(static_cast(FinChar)); } else { @@ -455,7 +455,7 @@ bool CImageGif::Load(const QString& fileName, CImageEx& outImage) for (i = OutCount - 1; i >= 0; i--) { - AddToPixel (OutCode[i]); + AddToPixel(static_cast(OutCode[i])); } OutCount = 0; diff --git a/Code/Editor/Util/ImageHistogram.cpp b/Code/Editor/Util/ImageHistogram.cpp index 15f6bc2e47..acea2dc340 100644 --- a/Code/Editor/Util/ImageHistogram.cpp +++ b/Code/Editor/Util/ImageHistogram.cpp @@ -220,5 +220,5 @@ void CImageHistogram::ComputeStatisticsForChannel(int aIndex) } } - m_median[aIndex] = median; + m_median[aIndex] = static_cast(median); } diff --git a/Code/Editor/Util/ImageTIF.cpp b/Code/Editor/Util/ImageTIF.cpp index 25e4296154..7929d63030 100644 --- a/Code/Editor/Util/ImageTIF.cpp +++ b/Code/Editor/Util/ImageTIF.cpp @@ -60,7 +60,7 @@ libtiffDummyReadProc (thandle_t fd, tdata_t buf, tsize_t size) memcpy(buf, &memImage->buffer[memImage->offset], size); - memImage->offset += size; + memImage->offset += static_cast(size); // Return the amount of data read return size; @@ -79,19 +79,19 @@ libtiffDummySeekProc (thandle_t fd, toff_t off, int i) switch (i) { case SEEK_SET: - memImage->offset = off; + memImage->offset = static_cast(off); break; case SEEK_CUR: - memImage->offset += off; + memImage->offset += static_cast(off); break; case SEEK_END: - memImage->offset = memImage->size - off; + memImage->offset = static_cast(memImage->size - off); break; default: - memImage->offset = off; + memImage->offset = static_cast(off); break; } @@ -119,7 +119,7 @@ bool CImageTIF::Load(const QString& fileName, CImageEx& outImage) std::vector data; - memImage.size = file.GetLength(); + memImage.size = static_cast(file.GetLength()); data.resize(memImage.size); memImage.buffer = &data[0]; @@ -210,7 +210,7 @@ bool CImageTIF::Load(const QString& fileName, CFloatImage& outImage) std::vector data; - memImage.size = file.GetLength(); + memImage.size = static_cast(file.GetLength()); data.resize(memImage.size); memImage.buffer = &data[0]; @@ -262,7 +262,7 @@ bool CImageTIF::Load(const QString& fileName, CFloatImage& outImage) } } - uint32 linesize = TIFFScanlineSize(tif); + uint32 linesize = static_cast(TIFFScanlineSize(tif)); uint8* linebuf = static_cast(_TIFFmalloc(linesize)); // We assume that a scanline has all of the samples in it. Validate the assumption. @@ -460,7 +460,7 @@ const char* CImageTIF::GetPreset(const QString& fileName) MemImage memImage; - memImage.size = file.GetLength(); + memImage.size = static_cast(file.GetLength()); data.resize(memImage.size); memImage.buffer = &data[0]; diff --git a/Code/Editor/Util/ImageUtil.cpp b/Code/Editor/Util/ImageUtil.cpp index 5753e0a138..00e33162cf 100644 --- a/Code/Editor/Util/ImageUtil.cpp +++ b/Code/Editor/Util/ImageUtil.cpp @@ -106,9 +106,9 @@ bool CImageUtil::SavePGM(const QString& fileName, const CImageEx& image) fprintf(file, fileHeader.c_str()); // Then print all the pixels. - for (int32 y = 0; y < height; y++) + for (uint32 y = 0; y < height; y++) { - for (int32 x = 0; x < width; x++) + for (uint32 x = 0; x < width; x++) { fprintf(file, "%d ", pixels[x + (y * width)]); } @@ -478,7 +478,7 @@ unsigned char CImageUtil::GetBilinearFilteredAt(const int iniX256, const int ini DWORD x = (DWORD)(iniX256) >> 8; DWORD y = (DWORD)(iniY256) >> 8; - if (x >= image.GetWidth() - 1 || y >= image.GetHeight() - 1) + if (x >= static_cast(image.GetWidth() - 1) || y >= static_cast(image.GetHeight() - 1)) { return image.ValueAt(x, y); // border is not filtered, 255 to get in range 0..1 } diff --git a/Code/Editor/Util/KDTree.cpp b/Code/Editor/Util/KDTree.cpp index 4547149e9b..af06a58c9f 100644 --- a/Code/Editor/Util/KDTree.cpp +++ b/Code/Editor/Util/KDTree.cpp @@ -190,7 +190,7 @@ bool SearchForBestSplitPos(CKDTree::ESplitAxis axis, const std::vector(indices.size()); for (int i = 0; i < nSizeOfIndices; ++i) { @@ -329,7 +329,7 @@ bool CKDTree::Build(IStatObj* pStatObj) entireBoundBox.Reset(); std::vector indices; - for (int i = 0, iStatObjSize(m_StatObjectList.size()); i < iStatObjSize; ++i) + for (int i = 0, iStatObjSize = static_cast(m_StatObjectList.size()); i < iStatObjSize; ++i) { IIndexedMesh* pMesh = m_StatObjectList[i].pStatObj->GetIndexedMesh(true); if (pMesh == nullptr) @@ -467,7 +467,7 @@ bool CKDTree::FindNearestVertexRecursively(KDTreeNode* pNode, const Vec3& raySrc uint32 nVertexIndex = pNode->GetVertexIndex(i); uint32 nObjIndex = pNode->GetObjIndex(i); - assert(nObjIndex < m_StatObjectList.size() && nObjIndex >= 0); + assert(nObjIndex < m_StatObjectList.size()); const SStatObj* pStatObjInfo = &(m_StatObjectList[nObjIndex]); diff --git a/Code/Editor/Util/MemoryBlock.cpp b/Code/Editor/Util/MemoryBlock.cpp index 03d432762d..e840a1735e 100644 --- a/Code/Editor/Util/MemoryBlock.cpp +++ b/Code/Editor/Util/MemoryBlock.cpp @@ -175,7 +175,7 @@ void CMemoryBlock::Uncompress(CMemoryBlock& toBlock) const #endif uncompress((unsigned char*)toBlock.GetBuffer(), &destSize, (unsigned char*)GetBuffer(), GetSize()); assert(result == Z_OK); - assert(destSize == m_uncompressedSize); + assert(destSize == static_cast(m_uncompressedSize)); } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/Util/NamedData.cpp b/Code/Editor/Util/NamedData.cpp index 240d71f58d..67e69a0392 100644 --- a/Code/Editor/Util/NamedData.cpp +++ b/Code/Editor/Util/NamedData.cpp @@ -158,7 +158,7 @@ bool CNamedData::Serialize(CArchive& ar) { if (ar.IsStoring()) { - int iSize = m_blocks.size(); + int iSize = static_cast(m_blocks.size()); ar << iSize; for (TBlocks::iterator it = m_blocks.begin(); it != m_blocks.end(); it++) @@ -286,7 +286,7 @@ bool CNamedData::Load(const QString& levelPath, [[maybe_unused]] CPakFile& pakFi CCryFile cfile; if (cfile.Open(Path::Make(levelPath, filename).toUtf8().data(), "rb")) { - int fileSize = cfile.GetLength(); + int fileSize = static_cast(cfile.GetLength()); if (fileSize > 0) { QString key = Path::GetFileName(filename); @@ -307,7 +307,7 @@ bool CNamedData::Load(const QString& levelPath, [[maybe_unused]] CPakFile& pakFi CCryFile cfile; if (cfile.Open(Path::Make(levelPath, filename).toUtf8().data(), "rb")) { - int fileSize = cfile.GetLength(); + int fileSize = static_cast(cfile.GetLength()); if (fileSize > 0) { // Read uncompressed data size. diff --git a/Code/Editor/Util/PakFile.cpp b/Code/Editor/Util/PakFile.cpp index 88d5598495..fc8431ef24 100644 --- a/Code/Editor/Util/PakFile.cpp +++ b/Code/Editor/Util/PakFile.cpp @@ -106,7 +106,7 @@ bool CPakFile::UpdateFile(const char* filename, CCryMemFile& file, bool bCompres { if (m_pArchive) { - int nSize = file.GetLength(); + int nSize = static_cast(file.GetLength()); UpdateFile(filename, file.GetMemPtr(), nSize, bCompress); file.Close(); diff --git a/Code/Editor/Util/Util.h b/Code/Editor/Util/Util.h index b0ec0db818..61bb0eed09 100644 --- a/Code/Editor/Util/Util.h +++ b/Code/Editor/Util/Util.h @@ -137,8 +137,6 @@ namespace Util { x = x - 1; -#pragma warning(push) -#pragma warning(disable : 4293) if (sizeof(TInteger) > 0) { x |= x >> 1; @@ -163,7 +161,6 @@ namespace Util { x |= x >> 32; } -#pragma warning(pop) return x + 1; } diff --git a/Code/Editor/Util/Variable.cpp b/Code/Editor/Util/Variable.cpp index 97c2a1e8af..3d7c35ac1c 100644 --- a/Code/Editor/Util/Variable.cpp +++ b/Code/Editor/Util/Variable.cpp @@ -511,7 +511,7 @@ CVarGlobalEnumList::CVarGlobalEnumList(const QString& enumName) //! Get the name of specified value in enumeration. QString CVarGlobalEnumList::GetItemName(uint index) { - if (!m_pEnum || index >= m_pEnum->strings.size()) + if (!m_pEnum || index >= static_cast(m_pEnum->strings.size())) { return QString(); } diff --git a/Code/Editor/Util/Variable.h b/Code/Editor/Util/Variable.h index da506b9db0..9c3f96a3f6 100644 --- a/Code/Editor/Util/Variable.h +++ b/Code/Editor/Util/Variable.h @@ -405,7 +405,7 @@ public: unsigned char GetDataType() const { return m_dataType; }; void SetDataType(unsigned char dataType) { m_dataType = dataType; } - void SetFlags(int flags) { m_flags = flags; } + void SetFlags(int flags) { m_flags = static_cast(flags); } int GetFlags() const { return m_flags; } void SetFlagRecursive(EFlags flag) { m_flags |= flag; } diff --git a/Code/Editor/Util/VariablePropertyType.cpp b/Code/Editor/Util/VariablePropertyType.cpp index 17c80a505c..3f472dde72 100644 --- a/Code/Editor/Util/VariablePropertyType.cpp +++ b/Code/Editor/Util/VariablePropertyType.cpp @@ -171,7 +171,7 @@ namespace Prop { // Limit step size to 1000. int nPrec = max(3 - int(log(m_rangeMax - m_rangeMin) / log(10.f)), 0); - m_step = max(m_step, powf(10.f, -nPrec)); + m_step = max(m_step, powf(10.f, static_cast(-nPrec))); } } diff --git a/Code/Editor/Util/XmlArchive.cpp b/Code/Editor/Util/XmlArchive.cpp index ca399632d4..e6bc93fdf4 100644 --- a/Code/Editor/Util/XmlArchive.cpp +++ b/Code/Editor/Util/XmlArchive.cpp @@ -120,7 +120,7 @@ bool CXmlArchive::SaveToPak([[maybe_unused]] const QString& levelPath, CPakFile& // Save xml file. QString xmlFilename = "Level.editor_xml"; - pakFile.UpdateFile(xmlFilename.toUtf8().data(), (void*)pXmlStrData->GetString(), pXmlStrData->GetStringLength()); + pakFile.UpdateFile(xmlFilename.toUtf8().data(), (void*)pXmlStrData->GetString(), static_cast(pXmlStrData->GetStringLength())); if (pakFile.GetArchive()) { diff --git a/Code/Editor/Util/bitarray.h b/Code/Editor/Util/bitarray.h index f55d195fd1..5a887b02d5 100644 --- a/Code/Editor/Util/bitarray.h +++ b/Code/Editor/Util/bitarray.h @@ -220,7 +220,7 @@ public: b.resize((compsize + 1) << 3); out = (char*)b.m_bits; in = (char*)m_bits; - *out++ = bsize; + *out++ = static_cast(bsize); for (i = 0; i < bsize; i++) { *out++ = in[i]; @@ -239,7 +239,7 @@ public: } } i--; - *out++ = countz; + *out++ = static_cast(countz); } } } diff --git a/Code/Editor/ViewPane.cpp b/Code/Editor/ViewPane.cpp index 466274c06e..421db8394e 100644 --- a/Code/Editor/ViewPane.cpp +++ b/Code/Editor/ViewPane.cpp @@ -646,7 +646,7 @@ namespace if (viewPane && viewPane->GetViewport()) { const QRect rcViewport = viewPane->GetViewport()->rect(); - return AZ::Vector2(rcViewport.width(), rcViewport.height()); + return AZ::Vector2(static_cast(rcViewport.width()), static_cast(rcViewport.height())); } else { @@ -769,7 +769,9 @@ namespace void PySetViewPaneLayout(unsigned int layoutId) { + AZ_PUSH_DISABLE_WARNING(4296, "-Wunknown-warning-option") if ((layoutId >= ET_Layout0) && (layoutId <= ET_Layout8)) + AZ_POP_DISABLE_WARNING { CLayoutWnd* layout = GetIEditor()->GetViewManager()->GetLayout(); if (layout) diff --git a/Code/Editor/Viewport.cpp b/Code/Editor/Viewport.cpp index 873f555c80..3c34f464b8 100644 --- a/Code/Editor/Viewport.cpp +++ b/Code/Editor/Viewport.cpp @@ -419,7 +419,7 @@ void QtViewport::Update() ////////////////////////////////////////////////////////////////////////// QPoint QtViewport::WorldToView(const Vec3& wp) const { - return QPoint(wp.x, wp.y); + return QPoint(static_cast(wp.x), static_cast(wp.y)); } ////////////////////////////////////////////////////////////////////////// @@ -427,8 +427,8 @@ Vec3 QtViewport::WorldToView3D(const Vec3& wp, [[maybe_unused]] int nFlags) cons { QPoint p = WorldToView(wp); Vec3 out; - out.x = p.x(); - out.y = p.y(); + out.x = static_cast(p.x()); + out.y = static_cast(p.y()); out.z = wp.z; return out; } @@ -437,8 +437,8 @@ Vec3 QtViewport::WorldToView3D(const Vec3& wp, [[maybe_unused]] int nFlags) cons Vec3 QtViewport::ViewToWorld(const QPoint& vp, bool* pCollideWithTerrain, [[maybe_unused]] bool onlyTerrain, [[maybe_unused]] bool bSkipVegetation, [[maybe_unused]] bool bTestRenderMesh, [[maybe_unused]] bool* collideWithObject) const { Vec3 wp; - wp.x = vp.x(); - wp.y = vp.y(); + wp.x = static_cast(vp.x()); + wp.y = static_cast(vp.y()); wp.z = 0; if (pCollideWithTerrain) { @@ -520,7 +520,7 @@ void QtViewport::mouseMoveEvent(QMouseEvent* event) void QtViewport::wheelEvent(QWheelEvent* event) { - OnMouseWheel(event->modifiers(), event->angleDelta().y(), event->position().toPoint()); + OnMouseWheel(event->modifiers(), static_cast(event->angleDelta().y()), event->position().toPoint()); event->accept(); } @@ -969,7 +969,7 @@ void QtViewport::MakeConstructionPlane(int axis) ////////////////////////////////////////////////////////////////////////// Vec3 QtViewport::MapViewToCP(const QPoint& point, int axis) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (axis == AXIS_TERRAIN) { @@ -1276,9 +1276,9 @@ float QtViewport::GetDistanceToLine(const Vec3& lineP1, const Vec3& lineP2, cons QPoint p2 = WorldToView(lineP2); return PointToLineDistance2D( - Vec3(p1.x(), p1.y(), 0), - Vec3(p2.x(), p2.y(), 0), - Vec3(point.x(), point.y(), 0)); + Vec3(static_cast(p1.x()), static_cast(p1.y()), 0.0f), + Vec3(static_cast(p2.x()), static_cast(p2.y()), 0.0f), + Vec3(static_cast(point.x()), static_cast(point.y()), 0.0f)); } ////////////////////////////////////////////////////////////////////////// @@ -1336,7 +1336,7 @@ bool QtViewport::GetAdvancedSelectModeFlag() ////////////////////////////////////////////////////////////////////////// bool QtViewport::MouseCallback(EMouseEvent event, const QPoint& point, Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); // Ignore any mouse events in game mode. if (GetIEditor()->IsInGameMode()) diff --git a/Code/Editor/ViewportManipulatorController.cpp b/Code/Editor/ViewportManipulatorController.cpp index 5282af009f..a67d733cf9 100644 --- a/Code/Editor/ViewportManipulatorController.cpp +++ b/Code/Editor/ViewportManipulatorController.cpp @@ -113,8 +113,8 @@ namespace SandboxEditor windowSize, event.m_windowHandle, &AzFramework::WindowRequestBus::Events::GetClientAreaSize); auto screenPoint = AzFramework::ScreenPoint( - position->m_normalizedPosition.GetX() * windowSize.m_width, - position->m_normalizedPosition.GetY() * windowSize.m_height); + static_cast(position->m_normalizedPosition.GetX() * windowSize.m_width), + static_cast(position->m_normalizedPosition.GetY() * windowSize.m_height)); m_mouseInteraction.m_mousePick.m_screenCoordinates = screenPoint; AZStd::optional ray; diff --git a/Code/Editor/ViewportTitleDlg.cpp b/Code/Editor/ViewportTitleDlg.cpp index eacf01a6fe..a6dee5382e 100644 --- a/Code/Editor/ViewportTitleDlg.cpp +++ b/Code/Editor/ViewportTitleDlg.cpp @@ -311,7 +311,7 @@ void CViewportTitleDlg::OnInitDialog() AZ::VR::VREventBus::Handler::BusConnect(); QFontMetrics metrics({}); - int width = metrics.boundingRect("-9999.99").width() * m_fieldWidthMultiplier; + int width = static_cast(metrics.boundingRect("-9999.99").width() * m_fieldWidthMultiplier); m_cameraSpeed->setFixedWidth(width); @@ -462,7 +462,7 @@ void CViewportTitleDlg::AddFOVMenus(QMenu* menu, std::function call float fov = gSettings.viewports.fDefaultFov; bool ok; - float f = customPreset.toDouble(&ok); + float f = customPreset.toFloat(&ok); if (ok) { fov = std::max(1.0f, f); @@ -482,7 +482,7 @@ void CViewportTitleDlg::OnMenuFOVCustom() if (ok) { - m_pViewPane->SetViewportFOV(fov); + m_pViewPane->SetViewportFOV(static_cast(fov)); // Update the custom presets. const QString text = QString::number(fov); @@ -986,12 +986,12 @@ void CViewportTitleDlg::OnAngleSnappingToggled() void CViewportTitleDlg::OnGridSpinBoxChanged(double value) { - SandboxEditor::SetGridSnappingSize(value); + SandboxEditor::SetGridSnappingSize(static_cast(value)); } void CViewportTitleDlg::OnAngleSpinBoxChanged(double value) { - SandboxEditor::SetAngleSnappingSize(value); + SandboxEditor::SetAngleSnappingSize(static_cast(value)); } void CViewportTitleDlg::UpdateOverFlowMenuState() diff --git a/Code/Editor/WipFeatureManager.cpp b/Code/Editor/WipFeatureManager.cpp index f6fbc7ac93..4fb9ed1d93 100644 --- a/Code/Editor/WipFeatureManager.cpp +++ b/Code/Editor/WipFeatureManager.cpp @@ -189,7 +189,7 @@ bool CWipFeatureManager::Load(const char* pFilename, bool bClearExisting) for (size_t i = 0, iCount = root->getChildCount(); i < iCount; ++i) { SWipFeatureInfo wf; - XmlNodeRef node = root->getChild(i); + XmlNodeRef node = root->getChild(static_cast(i)); XmlString str; node->getAttr("id", wf.m_id); diff --git a/Code/Editor/WipFeaturesDlg.cpp b/Code/Editor/WipFeaturesDlg.cpp index 0d0a179539..bc4372d7fb 100644 --- a/Code/Editor/WipFeaturesDlg.cpp +++ b/Code/Editor/WipFeaturesDlg.cpp @@ -35,7 +35,7 @@ public: int rowCount(const QModelIndex& parent = QModelIndex()) const override { - return parent.isValid() ? 0 : CWipFeatureManager::Instance()->GetFeatures().size(); + return parent.isValid() ? 0 : static_cast(CWipFeatureManager::Instance()->GetFeatures().size()); } int columnCount(const QModelIndex& parent = QModelIndex()) const override diff --git a/Code/Editor/editor_lib_files.cmake b/Code/Editor/editor_lib_files.cmake index c10db3bac5..6c5096a8f5 100644 --- a/Code/Editor/editor_lib_files.cmake +++ b/Code/Editor/editor_lib_files.cmake @@ -503,6 +503,7 @@ set(FILES LogFileImpl.h Objects/ClassDesc.cpp Objects/ClassDesc.h + Objects/DisplayContextShared.inl Objects/IEntityObjectListener.h Objects/SelectionGroup.cpp Objects/SelectionGroup.h diff --git a/Code/Editor/editor_lib_test_files.cmake b/Code/Editor/editor_lib_test_files.cmake index 49f707b1f6..2ae3d22c19 100644 --- a/Code/Editor/editor_lib_test_files.cmake +++ b/Code/Editor/editor_lib_test_files.cmake @@ -21,6 +21,7 @@ set(FILES Lib/Tests/test_ViewportTitleDlgPythonBindings.cpp Lib/Tests/test_DisplaySettingsPythonBindings.cpp Lib/Tests/test_ViewportManipulatorController.cpp + Lib/Tests/test_ModularViewportCameraController.cpp DisplaySettingsPythonFuncs.cpp DisplaySettingsPythonFuncs.h ) diff --git a/Code/Framework/AzCore/AzCore/Android/APKFileHandler.h b/Code/Framework/AzCore/AzCore/Android/APKFileHandler.h index 0d9d3c984d..8df97a0cea 100644 --- a/Code/Framework/AzCore/AzCore/Android/APKFileHandler.h +++ b/Code/Framework/AzCore/AzCore/Android/APKFileHandler.h @@ -26,8 +26,8 @@ #if AZ_ENABLED_VERBOSE_ANDROID_IO_PROFILING #include - #define ANDROID_IO_PROFILE_SECTION AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore) - #define ANDROID_IO_PROFILE_SECTION_ARGS(...) AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, __VA_ARGS__) + #define ANDROID_IO_PROFILE_SECTION AZ_PROFILE_FUNCTION(AzCore) + #define ANDROID_IO_PROFILE_SECTION_ARGS(...) AZ_PROFILE_SCOPE(AzCore, __VA_ARGS__) #else #define ANDROID_IO_PROFILE_SECTION #define ANDROID_IO_PROFILE_SECTION_ARGS(...) diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetDataStream.cpp b/Code/Framework/AzCore/AzCore/Asset/AssetDataStream.cpp index 425c729806..305ec0617b 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetDataStream.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetDataStream.cpp @@ -27,7 +27,7 @@ namespace AZ::Data void AssetDataStream::Open(const AZStd::vector& data) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Assert(!m_isOpen, "Attempting to open the stream when it is already open."); @@ -45,7 +45,7 @@ namespace AZ::Data void AssetDataStream::Open(AZStd::vector&& data) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Assert(!m_isOpen, "Attempting to open the stream when it is already open."); @@ -62,7 +62,7 @@ namespace AZ::Data AZStd::chrono::milliseconds deadline, AZ::IO::IStreamerTypes::Priority priority, OnCompleteCallback loadCallback) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Assert(!m_isOpen, "Attempting to open the stream when it is already open."); AZ_Assert(!m_curReadRequest, "Queueing an asset stream load while one is still in progress."); @@ -80,7 +80,7 @@ namespace AZ::Data // Set up the callback that will process the asset data once the raw file load is finished. auto streamerCallback = [this, loadCallback](AZ::IO::FileRequestHandle fileHandle) { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "AZ::Data::LoadAssetDataStreamCallback %s", + AZ_PROFILE_SCOPE(AzCore, "AZ::Data::LoadAssetDataStreamCallback %s", m_filePath.c_str()); // Get the results @@ -183,13 +183,13 @@ namespace AZ::Data // the real interval we want to record below won't show up unless this is here. /**/ { - AZ_PROFILE_INTERVAL_START(AZ::Debug::ProfileCategory::AzCore, this + 1, "AssetDataStream: %s", streamName); - AZ_PROFILE_INTERVAL_END(AZ::Debug::ProfileCategory::AzCore, this + 1); + AZ_PROFILE_INTERVAL_START(AzCore, this + 1, "AssetDataStream: %s", streamName); + AZ_PROFILE_INTERVAL_END(AzCore, this + 1); } /**/ // Start a timespan marker to track the full load time for the requested asset. - AZ_PROFILE_INTERVAL_START(AZ::Debug::ProfileCategory::AzCore, this, "AssetLoad: %s", streamName); + AZ_PROFILE_INTERVAL_START(AzCore, this, "AssetLoad: %s", streamName); // Lock the allocator to ensure it remains active from Open to Close. m_bufferAllocator->LockAllocator(); @@ -216,7 +216,7 @@ namespace AZ::Data ClearInternalStateData(); // End the load time timespan marker for this asset. - AZ_PROFILE_INTERVAL_END(AZ::Debug::ProfileCategory::AzCore, this); + AZ_PROFILE_INTERVAL_END(AzCore, this); } void AssetDataStream::RequestCancel() @@ -231,7 +231,7 @@ namespace AZ::Data void AssetDataStream::Seek(AZ::IO::OffsetType bytes, AZ::IO::GenericStream::SeekMode mode) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ::IO::OffsetType requestedOffset = 0; switch (mode) @@ -261,7 +261,7 @@ namespace AZ::Data AZ::IO::SizeType AssetDataStream::Read(AZ::IO::SizeType bytes, void* oBuffer) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (m_curOffset >= m_loadedSize) { return 0; diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetManager.cpp b/Code/Framework/AzCore/AzCore/Asset/AssetManager.cpp index 2a71baea46..f31859c14d 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetManager.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetManager.cpp @@ -163,7 +163,7 @@ namespace AZ else { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "AZ::Data::LoadAssetJob::Process: %s", + AZ_PROFILE_SCOPE(AzCore, "AZ::Data::LoadAssetJob::Process: %s", asset.GetHint().c_str()); AZ_ASSET_ATTACH_TO_SCOPE(this); @@ -198,7 +198,7 @@ namespace AZ if(cl_assetLoadDelay > 0) { - AZ_PROFILE_SCOPE_IDLE(AZ::Debug::ProfileCategory::AzCore, "LoadData suspended"); + AZ_PROFILE_SCOPE(AzCore, "LoadData suspended"); AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(cl_assetLoadDelay)); } @@ -314,7 +314,7 @@ namespace AZ protected: void Wait() { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "WaitForAsset - %s", m_assetData.GetHint().c_str()); + AZ_PROFILE_SCOPE(AzCore, "WaitForAsset - %s", m_assetData.GetHint().c_str()); // Continue to loop until the load completes. (Most of the time in the loop will be spent in a thread-blocking state) while (!m_loadCompleted) @@ -344,7 +344,7 @@ namespace AZ void Finish() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); m_loadCompleted = true; m_waitEvent.release(); } @@ -403,7 +403,7 @@ namespace AZ void SaveAsset() { auto asset = m_asset.GetStrongReference(); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); bool isSaved = false; AssetStreamInfo saveInfo = m_owner->GetSaveStreamInfoForAsset(asset.GetId(), asset.GetType()); if (saveInfo.IsValid()) @@ -565,7 +565,7 @@ namespace AZ //========================================================================= void AssetManager::DispatchEvents() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AssetManagerNotificationBus::Broadcast(&AssetManagerNotificationBus::Events::OnAssetEventsDispatchBegin); AssetBus::ExecuteQueuedEvents(); AssetManagerNotificationBus::Broadcast(&AssetManagerNotificationBus::Events::OnAssetEventsDispatchEnd); @@ -937,14 +937,14 @@ namespace AZ Asset AssetManager::GetAssetInternal(const AssetId& assetId, [[maybe_unused]] const AssetType& assetType, AssetLoadBehavior assetReferenceLoadBehavior, const AssetLoadParameters& loadParams, AssetInfo assetInfo /*= () */, bool signalLoaded /*= false */) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Error("AssetDatabase", assetId.IsValid(), "GetAsset called with invalid asset Id."); AZ_Error("AssetDatabase", !assetType.IsNull(), "GetAsset called with invalid asset type."); bool assetMissing = false; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "GetAsset: GetAssetInfo"); + AZ_PROFILE_SCOPE(AzCore, "GetAsset: GetAssetInfo"); // Attempt to look up asset info from catalog // This is so that when assetId is a legacy id, we're operating on the canonical id anyway @@ -974,7 +974,7 @@ namespace AZ } } - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "GetAsset: %s", assetInfo.m_relativePath.c_str()); + AZ_PROFILE_SCOPE(AzCore, "GetAsset: %s", assetInfo.m_relativePath.c_str()); AZ_ASSET_NAMED_SCOPE("GetAsset: %s", assetInfo.m_relativePath.c_str()); AZStd::shared_ptr dataStream; @@ -992,7 +992,7 @@ namespace AZ // check if asset already exists { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "GetAsset: FindAsset"); + AZ_PROFILE_SCOPE(AzCore, "GetAsset: FindAsset"); AssetMap::iterator it = m_assets.find(assetInfo.m_assetId); if (it != m_assets.end()) @@ -1007,7 +1007,7 @@ namespace AZ } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "GetAsset: FindAssetHandler"); + AZ_PROFILE_SCOPE(AzCore, "GetAsset: FindAssetHandler"); // find the asset type handler AssetHandlerMap::iterator handlerIt = m_handlers.find(assetInfo.m_assetType); @@ -1019,7 +1019,7 @@ namespace AZ handler = handlerIt->second; if (isNewEntry) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "GetAsset: CreateAsset"); + AZ_PROFILE_SCOPE(AzCore, "GetAsset: CreateAsset"); assetData = handler->CreateAsset(assetInfo.m_assetId, assetInfo.m_assetType); if (assetData) @@ -1043,7 +1043,7 @@ namespace AZ { if (isNewEntry && assetData->IsRegisterReadonlyAndShareable()) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "GetAsset: RegisterAsset"); + AZ_PROFILE_SCOPE(AzCore, "GetAsset: RegisterAsset"); m_assets.insert(AZStd::make_pair(assetInfo.m_assetId, assetData)); } if (assetData->GetStatus() == AssetData::AssetStatus::NotLoaded) @@ -1596,7 +1596,7 @@ namespace AZ const AZ::Data::AssetStreamInfo& streamInfo, bool isReload, AssetHandler* handler, const AssetLoadParameters& loadParams, bool signalLoaded) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // Set up the callback that will process the asset data once the raw file load is finished. // The callback is declared as mutable so that we can clear weakAsset within the callback. The refcount in weakAsset @@ -1613,7 +1613,7 @@ namespace AZ if (loadingAsset) { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "AZ::Data::LoadAssetStreamerCallback %s", + AZ_PROFILE_SCOPE(AzCore, "AZ::Data::LoadAssetStreamerCallback %s", loadingAsset.GetHint().c_str()); { AZStd::scoped_lock assetLock(m_assetMutex); @@ -1788,7 +1788,7 @@ namespace AZ //========================================================================= void AssetManager::RegisterAssetLoading(const Asset& asset) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AssetData* data = asset.Get(); if (data) @@ -1803,7 +1803,7 @@ namespace AZ //========================================================================= void AssetManager::UnregisterAssetLoading([[maybe_unused]] const Asset& asset) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); } //========================================================================= @@ -2050,7 +2050,7 @@ namespace AZ AZStd::shared_ptr stream, const AssetFilterCB& assetLoadFilterCB) { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "AssetHandler::LoadAssetData - %s", asset.GetHint().c_str()); + AZ_PROFILE_SCOPE(AzCore, "AssetHandler::LoadAssetData - %s", asset.GetHint().c_str()); #ifdef AZ_ENABLE_TRACING auto start = AZStd::chrono::system_clock::now(); @@ -2119,7 +2119,7 @@ namespace AZ void AssetManager::PostLoad(AZ::Data::Asset& asset, bool loadSucceeded, bool isReload, AZ::Data::AssetHandler* assetHandler) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!assetHandler) { assetHandler = GetHandler(asset.GetType()); diff --git a/Code/Framework/AzCore/AzCore/AzCoreModule.cpp b/Code/Framework/AzCore/AzCore/AzCoreModule.cpp index 6afcb6a334..d2b1b141a9 100644 --- a/Code/Framework/AzCore/AzCore/AzCoreModule.cpp +++ b/Code/Framework/AzCore/AzCore/AzCoreModule.cpp @@ -19,7 +19,6 @@ #include #include #include -#include #include #include #include @@ -45,9 +44,6 @@ namespace AZ LoggerSystemComponent::CreateDescriptor(), EventSchedulerSystemComponent::CreateDescriptor(), -#if !defined(_RELEASE) - Statistics::StatisticalProfilerProxySystemComponent::CreateDescriptor(), -#endif // #if !defined(_RELEASE) #if !defined(AZCORE_EXCLUDE_LUA) ScriptSystemComponent::CreateDescriptor(), #endif // #if !defined(AZCORE_EXCLUDE_LUA) @@ -61,10 +57,6 @@ namespace AZ azrtti_typeid(), azrtti_typeid(), azrtti_typeid(), - -#if !defined(_RELEASE) - azrtti_typeid(), -#endif // #if !defined(_RELEASE) }; } } diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index 7b1060a10f..5114ea19ec 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -1394,8 +1394,7 @@ namespace AZ void ComponentApplication::Tick(float deltaOverride /*= -1.f*/) { { - AZ_PROFILE_TIMER("System", "Component application simulation tick function"); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_SCOPE(System, "Component application simulation tick"); AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now(); @@ -1408,12 +1407,12 @@ namespace AZ } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "ComponentApplication::Tick:ExecuteQueuedEvents"); + AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:ExecuteQueuedEvents"); TickBus::ExecuteQueuedEvents(); } m_currentTime = now; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "ComponentApplication::Tick:OnTick"); + AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:OnTick"); EBUS_EVENT(TickBus, OnTick, m_deltaTime, ScriptTimePoint(now)); } } @@ -1428,8 +1427,7 @@ namespace AZ //========================================================================= void ComponentApplication::TickSystem() { - AZ_PROFILE_TIMER("System", "Component application system tick function"); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_SCOPE(System, "Component application tick"); SystemTickBus::ExecuteQueuedEvents(); EBUS_EVENT(SystemTickBus, OnSystemTick); diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h index 278e911455..d2da86c368 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include diff --git a/Code/Framework/AzCore/AzCore/Component/Entity.cpp b/Code/Framework/AzCore/AzCore/Component/Entity.cpp index 09b5526b6c..00c1895261 100644 --- a/Code/Framework/AzCore/AzCore/Component/Entity.cpp +++ b/Code/Framework/AzCore/AzCore/Component/Entity.cpp @@ -189,7 +189,7 @@ namespace AZ void Entity::Activate() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Assert(m_state == State::Init, "Entity should be in Init state to be Activated!"); @@ -226,7 +226,7 @@ namespace AZ void Entity::Deactivate() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ::ComponentApplicationRequests* componentApplication = AZ::Interface::Get(); if (componentApplication != nullptr) @@ -1034,7 +1034,7 @@ namespace AZ Entity::DependencySortOutcome Entity::DependencySort(ComponentArrayType& inOutComponents) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); using DependencySortInternal::ComponentInfo; using DependencySortInternal::InvalidEntry; diff --git a/Code/Framework/AzCore/AzCore/Component/EntityUtils.cpp b/Code/Framework/AzCore/AzCore/Component/EntityUtils.cpp index 9bb41bfd58..8241400aac 100644 --- a/Code/Framework/AzCore/AzCore/Component/EntityUtils.cpp +++ b/Code/Framework/AzCore/AzCore/Component/EntityUtils.cpp @@ -40,7 +40,7 @@ namespace AZ //========================================================================= void EnumerateEntityIds(const void* classPtr, const Uuid& classUuid, const EntityIdVisitor& visitor, SerializeContext* context) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!context) { diff --git a/Code/Framework/AzCore/AzCore/Component/EntityUtils.h b/Code/Framework/AzCore/AzCore/Component/EntityUtils.h index a5d0e4e53f..ce258bc637 100644 --- a/Code/Framework/AzCore/AzCore/Component/EntityUtils.h +++ b/Code/Framework/AzCore/AzCore/Component/EntityUtils.h @@ -54,7 +54,7 @@ namespace AZ template unsigned int ReplaceEntityRefs(T* classPtr, const EntityIdMapper& mapper, SerializeContext* context = nullptr) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); auto idMapper = [&mapper](const EntityId& originalId, bool isEntityId, const IdUtils::Remapper::IdGenerator&) -> EntityId { return mapper(originalId, isEntityId); @@ -83,7 +83,7 @@ namespace AZ template unsigned int ReplaceEntityIds(T* classPtr, const EntityIdMapper& mapper, SerializeContext* context = nullptr) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); auto idMapper = [&mapper](const EntityId& originalId, bool isEntityId, const IdUtils::Remapper::IdGenerator&) -> EntityId { return mapper(originalId, isEntityId); @@ -97,7 +97,7 @@ namespace AZ template unsigned int ReplaceEntityIdsAndEntityRefs(T* classPtr, const EntityIdMapper& mapper, SerializeContext* context = nullptr) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); auto idMapper = [&mapper](const EntityId& originalId, bool isEntityId, const IdUtils::Remapper::IdGenerator&) -> EntityId { return mapper(originalId, isEntityId); diff --git a/Code/Framework/AzCore/AzCore/Console/Console.cpp b/Code/Framework/AzCore/AzCore/Console/Console.cpp index 8bb50f77e0..a1b8a1759d 100644 --- a/Code/Framework/AzCore/AzCore/Console/Console.cpp +++ b/Code/Framework/AzCore/AzCore/Console/Console.cpp @@ -174,15 +174,31 @@ namespace AZ } } - bool Console::HasCommand(const char* command) + bool Console::ExecuteDeferredConsoleCommands() + { + auto DeferredCommandCallable = [this](const DeferredCommand& deferredCommand) + { + return this->DispatchCommand(deferredCommand.m_command, deferredCommand.m_arguments, deferredCommand.m_silentMode, + deferredCommand.m_invokedFrom, deferredCommand.m_requiredSet, deferredCommand.m_requiredClear); + }; + // Attempt to invoke the deferred command and remove it from the queue if successful + return AZStd::erase_if(m_deferredCommands, DeferredCommandCallable) != 0; + } + + void Console::ClearDeferredConsoleCommands() + { + m_deferredCommands = {}; + } + + bool Console::HasCommand(AZStd::string_view command) { return FindCommand(command) != nullptr; } - ConsoleFunctorBase* Console::FindCommand(const char* command) + ConsoleFunctorBase* Console::FindCommand(AZStd::string_view command) { CVarFixedString lowerName(command); - AZStd::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), [](char value) { return std::tolower(value); }); + AZStd::to_lower(lowerName.begin(), lowerName.end()); CommandMap::iterator iter = m_commands.find(lowerName); if (iter != m_commands.end()) @@ -200,11 +216,9 @@ namespace AZ return nullptr; } - AZStd::string Console::AutoCompleteCommand(const char* command, AZStd::vector* matches) + AZStd::string Console::AutoCompleteCommand(AZStd::string_view command, AZStd::vector* matches) { - const size_t commandLength = strlen(command); - - if (commandLength <= 0) + if (command.empty()) { return command; } @@ -219,7 +233,7 @@ namespace AZ continue; } - if (StringFunc::Equal(curr->m_name, command, false, commandLength)) + if (StringFunc::StartsWith(curr->m_name, command, false)) { AZLOG_INFO("- %s : %s\n", curr->m_name, curr->m_desc); commandSubset.push_back(curr->m_name); @@ -270,7 +284,7 @@ namespace AZ } CVarFixedString lowerName = functor->GetName(); - AZStd::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), [](char value) { return std::tolower(value); }); + AZStd::to_lower(lowerName.begin(), lowerName.end()); CommandMap::iterator iter = m_commands.find(lowerName); if (iter != m_commands.end()) { @@ -313,7 +327,7 @@ namespace AZ } CVarFixedString lowerName = functor->GetName(); - AZStd::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), [](char value) { return std::tolower(value); }); + AZStd::to_lower(lowerName.begin(), lowerName.end()); CommandMap::iterator iter = m_commands.find(lowerName); if (iter != m_commands.end()) { @@ -389,7 +403,7 @@ namespace AZ ConsoleFunctorFlags flags = ConsoleFunctorFlags::Null; CVarFixedString lowerName(command); - AZStd::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), [](char value) { return std::tolower(value); }); + AZStd::to_lower(lowerName.begin(), lowerName.end()); CommandMap::iterator iter = m_commands.find(lowerName); if (iter != m_commands.end()) @@ -498,7 +512,8 @@ namespace AZ AZ::IO::PathView consoleRootCommandKey{ IConsole::ConsoleRootCommandKey, AZ::IO::PosixPathSeparator }; AZ::IO::PathView inputKey{ path, AZ::IO::PosixPathSeparator }; - if (inputKey.IsRelativeTo(consoleRootCommandKey)) + // The ConsoleRootComamndKey is not a command itself so strictly children keys are being examined + if (inputKey.IsRelativeTo(consoleRootCommandKey) && inputKey != consoleRootCommandKey) { FixedValueString command = inputKey.LexicallyRelative(consoleRootCommandKey).Native(); ConsoleCommandContainer commandArgs; @@ -560,7 +575,24 @@ namespace AZ commandTrace += commandArg; } - m_console.PerformCommand(command, commandArgs, ConsoleSilentMode::NotSilent, ConsoleInvokedFrom::AzConsole, ConsoleFunctorFlags::Null, ConsoleFunctorFlags::Null); + if (!m_console.PerformCommand(command, commandArgs, ConsoleSilentMode::NotSilent, + ConsoleInvokedFrom::AzConsole, ConsoleFunctorFlags::Null, ConsoleFunctorFlags::Null)) + { + // If the command could not be dispatched at this time add it to the + // deferred commands queue + using DeferredCommand = Console::DeferredCommand; + DeferredCommand deferredCommand + { + AZStd::string_view{command}, + DeferredCommand::DeferredArguments{commandArgs.begin(), commandArgs.end()}, + ConsoleSilentMode::NotSilent, + ConsoleInvokedFrom::AzConsole, + ConsoleFunctorFlags::Null, + ConsoleFunctorFlags::Null + }; + + m_console.m_deferredCommands.emplace_back(AZStd::move(deferredCommand)); + } } } diff --git a/Code/Framework/AzCore/AzCore/Console/Console.h b/Code/Framework/AzCore/AzCore/Console/Console.h index dbcf2b116f..0edda9f531 100644 --- a/Code/Framework/AzCore/AzCore/Console/Console.h +++ b/Code/Framework/AzCore/AzCore/Console/Console.h @@ -60,9 +60,13 @@ namespace AZ ) override; void ExecuteConfigFile(AZStd::string_view configFileName) override; void ExecuteCommandLine(const AZ::CommandLine& commandLine) override; - bool HasCommand(const char* command) override; - ConsoleFunctorBase* FindCommand(const char* command) override; - AZStd::string AutoCompleteCommand(const char* command, AZStd::vector* matches = nullptr) override; + bool ExecuteDeferredConsoleCommands() override; + + void ClearDeferredConsoleCommands() override; + + bool HasCommand(AZStd::string_view command) override; + ConsoleFunctorBase* FindCommand(AZStd::string_view command) override; + AZStd::string AutoCompleteCommand(AZStd::string_view command, AZStd::vector* matches = nullptr) override; void VisitRegisteredFunctors(const FunctorVisitor& visitor) override; void RegisterFunctor(ConsoleFunctorBase* functor) override; void UnregisterFunctor(ConsoleFunctorBase* functor) override; @@ -98,7 +102,20 @@ namespace AZ using CommandMap = AZStd::unordered_map>; CommandMap m_commands; AZ::SettingsRegistryInterface::NotifyEventHandler m_consoleCommandKeyHandler; + struct DeferredCommand + { + using DeferredArguments = AZStd::vector; + AZStd::string m_command; + DeferredArguments m_arguments; + ConsoleSilentMode m_silentMode; + ConsoleInvokedFrom m_invokedFrom; + ConsoleFunctorFlags m_requiredSet; + ConsoleFunctorFlags m_requiredClear; + }; + using DeferredCommandQueue = AZStd::deque; + DeferredCommandQueue m_deferredCommands; + friend struct ConsoleCommandKeyNotificationHandler; friend class ConsoleFunctorBase; }; } diff --git a/Code/Framework/AzCore/AzCore/Console/IConsole.h b/Code/Framework/AzCore/AzCore/Console/IConsole.h index ee2b2bd0fb..dafc284ce3 100644 --- a/Code/Framework/AzCore/AzCore/Console/IConsole.h +++ b/Code/Framework/AzCore/AzCore/Console/IConsole.h @@ -94,22 +94,30 @@ namespace AZ //! @param commandLine the concatenated command-line string to execute virtual void ExecuteCommandLine(const AZ::CommandLine& commandLine) = 0; + //! Attempts to invoke a "deferred console command", which is a console command + //! that has failed to execute previously due to the command not being registered yet. + //! @return boolean true if any deferred console commands have executed, false otherwise + virtual bool ExecuteDeferredConsoleCommands() = 0; + + //! Clear out any deferred console commands queue + virtual void ClearDeferredConsoleCommands() = 0; + //! HasCommand is used to determine if the console knows about a command. //! @param command the command we are checking for //! @return boolean true on if the command is registered, false otherwise - virtual bool HasCommand(const char* command) = 0; + virtual bool HasCommand(AZStd::string_view command) = 0; //! FindCommand finds the console command with the specified console string. //! @param command the command that is being searched for //! @return non-null pointer to the console command if found - virtual ConsoleFunctorBase* FindCommand(const char* command) = 0; + virtual ConsoleFunctorBase* FindCommand(AZStd::string_view command) = 0; //! Finds all commands where the input command is a prefix and returns //! the longest matching substring prefix the results have in common. //! @param command The prefix string to find all matching commands for. //! @param matches The list of all commands that match the input prefix. //! @return The longest matching substring prefix the results have in common. - virtual AZStd::string AutoCompleteCommand(const char* command, + virtual AZStd::string AutoCompleteCommand(AZStd::string_view command, AZStd::vector* matches = nullptr) = 0; //! Retrieves the value of the requested cvar. @@ -117,7 +125,7 @@ namespace AZ //! @param outValue reference to the instance to write the current cvar value to //! @return GetValueResult::Success if the operation succeeded, or an error result if the operation failed template - GetValueResult GetCvarValue(const char* command, RETURN_TYPE& outValue); + GetValueResult GetCvarValue(AZStd::string_view command, RETURN_TYPE& outValue); //! Visits all registered console functors. //! @param visitor the instance to visit all functors with @@ -176,7 +184,7 @@ namespace AZ } template - inline GetValueResult IConsole::GetCvarValue(const char* command, RETURN_TYPE& outValue) + inline GetValueResult IConsole::GetCvarValue(AZStd::string_view command, RETURN_TYPE& outValue) { ConsoleFunctorBase* cvarFunctor = FindCommand(command); if (cvarFunctor == nullptr) diff --git a/Code/Framework/AzCore/AzCore/Debug/EventTrace.h b/Code/Framework/AzCore/AzCore/Debug/EventTrace.h index 5faf08f46e..1bc7ee20a6 100644 --- a/Code/Framework/AzCore/AzCore/Debug/EventTrace.h +++ b/Code/Framework/AzCore/AzCore/Debug/EventTrace.h @@ -38,17 +38,6 @@ namespace AZ } } -#ifdef AZ_PROFILE_TELEMETRY -# define AZ_TRACE_METHOD_NAME_CATEGORY(name, category) AZ::Debug::EventTrace::ScopedSlice AZ_JOIN(ScopedSlice__, __LINE__)(name, category); -# define AZ_TRACE_METHOD_NAME(name) \ - AZ_TRACE_METHOD_NAME_CATEGORY(name, "") \ - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzTrace, name) - -# define AZ_TRACE_METHOD() \ - AZ_TRACE_METHOD_NAME_CATEGORY(AZ_FUNCTION_SIGNATURE, "") \ - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzTrace) -#else -# define AZ_TRACE_METHOD_NAME_CATEGORY(name, category) -# define AZ_TRACE_METHOD_NAME(name) AZ_TRACE_METHOD_NAME_CATEGORY(name, "") -# define AZ_TRACE_METHOD() AZ_TRACE_METHOD_NAME(AZ_FUNCTION_SIGNATURE) -#endif +#define AZ_TRACE_METHOD_NAME_CATEGORY(name, category) +#define AZ_TRACE_METHOD_NAME(name) AZ_TRACE_METHOD_NAME_CATEGORY(name, "") +#define AZ_TRACE_METHOD() AZ_TRACE_METHOD_NAME(AZ_FUNCTION_SIGNATURE) diff --git a/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h b/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h index a11b411ded..f5bca5fba6 100644 --- a/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h +++ b/Code/Framework/AzCore/AzCore/Debug/IEventLogger.h @@ -13,6 +13,7 @@ #include #include #include +#include namespace AZ::Debug { diff --git a/Code/Framework/AzCore/AzCore/Debug/MemoryProfiler.h b/Code/Framework/AzCore/AzCore/Debug/MemoryProfiler.h new file mode 100644 index 0000000000..5b22e20c60 --- /dev/null +++ b/Code/Framework/AzCore/AzCore/Debug/MemoryProfiler.h @@ -0,0 +1,16 @@ +/* + * 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 + +#ifndef AZ_PROFILE_MEMORY_ALLOC +// No other profiler has defined the performance markers AZ_PROFILE_MEMORY_ALLOC (and friends), fall back to a Driller implementation (currently empty) +# define AZ_PROFILE_MEMORY_ALLOC(category, address, size, context) +# define AZ_PROFILE_MEMORY_ALLOC_EX(category, filename, lineNumber, address, size, context) +# define AZ_PROFILE_MEMORY_FREE(category, address) +# define AZ_PROFILE_MEMORY_FREE_EX(category, filename, lineNumber, address) +#endif diff --git a/Code/Framework/AzCore/AzCore/Debug/ProfileModuleInit.cpp b/Code/Framework/AzCore/AzCore/Debug/ProfileModuleInit.cpp deleted file mode 100644 index 9dda1f7656..0000000000 --- a/Code/Framework/AzCore/AzCore/Debug/ProfileModuleInit.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include - -#ifdef AZ_PROFILE_TELEMETRY -# include - // Define the per-module RAD Telemetry instance pointer - struct tm_api; - tm_api* g_radTmApi; -#endif - - -namespace AZ -{ - namespace Debug - { - void ProfileModuleInit() - { -#if defined(AZ_PROFILE_TELEMETRY) - { - if (!g_radTmApi) - { - using namespace RADTelemetry; - ProfileTelemetryRequestBus::BroadcastResult(g_radTmApi, &ProfileTelemetryRequests::GetApiInstance); - } - } -#endif - // Add additional per-DLL required profiler initialization here - } - - - ProfileModuleInitializer::ProfileModuleInitializer() - { - ProfilerNotificationBus::Handler::BusConnect(); - } - - ProfileModuleInitializer::~ProfileModuleInitializer() - { - ProfilerNotificationBus::Handler::BusDisconnect(); - } - - void ProfileModuleInitializer::OnProfileSystemInitialized() - { - ProfileModuleInit(); - } - } -} diff --git a/Code/Framework/AzCore/AzCore/Debug/ProfileModuleInit.h b/Code/Framework/AzCore/AzCore/Debug/ProfileModuleInit.h deleted file mode 100644 index e6666c9747..0000000000 --- a/Code/Framework/AzCore/AzCore/Debug/ProfileModuleInit.h +++ /dev/null @@ -1,36 +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 - * - */ - -#pragma once - -#include - -namespace AZ -{ - namespace Debug - { - //! Perform any required per-module initialization of the current profiler - void ProfileModuleInit(); - - - /*! - * ProfileModuleInitializer - * Helper class that calls ProfileModuleInit when OnProfileSystemInitialized is fired. - */ - class ProfileModuleInitializer - : private AZ::Debug::ProfilerNotificationBus::Handler - { - public: - ProfileModuleInitializer(); - ~ProfileModuleInitializer() override; - - private: - void OnProfileSystemInitialized() override; - }; - } -} diff --git a/Code/Framework/AzCore/AzCore/Debug/Profiler.cpp b/Code/Framework/AzCore/AzCore/Debug/Profiler.cpp index e6b7a80707..649bb0b8d7 100644 --- a/Code/Framework/AzCore/AzCore/Debug/Profiler.cpp +++ b/Code/Framework/AzCore/AzCore/Debug/Profiler.cpp @@ -20,6 +20,12 @@ namespace AZ { + uint32_t ProfileScope::GetSystemID(const char* system) + { + // TODO: stable ids for registered budgets + return AZ::Crc32(system); + } + namespace Debug { ////////////////////////////////////////////////////////////////////////// @@ -537,6 +543,7 @@ namespace AZ void ProfilerRegister::TimerStart(ProfilerSection* section) { ProfilerRegister* reg = this; + if (reg->m_isActive) { section->m_register = reg; diff --git a/Code/Framework/AzCore/AzCore/Debug/Profiler.h b/Code/Framework/AzCore/AzCore/Debug/Profiler.h index 243a8da0b0..f173bb8e17 100644 --- a/Code/Framework/AzCore/AzCore/Debug/Profiler.h +++ b/Code/Framework/AzCore/AzCore/Debug/Profiler.h @@ -5,310 +5,44 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZCORE_PROFILER_H -#define AZCORE_PROFILER_H 1 +#pragma once #include #include -namespace AZ -{ - namespace Debug - { - using ProfileCategoryPrimitiveType = AZ::u64; - - /** - * Profiling categories consumed by AZ_PROFILE_FUNCTION and AZ_PROFILE_SCOPE variants for profile filtering - */ - enum class ProfileCategory : ProfileCategoryPrimitiveType - { - // These initial categories match up with the legacy EProfiledSubsystem categories - Any = 0, - Renderer, - ThreeDEngine, - Particle, - AI, - Animation, - Movie, - Entity, - Font, - Network, - Physics, - Script, - ScriptCFunc, - Audio, - Editor, - System, - Action, - Game, - Input, - Sync, - - // Legacy network traffic categories - LegacyNetworkTrafficReserved, - LegacyDeviceReserved, - - // must match EProfiledSubsystem::PROFILE_LAST_SUBSYSTEM - LegacyLast, - - // Bulk category via AZ_TRACE_METHOD - AzTrace, - - AzCore, - AzRender, - AzFramework, - AzToolsFramework, - ScriptCanvas, - LegacyTerrain, - Terrain, - Cloth, - // Add new major categories here (and add names to the parallel position in ProfileCategoryNames) - these categories are enabled by default - - FirstDetailedCategory, - RendererDetailed = FirstDetailedCategory, - ThreeDEngineDetailed, - JobManagerDetailed, - - AzRenderDetailed, - ClothDetailed, - // Add new detailed categories here (and add names to the parallel position in ProfileCategoryNames) -- these categories are disabled by default - - // Internal reserved categories, not for use with performance events - FirstReservedCategory, - MemoryReserved = FirstReservedCategory, - Global, - - // Must be last - Count - }; - static_assert(static_cast(ProfileCategory::Count) < (sizeof(ProfileCategoryPrimitiveType) * 8), "The number of profile categories must not exceed the number of bits in ProfileCategoryPrimitiveType"); - - /** - * Parallel array to ProfileCategory as string category names to be used as Driller category names or for debug purposes - */ - static const char * ProfileCategoryNames[] = - { - "Any", - "Renderer", - "3DEngine", - "Particle", - "AI", - "Animation", - "Movie", - "Entity", - "Font", - "Network", - "Physics", - "Script", - "ScriptCFunc", - "Audio", - "Editor", - "System", - "Action", - "Game", - "Input", - "Sync", - - "LegacyNetworkTrafficReserved", - "LegacyDeviceReserved", - - "LegacyLast", - - "AzTrace", - "AzCore", - "AzRender", - "AzFramework", - "AzToolsFramework", - "ScriptCanvas", - "LegacyTerrain", - "Terrain", - "Cloth", - - "RendererDetailed", - "3DEngineDetailed", - "JobManagerDetailed", - "AzRenderDetailed", - "ClothDetailed", - - "MemoryReserved", - "Global" - }; - static_assert(AZ_ARRAY_SIZE(ProfileCategoryNames) == static_cast(ProfileCategory::Count), "ProfileCategory and ProfileCategoryNames size mismatch"); - } -} - -// Must be included below ProfileCategory -#ifdef AZ_PROFILE_TELEMETRY -# include +#ifdef USE_PIX +#include +#include #endif #if defined(AZ_PROFILER_MACRO_DISABLE) // by default we never disable the profiler registers as their overhead should be minimal, you can still do that for your code though. -# define AZ_PROFILE_TIMER(...) -# define AZ_PROFILE_TIMER_END(_SectionVariableName) -# define AZ_PROFILE_VALUE_SET(...) -# define AZ_PROFILE_VALUE_ADD(...) -# define AZ_PROFILE_VALUE_SET_NAMED(...) -# define AZ_PROFILE_VALUE_ADD_NAMED(...) +# define AZ_PROFILE_SCOPE(...) +# define AZ_PROFILE_FUNCTION(...) +# define AZ_PROFILE_BEGIN(...) +# define AZ_PROFILE_END(...) #else -/// Implementation when we have only 1 param system name -# define AZ_PROFILE_TIMER_1(_1) AZ_PROFILE_TIMER_2(_1, nullptr) -/// Implementation when we have 2 params (_1 system name and _2 is name of the "section"/register/profiled section - used for debug) -# define AZ_PROFILE_TIMER_2(_1, _2) AZ_PROFILE_TIMER_3(_1, _2, AZ_JOIN(azProfileSection, __LINE__)) -/// Implementation when we have all 3 params (system name, section/register name, section variable name) -# define AZ_PROFILE_TIMER_3(_1, _2, _3) \ - AZ::Debug::ProfilerSection _3; \ - if (AZ::u64 profilerId = AZ::Debug::Profiler::GetId()) { \ - static AZ_THREAD_LOCAL AZ::Internal::RegisterData AZ_JOIN(azProfileRegister, __LINE__) = {0, 0}; \ - if (AZ_JOIN(azProfileRegister, __LINE__).m_profilerId != profilerId) { \ - AZ_JOIN(azProfileRegister, __LINE__).m_register = AZ::Debug::ProfilerRegister::TimerCreateAndStart(_1, _2, &_3, AZ_FUNCTION_SIGNATURE, __LINE__); \ - AZ_JOIN(azProfileRegister, __LINE__).m_profilerId = profilerId; \ - } else { \ - AZ_JOIN(azProfileRegister, __LINE__).m_register->TimerStart(&_3); \ - } \ - } - /** * Macro to declare a profile section for the current scope { }. - * format is: AZ_PROFILE_TIMER(const char* systemName, const char* sectionDescription = nullptr , optional sectionName ) - * \param _1 is required and it's 'const char*' of the system name of which system this scope/register belongs to. - * \param _2 is optional and it's 'const char*' with a name for the "section"/register/profiled section - used as description. If not provided a "Anonymous" will be set. - * \param _3 is optional unique name for a section C++ variable (so you can stop the SCOPE as you wish). If not provided a default unique name is created. + * format is: AZ_PROFILE_SCOPE(categoryName, const char* formatStr, ...) */ -# define AZ_PROFILE_TIMER(...) AZ_MACRO_SPECIALIZE(AZ_PROFILE_TIMER_, AZ_VA_NUM_ARGS(__VA_ARGS__), (__VA_ARGS__)) - -// Optional (USE ONLY IN EXTREME CASES!!!) scope end command for named sections, so you stop the profiler register timing before it goes out of scope. -# define AZ_PROFILE_TIMER_END(_SectionVariableName) { _SectionVariableName.Stop(); } - -/** - * Macro to operate on custom values. All values are AZ::s64. You can provide up to 5 values. - * format is AZ_PROFILE_VALUE_SET/ADD(const char* systemName, const char* valueName, - * value1, optional value2, optional value3, optional value 4, optional value5, optional registerName (for direct register manipulation for EXPERTS ONLY)). - * \param _SystemName is required and it's 'const char*' of the system name of which system this scope/register belongs to. - * \param _RegisterName is required and it's 'const char*' with a name for the register - used as description. - * \param 3 is required and it's AZ::s64, operates on m_value1. - * \param 4 is optional and it's AZ::s64, operates on m_value2. - * \param 5 is optional and it's AZ::s64, operates on m_value3. - * \param 6 is optional and it's AZ::s64, operates on m_value4. - * \param 7 is optional and it's AZ::s64, operates on m_value5. - */ -# define AZ_PROFILE_VALUE_SET(_SystemName, _RegisterName, ...) \ - if (AZ::u64 profilerId = AZ::Debug::Profiler::GetId()) { \ - static AZ_THREAD_LOCAL AZ::Internal::RegisterData AZ_JOIN(azProfileRegister, __LINE__) = {0, 0}; \ - if (AZ_JOIN(azProfileRegister, __LINE__).m_profilerId != profilerId) { \ - AZ_JOIN(azProfileRegister, __LINE__).m_register = AZ::Debug::ProfilerRegister::ValueCreate(_SystemName, _RegisterName, AZ_FUNCTION_SIGNATURE, __LINE__); \ - AZ_JOIN(azProfileRegister, __LINE__).m_profilerId = profilerId; \ - } \ - AZ_JOIN(azProfileRegister, __LINE__).m_register->ValueSet(__VA_ARGS__); \ - } - -/// Same as AZ_PROFILE_VALUE_SET except is add the values passed in the macro (you can use -(value), to subtract values) -# define AZ_PROFILE_VALUE_ADD(_SystemName, _RegisterName, ...) \ - if (AZ::u64 profilerId = AZ::Debug::Profiler::GetId()) { \ - static AZ_THREAD_LOCAL AZ::Internal::RegisterData AZ_JOIN(azProfileRegister, __LINE__) = {0, 0}; \ - if (AZ_JOIN(azProfileRegister, __LINE__).m_profilerId != profilerId) { \ - AZ_JOIN(azProfileRegister, __LINE__).m_register = AZ::Debug::ProfilerRegister::ValueCreate(_SystemName, _RegisterName, AZ_FUNCTION_SIGNATURE, __LINE__); \ - AZ_JOIN(azProfileRegister, __LINE__).m_profilerId = profilerId; \ - } \ - AZ_JOIN(azProfileRegister, __LINE__).m_register->ValueAdd(__VA_ARGS__); \ - } - -/** - * Same as AZ_PROFILER_VALUE_SET but with option to access the register by name. (USE ONLY IN EXTREME CASES!!!) - * \param _RegisterVaribaleName is optional unique name for a register C++ variable so you can manipulate the register. - */ -# define AZ_PROFILE_VALUE_SET_NAMED(_SystemName, _RegisterName, _RegisterVaribaleName, ...) \ - AZ::Debug::ProfilerRegister * _RegisterVaribaleName = nullptr; \ - if (AZ::u64 profilerId = AZ::Debug::Profiler::GetId()) { \ - static AZ_THREAD_LOCAL AZ::Internal::RegisterData AZ_JOIN(azProfileRegister, __LINE__) = {0, 0}; \ - if (AZ_JOIN(azProfileRegister, __LINE__).m_profilerId != profilerId) { \ - AZ_JOIN(azProfileRegister, __LINE__).m_register = AZ::Debug::ProfilerRegister::ValueCreate(_SystemName, _RegisterName, AZ_FUNCTION_SIGNATURE, __LINE__); \ - AZ_JOIN(azProfileRegister, __LINE__).m_profilerId = profilerId; \ - } \ - AZ_JOIN(azProfileRegister, __LINE__).m_register->ValueSet(__VA_ARGS__); \ - _RegisterVaribaleName = AZ_JOIN(azProfileRegister, __LINE__).m_register; \ - } - -/// Same as AZ_PROFILE_VALUE_SET_NAMED but add the values to the current. (USE ONLY IN EXTREME CASES!!!) -# define AZ_PROFILE_VALUE_ADD_NAMED(_SystemName, _RegisterName, _RegisterVaribaleName, ...) \ - AZ::Debug::ProfilerRegister * _RegisterVaribaleName = nullptr; \ - if (AZ::u64 profilerId = AZ::Debug::Profiler::GetId()) { \ - static AZ_THREAD_LOCAL AZ::Internal::RegisterData AZ_JOIN(azProfileRegister, __LINE__) = {0, 0}; \ - if (AZ_JOIN(azProfileRegister, __LINE__).m_profilerId != profilerId) { \ - AZ_JOIN(azProfileRegister, __LINE__).m_register = AZ::Debug::ProfilerRegister::ValueCreate(_SystemName, _RegisterName, AZ_FUNCTION_SIGNATURE, __LINE__); \ - AZ_JOIN(azProfileRegister, __LINE__).m_profilerId = profilerId; \ - } \ - AZ_JOIN(azProfileRegister, __LINE__).m_register->ValueAdd(__VA_ARGS__); \ - _RegisterVaribaleName = AZ_JOIN(azProfileRegister, __LINE__).m_register; \ - } +# define AZ_PROFILE_SCOPE(category, ...) ::AZ::ProfileScope AZ_JOIN(azProfileScope, __LINE__){ #category, __VA_ARGS__ } +# define AZ_PROFILE_FUNCTION(category) AZ_PROFILE_SCOPE(category, AZ_FUNCTION_SIGNATURE) +// Prefer using the scoped macros which automatically end the event (AZ_PROFILE_SCOPE/AZ_PROFILE_FUNCTION) +# define AZ_PROFILE_BEGIN(category, ...) ::AZ::ProfileScope::BeginRegion(#category, __VA_ARGS__) +# define AZ_PROFILE_END() ::AZ::ProfileScope::EndRegion() #endif // AZ_PROFILER_MACRO_DISABLE -#ifndef AZ_PROFILE_FUNCTION -// No other profiler has defined the performance markers AZ_PROFILE_SCOPE (and friends), fallback to a Driller implementation -# define AZ_INTERNAL_PROF_VERIFY_CAT(category) static_assert(category < AZ::Debug::ProfileCategory::Count, "Invalid profile category") -# define AZ_INTERNAL_PROF_CAT_NAME(category) AZ::Debug::ProfileCategoryNames[static_cast(category)] - -# define AZ_PROFILE_FUNCTION(category) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_PROFILE_TIMER(AZ_INTERNAL_PROF_CAT_NAME(category)) -# define AZ_PROFILE_FUNCTION_STALL(category) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_PROFILE_TIMER(AZ_INTERNAL_PROF_CAT_NAME(category)) -# define AZ_PROFILE_FUNCTION_IDLE(category) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_PROFILE_TIMER(AZ_INTERNAL_PROF_CAT_NAME(category)) - -# define AZ_PROFILE_SCOPE(category, name) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_PROFILE_TIMER(AZ_INTERNAL_PROF_CAT_NAME(category)); (void)(name) -# define AZ_PROFILE_SCOPE_STALL(category, name) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_PROFILE_TIMER(AZ_INTERNAL_PROF_CAT_NAME(category)); (void)(name) -# define AZ_PROFILE_SCOPE_IDLE(category, name) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_PROFILE_TIMER(AZ_INTERNAL_PROF_CAT_NAME(category)); (void)(name) - -# define AZ_PROFILE_SCOPE_DYNAMIC(category, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_PROFILE_TIMER(AZ_INTERNAL_PROF_CAT_NAME(category)) -# define AZ_PROFILE_SCOPE_STALL_DYNAMIC(category, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_PROFILE_TIMER(AZ_INTERNAL_PROF_CAT_NAME(category)) -# define AZ_PROFILE_SCOPE_IDLE_DYNAMIC(category, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_PROFILE_TIMER(AZ_INTERNAL_PROF_CAT_NAME(category)) -#endif - -#ifndef AZ_PROFILE_EVENT_BEGIN -// No other profiler has defined the performance markers AZ_PROFILE_EVENT_START/END, fallback to a Driller implementation (currently empty) -# define AZ_PROFILE_EVENT_BEGIN(category, name) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); (void)(name) -# define AZ_PROFILE_EVENT_END(category) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category) -#endif - #ifndef AZ_PROFILE_INTERVAL_START -// No other profiler has defined the performance markers AZ_PROFILE_INTERVAL_START/END, fallback to a Driller implementation (currently empty) -# define AZ_INTERNAL_PROF_VERIFY_INTERVAL_ID(id) static_assert(sizeof(id) <= sizeof(AZ::u64), "Interval id must be a unique value no larger than 64-bits") -# define AZ_PROFILE_INTERVAL_START(category, id, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_INTERNAL_PROF_VERIFY_INTERVAL_ID(id) -# define AZ_PROFILE_INTERVAL_START_COLORED(category, id, color, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); (void)(color); AZ_INTERNAL_PROF_VERIFY_INTERVAL_ID(id) -# define AZ_PROFILE_INTERVAL_END(category, id) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_INTERNAL_PROF_VERIFY_INTERVAL_ID(id) -# define AZ_PROFILE_INTERVAL_SCOPED(category, id, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); AZ_INTERNAL_PROF_VERIFY_INTERVAL_ID(id) +# define AZ_PROFILE_INTERVAL_START(...) +# define AZ_PROFILE_INTERVAL_START_COLORED(...) +# define AZ_PROFILE_INTERVAL_END(...) +# define AZ_PROFILE_INTERVAL_SCOPED(...) #endif #ifndef AZ_PROFILE_DATAPOINT -// No other profiler has defined the performance markers AZ_PROFILE_DATAPOINT, fallback to a Driller implementation (currently empty) -#define AZ_PROFILE_DATAPOINT(category, value, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); static_cast(value) -#define AZ_PROFILE_DATAPOINT_PERCENT(category, value, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); static_cast(value) -#endif - -#ifndef AZ_PROFILE_MEMORY_ALLOC -// No other profiler has defined the performance markers AZ_PROFILE_MEMORY_ALLOC (and friends), fall back to a Driller implementation (currently empty) -# define AZ_PROFILE_MEMORY_ALLOC(category, address, size, context) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); (void)(context) -# define AZ_PROFILE_MEMORY_ALLOC_EX(category, filename, lineNumber, address, size, context) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); (void)(context) -# define AZ_PROFILE_MEMORY_FREE(category, address) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category) -# define AZ_PROFILE_MEMORY_FREE_EX(category, filename, lineNumber, address) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category) +# define AZ_PROFILE_DATAPOINT(...) +# define AZ_PROFILE_DATAPOINT_PERCENT(...) #endif namespace AZStd @@ -318,6 +52,42 @@ namespace AZStd namespace AZ { + class ProfileScope + { + public: + static uint32_t GetSystemID(const char* system); + + template + static void BeginRegion([[maybe_unused]] const char* system, [[maybe_unused]] const char* eventName, [[maybe_unused]] T const&... args) + { + // TODO: Verification that the supplied system name corresponds to a known budget +#if defined(USE_PIX) + PIXBeginEvent(PIX_COLOR_INDEX(GetSystemID(system) & 0xff), eventName, args...); +#endif + // TODO: injecting instrumentation for other profilers + // NOTE: external profiler registration won't occur inline in a header necessarily in this manner, but the exact mechanism + // will be introduced in a future PR + } + + static void EndRegion() + { +#if defined(USE_PIX) + PIXEndEvent(); +#endif + } + + template + ProfileScope(const char* system, char const* eventName, T const&... args) + { + BeginRegion(system, eventName, args...); + } + + ~ProfileScope() + { + EndRegion(); + } + }; + namespace Debug { class ProfilerSection; @@ -615,5 +385,9 @@ namespace AZ } } // namespace AZ -#endif // AZCORE_PROFILER_H -#pragma once +#ifdef USE_PIX +// The pix3 header unfortunately brings in other Windows macros we need to undef +#undef DeleteFile +#undef LoadImage +#undef GetCurrentTime +#endif diff --git a/Code/Framework/AzCore/AzCore/IO/ByteContainerStream.h b/Code/Framework/AzCore/AzCore/IO/ByteContainerStream.h index 17f72b9012..d198f47e00 100644 --- a/Code/Framework/AzCore/AzCore/IO/ByteContainerStream.h +++ b/Code/Framework/AzCore/AzCore/IO/ByteContainerStream.h @@ -12,6 +12,7 @@ #include #include #include +#include namespace AZ { diff --git a/Code/Framework/AzCore/AzCore/IO/FileIO.cpp b/Code/Framework/AzCore/AzCore/IO/FileIO.cpp index 125951c261..a6ce8cf101 100644 --- a/Code/Framework/AzCore/AzCore/IO/FileIO.cpp +++ b/Code/Framework/AzCore/AzCore/IO/FileIO.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #ifndef SEEK_SET # define SEEK_SET 0 /* Seek from beginning of file. */ @@ -353,7 +354,7 @@ namespace AZ m_filename = path; } - AZ_PROFILE_INTERVAL_START_COLORED(AZ::Debug::ProfileCategory::AzCore, &m_filename, 0xff0000ff, "FileIO: %s", m_filename.c_str()); + AZ_PROFILE_INTERVAL_START_COLORED(AzCore, &m_filename, 0xff0000ff, "FileIO: %s", m_filename.c_str()); return result; } @@ -372,7 +373,7 @@ namespace AZ FileIOBase::GetInstance()->Close(m_handle); m_handle = InvalidHandle; m_ownsHandle = false; - AZ_PROFILE_INTERVAL_END(AZ::Debug::ProfileCategory::AzCore, &m_filename); + AZ_PROFILE_INTERVAL_END(AzCore, &m_filename); } } @@ -425,7 +426,7 @@ namespace AZ void FileIOStream::Seek(OffsetType bytes, SeekMode mode) { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "FileIO Seek: %s", m_filename.c_str()); + AZ_PROFILE_SCOPE(AzCore, "FileIO Seek: %s", m_filename.c_str()); AZ_Assert(FileIOBase::GetInstance(), "FileIO is not initialized."); AZ_Assert(IsOpen(), "Cannot seek on a FileIOStream that is not open."); @@ -453,7 +454,7 @@ namespace AZ SizeType FileIOStream::Read(SizeType bytes, void* oBuffer) { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "FileIO Read: %s", m_filename.c_str()); + AZ_PROFILE_SCOPE(AzCore, "FileIO Read: %s", m_filename.c_str()); AZ_Assert(FileIOBase::GetInstance(), "FileIO is not initialized."); AZ_Assert(IsOpen(), "Cannot read from a FileIOStream that is not open."); diff --git a/Code/Framework/AzCore/AzCore/IO/GenericStreams.cpp b/Code/Framework/AzCore/AzCore/IO/GenericStreams.cpp index b3ab808711..e7ccf4c83a 100644 --- a/Code/Framework/AzCore/AzCore/IO/GenericStreams.cpp +++ b/Code/Framework/AzCore/AzCore/IO/GenericStreams.cpp @@ -11,6 +11,7 @@ #include #include #include +#include namespace AZ::IO { diff --git a/Code/Framework/AzCore/AzCore/IO/Path/Path.inl b/Code/Framework/AzCore/AzCore/IO/Path/Path.inl index 4e8356b436..309a4fa050 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/Path.inl +++ b/Code/Framework/AzCore/AzCore/IO/Path/Path.inl @@ -10,6 +10,7 @@ #include #include +#include // extern instantiations of Path templates to prevent implicit instantiations namespace AZ::IO @@ -221,7 +222,7 @@ namespace AZ::IO::Internal ? strncmp(left.data(), right.data(), maxCharsToCompare) : azstrnicmp(left.data(), right.data(), maxCharsToCompare); return charCompareResult == 0 - ? aznumeric_cast(left.size()) - aznumeric_cast(right.size()) + ? static_cast(aznumeric_cast(left.size()) - aznumeric_cast(right.size())) : charCompareResult; } } diff --git a/Code/Framework/AzCore/AzCore/IO/Streamer/BlockCache.cpp b/Code/Framework/AzCore/AzCore/IO/Streamer/BlockCache.cpp index f358370be5..e838324408 100644 --- a/Code/Framework/AzCore/AzCore/IO/Streamer/BlockCache.cpp +++ b/Code/Framework/AzCore/AzCore/IO/Streamer/BlockCache.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -38,7 +39,7 @@ namespace AZ break; } - u32 cacheSize = m_cacheSizeMib * 1_mib; + u32 cacheSize = static_cast(m_cacheSizeMib * 1_mib); if (blockSize * 2 > cacheSize) { AZ_Warning("Streamer", false, "Size (%u) for BlockCache isn't big enough to hold at least two cache blocks of size (%zu). " @@ -188,7 +189,7 @@ namespace AZ s32 numAvailableSlots = CalculateAvailableRequestSlots(); status.m_numAvailableSlots = AZStd::min(status.m_numAvailableSlots, numAvailableSlots); status.m_isIdle = status.m_isIdle && - numAvailableSlots == m_numBlocks && + static_cast(numAvailableSlots) == m_numBlocks && m_delayedSections.empty(); } @@ -245,7 +246,7 @@ namespace AZ auto continueReadFile = [this, request](FileRequest& fileSizeRequest) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Assert(m_numMetaDataRetrievalInProgress > 0, "More requests have completed meta data retrieval in the Block Cache than were requested."); m_numMetaDataRetrievalInProgress--; @@ -454,7 +455,7 @@ namespace AZ section.m_readSize, sharedRead); readRequest->SetCompletionCallback([this](FileRequest& request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); CompleteRead(request); }); section.m_cacheBlockIndex = cacheLocation; diff --git a/Code/Framework/AzCore/AzCore/IO/Streamer/DedicatedCache.cpp b/Code/Framework/AzCore/AzCore/IO/Streamer/DedicatedCache.cpp index 6ec3fb295c..e0e512e21f 100644 --- a/Code/Framework/AzCore/AzCore/IO/Streamer/DedicatedCache.cpp +++ b/Code/Framework/AzCore/AzCore/IO/Streamer/DedicatedCache.cpp @@ -36,7 +36,7 @@ namespace AZ break; } - u32 cacheSize = m_cacheSizeMib * 1_mib; + u32 cacheSize = static_cast(m_cacheSizeMib * 1_mib); if (blockSize > cacheSize) { AZ_Warning("Streamer", false, "Size (%u) for DedicatedCache isn't big enough to hold at least one cache blocks of size (%zu). " diff --git a/Code/Framework/AzCore/AzCore/IO/Streamer/FullFileDecompressor.cpp b/Code/Framework/AzCore/AzCore/IO/Streamer/FullFileDecompressor.cpp index 2e9dd43e83..44bf36bd9d 100644 --- a/Code/Framework/AzCore/AzCore/IO/Streamer/FullFileDecompressor.cpp +++ b/Code/Framework/AzCore/AzCore/IO/Streamer/FullFileDecompressor.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -367,7 +368,7 @@ namespace AZ { auto callback = [this, nextRequest](const FileRequest& checkRequest) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); auto check = AZStd::get_if(&checkRequest.GetCommand()); AZ_Assert(check, "Callback in FullFileDecompressor::PrepareReadRequest expected FileExistsCheck but got another command."); @@ -426,7 +427,7 @@ namespace AZ { auto callback = [this, nextRequest](const FileRequest& checkRequest) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); auto check = AZStd::get_if(&checkRequest.GetCommand()); AZ_Assert(check, "Callback in FullFileDecompressor::PrepareDedicatedCache expected FileExistsCheck but got another command."); @@ -508,7 +509,7 @@ namespace AZ archiveReadRequest->SetCompletionCallback( [this, readSlot = i](FileRequest& request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); FinishArchiveRead(&request, readSlot); }); m_next->QueueRequest(archiveReadRequest); @@ -596,7 +597,7 @@ namespace AZ waitRequest->SetCompletionCallback([this, jobSlot](FileRequest& request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); FinishDecompression(&request, jobSlot); }); diff --git a/Code/Framework/AzCore/AzCore/IO/Streamer/ReadSplitter.cpp b/Code/Framework/AzCore/AzCore/IO/Streamer/ReadSplitter.cpp index 9e019745a3..00c1c63933 100644 --- a/Code/Framework/AzCore/AzCore/IO/Streamer/ReadSplitter.cpp +++ b/Code/Framework/AzCore/AzCore/IO/Streamer/ReadSplitter.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -218,7 +219,7 @@ namespace AZ subRequest->CreateRead(pending.m_request, pending.m_output, bufferSize, data->m_path, pending.m_offset, readSize, data->m_sharedRead); subRequest->SetCompletionCallback([this](FileRequest&) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); QueuePendingRequest(); }); m_next->QueueRequest(subRequest); @@ -302,7 +303,7 @@ namespace AZ offset, readSize, data->m_sharedRead); subRequest->SetCompletionCallback([this, bufferSlot]([[maybe_unused]] FileRequest& request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); BufferCopyInformation& copyInfo = m_bufferCopyInformation[bufferSlot]; memcpy(copyInfo.m_target, GetBufferSlot(bufferSlot) + copyInfo.m_bufferOffset, copyInfo.m_size); diff --git a/Code/Framework/AzCore/AzCore/IO/Streamer/Scheduler.cpp b/Code/Framework/AzCore/AzCore/IO/Streamer/Scheduler.cpp index d6e5a7bb2c..e7f9b0fd18 100644 --- a/Code/Framework/AzCore/AzCore/IO/Streamer/Scheduler.cpp +++ b/Code/Framework/AzCore/AzCore/IO/Streamer/Scheduler.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -138,14 +139,14 @@ namespace AZ::IO while (m_isRunning) { { - AZ_PROFILE_SCOPE_IDLE(AZ::Debug::ProfileCategory::AzCore, "Scheduler suspended."); + AZ_PROFILE_SCOPE(AzCore, "Scheduler suspended."); m_context.SuspendSchedulingThread(); } // Only do processing if the thread hasn't been suspended. while (!m_isSuspended) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "Scheduler main loop."); + AZ_PROFILE_SCOPE(AzCore, "Scheduler main loop."); // Always schedule requests first as the main Streamer thread could have been asleep for a long time due to slow reading // but also don't schedule after every change in the queue as scheduling is not cheap. @@ -154,7 +155,7 @@ namespace AZ::IO { do { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "Scheduler queue requests."); + AZ_PROFILE_SCOPE(AzCore, "Scheduler queue requests."); // If there are pending requests and available slots, queue the next requests. while(m_context.GetNumPreparedRequests() > 0) { @@ -208,7 +209,7 @@ namespace AZ::IO void Scheduler::Thread_QueueNextRequest() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); FileRequest* next = m_context.PopPreparedRequest(); next->SetStatus(IStreamerTypes::RequestStatus::Processing); @@ -279,7 +280,7 @@ namespace AZ::IO m_processingSize += info.m_uncompressedSize; #endif } - AZ_PROFILE_INTERVAL_START_COLORED(AZ::Debug::ProfileCategory::AzCore, next, ProfilerColor, + AZ_PROFILE_INTERVAL_START_COLORED(AzCore, next, ProfilerColor, "Streamer queued %zu: %s", next->GetCommand().index(), parentReadRequest->m_path.GetRelativePath()); m_threadData.m_streamStack->QueueRequest(next); } @@ -293,7 +294,7 @@ namespace AZ::IO } else if constexpr (AZStd::is_same_v || AZStd::is_same_v) { - AZ_PROFILE_INTERVAL_START_COLORED(AZ::Debug::ProfileCategory::AzCore, next, ProfilerColor, + AZ_PROFILE_INTERVAL_START_COLORED(AzCore, next, ProfilerColor, "Streamer queued %zu", next->GetCommand().index()); // Flushing becomes a lot less complicated if there are no jobs and/or asynchronous I/O running. This does mean overall // longer processing time as bubbles are introduced into the pipeline, but flushing is an infrequent event that only @@ -303,7 +304,7 @@ namespace AZ::IO } else { - AZ_PROFILE_INTERVAL_START_COLORED(AZ::Debug::ProfileCategory::AzCore, next, ProfilerColor, + AZ_PROFILE_INTERVAL_START_COLORED(AzCore, next, ProfilerColor, "Streamer queued %zu", next->GetCommand().index()); m_threadData.m_streamStack->QueueRequest(next); } @@ -312,13 +313,13 @@ namespace AZ::IO bool Scheduler::Thread_ExecuteRequests() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); return m_threadData.m_streamStack->ExecuteRequests(); } bool Scheduler::Thread_PrepareRequests(AZStd::vector& outstandingRequests) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); { AZStd::scoped_lock lock(m_pendingRequestsLock); @@ -372,7 +373,7 @@ namespace AZ::IO void Scheduler::Thread_ProcessTillIdle() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); while (true) { @@ -390,7 +391,7 @@ namespace AZ::IO void Scheduler::Thread_ProcessCancelRequest(FileRequest* request, FileRequest::CancelData& data) { - AZ_PROFILE_INTERVAL_START_COLORED(AZ::Debug::ProfileCategory::AzCore, request, ProfilerColor, "Streamer queued cancel"); + AZ_PROFILE_INTERVAL_START_COLORED(AzCore, request, ProfilerColor, "Streamer queued cancel"); auto& pending = m_context.GetPreparedRequests(); auto pendingIt = pending.begin(); while (pendingIt != pending.end()) @@ -412,7 +413,7 @@ namespace AZ::IO void Scheduler::Thread_ProcessRescheduleRequest(FileRequest* request, FileRequest::RescheduleData& data) { - AZ_PROFILE_INTERVAL_START_COLORED(AZ::Debug::ProfileCategory::AzCore, request, ProfilerColor, "Streamer queued reschedule"); + AZ_PROFILE_INTERVAL_START_COLORED(AzCore, request, ProfilerColor, "Streamer queued reschedule"); auto& pendingRequests = m_context.GetPreparedRequests(); for (FileRequest* pending : pendingRequests) { @@ -543,7 +544,7 @@ namespace AZ::IO void Scheduler::Thread_ScheduleRequests() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now(); auto& pendingQueue = m_context.GetPreparedRequests(); @@ -554,7 +555,7 @@ namespace AZ::IO if (m_context.GetNumPreparedRequests() > 1) { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, + AZ_PROFILE_SCOPE(AzCore, "Scheduler::Thread_ScheduleRequests - Sorting %i requests", m_context.GetNumPreparedRequests()); auto sorter = [this](const FileRequest* lhs, const FileRequest* rhs) -> bool { diff --git a/Code/Framework/AzCore/AzCore/IO/Streamer/Statistics.cpp b/Code/Framework/AzCore/AzCore/IO/Streamer/Statistics.cpp index 593c052853..e64c3cae74 100644 --- a/Code/Framework/AzCore/AzCore/IO/Streamer/Statistics.cpp +++ b/Code/Framework/AzCore/AzCore/IO/Streamer/Statistics.cpp @@ -48,7 +48,7 @@ namespace AZ [[maybe_unused]] AZStd::string_view name, [[maybe_unused]] double value) { - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::AzCore, value, + AZ_PROFILE_DATAPOINT(AzCore, value, "Streamer/%.*s/%.*s (Raw)", aznumeric_cast(owner.size()), owner.data(), aznumeric_cast(name.size()), name.data()); diff --git a/Code/Framework/AzCore/AzCore/IO/Streamer/StorageDrive.cpp b/Code/Framework/AzCore/AzCore/IO/Streamer/StorageDrive.cpp index c4f9840a0b..6f33c0a216 100644 --- a/Code/Framework/AzCore/AzCore/IO/Streamer/StorageDrive.cpp +++ b/Code/Framework/AzCore/AzCore/IO/Streamer/StorageDrive.cpp @@ -59,7 +59,7 @@ namespace AZ void StorageDrive::PrepareRequest(FileRequest* request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Assert(request, "PrepareRequest was provided a null request."); if (AZStd::holds_alternative(request->GetCommand())) @@ -254,7 +254,7 @@ namespace AZ void StorageDrive::ReadFile(FileRequest* request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); auto data = AZStd::get_if(&request->GetCommand()); AZ_Assert(data, "FileRequest queued on StorageDrive to be read didn't contain read data."); @@ -341,7 +341,7 @@ namespace AZ void StorageDrive::FileExistsRequest(FileRequest* request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); TIMED_AVERAGE_WINDOW_SCOPE(m_getFileExistsTimeAverage); auto& fileExists = AZStd::get(request->GetCommand()); @@ -359,7 +359,7 @@ namespace AZ void StorageDrive::FileMetaDataRetrievalRequest(FileRequest* request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); TIMED_AVERAGE_WINDOW_SCOPE(m_getFileMetaDataTimeAverage); auto& command = AZStd::get(request->GetCommand()); diff --git a/Code/Framework/AzCore/AzCore/IO/Streamer/Streamer.cpp b/Code/Framework/AzCore/AzCore/IO/Streamer/Streamer.cpp index 792ef8ea1e..e634f2eac8 100644 --- a/Code/Framework/AzCore/AzCore/IO/Streamer/Streamer.cpp +++ b/Code/Framework/AzCore/AzCore/IO/Streamer/Streamer.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -262,15 +263,15 @@ namespace AZ::IO switch (stat.GetType()) { case Statistic::Type::FloatingPoint: - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::AzCore, stat.GetFloatValue(), "Streamer/%.*s/%.*s", + AZ_PROFILE_DATAPOINT(AzCore, stat.GetFloatValue(), "Streamer/%.*s/%.*s", aznumeric_cast(stat.GetOwner().length()), stat.GetOwner().data(), aznumeric_cast(stat.GetName().length()), stat.GetName().data()); break; case Statistic::Type::Integer: - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::AzCore, stat.GetIntegerValue(), "Streamer/%.*s/%.*s", + AZ_PROFILE_DATAPOINT(AzCore, stat.GetIntegerValue(), "Streamer/%.*s/%.*s", aznumeric_cast(stat.GetOwner().length()), stat.GetOwner().data(), aznumeric_cast(stat.GetName().length()), stat.GetName().data()); break; case Statistic::Type::Percentage: - AZ_PROFILE_DATAPOINT_PERCENT(AZ::Debug::ProfileCategory::AzCore, stat.GetPercentage(), "Streamer/%.*s/%.*s (percent)", + AZ_PROFILE_DATAPOINT_PERCENT(AzCore, stat.GetPercentage(), "Streamer/%.*s/%.*s (percent)", aznumeric_cast(stat.GetOwner().length()), stat.GetOwner().data(), aznumeric_cast(stat.GetName().length()), stat.GetName().data()); break; default: diff --git a/Code/Framework/AzCore/AzCore/IO/Streamer/StreamerContext.cpp b/Code/Framework/AzCore/AzCore/IO/Streamer/StreamerContext.cpp index e870e29786..823ab6e050 100644 --- a/Code/Framework/AzCore/AzCore/IO/Streamer/StreamerContext.cpp +++ b/Code/Framework/AzCore/AzCore/IO/Streamer/StreamerContext.cpp @@ -153,7 +153,7 @@ namespace AZ bool StreamerContext::FinalizeCompletedRequests() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); #if AZ_STREAMER_ADD_EXTRA_PROFILING_INFO auto now = AZStd::chrono::system_clock::now(); @@ -218,10 +218,10 @@ namespace AZ bool isInternal = top->m_usage == FileRequest::Usage::Internal; { - AZ_PROFILE_SCOPE_STALL(AZ::Debug::ProfileCategory::AzCore, + AZ_PROFILE_SCOPE(AzCore, isInternal ? "Completion callback internal" : "Completion callback external"); top->m_onCompletion(*top); - AZ_PROFILE_INTERVAL_END(AZ::Debug::ProfileCategory::AzCore, top); + AZ_PROFILE_INTERVAL_END(AzCore, top); } if (parent) diff --git a/Code/Framework/AzCore/AzCore/IO/SystemFile.cpp b/Code/Framework/AzCore/AzCore/IO/SystemFile.cpp index d98b7e1d36..8de8b6b70f 100644 --- a/Code/Framework/AzCore/AzCore/IO/SystemFile.cpp +++ b/Code/Framework/AzCore/AzCore/IO/SystemFile.cpp @@ -9,7 +9,6 @@ #include #include #include -#include #include #include @@ -97,9 +96,6 @@ SystemFile& SystemFile::operator=(SystemFile&& other) bool SystemFile::Open(const char* fileName, int mode, int platformFlags) { - AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Open - %s", fileName); - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Open - %s", fileName); - if (fileName) // If we reopen the file we are allowed to have NULL file name { if (strlen(fileName) > m_fileName.max_size()) @@ -136,9 +132,6 @@ bool SystemFile::ReOpen(int mode, int platformFlags) void SystemFile::Close() { - AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Close - %s", m_fileName.c_str()); - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Close - %s", m_fileName.c_str()); - if (FileIOBus::HasHandlers()) { bool isHandled = false; @@ -154,8 +147,6 @@ void SystemFile::Close() void SystemFile::Seek(SeekSizeType offset, SeekMode mode) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Seek - %s:%i", m_fileName.c_str(), offset); - if (FileIOBus::HasHandlers()) { bool isHandled = false; @@ -181,16 +172,11 @@ bool SystemFile::Eof() AZ::u64 SystemFile::ModificationTime() { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::ModTime - %s", m_fileName.c_str()); - return Platform::ModificationTime(m_handle, this); } SystemFile::SizeType SystemFile::Read(SizeType byteSize, void* buffer) { - AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Read - %s:%i", m_fileName.c_str(), byteSize); - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Read - %s:%i", m_fileName.c_str(), byteSize); - if (FileIOBus::HasHandlers()) { SizeType numRead = 0; @@ -207,9 +193,6 @@ SystemFile::SizeType SystemFile::Read(SizeType byteSize, void* buffer) SystemFile::SizeType SystemFile::Write(const void* buffer, SizeType byteSize) { - AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Write - %s:%i", m_fileName.c_str(), byteSize); - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Write - %s:%i", m_fileName.c_str(), byteSize); - if (FileIOBus::HasHandlers()) { SizeType numWritten = 0; @@ -226,15 +209,11 @@ SystemFile::SizeType SystemFile::Write(const void* buffer, SizeType byteSize) void SystemFile::Flush() { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Flush - %s", m_fileName.c_str()); - Platform::Flush(m_handle, this); } SystemFile::SizeType SystemFile::Length() const { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Length - %s", m_fileName.c_str()); - return Platform::Length(m_handle, this); } @@ -253,36 +232,26 @@ SystemFile::SizeType SystemFile::DiskOffset() const bool SystemFile::Exists(const char* fileName) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Exists(util) - %s", fileName); - return Platform::Exists(fileName); } void SystemFile::FindFiles(const char* filter, FindFileCB cb) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::FindFiles(util) - %s", filter); - Platform::FindFiles(filter, cb); } AZ::u64 SystemFile::ModificationTime(const char* fileName) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::ModTime(util) - %s", fileName); - return Platform::ModificationTime(fileName); } SystemFile::SizeType SystemFile::Length(const char* fileName) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Length(util) - %s", fileName); - return Platform::Length(fileName); } SystemFile::SizeType SystemFile::Read(const char* fileName, void* buffer, SizeType byteSize, SizeType byteOffset) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Read(util) - %s:[%i,%i]", fileName, byteOffset, byteSize); - SizeType numBytesRead = 0; SystemFile f; if (f.Open(fileName, SF_OPEN_READ_ONLY)) @@ -305,8 +274,6 @@ SystemFile::SizeType SystemFile::Read(const char* fileName, void* buffer, SizeTy bool SystemFile::Delete(const char* fileName) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Delete(util) - %s", fileName); - if (!Exists(fileName)) { return false; @@ -317,8 +284,6 @@ bool SystemFile::Delete(const char* fileName) bool SystemFile::Rename(const char* sourceFileName, const char* targetFileName, bool overwrite) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Rename(util) - %s", sourceFileName); - if (!Exists(sourceFileName)) { return false; @@ -329,29 +294,21 @@ bool SystemFile::Rename(const char* sourceFileName, const char* targetFileName, bool SystemFile::IsWritable(const char* sourceFileName) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::IsWritable(util) - %s", sourceFileName); - return Platform::IsWritable(sourceFileName); } bool SystemFile::SetWritable(const char* sourceFileName, bool writable) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::SetWritable(util) - %s", sourceFileName); - return Platform::SetWritable(sourceFileName, writable); } bool SystemFile::CreateDir(const char* dirName) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::CreateDir(util) - %s", dirName); - return Platform::CreateDir(dirName); } bool SystemFile::DeleteDir(const char* dirName) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::DeleteDir(util) - %s", dirName); - return Platform::DeleteDir(dirName); } diff --git a/Code/Framework/AzCore/AzCore/Jobs/Algorithms.h b/Code/Framework/AzCore/AzCore/Jobs/Algorithms.h index 27efde7e64..a45846c107 100644 --- a/Code/Framework/AzCore/AzCore/Jobs/Algorithms.h +++ b/Code/Framework/AzCore/AzCore/Jobs/Algorithms.h @@ -13,11 +13,6 @@ #include -#ifdef AZ_COMPILER_MSVC -# pragma warning(push) -# pragma warning(disable: 4355) // 'this' : used in base member initializer list -#endif - // A reasonable define for a stack allocator size for the high level jobs. #define AZ_JOBS_DEFAULT_STACK_ALLOCATOR_SIZE AZStd::GetMax(2048,512 * AZStd::thread::hardware_concurrency()) @@ -769,9 +764,5 @@ namespace AZ } } -#ifdef AZ_COMPILER_MSVC -# pragma warning(pop) -#endif - #endif #pragma once diff --git a/Code/Framework/AzCore/AzCore/Jobs/Internal/JobManagerBase.cpp b/Code/Framework/AzCore/AzCore/Jobs/Internal/JobManagerBase.cpp index 130ff8da6b..a17290d8c5 100644 --- a/Code/Framework/AzCore/AzCore/Jobs/Internal/JobManagerBase.cpp +++ b/Code/Framework/AzCore/AzCore/Jobs/Internal/JobManagerBase.cpp @@ -23,10 +23,10 @@ void JobManagerBase::Process(Job* job) Job* dependent = job->GetDependent(); bool isDelete = job->IsAutoDelete(); - AZ_PROFILE_INTERVAL_END(AZ::Debug::ProfileCategory::JobManagerDetailed, job); + AZ_PROFILE_INTERVAL_END(JobManagerDetailed, job); if (!job->IsCancelled()) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "AZ::JobManagerBase::Process Job"); + AZ_PROFILE_SCOPE(AzCore, "AZ::JobManagerBase::Process Job"); job->Process(); } diff --git a/Code/Framework/AzCore/AzCore/Jobs/Internal/JobManagerWorkStealing.cpp b/Code/Framework/AzCore/AzCore/Jobs/Internal/JobManagerWorkStealing.cpp index bdf137f621..73fb4ecfe8 100644 --- a/Code/Framework/AzCore/AzCore/Jobs/Internal/JobManagerWorkStealing.cpp +++ b/Code/Framework/AzCore/AzCore/Jobs/Internal/JobManagerWorkStealing.cpp @@ -122,7 +122,7 @@ void JobManagerWorkStealing::AddPendingJob(Job* job) } #endif - AZ_PROFILE_INTERVAL_START(AZ::Debug::ProfileCategory::JobManagerDetailed, job, "AzCore Job Queued Awaiting Execute"); + AZ_PROFILE_INTERVAL_START(JobManagerDetailed, job, "AzCore Job Queued Awaiting Execute"); if (job->IsCompletion()) { @@ -371,7 +371,7 @@ void JobManagerWorkStealing::ProcessJobsInternal(ThreadInfo* info, Job* suspende { //no available work, so go to sleep (or we have already been signaled by another thread and will acquire the semaphore but not actually sleep) info->m_waitEvent.acquire(); - AZ_PROFILE_INTERVAL_END(AZ::Debug::ProfileCategory::JobManagerDetailed, info); + AZ_PROFILE_INTERVAL_END(JobManagerDetailed, info); if (m_quitRequested) { @@ -457,7 +457,7 @@ void JobManagerWorkStealing::ProcessJobsInternal(ThreadInfo* info, Job* suspende else { //attempt to steal a job from another thread's queue - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "JobManagerWorkStealing::ProcessJobsInternal:WorkStealing"); + AZ_PROFILE_SCOPE(AzCore, "JobManagerWorkStealing::ProcessJobsInternal:WorkStealing"); unsigned int numStealAttempts = 0; const unsigned int maxStealAttempts = (unsigned int)m_workerThreads.size() * 3; //try every thread a few times before giving up @@ -674,7 +674,7 @@ inline void JobManagerWorkStealing::ActivateWorker() m_numAvailableWorkers.fetch_sub(1, AZStd::memory_order_acq_rel); // resume the thread execution - AZ_PROFILE_INTERVAL_START(AZ::Debug::ProfileCategory::JobManagerDetailed, info, "AzCore WakeJobThread %d", info->m_workerId); + AZ_PROFILE_INTERVAL_START(JobManagerDetailed, info, "AzCore WakeJobThread %d", info->m_workerId); info->m_waitEvent.release(); return; } diff --git a/Code/Framework/AzCore/AzCore/Jobs/JobCompletion.h b/Code/Framework/AzCore/AzCore/Jobs/JobCompletion.h index 50776a30da..eda03bb5f6 100644 --- a/Code/Framework/AzCore/AzCore/Jobs/JobCompletion.h +++ b/Code/Framework/AzCore/AzCore/Jobs/JobCompletion.h @@ -33,7 +33,7 @@ namespace AZ */ void StartAndWaitForCompletion() { - AZ_PROFILE_FUNCTION_STALL(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // start the job Start(); diff --git a/Code/Framework/AzCore/AzCore/Jobs/LegacyJobExecutor.h b/Code/Framework/AzCore/AzCore/Jobs/LegacyJobExecutor.h index dd626a9829..8018cf409f 100644 --- a/Code/Framework/AzCore/AzCore/Jobs/LegacyJobExecutor.h +++ b/Code/Framework/AzCore/AzCore/Jobs/LegacyJobExecutor.h @@ -72,7 +72,7 @@ namespace AZ while (m_running) { - AZ_PROFILE_FUNCTION_STALL(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); m_completionCondition.wait(uniqueLock, [this] { return !this->m_running; }); } } diff --git a/Code/Framework/AzCore/AzCore/Math/Internal/SimdMathVec4_scalar.inl b/Code/Framework/AzCore/AzCore/Math/Internal/SimdMathVec4_scalar.inl index 7320c9be1c..484351c799 100644 --- a/Code/Framework/AzCore/AzCore/Math/Internal/SimdMathVec4_scalar.inl +++ b/Code/Framework/AzCore/AzCore/Math/Internal/SimdMathVec4_scalar.inl @@ -10,12 +10,9 @@ #include -#ifdef _MSC_VER // Unity builds on windows using the scalar backend are tripping some really strange warning behavior.. // Disable the warning so we can test the scalar implementation with unity on windows -# pragma warning (push) -# pragma warning (disable: 4723) // Potential divide by zero -#endif +AZ_PUSH_DISABLE_WARNING(4723, "-Wunknown-warning-option") // Potential divide by zero namespace AZ { @@ -1049,6 +1046,4 @@ namespace AZ } } -#ifdef _MSC_VER -# pragma warning (pop) -#endif +AZ_POP_DISABLE_WARNING \ No newline at end of file diff --git a/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp b/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp index eabfcd8cf0..edf481a590 100644 --- a/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp +++ b/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp @@ -57,7 +57,7 @@ namespace AZ float GetPerspectiveMatrixFOV(const Matrix4x4& m) { - return 2.0 * AZStd::atan(1.0f / m.GetElement(1, 1)); + return 2.0f * AZStd::atan(1.0f / m.GetElement(1, 1)); } Matrix4x4* MakeFrustumMatrixRH(Matrix4x4& out, float left, float right, float bottom, float top, float nearDist, float farDist, bool reverseDepth) diff --git a/Code/Framework/AzCore/AzCore/Math/Quaternion.h b/Code/Framework/AzCore/AzCore/Math/Quaternion.h index 36def91817..f2c266ed3e 100644 --- a/Code/Framework/AzCore/AzCore/Math/Quaternion.h +++ b/Code/Framework/AzCore/AzCore/Math/Quaternion.h @@ -246,10 +246,6 @@ namespace AZ //! Takes the absolute value of each component of the quaternion. Quaternion GetAbs() const; -#ifdef AZ_COMPILER_MSVC -# pragma warning(push) -# pragma warning(disable:4201) // anonymous union -#endif union { Simd::Vec4::FloatType m_value; @@ -263,9 +259,6 @@ namespace AZ float m_w; }; }; -#ifdef AZ_COMPILER_MSVC -# pragma warning(pop) -#endif }; //! Non-member functionality belonging to the AZ namespace diff --git a/Code/Framework/AzCore/AzCore/Math/Vector2.h b/Code/Framework/AzCore/AzCore/Math/Vector2.h index c667f48010..b2b1ceeb4d 100644 --- a/Code/Framework/AzCore/AzCore/Math/Vector2.h +++ b/Code/Framework/AzCore/AzCore/Math/Vector2.h @@ -281,10 +281,6 @@ namespace AZ private: -#ifdef AZ_COMPILER_MSVC -# pragma warning(push) -# pragma warning(disable:4201) // anonymous union -#endif union { Simd::Vec2::FloatType m_value; @@ -296,9 +292,6 @@ namespace AZ float m_y; }; }; -#ifdef AZ_COMPILER_MSVC -# pragma warning(pop) -#endif }; //! Allows pre-multiplying by a float. diff --git a/Code/Framework/AzCore/AzCore/Math/Vector3.h b/Code/Framework/AzCore/AzCore/Math/Vector3.h index 6b7ded5641..4bf0a18894 100644 --- a/Code/Framework/AzCore/AzCore/Math/Vector3.h +++ b/Code/Framework/AzCore/AzCore/Math/Vector3.h @@ -312,10 +312,6 @@ namespace AZ private: -#ifdef AZ_COMPILER_MSVC -# pragma warning(push) -# pragma warning(disable:4201) // anonymous union -#endif union { Simd::Vec3::FloatType m_value; @@ -328,9 +324,6 @@ namespace AZ float m_z; }; }; -#ifdef AZ_COMPILER_MSVC -# pragma warning(pop) -#endif }; //! Non member functionality belonging to the AZ namespace. diff --git a/Code/Framework/AzCore/AzCore/Math/Vector4.h b/Code/Framework/AzCore/AzCore/Math/Vector4.h index 7ae0350805..6bd67e8831 100644 --- a/Code/Framework/AzCore/AzCore/Math/Vector4.h +++ b/Code/Framework/AzCore/AzCore/Math/Vector4.h @@ -283,11 +283,6 @@ namespace AZ Simd::Vec4::FloatType GetSimdValue() const; protected: - -#ifdef AZ_COMPILER_MSVC -# pragma warning(push) -# pragma warning(disable:4201) // anonymous union -#endif union { Simd::Vec4::FloatType m_value; @@ -301,9 +296,6 @@ namespace AZ float m_w; }; }; -#ifdef AZ_COMPILER_MSVC -# pragma warning(pop) -#endif }; } diff --git a/Code/Framework/AzCore/AzCore/Memory/AllocationRecords.cpp b/Code/Framework/AzCore/AzCore/Memory/AllocationRecords.cpp index fc75f3c37e..7d644c6917 100644 --- a/Code/Framework/AzCore/AzCore/Memory/AllocationRecords.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/AllocationRecords.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include diff --git a/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h b/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h index 08e8098dac..e9d001aec3 100644 --- a/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h @@ -12,9 +12,7 @@ #include #include #include -#include - -#include +#include namespace AZ { @@ -82,7 +80,7 @@ namespace AZ if (ProfileAllocations) { - AZ_PROFILE_MEMORY_ALLOC_EX(AZ::Debug::ProfileCategory::MemoryReserved, fileName, lineNum, ptr, byteSize, name ? name : GetName()); + AZ_PROFILE_MEMORY_ALLOC_EX(MemoryReserved, fileName, lineNum, ptr, byteSize, name ? name : GetName()); AZ_MEMORY_PROFILE(ProfileAllocation(ptr, byteSize, alignment, name, fileName, lineNum, suppressStackRecord)); } @@ -102,7 +100,7 @@ namespace AZ if (ProfileAllocations) { - AZ_PROFILE_MEMORY_FREE(AZ::Debug::ProfileCategory::MemoryReserved, ptr); + AZ_PROFILE_MEMORY_FREE(MemoryReserved, ptr); AZ_MEMORY_PROFILE(ProfileDeallocation(ptr, byteSize, alignment, nullptr)); } @@ -128,7 +126,7 @@ namespace AZ { if (ProfileAllocations) { - AZ_PROFILE_MEMORY_FREE(AZ::Debug::ProfileCategory::MemoryReserved, ptr); + AZ_PROFILE_MEMORY_FREE(MemoryReserved, ptr); } newSize = MemorySizeAdjustedUp(newSize); @@ -142,7 +140,7 @@ namespace AZ if (ProfileAllocations) { - AZ_PROFILE_MEMORY_ALLOC(AZ::Debug::ProfileCategory::MemoryReserved, newPtr, newSize, GetName()); + AZ_PROFILE_MEMORY_ALLOC(MemoryReserved, newPtr, newSize, GetName()); AZ_MEMORY_PROFILE(ProfileReallocationEnd(ptr, newPtr, newSize, newAlignment)); } diff --git a/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.cpp b/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.cpp index ada6c8f330..0fb64915dc 100644 --- a/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.cpp @@ -17,15 +17,23 @@ #include -#define AZCORE_SYS_ALLOCATOR_HPPA // If you disable this make sure you start building the heapschema.cpp -//#define AZCORE_SYS_ALLOCATOR_MALLOC +#define AZCORE_SYSTEM_ALLOCATOR_HPHA 1 +#define AZCORE_SYSTEM_ALLOCATOR_MALLOC 2 +#define AZCORE_SYSTEM_ALLOCATOR_HEAP 3 -#ifdef AZCORE_SYS_ALLOCATOR_HPPA -# include -#elif defined(AZCORE_SYS_ALLOCATOR_MALLOC) -#include +#if !defined(AZCORE_SYSTEM_ALLOCATOR) + // define the default + #define AZCORE_SYSTEM_ALLOCATOR AZCORE_SYSTEM_ALLOCATOR_HPHA +#endif + +#if AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HPHA + #include +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_MALLOC + #include +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HEAP + #include #else -# include + #error "Invalid allocator selected for SystemAllocator" #endif @@ -34,12 +42,12 @@ using namespace AZ; ////////////////////////////////////////////////////////////////////////// // Globals - we use global storage for the first memory schema, since we can't use dynamic memory! static bool g_isSystemSchemaUsed = false; -#ifdef AZCORE_SYS_ALLOCATOR_HPPA -static AZStd::aligned_storage::value>::type g_systemSchema; -#elif defined(AZCORE_SYS_ALLOCATOR_MALLOC) -static AZStd::aligned_storage::value>::type g_systemSchema; -#else -static AZStd::aligned_storage::value>::type g_systemSchema; +#if AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HPHA + static AZStd::aligned_storage::value>::type g_systemSchema; +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_MALLOC + static AZStd::aligned_storage::value>::type g_systemSchema; +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HEAP + static AZStd::aligned_storage::value>::type g_systemSchema; #endif ////////////////////////////////////////////////////////////////////////// @@ -97,9 +105,9 @@ SystemAllocator::Create(const Descriptor& desc) else { m_isCustom = false; -#ifdef AZCORE_SYS_ALLOCATOR_HPPA - HphaSchema::Descriptor heapDesc; - heapDesc.m_pageSize = desc.m_heap.m_pageSize; +#if AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HPHA + HphaSchema::Descriptor heapDesc; + heapDesc.m_pageSize = desc.m_heap.m_pageSize; heapDesc.m_poolPageSize = desc.m_heap.m_poolPageSize; AZ_Assert(desc.m_heap.m_numFixedMemoryBlocks <= 1, "We support max1 memory block at the moment!"); if (desc.m_heap.m_numFixedMemoryBlocks > 0) @@ -111,11 +119,10 @@ SystemAllocator::Create(const Descriptor& desc) heapDesc.m_isPoolAllocations = desc.m_heap.m_isPoolAllocations; // Fix SystemAllocator from growing in small chunks heapDesc.m_systemChunkSize = desc.m_heap.m_systemChunkSize; - -#elif defined(AZCORE_SYS_ALLOCATOR_MALLOC) +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_MALLOC MallocSchema::Descriptor heapDesc; -#else - HeapSchema::Descriptor heapDesc; +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HEAP + HeapSchema::Descriptor heapDesc; memcpy(heapDesc.m_memoryBlocks, desc.m_heap.m_memoryBlocks, sizeof(heapDesc.m_memoryBlocks)); memcpy(heapDesc.m_memoryBlocksByteSize, desc.m_heap.m_memoryBlocksByteSize, sizeof(heapDesc.m_memoryBlocksByteSize)); heapDesc.m_numMemoryBlocks = desc.m_heap.m_numMemoryBlocks; @@ -124,11 +131,11 @@ SystemAllocator::Create(const Descriptor& desc) { AZ_Assert(!g_isSystemSchemaUsed, "AZ::SystemAllocator MUST be created first! It's the source of all allocations!"); -#ifdef AZCORE_SYS_ALLOCATOR_HPPA +#if AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HPHA m_allocator = new(&g_systemSchema)HphaSchema(heapDesc); -#elif defined(AZCORE_SYS_ALLOCATOR_MALLOC) +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_MALLOC m_allocator = new(&g_systemSchema)MallocSchema(heapDesc); -#else +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HEAP m_allocator = new(&g_systemSchema)HeapSchema(heapDesc); #endif g_isSystemSchemaUsed = true; @@ -139,14 +146,13 @@ SystemAllocator::Create(const Descriptor& desc) // this class should be inheriting from SystemAllocator AZ_Assert(AllocatorInstance::IsReady(), "System allocator must be created before any other allocator! They allocate from it."); -#ifdef AZCORE_SYS_ALLOCATOR_HPPA +#if AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HPHA m_allocator = azcreate(HphaSchema, (heapDesc), SystemAllocator); -#elif defined(AZCORE_SYS_ALLOCATOR_MALLOC) +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_MALLOC m_allocator = azcreate(MallocSchema, (heapDesc), SystemAllocator); -#else +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HEAP m_allocator = azcreate(HeapSchema, (heapDesc), SystemAllocator); #endif - if (m_allocator == NULL) { isReady = false; @@ -178,11 +184,11 @@ SystemAllocator::Destroy() { if ((void*)m_allocator == (void*)&g_systemSchema) { -#ifdef AZCORE_SYS_ALLOCATOR_HPPA +#if AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HPHA static_cast(m_allocator)->~HphaSchema(); -#elif defined(AZCORE_SYS_ALLOCATOR_MALLOC) +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_MALLOC static_cast(m_allocator)->~MallocSchema(); -#else +#elif AZCORE_SYSTEM_ALLOCATOR == AZCORE_SYSTEM_ALLOCATOR_HEAP static_cast(m_allocator)->~HeapSchema(); #endif g_isSystemSchemaUsed = false; @@ -254,7 +260,7 @@ SystemAllocator::Allocate(size_type byteSize, size_type alignment, int flags, co AZ_Assert(address != 0, "SystemAllocator: Failed to allocate %d bytes aligned on %d (flags: 0x%08x) %s : %s (%d)!", byteSize, alignment, flags, name ? name : "(no name)", fileName ? fileName : "(no file name)", lineNum); - AZ_PROFILE_MEMORY_ALLOC_EX(AZ::Debug::ProfileCategory::MemoryReserved, fileName, lineNum, address, byteSize, name); + AZ_PROFILE_MEMORY_ALLOC_EX(MemoryReserved, fileName, lineNum, address, byteSize, name); AZ_MEMORY_PROFILE(ProfileAllocation(address, byteSize, alignment, name, fileName, lineNum, suppressStackRecord + 1)); return address; @@ -268,7 +274,7 @@ void SystemAllocator::DeAllocate(pointer_type ptr, size_type byteSize, size_type alignment) { byteSize = MemorySizeAdjustedUp(byteSize); - AZ_PROFILE_MEMORY_FREE(AZ::Debug::ProfileCategory::MemoryReserved, ptr); + AZ_PROFILE_MEMORY_FREE(MemoryReserved, ptr); AZ_MEMORY_PROFILE(ProfileDeallocation(ptr, byteSize, alignment, nullptr)); m_allocator->DeAllocate(ptr, byteSize, alignment); } @@ -283,9 +289,9 @@ SystemAllocator::ReAllocate(pointer_type ptr, size_type newSize, size_type newAl newSize = MemorySizeAdjustedUp(newSize); AZ_MEMORY_PROFILE(ProfileReallocationBegin(ptr, newSize)); - AZ_PROFILE_MEMORY_FREE(AZ::Debug::ProfileCategory::MemoryReserved, ptr); + AZ_PROFILE_MEMORY_FREE(MemoryReserved, ptr); pointer_type newAddress = m_allocator->ReAllocate(ptr, newSize, newAlignment); - AZ_PROFILE_MEMORY_ALLOC(AZ::Debug::ProfileCategory::MemoryReserved, newAddress, newSize, "SystemAllocator realloc"); + AZ_PROFILE_MEMORY_ALLOC(MemoryReserved, newAddress, newSize, "SystemAllocator realloc"); AZ_MEMORY_PROFILE(ProfileReallocationEnd(ptr, newAddress, newSize, newAlignment)); return newAddress; diff --git a/Code/Framework/AzCore/AzCore/Memory/dlmalloc.inl b/Code/Framework/AzCore/AzCore/Memory/dlmalloc.inl index 861e2de7ac..3756fbb36c 100644 --- a/Code/Framework/AzCore/AzCore/Memory/dlmalloc.inl +++ b/Code/Framework/AzCore/AzCore/Memory/dlmalloc.inl @@ -1294,14 +1294,6 @@ int mspace_mallopt(int, int); /*------------------------------ internal #includes ---------------------- */ -#ifdef WIN32 -#pragma warning(push) -#pragma warning( disable : 4146 ) /* no "unsigned" warnings */ -# ifdef AZ_PLATFORM_WINDOWS -# pragma warning( disable : 4267 ) -# endif -#endif /* WIN32 */ - #include /* for printing in malloc_stats */ #ifndef LACKS_ERRNO_H @@ -2170,7 +2162,7 @@ typedef unsigned int flag_t; /* The type of various bit flag sets */ #define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A))) /* Bounds on request (not chunk) sizes. */ -#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2) +#define MAX_REQUEST ((~MIN_CHUNK_SIZE + 1) << 2) #define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE) /* pad request bytes into a usable size */ @@ -2881,10 +2873,10 @@ static size_t traverse_and_check(mstate m); #define treemap_is_marked(M, i) ((M)->treemap & idx2bit(i)) /* isolate the least set bit of a bitmap */ -#define least_bit(x) ((x) & - (x)) +#define least_bit(x) ((x) & (~(x)+1)) /* mask with all bits to left of least bit of x on */ -#define left_bits(x) ((x << 1) | -(x << 1)) +#define left_bits(x) ((x << 1) | (~(x << 1)+1)) /* mask with all bits to left of or equal to least bit of x on */ #define same_or_left_bits(x) ((x) | -(x)) @@ -4528,7 +4520,7 @@ static int sys_trim(mstate m, size_t pad) static void* tmalloc_large(mstate m, size_t nb) { tchunkptr v = 0; - size_t rsize = -nb; /* Unsigned negation */ + size_t rsize = ~nb+1; /* Unsigned negation */ tchunkptr t; bindex_t idx; compute_tree_index(nb, idx); @@ -4807,7 +4799,7 @@ static void* internal_memalign(mstate m, size_t alignment, size_t bytes) char* br = (char*)mem2chunk((size_t)(((size_t)(mem + alignment - SIZE_T_ONE)) & - - alignment)); + (~alignment+1))); char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE) ? br : br + alignment; mchunkptr newp = (mchunkptr)pos; @@ -5489,7 +5481,7 @@ postaction: size_t msize; ensure_initialization(); msize = pad_request(sizeof(struct malloc_state)); - if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) + if (capacity < (~(msize + TOP_FOOT_SIZE + mparams.page_size)+1)) { size_t rs = ((capacity == 0) ? mparams.granularity : (capacity + TOP_FOOT_SIZE + msize)); @@ -5512,7 +5504,7 @@ postaction: ensure_initialization(); msize = pad_request(sizeof(struct malloc_state)); if (capacity > msize + TOP_FOOT_SIZE && - capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) + capacity < (~(msize + TOP_FOOT_SIZE + mparams.page_size)+1)) { m = init_user_mstate((char*)base, capacity); m->seg.sflags = EXTERN_BIT; @@ -6367,6 +6359,3 @@ postaction: */ -#ifdef WIN32 -#pragma warning(pop) -#endif /* WIN32 */ diff --git a/Code/Framework/AzCore/AzCore/Module/Module.h b/Code/Framework/AzCore/AzCore/Module/Module.h index 2c87b4f0fb..a4843f002c 100644 --- a/Code/Framework/AzCore/AzCore/Module/Module.h +++ b/Code/Framework/AzCore/AzCore/Module/Module.h @@ -9,7 +9,6 @@ #define AZCORE_MODULE_INCLUDE_H 1 #include -#include #include #include #include @@ -78,9 +77,6 @@ namespace AZ protected: AZStd::list m_descriptors; - - private: - AZ::Debug::ProfileModuleInitializer m_moduleProfilerInit; }; } // namespace AZ @@ -98,19 +94,26 @@ namespace AZ /// /// \param MODULE_NAME Name of module. /// \param MODULE_CLASSNAME Name of AZ::Module class (include namespace). +/// +/// Execute any deferred console commands after linking any new deferred functors +/// This allows deferred console commands defined within the module to now execute +/// at this point now that the module has been loaded #if defined(AZ_MONOLITHIC_BUILD) # define AZ_DECLARE_MODULE_CLASS(MODULE_NAME, MODULE_CLASSNAME) \ extern "C" AZ::Module * CreateModuleClass_##MODULE_NAME() { return aznew MODULE_CLASSNAME; } #else # define AZ_DECLARE_MODULE_CLASS(MODULE_NAME, MODULE_CLASSNAME) \ AZ_DECLARE_MODULE_INITIALIZATION \ - extern "C" AZ_DLL_EXPORT AZ::Module * CreateModuleClass() \ + extern "C" AZ_DLL_EXPORT AZ::Module* CreateModuleClass() \ { \ - AZ::ConsoleFunctorBase*& deferredHead = AZ::ConsoleFunctorBase::GetDeferredHead(); \ - AZ::Interface::Get()->LinkDeferredFunctors(deferredHead); \ + if (auto console = AZ::Interface::Get(); console != nullptr) \ + { \ + console->LinkDeferredFunctors(AZ::ConsoleFunctorBase::GetDeferredHead()); \ + console->ExecuteDeferredConsoleCommands(); \ + } \ return aznew MODULE_CLASSNAME; \ } \ - extern "C" AZ_DLL_EXPORT void DestroyModuleClass(AZ::Module * module) { delete module; } + extern "C" AZ_DLL_EXPORT void DestroyModuleClass(AZ::Module* module) { delete module; } #endif #endif // AZCORE_MODULE_INCLUDE_H diff --git a/Code/Framework/AzCore/AzCore/Name/Internal/NameData.cpp b/Code/Framework/AzCore/AzCore/Name/Internal/NameData.cpp index cfbd640762..0086e68c6d 100644 --- a/Code/Framework/AzCore/AzCore/Name/Internal/NameData.cpp +++ b/Code/Framework/AzCore/AzCore/Name/Internal/NameData.cpp @@ -36,10 +36,13 @@ namespace AZ void NameData::release() { + // this could be released after we decrement the counter, therefore we will + // base the release on the hash which is stable + Hash hash = m_hash; AZ_Assert(m_useCount > 0, "m_useCount is already 0!"); if (m_useCount.fetch_sub(1) == 1) { - AZ::NameDictionary::Instance().TryReleaseName(this); + AZ::NameDictionary::Instance().TryReleaseName(hash); } } } diff --git a/Code/Framework/AzCore/AzCore/Name/Name.h b/Code/Framework/AzCore/AzCore/Name/Name.h index 46a9b5b7cc..16179c9cde 100644 --- a/Code/Framework/AzCore/AzCore/Name/Name.h +++ b/Code/Framework/AzCore/AzCore/Name/Name.h @@ -10,6 +10,11 @@ #include +namespace UnitTest +{ + class NameTest; +} + namespace AZ { class NameDictionary; @@ -29,6 +34,7 @@ namespace AZ class Name { friend NameDictionary; + friend UnitTest::NameTest; public: using Hash = Internal::NameData::Hash; diff --git a/Code/Framework/AzCore/AzCore/Name/NameDictionary.cpp b/Code/Framework/AzCore/AzCore/Name/NameDictionary.cpp index c04ae0ea5e..cf85e0f4e0 100644 --- a/Code/Framework/AzCore/AzCore/Name/NameDictionary.cpp +++ b/Code/Framework/AzCore/AzCore/Name/NameDictionary.cpp @@ -166,7 +166,7 @@ namespace AZ } } - void NameDictionary::TryReleaseName(Internal::NameData* nameData) + void NameDictionary::TryReleaseName(Name::Hash hash) { // Note that we don't remove NameData from the dictionary if it has been involved in a collision. // This avoids specific edge cases where a Name object could get an incorrect hash value. Consider @@ -179,15 +179,24 @@ namespace AZ // the dictionary *again*, this time with hash value 1000. Name objects pointing to the original // entry and Name objects pointing to the new entry will fail comparison operations. - // Early exit to avoid locking the mutex unnecessarily. - if (nameData->m_hashCollision) - { - return; - } AZStd::unique_lock lock(m_sharedMutex); - // Check m_hashCollision again inside the m_sharedMutex because a new collision could have happened + auto dictIt = m_dictionary.find(hash); + if (dictIt == m_dictionary.end()) + { + // This check is to safeguard around the following scenario + // T1, gets into TryReleaseName + // T2 gets into MakeName, acquires the lock, returns a new Name that increments the counter + // T2 deletes the Name decrements the counter, gets into TryReleaseName + // T1 gets the lock, goes to the compare_exchange if and has a counter of 0, deletes + // Then T2 continues, gets the lock and crashes because nameData was deleted + return; + } + + Internal::NameData* nameData = dictIt->second; + + // Check m_hashCollision inside the m_sharedMutex because a new collision could have happened // on another thread before taking the lock. if (nameData->m_hashCollision) { diff --git a/Code/Framework/AzCore/AzCore/Name/NameDictionary.h b/Code/Framework/AzCore/AzCore/Name/NameDictionary.h index 7d4ffe80f6..fa13dbd682 100644 --- a/Code/Framework/AzCore/AzCore/Name/NameDictionary.h +++ b/Code/Framework/AzCore/AzCore/Name/NameDictionary.h @@ -83,7 +83,7 @@ namespace AZ // Attempts to release the name from the dictionary, but checks to make sure // a reference wasn't taken by another thread. - void TryReleaseName(Internal::NameData* data); + void TryReleaseName(Name::Hash hash); ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Framework/AzCore/AzCore/PlatformDef.h b/Code/Framework/AzCore/AzCore/PlatformDef.h index 55126fdf4c..47f45931ba 100644 --- a/Code/Framework/AzCore/AzCore/PlatformDef.h +++ b/Code/Framework/AzCore/AzCore/PlatformDef.h @@ -87,9 +87,6 @@ #define AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING AZ_POP_DISABLE_WARNING # define AZ_FORCE_INLINE __forceinline -#if !defined(_DEBUG) -# pragma warning(disable:4714) //warning C4714 marked as __forceinline not inlined. Sadly this happens when LTCG during linking. We tried to NOT use force inline but VC 2012 is bad at inlining. -#endif /// Aligns a declaration. # define AZ_ALIGN(_decl, _alignment) \ diff --git a/Code/Framework/AzCore/AzCore/RTTI/BehaviorContext.h b/Code/Framework/AzCore/AzCore/RTTI/BehaviorContext.h index 42fc762769..1c81a15bda 100644 --- a/Code/Framework/AzCore/AzCore/RTTI/BehaviorContext.h +++ b/Code/Framework/AzCore/AzCore/RTTI/BehaviorContext.h @@ -24,11 +24,6 @@ #include #include -#if defined(AZ_COMPILER_MSVC) -# pragma warning(push) -# pragma warning(disable: 4127) // conditional expression is constant -#endif - namespace AZStd { template @@ -1855,7 +1850,7 @@ namespace AZ * { * // do any conversion of caching of the "data" here and forward this to behavior (often the reason for this is that you can't pass everything to behavior * // plus behavior can't really handle all constructs pointer to pointer, rvalues, etc. as they don't make sense for most script environments - * int result = 0; // set the default value for your result if the behavior if there is no implmentation + * int result = 0; // set the default value for your result if the behavior if there is no implementation * // The AZ_EBUS_BEHAVIOR_BINDER defines FN_EventName for each index. You can also cache it yourself (but it's slower), static int cacheIndex = GetFunctionIndex("OnEvent1"); and use that . * CallResult(result, FN_OnEvent1, data); // forward to the binding (there can be none, this is why we need to always have properly set result, when there is one) * return result; // return the result like you will in any normal EBus even with result @@ -4507,7 +4502,7 @@ namespace AZ params.resize(sizeof...(Args) + eBehaviorBusForwarderEventIndices::ParameterFirst); SetParameters(¶ms[eBehaviorBusForwarderEventIndices::Result], nullptr); SetParameters(¶ms[eBehaviorBusForwarderEventIndices::UserData], nullptr); - if (sizeof...(Args) > 0) + if constexpr (sizeof...(Args) > 0) { SetParameters(¶ms[eBehaviorBusForwarderEventIndices::ParameterFirst], nullptr); } @@ -4872,10 +4867,6 @@ namespace AZ } // namespace Internal } // namespace AZ -#if defined(AZ_COMPILER_MSVC) -# pragma warning(pop) -#endif - // pull AzStd on demand reflection #include #include diff --git a/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp b/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp index fa61a225c8..a83232c8cb 100644 --- a/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp +++ b/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp @@ -287,14 +287,6 @@ void ScriptSystemComponent::OnSystemTick() contextContainer.m_context->GetDebugContext()->ProcessDebugCommands(); } -#ifdef AZ_PROFILE_TELEMETRY - if (contextContainer.m_context->GetId() == ScriptContextIds::DefaultScriptContextId) - { - size_t memoryUsageBytes = contextContainer.m_context->GetMemoryUsage(); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Script, memoryUsageBytes / 1024.0, "Script Memory (KB)"); - } -#endif // AZ_PROFILE_TELEMETRY - contextContainer.m_context->GarbageCollectStep(contextContainer.m_garbageCollectorSteps); } } diff --git a/Code/Framework/AzCore/AzCore/Serialization/DataPatch.cpp b/Code/Framework/AzCore/AzCore/Serialization/DataPatch.cpp index 12bb474cfe..edc0e8398b 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/DataPatch.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/DataPatch.cpp @@ -143,7 +143,7 @@ namespace AZ //========================================================================= void DataNodeTree::Build(const void* rootClassPtr, const Uuid& rootClassId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); m_root.Reset(); m_currentNode = nullptr; @@ -1400,7 +1400,7 @@ namespace AZ AddressTypeElement AddressTypeSerializer::LoadAddressElementFromPath(const AZStd::string& pathElement) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // AddressTypeElement default constructor defaults to an invalid addressElement AddressTypeElement addressElement; @@ -1485,13 +1485,13 @@ namespace AZ /// Load the class data from a stream. bool AddressTypeSerializer::Load(void* classPtr, IO::GenericStream& stream, unsigned int version, bool isDataBigEndian /*= false*/) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); (void)isDataBigEndian; constexpr unsigned int version1PathAddress = 1; if (version < version1PathAddress) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "AddressTypeSerializer::Load::LegacyUpgrade"); + AZ_PROFILE_SCOPE(AzCore, "AddressTypeSerializer::Load::LegacyUpgrade"); // Grab the AddressType object to be filled AddressType* address = reinterpret_cast(classPtr); address->clear(); @@ -1516,7 +1516,7 @@ namespace AZ } else { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "AddressTypeSerializer::Load::CurrentFlow"); + AZ_PROFILE_SCOPE(AzCore, "AddressTypeSerializer::Load::CurrentFlow"); // Grab the AddressType object to be filled AddressType* address = reinterpret_cast(classPtr); address->clear(); @@ -1749,7 +1749,7 @@ namespace AZ const FlagsMap& targetFlagsMap, SerializeContext* context) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!source || !target) { @@ -1804,7 +1804,7 @@ namespace AZ targetTree.Build(target, targetClassId); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "DataPatch::Create:RecursiveCallToCompareElements"); + AZ_PROFILE_SCOPE(AzCore, "DataPatch::Create:RecursiveCallToCompareElements"); sourceTree.CompareElements( &sourceTree.m_root, @@ -1829,7 +1829,7 @@ namespace AZ const FlagsMap& sourceFlagsMap, const FlagsMap& targetFlagsMap) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!source) { @@ -1870,7 +1870,7 @@ namespace AZ { // Loop over the original data patch and make a copy of the key value pair - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "DataPatch::Apply:UpgradeDataPatch"); + AZ_PROFILE_SCOPE(AzCore, "DataPatch::Apply:UpgradeDataPatch"); // Copy of the patch element is purposefully being created here(notice no ampersand) so that the UpgradeDataPatch // function can modify the key and insert it into the fixed patch map for (PatchMap::value_type patch : m_patch) @@ -1883,7 +1883,7 @@ namespace AZ // Build a mapping of child patches for quick look-up: [parent patch address] -> [list of patches for child elements (parentAddress + one more address element)] ChildPatchMap childPatchMap; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "DataPatch::Apply:GenerateChildPatchMap"); + AZ_PROFILE_SCOPE(AzCore, "DataPatch::Apply:GenerateChildPatchMap"); for (auto& patch : fixedPatch) { AddressType parentAddress = patch.first; @@ -1921,7 +1921,7 @@ namespace AZ } } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "DataPatch::Apply:RecursiveCallToApplyToElements"); + AZ_PROFILE_SCOPE(AzCore, "DataPatch::Apply:RecursiveCallToApplyToElements"); int rootContainerElementCounter = 0; result = DataNodeTree::ApplyToElements( @@ -2015,7 +2015,7 @@ namespace AZ */ bool LegacyDataPatchConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ::Outcome conversionResult = LegacyDataPatchConverter_Impl(context, classElement); if (!conversionResult.IsSuccess()) @@ -2043,7 +2043,7 @@ namespace AZ */ AZ::Outcome LegacyDataPatchConverter_Impl(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // Pull the targetClassId value out of the class element before it gets cleared when converting the DataPatch TypeId AZ::TypeId targetClassTypeId; if (!classElement.GetChildData(AZ_CRC("m_targetClassId", 0xcabab9dc), targetClassTypeId)) diff --git a/Code/Framework/AzCore/AzCore/Serialization/EditContext.h b/Code/Framework/AzCore/AzCore/Serialization/EditContext.h index 492550f266..a08e971ac4 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/EditContext.h +++ b/Code/Framework/AzCore/AzCore/Serialization/EditContext.h @@ -656,26 +656,25 @@ namespace AZ using ElementType = typename AZStd::Utils::if_c::value, typename ElementTypeInfo::Type, typename ElementTypeInfo::ElementType>::type; AZ_Assert(m_classData->m_typeId == AzTypeInfo::Uuid(), "Data element (%s) belongs to a different class!", AzTypeInfo::Name()); -#if defined(AZ_COMPILER_MSVC) -# pragma warning(push) -# pragma warning(disable: 4127) // conditional expression is constant -#endif const SerializeContext::ClassData* classData = m_context->m_serializeContext.FindClassData(AzTypeInfo::Uuid()); if (classData && classData->m_editData) { return DataElement(uiId, memberVariable, classData->m_editData->m_name, classData->m_editData->m_description); } - else if (AZStd::is_enum::value && AzTypeInfo::Name() != nullptr) + else { - auto enumIter = m_context->m_enumData.find(AzTypeInfo::Uuid()); - if (enumIter != m_context->m_enumData.end()) + if constexpr (AZStd::is_enum::value) { - return DataElement(uiId, memberVariable, enumIter->second.m_name, enumIter->second.m_description); + if (AzTypeInfo::Name() != nullptr) + { + auto enumIter = m_context->m_enumData.find(AzTypeInfo::Uuid()); + if (enumIter != m_context->m_enumData.end()) + { + return DataElement(uiId, memberVariable, enumIter->second.m_name, enumIter->second.m_description); + } + } } } -#if defined(AZ_COMPILER_MSVC) -# pragma warning(pop) -#endif const char* typeName = AzTypeInfo::Name(); return DataElement(uiId, memberVariable, typeName, typeName); diff --git a/Code/Framework/AzCore/AzCore/Serialization/ObjectStream.cpp b/Code/Framework/AzCore/AzCore/Serialization/ObjectStream.cpp index e0ee18633b..73ab174699 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/ObjectStream.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/ObjectStream.cpp @@ -786,7 +786,7 @@ namespace AZ // Serializable leaf element. else if (classData->m_serializer) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "ObjectStreamImpl::LoadClass Load"); + AZ_PROFILE_SCOPE(AzCore, "ObjectStreamImpl::LoadClass Load"); // Wrap the stream IO::GenericStream* currentStream = &m_inStream; @@ -1929,7 +1929,7 @@ namespace AZ //========================================================================= bool ObjectStreamImpl::Start() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); ++m_pending; diff --git a/Code/Framework/AzCore/AzCore/Serialization/SerializationUtils.cpp b/Code/Framework/AzCore/AzCore/Serialization/SerializationUtils.cpp index fdc7cd94b6..c8e6c28679 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/SerializationUtils.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/SerializationUtils.cpp @@ -24,7 +24,7 @@ namespace AZ { bool LoadObjectFromStreamInPlace(IO::GenericStream& stream, AZ::SerializeContext* context, const SerializeContext::ClassData* objectClassData, void* targetPointer, const FilterDescriptor& filterDesc) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Assert(objectClassData, "Class data is required."); @@ -72,7 +72,7 @@ namespace AZ bool LoadObjectFromStreamInPlace(IO::GenericStream& stream, AZ::SerializeContext* context, const Uuid& targetClassId, void* targetPointer, const FilterDescriptor& filterDesc) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!context) { @@ -111,7 +111,7 @@ namespace AZ void* LoadObjectFromStream(IO::GenericStream& stream, AZ::SerializeContext* context, const Uuid* targetClassId, const FilterDescriptor& filterDesc) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!context) { @@ -169,7 +169,7 @@ namespace AZ void* LoadObjectFromFile(const AZStd::string& filePath, const Uuid& targetClassId, SerializeContext* context, const FilterDescriptor& filterDesc, int /*platformFlags*/) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ::IO::FileIOStream fileStream; if (!fileStream.Open(filePath.c_str(), IO::OpenMode::ModeRead | IO::OpenMode::ModeBinary)) @@ -183,7 +183,7 @@ namespace AZ bool SaveObjectToStream(IO::GenericStream& stream, DataStream::StreamType streamType, const void* classPtr, const Uuid& classId, SerializeContext* context, const SerializeContext::ClassData* classData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!context) { @@ -243,7 +243,7 @@ namespace AZ bool SaveObjectToFile(const AZStd::string& filePath, DataStream::StreamType fileType, const void* classPtr, const Uuid& classId, SerializeContext* context, int platformFlags) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // \note This is ok for tools, but we should use the streamer to write objects directly (no memory store) AZStd::vector dstData; diff --git a/Code/Framework/AzCore/AzCore/Slice/SliceComponent.cpp b/Code/Framework/AzCore/AzCore/Slice/SliceComponent.cpp index 4cfccfa8bb..23a197b2ad 100644 --- a/Code/Framework/AzCore/AzCore/Slice/SliceComponent.cpp +++ b/Code/Framework/AzCore/AzCore/Slice/SliceComponent.cpp @@ -198,7 +198,7 @@ namespace AZ const EntityIdToEntityIdMap* remapFromIdToId/*=nullptr*/, const DataFlagsTransformFunction& dataFlagsTransformFn/*=nullptr*/) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); for (const auto& entityIdFlagsMapPair : from.m_entityToDataFlags) { @@ -240,7 +240,7 @@ namespace AZ //========================================================================= DataPatch::FlagsMap SliceComponent::DataFlagsPerEntity::GetDataFlagsForPatching(const EntityIdToEntityIdMap* remapFromIdToId /*=nullptr*/) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // Collect together data flags from all entities DataPatch::FlagsMap dataFlagsForAllEntities; @@ -423,7 +423,7 @@ namespace AZ //========================================================================= void SliceComponent::DataFlagsPerEntity::Cleanup(const EntityList& validEntities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); EntityIdSet validEntityIds; for (const Entity* entity : validEntities) @@ -677,7 +677,7 @@ namespace AZ //========================================================================= SliceComponent::SliceInstance* SliceComponent::SliceReference::PrepareCreateInstance(const SliceInstanceId& sliceInstanceId, bool allowUninstantiated) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // create an empty instance (just copy of the existing data) SliceInstance* instance = CreateEmptyInstance(sliceInstanceId); @@ -737,7 +737,7 @@ namespace AZ AZ::SerializeContext* serializeContext, const AZ::IdUtils::Remapper::IdMapper& customMapper) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!remapContainer) { @@ -808,7 +808,7 @@ namespace AZ SliceComponent::SliceInstance* SliceComponent::SliceReference::CreateInstance(const AZ::IdUtils::Remapper::IdMapper& customMapper, SliceInstanceId sliceInstanceId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // Validate that we are able to create an instance at this time // If we are instantiated then this includes verifying that we have a valid component and asset @@ -842,7 +842,7 @@ namespace AZ const EntityIdToEntityIdMap assetToLiveIdMap, SliceInstanceId sliceInstanceId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // Validate that we are able to create an instance at this time // This includes verifying that we are instantiated, and have a valid component and asset @@ -883,7 +883,7 @@ namespace AZ SliceComponent::SliceInstance* SliceComponent::SliceReference::CloneInstance(SliceComponent::SliceInstance* instance, SliceComponent::EntityIdToEntityIdMap& sourceToCloneEntityIdMap) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // check if source instance belongs to this slice reference auto findIt = AZStd::find_if(m_instances.begin(), m_instances.end(), [instance](const SliceInstance& element) -> bool { return &element == instance; }); @@ -1053,7 +1053,7 @@ namespace AZ //========================================================================= bool SliceComponent::SliceReference::Instantiate(const AZ::ObjectStream::FilterDescriptor& filterDesc) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (m_isInstantiated) { @@ -1145,7 +1145,7 @@ namespace AZ //========================================================================= void SliceComponent::SliceReference::InstantiateInstance(SliceInstance& instance, const AZ::ObjectStream::FilterDescriptor& filterDesc) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // Could have set this during SliceInstance() constructor, but we wait until instantiation since it involves allocation. instance.m_dataFlags.SetIsValidEntityFunction([&instance](EntityId entityId) { return instance.IsValidEntity(entityId); }); @@ -1167,7 +1167,7 @@ namespace AZ // An empty map indicates its a fresh instance (i.e. has never be instantiated and then serialized). if (entityIdMap.empty()) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "SliceComponent::SliceReference::InstantiateInstance:FreshInstanceClone"); + AZ_PROFILE_SCOPE(AzCore, "SliceComponent::SliceReference::InstantiateInstance:FreshInstanceClone"); // Generate new Ids and populate the map. AZ_Assert(!dataPatch.IsValid(), "Data patch is valid for slice instance, but entity Id map is not!"); @@ -1175,7 +1175,7 @@ namespace AZ } else { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "SliceComponent::SliceReference::InstantiateInstance:CloneAndApplyDataPatches"); + AZ_PROFILE_SCOPE(AzCore, "SliceComponent::SliceReference::InstantiateInstance:CloneAndApplyDataPatches"); // Clone entities while applying any data patches. AZ_Assert(dataPatch.IsValid(), "Data patch is not valid for existing slice instance!"); @@ -1261,7 +1261,7 @@ namespace AZ // Broadcast OnSliceEntitiesLoaded for freshly instantiated entities. if (!instance.m_instantiated->m_entities.empty()) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "SliceComponent::SliceReference::InstantiateInstance:OnSliceEntitiesLoaded"); + AZ_PROFILE_SCOPE(AzCore, "SliceComponent::SliceReference::InstantiateInstance:OnSliceEntitiesLoaded"); SliceAssetSerializationNotificationBus::Broadcast(&SliceAssetSerializationNotificationBus::Events::OnSliceEntitiesLoaded, instance.m_instantiated->m_entities); } } @@ -1363,7 +1363,7 @@ namespace AZ //========================================================================= void SliceComponent::SliceReference::ComputeDataPatch() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // Get source entities from the base asset (instantiate if needed) InstantiatedContainer source(m_asset.Get()->GetComponent(), false); @@ -1499,7 +1499,7 @@ namespace AZ //========================================================================= bool SliceComponent::GetEntities(EntityList& entities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); bool result = true; @@ -1532,7 +1532,7 @@ namespace AZ //========================================================================= bool SliceComponent::GetEntityIds(EntityIdSet& entities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); bool result = true; @@ -1582,7 +1582,7 @@ namespace AZ //========================================================================= bool SliceComponent::GetMetadataEntityIds(EntityIdSet& metadataEntities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); bool result = true; @@ -1654,7 +1654,7 @@ namespace AZ //========================================================================= SliceComponent::InstantiateResult SliceComponent::Instantiate() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZStd::unique_lock lock(m_instantiateMutex); if (m_slicesAreInstantiated) @@ -1856,7 +1856,7 @@ namespace AZ SliceComponent::SliceInstanceAddress SliceComponent::AddSliceUsingExistingEntities(const Data::Asset& sliceAsset, const AZ::SliceComponent::EntityIdToEntityIdMap& liveToAssetMap, SliceInstanceId sliceInstanceId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!sliceAsset.Get()->GetComponent()) { @@ -2337,7 +2337,7 @@ namespace AZ //========================================================================= bool SliceComponent::RemoveSliceInstance(SliceComponent::SliceInstanceAddress sliceAddress) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!sliceAddress.IsValid()) { AZ_Error("Slices", false, "Slice address is invalid."); @@ -2474,7 +2474,7 @@ namespace AZ bool SliceComponent::RemoveMetaDataEntity(EntityId metaDataEntityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); GetEntityInfoMap(); // Ensure map is built @@ -2567,7 +2567,7 @@ namespace AZ void SliceComponent::RemoveAllEntities(bool deleteEntities, bool removeEmptyInstances) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); // If we are deleting the entities, we need to do that one by one if (deleteEntities) @@ -2930,7 +2930,7 @@ namespace AZ //========================================================================= void SliceComponent::OnAssetReloaded(Data::Asset /*asset*/) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!m_myAsset) { @@ -3073,7 +3073,7 @@ namespace AZ /// Called right after we finish writing data to the instance pointed at by classPtr. void OnWriteEnd(void* classPtr) override { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); SliceComponent* sliceComponent = reinterpret_cast(classPtr); EBUS_EVENT(SliceAssetSerializationNotificationBus, OnWriteDataToSliceAssetEnd, *sliceComponent); @@ -3082,7 +3082,7 @@ namespace AZ // We can't broadcast this event for instanced entities yet, since they don't exist until instantiation. if (!sliceComponent->GetNewEntities().empty()) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "SliceComponentSerializationEvents::OnWriteEnd:OnSliceEntitiesLoaded"); + AZ_PROFILE_SCOPE(AzCore, "SliceComponentSerializationEvents::OnWriteEnd:OnSliceEntitiesLoaded"); EBUS_EVENT(SliceAssetSerializationNotificationBus, OnSliceEntitiesLoaded, sliceComponent->GetNewEntities()); } } @@ -3093,7 +3093,7 @@ namespace AZ //========================================================================= void SliceComponent::PrepareSave() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (m_slicesAreInstantiated) { @@ -3262,7 +3262,7 @@ namespace AZ //========================================================================= void SliceComponent::BuildEntityInfoMap() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); m_entityInfoMap.clear(); m_metaDataEntityInfoMap.clear(); @@ -3425,7 +3425,7 @@ namespace AZ //========================================================================= void SliceComponent::BuildDataFlagsForInstances() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Assert(IsInstantiated(), "Slice must be instantiated before the ancestry of its data flags can be calculated."); // Use lock since slice instantiation can occur from multiple threads @@ -3551,7 +3551,7 @@ namespace AZ { // if this function is a performance bottleneck, it could be optimized with caching // be wary not to create the cache in-game if the information is only needed by tools - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!IsInstantiated()) { @@ -3730,7 +3730,7 @@ namespace AZ //========================================================================= SliceComponent* SliceComponent::Clone(AZ::SerializeContext& serializeContext, SliceInstanceToSliceInstanceMap* sourceToCloneSliceInstanceMap) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); SliceComponent* clonedComponent = serializeContext.CloneObject(this); diff --git a/Code/Framework/AzCore/AzCore/Statistics/StatisticalProfilerProxy.h b/Code/Framework/AzCore/AzCore/Statistics/StatisticalProfilerProxy.h index 7d55a88f19..33d835076f 100644 --- a/Code/Framework/AzCore/AzCore/Statistics/StatisticalProfilerProxy.h +++ b/Code/Framework/AzCore/AzCore/Statistics/StatisticalProfilerProxy.h @@ -17,154 +17,148 @@ #include -#if !defined(AZ_PROFILE_TELEMETRY) && defined(AZ_STATISTICAL_PROFILING_ENABLED) +#if defined(AZ_STATISTICAL_PROFILING_ENABLED) #if defined(AZ_PROFILE_SCOPE) #undef AZ_PROFILE_SCOPE #endif // #if defined(AZ_PROFILE_SCOPE) #define AZ_PROFILE_SCOPE(profiler, scopeNameId) \ - static_assert(profiler < AZ::Debug::ProfileCategory::Count, "Invalid profiler category"); \ static const AZStd::string AZ_JOIN(blockName, __LINE__)(scopeNameId); \ AZ::Statistics::StatisticalProfilerProxy::TimedScope AZ_JOIN(scope, __LINE__)(profiler, AZ_JOIN(blockName, __LINE__)); -#endif //#if !defined(AZ_PROFILE_TELEMETRY) +#endif //#if defined(AZ_STATISTICAL_PROFILING_ENABLED) -namespace AZ +namespace AZ::Statistics { - namespace Statistics - { - using StatisticalProfilerId = AZ::Debug::ProfileCategory; + using StatisticalProfilerId = uint32_t; - //! This AZ::Interface<> (Yes, it is an application wide singleton) owns an array of StatisticalProfilers. - //! When is this useful? - //! When you need to statistically profile code that runs across DLL boundaries. - //! - //! What is the meaning of "statistically profile" code? - //! In regular profiling with tools like RAD Telemetry, every execution of a profiled - //! scope of code will be captured when using AZ_PROFILE_SCOPE(). You can collect - //! very large amounts of data and do your own post processing and analysis in tools like Excel,etc. - //! In contrast, "statistical profiling" means that everytime AZ_PROFILE_SCOPE() is called, - //! the time spent in the given scope of code will be mathematically accumulated as part of a unique - //! Running statistic. Common statistical parameters like min, max, average, variance and standard deviation - //! are calculated on the fly. This approach reduces considerably the amount of data that is collected. - //! The data is recorded in the Game/Editor Log file. - //! - //! This StatisticalProfilerProxy should be used via the AZ_PROFILE_SCOPE() macro, and by using - //! this macro the developer gains the flexibility of switching at compile time between profiling - //! the code via RAD Telemetry or through statistical profiling. - //! - //! When creating a new statistical profiler add your category (aka profiler id) in Profiler.h (enum class ProfileCategory). - //! Get a reference of the statistical profiler with "GetProfiler(const StatisticalProfilerId& id)" using the profiler Id. - //! Once you get a reference to the profiler you can customize it, add Running statistics to it, etc. - //! Some class in your code will manage the reference to the statistical profiler and will determine - //! the policy on how often to log data to the game logs, etc. For example, by subclassing the TickBus Handler, etc. - //! - //! The StatisticalProfilerProxySystemComponent guarantees that the StatisticalProfilerProxy singleton exists - //! as soon as the AZ::Environment is fully initialized. - //! See StatisticalProfiler.h for more details and info. - class StatisticalProfilerProxy + //! This AZ::Interface<> (Yes, it is an application wide singleton) owns an array of StatisticalProfilers. + //! When is this useful? + //! When you need to statistically profile code that runs across DLL boundaries. + //! + //! What is the meaning of "statistically profile" code? + //! In regular profiling with tools like RAD Telemetry, every execution of a profiled + //! scope of code will be captured when using AZ_PROFILE_SCOPE(). You can collect + //! very large amounts of data and do your own post processing and analysis in tools like Excel,etc. + //! In contrast, "statistical profiling" means that everytime AZ_PROFILE_SCOPE() is called, + //! the time spent in the given scope of code will be mathematically accumulated as part of a unique + //! Running statistic. Common statistical parameters like min, max, average, variance and standard deviation + //! are calculated on the fly. This approach reduces considerably the amount of data that is collected. + //! The data is recorded in the Game/Editor Log file. + //! + //! This StatisticalProfilerProxy should be used via the AZ_PROFILE_SCOPE() macro, and by using + //! this macro the developer gains the flexibility of switching at compile time between profiling + //! the code via RAD Telemetry or through statistical profiling. + //! + //! When creating a new statistical profiler add your category (aka profiler id) in Profiler.h (enum class ProfileCategory). + //! Get a reference of the statistical profiler with "GetProfiler(const StatisticalProfilerId& id)" using the profiler Id. + //! Once you get a reference to the profiler you can customize it, add Running statistics to it, etc. + //! Some class in your code will manage the reference to the statistical profiler and will determine + //! the policy on how often to log data to the game logs, etc. For example, by subclassing the TickBus Handler, etc. + //! + //! The StatisticalProfilerProxySystemComponent guarantees that the StatisticalProfilerProxy singleton exists + //! as soon as the AZ::Environment is fully initialized. + //! See StatisticalProfiler.h for more details and info. + class StatisticalProfilerProxy + { + public: + AZ_TYPE_INFO(StatisticalProfilerProxy, "{1103D0EB-1C32-4854-B9D9-40A2D65BDBD2}"); + + using StatIdType = AZStd::string; + using StatisticalProfilerType = StatisticalProfiler; + + //! A Convenience class used to measure time performance of scopes of code + //! with constructor/destructor. Suitable to be used as part of a macro + //! to facilitate its usage. + class TimedScope { public: - AZ_TYPE_INFO(StatisticalProfilerProxy, "{1103D0EB-1C32-4854-B9D9-40A2D65BDBD2}"); + TimedScope() = delete; - using StatIdType = AZStd::string; - using StatisticalProfilerType = StatisticalProfiler; - - //! A Convenience class used to measure time performance of scopes of code - //! with constructor/destructor. Suitable to be used as part of a macro - //! to facilitate its usage. - class TimedScope + TimedScope(const StatisticalProfilerId profilerId, const StatIdType& statId) + : m_profilerId(profilerId) + , m_statId(statId) { - public: - TimedScope() = delete; - - TimedScope(const StatisticalProfilerId profilerId, const StatIdType& statId) - : m_profilerId(profilerId), m_statId(statId) - { - if (!m_profilerProxy) - { - m_profilerProxy = AZ::Interface::Get(); - if (!m_profilerProxy) - { - return; - } - } - if (!m_profilerProxy->IsProfilerActive(profilerId)) - { - return; - } - m_startTime = AZStd::chrono::high_resolution_clock::now(); - } - ~TimedScope() + if (!m_profilerProxy) { + m_profilerProxy = AZ::Interface::Get(); if (!m_profilerProxy) { return; } - AZStd::chrono::system_clock::time_point stopTime = AZStd::chrono::high_resolution_clock::now(); - AZStd::chrono::microseconds duration = stopTime - m_startTime; - m_profilerProxy->PushSample(m_profilerId, m_statId, static_cast(duration.count())); } - - //! Required only for UnitTests - static void ClearCachedProxy() + if (!m_profilerProxy->IsProfilerActive(profilerId)) { - m_profilerProxy = nullptr; + return; } - - private: - static StatisticalProfilerProxy* m_profilerProxy; - const StatisticalProfilerId m_profilerId; - const StatIdType& m_statId; - AZStd::chrono::system_clock::time_point m_startTime; - }; //class TimedScope - - friend class TimedScope; - - StatisticalProfilerProxy() + m_startTime = AZStd::chrono::high_resolution_clock::now(); + } + ~TimedScope() { - m_profilers.reserve(static_cast(AZ::Debug::ProfileCategory::Count)); - for (AZStd::size_t i = 0; i < static_cast(AZ::Debug::ProfileCategory::Count); i++) + if (!m_profilerProxy) { - m_profilers.emplace_back(StatisticalProfilerType()); + return; } - AZ::Interface::Register(this); + AZStd::chrono::system_clock::time_point stopTime = AZStd::chrono::high_resolution_clock::now(); + AZStd::chrono::microseconds duration = stopTime - m_startTime; + m_profilerProxy->PushSample(m_profilerId, m_statId, static_cast(duration.count())); } - virtual ~StatisticalProfilerProxy() + //! Required only for UnitTests + static void ClearCachedProxy() { - AZ::Interface::Unregister(this); - } - - // Note that you have to delete these for safety reasons, you will trip a static_assert if you do not - StatisticalProfilerProxy(StatisticalProfilerProxy&&) = delete; - StatisticalProfilerProxy& operator=(StatisticalProfilerProxy&&) = delete; - - bool IsProfilerActive(StatisticalProfilerId id) const - { - return m_activeProfilersFlag[static_cast(id)]; - } - - StatisticalProfilerType& GetProfiler(StatisticalProfilerId id) - { - return m_profilers[static_cast(id)]; - } - - void ActivateProfiler(StatisticalProfilerId id, bool activate) - { - m_activeProfilersFlag[static_cast(id)] = activate; - } - - void PushSample(StatisticalProfilerId id, const StatIdType& statId, double value) - { - m_profilers[static_cast(id)].PushSample(statId, value); + m_profilerProxy = nullptr; } private: - AZStd::bitset(AZ::Debug::ProfileCategory::Count)> m_activeProfilersFlag; - AZStd::vector m_profilers; - }; //class StatisticalProfilerProxy + static StatisticalProfilerProxy* m_profilerProxy; + const StatisticalProfilerId m_profilerId; + const StatIdType& m_statId; + AZStd::chrono::system_clock::time_point m_startTime; + }; // class TimedScope - }; //namespace Statistics -}; //namespace AZ + friend class TimedScope; + + StatisticalProfilerProxy() + { + // TODO:BUDGETS Query available budgets at registration time and create an associated profiler per type + AZ::Interface::Register(this); + } + + virtual ~StatisticalProfilerProxy() + { + AZ::Interface::Unregister(this); + } + + // Note that you have to delete these for safety reasons, you will trip a static_assert if you do not + StatisticalProfilerProxy(StatisticalProfilerProxy&&) = delete; + StatisticalProfilerProxy& operator=(StatisticalProfilerProxy&&) = delete; + + bool IsProfilerActive(StatisticalProfilerId id) const + { + return m_activeProfilersFlag[static_cast(id)]; + } + + StatisticalProfilerType& GetProfiler(StatisticalProfilerId id) + { + return m_profilers[static_cast(id)]; + } + + void ActivateProfiler(StatisticalProfilerId id, bool activate) + { + m_activeProfilersFlag[static_cast(id)] = activate; + } + + void PushSample(StatisticalProfilerId id, const StatIdType& statId, double value) + { + m_profilers[static_cast(id)].PushSample(statId, value); + } + + private: + // TODO:BUDGETS the number of bits allocated here must be based on the number of budgets available at profiler registration time + AZStd::bitset<128> m_activeProfilersFlag; + AZStd::vector m_profilers; + }; // class StatisticalProfilerProxy + +}; // namespace AZ::Statistics diff --git a/Code/Framework/AzCore/AzCore/StringFunc/StringFunc.cpp b/Code/Framework/AzCore/AzCore/StringFunc/StringFunc.cpp index da7a78e1b3..ff30291a70 100644 --- a/Code/Framework/AzCore/AzCore/StringFunc/StringFunc.cpp +++ b/Code/Framework/AzCore/AzCore/StringFunc/StringFunc.cpp @@ -342,8 +342,8 @@ namespace AZ::StringFunc::Internal { for (const char stripCharacter : stripCharacters) { - const char lower = tolower(stripCharacter); - const char upper = toupper(stripCharacter); + const char lower = static_cast(tolower(stripCharacter)); + const char upper = static_cast(toupper(stripCharacter)); if (lower != upper) { combinedStripCharacters.push_back(lower); diff --git a/Code/Framework/AzCore/AzCore/Task/TaskExecutor.cpp b/Code/Framework/AzCore/AzCore/Task/TaskExecutor.cpp index 13db590291..2bb88fbfa2 100644 --- a/Code/Framework/AzCore/AzCore/Task/TaskExecutor.cpp +++ b/Code/Framework/AzCore/AzCore/Task/TaskExecutor.cpp @@ -41,7 +41,7 @@ namespace AZ { Task& task = m_tasks[i]; task.m_graph = this; - task.m_successorOffset = cursor - m_successors.data(); + task.m_successorOffset = static_cast(cursor - m_successors.data()); cursor += task.m_outboundLinkCount; AZ_Assert(task.m_outboundLinkCount == links[i].size(), "Task outbound link information mismatch"); @@ -78,7 +78,7 @@ namespace AZ return remaining; } - if (m_waitEvent && remaining == (m_parent ? 1 : 0)) + if (m_waitEvent && remaining == (m_parent ? 1u : 0u)) { m_waitEvent->Signal(); } @@ -259,7 +259,7 @@ namespace AZ } bool isRetained = task->m_graph->m_parent != nullptr; - if (task->m_graph->Release() == (isRetained ? 1 : 0)) + if (task->m_graph->Release() == (isRetained ? 1u : 0u)) { m_executor->ReleaseGraph(); } diff --git a/Code/Framework/AzCore/AzCore/azcore_files.cmake b/Code/Framework/AzCore/AzCore/azcore_files.cmake index 0c95b9d592..1ea86c7b93 100644 --- a/Code/Framework/AzCore/AzCore/azcore_files.cmake +++ b/Code/Framework/AzCore/AzCore/azcore_files.cmake @@ -25,6 +25,7 @@ set(FILES Asset/AssetJsonSerializer.h Asset/AssetManager.cpp Asset/AssetManager.h + Asset/AssetManager_private.h Asset/AssetManagerBus.h Asset/AssetManagerComponent.cpp Asset/AssetManagerComponent.h @@ -99,8 +100,7 @@ set(FILES Debug/FrameProfilerComponent.cpp Debug/FrameProfilerComponent.h Debug/IEventLogger.h - Debug/ProfileModuleInit.cpp - Debug/ProfileModuleInit.h + Debug/MemoryProfiler.h Debug/Profiler.cpp Debug/Profiler.h Debug/ProfilerBus.h diff --git a/Code/Framework/AzCore/AzCore/std/delegate/delegate.h b/Code/Framework/AzCore/AzCore/std/delegate/delegate.h index 610c1982f2..1b44437f31 100644 --- a/Code/Framework/AzCore/AzCore/std/delegate/delegate.h +++ b/Code/Framework/AzCore/AzCore/std/delegate/delegate.h @@ -291,9 +291,7 @@ namespace AZStd template <> struct SimplifyMemFunc { -#if defined(AZ_COMPILER_MSVC) -# pragma warning(push) -# pragma warning(disable: 4121) // alignment of a member was sensitive to packing + AZ_PUSH_DISABLE_WARNING(4121, "-Wunknown-warning-option") // alignment of a member was sensitive to packing // GenericClass* (X::*ProbeFunc) changes it's size. From Microsoft: // Jason Shirk [MSFT] // This is a known bug/issue. Unfortunately, we can't fix it in X86 product @@ -302,7 +300,6 @@ namespace AZStd // We have addressed the issue for all future platforms (including IA64) where // binary compatibility isn't yet an issue. // We can fix this warning by adding forward decl class __single_inheritance CLASS; if the XFuncType is member function. -#endif template inline static GenericClass* Convert(X* pthis, XFuncType function_to_bind, GenericMemFuncType& bound_func) { @@ -330,11 +327,7 @@ namespace AZStd u.s.codeptr = u2.s.codeptr; return (pthis->*u.ProbeFunc)(); } - -#if defined(AZ_COMPILER_MSVC) -# pragma warning(default: 4121) // alignment of a member was sensitive to packing -# pragma warning(pop) -#endif + AZ_POP_DISABLE_WARNING }; // Nasty hack for Microsoft and Intel (IA32 and Itanium) diff --git a/Code/Framework/AzCore/AzCore/std/function/function_base.h b/Code/Framework/AzCore/AzCore/std/function/function_base.h index c1dd669f51..32892a4c03 100644 --- a/Code/Framework/AzCore/AzCore/std/function/function_base.h +++ b/Code/Framework/AzCore/AzCore/std/function/function_base.h @@ -20,13 +20,6 @@ #include #include -#if defined(AZ_COMPILER_MSVC) -# pragma warning( push ) -# pragma warning( disable : 4793 ) // complaint about native code generation -# pragma warning( disable : 4127 ) // "conditional expression is constant" -# pragma warning( disable : 4275 ) // non dll-interface class 'stdext::exception' used as base for dll-interface class 'std::bad_cast' -#endif - #define AZSTD_FUNCTION_TARGET_FIX(x) #define AZSTD_FUNCTION_ENABLE_IF_NOT_INTEGRAL(Functor, Type) AZStd::enable_if_t, Type> @@ -796,12 +789,5 @@ namespace AZStd //#undef aztypeid //#undef aztypeid_cmp -#if defined(AZ_COMPILER_MSVC) -# pragma warning( default : 4793 ) // complaint about native code generation -# pragma warning( default : 4127 ) // "conditional expression is constant" -# pragma warning( default : 4275 ) // non dll-interface class 'stdext::exception' used as base for dll-interface class 'std::bad_cast' -# pragma warning( pop ) -#endif - #endif // AZSTD_FUNCTION_BASE_HEADER #pragma once diff --git a/Code/Framework/AzCore/AzCore/std/function/function_template.h b/Code/Framework/AzCore/AzCore/std/function/function_template.h index 586b02e671..7f388c4006 100644 --- a/Code/Framework/AzCore/AzCore/std/function/function_template.h +++ b/Code/Framework/AzCore/AzCore/std/function/function_template.h @@ -13,11 +13,6 @@ #include #include -#if defined(AZ_COMPILER_MSVC) -# pragma warning( push ) -# pragma warning( disable : 4127 ) // "conditional expression is constant" -#endif - namespace AZStd { namespace Internal @@ -689,7 +684,3 @@ namespace AZStd } }; } // end namespace AZStd - -#if defined(AZ_COMPILER_MSVC) -# pragma warning( pop ) -#endif diff --git a/Code/Framework/AzCore/AzCore/std/parallel/containers/internal/concurrent_hash_table.h b/Code/Framework/AzCore/AzCore/std/parallel/containers/internal/concurrent_hash_table.h index 524eff7e64..c8fc709778 100644 --- a/Code/Framework/AzCore/AzCore/std/parallel/containers/internal/concurrent_hash_table.h +++ b/Code/Framework/AzCore/AzCore/std/parallel/containers/internal/concurrent_hash_table.h @@ -489,24 +489,26 @@ namespace AZStd { return; } - - float loadFactor = (float)m_numElements.load(memory_order_acquire) / (float)m_storage.get_num_buckets(); - if (loadFactor > max_load_factor()) + else { - acquire_all(); - - //check the load factor again, as another thread may have beaten us to the rehash - size_type numElements = m_numElements.load(memory_order_acquire); - float maxLoadFactor = max_load_factor(); - size_type numBuckets = m_storage.get_num_buckets(); - loadFactor = (float)numElements / (float)numBuckets; - if (loadFactor > maxLoadFactor) + float loadFactor = (float)m_numElements.load(memory_order_acquire) / (float)m_storage.get_num_buckets(); + if (loadFactor > max_load_factor()) { - size_type minNumBuckets = (size_type)((float)numElements / maxLoadFactor); - m_storage.rehash(this, minNumBuckets); - } + acquire_all(); - release_all(); + // check the load factor again, as another thread may have beaten us to the rehash + size_type numElements = m_numElements.load(memory_order_acquire); + float maxLoadFactor = max_load_factor(); + size_type numBuckets = m_storage.get_num_buckets(); + loadFactor = (float)numElements / (float)numBuckets; + if (loadFactor > maxLoadFactor) + { + size_type minNumBuckets = (size_type)((float)numElements / maxLoadFactor); + m_storage.rehash(this, minNumBuckets); + } + + release_all(); + } } } diff --git a/Code/Framework/AzCore/AzCore/std/parallel/spin_mutex.h b/Code/Framework/AzCore/AzCore/std/parallel/spin_mutex.h index 926e404668..2fc4c331ee 100644 --- a/Code/Framework/AzCore/AzCore/std/parallel/spin_mutex.h +++ b/Code/Framework/AzCore/AzCore/std/parallel/spin_mutex.h @@ -8,7 +8,6 @@ #ifndef AZSTD_PARALLEL_SPIN_MUTEX_H #define AZSTD_PARALLEL_SPIN_MUTEX_H 1 -#include #include #include @@ -32,8 +31,6 @@ namespace AZStd bool expected = false; if (!m_flag.compare_exchange_weak(expected, true, memory_order_acq_rel, memory_order_acquire)) { - AZ_PROFILE_FUNCTION_STALL(AZ::Debug::ProfileCategory::AzCore); - exponential_backoff backoff; for (;; ) { diff --git a/Code/Framework/AzCore/AzCore/std/smart_ptr/weak_ptr.h b/Code/Framework/AzCore/AzCore/std/smart_ptr/weak_ptr.h index aaaf90e8f7..80dee72d03 100644 --- a/Code/Framework/AzCore/AzCore/std/smart_ptr/weak_ptr.h +++ b/Code/Framework/AzCore/AzCore/std/smart_ptr/weak_ptr.h @@ -192,9 +192,5 @@ namespace AZStd } } // namespace AZStd -/*#ifdef AZ_COMPILER_MSVC -# pragma warning(pop) -#endif */ - #endif // #ifndef AZSTD_SMART_PTR_WEAK_PTR_H #pragma once diff --git a/Code/Framework/AzCore/AzCore/std/string/regex.h b/Code/Framework/AzCore/AzCore/std/string/regex.h index 2c120436d5..2ca223937b 100644 --- a/Code/Framework/AzCore/AzCore/std/string/regex.h +++ b/Code/Framework/AzCore/AzCore/std/string/regex.h @@ -22,11 +22,6 @@ // used for std::pointer_traits \note do an AZStd version #include -#if defined(AZ_COMPILER_MSVC) -# pragma warning(push) -# pragma warning(disable: 6011 28198) -#endif // AZ_COMPILER_MSVC - #ifndef AZ_REGEX_MAX_COMPLEXITY_COUNT #define AZ_REGEX_MAX_COMPLEXITY_COUNT 10000000L /* set to 0 to disable */ #endif /* AZ_REGEX_MAX_COMPLEXITY_COUNT */ @@ -4766,7 +4761,3 @@ namespace AZStd Trans(); } } // namespace AZStd - -#if defined(AZ_COMPILER_MSVC) -# pragma warning(pop) -#endif // AZ_COMPILER_MSVC diff --git a/Code/Framework/AzCore/AzCore/std/string/string_view.h b/Code/Framework/AzCore/AzCore/std/string/string_view.h index 9a98795554..4ded44644f 100644 --- a/Code/Framework/AzCore/AzCore/std/string/string_view.h +++ b/Code/Framework/AzCore/AzCore/std/string/string_view.h @@ -7,7 +7,6 @@ */ #pragma once -#include #include #include @@ -46,6 +45,10 @@ namespace AZStd return npos; } size_t foundIndex = searchIndex + charFindIndex; + if (foundIndex + count > size) + { + return npos; // the rest of the string doesnt fit in the remainder of the data buffer + } if (Traits::compare(&data[foundIndex], ptr, count) == 0) { return foundIndex; diff --git a/Code/Framework/AzCore/CMakeLists.txt b/Code/Framework/AzCore/CMakeLists.txt index ea7cc27af5..eec5b37e03 100644 --- a/Code/Framework/AzCore/CMakeLists.txt +++ b/Code/Framework/AzCore/CMakeLists.txt @@ -12,11 +12,10 @@ ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) ly_get_list_relative_pal_filename(common_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/Common) -if(LY_RAD_TELEMETRY_ENABLED) - set(AZ_CORE_RADTELEMETRY_FILES ${common_dir}/azcore_profile_telemetry_files.cmake) - set(AZ_CORE_RADTELEMETRY_PLATFORM_INCLUDES ${pal_dir}/profile_telemetry_platform_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) - set(AZ_CORE_RADTELEMETRY_INCLUDE_DIRECTORIES ${common_dir}) - set(AZ_CORE_RADTELEMETRY_BUILD_DEPENDENCIES 3rdParty::RadTelemetry) +if(PAL_TRAIT_PROF_PIX_SUPPORTED AND LY_PIX_ENABLED) + set(LY_PIX_PATH "${LY_3RDPARTY_PATH}/winpixeventruntime" CACHE PATH "Path to the Windows Pix Event Runtime.") + set(AZ_CORE_PIX_BUILD_DEPENDENCIES 3rdParty::pix) + set(AZ_CORE_PIX_BUILD_DEFINES "USE_PIX") endif() ly_add_target( @@ -26,16 +25,13 @@ ly_add_target( AzCore/azcore_files.cmake AzCore/std/azstd_files.cmake ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - ${AZ_CORE_RADTELEMETRY_FILES} PLATFORM_INCLUDE_FILES ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}.cmake - ${AZ_CORE_RADTELEMETRY_PLATFORM_INCLUDES} INCLUDE_DIRECTORIES PUBLIC . ${pal_dir} ${common_dir} - ${AZ_CORE_RADTELEMETRY_INCLUDE_DIRECTORIES} BUILD_DEPENDENCIES PUBLIC 3rdParty::Lua @@ -44,7 +40,10 @@ ly_add_target( 3rdParty::zlib 3rdParty::zstd 3rdParty::cityhash - ${AZ_CORE_RADTELEMETRY_BUILD_DEPENDENCIES} + ${AZ_CORE_PIX_BUILD_DEPENDENCIES} + COMPILE_DEFINITIONS + PUBLIC + ${AZ_CORE_PIX_BUILD_DEFINES} ) ly_add_source_properties( SOURCES @@ -54,6 +53,15 @@ ly_add_source_properties( VALUES ${LY_PAL_TOOLS_DEFINES} ) +if(LY_BUILD_WITH_ADDRESS_SANITIZER) + # Default to use Malloc schema so ASan works well + ly_add_source_properties( + SOURCES AzCore/Memory/SystemAllocator.cpp + PROPERTY COMPILE_DEFINITIONS + VALUES AZCORE_SYSTEM_ALLOCATOR=AZCORE_SYSTEM_ALLOCATOR_MALLOC + ) +endif() + ################################################################################ # Tests ################################################################################ diff --git a/Code/Framework/AzCore/Platform/Android/AzCore/AzCore_Traits_Android.h b/Code/Framework/AzCore/Platform/Android/AzCore/AzCore_Traits_Android.h index 1b67f3b720..495c8d5f2c 100644 --- a/Code/Framework/AzCore/Platform/Android/AzCore/AzCore_Traits_Android.h +++ b/Code/Framework/AzCore/Platform/Android/AzCore/AzCore_Traits_Android.h @@ -109,6 +109,19 @@ #define AZ_TRAIT_USE_ERRNO_T_TYPEDEF 1 #define AZ_TRAIT_USE_POSIX_TEMP_FOLDER 0 +// wchar_t/char formatting +// Reason: https://docs.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=msvc-160 +// The Z type character, and the behavior of the c, C, s, and S type characters when they're used with the printf and wprintf functions, +// are Microsoft extensions. The ISO C standard uses c and s consistently for narrow characters and strings, and C and S for wide characters +// and strings, in all formatting functions. +#define AZ_TRAIT_FORMAT_STRING_PRINTF_CHAR "%c" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_WCHAR "%C" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_CHAR "%c" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_WCHAR "%C" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_STRING "%s" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_WSTRING "%S" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_STRING "%s" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_WSTRING "%S" // Legacy traits ... #define AZ_TRAIT_LEGACY_CRYCOMMON_USE_WINDOWS_STUBS 1 #define AZ_TRAIT_LEGACY_CRYPAK_UNIX_LIKE_FILE_SYSTEM 1 diff --git a/Code/Framework/AzCore/Platform/Android/profile_telemetry_platform_android.cmake b/Code/Framework/AzCore/Platform/Android/profile_telemetry_platform_android.cmake index df12777586..9ecf9fd999 100644 --- a/Code/Framework/AzCore/Platform/Android/profile_telemetry_platform_android.cmake +++ b/Code/Framework/AzCore/Platform/Android/profile_telemetry_platform_android.cmake @@ -11,7 +11,3 @@ # NOTE: functions in cmake are global, therefore adding functions to this file # is being avoided to prevent overriding functions declared in other targets platfrom # specific cmake files - -if(LY_RAD_TELEMETRY_ENABLED) - set(LY_COMPILE_DEFINITIONS PUBLIC AZ_PROFILE_TELEMETRY) -endif() diff --git a/Code/Framework/AzCore/Platform/Common/RadTelemetry/ProfileTelemetry.h b/Code/Framework/AzCore/Platform/Common/RadTelemetry/ProfileTelemetry.h deleted file mode 100644 index 3337df9ede..0000000000 --- a/Code/Framework/AzCore/Platform/Common/RadTelemetry/ProfileTelemetry.h +++ /dev/null @@ -1,159 +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 - * - */ - -#pragma once - -#ifdef AZ_PROFILE_TELEMETRY - -/*! -* ProfileTelemetry.h provides a RAD Telemetry specific implementation of the AZ_PROFILE_FUNCTION, AZ_PROFILE_SCOPE, and AZ_PROFILE_SCOPE_DYNAMIC performance instrumentation markers -*/ - -#define TM_API_PTR g_radTmApi -#include -#include - -namespace ProfileTelemetryInternal -{ - inline constexpr tm_uint32 ConvertColor(uint32_t rgba) - { - return - ((rgba >> 24) & 0x000000ff) | // move byte 3 to byte 0 - ((rgba << 8) & 0x00ff0000) | // move byte 1 to byte 2 - ((rgba >> 8) & 0x0000ff00) | // move byte 2 to byte 1 - ((rgba << 24) & 0xff000000); // byte 0 to byte 3 - } - - inline constexpr tm_uint32 ConvertColor(const AZ::Color& color) - { - return ConvertColor(color.ToU32()); - } -} - -#define AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category) (static_cast(1) << static_cast(category)) -// Helpers -#define AZ_INTERNAL_PROF_VERIFY_CAT(category) static_assert(category < AZ::Debug::ProfileCategory::Count, "Invalid profile category") - -#define AZ_INTERNAL_PROF_MEMORY_CAT_TO_FLAGS(category) (AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category) | \ - AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(AZ::Debug::ProfileCategory::MemoryReserved)) - -#define AZ_INTERNAL_PROF_VERIFY_INTERVAL_ID(id) static_assert(sizeof(id) <= sizeof(tm_uint64), "Interval id must be a unique value no larger than 64-bits") - -#define AZ_INTERNAL_PROF_TM_FUNC_VERIFY_CAT(category, flags) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - tmFunction(AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category), flags) - -#define AZ_INTERNAL_PROF_TM_ZONE_VERIFY_CAT(category, flags, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - tmZone(AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category), flags, __VA_ARGS__) - -// AZ_PROFILE_FUNCTION -#define AZ_PROFILE_FUNCTION(category) \ - AZ_INTERNAL_PROF_TM_FUNC_VERIFY_CAT(category, TMZF_NONE) - -#define AZ_PROFILE_FUNCTION_STALL(category) \ - AZ_INTERNAL_PROF_TM_FUNC_VERIFY_CAT(category, TMZF_STALL) - -#define AZ_PROFILE_FUNCTION_IDLE(category) \ - AZ_INTERNAL_PROF_TM_FUNC_VERIFY_CAT(category, TMZF_IDLE) - - -// AZ_PROFILE_SCOPE -#define AZ_PROFILE_SCOPE(category, name) \ - AZ_INTERNAL_PROF_TM_ZONE_VERIFY_CAT(category, TMZF_NONE, name) - -#define AZ_PROFILE_SCOPE_STALL(category, name) \ - AZ_INTERNAL_PROF_TM_ZONE_VERIFY_CAT(category, TMZF_STALL, name) - -#define AZ_PROFILE_SCOPE_IDLE(category, name) \ - AZ_INTERNAL_PROF_TM_ZONE_VERIFY_CAT(category, TMZF_IDLE, name) - -// AZ_PROFILE_SCOPE_DYNAMIC -// For profiling events with dynamic scope names -// Note: the first variable argument must be a const format string -// Usage: AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory, , format args...) -#define AZ_PROFILE_SCOPE_DYNAMIC(category, ...) \ - AZ_INTERNAL_PROF_TM_ZONE_VERIFY_CAT(category, TMZF_NONE, __VA_ARGS__) - -#define AZ_PROFILE_SCOPE_STALL_DYNAMIC(category, ...) \ - AZ_INTERNAL_PROF_TM_ZONE_VERIFY_CAT(category, TMZF_STALL, __VA_ARGS__) - -#define AZ_PROFILE_SCOPE_IDLE_DYNAMIC(category, ...) \ - AZ_INTERNAL_PROF_TM_ZONE_VERIFY_CAT(category, TMZF_IDLE, __VA_ARGS__) - - -// AZ_PROFILE_EVENT_BEGIN/END -// For profiling events that do not start and stop in the same scope (they MUST start/stop on the same thread) -// ALWAYS favor using scoped events (AZ_PROFILE_FUNCTION, AZ_PROFILE_SCOPE) as debugging an unmatched begin/end can be challenging -#define AZ_PROFILE_EVENT_BEGIN(category, name) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - tmEnter(AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category), TMZF_NONE, name) - -#define AZ_PROFILE_EVENT_END(category) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - tmLeave(AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category)) - - -// AZ_PROFILE_INTERVAL (mapped to Telemetry Timespan APIs) -// Note: using C-style casting as we allow either pointers or integral types as IDs -#define AZ_PROFILE_INTERVAL_START(category, id, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - AZ_INTERNAL_PROF_VERIFY_INTERVAL_ID(id); \ - tmBeginTimeSpan(AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category), (tm_uint64)(id), TMZF_NONE, __VA_ARGS__) - -#define AZ_PROFILE_INTERVAL_START_COLORED(category, id, color, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - AZ_INTERNAL_PROF_VERIFY_INTERVAL_ID(id); \ - tmBeginColoredTimeSpan(AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category), (tm_uint64)(id), 0, ProfileTelemetryInternal::ConvertColor(color), TMZF_NONE, __VA_ARGS__) - -#define AZ_PROFILE_INTERVAL_END(category, id) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - AZ_INTERNAL_PROF_VERIFY_INTERVAL_ID(id); \ - tmEndTimeSpan(AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category), (tm_uint64)(id)) - -// AZ_PROFILE_INTERVAL_SCOPED -// Scoped interval event that implicitly starts and ends in the same scope -// Note: using C-style casting as we allow either pointers or integral types as IDs -// Note: the first variable argument must be a const format string -// Usage: AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory, , , format args...) -#define AZ_PROFILE_INTERVAL_SCOPED(category, id, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - AZ_INTERNAL_PROF_VERIFY_INTERVAL_ID(id); \ - tmTimeSpan(AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category), (tm_uint64)(id), TM_MIN_TIME_SPAN_TRACK_ID + static_cast(category), 0, TMZF_NONE, __VA_ARGS__) - - -// AZ_PROFILE_DATAPOINT (mapped to tmPlot APIs) -// Note: data points can have static or dynamic names, if using a dynamic name the first variable argument must be a const format string -// Usage: AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory, , format args...) -#define AZ_PROFILE_DATAPOINT(category, value, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - tmPlot(AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category), TM_PLOT_UNITS_REAL, TM_PLOT_DRAW_LINE, static_cast(value), __VA_ARGS__) - -#define AZ_PROFILE_DATAPOINT_PERCENT(category, value, ...) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - tmPlot(AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(category), TM_PLOT_UNITS_PERCENTAGE_DIRECT, TM_PLOT_DRAW_LINE, static_cast(value), __VA_ARGS__) - - -// AZ_PROFILE_MEMORY_ALLOC -#define AZ_PROFILE_MEMORY_ALLOC(category, address, size, context) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - tmAlloc(AZ_INTERNAL_PROF_MEMORY_CAT_TO_FLAGS(category), address, size, context) - -#define AZ_PROFILE_MEMORY_ALLOC_EX(category, filename, lineNumber, address, size, context) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - tmAllocEx(AZ_INTERNAL_PROF_MEMORY_CAT_TO_FLAGS(category), filename, lineNumber, address, size, context) - -#define AZ_PROFILE_MEMORY_FREE(category, address) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - tmFree(AZ_INTERNAL_PROF_MEMORY_CAT_TO_FLAGS(category), address) - -#define AZ_PROFILE_MEMORY_FREE_EX(category, filename, lineNumber, address) \ - AZ_INTERNAL_PROF_VERIFY_CAT(category); \ - tmFreeEx(AZ_INTERNAL_PROF_MEMORY_CAT_TO_FLAGS(category), filename, lineNumber, address) - -#endif diff --git a/Code/Framework/AzCore/Platform/Common/RadTelemetry/ProfileTelemetryBus.h b/Code/Framework/AzCore/Platform/Common/RadTelemetry/ProfileTelemetryBus.h deleted file mode 100644 index e572314723..0000000000 --- a/Code/Framework/AzCore/Platform/Common/RadTelemetry/ProfileTelemetryBus.h +++ /dev/null @@ -1,49 +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 - * - */ - -#pragma once - -#ifdef AZ_PROFILE_TELEMETRY - -#include -#include -#include -#include - -struct tm_api; - -namespace RADTelemetry -{ - class ProfileTelemetryRequests - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - virtual ~ProfileTelemetryRequests() = default; - - virtual void ToggleEnabled() = 0; - - virtual void SetAddress(const char* address, AZ::u16 port) = 0; - - virtual void SetCaptureMask(AZ::Debug::ProfileCategoryPrimitiveType mask) = 0; - - virtual void SetFrameAdvanceType(AZ::Debug::ProfileFrameAdvanceType type) = 0; - - virtual AZ::Debug::ProfileCategoryPrimitiveType GetCaptureMask() = 0; - - virtual AZ::Debug::ProfileCategoryPrimitiveType GetDefaultCaptureMask() = 0; - - virtual tm_api* GetApiInstance() = 0; - }; - - using ProfileTelemetryRequestBus = AZ::EBus; -} - -#endif diff --git a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/IO/SystemFile_UnixLike.cpp b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/IO/SystemFile_UnixLike.cpp index 797f3e35e8..8f651a9559 100644 --- a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/IO/SystemFile_UnixLike.cpp +++ b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/IO/SystemFile_UnixLike.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -208,7 +209,7 @@ namespace Platform bool DeleteDir(const char* dirName) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::DeleteDir(util) - %s", dirName); + AZ_PROFILE_SCOPE(AzCore, "SystemFile::DeleteDir(util) - %s", dirName); if (dirName) { diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/Streamer/StreamerContext_WinAPI.cpp b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/Streamer/StreamerContext_WinAPI.cpp index cda0a3f056..8f46bc5eba 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/Streamer/StreamerContext_WinAPI.cpp +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/IO/Streamer/StreamerContext_WinAPI.cpp @@ -49,7 +49,7 @@ namespace AZ::Platform AZ_Assert(m_events[0], "There is no synchronization event created for the main streamer thread to use to suspend."); DWORD result = ::WaitForMultipleObjects(m_handleCount, m_events, false, INFINITE); - if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + m_handleCount) + if (result < WAIT_OBJECT_0 + m_handleCount) { DWORD index = result - WAIT_OBJECT_0; ::ResetEvent(m_events[index]); diff --git a/Code/Framework/AzCore/Platform/Linux/AzCore/AzCore_Traits_Linux.h b/Code/Framework/AzCore/Platform/Linux/AzCore/AzCore_Traits_Linux.h index d36be0f61a..6ba369e86d 100644 --- a/Code/Framework/AzCore/Platform/Linux/AzCore/AzCore_Traits_Linux.h +++ b/Code/Framework/AzCore/Platform/Linux/AzCore/AzCore_Traits_Linux.h @@ -109,6 +109,20 @@ #define AZ_TRAIT_USE_ERRNO_T_TYPEDEF 1 #define AZ_TRAIT_USE_POSIX_TEMP_FOLDER 1 +// wchar_t/char formatting +// Reason: https://docs.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=msvc-160 +// The Z type character, and the behavior of the c, C, s, and S type characters when they're used with the printf and wprintf functions, +// are Microsoft extensions. The ISO C standard uses c and s consistently for narrow characters and strings, and C and S for wide characters +// and strings, in all formatting functions. +#define AZ_TRAIT_FORMAT_STRING_PRINTF_CHAR "%c" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_WCHAR "%C" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_CHAR "%c" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_WCHAR "%C" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_STRING "%s" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_WSTRING "%S" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_STRING "%s" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_WSTRING "%S" + // Legacy traits ... #define AZ_TRAIT_LEGACY_CRYCOMMON_USE_WINDOWS_STUBS 1 #define AZ_TRAIT_LEGACY_CRYPAK_UNIX_LIKE_FILE_SYSTEM 1 diff --git a/Code/Framework/AzCore/Platform/Mac/AzCore/AzCore_Traits_Mac.h b/Code/Framework/AzCore/Platform/Mac/AzCore/AzCore_Traits_Mac.h index b449cac072..a41b5c6baa 100644 --- a/Code/Framework/AzCore/Platform/Mac/AzCore/AzCore_Traits_Mac.h +++ b/Code/Framework/AzCore/Platform/Mac/AzCore/AzCore_Traits_Mac.h @@ -109,6 +109,20 @@ #define AZ_TRAIT_USE_ERRNO_T_TYPEDEF 0 #define AZ_TRAIT_USE_POSIX_TEMP_FOLDER 1 +// wchar_t/char formatting +// Reason: https://docs.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=msvc-160 +// The Z type character, and the behavior of the c, C, s, and S type characters when they're used with the printf and wprintf functions, +// are Microsoft extensions. The ISO C standard uses c and s consistently for narrow characters and strings, and C and S for wide characters +// and strings, in all formatting functions. +#define AZ_TRAIT_FORMAT_STRING_PRINTF_CHAR "%c" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_WCHAR "%C" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_CHAR "%c" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_WCHAR "%C" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_STRING "%s" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_WSTRING "%S" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_STRING "%s" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_WSTRING "%S" + // Legacy traits ... #define AZ_TRAIT_LEGACY_CRYCOMMON_USE_WINDOWS_STUBS 1 #define AZ_TRAIT_LEGACY_CRYPAK_UNIX_LIKE_FILE_SYSTEM 1 diff --git a/Code/Framework/AzCore/Platform/Mac/profile_telemetry_platform_mac.cmake b/Code/Framework/AzCore/Platform/Mac/profile_telemetry_platform_mac.cmake index df12777586..9ecf9fd999 100644 --- a/Code/Framework/AzCore/Platform/Mac/profile_telemetry_platform_mac.cmake +++ b/Code/Framework/AzCore/Platform/Mac/profile_telemetry_platform_mac.cmake @@ -11,7 +11,3 @@ # NOTE: functions in cmake are global, therefore adding functions to this file # is being avoided to prevent overriding functions declared in other targets platfrom # specific cmake files - -if(LY_RAD_TELEMETRY_ENABLED) - set(LY_COMPILE_DEFINITIONS PUBLIC AZ_PROFILE_TELEMETRY) -endif() diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/AzCore_Traits_Windows.h b/Code/Framework/AzCore/Platform/Windows/AzCore/AzCore_Traits_Windows.h index e9a06740a0..2f9fcefdbd 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/AzCore_Traits_Windows.h +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/AzCore_Traits_Windows.h @@ -109,6 +109,20 @@ #define AZ_TRAIT_USE_ERRNO_T_TYPEDEF 0 #define AZ_TRAIT_USE_POSIX_TEMP_FOLDER 0 +// wchar_t/char formatting +// Reason: https://docs.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=msvc-160 +// The Z type character, and the behavior of the c, C, s, and S type characters when they're used with the printf and wprintf functions, +// are Microsoft extensions. The ISO C standard uses c and s consistently for narrow characters and strings, and C and S for wide characters +// and strings, in all formatting functions. +#define AZ_TRAIT_FORMAT_STRING_PRINTF_CHAR "%c" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_WCHAR "%C" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_CHAR "%C" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_WCHAR "%c" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_STRING "%s" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_WSTRING "%S" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_STRING "%S" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_WSTRING "%s" + // Legacy traits ... #define AZ_TRAIT_LEGACY_CRYCOMMON_USE_WINDOWS_STUBS 0 #define AZ_TRAIT_LEGACY_CRYPAK_UNIX_LIKE_FILE_SYSTEM 0 diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp index 2489749b51..2462af861b 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StorageDrive_Windows.cpp @@ -169,7 +169,7 @@ namespace AZ::IO void StorageDriveWin::PrepareRequest(FileRequest* request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Assert(request, "PrepareRequest was provided a null request."); if (AZStd::holds_alternative(request->GetCommand())) @@ -189,7 +189,7 @@ namespace AZ::IO void StorageDriveWin::QueueRequest(FileRequest* request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Assert(request, "QueueRequest was provided a null request."); AZStd::visit([this, request](auto&& args) @@ -459,7 +459,7 @@ namespace AZ::IO // Adding explicit scope here for profiling file Open & Close { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "StorageDriveWin::ReadRequest OpenFile %s", m_name.c_str()); + AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::ReadRequest OpenFile %s", m_name.c_str()); TIMED_AVERAGE_WINDOW_SCOPE(m_fileOpenCloseTimeAverage); // All reads are overlapped (asynchronous). @@ -516,7 +516,7 @@ namespace AZ::IO bool StorageDriveWin::ReadRequest(FileRequest* request) { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "StorageDriveWin::ReadRequest %s", m_name.c_str()); + AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::ReadRequest %s", m_name.c_str()); if (!m_cachesInitialized) { @@ -545,7 +545,7 @@ namespace AZ::IO bool StorageDriveWin::ReadRequest(FileRequest* request, size_t readSlot) { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "StorageDriveWin::ReadRequest %s", m_name.c_str()); + AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::ReadRequest %s", m_name.c_str()); if (!m_context->GetStreamerThreadSynchronizer().AreEventHandlesAvailable()) { @@ -666,7 +666,7 @@ namespace AZ::IO bool result = false; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, "StorageDriveWin::ReadRequest ::ReadFile"); + AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::ReadRequest ::ReadFile"); result = ::ReadFile(file, output, readSize, nullptr, overlapped); } @@ -782,7 +782,7 @@ namespace AZ::IO { auto& fileExists = AZStd::get(request->GetCommand()); - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "StorageDriveWin::FileExistsRequest %s : %s", + AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::FileExistsRequest %s : %s", m_name.c_str(), fileExists.m_path.GetRelativePath()); TIMED_AVERAGE_WINDOW_SCOPE(m_getFileExistsTimeAverage); @@ -838,7 +838,7 @@ namespace AZ::IO { auto& command = AZStd::get(request->GetCommand()); - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "StorageDriveWin::FileMetaDataRetrievalRequest %s : %s", + AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::FileMetaDataRetrievalRequest %s : %s", m_name.c_str(), command.m_path.GetRelativePath()); TIMED_AVERAGE_WINDOW_SCOPE(m_getFileMetaDataRetrievalTimeAverage); @@ -954,7 +954,7 @@ namespace AZ::IO bool StorageDriveWin::FinalizeReads() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); bool hasWorked = false; for (size_t readSlot = 0; readSlot < m_readSlots_active.size(); ++readSlot) diff --git a/Code/Framework/AzCore/Platform/Windows/profile_telemetry_platform_windows.cmake b/Code/Framework/AzCore/Platform/Windows/profile_telemetry_platform_windows.cmake index df12777586..9ecf9fd999 100644 --- a/Code/Framework/AzCore/Platform/Windows/profile_telemetry_platform_windows.cmake +++ b/Code/Framework/AzCore/Platform/Windows/profile_telemetry_platform_windows.cmake @@ -11,7 +11,3 @@ # NOTE: functions in cmake are global, therefore adding functions to this file # is being avoided to prevent overriding functions declared in other targets platfrom # specific cmake files - -if(LY_RAD_TELEMETRY_ENABLED) - set(LY_COMPILE_DEFINITIONS PUBLIC AZ_PROFILE_TELEMETRY) -endif() diff --git a/Code/Framework/AzCore/Platform/iOS/AzCore/AzCore_Traits_iOS.h b/Code/Framework/AzCore/Platform/iOS/AzCore/AzCore_Traits_iOS.h index 56bc747c09..d53f4b057e 100644 --- a/Code/Framework/AzCore/Platform/iOS/AzCore/AzCore_Traits_iOS.h +++ b/Code/Framework/AzCore/Platform/iOS/AzCore/AzCore_Traits_iOS.h @@ -110,6 +110,20 @@ #define AZ_TRAIT_USE_ERRNO_T_TYPEDEF 0 #define AZ_TRAIT_USE_POSIX_TEMP_FOLDER 0 +// wchar_t/char formatting +// Reason: https://docs.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=msvc-160 +// The Z type character, and the behavior of the c, C, s, and S type characters when they're used with the printf and wprintf functions, +// are Microsoft extensions. The ISO C standard uses c and s consistently for narrow characters and strings, and C and S for wide characters +// and strings, in all formatting functions. +#define AZ_TRAIT_FORMAT_STRING_PRINTF_CHAR "%c" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_WCHAR "%C" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_CHAR "%c" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_WCHAR "%C" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_STRING "%s" +#define AZ_TRAIT_FORMAT_STRING_PRINTF_WSTRING "%S" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_STRING "%s" +#define AZ_TRAIT_FORMAT_STRING_WPRINTF_WSTRING "%S" + // Legacy traits ... #define AZ_TRAIT_LEGACY_CRYCOMMON_USE_WINDOWS_STUBS 1 #define AZ_TRAIT_LEGACY_CRYPAK_UNIX_LIKE_FILE_SYSTEM 1 diff --git a/Code/Framework/AzCore/Platform/iOS/profile_telemetry_platform_ios.cmake b/Code/Framework/AzCore/Platform/iOS/profile_telemetry_platform_ios.cmake index aeb91ebce6..7a325ca97e 100644 --- a/Code/Framework/AzCore/Platform/iOS/profile_telemetry_platform_ios.cmake +++ b/Code/Framework/AzCore/Platform/iOS/profile_telemetry_platform_ios.cmake @@ -5,7 +5,3 @@ # SPDX-License-Identifier: Apache-2.0 OR MIT # # - -if(LY_RAD_TELEMETRY_ENABLED) - set(LY_COMPILE_DEFINITIONS PUBLIC AZ_PROFILE_TELEMETRY) -endif() diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp index 9dae4a3d3f..0ff12a352c 100644 --- a/Code/Framework/AzCore/Tests/AZStd/String.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp @@ -1458,17 +1458,17 @@ namespace UnitTest constexpr double v15 = 0; constexpr const char* v16 = "Hello"; constexpr const wchar_t* v17 = L"Hello"; - constexpr void* v18 = 0; + constexpr void* v18 = nullptr; // This shouldn't give a compile error AZStd::string::format( - "%i %c %uc %c %c %i %i %u %i %lu %li %llu %lli %f %f %s %ls %p", + "%i %c %uc " AZ_TRAIT_FORMAT_STRING_PRINTF_CHAR AZ_TRAIT_FORMAT_STRING_PRINTF_WCHAR " %i %i %u %i %lu %li %llu %lli %f %f " AZ_TRAIT_FORMAT_STRING_PRINTF_STRING AZ_TRAIT_FORMAT_STRING_PRINTF_WSTRING " %p", v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18); // This shouldn't give a compile error AZStd::wstring::format( - L"%i %c %uc %c %lc %i %i %u %i %lu %li %llu %lli %f %f %s %ls %p", - v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18); + L"%i %c %uc " AZ_TRAIT_FORMAT_STRING_WPRINTF_CHAR AZ_TRAIT_FORMAT_STRING_WPRINTF_WCHAR " %i %i %u %i %lu %li %llu %lli %f %f " AZ_TRAIT_FORMAT_STRING_WPRINTF_STRING AZ_TRAIT_FORMAT_STRING_WPRINTF_WSTRING " %p", + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18); class WrappedInt { diff --git a/Code/Framework/AzCore/Tests/AZStd/VectorAndArray.cpp b/Code/Framework/AzCore/Tests/AZStd/VectorAndArray.cpp index dd10d20ef8..933db73c3f 100644 --- a/Code/Framework/AzCore/Tests/AZStd/VectorAndArray.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/VectorAndArray.cpp @@ -36,12 +36,23 @@ using namespace UnitTestInternal; /** * Validate a vector for certain number of elements. */ -#define AZ_TEST_VALIDATE_VECTOR(_Vector, _NumElements) \ - EXPECT_TRUE(_Vector.validate()); \ - EXPECT_EQ(_NumElements, _Vector.size()); \ - EXPECT_TRUE((_NumElements > 0) ? !_Vector.empty() : _Vector.empty()); \ - EXPECT_TRUE((_NumElements > 0) ? _Vector.capacity() >= _NumElements : true); \ - EXPECT_TRUE((_NumElements > 0) ? _Vector.begin() != _Vector.end() : _Vector.begin() == _Vector.end()); \ +#define AZ_TEST_VALIDATE_VECTOR(_Vector, _NumElements) \ + EXPECT_NE(_NumElements, 0); \ + EXPECT_TRUE(_Vector.validate()); \ + EXPECT_EQ(_NumElements, _Vector.size()); \ + EXPECT_TRUE(!_Vector.empty()); \ + EXPECT_TRUE(_Vector.capacity() >= _NumElements); \ + EXPECT_TRUE(_Vector.begin() != _Vector.end()); \ + EXPECT_NE(nullptr, _Vector.data()) + + /** + * Validate a vector for 0 number of elements. The above macro creates expressions that are always true for size == 0 + */ +#define AZ_TEST_VALIDATE_VECTOR_0(_Vector) \ + EXPECT_TRUE(_Vector.validate()); \ + EXPECT_EQ(0, _Vector.size()); \ + EXPECT_TRUE(_Vector.empty()); \ + EXPECT_TRUE(_Vector.begin() == _Vector.end()); \ EXPECT_NE(nullptr, _Vector.data()) namespace UnitTest @@ -312,7 +323,7 @@ namespace UnitTest // erase int_vector1.erase(int_vector1.begin(), int_vector1.end()); - AZ_TEST_VALIDATE_VECTOR(int_vector1, 0); // Zero elements but valid capacity. + AZ_TEST_VALIDATE_VECTOR_0(int_vector1); // Zero elements but valid capacity. int_vector1.push_back(10); int_vector1.push_back(20); @@ -324,11 +335,11 @@ namespace UnitTest // clear int_vector1.clear(); - AZ_TEST_VALIDATE_VECTOR(int_vector1, 0); // Zero elements but valid capacity. + AZ_TEST_VALIDATE_VECTOR_0(int_vector1); // Zero elements but valid capacity. // swap int_vector1.swap(int_vector); - AZ_TEST_VALIDATE_VECTOR(int_vector, 0); + AZ_TEST_VALIDATE_VECTOR_0(int_vector); AZ_TEST_VALIDATE_VECTOR(int_vector1, 33); AZ_TEST_ASSERT(int_vector1.front() == 55); @@ -524,11 +535,11 @@ namespace UnitTest // Default vector (integral type). fixed_vector int_vector_default; - AZ_TEST_VALIDATE_VECTOR(int_vector_default, 0); + AZ_TEST_VALIDATE_VECTOR_0(int_vector_default); // Default vector (non-integral type). fixed_vector myclass_vector_default; - AZ_TEST_VALIDATE_VECTOR(myclass_vector_default, 0); + AZ_TEST_VALIDATE_VECTOR_0(myclass_vector_default); // Create a vector (using fill ctor, with memset optimization to set the values) typedef fixed_vector char_10_type; @@ -633,7 +644,7 @@ namespace UnitTest // erase int_vector1.erase(int_vector1.begin(), int_vector1.end()); - AZ_TEST_VALIDATE_VECTOR(int_vector1, 0); + AZ_TEST_VALIDATE_VECTOR_0(int_vector1); int_vector1.push_back(10); int_vector1.push_back(20); @@ -645,11 +656,11 @@ namespace UnitTest // clear int_vector1.clear(); - AZ_TEST_VALIDATE_VECTOR(int_vector1, 0); + AZ_TEST_VALIDATE_VECTOR_0(int_vector1); // swap int_vector1.swap(int_vector); - AZ_TEST_VALIDATE_VECTOR(int_vector, 0); + AZ_TEST_VALIDATE_VECTOR_0(int_vector); AZ_TEST_VALIDATE_VECTOR(int_vector1, 33); AZ_TEST_ASSERT(int_vector1.front() == 55); @@ -963,7 +974,7 @@ namespace UnitTest AZ_TEST_VALIDATE_VECTOR(deep_vec_2, 12); deep_vec_2.clear(); - AZ_TEST_VALIDATE_VECTOR(deep_vec_2, 0); + AZ_TEST_VALIDATE_VECTOR_0(deep_vec_2); } #endif // AZ_UNIT_TEST_SKIP_STD_VECTOR_AND_ARRAY_TESTS diff --git a/Code/Framework/AzCore/Tests/AZTestShared/Math/MathTestHelpers.cpp b/Code/Framework/AzCore/Tests/AZTestShared/Math/MathTestHelpers.cpp index bf0a1023ab..fc707c9751 100644 --- a/Code/Framework/AzCore/Tests/AZTestShared/Math/MathTestHelpers.cpp +++ b/Code/Framework/AzCore/Tests/AZTestShared/Math/MathTestHelpers.cpp @@ -95,7 +95,7 @@ namespace AZ auto printElement = [&os, &mat](int64_t row, int64_t col) -> std::ostream& { const std::streamsize width = 10; - os << std::setw(width) << std::fixed << mat.GetElement(row, col); + os << std::setw(width) << std::fixed << mat.GetElement(static_cast(row), static_cast(col)); return os; }; diff --git a/Code/Framework/AzCore/Tests/Components.cpp b/Code/Framework/AzCore/Tests/Components.cpp index b14dcbbe53..77524dabc9 100644 --- a/Code/Framework/AzCore/Tests/Components.cpp +++ b/Code/Framework/AzCore/Tests/Components.cpp @@ -1191,154 +1191,6 @@ namespace UnitTest ////////////////////////////////////////////////////////////////////////// } - class FrameProfilerComponentTest - : public AllocatorsFixture - , public FrameProfilerBus::Handler - { - public: - FrameProfilerComponentTest() - : AllocatorsFixture() - { - } - - ////////////////////////////////////////////////////////////////////////// - // FrameProfilerDrillerBus - void OnFrameProfilerData(const FrameProfiler::ThreadDataArray& data) override - { - for (size_t iThread = 0; iThread < data.size(); ++iThread) - { - const FrameProfiler::ThreadData& td = data[iThread]; - FrameProfiler::ThreadData::RegistersMap::const_iterator regIt = td.m_registers.begin(); - size_t numRegisters = m_numRegistersReceived; - for (; regIt != td.m_registers.end(); ++regIt) - { - const FrameProfiler::RegisterData& rd = regIt->second; - - AZ_TEST_ASSERT(rd.m_function != NULL); - if (strstr(rd.m_function, "ChildFunction") || strstr(rd.m_function, "Profile1")) // filter only the test registers - { - ++m_numRegistersReceived; - - EXPECT_GT(rd.m_line, 0); - EXPECT_TRUE(rd.m_name == nullptr || strstr(rd.m_name, "Child1") || strstr(rd.m_name, "Custom name")); - AZ::u32 unitTestCrc = AZ_CRC("UnitTest", 0x8089cea8); - EXPECT_EQ(unitTestCrc, rd.m_systemId); - EXPECT_EQ(ProfilerRegister::PRT_TIME, rd.m_type); - - EXPECT_FALSE(rd.m_frames.empty()); - const FrameProfiler::FrameData& fd = rd.m_frames.back(); - EXPECT_GT(fd.m_frameId, 0u); - EXPECT_GT(fd.m_timeData.m_time, 0); - EXPECT_GT(fd.m_timeData.m_calls, 0); - } - } - - if (numRegisters < m_numRegistersReceived) - { - // we have received valid test registers for this thread, add it to the list - ++m_numThreads; - } - } - } - ////////////////////////////////////////////////////////////////////////// - - int ChildFunction(int input) - { - AZ_PROFILE_TIMER("UnitTest", nullptr, NamedRegister); - int result = 5; - for (int i = 0; i < 10000; ++i) - { - result += i % (input + 3); - } - AZ_PROFILE_TIMER_END(NamedRegister); - return result; - } - - int ChildFunction1(int input) - { - AZ_PROFILE_TIMER("UnitTest", "Child1"); - int result = 5; - for (int i = 0; i < 10000; ++i) - { - result += i % (input + 1); - } - return result; - } - - int Profile1(int numIterations) - { - AZ_PROFILE_TIMER("UnitTest", "Custom name"); - int result = 0; - for (int i = 0; i < numIterations; ++i) - { - result += ChildFunction(i); - } - - result += ChildFunction1(numIterations / 3); - return result; - } - - void run() - { - FrameProfilerBus::Handler::BusConnect(); - - ComponentApplication app; - ComponentApplication::Descriptor desc; - desc.m_useExistingAllocator = true; - desc.m_enableDrilling = false; // we already created a memory driller for the test (AllocatorsFixture) - ComponentApplication::StartupParameters startupParams; - startupParams.m_allocator = &AZ::AllocatorInstance::Get(); - Entity* systemEntity = app.Create(desc, startupParams); - systemEntity->CreateComponent(); - - systemEntity->Init(); - systemEntity->Activate(); // start frame component - - m_numThreads = 0; - m_numRegistersReceived = 0; - - // tick to frame 1 and collect all the samples - app.Tick(); - EXPECT_EQ(0, m_numThreads); - EXPECT_EQ(0, m_numRegistersReceived); - - int numIterations = 10000; - { - AZStd::thread t1(AZStd::bind(&FrameProfilerComponentTest::Profile1, this, numIterations)); - AZStd::thread t2(AZStd::bind(&FrameProfilerComponentTest::Profile1, this, numIterations)); - AZStd::thread t3(AZStd::bind(&FrameProfilerComponentTest::Profile1, this, numIterations)); - AZStd::thread t4(AZStd::bind(&FrameProfilerComponentTest::Profile1, this, numIterations)); - - t1.join(); - t2.join(); - t3.join(); - t4.join(); - } - - // tick to frame 2 and collect all the samples - app.Tick(); - - EXPECT_EQ(4, m_numThreads); - EXPECT_EQ(m_numThreads * 3, m_numRegistersReceived); - - FrameProfilerBus::Handler::BusDisconnect(); - - app.Destroy(); - } - - size_t m_numRegistersReceived; - size_t m_numThreads; - }; - -#if AZ_TRAIT_DISABLE_FAILED_FRAMEPROFILER_TEST - TEST_F(FrameProfilerComponentTest, DISABLED_Test) -#else - TEST_F(FrameProfilerComponentTest, Test) -#endif - { - run(); - } - class SimpleEntityRefTestComponent : public Component { diff --git a/Code/Framework/AzCore/Tests/Console/ConsoleTests.cpp b/Code/Framework/AzCore/Tests/Console/ConsoleTests.cpp index 3a56772b3c..d91ec5ba58 100644 --- a/Code/Framework/AzCore/Tests/Console/ConsoleTests.cpp +++ b/Code/Framework/AzCore/Tests/Console/ConsoleTests.cpp @@ -507,6 +507,70 @@ namespace ConsoleSettingsRegistryTests AZ::Interface::Unregister(&testConsole); } + template + using ConsoleDataWrapper = AZ::ConsoleDataWrapper>; + TEST_P(ConsoleSettingsRegistryFixture, Console_RecordsUnregisteredCommands_And_IsAbleToDeferDispatchCommand_Successfully) + { + AZ::Console testConsole(*m_registry); + AZ::Interface::Register(&testConsole); + // GetDeferredHead is invoked for the side effect of to set the s_deferredHeadInvoked value to true + // This allows scoped console variables to be attached immediately + [[maybe_unused]] auto deferredHead = AZ::ConsoleFunctorBase::GetDeferredHead(); + + + ConsoleDataWrapper localTestInit{ {}, nullptr, "testInit", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestChar{ {}, nullptr, "testChar", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestBool{ {}, nullptr, "testBool", "", AZ::ConsoleFunctorFlags::Null }; + + s_consoleFreeFunctionInvoked = false; + + // Invoke the Commands for Scoped CVar variables above + auto configFileParams = GetParam(); + auto testFilePath = m_testFolder / configFileParams.m_testConfigFileName; + EXPECT_TRUE(AZ::IO::SystemFile::Exists(testFilePath.c_str())); + testConsole.ExecuteConfigFile(testFilePath.Native()); + + EXPECT_EQ(3, localTestInit); + EXPECT_TRUE(static_cast(localTestBool)); + EXPECT_EQ('Q', localTestChar); + + // The following commands from the config files should have been deferred + ConsoleDataWrapper localTestInt8{ {}, nullptr, "testInt8", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestInt16{ {}, nullptr, "testInt16", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestInt32{ {}, nullptr, "testInt32", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestInt64{ {}, nullptr, "testInt64", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestUInt8{ {}, nullptr, "testUInt8", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestUInt16{ {}, nullptr, "testUInt16", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestUInt32{ {}, nullptr, "testUInt32", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestUInt64{ {}, nullptr, "testUInt64", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestFloat{ {}, nullptr, "testFloat", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestDouble{ {}, nullptr, "testDouble", "", AZ::ConsoleFunctorFlags::Null }; + ConsoleDataWrapper localTestString{ {}, nullptr, "testString", "", AZ::ConsoleFunctorFlags::Null }; + + + // The scoped cvars just above should have all been deferred for execution + // Each of them should have executed resulting in the expected return value + EXPECT_TRUE(testConsole.ExecuteDeferredConsoleCommands()); + + EXPECT_EQ(24, localTestInt8); + EXPECT_EQ(-32, localTestInt16); + EXPECT_EQ(41, localTestInt32); + EXPECT_EQ(-51, localTestInt64); + EXPECT_EQ(3, localTestUInt8); + EXPECT_EQ(5, localTestUInt16); + EXPECT_EQ(6, localTestUInt32); + EXPECT_EQ(0xFFFF'FFFF'FFFF'FFFF, localTestUInt64); + EXPECT_FLOAT_EQ(1.0f, localTestFloat); + EXPECT_DOUBLE_EQ(2, localTestDouble); + EXPECT_STREQ("Stable", static_cast(localTestString).c_str()); + + // All of the deferred console commands should have executed at this point + // Therefore this invocation should return false + EXPECT_FALSE(testConsole.ExecuteDeferredConsoleCommands()); + + AZ::Interface::Unregister(&testConsole); + } + static constexpr AZStd::string_view UserINIStyleContent = R"( diff --git a/Code/Framework/AzCore/Tests/Debug.cpp b/Code/Framework/AzCore/Tests/Debug.cpp index 6181823737..0d6e1a51e0 100644 --- a/Code/Framework/AzCore/Tests/Debug.cpp +++ b/Code/Framework/AzCore/Tests/Debug.cpp @@ -171,276 +171,6 @@ namespace UnitTest run(); } - class ProfilerTest - : public AllocatorsFixture - { - public: - int m_numRegistersReceived; - - bool ReadRegisterCallback(const ProfilerRegister& reg, const AZStd::thread_id& id) - { - (void)reg; - (void)id; - switch (reg.m_type) - { - case ProfilerRegister::PRT_TIME: - { - AZ_TEST_ASSERT(reg.m_timeData.m_time > 0); - AZ_TEST_ASSERT(reg.m_timeData.m_calls > 0); - } break; - case ProfilerRegister::PRT_VALUE: - { - AZ_TEST_ASSERT(reg.m_userValues.m_value1 == 1 || reg.m_userValues.m_value1 == 2); - AZ_TEST_ASSERT(reg.m_userValues.m_value2 == 0 || reg.m_userValues.m_value2 == 2 || reg.m_userValues.m_value2 == 4); - AZ_TEST_ASSERT(reg.m_userValues.m_value3 == 0 || reg.m_userValues.m_value3 == 3 || reg.m_userValues.m_value3 == 6); - AZ_TEST_ASSERT(reg.m_userValues.m_value4 == 0 || reg.m_userValues.m_value4 == 4 || reg.m_userValues.m_value4 == 8); - AZ_TEST_ASSERT(reg.m_userValues.m_value5 == 0 || reg.m_userValues.m_value5 == 5 || reg.m_userValues.m_value5 == 10); - } break; - } - - //AZ::u64 threadId = (AZ::u64)id.m_id; - //AZ_TracePrintf("Profiler","[%llu] '%s' '%s'(%d) %d Ms (Child calls: %d time: %d Ms) Parent: '%s'!\n",threadId, - // reg.m_name,reg.m_function,reg.m_line,reg.m_time.count(),reg.m_childrenCalls,reg.m_childrenTime.count(),reg.m_lastParent ? reg.m_lastParent->m_name : "No"); - ++m_numRegistersReceived; - return true; - } - - int ChildFunction(int input) - { - AZ_PROFILE_TIMER("UnitTest"); - - auto start = AZStd::chrono::system_clock::now(); - - int result = 5; - for (int i = 0; i < 30000; ++i) - { - result += i % (input + 3); - } - - auto end = AZStd::chrono::system_clock::now(); - AZ_TEST_ASSERT(end >= start); - while (end <= start) - { - end = AZStd::chrono::system_clock::now(); - } - return result; - } - - int ChildFunction1(int input) - { - AZ_PROFILE_TIMER("UnitTest", "Child1"); - - auto start = AZStd::chrono::system_clock::now(); - - int result = 5; - for (int i = 0; i < 30000; ++i) - { - result += i % (input + 1); - } - - - auto end = AZStd::chrono::system_clock::now(); - AZ_TEST_ASSERT(end >= start); - while (end <= start) - { - end = AZStd::chrono::system_clock::now(); - } - - return result; - } - - int Profile1(int numIterations) - { - AZ_PROFILE_TIMER("UnitTest", "Custom name"); - int result = 0; - for (int i = 0; i < numIterations; ++i) - { - result += ChildFunction(i); - } - - result += ChildFunction1(numIterations / 3); - return result; - } - - void UserValuesSet() - { - AZ_PROFILE_VALUE_SET("UnitTest", "UserValues1", 1); - AZ_PROFILE_VALUE_SET("UnitTest", "UserValues2", 1, 2); - AZ_PROFILE_VALUE_SET("UnitTest", "UserValues3", 1, 2, 3); - AZ::s64 v1 = 1, v2 = 2, v3 = 3, v4 = 4, v5 = 5; - AZ_PROFILE_VALUE_SET("UnitTest", "UserValues4", v1, v2, v3, v4); - AZ_PROFILE_VALUE_SET("UnitTest", "UserValues5", v1, v2, v3, v4, v5); - - // test named register - AZ_PROFILE_VALUE_SET_NAMED("UnitTest", "UserValues5", userValues5, v1, v2, v3, v4, v5); -#if defined(AZ_PROFILER_MACRO_DISABLE) - (void)v1; - (void)v2; - (void)v3; - (void)v4; - (void)v5; -#else - AZ_TEST_ASSERT(userValues5 != nullptr); -#endif // !defined(AZ_PROFILER_MACRO_DISABLE) - } - - void UserValuesAdd(int numAdditions) - { - for (int i = 0; i < numAdditions; ++i) - { - AZ_PROFILE_VALUE_ADD("UnitTest", "UserValues1", 1); - AZ_PROFILE_VALUE_ADD("UnitTest", "UserValues2", 1, 2); - AZ_PROFILE_VALUE_ADD("UnitTest", "UserValues3", 1, 2, 3); - AZ::s64 v1 = 1, v2 = 2, v3 = 3, v4 = 4, v5 = 5; - AZ_PROFILE_VALUE_ADD("UnitTest", "UserValues4", v1, v2, v3, v4); - AZ_PROFILE_VALUE_ADD("UnitTest", "UserValues5", v1, v2, v3, v4, v5); - - // test named register - AZ_PROFILE_VALUE_ADD_NAMED("UnitTest", "UserValues5", userValues5, v1, v2, v3, v4, v5); -#if defined(AZ_PROFILER_MACRO_DISABLE) - (void)v1; - (void)v2; - (void)v3; - (void)v4; - (void)v5; -#else - AZ_TEST_ASSERT(userValues5 != nullptr); -#endif // !defined(AZ_PROFILER_MACRO_DISABLE) - } - } - - void run() - { - AZ_TEST_ASSERT(!Profiler::IsReady()); - Profiler::Create(); - AZ_TEST_ASSERT(Profiler::IsReady()); - Profiler::Destroy(); - AZ_TEST_ASSERT(!Profiler::IsReady()); - -#if !defined(AZ_PROFILER_MACRO_DISABLE) - Profiler::Create(); - - //Profile1(); - - //Profiler::Instance().ReadRegisterValues(AZStd::bind(&ProfilerTest::ReadRegisterCallback,this,AZStd::placeholders::_1,AZStd::placeholders::_2)); - - //Profiler::Instance().ResetRegisters(); - - AZStd::thread_id removeThreadId; - AZStd::chrono::microseconds elapsed[2]; - int numIterations = 10000; - for (int i = 0; i < 2; ++i) - { - // for the second run we should not record any data - if (i == 1) - { - Profiler::Instance().DeactivateSystem("UnitTest"); - } - - AZStd::chrono::system_clock::time_point start = AZStd::chrono::system_clock::now(); - AZStd::thread t1(AZStd::bind(&ProfilerTest::Profile1, this, numIterations)); - AZStd::thread t2(AZStd::bind(&ProfilerTest::Profile1, this, numIterations)); - AZStd::thread t3(AZStd::bind(&ProfilerTest::Profile1, this, numIterations)); - AZStd::thread t4(AZStd::bind(&ProfilerTest::Profile1, this, numIterations)); - AZStd::thread t5(AZStd::bind(&ProfilerTest::Profile1, this, numIterations)); - AZStd::thread t6(AZStd::bind(&ProfilerTest::Profile1, this, numIterations)); - AZStd::thread t7(AZStd::bind(&ProfilerTest::Profile1, this, numIterations)); - AZStd::thread t8(AZStd::bind(&ProfilerTest::Profile1, this, numIterations)); - - removeThreadId = t4.get_id(); - - t1.join(); - t2.join(); - t3.join(); - t4.join(); - t5.join(); - t6.join(); - t7.join(); - t8.join(); - elapsed[i] = AZStd::chrono::system_clock::now() - start; - //AZ_Printf("Profiler","Elapsed time %d\n",elapsed[i].count()); - - if (i == 0) - { - // just as test remove all associated data and registers. - Profiler::Instance().RemoveThreadData(removeThreadId); - } - - m_numRegistersReceived = 0; - Profiler::Instance().ReadRegisterValues(AZStd::bind(&ProfilerTest::ReadRegisterCallback, this, AZStd::placeholders::_1, AZStd::placeholders::_2)); - if (i == 0) - { - AZ_TEST_ASSERT(m_numRegistersReceived == 7 * 3); // 3 registers for each thread (8 threads - 1 we removed the data for 't4') - } - else - { - AZ_TEST_ASSERT(m_numRegistersReceived == 0); - } - } - Profiler::Destroy(); - - // Test user value registers - Profiler::Create(); - - for (int i = 0; i < 2; ++i) - { - // for the second run we should not record any data - if (i == 1) - { - Profiler::Instance().DeactivateSystem("UnitTest"); - } - - AZStd::thread t1(AZStd::bind(&ProfilerTest::UserValuesSet, this)); - AZStd::thread t2(AZStd::bind(&ProfilerTest::UserValuesSet, this)); - AZStd::thread t3(AZStd::bind(&ProfilerTest::UserValuesSet, this)); - AZStd::thread t4(AZStd::bind(&ProfilerTest::UserValuesSet, this)); - AZStd::thread t5(AZStd::bind(&ProfilerTest::UserValuesAdd, this, 2)); - AZStd::thread t6(AZStd::bind(&ProfilerTest::UserValuesAdd, this, 2)); - AZStd::thread t7(AZStd::bind(&ProfilerTest::UserValuesAdd, this, 2)); - AZStd::thread t8(AZStd::bind(&ProfilerTest::UserValuesAdd, this, 2)); - - removeThreadId = t4.get_id(); - - t1.join(); - t2.join(); - t3.join(); - t4.join(); - t5.join(); - t6.join(); - t7.join(); - t8.join(); - - if (i == 0) - { - // just as test remove all associated data and registers. - Profiler::Instance().RemoveThreadData(removeThreadId); - } - - m_numRegistersReceived = 0; - Profiler::Instance().ReadRegisterValues(AZStd::bind(&ProfilerTest::ReadRegisterCallback, this, AZStd::placeholders::_1, AZStd::placeholders::_2)); - if (i == 0) - { - AZ_TEST_ASSERT(m_numRegistersReceived == 7 * 6); // 6 registers for each thread (8 threads - 1 we removed the data for 't4' ) - } - else - { - AZ_TEST_ASSERT(m_numRegistersReceived == 0); - } - } - Profiler::Destroy(); -#endif - } - }; -#if AZ_TRAIT_DISABLE_FAILED_PROFILER_TEST - TEST_F(ProfilerTest, DISABLED_Test) -#else - TEST_F(ProfilerTest, Test) -#endif // AZ_TRAIT_DISABLE_FAILED_PROFILER_TEST - - { - run(); - } - TEST(Time, Test) { AZStd::sys_time_t ticksPerSecond = AZStd::GetTimeTicksPerSecond(); diff --git a/Code/Framework/AzCore/Tests/Jobs.cpp b/Code/Framework/AzCore/Tests/Jobs.cpp index 4a1af4cc24..0eb46a0051 100644 --- a/Code/Framework/AzCore/Tests/Jobs.cpp +++ b/Code/Framework/AzCore/Tests/Jobs.cpp @@ -1736,7 +1736,7 @@ namespace Benchmark std::numeric_limits::max()); std::generate(m_randomPriorities.begin(), m_randomPriorities.end(), [&randomPriorityDistribution, &randomPriorityGenerator]() { - return randomPriorityDistribution(randomPriorityGenerator); + return static_cast(randomPriorityDistribution(randomPriorityGenerator)); }); // Generate some random depths diff --git a/Code/Framework/AzCore/Tests/Math/ObbTests.cpp b/Code/Framework/AzCore/Tests/Math/ObbTests.cpp index b0012ee93c..de285343f6 100644 --- a/Code/Framework/AzCore/Tests/Math/ObbTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/ObbTests.cpp @@ -6,16 +6,16 @@ * */ -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include using namespace AZ; -namespace UnitTest +namespace UnitTest::ObbTests { const Vector3 position(1.0f, 2.0f, 3.0f); const Quaternion rotation = Quaternion::CreateRotationZ(Constants::QuarterPi); @@ -151,4 +151,4 @@ namespace UnitTest EXPECT_NEAR(obb.GetDistanceSq(Vector3(2.4f, 0.5f, 1.5f)), 0.5532f, 1e-3f); EXPECT_NEAR(obb.GetDistanceSq(Vector3(1.1f, 7.3f, 5.8f)), 1.3612f, 1e-3f); } -} +} // namespace UnitTest::ObbTests diff --git a/Code/Framework/AzCore/Tests/Math/SfmtTests.cpp b/Code/Framework/AzCore/Tests/Math/SfmtTests.cpp index f40246b8e9..73fdd6e2fc 100644 --- a/Code/Framework/AzCore/Tests/Math/SfmtTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/SfmtTests.cpp @@ -8,6 +8,7 @@ #include #include +#include using namespace AZ; @@ -27,8 +28,8 @@ namespace UnitTest void SetUp() override { AllocatorsFixture::SetUp(); - array1 = (AZ::u64*)azmalloc(sizeof(AZ::u64) * 2 * (BLOCK_SIZE / 4), AZStd::alignment_of::value); - array2 = (AZ::u64*)azmalloc(sizeof(AZ::u64) * 2 * (10000 / 4), AZStd::alignment_of::value); + array1 = (AZ::u64*)azmalloc(sizeof(AZ::u64) * 2 * (BLOCK_SIZE / 4), AZStd::alignment_of::value); + array2 = (AZ::u64*)azmalloc(sizeof(AZ::u64) * 2 * (10000 / 4), AZStd::alignment_of::value); } void TearDown() override diff --git a/Code/Framework/AzCore/Tests/Math/SimdMathTests.cpp b/Code/Framework/AzCore/Tests/Math/SimdMathTests.cpp index b05a95dbce..4570d79b83 100644 --- a/Code/Framework/AzCore/Tests/Math/SimdMathTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/SimdMathTests.cpp @@ -94,7 +94,7 @@ namespace UnitTest float testStoreValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; VectorType::StoreUnaligned(testStoreValues, result); - for (int32_t i = 0; i < VectorType::ElementCount; ++i) + for (uint32_t i = 0; i < VectorType::ElementCount; ++i) { if (i == replaceIndex) { diff --git a/Code/Framework/AzCore/Tests/Memory/HphaSchemaErrorDetection.cpp b/Code/Framework/AzCore/Tests/Memory/HphaSchemaErrorDetection.cpp index 3bda826313..44c1b1641d 100644 --- a/Code/Framework/AzCore/Tests/Memory/HphaSchemaErrorDetection.cpp +++ b/Code/Framework/AzCore/Tests/Memory/HphaSchemaErrorDetection.cpp @@ -297,7 +297,7 @@ AZ_POP_DISABLE_WARNING // the overflow guard is generated out of rand, so we set a fixed seed before doing the allocation // to get a deterministic guard srand(0); - const unsigned char expectedInitialGuard = rand(); + const unsigned char expectedInitialGuard = static_cast(rand()); srand(0); TestClass<16>* someObject = aznew TestClass<16>(); diff --git a/Code/Framework/AzCore/Tests/Name/NameTests.cpp b/Code/Framework/AzCore/Tests/Name/NameTests.cpp index 3b6310b1de..3db77ac4c4 100644 --- a/Code/Framework/AzCore/Tests/Name/NameTests.cpp +++ b/Code/Framework/AzCore/Tests/Name/NameTests.cpp @@ -171,7 +171,17 @@ namespace UnitTest azsnprintf(buffer, RandomStringBufferSize, "%d", m_random.GetRandom()); return buffer; } - + + AZ::Internal::NameData* GetNameData(AZ::Name& name) + { + return name.m_data.get(); + } + + void FreeMemoryFromNameData(AZ::Internal::NameData* nameData) + { + delete nameData; + } + AZ::SimpleLcgRandom m_random; }; @@ -488,13 +498,20 @@ namespace UnitTest TEST_F(NameTest, ReportLeakedNames) { - AZ::Name leakedName{"hello"}; - AZ_TEST_START_TRACE_SUPPRESSION; - AZ::NameDictionary::Destroy(); - AZ_TEST_STOP_TRACE_SUPPRESSION(1); + AZ::Internal::NameData* leakedNameData = nullptr; + { + AZ::Name leakedName{ "hello" }; + AZ_TEST_START_TRACE_SUPPRESSION; + AZ::NameDictionary::Destroy(); + AZ_TEST_STOP_TRACE_SUPPRESSION(1); - // Create the dictionary again to avoid error in TearDown() - AZ::NameDictionary::Create(); + leakedNameData = GetNameData(leakedName); + + // Create the dictionary again to avoid crash when the intrusive_ptr in Name tries to access NameDictionary to free it + AZ::NameDictionary::Create(); + } + + FreeMemoryFromNameData(leakedNameData); // free it to avoid memory system reporting the leak } TEST_F(NameTest, NullTerminatedTest) @@ -587,7 +604,7 @@ namespace UnitTest AZ::NameDictionary::Create(); // 3 threads per name effectively makes two readers and one writer (the first to run will write in the dictionary) - RunConcurrencyTest(AZ_TRAIT_UNIT_TEST_NAME_COUNT, 3); + RunConcurrencyTest(AZStd::thread::hardware_concurrency(), 3); } TEST_F(NameTest, ConcurrencyDataTest_EachThreadCreatesOneName_HighCollisions) @@ -597,7 +614,7 @@ namespace UnitTest AZ::NameDictionary::Create(); // 3 threads per name effectively makes two readers and one writer (the first to run will write in the dictionary) - RunConcurrencyTest(AZ_TRAIT_UNIT_TEST_NAME_COUNT, 3); + RunConcurrencyTest(AZStd::thread::hardware_concurrency() / 2, 3); } TEST_F(NameTest, ConcurrencyDataTest_EachThreadRepeatedlyCreatesAndReleasesOneName_NoCollision) @@ -624,7 +641,7 @@ namespace UnitTest TEST_F(NameTest, DISABLED_NameVsStringPerf_Creation) { - constexpr int CreateCount = AZ_TRAIT_UNIT_TEST_NAME_COUNT; + constexpr int CreateCount = 1000; char buffer[RandomStringBufferSize]; @@ -633,7 +650,7 @@ namespace UnitTest AZStd::sys_time_t stringTime; { - const size_t dictionaryNoiseSize = AZ_TRAIT_UNIT_TEST_NAME_COUNT; + const size_t dictionaryNoiseSize = 1000; AZStd::vector existingNames; existingNames.reserve(dictionaryNoiseSize); diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/IntSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/IntSerializerTests.cpp index be06e76f68..c971535f0b 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/IntSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/IntSerializerTests.cpp @@ -32,12 +32,12 @@ namespace JsonSerializationTests AZStd::shared_ptr CreateDefaultInstance() override { - return AZStd::make_shared(0); + return AZStd::make_shared(NumberType(0)); } AZStd::shared_ptr CreateFullySetInstance() override { - return AZStd::make_shared(4); + return AZStd::make_shared(NumberType(4)); } AZStd::string_view GetJsonForFullySetInstance() override diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/MathMatrixSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/MathMatrixSerializerTests.cpp index ca558d1624..1126aeb662 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/MathMatrixSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/MathMatrixSerializerTests.cpp @@ -225,7 +225,6 @@ namespace JsonSerializationTests static_assert((RowCount >= 3 && RowCount <= 4) && (ColumnCount >= 3 && ColumnCount <= 4), "Only matrix 3x3, 3x4 or 4x4 are supported by this test."); } - return "{}"; } void ConfigureFeatures(JsonSerializerConformityTestDescriptorFeatures& features) override diff --git a/Code/Framework/AzCore/Tests/TimeDataStatistics.cpp b/Code/Framework/AzCore/Tests/TimeDataStatistics.cpp index 50856b1df8..21b42fc451 100644 --- a/Code/Framework/AzCore/Tests/TimeDataStatistics.cpp +++ b/Code/Framework/AzCore/Tests/TimeDataStatistics.cpp @@ -83,7 +83,7 @@ namespace UnitTest int ChildFunction0(int numIterations, int sleepTimeMilliseconds) { - AZ_PROFILE_TIMER("UnitTest", CHILD_TIMER_STAT0); + AZ_PROFILE_SCOPE(UnitTest, CHILD_TIMER_STAT0); AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(sleepTimeMilliseconds)); int result = 5; for (int i = 0; i < numIterations; ++i) @@ -95,7 +95,7 @@ namespace UnitTest int ChildFunction1(int numIterations, int sleepTimeMilliseconds) { - AZ_PROFILE_TIMER("UnitTest", CHILD_TIMER_STAT1); + AZ_PROFILE_SCOPE(UnitTest, CHILD_TIMER_STAT1); AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(sleepTimeMilliseconds)); int result = 5; for (int i = 0; i < numIterations; ++i) @@ -107,7 +107,7 @@ namespace UnitTest int ParentFunction(int numIterations, int sleepTimeMilliseconds) { - AZ_PROFILE_TIMER("UnitTest", PARENT_TIMER_STAT); + AZ_PROFILE_SCOPE(UnitTest, PARENT_TIMER_STAT); AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(sleepTimeMilliseconds)); int result = 0; result += ChildFunction0(numIterations, sleepTimeMilliseconds); @@ -198,10 +198,11 @@ namespace UnitTest AZStd::unique_ptr m_statsManager; };//class TimeDataStatisticsManagerTest - TEST_F(TimeDataStatisticsManagerTest, Test) - { - run(); - } + // TODO:BUDGETS disabled until profiler budgets system comes online + // TEST_F(TimeDataStatisticsManagerTest, Test) + // { + // run(); + // } //End of all Tests of TimeDataStatisticsManagerTest }//namespace UnitTest diff --git a/Code/Framework/AzCore/Tests/azcoretests_files.cmake b/Code/Framework/AzCore/Tests/azcoretests_files.cmake index ca0e2862fc..911eaa7b10 100644 --- a/Code/Framework/AzCore/Tests/azcoretests_files.cmake +++ b/Code/Framework/AzCore/Tests/azcoretests_files.cmake @@ -60,7 +60,6 @@ set(FILES SerializeContextFixture.h Slice.cpp State.cpp - StatisticalProfiler.cpp Statistics.cpp StreamerTests.cpp StringFunc.cpp diff --git a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp index 7b4c328af9..abd97aee0d 100644 --- a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp +++ b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -540,7 +541,7 @@ namespace AzFramework const AZStd::function& workForNewThread, const char* newThreadName) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); AZStd::thread_desc newThreadDesc; newThreadDesc.m_cpuId = AFFINITY_MASK_USERTHREADS; @@ -548,7 +549,7 @@ namespace AzFramework AZStd::binary_semaphore binarySemaphore; AZStd::thread newThread([&workForNewThread, &binarySemaphore, &newThreadName] { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzFramework, + AZ_PROFILE_SCOPE(AzFramework, "Application::PumpSystemEventLoopWhileDoingWorkInNewThread:ThreadWorker %s", newThreadName); workForNewThread(); @@ -559,7 +560,7 @@ namespace AzFramework PumpSystemEventLoopUntilEmpty(); } { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzFramework, + AZ_PROFILE_SCOPE(AzFramework, "Application::PumpSystemEventLoopWhileDoingWorkInNewThread:WaitOnThread %s", newThreadName); newThread.join(); } @@ -571,10 +572,14 @@ namespace AzFramework //////////////////////////////////////////////////////////////////////////// void Application::RunMainLoop() { + uint32_t frameCounter = 0; while (!m_exitMainLoopRequested) { PumpSystemEventLoopUntilEmpty(); + + AZ_PROFILE_SCOPE(AzCore, "Frame %i", frameCounter); Tick(); + ++frameCounter; } } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp index a3d2103650..5bcdc3d719 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -206,7 +207,7 @@ namespace AZ::IO::ArchiveInternal ////////////////////////////////////////////////////////////////////////// size_t ArchiveInternal::CZipPseudoFile::FRead(void* pDest, size_t nSize, size_t nCount, [[maybe_unused]] AZ::IO::HandleType fileHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!GetFile()) { @@ -235,7 +236,7 @@ namespace AZ::IO::ArchiveInternal return 0; } - if (nReadBytes != nTotal) + if (static_cast(nReadBytes) != nTotal) { AZ_Warning("Archive", false, "FRead did not read expected number of byte from file, only %zu of %lld bytes read", nTotal, nReadBytes); nTotal = (size_t)nReadBytes; @@ -271,7 +272,7 @@ namespace AZ::IO::ArchiveInternal ////////////////////////////////////////////////////////////////////////// void* ArchiveInternal::CZipPseudoFile::GetFileData(size_t& nFileSize, [[maybe_unused]] AZ::IO::HandleType fileHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); if (!GetFile()) { @@ -347,17 +348,12 @@ namespace AZ::IO::ArchiveInternal return EOF; } int c = EOF; - int i; - for (i = 0; i < 1; i++) + if (m_nCurSeek == GetFileSize()) { - if (i + m_nCurSeek == GetFileSize()) - { - return c; - } - c = pData[i + m_nCurSeek]; - break; + return c; } - m_nCurSeek += i + 1; + c = pData[m_nCurSeek]; + m_nCurSeek += 1; return c; } } @@ -685,7 +681,7 @@ namespace AZ::IO ////////////////////////////////////////////////////////////////////////// AZ::IO::HandleType Archive::FOpen(AZStd::string_view pName, const char* szMode, uint32_t nInputFlags) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); const size_t pathLen = pName.size(); if (pathLen == 0 || pathLen >= MaxPath) @@ -693,7 +689,7 @@ namespace AZ::IO return AZ::IO::InvalidHandle; } - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::Game, "File: %.*s Archive: %p", + AZ_PROFILE_SCOPE(Game, "File: %.*s Archive: %p", aznumeric_cast(pName.size()), pName.data(), this); SAutoCollectFileAccessTime accessTime(this); @@ -716,7 +712,7 @@ namespace AZ::IO } const bool fileWritable = (nOSFlags & (AZ::IO::OpenMode::ModeWrite | AZ::IO::OpenMode::ModeAppend | AZ::IO::OpenMode::ModeUpdate)) != AZ::IO::OpenMode::Invalid; - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::Game, "File: %s Archive: %p", szFullPath->c_str(), this); + AZ_PROFILE_SCOPE(Game, "File: %s Archive: %p", szFullPath->c_str(), this); if (fileWritable) { // we need to open the file for writing, but we failed to do so. @@ -1094,8 +1090,8 @@ namespace AZ::IO ////////////////////////////////////////////////////////////////////////// size_t Archive::FReadRaw(void* pData, size_t nSize, size_t nCount, AZ::IO::HandleType fileHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::Game, "Size: %d Archive: %p", nSize, this); + AZ_PROFILE_FUNCTION(AzCore); + AZ_PROFILE_SCOPE(Game, "Size: %d Archive: %p", nSize, this); SAutoCollectFileAccessTime accessTime(this); ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); @@ -1112,7 +1108,7 @@ namespace AZ::IO ////////////////////////////////////////////////////////////////////////// size_t Archive::FReadRawAll(void* pData, size_t nFileSize, AZ::IO::HandleType fileHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); SAutoCollectFileAccessTime accessTime(this); ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); @@ -1130,7 +1126,7 @@ namespace AZ::IO ////////////////////////////////////////////////////////////////////////// void* Archive::FGetCachedFileData(AZ::IO::HandleType fileHandle, size_t& nFileSize) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); SAutoCollectFileAccessTime accessTime(this); ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); @@ -1791,11 +1787,11 @@ namespace AZ::IO AZ_Assert(m_pZip, "ZipFile is nullptr"); AZ_Assert(m_pFileEntry && m_pZip->IsOwnerOf(m_pFileEntry), "ZipFile is not owner of m_pFileEntry"); - if (nDataSize != m_pFileEntry->desc.lSizeUncompressed && bDecompress) + if (static_cast(nDataSize) != m_pFileEntry->desc.lSizeUncompressed && bDecompress) { return false; } - else if (nDataSize != m_pFileEntry->desc.lSizeCompressed && !bDecompress) + else if (static_cast(nDataSize) != m_pFileEntry->desc.lSizeCompressed && !bDecompress) { return false; } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp index baabfb35cc..d74f69e27b 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp @@ -75,7 +75,7 @@ namespace AZ::IO::ZipDir for (i = 0; i < AZ_ARRAY_SIZE(szBuf) - 1; ++i) { int r = distrib(gen); - szBuf[i] = r > 9 ? (r - 10) + 'a' : '0' + r; + szBuf[i] = static_cast(r > 9 ? (r - 10) + 'a' : '0' + r); } szBuf[i] = '\0'; return szBuf; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp index 445bba63f4..5f0d58a4cb 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp @@ -104,7 +104,7 @@ namespace AZ::IO::ZipDir::ZipDirStructuresInternal if (*pReturnCode == Z_BUF_ERROR) { // As long as we consumed something, keep going. Only fail permanently if we've stalled. - if (nAvailIn != pZStream->avail_in || nAvailOut != pZStream->avail_out) + if (nAvailIn != static_cast(pZStream->avail_in) || nAvailOut != static_cast(pZStream->avail_out)) { *pReturnCode = Z_OK; } @@ -338,14 +338,15 @@ namespace AZ::IO::ZipDir else { AZ::IO::HandleType realFileHandle = m_fileHandle; - size_t nFileSize = ~0; AZ::u64 fileSize = 0; if (!m_fileIOBase->Size(realFileHandle, fileSize)) { - goto error; + // Error + m_nSize = 0; + return; } - nFileSize = static_cast(fileSize); + const size_t nFileSize = static_cast(fileSize); m_pInMemoryData = ZipDirStructuresInternal::CreateMemoryBlock(nFileSize, szUsage); @@ -353,16 +354,18 @@ namespace AZ::IO::ZipDir if (!m_fileIOBase->Seek(realFileHandle, 0, AZ::IO::SeekType::SeekFromStart)) { - goto error; + // Error + m_nSize = 0; + return; } if (!m_fileIOBase->Read(realFileHandle, m_pInMemoryData->m_address.get(), nFileSize, true)) { - goto error; + // Error + m_nSize = 0; + return; } return; - error: - m_nSize = 0; } } } @@ -832,18 +835,18 @@ namespace AZ::IO::ZipDir // conversion routines for the date/time fields used in Zip uint16_t DOSDate(tm* t) { - return + return static_cast( ((t->tm_year - 80) << 9) | (t->tm_mon << 5) - | t->tm_mday; + | t->tm_mday); } uint16_t DOSTime(tm* t) { - return + return static_cast( ((t->tm_hour) << 11) | ((t->tm_min) << 5) - | ((t->tm_sec) >> 1); + | ((t->tm_sec) >> 1)); } // sets the current time to modification time @@ -872,7 +875,7 @@ namespace AZ::IO::ZipDir // we'll need CRC32 of the file to pack it this->desc.lCRC32 = AZ::Crc32(pUncompressed, nSize); - this->nMethod = nCompressionMethod; + this->nMethod = static_cast(nCompressionMethod); } uint64_t FileEntry::GetModificationTime() diff --git a/Code/Framework/AzFramework/AzFramework/Entity/EntityContext.cpp b/Code/Framework/AzFramework/AzFramework/Entity/EntityContext.cpp index a323033001..c1283c9379 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/EntityContext.cpp +++ b/Code/Framework/AzFramework/AzFramework/Entity/EntityContext.cpp @@ -167,7 +167,7 @@ namespace AzFramework //========================================================================= void EntityContext::HandleEntitiesAdded(const EntityList& entities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); for (AZ::Entity* entity : entities) { @@ -184,7 +184,7 @@ namespace AzFramework //========================================================================= void EntityContext::HandleEntitiesRemoved(const EntityIdList& entityIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); for (AZ::EntityId id : entityIds) { diff --git a/Code/Framework/AzFramework/AzFramework/Entity/SliceEntityOwnershipService.cpp b/Code/Framework/AzFramework/AzFramework/Entity/SliceEntityOwnershipService.cpp index 8ed89ee121..9a077cd611 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/SliceEntityOwnershipService.cpp +++ b/Code/Framework/AzFramework/AzFramework/Entity/SliceEntityOwnershipService.cpp @@ -155,7 +155,7 @@ namespace AzFramework void SliceEntityOwnershipService::CreateRootSlice() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); AZ_Assert(m_rootAsset && m_rootAsset.Get(), "Root slice asset has not been created yet."); @@ -164,7 +164,7 @@ namespace AzFramework void SliceEntityOwnershipService::CreateRootSlice(AZ::SliceAsset* rootSliceAsset) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); AZ_Assert(m_rootAsset && m_rootAsset.Get(), "Root slice asset has not been created yet."); AZ::Entity* rootEntity = new AZ::Entity(); @@ -240,7 +240,7 @@ namespace AzFramework bool SliceEntityOwnershipService::LoadFromStream(AZ::IO::GenericStream& stream, bool remapIds, EntityIdToEntityIdMap* idRemapTable, const AZ::ObjectStream::FilterDescriptor& filterDesc) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); AZ_Assert(m_rootAsset, "The entity ownership service has not been initialized."); @@ -259,7 +259,7 @@ namespace AzFramework bool SliceEntityOwnershipService::HandleRootEntityReloadedFromStream(AZ::Entity* rootEntity, bool remapIds, AZ::SliceComponent::EntityIdToEntityIdMap* idRemapTable) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); if (!rootEntity) { @@ -385,7 +385,7 @@ namespace AzFramework void SliceEntityOwnershipService::OnAssetReady(AZ::Data::Asset readyAsset) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); AZ_ASSET_ATTACH_TO_SCOPE(readyAsset.Get()); AZ_Assert(readyAsset.GetAs(), "Asset is not a slice!"); @@ -472,7 +472,7 @@ namespace AzFramework void SliceEntityOwnershipService::OnAssetReloaded(AZ::Data::Asset asset) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); if (asset == m_rootAsset && asset.Get() != m_rootAsset.Get()) { Reset(); @@ -548,7 +548,7 @@ namespace AzFramework AZ::SliceComponent::SliceInstanceAddress SliceEntityOwnershipService::CloneSliceInstance( AZ::SliceComponent::SliceInstanceAddress sourceInstance, AZ::SliceComponent::EntityIdToEntityIdMap& sourceToCloneEntityIdMap) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); AZ_Assert(sourceInstance.IsValid(), "Source slice instance is invalid."); diff --git a/Code/Framework/AzFramework/AzFramework/IO/RemoteFileIO.cpp b/Code/Framework/AzFramework/AzFramework/IO/RemoteFileIO.cpp index 75b43100c5..25bc31b760 100644 --- a/Code/Framework/AzFramework/AzFramework/IO/RemoteFileIO.cpp +++ b/Code/Framework/AzFramework/AzFramework/IO/RemoteFileIO.cpp @@ -1081,16 +1081,6 @@ namespace AZ return ResultCode::Error; } - //bound check - //note that seeking beyond end or before beginning is system dependent - //therefore we will define that on all platforms it is not allowed - if (newFilePosition < 0) - { - AZ_TracePrintf(RemoteFileIOChannel, "RemoteFileIO::Seek(fileHandle=%u, offset=%i, type=%s) seek to a position before the begining of a file!", fileHandle, offset, type == SeekType::SeekFromCurrent ? "SeekFromCurrent" : type == SeekType::SeekFromEnd ? "SeekFromEnd" : type == SeekType::SeekFromStart ? "SeekFromStart" : "Unknown"); - REMOTEFILE_LOG_APPEND(AZStd::string::format("RemoteFileIO::Seek(fileHandle=%u, offset=%i, type=%s) seek to a position before the begining of a file!", fileHandle, offset, type == SeekType::SeekFromCurrent ? "SeekFromCurrent" : type == SeekType::SeekFromEnd ? "SeekFromEnd" : type == SeekType::SeekFromStart ? "SeekFromStart" : "Unknown").c_str()); - newFilePosition = 0; - } - else { AZ::u64 fileSize = 0; Size(fileHandle, fileSize); diff --git a/Code/Framework/AzFramework/AzFramework/IO/RemoteStorageDrive.cpp b/Code/Framework/AzFramework/AzFramework/IO/RemoteStorageDrive.cpp index 5b38a5e966..8db0c27475 100644 --- a/Code/Framework/AzFramework/AzFramework/IO/RemoteStorageDrive.cpp +++ b/Code/Framework/AzFramework/AzFramework/IO/RemoteStorageDrive.cpp @@ -80,7 +80,7 @@ namespace AzFramework { using namespace AZ::IO; - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); AZ_Assert(request, "PrepareRequest was provided a null request."); if (AZStd::holds_alternative(request->GetCommand())) @@ -278,7 +278,7 @@ namespace AzFramework { using namespace AZ::IO; - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); auto data = AZStd::get_if(&request->GetCommand()); AZ_Assert(data, "Request doing reading in the RemoteStorageDrive didn't contain read data.") @@ -424,7 +424,7 @@ namespace AzFramework { using namespace AZ::IO; - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore); + AZ_PROFILE_FUNCTION(AzCore); TIMED_AVERAGE_WINDOW_SCOPE(m_getFileMetaDataTimeAverage); AZ::u64 fileSize = 0; diff --git a/Code/Framework/AzFramework/AzFramework/Input/Events/InputChannelEventListener.h b/Code/Framework/AzFramework/AzFramework/Input/Events/InputChannelEventListener.h index 2b45012fa3..00bdf30f0e 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Events/InputChannelEventListener.h +++ b/Code/Framework/AzFramework/AzFramework/Input/Events/InputChannelEventListener.h @@ -35,6 +35,7 @@ namespace AzFramework //! Predefined input event listener priority, used to sort handlers from highest to lowest inline static AZ::s32 GetPriorityFirst() { return std::numeric_limits::max(); } inline static AZ::s32 GetPriorityDebug() { return (GetPriorityFirst() / 4) * 3; } + inline static AZ::s32 GetPriorityDebugUI() { return (GetPriorityFirst() / 8) * 5; } inline static AZ::s32 GetPriorityUI() { return GetPriorityFirst() / 2; } inline static AZ::s32 GetPriorityDefault() { return 0; } inline static AZ::s32 GetPriorityLast() { return std::numeric_limits::min(); } diff --git a/Code/Framework/AzFramework/AzFramework/Input/Events/InputTextEventListener.h b/Code/Framework/AzFramework/AzFramework/Input/Events/InputTextEventListener.h index 32c44f83d4..4629a5a5c0 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Events/InputTextEventListener.h +++ b/Code/Framework/AzFramework/AzFramework/Input/Events/InputTextEventListener.h @@ -28,6 +28,7 @@ namespace AzFramework //! Predefined text event listener priority, used to sort handlers from highest to lowest inline static AZ::s32 GetPriorityFirst() { return std::numeric_limits::max(); } inline static AZ::s32 GetPriorityDebug() { return (GetPriorityFirst() / 4) * 3; } + inline static AZ::s32 GetPriorityDebugUI() { return (GetPriorityFirst() / 8) * 5; } inline static AZ::s32 GetPriorityUI() { return GetPriorityFirst() / 2; } inline static AZ::s32 GetPriorityDefault() { return 0; } inline static AZ::s32 GetPriorityLast() { return std::numeric_limits::min(); } diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.cpp b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.cpp index 3ffeb0cf5b..84e0184462 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionGroups.cpp @@ -13,14 +13,6 @@ #include -//This bit is defined in the TouchBending Gem wscript. -//Make sure the bit has a valid value. -#ifdef TOUCHBENDING_LAYER_BIT -#if (TOUCHBENDING_LAYER_BIT < 1) || (TOUCHBENDING_LAYER_BIT > 63) -#error Invalid Bit Definition For the TouchBending Layer Bit -#endif -#endif //#ifdef TOUCHBENDING_LAYER_BIT - namespace AzPhysics { AZ_CLASS_ALLOCATOR_IMPL(CollisionGroup, AZ::SystemAllocator, 0); @@ -31,10 +23,6 @@ namespace AzPhysics const CollisionGroup CollisionGroup::None = 0x0000000000000000ULL; const CollisionGroup CollisionGroup::All = 0xFFFFFFFFFFFFFFFFULL; -#ifdef TOUCHBENDING_LAYER_BIT - const CollisionGroup CollisionGroup::All_NoTouchBend = CollisionGroup::All.GetMask() & ~CollisionLayer::TouchBend.GetMask(); -#endif - void CollisionGroupScriptConstructor(CollisionGroup* thisPtr, AZ::ScriptDataContext& scriptDataContext) { if (int numArgs = scriptDataContext.GetNumArguments(); diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.cpp b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.cpp index 924af41113..42ea38961f 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/Collision/CollisionLayers.cpp @@ -14,14 +14,6 @@ #include -//This bit is defined in the TouchBending Gem wscript. -//Make sure the bit has a valid value. -#ifdef TOUCHBENDING_LAYER_BIT -#if (TOUCHBENDING_LAYER_BIT < 1) || (TOUCHBENDING_LAYER_BIT > 63) -#error Invalid Bit Definition For the TouchBending Layer Bit -#endif -#endif //#ifdef TOUCHBENDING_LAYER_BIT - namespace AzPhysics { AZ_CLASS_ALLOCATOR_IMPL(CollisionLayer, AZ::SystemAllocator, 0); @@ -29,10 +21,6 @@ namespace AzPhysics const CollisionLayer CollisionLayer::Default = 0; -#ifdef TOUCHBENDING_LAYER_BIT - const CollisionLayer CollisionLayer::TouchBend = TOUCHBENDING_LAYER_BIT; -#endif - void CollisionLayer::Reflect(AZ::ReflectContext* context) { if (auto* serializeContext = azrtti_cast(context)) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsTypes.h b/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsTypes.h index bb53d6d3dd..500b34ee34 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsTypes.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Common/PhysicsTypes.h @@ -13,6 +13,7 @@ #include #include #include +#include namespace Physics { @@ -56,7 +57,7 @@ namespace AzPhysics //! A handle to a Scene within the physics simulation. //! A SceneHandle is a tuple of a Crc of the scenes name and the index in the Scene list. using SceneHandle = AZStd::tuple; - static constexpr SceneHandle InvalidSceneHandle = { AZ::Crc32(), -1 }; + static constexpr SceneHandle InvalidSceneHandle = { AZ::Crc32(), SceneIndex(-1) }; //! Ease of use type for referencing a List of SceneHandle objects. using SceneHandleList = AZStd::vector; diff --git a/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/StaticRigidBody.h b/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/StaticRigidBody.h index 2cd3b9f7ae..8f84609379 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/StaticRigidBody.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/StaticRigidBody.h @@ -32,12 +32,20 @@ namespace AzPhysics { public: AZ_CLASS_ALLOCATOR_DECL; - AZ_RTTI(StaticRigidBody, "{13A677BB-7085-4EDB-BCC8-306548238692}", SimulatedBody); + AZ_RTTI(AzPhysics::StaticRigidBody, "{13A677BB-7085-4EDB-BCC8-306548238692}", AzPhysics::SimulatedBody); static void Reflect(AZ::ReflectContext* context); - //Legacy API - may change with LYN-438 + //! Add a shape to the static rigid body. + //! @param shape A shared pointer of the shape to add. virtual void AddShape(const AZStd::shared_ptr& shape) = 0; + + //! Returns the number of shapes that make up this static rigid body. + //! @return Returns the number of shapes as a AZ::u32. virtual AZ::u32 GetShapeCount() { return 0; } + + //! Returns a shared pointer to the requested shape index. + //! @param index The index of the shapes to return. Expected to be between 0 and GetShapeCount(). + //! @return Returns a shared pointer of the shape requested or nullptr if index is out of bounds. virtual AZStd::shared_ptr GetShape([[maybe_unused]]AZ::u32 index) { return nullptr; } }; } diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp b/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp index 6b25c49b88..292cce29ec 100644 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp @@ -357,26 +357,23 @@ namespace AzFramework } } - #pragma warning( push ) - #pragma warning( disable : 4505 ) // StackDump is useful to debug the lua stack. Disable warning about this method being unused. //========================================================================= // DebugPrintStack // Prints the Lua stack starting from the bottom. //========================================================================= - static void DebugPrintStack(lua_State* lua, const AZStd::string& prefix = "") - { - AZStd::string dump = prefix; - const int stackSize = lua_gettop(lua); - for (int stackIdx = 1; stackIdx <= stackSize; ++stackIdx) - { - dump += PrintLuaValue(lua, stackIdx); - dump += " "; // add separator - } - - AZ_Warning("ScriptComponent", false, "Stack Dump: '%s'", dump.c_str()); - } - #pragma warning( pop ) - + // DO NOT DELETE StackDump is useful to debug the lua stack. + //static void DebugPrintStack(lua_State* lua, const AZStd::string& prefix = "") + //{ + // AZStd::string dump = prefix; + // const int stackSize = lua_gettop(lua); + // for (int stackIdx = 1; stackIdx <= stackSize; ++stackIdx) + // { + // dump += PrintLuaValue(lua, stackIdx); + // dump += " "; // add separator + // } + // + // AZ_Warning("ScriptComponent", false, "Stack Dump: '%s'", dump.c_str()); + //} //========================================================================= // Properties__IndexFindSubtable @@ -619,7 +616,7 @@ namespace AzFramework //========================================================================= void ScriptComponent::LoadScript() { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::Script, "Load: %s", m_script.GetHint().c_str()); + AZ_PROFILE_SCOPE(Script, "Load: %s", m_script.GetHint().c_str()); // Load the script, find the base table, create the entity table // find the Activate/Deactivate functions in the script and call them @@ -634,7 +631,7 @@ namespace AzFramework //========================================================================= void ScriptComponent::UnloadScript() { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::Script, "Unload: %s", m_script.GetHint().c_str()); + AZ_PROFILE_SCOPE(Script, "Unload: %s", m_script.GetHint().c_str()); DestroyEntityTable(); } @@ -822,7 +819,7 @@ namespace AzFramework lua_rawget(lua, baseStackIndex); // ScriptTable[OnActivate] if (lua_isfunction(lua, -1)) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Script, "OnActivate"); + AZ_PROFILE_SCOPE(Script, "OnActivate"); lua_rawgeti(lua, LUA_REGISTRYINDEX, m_table); // push the entity table as the only argument AZ::Internal::LuaSafeCall(lua, 1, 0); // Call OnActivate } @@ -856,7 +853,7 @@ namespace AzFramework lua_rawget(lua, -2); // ScriptTable[OnDeactivte] if (lua_isfunction(lua, -1)) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Script, "OnDeactivate"); + AZ_PROFILE_SCOPE(Script, "OnDeactivate"); lua_pushvalue(lua, -3); // push the entity table as the only argument AZ::Internal::LuaSafeCall(lua, 1, 0); // Call OnDeactivate diff --git a/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp b/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp index eec384a695..c1ce31613c 100644 --- a/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp @@ -625,7 +625,7 @@ namespace AzFramework return; } - AZ_PROFILE_TIMER("TargetManager"); + AZ_PROFILE_SCOPE(AzFramework, "TargetManager::SendTmMessage"); AZStd::vector msgBuffer; AZ::IO::ByteContainerStream > outMsg(&msgBuffer); @@ -651,7 +651,7 @@ namespace AzFramework void TargetManagementComponent::DispatchMessages(MsgSlotId id) { - AZ_PROFILE_TIMER("TargetManager"); + AZ_PROFILE_SCOPE(AzFramework, "TargetManager::DispatchMessages"); AZStd::lock_guard lock(m_inboxMutex); size_t maxMsgsToProcess = m_inbox.size(); TmMsgQueue::iterator itMsg = m_inbox.begin(); @@ -684,7 +684,7 @@ namespace AzFramework { if (m_networkImpl->m_gridMate) { - AZ_PROFILE_TIMER("TargetManager"); + AZ_PROFILE_SCOPE(AzFramework, "TargetManager::Tick"); if (!m_networkImpl->m_session && !m_networkImpl->m_gridSearch) { if (AZStd::chrono::system_clock::now() > m_reconnectionTime) @@ -694,7 +694,7 @@ namespace AzFramework } { - AZ_PROFILE_TIMER("TargetManager", "Tick Gridmate"); + AZ_PROFILE_SCOPE(AzFramework, "TargetManager::Tick Gridmate"); m_networkImpl->m_gridMate->Update(); if (m_networkImpl->m_session && m_networkImpl->m_session->GetReplicaMgr()) { @@ -707,7 +707,7 @@ namespace AzFramework if (m_networkImpl->m_session) { - AZ_PROFILE_TIMER("TargetManager", "Send/Receive TmMsgs"); + AZ_PROFILE_SCOPE(AzFramework, "TargetManager::Tick Send/Receive TmMsgs"); // Receive for (unsigned int i = 0; i < m_networkImpl->m_session->GetNumberOfMembers(); ++i) diff --git a/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h b/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h index 2e7cd1d170..08e238434e 100644 --- a/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h +++ b/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h @@ -102,11 +102,25 @@ namespace AzFramework static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; ////////////////////////////////////////////////////////////////////////// - virtual void OnTerrainDataCreateBegin() {}; - virtual void OnTerrainDataCreateEnd() {}; + enum TerrainDataChangedMask : uint8_t + { + None = 0b00000000, + Settings = 0b00000001, + HeightData = 0b00000010, + ColorData = 0b00000100, + SurfaceData = 0b00001000 + }; - virtual void OnTerrainDataDestroyBegin() {}; - virtual void OnTerrainDataDestroyEnd() {}; + virtual void OnTerrainDataCreateBegin() {} + virtual void OnTerrainDataCreateEnd() {} + + virtual void OnTerrainDataDestroyBegin() {} + virtual void OnTerrainDataDestroyEnd() {} + + virtual void OnTerrainDataChanged( + [[maybe_unused]] const AZ::Aabb& dirtyRegion, [[maybe_unused]] TerrainDataChangedMask dataChangedMask) + { + } }; using TerrainDataNotificationBus = AZ::EBus; diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index c5b6a2ff96..74adcd9543 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -8,12 +8,12 @@ #include "CameraInput.h" -#include #include #include #include #include #include +#include namespace AzFramework { @@ -26,6 +26,13 @@ namespace AzFramework "The default height of the ground plane to do intersection tests against when orbiting"); AZ_CVAR(float, ed_cameraSystemMinOrbitDistance, 10.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); AZ_CVAR(float, ed_cameraSystemMaxOrbitDistance, 50.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR( + bool, + ed_cameraSystemUseCursor, + true, + nullptr, + AZ::ConsoleFunctorFlags::Null, + "Should the camera use cursor absolute positions or motion deltas"); //! return -1.0f if inverted, 1.0f otherwise constexpr static float Invert(const bool invert) @@ -134,9 +141,13 @@ namespace AzFramework bool CameraSystem::HandleEvents(const InputEvent& event) { - if (const auto& horizonalMotion = AZStd::get_if(&event)) + if (const auto& cursor = AZStd::get_if(&event)) { - m_motionDelta.m_x = horizonalMotion->m_delta; + m_cursorState.SetCurrentPosition(cursor->m_position); + } + else if (const auto& horizontalMotion = AZStd::get_if(&event)) + { + m_motionDelta.m_x = horizontalMotion->m_delta; } else if (const auto& verticalMotion = AZStd::get_if(&event)) { @@ -147,15 +158,18 @@ namespace AzFramework m_scrollDelta = scroll->m_delta; } - m_handlingEvents = m_cameras.HandleEvents(event, m_motionDelta, m_scrollDelta); + m_handlingEvents = + m_cameras.HandleEvents(event, ed_cameraSystemUseCursor ? m_cursorState.CursorDelta() : m_motionDelta, m_scrollDelta); return m_handlingEvents; } Camera CameraSystem::StepCamera(const Camera& targetCamera, const float deltaTime) { - const auto nextCamera = m_cameras.StepCamera(targetCamera, m_motionDelta, m_scrollDelta, deltaTime); + const auto nextCamera = m_cameras.StepCamera( + targetCamera, ed_cameraSystemUseCursor ? m_cursorState.CursorDelta() : m_motionDelta, m_scrollDelta, deltaTime); + m_cursorState.Update(); m_motionDelta = ScreenVector{ 0, 0 }; m_scrollDelta = 0.0f; @@ -727,18 +741,36 @@ namespace AzFramework Camera camera; // note: the math for the lerp smoothing implementation for camera rotation and translation was inspired by this excellent // article by Scott Lembcke: https://www.gamasutra.com/blogs/ScottLembcke/20180404/316046/Improved_Lerp_Smoothing.php - const float lookRate = AZStd::exp2(cameraProps.m_rotateSmoothnessFn()); - const float lookT = AZStd::exp2(-lookRate * deltaTime); - camera.m_pitch = AZ::Lerp(targetCamera.m_pitch, currentCamera.m_pitch, lookT); - camera.m_yaw = AZ::Lerp(targetYaw, currentYaw, lookT); - const float moveRate = AZStd::exp2(cameraProps.m_translateSmoothnessFn()); - const float moveT = AZStd::exp2(-moveRate * deltaTime); - camera.m_lookDist = AZ::Lerp(targetCamera.m_lookDist, currentCamera.m_lookDist, moveT); - camera.m_lookAt = targetCamera.m_lookAt.Lerp(currentCamera.m_lookAt, moveT); + if (cameraProps.m_rotateSmoothingEnabledFn()) + { + const float lookRate = AZStd::exp2(cameraProps.m_rotateSmoothnessFn()); + const float lookTime = AZStd::exp2(-lookRate * deltaTime); + camera.m_pitch = AZ::Lerp(targetCamera.m_pitch, currentCamera.m_pitch, lookTime); + camera.m_yaw = AZ::Lerp(targetYaw, currentYaw, lookTime); + } + else + { + camera.m_pitch = targetCamera.m_pitch; + camera.m_yaw = targetYaw; + } + + if (cameraProps.m_translateSmoothingEnabledFn()) + { + const float moveRate = AZStd::exp2(cameraProps.m_translateSmoothnessFn()); + const float moveTime = AZStd::exp2(-moveRate * deltaTime); + camera.m_lookDist = AZ::Lerp(targetCamera.m_lookDist, currentCamera.m_lookDist, moveTime); + camera.m_lookAt = targetCamera.m_lookAt.Lerp(currentCamera.m_lookAt, moveTime); + } + else + { + camera.m_lookDist = targetCamera.m_lookDist; + camera.m_lookAt = targetCamera.m_lookAt; + } + return camera; } - InputEvent BuildInputEvent(const InputChannel& inputChannel) + InputEvent BuildInputEvent(const InputChannel& inputChannel, const WindowSize& windowSize) { const auto& inputChannelId = inputChannel.GetInputChannelId(); const auto& inputDeviceId = inputChannel.GetInputDevice().GetInputDeviceId(); @@ -753,7 +785,16 @@ namespace AzFramework // accept active mouse channel updates, inactive movement channels will just have a 0 delta if (inputChannel.IsActive()) { - if (inputChannelId == InputDeviceMouse::Movement::X) + if (inputChannelId == InputDeviceMouse::SystemCursorPosition) + { + const auto* position = inputChannel.GetCustomData(); + AZ_Assert(position, "Expected PositionData2D but found nullptr"); + + return CursorEvent{ ScreenPoint( + static_cast(position->m_normalizedPosition.GetX() * windowSize.m_width), + static_cast(position->m_normalizedPosition.GetY() * windowSize.m_height)) }; + } + else if (inputChannelId == InputDeviceMouse::Movement::X) { return HorizontalMotionEvent{ aznumeric_cast(inputChannel.GetValue()) }; } @@ -761,6 +802,7 @@ namespace AzFramework { return VerticalMotionEvent{ aznumeric_cast(inputChannel.GetValue()) }; } + else if (inputChannelId == InputDeviceMouse::Movement::Z) { return ScrollEvent{ inputChannel.GetValue() }; diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index bb0df4853a..0b7bbbc30d 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -8,17 +8,23 @@ #pragma once +#include #include #include #include #include #include #include +#include #include #include namespace AzFramework { + AZ_CVAR_EXTERNED(bool, ed_cameraSystemUseCursor); + + struct WindowSize; + //! Returns Euler angles (pitch, roll, yaw) for the incoming orientation. //! @note Order of rotation is Z, Y, X. AZ::Vector3 EulerAngles(const AZ::Matrix3x3& orientation); @@ -79,6 +85,11 @@ namespace AzFramework using HorizontalMotionEvent = MotionEvent; using VerticalMotionEvent = MotionEvent; + struct CursorEvent + { + ScreenPoint m_position; + }; + struct ScrollEvent { float m_delta; @@ -93,7 +104,8 @@ namespace AzFramework }; //! Represents a type-safe union of input events that are handled by the camera system. - using InputEvent = AZStd::variant; + using InputEvent = + AZStd::variant; //! Base class for all camera behaviors. //! The core interface consists of: @@ -219,10 +231,14 @@ namespace AzFramework //! Properties to use to configure behavior across all types of camera. struct CameraProps { - AZStd::function - m_rotateSmoothnessFn; //!< Rotate smoothing value (useful approx range 3-6, higher values give sharper feel). - AZStd::function - m_translateSmoothnessFn; //!< Translate smoothing value (useful approx range 3-6, higher values give sharper feel). + //! Rotate smoothing value (useful approx range 3-6, higher values give sharper feel). + AZStd::function m_rotateSmoothnessFn; + //! Translate smoothing value (useful approx range 3-6, higher values give sharper feel). + AZStd::function m_translateSmoothnessFn; + //! Enable/disable rotation smoothing. + AZStd::function m_rotateSmoothingEnabledFn; + //! Enable/disable translation smoothing. + AZStd::function m_translateSmoothingEnabledFn; }; //! An interpolation function to smoothly interpolate all camera properties from currentCamera to targetCamera. @@ -262,12 +278,16 @@ namespace AzFramework public: bool HandleEvents(const InputEvent& event); Camera StepCamera(const Camera& targetCamera, float deltaTime); - bool HandlingEvents() const { return m_handlingEvents; } + bool HandlingEvents() const + { + return m_handlingEvents; + } Cameras m_cameras; //!< Represents a collection of camera inputs that together provide a camera controller. private: ScreenVector m_motionDelta; //!< The delta used for look/orbit/pan (rotation + translation) - two dimensional. + CursorState m_cursorState; //!< The current and previous position of the cursor (used to calculate movement delta). float m_scrollDelta = 0.0f; //!< The delta used for dolly/movement (translation) - one dimensional. bool m_handlingEvents = false; //!< Is the camera system currently handling events (events are consumed and not propagated). }; @@ -548,5 +568,5 @@ namespace AzFramework } //! Map from a generic InputChannel event to a camera specific InputEvent. - InputEvent BuildInputEvent(const InputChannel& inputChannel); + InputEvent BuildInputEvent(const InputChannel& inputChannel, const WindowSize& windowSize); } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.cpp b/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.cpp index c5253a8c89..bfa9dfcf9e 100644 --- a/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.cpp +++ b/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityBoundsUnionSystem.cpp @@ -8,6 +8,7 @@ #include "EntityVisibilityBoundsUnionSystem.h" +#include #include #include @@ -42,7 +43,7 @@ namespace AzFramework void EntityVisibilityBoundsUnionSystem::OnEntityActivated(AZ::Entity* entity) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); // ignore any entity that might activate which does not have a TransformComponent if (entity->GetTransform() == nullptr) @@ -68,7 +69,7 @@ namespace AzFramework void EntityVisibilityBoundsUnionSystem::OnEntityDeactivated(AZ::Entity* entity) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); // ignore any entity that might deactivate which does not have a TransformComponent if (entity->GetTransform() == nullptr) @@ -89,7 +90,7 @@ namespace AzFramework void EntityVisibilityBoundsUnionSystem::UpdateVisibilitySystem(AZ::Entity* entity, EntityVisibilityBoundsUnionInstance& instance) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); if (const auto& localEntityBoundsUnions = instance.m_localEntityBoundsUnion; localEntityBoundsUnions.IsValid()) { @@ -136,7 +137,7 @@ namespace AzFramework void EntityVisibilityBoundsUnionSystem::ProcessEntityBoundsUnionRequests() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); // iterate over all entities whose bounds changed and recalculate them for (const auto& entity : m_entityBoundsDirty) @@ -155,7 +156,7 @@ namespace AzFramework void EntityVisibilityBoundsUnionSystem::OnTransformUpdated(AZ::Entity* entity) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); // update the world transform of the visibility bounds union if (auto instance_it = m_entityVisibilityBoundsUnionInstanceMapping.find(entity); diff --git a/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityQuery.cpp b/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityQuery.cpp index 2023cb969d..96d371fa12 100644 --- a/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityQuery.cpp +++ b/Code/Framework/AzFramework/AzFramework/Visibility/EntityVisibilityQuery.cpp @@ -34,7 +34,7 @@ namespace AzFramework { void EntityVisibilityQuery::UpdateVisibility(const AzFramework::CameraState& cameraState) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzFramework); + AZ_PROFILE_FUNCTION(AzFramework); auto* visSystem = AZ::Interface::Get(); if (!visSystem) diff --git a/Code/Framework/AzFramework/CMakeLists.txt b/Code/Framework/AzFramework/CMakeLists.txt index 8a68aac887..1164d81f04 100644 --- a/Code/Framework/AzFramework/CMakeLists.txt +++ b/Code/Framework/AzFramework/CMakeLists.txt @@ -10,9 +10,6 @@ ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) ly_get_list_relative_pal_filename(common_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/Common) -set(LY_STATISTICAL_PROFILING_ENABLED OFF CACHE BOOL "Enables statistical profiling when using AZ_PROFILE_SCOPE. If True, it takes effect only if RAD Telemetry is disabled.") -set(LY_TOUCHBENDING_LAYER_BIT 63 CACHE STRING "Use TouchBending as the collision layer. The TouchBending layer can be a number from 1 to 63 (Default=63).") - ly_add_target( NAME AzFramework STATIC NAMESPACE AZ @@ -38,22 +35,6 @@ ly_add_target( 3rdParty::lz4 ) -if(LY_STATISTICAL_PROFILING_ENABLED) - ly_add_source_properties( - SOURCES AzFramework/Debug/StatisticalProfilerProxy.h - PROPERTY COMPILE_DEFINITIONS - VALUES AZ_STATISTICAL_PROFILING_ENABLED - ) -endif() - -ly_add_source_properties( - SOURCES - AzFramework/Physics/Collision/CollisionGroups.cpp - AzFramework/Physics/Collision/CollisionLayers.cpp - PROPERTY COMPILE_DEFINITIONS - VALUES TOUCHBENDING_LAYER_BIT=${LY_TOUCHBENDING_LAYER_BIT} -) - if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Tests/Platform/${PAL_PLATFORM_NAME}) @@ -70,6 +51,9 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PRIVATE AZ::AzCore AZ::AzFramework + PUBLIC + AZ::AzTest + AZ::AzTestShared ) if(PAL_TRAIT_BUILD_HOST_TOOLS) diff --git a/Code/Framework/AzFramework/Tests/CameraInputTests.cpp b/Code/Framework/AzFramework/Tests/CameraInputTests.cpp index 590d46850e..ef340a41a5 100644 --- a/Code/Framework/AzFramework/Tests/CameraInputTests.cpp +++ b/Code/Framework/AzFramework/Tests/CameraInputTests.cpp @@ -59,10 +59,15 @@ namespace UnitTest m_cameraSystem->m_cameras.AddCamera(m_firstPersonRotateCamera); m_cameraSystem->m_cameras.AddCamera(m_firstPersonTranslateCamera); m_cameraSystem->m_cameras.AddCamera(orbitCamera); + + // these tests rely on using motion delta, not cursor positions (default is true) + AzFramework::ed_cameraSystemUseCursor = false; } void TearDown() override { + AzFramework::ed_cameraSystemUseCursor = true; + m_firstPersonRotateCamera.reset(); m_firstPersonTranslateCamera.reset(); diff --git a/Code/Framework/AzFramework/Tests/Mocks/MockWindowRequests.h b/Code/Framework/AzFramework/Tests/Mocks/MockWindowRequests.h new file mode 100644 index 0000000000..63f73d0b28 --- /dev/null +++ b/Code/Framework/AzFramework/Tests/Mocks/MockWindowRequests.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 + +namespace UnitTest +{ + class MockWindowRequests : public AzFramework::WindowRequestBus::Handler + { + public: + void Connect(AzFramework::NativeWindowHandle handle) + { + AzFramework::WindowRequestBus::Handler::BusConnect(handle); + } + void Disconnect() + { + AzFramework::WindowRequestBus::Handler::BusDisconnect(); + } + + // AzFramework::WindowRequestBus overrides ... + MOCK_METHOD1(SetWindowTitle, void(const AZStd::string&)); + MOCK_CONST_METHOD0(GetClientAreaSize, AzFramework::WindowSize()); + MOCK_METHOD1(ResizeClientArea, void(AzFramework::WindowSize clientAreaSize)); + MOCK_CONST_METHOD0(GetFullScreenState, bool()); + MOCK_METHOD1(SetFullScreenState, void(bool)); + MOCK_CONST_METHOD0(CanToggleFullScreenState, bool()); + MOCK_METHOD0(ToggleFullScreenState, void()); + MOCK_CONST_METHOD0(GetDpiScaleFactor, float()); + MOCK_CONST_METHOD0(GetSyncInterval, uint32_t()); + MOCK_CONST_METHOD0(GetDisplayRefreshRate, uint32_t()); + }; +} // namespace UnitTest diff --git a/Code/Framework/AzFramework/Tests/framework_shared_tests_files.cmake b/Code/Framework/AzFramework/Tests/framework_shared_tests_files.cmake index 3d2c2a51be..85c00a2e8a 100644 --- a/Code/Framework/AzFramework/Tests/framework_shared_tests_files.cmake +++ b/Code/Framework/AzFramework/Tests/framework_shared_tests_files.cmake @@ -8,6 +8,7 @@ set(FILES Mocks/MockSpawnableEntitiesInterface.h + Mocks/MockWindowRequests.h Utils/Utils.h Utils/Utils.cpp FrameworkApplicationFixture.h diff --git a/Code/Framework/AzNetworking/AzNetworking/Utilities/QuantizedValues.h b/Code/Framework/AzNetworking/AzNetworking/Utilities/QuantizedValues.h index 190a32ddc7..49f5533548 100644 --- a/Code/Framework/AzNetworking/AzNetworking/Utilities/QuantizedValues.h +++ b/Code/Framework/AzNetworking/AzNetworking/Utilities/QuantizedValues.h @@ -176,7 +176,7 @@ namespace AzNetworking //! Takes a quantized integral value and stores the floating point representation. void DecodeQuantizedValues(); - AZ_PUSH_DISABLE_WARNING(4201 4324, "-Wunknown-warning-option") // anonymous union, structure was padded due to alignment + AZ_PUSH_DISABLE_WARNING(4324, "-Wunknown-warning-option") // structure was padded due to alignment union { float m_quantizedValues[NUM_ELEMENTS]; diff --git a/Code/Framework/AzNetworking/AzNetworking/Utilities/QuantizedValues.inl b/Code/Framework/AzNetworking/AzNetworking/Utilities/QuantizedValues.inl index b0a424d48a..86e736928a 100644 --- a/Code/Framework/AzNetworking/AzNetworking/Utilities/QuantizedValues.inl +++ b/Code/Framework/AzNetworking/AzNetworking/Utilities/QuantizedValues.inl @@ -218,14 +218,7 @@ namespace AzNetworking { SerializeType serializedValue = static_cast(m_serializeValues[i]); -#ifdef AZ_COMPILER_MSVC -# pragma warning(push) -# pragma warning(disable: 4127) // conditional expression is constant -#endif - if (NUM_BYTES == 3) -#ifdef AZ_COMPILER_MSVC -# pragma warning(pop) -#endif + if constexpr (NUM_BYTES == 3) { uint8_t lowByte = static_cast((serializedValue & 0x000000FF) ); uint8_t midByte = static_cast((serializedValue & 0x0000FF00) >> 8); diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/SliderCombo.h b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/SliderCombo.h index 7baa386784..2646162af4 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/SliderCombo.h +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/SliderCombo.h @@ -40,6 +40,8 @@ namespace AzQtComponents //! Current value. Q_PROPERTY(int value READ value WRITE setValue NOTIFY valueChanged) public: + using value_type = int; + explicit SliderCombo(QWidget *parent = nullptr); ~SliderCombo(); @@ -142,6 +144,8 @@ namespace AzQtComponents Q_PROPERTY(double curveMidpoint READ curveMidpoint WRITE setCurveMidpoint) public: + using value_type = double; + explicit SliderDoubleCombo(QWidget *parent = nullptr); ~SliderDoubleCombo(); diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/SpinBox.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/SpinBox.cpp index fc73f88d1c..06361ceee9 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/SpinBox.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/SpinBox.cpp @@ -366,7 +366,7 @@ bool SpinBoxWatcher::filterSpinBoxEvents(QAbstractSpinBox* spinBox, QEvent* even { // To prevent the event being turned into a focus event, be sure to install an // AzQtComponents::GlobalEventFilter on your QApplication instance. - event->ignore(); + event->accept(); return true; } diff --git a/Code/Framework/AzTest/AzTest/Platform/Android/AzTest_Traits_Android.h b/Code/Framework/AzTest/AzTest/Platform/Android/AzTest_Traits_Android.h index b210fb9b62..3ec3051576 100644 --- a/Code/Framework/AzTest/AzTest/Platform/Android/AzTest_Traits_Android.h +++ b/Code/Framework/AzTest/AzTest/Platform/Android/AzTest_Traits_Android.h @@ -12,7 +12,6 @@ #define AZ_TRAIT_UNIT_TEST_ASSET_MANAGER_TEST_DEFAULT_TIMEOUT_SECS 5 #define AZ_TRAIT_UNIT_TEST_ENTITY_ID_GEN_TEST_COUNT 10000 #define AZ_TRAIT_UNIT_TEST_DILLER_TRIGGER_EVENT_COUNT 100000 -#define AZ_TRAIT_UNIT_TEST_NAME_COUNT 1000 #define AZ_TRAIT_TEST_APPEND_ROOT_FOLDER_TO_PATH true @@ -30,7 +29,6 @@ #define AZ_TRAIT_DISABLE_FAILED_MULTIPLAYER_GRIDMATE_TESTS true #define AZ_TRAIT_DISABLE_FAILED_NETWORKING_TESTS true #define AZ_TRAIT_DISABLE_FAILED_PHYSICS_TESTS true -#define AZ_TRAIT_DISABLE_FAILED_PROFILER_TEST true #define AZ_TRAIT_DISABLE_FAILED_SAVE_DATA_TESTS true #define AZ_TRAIT_DISABLE_FAILED_SERIALIZE_BASIC_TEST true #define AZ_TRAIT_DISABLE_FAILED_STREAMER_TESTS true diff --git a/Code/Framework/AzTest/AzTest/Platform/Linux/AzTest_Traits_Linux.h b/Code/Framework/AzTest/AzTest/Platform/Linux/AzTest_Traits_Linux.h index 8b8d87a5b9..d9b48b7835 100644 --- a/Code/Framework/AzTest/AzTest/Platform/Linux/AzTest_Traits_Linux.h +++ b/Code/Framework/AzTest/AzTest/Platform/Linux/AzTest_Traits_Linux.h @@ -12,7 +12,6 @@ #define AZ_TRAIT_UNIT_TEST_ASSET_MANAGER_TEST_DEFAULT_TIMEOUT_SECS 5 #define AZ_TRAIT_UNIT_TEST_ENTITY_ID_GEN_TEST_COUNT 10000 #define AZ_TRAIT_UNIT_TEST_DILLER_TRIGGER_EVENT_COUNT 100000 -#define AZ_TRAIT_UNIT_TEST_NAME_COUNT 1000 #define AZ_TRAIT_DISABLE_ALL_SAVE_DATA_TESTS true diff --git a/Code/Framework/AzTest/AzTest/Platform/Mac/AzTest_Traits_Mac.h b/Code/Framework/AzTest/AzTest/Platform/Mac/AzTest_Traits_Mac.h index a43c62ac98..69dd592a2b 100644 --- a/Code/Framework/AzTest/AzTest/Platform/Mac/AzTest_Traits_Mac.h +++ b/Code/Framework/AzTest/AzTest/Platform/Mac/AzTest_Traits_Mac.h @@ -12,7 +12,6 @@ #define AZ_TRAIT_UNIT_TEST_ASSET_MANAGER_TEST_DEFAULT_TIMEOUT_SECS 5 #define AZ_TRAIT_UNIT_TEST_ENTITY_ID_GEN_TEST_COUNT 10000 #define AZ_TRAIT_UNIT_TEST_DILLER_TRIGGER_EVENT_COUNT 100000 -#define AZ_TRAIT_UNIT_TEST_NAME_COUNT 1000 #define AZ_TRAIT_DISABLE_ASSET_JOB_PARALLEL_TESTS true #define AZ_TRAIT_DISABLE_ASSET_MANAGER_FLOOD_TEST true diff --git a/Code/Framework/AzTest/AzTest/Platform/Windows/AzTest_Traits_Windows.h b/Code/Framework/AzTest/AzTest/Platform/Windows/AzTest_Traits_Windows.h index 3721d8891a..a11b8586f4 100644 --- a/Code/Framework/AzTest/AzTest/Platform/Windows/AzTest_Traits_Windows.h +++ b/Code/Framework/AzTest/AzTest/Platform/Windows/AzTest_Traits_Windows.h @@ -13,4 +13,3 @@ #define AZ_TRAIT_UNIT_TEST_ASSET_MANAGER_TEST_DEFAULT_TIMEOUT_SECS 5 #define AZ_TRAIT_UNIT_TEST_ENTITY_ID_GEN_TEST_COUNT 10000 #define AZ_TRAIT_UNIT_TEST_DILLER_TRIGGER_EVENT_COUNT 100000 -#define AZ_TRAIT_UNIT_TEST_NAME_COUNT 1000 diff --git a/Code/Framework/AzTest/AzTest/Platform/Windows/ScopedAutoTempDirectory_Windows.cpp b/Code/Framework/AzTest/AzTest/Platform/Windows/ScopedAutoTempDirectory_Windows.cpp index dc4b31c9be..fcda5d351a 100644 --- a/Code/Framework/AzTest/AzTest/Platform/Windows/ScopedAutoTempDirectory_Windows.cpp +++ b/Code/Framework/AzTest/AzTest/Platform/Windows/ScopedAutoTempDirectory_Windows.cpp @@ -30,7 +30,7 @@ namespace AZ while (maxAttempts > 0) { // Use the system's tick count to base the folder name - DWORD currentTick = GetTickCount64(); + ULONGLONG currentTick = GetTickCount64(); azsnprintf(workingTempPathBuffer, bufferSize, "%sUnitTest-%X", tempDir, aznumeric_cast(currentTick)); // Check if the requested directory name is available and re-generate if it already exists diff --git a/Code/Framework/AzTest/AzTest/Platform/iOS/AzTest_Traits_iOS.h b/Code/Framework/AzTest/AzTest/Platform/iOS/AzTest_Traits_iOS.h index a43c62ac98..69dd592a2b 100644 --- a/Code/Framework/AzTest/AzTest/Platform/iOS/AzTest_Traits_iOS.h +++ b/Code/Framework/AzTest/AzTest/Platform/iOS/AzTest_Traits_iOS.h @@ -12,7 +12,6 @@ #define AZ_TRAIT_UNIT_TEST_ASSET_MANAGER_TEST_DEFAULT_TIMEOUT_SECS 5 #define AZ_TRAIT_UNIT_TEST_ENTITY_ID_GEN_TEST_COUNT 10000 #define AZ_TRAIT_UNIT_TEST_DILLER_TRIGGER_EVENT_COUNT 100000 -#define AZ_TRAIT_UNIT_TEST_NAME_COUNT 1000 #define AZ_TRAIT_DISABLE_ASSET_JOB_PARALLEL_TESTS true #define AZ_TRAIT_DISABLE_ASSET_MANAGER_FLOOD_TEST true diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp index 56ef749247..3e895465e5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Application/ToolsApplication.cpp @@ -95,7 +95,7 @@ namespace AzToolsFramework template void DeleteEntities(const IdContainerType& entityIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (entityIds.empty()) { @@ -141,7 +141,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DeleteEntities:UndoCaptureAndPurgeEntities"); + AZ_PROFILE_SCOPE(AzToolsFramework, "Internal::DeleteEntities:UndoCaptureAndPurgeEntities"); for (const auto& entityId : entityIds) { AZ::Entity* entity = NULL; @@ -160,7 +160,7 @@ namespace AzToolsFramework selCommand->SetParent(currentUndoBatch); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DeleteEntities:RunRedo"); + AZ_PROFILE_SCOPE(AzToolsFramework, "Internal::DeleteEntities:RunRedo"); selCommand->RunRedo(); } } @@ -458,7 +458,7 @@ namespace AzToolsFramework bool ToolsApplication::RemoveEntity(AZ::Entity* entity) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto undoCacheInterface = AZ::Interface::Get(); if (undoCacheInterface) @@ -472,7 +472,7 @@ namespace AzToolsFramework EBUS_EVENT(ToolsApplicationEvents::Bus, EntityDeregistered, entity->GetId()); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "ToolsApplication::RemoveEntity:CallApplicationRemoveEntity"); + AZ_PROFILE_SCOPE(AzToolsFramework, "ToolsApplication::RemoveEntity:CallApplicationRemoveEntity"); if (AzFramework::Application::RemoveEntity(entity)) { return true; @@ -545,7 +545,7 @@ namespace AzToolsFramework void ToolsApplication::MarkEntitySelected(AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(entityId.IsValid(), "Invalid entity Id being marked as selected."); EntityIdList::iterator foundIter = AZStd::find(m_selectedEntities.begin(), m_selectedEntities.end(), entityId); @@ -563,7 +563,7 @@ namespace AzToolsFramework void ToolsApplication::MarkEntitiesSelected(const EntityIdList& entitiesToSelect) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EntityIdList entitiesSelected; entitiesSelected.reserve(entitiesToSelect.size()); @@ -587,11 +587,11 @@ namespace AzToolsFramework void ToolsApplication::MarkEntityDeselected(AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto foundIter = AZStd::find(m_selectedEntities.begin(), m_selectedEntities.end(), entityId); if (foundIter != m_selectedEntities.end()) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "ToolsApplication::MarkEntityDeselected:Deselect"); + AZ_PROFILE_SCOPE(AzToolsFramework, "ToolsApplication::MarkEntityDeselected:Deselect"); ToolsApplicationEvents::Bus::Broadcast(&ToolsApplicationEvents::BeforeEntitySelectionChanged); m_selectedEntities.erase(foundIter); @@ -603,7 +603,7 @@ namespace AzToolsFramework void ToolsApplication::MarkEntitiesDeselected(const EntityIdList& entitiesToDeselect) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ToolsApplicationEvents::Bus::Broadcast(&ToolsApplicationEvents::BeforeEntitySelectionChanged); @@ -633,14 +633,14 @@ namespace AzToolsFramework void ToolsApplication::SetEntityHighlighted(AZ::EntityId entityId, bool highlighted) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto foundIter = AZStd::find(m_highlightedEntities.begin(), m_highlightedEntities.end(), entityId); if (foundIter != m_highlightedEntities.end()) { if (!highlighted) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "ToolsApplication::SetEntityHighlighted:RemoveHighlight"); + AZ_PROFILE_SCOPE(AzToolsFramework, "ToolsApplication::SetEntityHighlighted:RemoveHighlight"); ToolsApplicationEvents::Bus::Broadcast(&ToolsApplicationEvents::BeforeEntityHighlightingChanged); m_highlightedEntities.erase(foundIter); ToolsApplicationEvents::Bus::Broadcast(&ToolsApplicationEvents::AfterEntityHighlightingChanged); @@ -648,7 +648,7 @@ namespace AzToolsFramework } else if (highlighted) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "ToolsApplication::SetEntityHighlighted:AddHighlight"); + AZ_PROFILE_SCOPE(AzToolsFramework, "ToolsApplication::SetEntityHighlighted:AddHighlight"); ToolsApplicationEvents::Bus::Broadcast(&ToolsApplicationEvents::BeforeEntityHighlightingChanged); m_highlightedEntities.push_back(entityId); ToolsApplicationEvents::Bus::Broadcast(&ToolsApplicationEvents::AfterEntityHighlightingChanged); @@ -657,7 +657,7 @@ namespace AzToolsFramework void ToolsApplication::SetSelectedEntities(const EntityIdList& selectedEntities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // We're setting the selection set as a batch from an external caller. // * Filter out any unselectable entities @@ -1535,7 +1535,7 @@ namespace AzToolsFramework void ToolsApplication::CreateUndosForDirtyEntities() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(!m_isDuringUndoRedo, "Cannot add dirty entities during undo/redo."); if (m_dirtyEntities.empty()) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Commands/EntityStateCommand.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Commands/EntityStateCommand.cpp index 9f251bee7a..b73e1ea5ac 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Commands/EntityStateCommand.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Commands/EntityStateCommand.cpp @@ -54,7 +54,7 @@ namespace AzToolsFramework void EntityStateCommand::Capture(AZ::Entity* pSourceEntity, bool captureUndo) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_entityID = pSourceEntity->GetId(); EBUS_EVENT_ID_RESULT(m_entityContextId, m_entityID, AzFramework::EntityIdContextQueryBus, GetOwningContextId); @@ -114,7 +114,7 @@ namespace AzToolsFramework void EntityStateCommand::RestoreEntity(const AZ::u8* buffer, AZStd::size_t bufferSizeBytes, const AZ::SliceComponent::EntityRestoreInfo& sliceRestoreInfo) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(buffer, "No data to undo!"); AZ_Assert(bufferSizeBytes, "Undo data is empty."); @@ -259,7 +259,7 @@ namespace AzToolsFramework void EntityDeleteCommand::Redo() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EBUS_EVENT(AZ::ComponentApplicationBus, DeleteEntity, m_entityID); PreemptiveUndoCache::Get()->PurgeCache(m_entityID); } @@ -277,7 +277,7 @@ namespace AzToolsFramework void EntityCreateCommand::Undo() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EBUS_EVENT(AZ::ComponentApplicationBus, DeleteEntity, m_entityID); PreemptiveUndoCache::Get()->PurgeCache(m_entityID); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Commands/PreemptiveUndoCache.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Commands/PreemptiveUndoCache.cpp index 4d84089a74..d4c4fa1e65 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Commands/PreemptiveUndoCache.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Commands/PreemptiveUndoCache.cpp @@ -86,7 +86,7 @@ namespace AzToolsFramework void PreemptiveUndoCache::UpdateCache(const AZ::EntityId& entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // capture it diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.cpp index b45ffdd31d..90657132ca 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityContextComponent.cpp @@ -312,7 +312,7 @@ namespace AzToolsFramework EntityList& resultEntities, EntityIdToEntityIdMap& sourceToCloneEntityIdMap) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); resultEntities.clear(); @@ -365,7 +365,7 @@ namespace AzToolsFramework const EntityList& entitiesInLayers, AZ::SliceComponent::SliceReferenceToInstancePtrs& instancesInLayers) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_isLegacySliceService) { @@ -390,7 +390,7 @@ namespace AzToolsFramework //========================================================================= bool EditorEntityContextComponent::SaveToStreamForGame(AZ::IO::GenericStream& stream, AZ::DataStream::StreamType streamType) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_isLegacySliceService) { SliceEditorEntityOwnershipService* editorEntityOwnershipService = @@ -409,7 +409,7 @@ namespace AzToolsFramework //========================================================================= bool EditorEntityContextComponent::LoadFromStream(AZ::IO::GenericStream& stream) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(stream.IsOpen(), "Invalid source stream."); AZ_Assert(m_entityOwnershipService->IsInitialized(), "The context has not been initialized."); @@ -427,7 +427,7 @@ namespace AzToolsFramework bool EditorEntityContextComponent::LoadFromStreamWithLayers(AZ::IO::GenericStream& stream, QString levelPakFile) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(stream.IsOpen(), "Invalid source stream."); AZ_Assert(m_entityOwnershipService->IsInitialized(), "The context has not been initialized."); @@ -477,7 +477,7 @@ namespace AzToolsFramework //========================================================================= void EditorEntityContextComponent::StartPlayInEditor() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EditorEntityContextNotificationBus::Broadcast(&EditorEntityContextNotification::OnStartPlayInEditorBegin); @@ -513,7 +513,7 @@ namespace AzToolsFramework //========================================================================= void EditorEntityContextComponent::StopPlayInEditor() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_isRunningGame = false; @@ -696,13 +696,13 @@ namespace AzToolsFramework //========================================================================= void EditorEntityContextComponent::SetupEditorEntities(const EntityList& entities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::Data::AssetManager::Instance().SuspendAssetRelease(); // All editor entities are automatically activated. { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorEntityContextComponent::SetupEditorEntities:ScrubEntities"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EditorEntityContextComponent::SetupEditorEntities:ScrubEntities"); // Scrub entities before initialization. // Anything could go wrong with entities loaded from disk. @@ -712,7 +712,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorEntityContextComponent::SetupEditorEntities:InitEntities"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EditorEntityContextComponent::SetupEditorEntities:InitEntities"); for (AZ::Entity* entity : entities) { if (entity->GetState() == AZ::Entity::State::Constructed) @@ -723,7 +723,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorEntityContextComponent::SetupEditorEntities:CreateEditorRepresentations"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EditorEntityContextComponent::SetupEditorEntities:CreateEditorRepresentations"); for (AZ::Entity* entity : entities) { EditorRequests::Bus::Broadcast(&EditorRequests::CreateEditorRepresentation, entity); @@ -731,7 +731,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorEntityContextComponent::SetupEditorEntities:ActivateEntities"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EditorEntityContextComponent::SetupEditorEntities:ActivateEntities"); for (AZ::Entity* entity : entities) { if (entity->GetState() == AZ::Entity::State::Init) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.cpp index 17ea732103..0b0358d613 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.cpp @@ -323,7 +323,7 @@ namespace AzToolsFramework void AddEntityIdToSortInfo(const AZ::EntityId parentId, const AZ::EntityId childId, bool forceAddToBack) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::EntityId sortEntityId = GetEntityIdForSortInfo(parentId); bool success = false; @@ -336,7 +336,7 @@ namespace AzToolsFramework void AddEntityIdToSortInfo(const AZ::EntityId parentId, const AZ::EntityId childId, const AZ::EntityId beforeEntity) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::EntityId sortEntityId = GetEntityIdForSortInfo(parentId); bool success = false; @@ -349,7 +349,7 @@ namespace AzToolsFramework bool RecoverEntitySortInfo(const AZ::EntityId parentId, const AZ::EntityId childId, AZ::u64 sortIndex) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EntityOrderArray entityOrderArray; EditorEntitySortRequestBus::EventResult(entityOrderArray, GetEntityIdForSortInfo(parentId), &EditorEntitySortRequestBus::Events::GetChildEntityOrderArray); @@ -372,7 +372,7 @@ namespace AzToolsFramework void RemoveEntityIdFromSortInfo(const AZ::EntityId parentId, const AZ::EntityId childId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::EntityId sortEntityId = GetEntityIdForSortInfo(parentId); bool success = false; @@ -385,7 +385,7 @@ namespace AzToolsFramework bool SetEntityChildOrder(const AZ::EntityId parentId, const EntityIdList& children) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto sortEntityId = GetEntityIdForSortInfo(parentId); bool success = false; @@ -399,7 +399,7 @@ namespace AzToolsFramework EntityIdList GetEntityChildOrder(const AZ::EntityId parentId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EntityIdList children; EditorEntityInfoRequestBus::EventResult(children, parentId, &EditorEntityInfoRequestBus::Events::GetChildren); @@ -441,7 +441,7 @@ namespace AzToolsFramework //sort vector of entities by how they're arranged void SortEntitiesByLocationInHierarchy(EntityIdList& entityIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //cache locations for faster sort AZStd::unordered_map> locations; for (auto entityId : entityIds) @@ -575,7 +575,7 @@ namespace AzToolsFramework bool IsSelected(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); bool selected = false; EditorEntityInfoRequestBus::EventResult( @@ -585,7 +585,7 @@ namespace AzToolsFramework bool IsSelectableInViewport(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); bool visible = false; EditorEntityInfoRequestBus::EventResult( @@ -602,7 +602,7 @@ namespace AzToolsFramework const AZ::EntityId entityId, const bool locked, const AZ::EntityId toggledEntityId, const bool toggledEntityWasLayer) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!entityId.IsValid()) { @@ -661,7 +661,7 @@ namespace AzToolsFramework // note: must be called on layer entity static void UnlockLayer(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EditorLockComponentRequestBus::Event( entityId, &EditorLockComponentRequestBus::Events::SetLocked, false); @@ -698,7 +698,7 @@ namespace AzToolsFramework void SetEntityLockState(const AZ::EntityId entityId, const bool locked) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // when an entity is unlocked, if it was in a locked layer(s), unlock those layers if (!locked) @@ -736,7 +736,7 @@ namespace AzToolsFramework void ToggleEntityLockState(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (entityId.IsValid()) { @@ -772,7 +772,7 @@ namespace AzToolsFramework static void SetEntityVisibilityInternal(const AZ::EntityId entityId, const bool visibility) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); bool layerEntity = false; Layers::EditorLayerComponentRequestBus::EventResult( @@ -795,7 +795,7 @@ namespace AzToolsFramework // note: must be called on layer entity static void ShowLayer(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); SetEntityVisibilityInternal(entityId, true); @@ -830,7 +830,7 @@ namespace AzToolsFramework const AZ::EntityId entityId, const bool visible, const AZ::EntityId toggledEntityId, const bool toggledEntityWasLayer) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!entityId.IsValid()) { @@ -879,7 +879,7 @@ namespace AzToolsFramework void SetEntityVisibility(const AZ::EntityId entityId, const bool visible) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // when an entity is set to visible, if it was in an invisible layer(s), make that layer visible if (visible) @@ -917,7 +917,7 @@ namespace AzToolsFramework void ToggleEntityVisibility(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (entityId.IsValid()) { @@ -969,7 +969,7 @@ namespace AzToolsFramework bool IsEntitySetToBeVisible(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // Visibility state is tracked in 5 places, see OutlinerListModel::dataForLock for info on 3 of these ways. // Visibility's fourth state over lock is the EditorVisibilityRequestBus has two sets of @@ -1007,7 +1007,7 @@ namespace AzToolsFramework AZ::Vector3 GetWorldTranslation(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::Vector3 worldTranslation = AZ::Vector3::CreateZero(); AZ::TransformBus::EventResult( @@ -1018,7 +1018,7 @@ namespace AzToolsFramework AZ::Vector3 GetLocalTranslation(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::Vector3 localTranslation = AZ::Vector3::CreateZero(); AZ::TransformBus::EventResult( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityModel.cpp index 860c12b11a..8d96cc42fe 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityModel.cpp @@ -38,7 +38,7 @@ namespace bool HasDifferences(T* sourceElem, T* compareElem, bool isRoot, AZ::SerializeContext* serializeContext) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!sourceElem || !compareElem) { @@ -146,7 +146,7 @@ namespace AzToolsFramework void EditorEntityModel::Reset() { m_preparingForContextReset = false; - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //disconnect all entity ids EditorEntitySortNotificationBus::MultiHandler::BusDisconnect(); @@ -209,7 +209,7 @@ namespace AzToolsFramework sortedEntitiesToAdd.reserve(unsortedEntitiesToAdd.size()); { // Sort pending entities - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorEntityModel::AddEntityBatch:Sort"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EditorEntityModel::AddEntityBatch:Sort"); // Gather basic sorting data for each pending entity and // create map from parent ID to child entries. @@ -307,7 +307,7 @@ namespace AzToolsFramework } { // Add sorted entities - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorEntityModel::AddEntityBatch:Add"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EditorEntityModel::AddEntityBatch:Add"); for (AZ::EntityId entityId : sortedEntitiesToAdd) { AddEntity(entityId); @@ -325,7 +325,7 @@ namespace AzToolsFramework void EditorEntityModel::AddEntity(AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto& entityInfo = GetInfo(entityId); //initialize and connect this entry to the entity id @@ -374,7 +374,7 @@ namespace AzToolsFramework // Skip doing slow, unecessary work for this bulk operations. return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto& entityInfo = GetInfo(entityId); if (!entityInfo.IsConnected()) { @@ -404,7 +404,7 @@ namespace AzToolsFramework void EditorEntityModel::AddChildToParent(AZ::EntityId parentId, AZ::EntityId childId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(childId != parentId, "AddChildToParent called with same child and parent"); if (childId == parentId || !childId.IsValid()) { @@ -479,7 +479,7 @@ namespace AzToolsFramework void EditorEntityModel::RemoveChildFromParent(AZ::EntityId parentId, AZ::EntityId childId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(childId != parentId, "RemoveChildFromparent called with same child and parent"); AZ_Assert(childId.IsValid(), "RemoveChildFromparent called with an invalid child entity id"); if (childId == parentId || !childId.IsValid()) @@ -544,7 +544,7 @@ namespace AzToolsFramework void EditorEntityModel::ReparentChild(AZ::EntityId entityId, AZ::EntityId newParentId, AZ::EntityId oldParentId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(oldParentId != entityId, "ReparentChild gave us an oldParentId that is the same as the entityId. An entity cannot be a parent of itself, ignoring old parent"); AZ_Assert(newParentId != entityId, "ReparentChild gave us an newParentId that is the same as the entityId. An entity cannot be a parent of itself, ignoring old parent"); if (oldParentId != entityId && newParentId != entityId) @@ -573,7 +573,7 @@ namespace AzToolsFramework void EditorEntityModel::EntityRegistered(AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //when an editor entity is created and registered, add it to a pending list. //once all entities in the pending list are activated, add them to model. bool isEditorEntity = false; @@ -591,7 +591,7 @@ namespace AzToolsFramework void EditorEntityModel::EntityDeregistered(AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //when an editor entity is de-registered, stop tracking it if (m_entityInfoTable.find(entityId) != m_entityInfoTable.end()) { @@ -628,7 +628,7 @@ namespace AzToolsFramework void EditorEntityModel::EntityParentChanged(AZ::EntityId entityId, AZ::EntityId newParentId, AZ::EntityId oldParentId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (GetInfo(entityId).IsConnected()) { ReparentChild(entityId, newParentId, oldParentId); @@ -647,7 +647,7 @@ namespace AzToolsFramework void EditorEntityModel::ChildEntityOrderArrayUpdated() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //when notified that a parent has reordered its children, they must be updated if (m_enableChildReorderHandler) { @@ -671,14 +671,14 @@ namespace AzToolsFramework void EditorEntityModel::OnEditorEntitiesPromotedToSlicedEntities(const AzToolsFramework::EntityIdList& promotedEntities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); OnEditorEntitiesSliceOwnershipChanged(promotedEntities); } void EditorEntityModel::OnEditorEntitiesSliceOwnershipChanged(const AzToolsFramework::EntityIdList& entityIdList) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // Need to update slice info from top of hierarchy down // as parent entity slice status will be querried and needs to be correct @@ -712,7 +712,7 @@ namespace AzToolsFramework void EditorEntityModel::OnEntityStreamLoadSuccess() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //block internal reorder event handling to avoid recursion since we're manually updating everything m_enableChildReorderHandler = false; @@ -722,7 +722,7 @@ namespace AzToolsFramework //refresh all order info while blocking related events (keeps UI observers from updating until refresh is complete) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorEntityModel::OnEntityStreamLoadSuccess:UpdateChildOrderInfo"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EditorEntityModel::OnEntityStreamLoadSuccess:UpdateChildOrderInfo"); for (auto& entityInfoPair : m_entityInfoTable) { if (entityInfoPair.second.IsConnected()) @@ -733,7 +733,7 @@ namespace AzToolsFramework } } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorEntityModel::OnEntityStreamLoadSuccess:UpdateOrderInfo"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EditorEntityModel::OnEntityStreamLoadSuccess:UpdateOrderInfo"); for (auto& entityInfoPair : m_entityInfoTable) { if (entityInfoPair.second.IsConnected()) @@ -778,7 +778,7 @@ namespace AzToolsFramework void EditorEntityModel::OnEntityTransformChanged(const AzToolsFramework::EntityIdList& entityIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (const AZ::EntityId& entityId : entityIds) { @@ -846,7 +846,7 @@ namespace AzToolsFramework void EditorEntityModel::UpdateSliceInfoHierarchy(AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto& entityInfo = GetInfo(entityId); entityInfo.UpdateOrderInfo(false); entityInfo.UpdateSliceInfo(); @@ -896,7 +896,7 @@ namespace AzToolsFramework void EditorEntityModel::EditorEntityModelEntry::Connect() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); Disconnect(); EntityInfoRequestConnect(); @@ -946,7 +946,7 @@ namespace AzToolsFramework void EditorEntityModel::EditorEntityModelEntry::UpdateSliceInfo() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //reset slice info m_sliceFlags = (m_sliceFlags & SliceFlag_OverridesMask); // only hold on to the override flags @@ -1037,7 +1037,7 @@ namespace AzToolsFramework void EditorEntityModel::EditorEntityModelEntry::UpdateOrderInfo(bool notify) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::u64 oldIndex = m_indexForSorting; AZ::u64 newIndex = 0; @@ -1061,7 +1061,7 @@ namespace AzToolsFramework void EditorEntityModel::EditorEntityModelEntry::UpdateChildOrderInfo(bool forceAddToBack) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //add order info if missing for (auto childId : m_children) { @@ -1475,7 +1475,7 @@ namespace AzToolsFramework void EditorEntityModel::EditorEntityModelEntry::OnEntityLockFlagChanged(bool locked) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_locked != locked) { @@ -1493,7 +1493,7 @@ namespace AzToolsFramework void EditorEntityModel::EditorEntityModelEntry::OnEntityVisibilityFlagChanged(bool visibility) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_visible != visibility) { @@ -1511,7 +1511,7 @@ namespace AzToolsFramework void EditorEntityModel::EditorEntityModelEntry::OnSelected() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!m_selected) { m_selected = true; @@ -1522,7 +1522,7 @@ namespace AzToolsFramework void EditorEntityModel::EditorEntityModelEntry::OnDeselected() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_selected) { m_selected = false; @@ -1533,7 +1533,7 @@ namespace AzToolsFramework void EditorEntityModel::EditorEntityModelEntry::OnEntityNameChanged(const AZStd::string& name) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_name != name) { m_name = name; @@ -1554,7 +1554,7 @@ namespace AzToolsFramework { if (CanProcessOverrides()) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); using TransformComponent = AzToolsFramework::Components::TransformComponent; @@ -1569,7 +1569,7 @@ namespace AzToolsFramework { if (CanProcessOverrides()) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); using EditorInspectorComponent = AzToolsFramework::Components::EditorInspectorComponent; @@ -1584,7 +1584,7 @@ namespace AzToolsFramework { if (CanProcessOverrides()) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::Component* liveComponent = m_entity->FindComponent(componentId); AZ::Component* sourceComponent = m_sourceClone->FindComponent(componentId); @@ -1804,7 +1804,7 @@ namespace AzToolsFramework return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::u8 lastFlags = m_sliceFlags; @@ -1884,7 +1884,7 @@ namespace AzToolsFramework void EditorEntityModel::EditorEntityModelEntry::ModifyParentsOverriddenChildren(AZ::EntityId childEntityId, AZ::u8 lastFlags, bool childHasOverrides) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (((lastFlags & SliceFlag_EntityHasOverrides) == 0) != ((m_sliceFlags & SliceFlag_EntityHasOverrides) == 0)) { @@ -1916,7 +1916,7 @@ namespace AzToolsFramework void EditorEntityModel::EditorEntityModelEntry::UpdateCyclicDependencyInfo() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // Only check cyclic dependency if the current entity is a slice root if (!IsSliceRoot()) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntitySortComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntitySortComponent.cpp index 0e53c180d4..b747469f4d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntitySortComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntitySortComponent.cpp @@ -130,7 +130,7 @@ namespace AzToolsFramework bool EditorEntitySortComponent::SetChildEntityOrderArray(const EntityOrderArray& entityOrderArray) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_childEntityOrderArray != entityOrderArray) { m_childEntityOrderArray = entityOrderArray; @@ -143,7 +143,7 @@ namespace AzToolsFramework bool EditorEntitySortComponent::AddChildEntityInternal(const AZ::EntityId& entityId, bool addToBack, EntityOrderArray::iterator insertPosition) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto entityItr = m_childEntityOrderCache.find(entityId); if (entityItr == m_childEntityOrderCache.end()) { @@ -197,7 +197,7 @@ namespace AzToolsFramework bool EditorEntitySortComponent::RemoveChildEntity(const AZ::EntityId& entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto entityItr = m_childEntityOrderCache.find(entityId); if (entityItr != m_childEntityOrderCache.end()) { @@ -222,7 +222,7 @@ namespace AzToolsFramework void EditorEntitySortComponent::OnEntityStreamLoadSuccess() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_childEntityOrderCache.clear(); if (!m_childEntityOrderArray.empty()) @@ -320,7 +320,7 @@ namespace AzToolsFramework void EditorEntitySortComponent::RebuildEntityOrderCache() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_childEntityOrderCache.clear(); for (auto entityId : m_childEntityOrderArray) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/SliceEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/SliceEditorEntityOwnershipService.cpp index e22800498c..7ac3b7be8f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/SliceEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/SliceEditorEntityOwnershipService.cpp @@ -77,7 +77,7 @@ namespace AzToolsFramework AzFramework::SliceInstantiationTicket SliceEditorEntityOwnershipService::InstantiateEditorSlice( const AZ::Data::Asset& sliceAsset, const AZ::Transform& worldTransform) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (sliceAsset.GetId().IsValid()) { @@ -97,7 +97,7 @@ namespace AzToolsFramework void SliceEditorEntityOwnershipService::OnSlicePreInstantiate(const AZ::Data::AssetId& sliceAssetId, const AZ::SliceComponent::SliceInstanceAddress& sliceAddress) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AzFramework::SliceInstantiationTicket ticket = *AzFramework::SliceInstantiationResultBus::GetCurrentBusId(); // Start an undo that will wrap the entire slice instantiation event (unable to do this at a higher level since this is queued up by AzFramework and there's no undo concept at that level) @@ -134,7 +134,7 @@ namespace AzToolsFramework void SliceEditorEntityOwnershipService::OnSliceInstantiated(const AZ::Data::AssetId& sliceAssetId, const AZ::SliceComponent::SliceInstanceAddress& sliceAddress) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AzFramework::SliceInstantiationTicket ticket = *AzFramework::SliceInstantiationResultBus::GetCurrentBusId(); @@ -149,7 +149,7 @@ namespace AzToolsFramework // Close out the next ticket corresponding to this asset. for (auto instantiatingIter = m_instantiatingSlices.begin(); instantiatingIter != m_instantiatingSlices.end(); ++instantiatingIter) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorEntityContextComponent::OnSliceInstantiated:CloseTicket"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EditorEntityContextComponent::OnSliceInstantiated:CloseTicket"); if (instantiatingIter->first.GetId() == sliceAssetId) { const AZ::SliceComponent::EntityList& entities = sliceAddressCopy.GetInstance()->GetInstantiated()->m_entities; @@ -165,7 +165,7 @@ namespace AzToolsFramework // Create a slice instantiation undo command. { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorEntityContextComponent::OnSliceInstantiated:CloseTicket:CreateInstantiateUndo"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EditorEntityContextComponent::OnSliceInstantiated:CloseTicket:CreateInstantiateUndo"); ScopedUndoBatch undoBatch("Instantiate Slice"); for (AZ::Entity* entity : entities) { @@ -192,7 +192,7 @@ namespace AzToolsFramework void SliceEditorEntityOwnershipService::OnSliceInstantiationFailed(const AZ::Data::AssetId& sliceAssetId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AzFramework::SliceInstantiationTicket ticket = *AzFramework::SliceInstantiationResultBus::GetCurrentBusId(); @@ -214,7 +214,7 @@ namespace AzToolsFramework AZ::SliceComponent::SliceInstanceAddress SliceEditorEntityOwnershipService::CloneEditorSliceInstance( AZ::SliceComponent::SliceInstanceAddress sourceInstance, AZ::SliceComponent::EntityIdToEntityIdMap& sourceToCloneEntityIdMap) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (sourceInstance.IsValid()) { @@ -330,7 +330,7 @@ namespace AzToolsFramework void SliceEditorEntityOwnershipService::DetachSliceInstances(const AZ::SliceComponent::SliceInstanceAddressSet& instances) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const char* undoMsg = instances.size() == 1 ? "Detach Instance from Slice" : "Detach Instances from Slice"; @@ -359,7 +359,7 @@ namespace AzToolsFramework void SliceEditorEntityOwnershipService::DetachSubsliceInstances(const AZ::SliceComponent::SliceInstanceEntityIdRemapList& subsliceRootList) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (subsliceRootList.empty()) { @@ -379,7 +379,7 @@ namespace AzToolsFramework void SliceEditorEntityOwnershipService::DetachFromSlice(const AzToolsFramework::EntityIdList& entities, const char* undoMessage) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (entities.empty()) { @@ -424,7 +424,7 @@ namespace AzToolsFramework void SliceEditorEntityOwnershipService::OnAssetReady(AZ::Data::Asset asset) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::Data::AssetBus::MultiHandler::BusDisconnect(asset.GetId()); @@ -511,7 +511,7 @@ namespace AzToolsFramework //========================================================================= void SliceEditorEntityOwnershipService::OnAssetReloaded(AZ::Data::Asset asset) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EntityIdList selectedEntities; ToolsApplicationRequests::Bus::BroadcastResult(selectedEntities, &ToolsApplicationRequests::GetSelectedEntities); @@ -524,7 +524,7 @@ namespace AzToolsFramework void SliceEditorEntityOwnershipService::ResetEntitiesToSliceDefaults(EntityIdList entities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch("Resetting entities to slice defaults."); PreemptiveUndoCache* preemptiveUndoCache = nullptr; @@ -646,7 +646,7 @@ namespace AzToolsFramework bool SliceEditorEntityOwnershipService::SaveToStreamForEditor(AZ::IO::GenericStream& stream, const EntityList& entitiesInLayers, AZ::SliceComponent::SliceReferenceToInstancePtrs& instancesInLayers) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(stream.IsOpen(), "Invalid target stream."); AzFramework::RootSliceAsset rootSliceAsset = GetRootAsset(); @@ -685,7 +685,7 @@ namespace AzToolsFramework bool SliceEditorEntityOwnershipService::SaveToStreamForGame(AZ::IO::GenericStream& stream, AZ::DataStream::StreamType streamType) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::SliceComponent::EntityList sourceEntities; GetRootSlice()->GetEntities(sourceEntities); @@ -929,7 +929,7 @@ namespace AzToolsFramework bool SliceEditorEntityOwnershipService::LoadFromStreamWithLayers(AZ::IO::GenericStream& stream, QString levelPakFile) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::ObjectStream::FilterDescriptor filterDesc = AZ::ObjectStream::FilterDescriptor(&AZ::Data::AssetFilterSourceSlicesOnly); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.cpp index b7776238ba..d39ade5527 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.cpp @@ -285,7 +285,7 @@ namespace AzToolsFramework } } - void QtEventToAzInputMapper::ProcessPendingMouseEvents() + void QtEventToAzInputMapper::ProcessPendingMouseEvents(const QPoint& cursorDelta) { auto systemCursorChannel = GetInputChannel(AzFramework::InputDeviceMouse::SystemCursorPosition); @@ -297,14 +297,8 @@ namespace AzToolsFramework GetInputChannel(AzFramework::InputDeviceMouse::Movement::Z); systemCursorChannel->ProcessRawInputEvent(m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta.GetLength()); - // Generate movement events based on the pixel delta divided by the DPI scaling factor, to calculate a rough approximation - // of cursor movement velocity. - movementXChannel->ProcessRawInputEvent( - m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta.GetX() * aznumeric_cast(m_sourceWidget->width()) / - m_sourceWidget->devicePixelRatioF()); - movementYChannel->ProcessRawInputEvent( - m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta.GetY() * aznumeric_cast(m_sourceWidget->height()) / - m_sourceWidget->devicePixelRatioF()); + movementXChannel->ProcessRawInputEvent(static_cast(cursorDelta.x())); + movementYChannel->ProcessRawInputEvent(static_cast(cursorDelta.y())); mouseWheelChannel->ProcessRawInputEvent(0.0f); NotifyUpdateChannelIfNotIdle(systemCursorChannel, nullptr); @@ -337,41 +331,43 @@ namespace AzToolsFramework } } - AZ::Vector2 QtEventToAzInputMapper::WidgetPositionToNormalizedPosition(QPoint position) + AZ::Vector2 QtEventToAzInputMapper::WidgetPositionToNormalizedPosition(const QPoint& position) { const float normalizedX = aznumeric_cast(position.x()) / aznumeric_cast(m_sourceWidget->width()); const float normalizedY = aznumeric_cast(position.y()) / aznumeric_cast(m_sourceWidget->height()); - return AZ::Vector2{normalizedX, normalizedY}; + return AZ::Vector2{ normalizedX, normalizedY }; } - QPoint QtEventToAzInputMapper::NormalizedPositionToWidgetPosition(AZ::Vector2 normalizedPosition) + QPoint QtEventToAzInputMapper::NormalizedPositionToWidgetPosition(const AZ::Vector2& normalizedPosition) { const int denormalizedX = aznumeric_cast(normalizedPosition.GetX() * m_sourceWidget->width()); const int denormalizedY = aznumeric_cast(normalizedPosition.GetY() * m_sourceWidget->height()); - return QPoint{denormalizedX, denormalizedY}; + return QPoint{ denormalizedX, denormalizedY }; } void QtEventToAzInputMapper::HandleMouseMoveEvent(QMouseEvent* mouseEvent) { - AZ::Vector2 lastCursorPosition = m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition; + const QPoint cursorPosition = mouseEvent->pos(); + const QPoint cursorDelta = cursorPosition - m_previousCursorPosition; - const QPoint mousePos = mouseEvent->pos(); - const AZ::Vector2 normalizedPosition = WidgetPositionToNormalizedPosition(mousePos); - m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta = normalizedPosition - m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition; - m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition = normalizedPosition; - ProcessPendingMouseEvents(); + m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition = WidgetPositionToNormalizedPosition(cursorPosition); + m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta = WidgetPositionToNormalizedPosition(cursorDelta); + + ProcessPendingMouseEvents(cursorDelta); if (m_capturingCursor) { // Reset our cursor position to the previous point. - QPoint targetScreenPosition = m_sourceWidget->mapToGlobal(NormalizedPositionToWidgetPosition(lastCursorPosition)); + const QPoint targetScreenPosition = m_sourceWidget->mapToGlobal(m_previousCursorPosition); AzQtComponents::SetCursorPos(targetScreenPosition); // Even though we just set the cursor position, there are edge cases such as remote desktop that will leave // the cursor position unchanged. For safety, we re-cache our last cursor position for delta generation. - QPoint actualWidgetPosition = m_sourceWidget->mapFromGlobal(QCursor::pos()); + const QPoint actualWidgetPosition = m_sourceWidget->mapFromGlobal(QCursor::pos()); m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition = WidgetPositionToNormalizedPosition(actualWidgetPosition); } + + m_previousCursorPosition = cursorPosition; } void QtEventToAzInputMapper::HandleKeyEvent(QKeyEvent* keyEvent) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.h index 0187cb2e5b..6e73bf4f9c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Input/QtEventToAzInputManager.h @@ -21,6 +21,7 @@ #include #include +#include #endif //! defined(Q_MOC_RUN) class QWidget; @@ -111,12 +112,12 @@ namespace AzToolsFramework void NotifyUpdateChannelIfNotIdle(const AzFramework::InputChannel* channel, QEvent* event); // Processes any pending mouse movement events, this allows mouse movement channels to close themselves. - void ProcessPendingMouseEvents(); + void ProcessPendingMouseEvents(const QPoint& cursorDelta); // Converts a point in logical source widget space [0..m_sourceWidget->size()] to normalized [0..1] space. - AZ::Vector2 WidgetPositionToNormalizedPosition(QPoint position); + AZ::Vector2 WidgetPositionToNormalizedPosition(const QPoint& position); // Converts a point in normalized [0..1] space to logical source widget space [0..m_sourceWidget->size()]. - QPoint NormalizedPositionToWidgetPosition(AZ::Vector2 normalizedPosition); + QPoint NormalizedPositionToWidgetPosition(const AZ::Vector2& normalizedPosition); // Handle mouse click events. void HandleMouseButtonEvent(QMouseEvent* mouseEvent); @@ -148,6 +149,8 @@ namespace AzToolsFramework AZStd::unordered_set m_highPriorityKeys; // A lookup table for AZ input channel ID -> physical input channel on our mouse or keyboard device. AZStd::unordered_map m_channels; + // Where the position of the mouse cursor was at the last cursor event. + QPoint m_previousCursorPosition; // The source widget to map events from, used to calculate the relative mouse position within the widget bounds. QWidget* m_sourceWidget; // Flags whether or not Qt events should currently be processed. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp index 1a7e7260c5..b514c3957f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BaseManipulator.cpp @@ -33,7 +33,7 @@ namespace AzToolsFramework bool BaseManipulator::OnLeftMouseDown(const ViewportInteraction::MouseInteraction& interaction, const float rayIntersectionDistance) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_onLeftMouseDownImpl) { @@ -59,7 +59,7 @@ namespace AzToolsFramework bool BaseManipulator::OnRightMouseDown(const ViewportInteraction::MouseInteraction& interaction, const float rayIntersectionDistance) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_onRightMouseDownImpl) { @@ -87,7 +87,7 @@ namespace AzToolsFramework // attached as no active manipulator will have been set in ManipulatorManager. void BaseManipulator::OnLeftMouseUp(const ViewportInteraction::MouseInteraction& interaction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); SetBoundsDirty(); @@ -98,7 +98,7 @@ namespace AzToolsFramework void BaseManipulator::OnRightMouseUp(const ViewportInteraction::MouseInteraction& interaction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); SetBoundsDirty(); @@ -109,7 +109,7 @@ namespace AzToolsFramework bool BaseManipulator::OnMouseOver(const ManipulatorId manipulatorId, const ViewportInteraction::MouseInteraction& interaction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); UpdateMouseOver(manipulatorId); OnMouseOverImpl(manipulatorId, interaction); @@ -125,7 +125,7 @@ namespace AzToolsFramework void BaseManipulator::OnMouseMove(const ViewportInteraction::MouseInteraction& interaction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!m_performingAction) { @@ -142,7 +142,7 @@ namespace AzToolsFramework void BaseManipulator::SetBoundsDirty() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); SetBoundsDirtyImpl(); } @@ -190,7 +190,7 @@ namespace AzToolsFramework void BaseManipulator::EndAction() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!m_performingAction) { @@ -235,7 +235,7 @@ namespace AzToolsFramework void BaseManipulator::NotifyEntityComponentPropertyChanged() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (const AZ::EntityComponentIdPair& entityComponentIdPair : m_entityComponentIdPairs) { @@ -268,7 +268,7 @@ namespace AzToolsFramework AZStd::unordered_set::iterator BaseManipulator::RemoveEntityId(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto afterErased = m_entityComponentIdPairs.end(); @@ -297,7 +297,7 @@ namespace AzToolsFramework AZStd::unordered_set::iterator BaseManipulator::RemoveEntityComponentIdPair( const AZ::EntityComponentIdPair& entityComponentIdPair) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto entityIdIt = m_entityComponentIdPairs.find(entityComponentIdPair); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp index fa4fb9ad31..f49df5d029 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp @@ -147,7 +147,7 @@ namespace AzToolsFramework const AZ::Vector3& localManipulatorStartPosition, const AZ::Vector3& localManipulatorOffset) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // bind FixedVerticesRequestBus for improved performance typename AZ::FixedVerticesRequestBus::BusPtr fixedVertices; @@ -180,7 +180,7 @@ namespace AzToolsFramework template void InitializeVertexLookup(IndexedTranslationManipulator& translationManipulator, const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // bind FixedVerticesRequestBus for improved performance typename AZ::FixedVerticesRequestBus::BusPtr fixedVertices; @@ -210,7 +210,7 @@ namespace AzToolsFramework const Vertex& vertex, size_t vertexIndex) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // if we have a vertex (translation) manipulator active, ensure // it gets removed when clicking on another selection manipulator @@ -342,7 +342,7 @@ namespace AzToolsFramework const EditorBoxSelect& editorBoxSelect, const AZStd::vector>& selectionManipulators) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // refresh selection manipulators and box select data when modifiers change // (switching from additive to subtractive) @@ -481,7 +481,7 @@ namespace AzToolsFramework const TranslationManipulators::Dimensions dimensions, const TranslationManipulatorConfiguratorFn translationManipulatorConfigurator) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_dimensions = dimensions; m_manipulatorManagerId = managerId; @@ -705,7 +705,7 @@ namespace AzToolsFramework template void EditorVertexSelectionBase::ClearSelected() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // if translation manipulator is active, remove it when receiving this event and enable // the hover manipulator bounds again so points can be inserted again @@ -736,7 +736,7 @@ namespace AzToolsFramework void EditorVertexSelectionBase::DisplayEntityViewport( const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_editorBoxSelect.DisplayScene(viewportInfo, debugDisplay); @@ -747,7 +747,7 @@ namespace AzToolsFramework void EditorVertexSelectionBase::DisplayViewport2d( const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_editorBoxSelect.Display2d(viewportInfo, debugDisplay); } @@ -756,7 +756,7 @@ namespace AzToolsFramework template::value>::type*> void EditorVertexSelectionBase::UpdateManipulatorSpace(const AzFramework::ViewportInfo& viewportInfo) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // check if 'shift' is being held to move to parent space bool worldSpace = false; @@ -803,7 +803,7 @@ namespace AzToolsFramework template void EditorVertexSelectionVariable::DestroySelected() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::EntityId entityId = EditorVertexSelectionBase::GetEntityId(); @@ -855,7 +855,7 @@ namespace AzToolsFramework template void EditorVertexSelectionBase::SetSelectedPosition(const AZ::Vector3& localPosition) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_translationManipulator) { @@ -884,7 +884,7 @@ namespace AzToolsFramework template void EditorVertexSelectionBase::RefreshTranslationManipulator() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // bind FixedVerticesRequestBus for improved performance typename AZ::FixedVerticesRequestBus::BusPtr fixedVertices; @@ -915,7 +915,7 @@ namespace AzToolsFramework template void EditorVertexSelectionBase::RefreshLocal() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // we do not want to refresh our local state while a batch movement is in progress, // even if we have been signalled to do so by a callback @@ -955,7 +955,7 @@ namespace AzToolsFramework template void EditorVertexSelectionBase::RefreshSpace(const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (auto& manipulator : m_selectionManipulators) { @@ -982,7 +982,7 @@ namespace AzToolsFramework template void EditorVertexSelectionBase::SetBoundsDirty() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (auto& manipulator : m_selectionManipulators) { @@ -1008,7 +1008,7 @@ namespace AzToolsFramework const AZ::EntityComponentIdPair& entityComponentIdPair, const ManipulatorManagerId managerId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); Vertex vertex; bool found = false; @@ -1078,7 +1078,7 @@ namespace AzToolsFramework const ManipulatorManagerId managerId, const size_t vertexIndex) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // setup selection manipulator const AZStd::shared_ptr selectionView = AzToolsFramework::CreateManipulatorViewSphere( @@ -1115,7 +1115,7 @@ namespace AzToolsFramework const ManipulatorManagerId managerId, const size_t vertexIndex) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // setup selection manipulator const AZStd::shared_ptr manipulatorView = AzToolsFramework::CreateManipulatorViewSphere( @@ -1223,7 +1223,7 @@ namespace AzToolsFramework Vertex EditorVertexSelectionVariable::InsertSelectedInPlace( AZStd::vector::VertexLookup>& manipulators) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // utility to calculate the center point of the selected vertices after duplication MidpointCalculator midpointCalculator; @@ -1267,7 +1267,7 @@ namespace AzToolsFramework template void EditorVertexSelectionVariable::DuplicateSelected() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch duplicateUndo("Duplicate Vertices"); ScopedUndoBatch::MarkEntityDirty(EditorVertexSelectionBase::GetEntityId()); @@ -1346,7 +1346,7 @@ namespace AzToolsFramework template void InsertVertexAfter(const AZ::EntityComponentIdPair& entityComponentIdPair, const size_t vertexIndex, const Vertex& localPosition) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); size_t size = 0; AZ::VariableVerticesRequestBus::EventResult( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.cpp index e994e8e2cd..b07ac08d87 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/ManipulatorManager.cpp @@ -74,7 +74,7 @@ namespace AzToolsFramework Picking::RegisteredBoundId ManipulatorManager::UpdateBound( const ManipulatorId manipulatorId, const Picking::RegisteredBoundId boundId, const Picking::BoundRequestShapeBase& boundShapeData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (manipulatorId == InvalidManipulatorId) { @@ -124,7 +124,7 @@ namespace AzToolsFramework void ManipulatorManager::RefreshMouseOverState(const ViewportInteraction::MousePick& mousePick) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!Interacting()) { @@ -142,7 +142,7 @@ namespace AzToolsFramework const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteraction& mouseInteraction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (const auto& pair : m_manipulatorIdToPtrMap) { @@ -155,7 +155,7 @@ namespace AzToolsFramework AZStd::shared_ptr ManipulatorManager::PerformRaycast( const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection, float& rayIntersectionDistance) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); Picking::RaySelectInfo raySelection; raySelection.m_origin = rayOrigin; @@ -255,7 +255,7 @@ namespace AzToolsFramework ManipulatorManager::ConsumeMouseMoveResult ManipulatorManager::ConsumeViewportMouseMove( const ViewportInteraction::MouseInteraction& interaction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_activeManipulator) { @@ -279,7 +279,7 @@ namespace AzToolsFramework void ManipulatorManager::OnEntityInfoUpdatedVisibility(const AZ::EntityId entityId, const bool visible) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (auto& pair : m_manipulatorIdToPtrMap) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp index 043f864245..54e7f7608c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/Instance.cpp @@ -650,7 +650,10 @@ namespace AzToolsFramework AZStd::unique_ptr Instance::DetachContainerEntity() { - m_instanceEntityMapper->UnregisterEntity(m_containerEntity->GetId()); + if (m_containerEntity) + { + m_instanceEntityMapper->UnregisterEntity(m_containerEntity->GetId()); + } return AZStd::move(m_containerEntity); } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 7af953efca..cdb1e9a2ad 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::CreatePrefabInMemory(const AZStd::vector& entityIds, AZ::IO::PathView filePath) + PrefabOperationResult PrefabPublicHandler::CreatePrefabInMemory(const EntityIdList& entityIds, AZ::IO::PathView filePath) { EntityList inputEntityList, topLevelEntities; AZ::EntityId commonRootEntityId; @@ -264,7 +264,7 @@ namespace AzToolsFramework return AZ::Success(); } - PrefabOperationResult PrefabPublicHandler::CreatePrefabInDisk(const AZStd::vector& entityIds, AZ::IO::PathView filePath) + PrefabOperationResult PrefabPublicHandler::CreatePrefabInDisk(const EntityIdList& entityIds, AZ::IO::PathView filePath) { auto result = CreatePrefabInMemory(entityIds, filePath); if (result.IsSuccess()) @@ -996,12 +996,12 @@ namespace AzToolsFramework // the full nested hierarchy with what is returned from RetrieveAndSortPrefabEntitiesAndInstances AzToolsFramework::EntityIdSet duplicationSet = AzToolsFramework::GetCulledEntityHierarchy(entityIdsNoLevelInstance); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch("Duplicate Entities"); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "DuplicateEntitiesInInstance::UndoCaptureAndDuplicateEntities"); + AZ_PROFILE_SCOPE(AzToolsFramework, "DuplicateEntitiesInInstance::UndoCaptureAndDuplicateEntities"); AZStd::vector entities; AZStd::vector instances; @@ -1123,7 +1123,7 @@ namespace AzToolsFramework // Retrieve entityList from entityIds EntityList inputEntityList = EntityIdListToEntityList(entityIdsNoLevelInstance); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch("Delete Selected"); @@ -1145,7 +1145,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DeleteEntities:UndoCaptureAndPurgeEntities"); + AZ_PROFILE_SCOPE(AzToolsFramework, "Internal::DeleteEntities:UndoCaptureAndPurgeEntities"); Prefab::PrefabDom instanceDomBefore; m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, commonOwningInstance->get()); @@ -1205,7 +1205,7 @@ namespace AzToolsFramework selCommand->SetParent(undoBatch.GetUndoBatch()); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DeleteEntities:RunRedo"); + AZ_PROFILE_SCOPE(AzToolsFramework, "Internal::DeleteEntities:RunRedo"); selCommand->RunRedo(); } @@ -1230,10 +1230,10 @@ namespace AzToolsFramework return AZ::Failure(AZStd::string("Input entity should be its owning Instance's container entity.")); } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DetachPrefab:UndoCapture"); + AZ_PROFILE_SCOPE(AzToolsFramework, "Internal::DetachPrefab:UndoCapture"); ScopedUndoBatch undoBatch("Detach Prefab"); @@ -1294,7 +1294,7 @@ namespace AzToolsFramework command->Capture(instanceDomBefore, instanceDomAfter, parentTemplateId); command->SetParent(undoBatch.GetUndoBatch()); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DetachPrefab:RunRedo"); + AZ_PROFILE_SCOPE(AzToolsFramework, "Internal::DetachPrefab:RunRedo"); command->RunRedo(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 8f124e8edd..6faaa6932f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -43,9 +43,9 @@ namespace AzToolsFramework // PrefabPublicInterface... PrefabOperationResult CreatePrefabInDisk( - const AZStd::vector& entityIds, AZ::IO::PathView filePath) override; + const EntityIdList& entityIds, AZ::IO::PathView filePath) override; PrefabOperationResult CreatePrefabInMemory( - const AZStd::vector& entityIds, AZ::IO::PathView filePath) override; + const EntityIdList& 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 67d65dfca6..83763ef55f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicInterface.h @@ -47,7 +47,7 @@ namespace AzToolsFramework * @return An outcome object; on failure, it comes with an error message detailing the cause of the error. */ virtual PrefabOperationResult CreatePrefabInDisk( - const AZStd::vector& entityIds, AZ::IO::PathView filePath) = 0; + const EntityIdList& entityIds, AZ::IO::PathView filePath) = 0; /** * Create a prefab out of the entities provided, at the path provided, and keep it in memory. @@ -57,7 +57,7 @@ namespace AzToolsFramework * @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; + const EntityIdList& entityIds, AZ::IO::PathView filePath) = 0; /** * Instantiate a prefab from a prefab file. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h index 1b86d3cd4e..1605ad97be 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestBus.h @@ -11,13 +11,20 @@ #include #include #include +#include #include +#include #include namespace AzToolsFramework { + using EntityIdList = AZStd::vector; + namespace Prefab { + using PrefabOperationResult = AZ::Outcome; + using InstantiatePrefabResult = AZ::Outcome; + /** * The primary purpose of this bus is to facilitate writing automated tests for prefabs. * It calls PrefabPublicInterface internally to talk to the prefab system. @@ -40,14 +47,25 @@ namespace AzToolsFramework /** * 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. + * Return whether the creation succeeded or not. */ - virtual bool CreatePrefabInMemory( - const AZStd::vector& entityIds, AZStd::string_view filePath) = 0; + virtual PrefabOperationResult CreatePrefabInMemory( + const EntityIdList& entityIds, AZStd::string_view filePath) = 0; /** * Instantiate a prefab from a prefab file. + * Return the container entity id of the prefab instantiated if instantiation succeeded. */ - virtual AZ::EntityId 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; + + /** + * Deletes all entities and their descendants from the owning instance. Bails if the entities don't + * all belong to the same instance. + * Return whether the deletion succeeded or not. + */ + virtual PrefabOperationResult DeleteEntitiesAndAllDescendantsInInstance(const EntityIdList& entityIds) = 0; + }; using PrefabPublicRequestBus = AZ::EBus; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp index 0e68a286a6..d964be25af 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.cpp @@ -25,6 +25,7 @@ namespace AzToolsFramework ->Attribute(AZ::Script::Attributes::Module, "prefab") ->Event("CreatePrefabInMemory", &PrefabPublicRequests::CreatePrefabInMemory) ->Event("InstantiatePrefab", &PrefabPublicRequests::InstantiatePrefab) + ->Event("DeleteEntitiesAndAllDescendantsInInstance", &PrefabPublicRequests::DeleteEntitiesAndAllDescendantsInInstance) ; } } @@ -44,36 +45,20 @@ namespace AzToolsFramework m_prefabPublicInterface = nullptr; } - bool PrefabPublicRequestHandler::CreatePrefabInMemory(const AZStd::vector& entityIds, AZStd::string_view filePath) + PrefabOperationResult PrefabPublicRequestHandler::CreatePrefabInMemory(const EntityIdList& 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; + return m_prefabPublicInterface->CreatePrefabInMemory(entityIds, filePath); } - AZ::EntityId PrefabPublicRequestHandler::InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) + InstantiatePrefabResult 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(); + return m_prefabPublicInterface->InstantiatePrefab(filePath, parent, position); } + + PrefabOperationResult PrefabPublicRequestHandler::DeleteEntitiesAndAllDescendantsInInstance(const EntityIdList& entityIds) + { + return m_prefabPublicInterface->DeleteEntitiesAndAllDescendantsInInstance(entityIds); + } + } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h index 548bc8e04a..87608e1263 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicRequestHandler.h @@ -31,8 +31,9 @@ namespace AzToolsFramework 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; + PrefabOperationResult CreatePrefabInMemory(const EntityIdList& entityIds, AZStd::string_view filePath) override; + InstantiatePrefabResult InstantiatePrefab(AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position) override; + PrefabOperationResult DeleteEntitiesAndAllDescendantsInInstance(const EntityIdList& entityIds) override; private: PrefabPublicInterface* m_prefabPublicInterface = nullptr; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.cpp index 3d22a35858..c83e0857a3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoCache.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -111,7 +112,7 @@ namespace AzToolsFramework void PrefabUndoCache::UpdateCache(const AZ::EntityId& entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::Entity* entity = nullptr; AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, entityId); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp index c455873036..7b7107ae3e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp @@ -65,16 +65,24 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils AzFramework::Spawnable::EntityList& entities = spawnable->GetEntities(); for (auto it = entities.begin(); it != entities.end(); ) { - (*it)->InvalidateDependencies(); - AZ::Entity::DependencySortOutcome evaluation = (*it)->EvaluateDependenciesGetDetails(); - if (evaluation.IsSuccess()) + if (*it) { - ++it; + (*it)->InvalidateDependencies(); + AZ::Entity::DependencySortOutcome evaluation = (*it)->EvaluateDependenciesGetDetails(); + if (evaluation.IsSuccess()) + { + ++it; + } + else + { + AZ_Error( + "Prefabs", false, "Entity '%s' %s cannot be activated for the following reason: %s", (*it)->GetName().c_str(), + (*it)->GetId().ToString().c_str(), evaluation.GetError().m_message.c_str()); + it = entities.erase(it); + } } else { - AZ_Error("Prefabs", false, "Entity '%s' %s cannot be activated for the following reason: %s", - (*it)->GetName().c_str(), (*it)->GetId().ToString().c_str(), evaluation.GetError().m_message.c_str()); it = entities.erase(it); } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceCompilation.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceCompilation.cpp index 3c7bab3e77..e9825f6f14 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceCompilation.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceCompilation.cpp @@ -274,7 +274,7 @@ namespace AzToolsFramework */ SliceCompilationResult CompileEditorSlice(const AZ::Data::Asset& sourceSliceAsset, const AZ::PlatformTagSet& platformTags, AZ::SerializeContext& serializeContext, const EditorOnlyEntityHandlers& editorOnlyEntityHandlers) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!sourceSliceAsset) { return AZ::Failure(AZStd::string("Source slice is invalid.")); @@ -657,7 +657,7 @@ namespace AzToolsFramework // tolerate ALL possible input errors (looping parents, invalid IDs, etc). void SortTransformParentsBeforeChildren(AZStd::vector& entities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // IDs of those present in 'entities'. Does not include parent ID if parent not found in 'entities' AZStd::unordered_set existingEntityIds; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceTransaction.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceTransaction.cpp index 15b330c65b..d8b5fe0a15 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceTransaction.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceTransaction.cpp @@ -63,7 +63,7 @@ namespace AzToolsFramework void Capture(const SliceTransaction::SliceAssetPtr& before, const SliceTransaction::SliceAssetPtr& after, const char* sliceAssetPath) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_sliceAssetPath = sliceAssetPath; m_isNewAsset = !before.GetId().IsValid(); @@ -74,7 +74,7 @@ namespace AzToolsFramework if (!m_isNewAsset) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDiskCommand::Capture:SaveBefore"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDiskCommand::Capture:SaveBefore"); AZ::SliceAsset* sliceBefore = before.Get(); AZ::Entity* sliceEntityBefore = sliceBefore->GetEntity(); AZ::IO::ByteContainerStream beforeStream(&m_sliceAssetBeforeBuffer); @@ -82,7 +82,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDiskCommand::Capture:SaveAfter"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDiskCommand::Capture:SaveAfter"); AZ::SliceAsset* sliceAfter = after.Get(); AZ::Entity* sliceEntityAfter = sliceAfter->GetEntity(); AZ::IO::ByteContainerStream afterStream(&m_sliceAssetAfterBuffer); @@ -105,13 +105,13 @@ namespace AzToolsFramework void Redo() override { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_redoResult = Internal::SaveSliceToDisk(m_sliceAssetPath.c_str(), m_sliceAssetAfterBuffer); } void Undo() override { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_isNewAsset) { // New asset means we didn't have an existing asset, so we should instead remove the newly created asset as our undo @@ -149,7 +149,7 @@ namespace AzToolsFramework AZ::SerializeContext* serializeContext, AZ::u32 sliceCreationFlags) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!serializeContext) { @@ -179,7 +179,7 @@ namespace AzToolsFramework SliceTransaction::TransactionPtr SliceTransaction::BeginSliceOverwrite(const SliceAssetPtr& asset, const AZ::SliceComponent& overwriteComponent, AZ::SerializeContext* serializeContext) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!serializeContext) { @@ -212,7 +212,7 @@ namespace AzToolsFramework AZ::SerializeContext* serializeContext, AZ::u32 /*slicePushFlags*/) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!serializeContext) { @@ -515,7 +515,7 @@ namespace AzToolsFramework SliceTransaction::PostSaveCallback postSaveCallback, AZ::u32 sliceCommitFlags) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // Clone asset for final modifications and save. // This also releases borrowed entities and slice instances. @@ -702,7 +702,7 @@ namespace AzToolsFramework SliceTransaction::PostSaveCallback postSaveCallback, AZ::u32 sliceCommitFlags) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::string sliceAssetPath; AZ::Data::AssetCatalogRequestBus::BroadcastResult(sliceAssetPath, &AZ::Data::AssetCatalogRequests::GetAssetPathById, targetAssetId); @@ -762,7 +762,7 @@ namespace AzToolsFramework //========================================================================= SliceTransaction::SliceAssetPtr SliceTransaction::CloneAssetForSave() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // Move included slice instances to the target asset temporarily so that they are included in the clone for (auto& addedSliceInstanceIt : m_addedSliceInstances) @@ -868,7 +868,7 @@ namespace AzToolsFramework //========================================================================= SliceTransaction::Result SliceTransaction::PreSave(const char* fullPath, SliceAssetPtr& asset, PreSaveCallback preSaveCallback, AZ::u32 /*sliceCommitFlags*/) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // Remap live Ids back to those of the asset. AZ::EntityUtils::SerializableEntityContainer assetEntities; @@ -904,7 +904,7 @@ namespace AzToolsFramework //========================================================================= AZ::EntityId SliceTransaction::FindTargetAncestorAndUpdateInstanceIdMap(AZ::EntityId entityId, AZ::SliceComponent::EntityIdToEntityIdMap& liveToAssetIdMap, const AZ::SliceComponent::SliceInstanceAddress* ignoreSliceInstance) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::SliceComponent* slice = m_targetAsset.Get()->GetComponent(); @@ -1036,7 +1036,7 @@ namespace AzToolsFramework //========================================================================= SliceTransaction::Result SaveSliceToDisk(const char* targetPath, AZStd::vector& sliceAssetEntityMemoryBuffer, AZ::SerializeContext* serializeContext) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); AZ_Assert(fileIO, "File IO is not initialized."); @@ -1058,7 +1058,7 @@ namespace AzToolsFramework // Write the in-memory copy to file bool savedToFile; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDisk:SaveToFileStream"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDisk:SaveToFileStream"); memoryStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN); savedToFile = fileStream.Write(memoryStream.GetLength(), memoryStream.GetData()->data()) != 0; } @@ -1066,14 +1066,14 @@ namespace AzToolsFramework if (savedToFile) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDisk:TempToTargetFileReplacement"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDisk:TempToTargetFileReplacement"); // Copy scratch file to target location. const bool targetFileExists = fileIO->Exists(targetPath); bool removedTargetFile; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDisk:TempToTargetFileReplacement:RemoveTarget"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDisk:TempToTargetFileReplacement:RemoveTarget"); removedTargetFile = fileIO->Remove(targetPath); } @@ -1083,7 +1083,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDisk:TempToTargetFileReplacement:RenameTempFile"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDisk:TempToTargetFileReplacement:RenameTempFile"); AZ::IO::Result renameResult = fileIO->Rename(tempFilePath.c_str(), targetPath); if (!renameResult) { @@ -1093,7 +1093,7 @@ namespace AzToolsFramework // Bump the slice asset up in the asset processor's queue. { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDisk:TempToTargetFileReplacement:GetAssetStatus"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::Internal::SaveSliceToDisk:TempToTargetFileReplacement:GetAssetStatus"); EBUS_EVENT(AzFramework::AssetSystemRequestBus, EscalateAssetBySearchTerm, targetPath); } return AZ::Success(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceUtilities.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceUtilities.cpp index 6ef0c83991..02fc2c2c40 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceUtilities.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Slice/SliceUtilities.cpp @@ -405,7 +405,7 @@ namespace AzToolsFramework bool QueryAndPruneMissingExternalReferences(AzToolsFramework::EntityIdSet& entities, AzToolsFramework::EntityIdSet& selectedAndReferencedEntities, bool& useReferencedEntities, bool defaultMoveExternalRefs = false) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::MakeNewSlice:HandleNotIncludedReferences"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::MakeNewSlice:HandleNotIncludedReferences"); useReferencedEntities = false; AZStd::string includedEntities; @@ -440,7 +440,7 @@ namespace AzToolsFramework { if (!defaultMoveExternalRefs) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::MakeNewSlice:HandleNotIncludedReferences:UserDialog"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::MakeNewSlice:HandleNotIncludedReferences:UserDialog"); const AZStd::string message = AZStd::string::format( "Entity references may not be valid if the entity IDs change or if the entities do not exist when the slice is instantiated.\r\n\r\nSelected Entities\n%s\nReferenced Entities\n%s\n", @@ -510,7 +510,7 @@ namespace AzToolsFramework while (true) { { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::MakeNewSlice:SaveAsDialog"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::MakeNewSlice:SaveAsDialog"); saveAs = QFileDialog::getSaveFileName(nullptr, QString("Save As..."), saveAsInitialSuggestedFullPath.c_str(), QString("Slices (*.slice)")); } @@ -608,7 +608,7 @@ namespace AzToolsFramework bool silenceWarningPopups, AZ::SerializeContext* serializeContext) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (entities.empty()) { @@ -702,7 +702,7 @@ namespace AzToolsFramework { if (inheritSlices) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::MakeNewSlice:CloneExistingSliceEntities"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::MakeNewSlice:CloneExistingSliceEntities"); const AZ::EntityId dummyParentId; @@ -801,14 +801,14 @@ namespace AzToolsFramework // Setup and execute transaction for the new slice. // { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::MakeNewSlice:SetupAndExecuteTransaction"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::MakeNewSlice:SetupAndExecuteTransaction"); // PreSaveCallback for slice creation: Before saving slice, we ensure it has a single root by optionally auto-creating one for the user SliceTransaction::PreSaveCallback preSaveCallback = [&sliceName, &sliceRootEntityPosition, &sliceRootEntityRotation, &activeWindow, &defaultGenerateSharedRoot] (SliceTransaction::TransactionPtr transaction, const char* fullPath, SliceTransaction::SliceAssetPtr& asset) -> SliceTransaction::Result { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::MakeNewSlice:PreSaveCallback"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::MakeNewSlice:PreSaveCallback"); AZ::SliceComponent::EntityIdToEntityIdMap assetToLiveEntityIDMap; const AZ::SliceComponent::EntityIdToEntityIdMap& liveToAssetEntityIDMap = transaction->GetLiveToAssetEntityIdMap(); @@ -855,7 +855,7 @@ namespace AzToolsFramework // Add entities { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::MakeNewSlice:SetupAndExecuteTransaction:AddEntities"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::MakeNewSlice:SetupAndExecuteTransaction:AddEntities"); for (const AZ::EntityId& entityId : entitiesToIncludeInAsset) { SliceTransaction::Result addResult = transaction->AddEntity(entityId, !inheritSlices ? SliceTransaction::SliceAddEntityFlags::DiscardSliceAncestry : 0); @@ -914,7 +914,7 @@ namespace AzToolsFramework void GatherAllReferencedEntities(AzToolsFramework::EntityIdSet& entitiesWithReferences, AZ::SerializeContext& serializeContext) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::vector floodQueue; floodQueue.reserve(entitiesWithReferences.size()); @@ -1038,7 +1038,7 @@ namespace AzToolsFramework const AZ::SliceComponent::SliceInstance& instance, AZ::SerializeContext& serializeContext) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(instance.GetEntityIdMap().find(sourceEntity.GetId()) != instance.GetEntityIdMap().end(), "Provided source entity is not a member of the provided slice instance."); @@ -1494,7 +1494,7 @@ namespace AzToolsFramework //========================================================================= SliceTransaction::Result SlicePreSaveCallbackForWorldEntities(SliceTransaction::TransactionPtr transaction, const char* fullPath, SliceTransaction::SliceAssetPtr& asset) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::SlicePreSaveCallbackForWorldEntities"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::SlicePreSaveCallbackForWorldEntities"); // Apply standard root transform rules. Zero out root entity translation, ensure single root, ensure slice root has no parent in slice. SliceTransaction::Result worldTransformRulesResult = VerifyAndApplySliceWorldTransformRules(asset); @@ -1536,7 +1536,7 @@ namespace AzToolsFramework void SlicePostSaveCallbackForNewSlice(SliceTransaction::TransactionPtr transaction, const char* fullPath, const SliceTransaction::SliceAssetPtr& transactionAsset) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::SlicePostSaveCallbackForNewSlice"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::SlicePostSaveCallbackForNewSlice"); const char* undoMessage = "Create Slice Asset"; ScopedUndoBatch undoBatch(undoMessage); @@ -1568,7 +1568,7 @@ namespace AzToolsFramework bool CheckSliceAdditionCyclicDependencySafe(const AZ::SliceComponent::SliceInstanceAddress& instanceToAdd, const AZ::SliceComponent::SliceInstanceAddress& targetInstanceToAddTo) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(instanceToAdd.IsValid(), "Invalid instanceToAdd passed to CheckSliceADditionCyclicDependencySafe."); @@ -1706,7 +1706,7 @@ namespace AzToolsFramework void PopulateSliceSubMenus(QMenu& outerMenu, const AzToolsFramework::EntityIdList& inputEntities, SliceSelectedCallback sliceSelectedCallback, SliceSelectedCallback sliceRelationshipViewCallback) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // The find slice menu only works with a single entity selected. if (inputEntities.size() != 1) { @@ -2244,7 +2244,7 @@ namespace AzToolsFramework //========================================================================= bool DoEntitiesHaveOverrides(const AzToolsFramework::EntityIdList& inputEntities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::SerializeContext* serializeContext = nullptr; AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); @@ -2287,7 +2287,7 @@ namespace AzToolsFramework //========================================================================= bool IsReparentNonTrivial(const AZ::EntityId& entityId, const AZ::EntityId& newParentId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::EntityId oldParentId; AZ::TransformBus::EventResult(oldParentId, entityId, &AZ::TransformBus::Events::GetParentId); @@ -2358,7 +2358,7 @@ namespace AzToolsFramework void ReparentNonTrivialSliceInstanceHierarchy(const AZ::EntityId& entityId, const AZ::EntityId& newParentId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::SliceComponent::SliceInstanceEntityIdRemapList subslicesToDetach; AzToolsFramework::EntityIdList entitiesToDetach; @@ -2892,7 +2892,7 @@ namespace AzToolsFramework //========================================================================= void GenerateSuggestedSliceFilenameFromEntities(const AzToolsFramework::EntityIdList& entities, AZStd::string& outName) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // Determine suggested save name for slice based on entity names // For example, with entities Entity0, Entity1, and Entity2, we would end up with @@ -2962,7 +2962,7 @@ namespace AzToolsFramework //========================================================================= void GenerateSuggestedSlicePath(const AZStd::string& sliceName, const AZStd::string& targetDirectory, AZStd::string& suggestedFullPath) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // Generate full suggested path from sliceName - if given NewSlice as sliceName, // NewSlice_001.slice would be tried, and if that already existed we would suggest @@ -3079,7 +3079,7 @@ namespace AzToolsFramework QWidget* activeWindow, bool defaultGenerateSharedRoot) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::SerializeContext* serializeContext = nullptr; AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); @@ -3105,7 +3105,7 @@ namespace AzToolsFramework { int response; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SliceUtilities::CheckAndAddSliceRoot:SingleRootUserQuery"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SliceUtilities::CheckAndAddSliceRoot:SingleRootUserQuery"); response = QMessageBox::warning(activeWindow, QStringLiteral("Cannot Create Slice"), QString("The slice cannot be created because no single transform root is defined. " diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorLayerComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorLayerComponent.cpp index 6b897efdf8..cca0071a4d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorLayerComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorLayerComponent.cpp @@ -345,7 +345,7 @@ namespace AzToolsFramework EntityList& entityList, AZ::SliceComponent::SliceReferenceToInstancePtrs& layerInstances) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EditorLayer layer; LayerResult layerPrepareResult = PrepareLayerForSaving(layer, entityList, layerInstances); if (!layerPrepareResult.IsSuccess()) @@ -373,7 +373,7 @@ namespace AzToolsFramework AZ::SliceComponent::SliceAssetToSliceInstancePtrs& sliceInstances, AZStd::unordered_map& uniqueEntities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // If this layer is being loaded, it won't have a level save dependency yet, so clear that flag. m_mustSaveLevelWhenLayerSaves = false; QString fullPathName = levelPakFile; @@ -518,7 +518,7 @@ namespace AzToolsFramework EntityList& entityList, AZ::SliceComponent::SliceReferenceToInstancePtrs& layerInstances) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // Move the editable data into the data serialized to the layer, and not the layer component. layer.m_layerProperties = m_editableLayerProperties; layer.m_layerEntityId = GetEntityId(); @@ -640,7 +640,7 @@ namespace AzToolsFramework const EditorLayer& layer, AZ::IO::ByteContainerStream >& entitySaveStream) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_otherLayersToSave.clear(); m_mustSaveLevelWhenLayerSaves = false; @@ -662,7 +662,7 @@ namespace AzToolsFramework QString levelAbsoluteFolder, const AZ::IO::ByteContainerStream >& entitySaveStream) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::string layerBaseFileName(m_layerFileName); // Write to a temp file first. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorSelectionAccentSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorSelectionAccentSystemComponent.cpp index ff9eb025d7..56b0177e94 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorSelectionAccentSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorSelectionAccentSystemComponent.cpp @@ -68,7 +68,7 @@ namespace AzToolsFramework AZStd::function accentRefreshCallback = [this]() { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EditorSelectionAccentSystemComponent::QueueAccentRefresh:AccentRefreshCallback"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EditorSelectionAccentSystemComponent::QueueAccentRefresh:AccentRefreshCallback"); InvalidateAccents(); RecalculateAndApplyAccents(); m_isAccentRefreshQueued = false; @@ -79,14 +79,14 @@ namespace AzToolsFramework void EditorSelectionAccentSystemComponent::ForceSelectionAccentRefresh() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); InvalidateAccents(); RecalculateAndApplyAccents(); } void EditorSelectionAccentSystemComponent::InvalidateAccents() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (const AZ::EntityId& accentedEntity : m_currentlyAccentedEntities) { AzToolsFramework::ComponentEntityEditorRequestBus::Event(accentedEntity, &AzToolsFramework::ComponentEntityEditorRequests::SetSandboxObjectAccent, ComponentEntityAccentType::None); @@ -96,7 +96,7 @@ namespace AzToolsFramework void EditorSelectionAccentSystemComponent::RecalculateAndApplyAccents() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AzToolsFramework::EntityIdList selectedEntities; AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(selectedEntities, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); AzToolsFramework::EntityIdSet selectedEntitiesSet; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/ComponentPalette/ComponentPaletteUtil.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/ComponentPalette/ComponentPaletteUtil.cpp index 3ccb4065bf..6f3727bdb4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/ComponentPalette/ComponentPaletteUtil.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/ComponentPalette/ComponentPaletteUtil.cpp @@ -121,7 +121,7 @@ namespace AzToolsFramework ComponentDataTable &componentDataTable, ComponentIconTable &componentIconTable) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); serializeContext->EnumerateDerived( [&](const AZ::SerializeContext::ClassData* componentClass, const AZ::Uuid& knownType) -> bool { @@ -179,7 +179,7 @@ namespace AzToolsFramework const AZStd::vector& incompatibleServiceFilter ) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); bool containsEditable = false; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/ComponentPalette/ComponentPaletteWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/ComponentPalette/ComponentPaletteWidget.cpp index afa7edc565..3218bd402b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/ComponentPalette/ComponentPaletteWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/ComponentPalette/ComponentPaletteWidget.cpp @@ -130,7 +130,7 @@ namespace AzToolsFramework void ComponentPaletteWidget::UpdateContent() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_componentModel->clear(); bool applyRegExFilter = !m_searchRegExp.isEmpty(); @@ -204,12 +204,11 @@ namespace AzToolsFramework } } - for (const auto& categoryPair : componentDataTable) + for (const auto& [categoryName, componentMap] : componentDataTable) { - auto categoryItemItr = categoryItemMap.find(categoryPair.first + "/"); + auto categoryItemItr = categoryItemMap.find(categoryName + "/"); auto parentItem = categoryItemItr != categoryItemMap.end() ? categoryItemItr->second : m_componentModel->invisibleRootItem(); - const auto& componentMap = categoryPair.second; for (const auto& componentPair : componentMap) { auto componentClass = componentPair.second; @@ -217,7 +216,8 @@ namespace AzToolsFramework const QString& componentIconName = componentIconTable[componentClass]; auto deprecatedInfo = deprecatedList.find(componentClass->m_typeId); bool componentIsDeprecated = deprecatedInfo != deprecatedList.end(); - if ((!applyRegExFilter || componentName.contains(m_searchRegExp)) && (!componentIsDeprecated || !deprecatedInfo->second.m_hideComponent)) + if ((!applyRegExFilter || categoryName.contains(m_searchRegExp) || componentName.contains(m_searchRegExp)) + && (!componentIsDeprecated || !deprecatedInfo->second.m_hideComponent)) { //count the number of components on selected entities that match this type auto componentCount = AZStd::count_if(allComponentsOnSelectedEntities.begin(), allComponentsOnSelectedEntities.end(), [componentClass](const AZ::Component* component) { @@ -321,7 +321,7 @@ namespace AzToolsFramework void ComponentPaletteWidget::UpdateSearch() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_searchRegExp = QRegExp(m_searchText->text(), Qt::CaseInsensitive, QRegExp::RegExp); m_searchText->setFocus(); UpdateContent(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp index 4115fe409e..380d6876da 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp @@ -936,7 +936,7 @@ namespace AzToolsFramework bool EntityOutlinerListModel::CanReparentEntities(const AZ::EntityId& newParentId, const EntityIdList &selectedEntityIds) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (selectedEntityIds.empty()) { return false; @@ -1025,7 +1025,7 @@ namespace AzToolsFramework bool EntityOutlinerListModel::ReparentEntities(const AZ::EntityId& newParentId, const EntityIdList &selectedEntityIds, const AZ::EntityId& beforeEntityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!CanReparentEntities(newParentId, selectedEntityIds)) { return false; @@ -1105,7 +1105,7 @@ namespace AzToolsFramework QMimeData* EntityOutlinerListModel::mimeData(const QModelIndexList& indexes) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::TypeId uuid1 = AZ::AzTypeInfo::Uuid(); AZ::TypeId uuid2 = AZ::AzTypeInfo::Uuid(); @@ -1195,7 +1195,7 @@ namespace AzToolsFramework void EntityOutlinerListModel::ProcessEntityUpdates() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); m_entityChangeQueued = false; if (m_layoutResetQueued) { @@ -1203,7 +1203,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Editor, "EntityOutlinerListModel::ProcessEntityUpdates:ExpandQueue"); + AZ_PROFILE_SCOPE(Editor, "EntityOutlinerListModel::ProcessEntityUpdates:ExpandQueue"); for (auto entityId : m_entityExpandQueue) { emit ExpandEntity(entityId, IsExpanded(entityId)); @@ -1212,7 +1212,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Editor, "EntityOutlinerListModel::ProcessEntityUpdates:SelectQueue"); + AZ_PROFILE_SCOPE(Editor, "EntityOutlinerListModel::ProcessEntityUpdates:SelectQueue"); for (auto entityId : m_entitySelectQueue) { emit SelectEntity(entityId, IsSelected(entityId)); @@ -1222,7 +1222,7 @@ namespace AzToolsFramework if (!m_entityChangeQueue.empty()) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Editor, "EntityOutlinerListModel::ProcessEntityUpdates:ChangeQueue"); + AZ_PROFILE_SCOPE(Editor, "EntityOutlinerListModel::ProcessEntityUpdates:ChangeQueue"); // its faster to just do a bulk data change than to carefully pick out indices // so we'll just merge all ranges into a single range rather than try to make gaps @@ -1255,7 +1255,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Editor, "EntityOutlinerListModel::ProcessEntityUpdates:LayoutChanged"); + AZ_PROFILE_SCOPE(Editor, "EntityOutlinerListModel::ProcessEntityUpdates:LayoutChanged"); if (m_entityLayoutQueued) { emit layoutAboutToBeChanged(); @@ -1265,7 +1265,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Editor, "EntityOutlinerListModel::ProcessEntityUpdates:InvalidateFilter"); + AZ_PROFILE_SCOPE(Editor, "EntityOutlinerListModel::ProcessEntityUpdates:InvalidateFilter"); if (m_isFilterDirty) { InvalidateFilter(); @@ -1288,7 +1288,7 @@ namespace AzToolsFramework void EntityOutlinerListModel::ProcessEntityInfoResetEnd() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_layoutResetQueued = false; m_entityChangeQueued = false; m_entityChangeQueue.clear(); @@ -1309,7 +1309,7 @@ namespace AzToolsFramework void EntityOutlinerListModel::OnEntityInfoUpdatedAddChildEnd(AZ::EntityId parentId, AZ::EntityId childId) { (void)parentId; - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); endInsertRows(); //expand ancestors if a new descendant is already selected @@ -1347,7 +1347,7 @@ namespace AzToolsFramework void EntityOutlinerListModel::OnEntityInfoUpdatedRemoveChildEnd(AZ::EntityId parentId, AZ::EntityId childId) { (void)childId; - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); endResetModel(); @@ -1366,7 +1366,7 @@ namespace AzToolsFramework void EntityOutlinerListModel::OnEntityInfoUpdatedOrderEnd(AZ::EntityId parentId, AZ::EntityId childId, AZ::u64 index) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); (void)index; m_entityLayoutQueued = true; QueueEntityUpdate(parentId); @@ -1425,7 +1425,7 @@ namespace AzToolsFramework QModelIndex EntityOutlinerListModel::GetIndexFromEntity(const AZ::EntityId& entityId, int column) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (entityId.IsValid()) { @@ -1587,7 +1587,7 @@ namespace AzToolsFramework void EntityOutlinerListModel::ExpandAncestors(const AZ::EntityId& entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //typically to reveal selected entities, expand all parent entities if (entityId.IsValid()) { @@ -1792,7 +1792,7 @@ namespace AzToolsFramework bool EntityOutlinerListModel::AreAllDescendantsSameLockState(const AZ::EntityId& entityId) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //TODO result can be cached in mutable map and cleared when any descendant changes to avoid recursion in deep hierarchies bool isLocked = false; EditorEntityInfoRequestBus::EventResult(isLocked, entityId, &EditorEntityInfoRequestBus::Events::IsJustThisEntityLocked); @@ -1813,7 +1813,7 @@ namespace AzToolsFramework bool EntityOutlinerListModel::AreAllDescendantsSameVisibleState(const AZ::EntityId& entityId) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); //TODO result can be cached in mutable map and cleared when any descendant changes to avoid recursion in deep hierarchies bool isVisible = IsEntitySetToBeVisible(entityId); @@ -2180,7 +2180,7 @@ namespace AzToolsFramework QPainterPath path; auto newRect = option.rect; - newRect.setHeight(newRect.height() - 1.0); + newRect.setHeight(newRect.height() - 1); path.addRect(newRect); // Get the foreground color of the current object to draw our sub-object-selected box diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp index c6d3c2f28f..4db235d073 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp @@ -98,7 +98,7 @@ namespace void SortEntityChildren(AZ::EntityId entityId, const EntityIdCompareFunc& comparer, AzToolsFramework::EntityOrderArray* newEntityOrder = nullptr) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AzToolsFramework::EntityOrderArray entityOrderArray = AzToolsFramework::GetEntityChildOrder(entityId); AZStd::sort(entityOrderArray.begin(), entityOrderArray.end(), comparer); @@ -112,7 +112,7 @@ namespace void SortEntityChildrenRecursively(AZ::EntityId entityId, const EntityIdCompareFunc& comparer) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AzToolsFramework::EntityOrderArray entityOrderArray; SortEntityChildren(entityId, comparer, &entityOrderArray); @@ -325,7 +325,7 @@ namespace AzToolsFramework return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EntityIdList newlySelected; ExtractEntityIdsFromSelection(selected, newlySelected); @@ -472,7 +472,7 @@ namespace AzToolsFramework { if (m_selectionChangeQueued) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_selectionChangeInProgress = true; @@ -480,7 +480,7 @@ namespace AzToolsFramework { // Calling Deselect for a large number of items is very slow, // use a single ClearAndSelect call instead. - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EntityOutlinerWidget::ModelEntitySelectionChanged:ClearAndSelect"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EntityOutlinerWidget::ModelEntitySelectionChanged:ClearAndSelect"); EntityIdList selectedEntities; ToolsApplicationRequests::Bus::BroadcastResult(selectedEntities, &ToolsApplicationRequests::Bus::Events::GetSelectedEntities); @@ -491,12 +491,12 @@ namespace AzToolsFramework else { { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EntityOutlinerWidget::ModelEntitySelectionChanged:Deselect"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EntityOutlinerWidget::ModelEntitySelectionChanged:Deselect"); m_gui->m_objectTree->selectionModel()->select( BuildSelectionFromEntities(m_entitiesToDeselect), QItemSelectionModel::Deselect); } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EntityOutlinerWidget::ModelEntitySelectionChanged:Select"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EntityOutlinerWidget::ModelEntitySelectionChanged:Select"); m_gui->m_objectTree->selectionModel()->select( BuildSelectionFromEntities(m_entitiesToSelect), QItemSelectionModel::Select); } @@ -519,7 +519,7 @@ namespace AzToolsFramework template QItemSelection EntityOutlinerWidget::BuildSelectionFromEntities(const EntityIdCollection& entityIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); QItemSelection selection; for (const auto& entityId : entityIds) @@ -539,7 +539,7 @@ namespace AzToolsFramework void EntityOutlinerWidget::OnOpenTreeContextMenu(const QPoint& pos) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); bool isDocumentOpen = false; EBUS_EVENT_RESULT(isDocumentOpen, EditorRequests::Bus, IsLevelDocumentOpen); @@ -1057,7 +1057,7 @@ namespace AzToolsFramework void EntityOutlinerWidget::OnSearchTextChanged(const QString& activeTextFilter) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::string filterString = activeTextFilter.toUtf8().data(); m_listModel->SearchStringChanged(filterString); @@ -1168,7 +1168,7 @@ namespace AzToolsFramework void EntityOutlinerWidget::SortContent() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_sortContentQueued = false; @@ -1204,7 +1204,7 @@ namespace AzToolsFramework if (sortMode != EntityOutliner::DisplaySortMode::Manually) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto comparer = AZStd::bind(&CompareEntitiesForSorting, AZStd::placeholders::_1, AZStd::placeholders::_2, sortMode); SortEntityChildrenRecursively(AZ::EntityId(), comparer); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp index eb9cf2b65f..c17b96411e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabIntegrationManager.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -363,12 +364,25 @@ namespace AzToolsFramework if (hasUserSelectedValidSourceFile) { - // Get position (center of viewport). If no viewport is available, (0,0,0) will be used. - AZ::Vector3 viewportCenterPosition = AZ::Vector3::CreateZero(); - EditorRequestBus::BroadcastResult(viewportCenterPosition, &EditorRequestBus::Events::GetWorldPositionAtViewportCenter); + AZ::EntityId parentId; + AZ::Vector3 position = AZ::Vector3::CreateZero(); + + EntityIdList selectedEntities; + ToolsApplicationRequestBus::BroadcastResult(selectedEntities, &ToolsApplicationRequests::GetSelectedEntities); + // if one entity is selected, instantiate prefab as its child and place it at same position as parent + if (selectedEntities.size() == 1) + { + parentId = selectedEntities.front(); + AZ::TransformBus::EventResult(position, parentId, &AZ::TransformInterface::GetWorldTranslation); + } + // otherwise instantiate it at root level and center of viewport + else + { + EditorRequestBus::BroadcastResult(position, &EditorRequestBus::Events::GetWorldPositionAtViewportCenter); + } // Instantiating from context menu always puts the instance at the root level - auto createPrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(prefabFilePath, AZ::EntityId(), viewportCenterPosition); + auto createPrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(prefabFilePath, parentId, position); if (!createPrefabOutcome.IsSuccess()) { @@ -420,7 +434,7 @@ namespace AzToolsFramework void PrefabIntegrationManager::GenerateSuggestedFilenameFromEntities(const EntityIdList& entityIds, AZStd::string& outName) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::string suggestedName; @@ -501,7 +515,7 @@ namespace AzToolsFramework while (true) { { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); saveAs = QFileDialog::getSaveFileName(nullptr, QString("Save As..."), saveAsInitialSuggestedFullPath.c_str(), QString("Prefabs (*.prefab)")); } @@ -837,7 +851,7 @@ namespace AzToolsFramework void PrefabIntegrationManager::GatherAllReferencedEntities(EntityIdSet& entitiesWithReferences, AZ::SerializeContext& serializeContext) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::vector floodQueue; floodQueue.reserve(entitiesWithReferences.size()); @@ -929,7 +943,7 @@ namespace AzToolsFramework bool PrefabIntegrationManager::QueryAndPruneMissingExternalReferences(EntityIdSet& entities, EntityIdSet& selectedAndReferencedEntities, bool& useReferencedEntities, bool defaultMoveExternalRefs) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); useReferencedEntities = false; AZStd::string includedEntities; @@ -964,7 +978,7 @@ namespace AzToolsFramework { if (!defaultMoveExternalRefs) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZStd::string message = AZStd::string::format( "Entity references may not be valid if the entity IDs change or if the entities do not exist when the prefab is instantiated.\r\n\r\nSelected Entities\n%s\nReferenced Entities\n%s\n", diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ComponentEditor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ComponentEditor.cpp index 5fa8e9adbe..fbbf55d0ad 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ComponentEditor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ComponentEditor.cpp @@ -527,7 +527,7 @@ namespace AzToolsFramework void ComponentEditor::SetComponentOverridden(const bool overridden) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto entityId = m_components[0]->GetEntityId(); AZ::SliceComponent::SliceInstanceAddress sliceInstanceAddress; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp index 2c46bb2d26..223a573c55 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp @@ -254,8 +254,8 @@ namespace AzToolsFramework QRect globalRect = m_editor->GetWidgetAndVisibleChildrenGlobalRect(dragRowWidget); int top = mapFromGlobal(globalRect.topLeft()).y(); - int imageHeight = dragImage.height() / dragImage.devicePixelRatioF(); - int imageWidth = dragImage.width() / dragImage.devicePixelRatioF(); + int imageHeight = static_cast(dragImage.height() / dragImage.devicePixelRatioF()); + int imageWidth = static_cast(dragImage.width() / dragImage.devicePixelRatioF()); QRect currRect = QRect(QPoint(LeftMargin + 1, top), QPoint(LeftMargin + 1 + imageWidth, top + imageHeight)); painter.setOpacity(alpha); @@ -699,7 +699,7 @@ namespace AzToolsFramework void EntityPropertyEditor::BeforeEntitySelectionChanged() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (IsLockedToSpecificEntities()) { return; @@ -723,7 +723,7 @@ namespace AzToolsFramework const AzToolsFramework::EntityIdList& newlySelectedEntities, const AzToolsFramework::EntityIdList& newlyDeselectedEntities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (IsLockedToSpecificEntities()) { // ensure we refresh all entity property editors when @@ -951,7 +951,7 @@ namespace AzToolsFramework EntityPropertyEditor::SelectionEntityTypeInfo EntityPropertyEditor::GetSelectionEntityTypeInfo(const EntityIdList& selection) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); SelectionEntityTypeInfo result = SelectionEntityTypeInfo::None; InspectorLayout layout = GetCurrentInspectorLayout(); @@ -1069,7 +1069,7 @@ namespace AzToolsFramework void EntityPropertyEditor::UpdateContents() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); setUpdatesEnabled(false); m_isBuildingProperties = true; @@ -1921,7 +1921,7 @@ namespace AzToolsFramework void EntityPropertyEditor::QueuePropertyRefresh() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!m_isAlreadyQueuedRefresh) { m_isAlreadyQueuedRefresh = true; @@ -3234,7 +3234,7 @@ namespace AzToolsFramework void EntityPropertyEditor::UpdateActions() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_disabled) { @@ -3282,7 +3282,7 @@ namespace AzToolsFramework // Even though this causes two loops on the selected entity list, calling GetSelectionEntityTypeInfo avoids duplicating code. SelectionEntityTypeInfo selectionTypeInfo; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "EntityPropertyEditor::UpdateActions GetSelectionEntityTypeInfo"); + AZ_PROFILE_SCOPE(AzToolsFramework, "EntityPropertyEditor::UpdateActions GetSelectionEntityTypeInfo"); selectionTypeInfo = GetSelectionEntityTypeInfo(m_selectedEntityIds); } m_actionToAddComponents->setEnabled(CanAddComponentsToSelection(selectionTypeInfo)); @@ -3907,7 +3907,7 @@ namespace AzToolsFramework void EntityPropertyEditor::ClearComponentEditorDragging() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (auto componentEditor : m_componentEditors) { componentEditor->SetDragged(false); @@ -3918,7 +3918,7 @@ namespace AzToolsFramework void EntityPropertyEditor::ClearComponentEditorSelection() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (auto componentEditor : m_componentEditors) { componentEditor->SetSelected(false); @@ -4043,7 +4043,7 @@ namespace AzToolsFramework void EntityPropertyEditor::UpdateSelectionCache() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_selectedComponentEditors.clear(); m_selectedComponentEditors.reserve(m_componentEditors.size()); for (auto componentEditor : m_componentEditors) @@ -4070,7 +4070,7 @@ namespace AzToolsFramework void EntityPropertyEditor::SaveComponentEditorState() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // SaveComponentEditorState can be called when adding or removing a // component, the components list stored by the component editor @@ -5584,14 +5584,14 @@ namespace AzToolsFramework void EntityPropertyEditor::ConnectToEntityBuses(const AZ::EntityId& entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AzToolsFramework::EditorInspectorComponentNotificationBus::MultiHandler::BusConnect(entityId); AzToolsFramework::PropertyEditorEntityChangeNotificationBus::MultiHandler::BusConnect(entityId); } void EntityPropertyEditor::DisconnectFromEntityBuses(const AZ::EntityId& entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AzToolsFramework::EditorInspectorComponentNotificationBus::MultiHandler::BusDisconnect(entityId); AzToolsFramework::PropertyEditorEntityChangeNotificationBus::MultiHandler::BusDisconnect(entityId); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp index 2e697a7398..fccabbf205 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp @@ -603,7 +603,7 @@ namespace AzToolsFramework //----------------------------------------------------------------------------- void InstanceDataHierarchy::Build(AZ::SerializeContext* sc, unsigned int accessFlags, DynamicEditDataProvider dynamicEditDataProvider, ComponentEditor* editorParent) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(sc, "sc can't be NULL!"); AZ_Assert(m_rootInstances.size() > 0, "No root instances have been added to this hierarchy!"); @@ -761,7 +761,7 @@ namespace AzToolsFramework //----------------------------------------------------------------------------- void InstanceDataHierarchy::FixupEditData(InstanceDataNode* node, int siblingIdx) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); bool mergeElementEditData = node->m_classElement && node->m_classElement->m_editData && node->GetElementEditMetadata() != node->m_classElement->m_editData; bool mergeContainerEditData = node->m_parent && node->m_parent->m_classData->m_container && node->m_parent->GetElementEditMetadata() && (node->m_classElement->m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER) == 0; @@ -915,7 +915,7 @@ namespace AzToolsFramework //----------------------------------------------------------------------------- bool InstanceDataHierarchy::BeginNode(void* ptr, const AZ::SerializeContext::ClassData* classData, const AZ::SerializeContext::ClassElement* classElement, DynamicEditDataProvider dynamicEditDataProvider) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::Edit::ElementData* elementEditData = nullptr; @@ -1140,7 +1140,7 @@ namespace AzToolsFramework //----------------------------------------------------------------------------- bool InstanceDataHierarchy::EndNode() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ_Assert(m_curParentNode, "EndEnum called without a matching BeginNode call!"); @@ -1177,7 +1177,7 @@ namespace AzToolsFramework //----------------------------------------------------------------------------- bool InstanceDataHierarchy::RefreshComparisonData(unsigned int accessFlags, DynamicEditDataProvider dynamicEditDataProvider) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!m_root || m_comparisonInstances.empty()) { @@ -1438,7 +1438,7 @@ namespace AzToolsFramework RemovedNodeCB removedNodeCallback, ChangedNodeCB changedNodeCallback) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); targetNode->m_comparisonNode = sourceNode; @@ -1582,7 +1582,7 @@ namespace AzToolsFramework ContainerChildNodeBeingCreatedCB containerChildNodeBeingCreatedCB, const InstanceDataNode::Address& filterElementAddress) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!context) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h index 3c72e8bc9c..415a87f984 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h @@ -161,7 +161,7 @@ namespace AzToolsFramework virtual void ReadValuesIntoGUI_Internal(QWidget* widget, InstanceDataNode* node) override { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (size_t i = 0; i < node->GetNumInstances(); ++i) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals.h index 15506c1a50..8b53121776 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals.h @@ -15,6 +15,7 @@ // A user is expected to derive from PropertyHandler // and implement that interface, then register it with the property manager. +#include #include #include #include @@ -257,7 +258,7 @@ namespace AzToolsFramework virtual void ReadValuesIntoGUI_Internal(QWidget* widget, InstanceDataNode* node) override { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); WidgetType* wid = static_cast(widget); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorApi.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorApi.cpp index 8693ca2d48..096fb6c7c1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorApi.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorApi.cpp @@ -98,7 +98,7 @@ namespace AzToolsFramework //----------------------------------------------------------------------------- NodeDisplayVisibility CalculateNodeDisplayVisibility(const InstanceDataNode& node, bool isSlicePushUI) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); NodeDisplayVisibility visibility = NodeDisplayVisibility::NotVisible; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp index 604c6141d7..9ba998b99a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp @@ -458,7 +458,7 @@ namespace AzToolsFramework void PropertyRowWidget::OnValuesUpdated() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_sourceNode) { @@ -1867,7 +1867,7 @@ namespace AzToolsFramework } const auto dpr = devicePixelRatioF(); - QPixmap dragImage(width * dpr, height * dpr); + QPixmap dragImage(static_cast(width * dpr), static_cast(height * dpr)); dragImage.setDevicePixelRatio(dpr); dragImage.fill(Qt::transparent); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp index 5d5b00e83d..87df1eff1b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp @@ -1038,12 +1038,12 @@ namespace AzToolsFramework void ReflectedPropertyEditor::InvalidateValues() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_releasePrompt = true; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "ReflectedPropertyEditor::InvalidateValues:InstancesRefreshDataCompare"); + AZ_PROFILE_SCOPE(AzToolsFramework, "ReflectedPropertyEditor::InvalidateValues:InstancesRefreshDataCompare"); for (InstanceDataHierarchy& instance : m_impl->m_instances) { const bool dataIdentical = instance.RefreshComparisonData( @@ -1057,7 +1057,7 @@ namespace AzToolsFramework } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "ReflectedPropertyEditor::InvalidateValues:RowWidgetGuiUpdate"); + AZ_PROFILE_SCOPE(AzToolsFramework, "ReflectedPropertyEditor::InvalidateValues:RowWidgetGuiUpdate"); for (auto it = m_impl->m_userWidgetsToData.begin(); it != m_impl->m_userWidgetsToData.end(); ++it) { auto rowWidget = m_impl->m_widgets.find(it->second); @@ -2294,7 +2294,7 @@ namespace AzToolsFramework void ReflectedPropertyEditor::DoRefresh() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_impl->m_preventRefresh || (m_impl->m_queuedRefreshLevel == Refresh_None)) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp index b2c378181e..ff13bce531 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/EditorContextMenu.cpp @@ -23,7 +23,7 @@ namespace AzToolsFramework { void EditorContextMenuUpdate(EditorContextMenu& contextMenu, const ViewportInteraction::MouseInteractionEvent& mouseInteraction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // could potentially show the context menu if (mouseInteraction.m_mouseInteraction.m_mouseButtons.Right() && diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorBoxSelect.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorBoxSelect.cpp index d4d53c5907..c39b2c0ebc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorBoxSelect.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorBoxSelect.cpp @@ -22,7 +22,7 @@ namespace AzToolsFramework void EditorBoxSelect::HandleMouseInteraction( const ViewportInteraction::MouseInteractionEvent& mouseInteraction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_cursorState.SetCurrentPosition(mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates); @@ -74,7 +74,7 @@ namespace AzToolsFramework void EditorBoxSelect::Display2d(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_cursorState.Update(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.cpp index 0eae7707bc..d7dd008c9e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorDefaultSelection.cpp @@ -188,7 +188,7 @@ namespace AzToolsFramework return false; } - using namespace AzToolsFramework::ViewportInteraction; + using AzToolsFramework::ViewportInteraction::MouseEvent; const auto& mouseInteraction = mouseInteractionEvent.m_mouseInteraction; // store the current interaction for use in DrawManipulators m_currentInteraction = mouseInteraction; @@ -196,28 +196,19 @@ namespace AzToolsFramework switch (mouseInteractionEvent.m_mouseEvent) { case MouseEvent::Down: - { - return m_manipulatorManager->ConsumeViewportMousePress(mouseInteraction); - } + return m_manipulatorManager->ConsumeViewportMousePress(mouseInteraction); case MouseEvent::DoubleClick: - { - return false; - } + return false; case MouseEvent::Move: { - AzToolsFramework::ManipulatorManager::ConsumeMouseMoveResult mouseMoveResult = - AzToolsFramework::ManipulatorManager::ConsumeMouseMoveResult::None; - mouseMoveResult = m_manipulatorManager->ConsumeViewportMouseMove(mouseInteraction); + const AzToolsFramework::ManipulatorManager::ConsumeMouseMoveResult mouseMoveResult = + m_manipulatorManager->ConsumeViewportMouseMove(mouseInteraction); return mouseMoveResult == AzToolsFramework::ManipulatorManager::ConsumeMouseMoveResult::Interacting; } case MouseEvent::Up: - { - return m_manipulatorManager->ConsumeViewportMouseRelease(mouseInteraction); - } + return m_manipulatorManager->ConsumeViewportMouseRelease(mouseInteraction); case MouseEvent::Wheel: - { - return m_manipulatorManager->ConsumeViewportMouseWheel(mouseInteraction); - } + return m_manipulatorManager->ConsumeViewportMouseWheel(mouseInteraction); default: return false; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp index 304a4df31f..7abff230e3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp @@ -64,7 +64,7 @@ namespace AzToolsFramework // note: this is mostly likely distance from the camera static float GetIconScale(const float distSq) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return s_iconMinScale + (s_iconMaxScale - s_iconMinScale) * @@ -74,7 +74,7 @@ namespace AzToolsFramework static void DisplayComponents( const AZ::EntityId entityId, const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::Entity* entity = AZ::Interface::Get()->FindEntity(entityId); AzFramework::EntityDebugDisplayEventBus::Event( @@ -114,7 +114,7 @@ namespace AzToolsFramework AZ::EntityId EditorHelpers::HandleMouseInteraction( const AzFramework::CameraState& cameraState, const ViewportInteraction::MouseInteractionEvent& mouseInteraction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const int viewportId = mouseInteraction.m_mouseInteraction.m_interactionId.m_viewportId; @@ -185,7 +185,7 @@ namespace AzToolsFramework AzFramework::DebugDisplayRequests& debugDisplay, const AZStd::function& showIconCheck) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (HelpersVisible()) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.cpp index 696cf6b184..7002436d13 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorInteractionSystemComponent.cpp @@ -85,7 +85,7 @@ namespace AzToolsFramework void EditorInteractionSystemComponent::DisplayViewport( const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // calculate which entities are in the view and can be interacted with // and cache that data to make iterating/looking it up much faster diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.cpp index 7cd0170989..ea1bc73056 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorPickEntitySelection.cpp @@ -37,7 +37,7 @@ namespace AzToolsFramework static void HandleAccents( const AZ::EntityId entityIdUnderCursor, AZ::EntityId& hoveredEntityId, const ViewportInteraction::MouseButtons mouseButtons) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const bool invalidMouseButtonHeld = mouseButtons.Middle() || mouseButtons.Right(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp index 8e08dc9d97..7cb0e718a8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp @@ -50,7 +50,7 @@ namespace AzToolsFramework AzFramework::ScreenPoint GetScreenPosition(const int viewportId, const AZ::Vector3& worldTranslation) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto screenPosition = AzFramework::ScreenPoint(0, 0); ViewportInteraction::ViewportInteractionRequestBus::EventResult( @@ -62,7 +62,7 @@ namespace AzToolsFramework bool AabbIntersectMouseRay(const ViewportInteraction::MouseInteraction& mouseInteraction, const AZ::Aabb& aabb) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::Vector3 rayScaledDir = mouseInteraction.m_mousePick.m_rayDirection * s_pickRayLength; @@ -78,7 +78,7 @@ namespace AzToolsFramework float& closestDistance, const int viewportId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); bool entityPicked = false; EditorComponentSelectionRequestsBus::EnumerateHandlersId( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index b05dfd0676..d315243697 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -276,7 +276,7 @@ namespace AzToolsFramework static void DestroyManipulators(EntityIdManipulators& manipulators) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (manipulators.m_manipulators) { @@ -306,7 +306,7 @@ namespace AzToolsFramework { static_assert(AZStd::is_same::value, "Container type is not an EntityId"); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return AZStd::vector(entityIdContainer.begin(), entityIdContainer.end()); } @@ -316,7 +316,7 @@ namespace AzToolsFramework { static_assert(AZStd::is_same::value, "Container key type is not an EntityId"); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::vector entityIds; entityIds.reserve(entityIdMap.size()); @@ -348,7 +348,7 @@ namespace AzToolsFramework EntitySelectFuncType selectFunc2, Compare outgoingCheck) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (boxSelect->contains(ViewportInteraction::QPointFromScreenPoint(screenPosition))) { @@ -385,7 +385,7 @@ namespace AzToolsFramework const ViewportInteraction::KeyboardModifiers currentKeyboardModifiers, const ViewportInteraction::KeyboardModifiers& previousKeyboardModifiers) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (boxSelect) { @@ -449,7 +449,7 @@ namespace AzToolsFramework static void InitializeTranslationLookup(EntityIdManipulators& entityIdManipulators) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (auto& entityIdLookup : entityIdManipulators.m_lookups) { @@ -498,7 +498,7 @@ namespace AzToolsFramework // return either center or entity pivot static AZ::Vector3 CalculatePivotTranslation(const AZ::EntityId entityId, const EditorTransformComponentSelectionRequests::Pivot pivot) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); @@ -539,7 +539,7 @@ namespace AzToolsFramework { PivotOrientationResult CalculatePivotOrientation(const AZ::EntityId entityId, const ReferenceFrame referenceFrame) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // initialize to world space, no parent PivotOrientationResult result{ AZ::Quaternion::CreateIdentity(), AZ::EntityId() }; @@ -577,7 +577,7 @@ namespace AzToolsFramework template static ETCS::PivotOrientationResult CalculateParentSpace(EntityIdMapIterator begin, EntityIdMapIterator end) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // initialize to world with no parent ETCS::PivotOrientationResult result{ AZ::Quaternion::CreateIdentity(), AZ::EntityId() }; @@ -629,7 +629,7 @@ namespace AzToolsFramework { static_assert(AZStd::is_same::value, "Container key type is not an EntityId"); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!entityIdMap.empty()) { @@ -656,7 +656,7 @@ namespace AzToolsFramework { static_assert(AZStd::is_same::value, "Container key type is not an EntityId"); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // simple case with one entity if (entityIdMap.size() == 1) @@ -689,7 +689,7 @@ namespace AzToolsFramework AZStd::is_same::value, "Container value type is not an EntityIdManipulators::Lookup"); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // start - calculate orientation without considering current overrides/modifications PivotOrientationResult pivot = CalculatePivotOrientationForEntityIds(entityIdMap, referenceFrame); @@ -747,7 +747,7 @@ namespace AzToolsFramework const OptionalFrame& pivotOverrideFrame, const EditorTransformComponentSelectionRequests::Pivot pivot) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return pivotOverrideFrame.m_translationOverride.value_or(CalculatePivotTranslationForEntityIds(entityIdMap, pivot)); } @@ -756,7 +756,7 @@ namespace AzToolsFramework static AZ::Quaternion RecalculateAverageManipulatorOrientation( const EntityIdMap& entityIdMap, const OptionalFrame& pivotOverrideFrame, const ReferenceFrame referenceFrame) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return ETCS::CalculateSelectionPivotOrientation(entityIdMap, pivotOverrideFrame, referenceFrame).m_worldOrientation; } @@ -768,7 +768,7 @@ namespace AzToolsFramework const EditorTransformComponentSelectionRequests::Pivot pivot, const ReferenceFrame referenceFrame) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // return final transform, if we have an override for translation use that, otherwise // use centered translation of selection @@ -825,7 +825,7 @@ namespace AzToolsFramework bool& transformChangedInternally, const AZStd::optional spaceLock) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); entityIdManipulators.m_manipulators->SetLocalPosition(action.LocalPosition()); @@ -914,7 +914,7 @@ namespace AzToolsFramework const ViewportInteraction::MouseButtons mouseButtons, const bool usingBoxSelect) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const bool invalidMouseButtonHeld = mouseButtons.Middle() || mouseButtons.Right(); @@ -942,7 +942,7 @@ namespace AzToolsFramework static AZ::Vector3 PickTerrainPosition(const ViewportInteraction::MouseInteraction& mouseInteraction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const int viewportId = mouseInteraction.m_interactionId.m_viewportId; // get unsnapped terrain position (world space) @@ -964,14 +964,14 @@ namespace AzToolsFramework template static bool IsEntitySelectedInternal(AZ::EntityId entityId, const EntityIdContainer& selectedEntityIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto entityIdIt = selectedEntityIds.find(entityId); return entityIdIt != selectedEntityIds.end(); } static EntityIdTransformMap RecordTransformsBefore(const EntityIdList& entityIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // save initial transforms - this is necessary in cases where entities exist // in a hierarchy. We want to make sure a parent transform does not affect @@ -1202,7 +1202,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::BeginRecordManipulatorCommand() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // we must have an existing parent undo batch active when beginning to record // a manipulator command @@ -1219,7 +1219,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::EndRecordManipulatorCommand() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_manipulatorMoveCommand) { @@ -1245,7 +1245,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::CreateTranslationManipulators() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::unique_ptr translationManipulators = AZStd::make_unique( TranslationManipulators::Dimensions::Three, AZ::Transform::CreateIdentity(), AZ::Vector3::CreateOne()); @@ -1372,7 +1372,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::CreateRotationManipulators() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::unique_ptr rotationManipulators = AZStd::make_unique(AZ::Transform::CreateIdentity()); @@ -1542,7 +1542,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::CreateScaleManipulators() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::unique_ptr scaleManipulators = AZStd::make_unique(AZ::Transform::CreateIdentity()); @@ -1680,7 +1680,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::DeselectEntities() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!UndoRedoOperationInProgress()) { @@ -1708,7 +1708,7 @@ namespace AzToolsFramework bool EditorTransformComponentSelection::SelectDeselect(const AZ::EntityId entityIdUnderCursor) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (entityIdUnderCursor.IsValid()) { @@ -1760,7 +1760,7 @@ namespace AzToolsFramework bool EditorTransformComponentSelection::HandleMouseInteraction(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); CheckDirtyEntityIds(); @@ -2024,7 +2024,7 @@ namespace AzToolsFramework const QString& statusTip, const T& callback) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); actions.emplace_back(AZStd::make_unique(nullptr)); @@ -2080,11 +2080,11 @@ namespace AzToolsFramework void EditorTransformComponentSelection::RegisterActions() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto lockUnlock = [this](const bool lock) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch(s_lockSelectionUndoRedoDesc); @@ -2122,7 +2122,7 @@ namespace AzToolsFramework const auto showHide = [this](const bool show) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch(s_hideSelectionUndoRedoDesc); @@ -2163,7 +2163,7 @@ namespace AzToolsFramework m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_L) }, UnlockAll, s_unlockAllTitle, s_unlockAllDesc, []() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch(s_unlockAllUndoRedoDesc); @@ -2180,7 +2180,7 @@ namespace AzToolsFramework m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_H) }, ShowAll, s_showAllTitle, s_showAllDesc, []() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch(s_showAllEntitiesUndoRedoDesc); @@ -2197,7 +2197,7 @@ namespace AzToolsFramework m_actions, { QKeySequence(Qt::CTRL + Qt::Key_A) }, SelectAll, s_selectAllTitle, s_selectAllDesc, [this]() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch(s_selectAllEntitiesUndoRedoDesc); @@ -2237,7 +2237,7 @@ namespace AzToolsFramework m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_I) }, InvertSelect, s_invertSelectionTitle, s_invertSelectionDesc, [this]() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch(s_invertSelectionUndoRedoDesc); @@ -2284,7 +2284,7 @@ namespace AzToolsFramework m_actions, { QKeySequence(Qt::CTRL + Qt::Key_D) }, DuplicateSelect, s_duplicateTitle, s_duplicateDesc, []() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // Clear Widget selection - Prevents issues caused by cloning entities while a property in the Reflected Property Editor // is being edited. @@ -2309,7 +2309,7 @@ namespace AzToolsFramework m_actions, { QKeySequence(Qt::Key_Delete) }, DeleteSelect, s_deleteTitle, s_deleteDesc, [this]() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch(s_deleteUndoRedoDesc); @@ -2419,7 +2419,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::UnregisterManipulator() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_entityIdManipulators.m_manipulators && m_entityIdManipulators.m_manipulators->Registered()) { @@ -2429,7 +2429,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::RegisterManipulator() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_entityIdManipulators.m_manipulators && !m_entityIdManipulators.m_manipulators->Registered()) { @@ -2439,7 +2439,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::CreateEntityIdManipulators() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_selectedEntityIds.empty()) { @@ -2469,7 +2469,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::RegenerateManipulators() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // note: create/destroy pattern to be addressed DestroyManipulators(m_entityIdManipulators); @@ -2636,7 +2636,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::SnapSelectedEntitiesToWorldGrid(const float gridSize) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZStd::array snapAxes = { AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY(), AZ::Vector3::CreateAxisZ() }; @@ -2658,7 +2658,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::SetTransformMode(const Mode mode) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (mode == m_mode) { @@ -2725,7 +2725,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::AddEntityToSelection(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_selectedEntityIds.insert(entityId); AZ::TransformNotificationBus::MultiHandler::BusConnect(entityId); @@ -2733,7 +2733,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::RemoveEntityFromSelection(const AZ::EntityId entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_selectedEntityIds.erase(entityId); AZ::TransformNotificationBus::MultiHandler::BusDisconnect(entityId); @@ -2746,7 +2746,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::SetSelectedEntities(const EntityIdList& entityIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // we are responsible for updating the current selection m_didSetSelectedEntities = true; @@ -2755,7 +2755,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::RefreshManipulators(const RefreshType refreshType) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_entityIdManipulators.m_manipulators) { @@ -2793,7 +2793,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::OverrideManipulatorOrientation(const AZ::Quaternion& orientation) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_pivotOverrideFrame.m_orientationOverride = orientation; @@ -2808,7 +2808,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::OverrideManipulatorTranslation(const AZ::Vector3& translation) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_pivotOverrideFrame.m_translationOverride = translation; @@ -2821,7 +2821,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::ClearManipulatorTranslationOverride() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_entityIdManipulators.m_manipulators) { @@ -2847,7 +2847,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::ClearManipulatorOrientationOverride() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_entityIdManipulators.m_manipulators) { @@ -2875,7 +2875,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::ToggleCenterPivotSelection() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_pivotMode = TogglePivotMode(m_pivotMode); RefreshManipulators(RefreshType::Translation); } @@ -2883,7 +2883,7 @@ namespace AzToolsFramework template static bool ShouldUpdateEntityTransform(const AZ::EntityId entityId, const EntityIdMap& entityIdMap) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); static_assert(AZStd::is_same::value, "Container key type is not an EntityId"); @@ -2907,7 +2907,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::CopyTranslationToSelectedEntitiesGroup(const AZ::Vector3& translation) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_mode != Mode::Translation) { @@ -2963,7 +2963,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::CopyTranslationToSelectedEntitiesIndividual(const AZ::Vector3& translation) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_mode != Mode::Translation) { @@ -3008,7 +3008,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::CopyScaleToSelectedEntitiesIndividualWorld(float scale) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch(s_dittoScaleIndividualWorldUndoRedoDesc); @@ -3042,7 +3042,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::CopyScaleToSelectedEntitiesIndividualLocal(float scale) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch(s_dittoScaleIndividualLocalUndoRedoDesc); @@ -3061,7 +3061,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::CopyOrientationToSelectedEntitiesIndividual(const AZ::Quaternion& orientation) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_entityIdManipulators.m_manipulators) { @@ -3099,7 +3099,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::CopyOrientationToSelectedEntitiesGroup(const AZ::Quaternion& orientation) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_entityIdManipulators.m_manipulators) { @@ -3147,7 +3147,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::ResetOrientationForSelectedEntitiesLocal() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); ScopedUndoBatch undoBatch(s_resetOrientationToParentUndoRedoDesc); for (const auto& entityIdLookup : m_entityIdManipulators.m_lookups) @@ -3166,7 +3166,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::ResetTranslationForSelectedEntitiesLocal() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (m_entityIdManipulators.m_manipulators) { @@ -3236,7 +3236,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::AfterEntitySelectionChanged( [[maybe_unused]] const EntityIdList& newlySelectedEntities, [[maybe_unused]] const EntityIdList& newlyDeselectedEntities) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // EditorTransformComponentSelection was not responsible for the change in selection if (!m_didSetSelectedEntities) @@ -3265,7 +3265,7 @@ namespace AzToolsFramework const float axisLength, const AzFramework::CameraState& cameraState) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const int prevState = display.GetState(); @@ -3318,7 +3318,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::DisplayViewportSelection( const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); CheckDirtyEntityIds(); @@ -3536,7 +3536,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::DisplayViewportSelection2d( const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); DrawAxisGizmo(viewportInfo, debugDisplay); @@ -3545,7 +3545,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::RefreshSelectedEntityIds() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // check what the 'authoritative' selected entity ids are after an undo/redo EntityIdList selectedEntityIds; @@ -3556,7 +3556,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::RefreshSelectedEntityIds(const EntityIdList& selectedEntityIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::TransformNotificationBus::MultiHandler::BusDisconnect(); for (const AZ::EntityId& entityId : selectedEntityIds) @@ -3573,7 +3573,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::OnTransformChanged( [[maybe_unused]] const AZ::Transform& localTM, [[maybe_unused]] const AZ::Transform& worldTM) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!m_transformChangedInternally) { @@ -3583,7 +3583,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::OnViewportViewEntityChanged(const AZ::EntityId& newViewId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // if a viewport view entity has been set (e.g. we have set EditorCameraComponent to // match the editor camera translation/orientation), record the entity id if we have diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp index f371805997..c65f494b72 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.cpp @@ -157,7 +157,7 @@ namespace AzToolsFramework void EditorVisibleEntityDataCache::CalculateVisibleEntityDatas(const AzFramework::ViewportInfo& viewportInfo) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // request list of visible entities from authoritative system EntityIdList nextVisibleEntityIds; @@ -288,7 +288,7 @@ namespace AzToolsFramework void EditorVisibleEntityDataCache::OnEntityVisibilityChanged(const bool visibility) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::EntityId entityId = *EditorEntityVisibilityNotificationBus::GetCurrentBusId(); @@ -300,7 +300,7 @@ namespace AzToolsFramework void EditorVisibleEntityDataCache::OnEntityLockChanged(const bool locked) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::EntityId entityId = *EditorEntityLockComponentNotificationBus::GetCurrentBusId(); @@ -312,7 +312,7 @@ namespace AzToolsFramework void EditorVisibleEntityDataCache::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::EntityId entityId = *AZ::TransformNotificationBus::GetCurrentBusId(); @@ -324,7 +324,7 @@ namespace AzToolsFramework void EditorVisibleEntityDataCache::OnAccentTypeChanged(const EntityAccentType accent) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::EntityId entityId = *EditorComponentSelectionNotificationsBus::GetCurrentBusId(); @@ -336,7 +336,7 @@ namespace AzToolsFramework void EditorVisibleEntityDataCache::OnSelected() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::EntityId entityId = *EntitySelectionEvents::Bus::GetCurrentBusId(); @@ -348,7 +348,7 @@ namespace AzToolsFramework void EditorVisibleEntityDataCache::OnDeselected() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::EntityId entityId = *EntitySelectionEvents::Bus::GetCurrentBusId(); @@ -360,7 +360,7 @@ namespace AzToolsFramework void EditorVisibleEntityDataCache::OnEntityIconChanged(const AZ::Data::AssetId& /*entityIconAssetId*/) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::EntityId entityId = *EditorEntityIconComponentNotificationBus::GetCurrentBusId(); diff --git a/Code/Framework/AzToolsFramework/CMakeLists.txt b/Code/Framework/AzToolsFramework/CMakeLists.txt index 4ee329bd93..e444ce5efb 100644 --- a/Code/Framework/AzToolsFramework/CMakeLists.txt +++ b/Code/Framework/AzToolsFramework/CMakeLists.txt @@ -20,7 +20,6 @@ ly_add_target( AzToolsFramework/aztoolsframework_files.cmake AzToolsFramework/aztoolsframework_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake Platform/${PAL_PLATFORM_NAME}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - Platform/Common/${PAL_TRAIT_COMPILER_ID}/aztoolsframework_${PAL_TRAIT_COMPILER_ID_LOWERCASE}.cmake INCLUDE_DIRECTORIES PUBLIC . diff --git a/Code/Framework/AzToolsFramework/Platform/Common/Clang/aztoolsframework_clang.cmake b/Code/Framework/AzToolsFramework/Platform/Common/Clang/aztoolsframework_clang.cmake deleted file mode 100644 index 7a325ca97e..0000000000 --- a/Code/Framework/AzToolsFramework/Platform/Common/Clang/aztoolsframework_clang.cmake +++ /dev/null @@ -1,7 +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 -# -# diff --git a/Code/Framework/AzToolsFramework/Platform/Common/MSVC/aztoolsframework_msvc.cmake b/Code/Framework/AzToolsFramework/Platform/Common/MSVC/aztoolsframework_msvc.cmake deleted file mode 100644 index 1a34f54a63..0000000000 --- a/Code/Framework/AzToolsFramework/Platform/Common/MSVC/aztoolsframework_msvc.cmake +++ /dev/null @@ -1,13 +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 -# -# - -ly_add_source_properties( - SOURCES AzToolsFramework/Application/ToolsApplication.cpp - PROPERTY COMPILE_OPTIONS - VALUES -bigobj -) diff --git a/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp b/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp index 895c91b0a4..e95f7aa271 100644 --- a/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp @@ -583,7 +583,7 @@ namespace UnitTest AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::EventResult( m_mouseInteractionResult, AzToolsFramework::GetEntityContextId(), &AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleAllMouseInteractions, - vi::MouseInteractionEvent(mouseInteraction, ev->angleDelta().y())); + vi::MouseInteractionEvent(mouseInteraction, static_cast(ev->angleDelta().y()))); } MouseInteractionResult m_mouseInteractionResult; diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp index 12efea1cc8..64c4058a47 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp @@ -16,7 +16,7 @@ namespace Benchmark BENCHMARK_DEFINE_F(BM_PrefabCreate, CreatePrefabs_SingleEntityEach)(::benchmark::State& state) { - const unsigned int numEntities = state.range(); + const unsigned int numEntities = static_cast(state.range()); const unsigned int numInstances = numEntities; CreateFakePaths(numInstances); @@ -58,7 +58,7 @@ namespace Benchmark BENCHMARK_DEFINE_F(BM_PrefabCreate, CreatePrefab_FromEntities)(::benchmark::State& state) { - const unsigned int numEntities = state.range(); + const unsigned int numEntities = static_cast(state.range()); for (auto _ : state) { @@ -93,7 +93,7 @@ namespace Benchmark BENCHMARK_DEFINE_F(BM_PrefabCreate, CreatePrefab_FromSingleDepthInstances)(::benchmark::State& state) { - const unsigned int numInstancesToAdd = state.range(); + const unsigned int numInstancesToAdd = static_cast(state.range()); const unsigned int numEntities = numInstancesToAdd; // Create fake paths for all the nested instances @@ -144,7 +144,7 @@ namespace Benchmark BENCHMARK_DEFINE_F(BM_PrefabCreate, CreatePrefab_FromLinearNestingOfInstances)(::benchmark::State& state) { - const unsigned int numInstances = state.range(); + const unsigned int numInstances = static_cast(state.range()); // Create fake paths for all the nested instances // plus the root instance diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp index 90ff30a30e..f2f3cf82b0 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp @@ -16,7 +16,7 @@ namespace Benchmark BENCHMARK_DEFINE_F(BM_PrefabInstantiate, InstantiatePrefab_SingleEntityInstance)(::benchmark::State& state) { - const unsigned int numInstances = state.range(); + const unsigned int numInstances = static_cast(state.range()); AZStd::unique_ptr firstInstance = m_prefabSystemComponent->CreatePrefab( { CreateEntity("Entity1") }, diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp index a6c1e27caf..dd29654416 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp @@ -16,7 +16,7 @@ namespace Benchmark BENCHMARK_DEFINE_F(BM_PrefabLoad, LoadPrefab_Basic)(::benchmark::State& state) { - const unsigned int numTemplates = state.range(); + const unsigned int numTemplates = static_cast(state.range()); CreateFakePaths(numTemplates); for (auto _ : state) diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabUpdateInstancesBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabUpdateInstancesBenchmarks.cpp index f1e319b28a..0d95049e76 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabUpdateInstancesBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabUpdateInstancesBenchmarks.cpp @@ -18,7 +18,7 @@ namespace Benchmark BENCHMARK_DEFINE_F(BM_PrefabUpdateInstances, UpdateInstances_SingeEntityInstances)(::benchmark::State& state) { - const unsigned int numInstances = state.range(); + const unsigned int numInstances = static_cast(state.range()); CreateFakePaths(2); const auto& nestedTemplatePath = m_paths.front(); @@ -80,7 +80,7 @@ namespace Benchmark BENCHMARK_DEFINE_F(BM_PrefabUpdateInstances, UpdateInstances_SingleLinearNestingOfInstances)(::benchmark::State& state) { - const unsigned int maxDepth = state.range(); + const unsigned int maxDepth = static_cast(state.range()); CreateFakePaths(maxDepth); const unsigned int numInstances = maxDepth; @@ -131,8 +131,8 @@ namespace Benchmark BENCHMARK_DEFINE_F(BM_PrefabUpdateInstances, UpdateInstances_MultipleLinearNestingOfInstances)(::benchmark::State& state) { - const unsigned int numRootInstances = state.range(); - const unsigned int maxDepth = state.range(); + const unsigned int numRootInstances = static_cast(state.range()); + const unsigned int maxDepth = static_cast(state.range()); CreateFakePaths(maxDepth); const unsigned int numInstances = numRootInstances * maxDepth; @@ -192,7 +192,7 @@ namespace Benchmark BENCHMARK_DEFINE_F(BM_PrefabUpdateInstances, UpdateInstances_BinaryTreeNestedInstanceHierarchy)(::benchmark::State& state) { - const unsigned int maxDepth = state.range(); + const unsigned int maxDepth = static_cast(state.range()); CreateFakePaths(maxDepth); const unsigned int numInstances = (1 << maxDepth) - 1; diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp index 54e53a6ebc..d9024114a5 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp @@ -18,7 +18,7 @@ namespace Benchmark BENCHMARK_DEFINE_F(BM_SpawnableCreate, CreateSpawnable_SingleEntityInstance)(::benchmark::State& state) { - const unsigned int numSpawnables = state.range(); + const unsigned int numSpawnables = static_cast(state.range()); AZStd::unique_ptr instance(m_prefabSystemComponent->CreatePrefab( { CreateEntity("Entity1") }, diff --git a/Code/Framework/CMakeLists.txt b/Code/Framework/CMakeLists.txt index 61f65de5a4..8cc02fd4e8 100644 --- a/Code/Framework/CMakeLists.txt +++ b/Code/Framework/CMakeLists.txt @@ -15,6 +15,5 @@ add_subdirectory(AzTest) add_subdirectory(AzToolsFramework) add_subdirectory(AzManipulatorTestFramework) add_subdirectory(AzNetworking) -add_subdirectory(Crcfix) add_subdirectory(GFxFramework) add_subdirectory(GridMate) diff --git a/Code/Framework/Crcfix/CMakeLists.txt b/Code/Framework/Crcfix/CMakeLists.txt deleted file mode 100644 index 4fdad1e338..0000000000 --- a/Code/Framework/Crcfix/CMakeLists.txt +++ /dev/null @@ -1,32 +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 -# -# - -if (NOT PAL_TRAIT_BUILD_HOST_TOOLS) - return() -endif() - -include(Platform/${PAL_PLATFORM_NAME}/PAL_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) -if (NOT PAL_TRAIT_BUILD_CRCFIX) - return() -endif() - -ly_add_target( - NAME Crcfix EXECUTABLE - NAMESPACE AZ - FILES_CMAKE - crcfix_files.cmake - BUILD_DEPENDENCIES - PRIVATE - AZ::AzCore -) - -ly_add_source_properties( - SOURCES crcfix.cpp - PROPERTY COMPILE_DEFINITIONS - VALUES _CRT_SECURE_NO_WARNINGS -) diff --git a/Code/Framework/Crcfix/Platform/Linux/PAL_linux.cmake b/Code/Framework/Crcfix/Platform/Linux/PAL_linux.cmake deleted file mode 100644 index a63f2bed45..0000000000 --- a/Code/Framework/Crcfix/Platform/Linux/PAL_linux.cmake +++ /dev/null @@ -1,9 +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 -# -# - -set(PAL_TRAIT_BUILD_CRCFIX FALSE) diff --git a/Code/Framework/Crcfix/Platform/Mac/PAL_mac.cmake b/Code/Framework/Crcfix/Platform/Mac/PAL_mac.cmake deleted file mode 100644 index a63f2bed45..0000000000 --- a/Code/Framework/Crcfix/Platform/Mac/PAL_mac.cmake +++ /dev/null @@ -1,9 +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 -# -# - -set(PAL_TRAIT_BUILD_CRCFIX FALSE) diff --git a/Code/Framework/Crcfix/Platform/Windows/PAL_windows.cmake b/Code/Framework/Crcfix/Platform/Windows/PAL_windows.cmake deleted file mode 100644 index 8a8884139d..0000000000 --- a/Code/Framework/Crcfix/Platform/Windows/PAL_windows.cmake +++ /dev/null @@ -1,9 +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 -# -# - -set(PAL_TRAIT_BUILD_CRCFIX TRUE) diff --git a/Code/Framework/Crcfix/crcfix.cpp b/Code/Framework/Crcfix/crcfix.cpp deleted file mode 100644 index 778b9e2185..0000000000 --- a/Code/Framework/Crcfix/crcfix.cpp +++ /dev/null @@ -1,538 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -int g_totalFixTimeMs = 0; -int g_longestFixTimeMs = 0; - -class Filename -{ - wchar_t fullpath[MAX_PATH]; - wchar_t drive[_MAX_DRIVE]; - wchar_t dir[_MAX_DIR]; - wchar_t fname[_MAX_FNAME]; - wchar_t ext[_MAX_EXT]; - -public: - Filename() - { - fullpath[0] = drive[0] = dir[0] = fname[0] = ext[0] = 0; - } - - Filename(const AZStd::wstring& filename) - { - _wsplitpath(filename.c_str(), drive, dir, fname, ext); - wcscpy(fullpath, filename.c_str()); - } - - void SetExt(const wchar_t* pExt) { wcscpy(ext, pExt); _wmakepath(fullpath, drive, dir, fname, pExt); } - const wchar_t* GetFullPath() const { return fullpath; } - bool Exists() const { return _waccess(fullpath, 0) == 0; } - bool IsReadOnly() const { return _waccess(fullpath, 6) == -1; } - bool SetReadOnly() const { return _wchmod(fullpath, _S_IREAD) == 0; } - bool SetWritable() const { return _wchmod(fullpath, _S_IREAD | _S_IWRITE) == 0; } - bool Delete() const { return _wremove(fullpath) == 0; } - bool Rename(const wchar_t* fn2) const{ return MoveFileEx(fullpath, fn2, MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING) == 0; } - bool Copy(const wchar_t* dest) const { return ::CopyFile(fullpath, dest, FALSE) == TRUE; } -}; - -class CRCfix -{ - int lastchar; - int linenum; - -public: - void SkipToEOL(FILE* infile); - char* GetToken(FILE* infile, FILE* outfile); - void GetPreviousCRC(char* token, FILE* infile); - int Fix(Filename srce); -}; - -void FixFiles(const AZStd::wstring& dir, const AZStd::wstring& files, FILETIME* pLastRun, bool verbose, int& nFound, int& nProcessed, int& nFixed, int& nFailed) -{ - CRCfix fixer; - WIN32_FIND_DATA wfd; - HANDLE hFind; - hFind = FindFirstFile((dir + files).c_str(), &wfd); - if (hFind != INVALID_HANDLE_VALUE) - { - do - { - if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) - { - if (verbose) - { - AZ_TracePrintf("CrcFix", "\tProcessing %ls ...", wfd.cFileName); - } - nFound++; - - int n = 0; - if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0 && (!pLastRun || CompareFileTime(pLastRun, &wfd.ftLastWriteTime) <= 0)) - { - n = fixer.Fix(Filename(dir + L"\\" + wfd.cFileName)); - nProcessed++; - } - if (n < 0) - { - nFailed++; - if (verbose) - { - AZ_TracePrintf("CrcFix", "Failed\n"); - } - } - else - { - if (verbose) - { - AZ_TracePrintf("CrcFix", n > 0 ? "Done\n" : (wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0 ? "ReadOnly\n" : "Unchanged\n"); - } - nFixed += n; - } - } - } while (FindNextFile(hFind, &wfd)); - } - FindClose(hFind); -} - -void FixDirectories(const AZStd::wstring& dirs, const AZStd::wstring& files, FILETIME* pLastRun, bool verbose, int& nFound, int& nProcessed, int& nFixed, int& nFailed) -{ - if (verbose) - { - AZ_TracePrintf("CrcFix", "Processing %ls ...\n", dirs.c_str()); - } - - // do files - FixFiles(dirs, files, pLastRun, verbose, nFound, nProcessed, nFixed, nFailed); - - // do folders - WIN32_FIND_DATA wfd; - HANDLE hFind; - hFind = FindFirstFile((dirs + L"\\*").c_str(), &wfd); - if (hFind != INVALID_HANDLE_VALUE) - { - do - { - if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) - { - if (wfd.cFileName[0] == '.') - { - continue; - } - FixDirectories(AZStd::wstring(dirs + L"\\" + wfd.cFileName), files, pLastRun, verbose, nFound, nProcessed, nFixed, nFailed); - } - } while (FindNextFile(hFind, &wfd)); - } - FindClose(hFind); -} - -int main(int argc, char* argv[]) -{ - AZStd::chrono::system_clock::time_point startTime = AZStd::chrono::system_clock::now(); - - AZ::SystemAllocator::Descriptor desc; - //desc.m_stackRecordLevels = 15; - AZ::AllocatorInstance::Create(desc); - //if (AZ::AllocatorInstance::Get().GetRecords()) { - // AZ::AllocatorInstance::Get().GetRecords()->SetMode(AZ::Debug::AllocationRecords::RECORD_FULL); - //} - { - if (argc < 2) - { - AZ_TracePrintf("CrcFix", "Usage:\n crcfix [-v(erbose)] [-log:logfile] {path[\\*][\\*.*]}\n"); - AZ_TracePrintf("CrcFix", "\n Ex:\n crcfix -v -log:timestamp.log src\\*\\*.cpp src\\*\\*.h ..\\scripts\\*.*\n\n"); - } - - char root[MAX_PATH]; - AZ::Utils::GetExecutableDirectory(root, MAX_PATH); - - AZStd::vector entries; - - AZStd::wstring logfilename; - FILETIME lastRun; - FILETIME* pLastRun = NULL; - - bool verbose = false; - - for (int iArg = 1; iArg < argc; ++iArg) - { - const char* pArg = argv[iArg]; - if (!pArg) - { - continue; - } - AZStd::wstring pArgW; - AZStd::to_wstring(pArgW, pArg); - if (_strnicmp(pArg, "-log:", 5) == 0) - { - logfilename.assign(pArgW.begin() + 5, pArgW.end()); - HANDLE hFile = CreateFile(logfilename.data(), 0, 0, NULL, OPEN_EXISTING, 0, NULL); - if (hFile != INVALID_HANDLE_VALUE) - { - pLastRun = &lastRun; - GetFileTime(hFile, NULL, NULL, pLastRun); - CloseHandle(hFile); - } - } - else if (_stricmp(pArg, "-v") == 0) - { - verbose = true; - } - else - { - entries.emplace_back(AZStd::move(pArgW)); - } - } - - // for each entry from the command line... - int nFound = 0; - int nProcessed = 0; - int nFixed = 0; - int nFailed = 0; - for (AZStd::vector::const_iterator iEntry = entries.begin(); iEntry != entries.end(); ++iEntry) - { - AZStd::wstring entry = (iEntry->at(0) == L'\\' || iEntry->find(L":") != iEntry->npos) ? *iEntry : AZStd::wstring(root) + L"\\" + *iEntry; - AZStd::wstring::size_type split = entry.find(L"*\\"); - bool doSubdirs = split != entry.npos; - if (doSubdirs) - { - FixDirectories(entry.substr(0, split), entry.substr(split + 1), pLastRun, verbose, nFound, nProcessed, nFixed, nFailed); - } - else - { - split = entry.rfind(L"\\"); - if (split == entry.npos) - { - split = 0; - } - FixFiles(entry.substr(0, split), entry.substr(split), pLastRun, verbose, nFound, nProcessed, nFixed, nFailed); - } - } - - // update timestamp - if (!logfilename.empty()) - { - HANDLE hFile = CreateFile(logfilename.data(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); - GetSystemTimeAsFileTime(&lastRun); - SetFileTime(hFile, NULL, NULL, &lastRun); - char log[1024]; - DWORD oCount; - - sprintf(log, "Batches processed: %zu\n\tFiles found: %d\n\tFiles processed: %d\n\tFiles fixed: %d\n\tFiles failed: %d\n", entries.size(), nFound, nProcessed, nFixed, nFailed); - WriteFile(hFile, log, static_cast(strlen(log)), &oCount, NULL); - - AZStd::chrono::system_clock::time_point endTime = AZStd::chrono::system_clock::now(); - sprintf(log, "Total running time: %.2f secs.\n\tTotal processing time: %.2f secs.\n\tLongest processing time: %.2f secs.\n", (float)AZStd::chrono::milliseconds(endTime - startTime).count() / 1000.f, (float)g_totalFixTimeMs / 1000.f, (float)g_longestFixTimeMs / 1000.f); - WriteFile(hFile, log, static_cast(strlen(log)), &oCount, NULL); - - CloseHandle(hFile); - } - } - - AZ::AllocatorInstance::Destroy(); - return 0; -} - -//----------------------------------------------------------------------------- -// CRCfix -//----------------------------------------------------------------------------- -void CRCfix::SkipToEOL(FILE* infile) -{ - int c; - for (c = lastchar; c != EOF && c != '\n'; c = fgetc(infile)) - { - ; - } - lastchar = fgetc(infile); - linenum++; -} -//----------------------------------------------------------------------------- -char* CRCfix::GetToken(FILE* infile, FILE* outfile) -{ - static char token[512]; - bool commentline = false; - bool commentblock = false; - bool doublequote = false; - bool singlequote = false; - int i = 0; - int c; - - if (lastchar == EOF) - { - return NULL; - } - - for (c = lastchar; c != EOF; c = fgetc(infile)) - { - if (!commentline && !commentblock && !doublequote && !singlequote) - { - if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '#' || c == '_') - { - token[i++] = c; - continue; - } - else - { - if (i) - { - lastchar = c; - token[i] = 0; - i = 0; - return token; - } - } - } - - if (commentline) - { - if (c == '\n') - { - commentline = false; - } - } - else if (commentblock) - { - while (c == '*') - { - c = fgetc(infile); - if (c == '/') - { - commentblock = false; - } - fputc('*', outfile); - } - } - - if (!commentline && !commentblock) - { - if (c == '"' && !singlequote) - { - doublequote = !doublequote; - } - else if (c == '\'' && !doublequote) - { - singlequote = !singlequote; - } - else if (!singlequote && !doublequote) - { - if (c == '/') - { - c = fgetc(infile); - if (c == '/') - { - commentline = true; - } - else if (c == '*') - { - commentblock = true; - } - if (c == '\'') - { - singlequote = true; - } - else if (c == '"') - { - doublequote = true; - } - fputc('/', outfile); - } - } - else if (c == '\\') - { - fputc(c, outfile); - c = fgetc(infile); - } - } - fputc(c, outfile); - if (c == '\n') - { - linenum++; - } - } - lastchar = c; - token[i] = 0; - return i ? token : NULL; -} -//----------------------------------------------------------------------------- -void CRCfix::GetPreviousCRC(char* token, FILE* infile) -{ - int c; - while ((c = fgetc(infile)) != ')') - { - *token++ = c; - } - *token = 0; -} -//----------------------------------------------------------------------------- -int CRCfix::Fix(Filename srce) -{ - AZStd::chrono::system_clock::time_point startTime = AZStd::chrono::system_clock::now(); - - bool changed = false; - Filename dest(srce); - dest.SetExt(L"xxx"); - - linenum = 0; - - FILE* infile = _wfopen(srce.GetFullPath(), L"r"); - FILE* outfile = _wfopen(dest.GetFullPath(), L"w"); - - if (!infile || !outfile) - { - if (infile) - { - fclose(infile); - infile = nullptr; - } - - if (outfile) - { - fclose(outfile); - outfile = nullptr; - } - - int dt = static_cast(AZStd::chrono::milliseconds(AZStd::chrono::system_clock::now() - startTime).count()); - g_totalFixTimeMs += dt; - if (dt > g_longestFixTimeMs) - { - g_longestFixTimeMs = dt; - } - - return -1; - } - - lastchar = fgetc(infile); - - while (char* token = GetToken(infile, outfile)) - { - bool got = false; - - if (strcmp(token, "AZ_CRC") == 0 && lastchar == '(') - { - size_t i = strlen(token); - token[i++] = lastchar; - int c = fgetc(infile); - - if (c == '"') - { - size_t j = i + 1; - - do - { - token[i++] = c; - c = fgetc(infile); - } while (c != '"'); - - token[i++] = c; - c = fgetc(infile); - - int oldcrc = 0, newcrc; - - if (c == ',') - { - GetPreviousCRC(token + i, infile); - sscanf(token + i, "%i", &oldcrc); - c = ')'; - } - - if (c == ')') - { - token[i] = 0; - c = fgetc(infile); - got = true; - newcrc = AZ::Crc32(token + j, i - j - 1, true); - fprintf(outfile, "%s, 0x%08x)", token, newcrc); - if (newcrc != oldcrc) - { - changed = true; - } - } - } - lastchar = c; - token[i] = 0; - } - if (!got) - { - fwrite(token, 1, strlen(token), outfile); - } - } - fclose(infile); - fclose(outfile); - - if (changed) - { - Filename backup(srce); - backup.SetExt(L"crcfix_old"); - - if (backup.Exists()) - { - backup.SetWritable(); - [[maybe_unused]] bool deleted = backup.Delete(); - AZ_Assert(deleted, "failed to delete"); - } - - if (!srce.Copy(backup.GetFullPath())) - { - AZ_TracePrintf("CrcFix", "Failed to copy %ls to %ls\n", srce, backup); - - int dt = static_cast(AZStd::chrono::milliseconds(AZStd::chrono::system_clock::now() - startTime).count()); - g_totalFixTimeMs += dt; - if (dt > g_longestFixTimeMs) - { - g_longestFixTimeMs = dt; - } - - return -1; - } - - if (!dest.Rename(srce.GetFullPath())) - { - AZ_TracePrintf("CrcFix", "Failed to rename %ls to %ls\n", dest, srce); - - int dt = static_cast(AZStd::chrono::milliseconds(AZStd::chrono::system_clock::now() - startTime).count()); - g_totalFixTimeMs += dt; - if (dt > g_longestFixTimeMs) - { - g_longestFixTimeMs = dt; - } - - return -1; - } - - if (!backup.Delete()) - { - AZ_TracePrintf("CrcFix", "Failed to delete %ls\n", backup); - } - } - else - { - dest.Delete(); - } - - - int dt = static_cast(AZStd::chrono::milliseconds(AZStd::chrono::system_clock::now() - startTime).count()); - g_totalFixTimeMs += dt; - if (dt > g_longestFixTimeMs) - { - g_longestFixTimeMs = dt; - } - - return changed ? 1 : 0; -} -//----------------------------------------------------------------------------- diff --git a/Code/Framework/Crcfix/crcfix_files.cmake b/Code/Framework/Crcfix/crcfix_files.cmake deleted file mode 100644 index d170013e67..0000000000 --- a/Code/Framework/Crcfix/crcfix_files.cmake +++ /dev/null @@ -1,11 +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 -# -# - -set(FILES crcfix_files.cmake - crcfix.cpp -) diff --git a/Code/Framework/GridMate/GridMate/Replica/Replica.cpp b/Code/Framework/GridMate/GridMate/Replica/Replica.cpp index 5d0949bbe8..c1de3b71f2 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Replica.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/Replica.cpp @@ -40,7 +40,7 @@ namespace GridMate , m_priority(0) , m_revision(1) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); m_upstreamHop = nullptr; m_dirtyHook.m_next = m_dirtyHook.m_prev = nullptr; @@ -86,7 +86,7 @@ namespace GridMate //----------------------------------------------------------------------------- void Replica::PreDestruct() { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); for (auto chunk : m_chunks) { @@ -137,7 +137,7 @@ namespace GridMate //----------------------------------------------------------------------------- bool Replica::AttachReplicaChunk(const ReplicaChunkPtr& chunk) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); // Check for duplicate attach if (!chunk->GetReplica()) @@ -174,7 +174,7 @@ namespace GridMate //----------------------------------------------------------------------------- bool Replica::DetachReplicaChunk(const ReplicaChunkPtr& chunk) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); if (!IsActive()) { @@ -213,7 +213,7 @@ namespace GridMate //----------------------------------------------------------------------------- void Replica::UpdateReplica(const ReplicaContext& rc) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); for (auto chunk : m_chunks) { @@ -226,7 +226,7 @@ namespace GridMate //----------------------------------------------------------------------------- void Replica::UpdateFromReplica(const ReplicaContext& rc) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); for (auto chunk : m_chunks) { @@ -239,7 +239,7 @@ namespace GridMate //----------------------------------------------------------------------------- bool Replica::AcceptChangeOwnership(PeerId requestor, const ReplicaContext& rc) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); for (auto chunk : m_chunks) { @@ -274,7 +274,7 @@ namespace GridMate //----------------------------------------------------------------------------- void Replica::OnDeactivate(const ReplicaContext& rc) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); EBUS_EVENT_ID(rc.m_rm->GetGridMate(), ReplicaMgrCallbackBus, OnDeactivateReplica, GetRepId(), rc.m_rm); EBUS_EVENT(Debug::ReplicaDrillerBus, OnDeactivateReplica, this); @@ -294,7 +294,7 @@ namespace GridMate //----------------------------------------------------------------------------- void Replica::OnChangeOwnership(const ReplicaContext& rc) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); for (auto chunk : m_chunks) { @@ -319,7 +319,7 @@ namespace GridMate { (void) rpcContext; - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); if (IsActive()) { @@ -382,7 +382,7 @@ namespace GridMate //----------------------------------------------------------------------------- void Replica::Activate(const ReplicaContext& rc) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); // Resolve whether we're migratable or not from the chunks // present when we're attached to the network. @@ -410,7 +410,7 @@ namespace GridMate //----------------------------------------------------------------------------- void Replica::Deactivate(const ReplicaContext& rc) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); if (IsActive()) { @@ -440,7 +440,7 @@ namespace GridMate //----------------------------------------------------------------------------- bool Replica::ProcessRPCs(const ReplicaContext& rc) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); bool isProcessed = true; for (auto chunk : m_chunks) @@ -508,7 +508,7 @@ namespace GridMate //----------------------------------------------------------------------------- PrepareDataResult Replica::PrepareData(EndianType endianType, AZ::u32 marshalFlags) { - //AZ_PROFILE_TIMER("GridMate"); + //AZ_PROFILE_SCOPE("GridMate"); PrepareDataResult pdr(false, false, false, false); bool dataSetChange = false; @@ -536,7 +536,7 @@ namespace GridMate //----------------------------------------------------------------------------- void Replica::Marshal(MarshalContext& mc) { - //AZ_PROFILE_TIMER("GridMate"); + //AZ_PROFILE_SCOPE("GridMate"); // We are going to replace the outBuffer with a temporary chunk buffer for each chunk, // hold on to the original so we can restore it later and write the chunk buffers into @@ -639,7 +639,7 @@ namespace GridMate //----------------------------------------------------------------------------- bool Replica::Unmarshal(UnmarshalContext& mc) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); UnmarshalContext chunkContext(mc); ReadBuffer& buffer = *mc.m_iBuf; @@ -715,7 +715,7 @@ namespace GridMate //----------------------------------------------------------------------------- ReplicaChunkPtr Replica::CreateReplicaChunkFromStream(ReplicaChunkClassId classId, UnmarshalContext& mc) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); ReplicaChunkPtr chunk = nullptr; ReplicaChunkDescriptor* pDesc = ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(classId); diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp b/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp index 07b056d3bb..ee42ff2ad0 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp @@ -152,7 +152,7 @@ namespace GridMate //----------------------------------------------------------------------------- PrepareDataResult ReplicaChunkBase::PrepareData(EndianType endianType, AZ::u32 marshalFlags) { - //AZ_PROFILE_TIMER("GridMate"); + //AZ_PROFILE_SCOPE("GridMate"); PrepareDataResult pdr(false, false, false, false); bool forceDatasetsReliable = !!(marshalFlags & ReplicaMarshalFlags::ForceReliable); @@ -250,7 +250,7 @@ namespace GridMate //----------------------------------------------------------------------------- bool ReplicaChunkBase::ShouldSendToPeer(ReplicaPeer* peer) const { - //AZ_PROFILE_TIMER("GridMate"); + //AZ_PROFILE_SCOPE("GridMate"); // Only send chunks to the same zone as the peer return !!(peer->GetZoneMask() & GetDescriptor()->GetZoneMask()); @@ -258,7 +258,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaChunkBase::Marshal(MarshalContext& mc, AZ::u32 chunkIndex) { - //AZ_PROFILE_TIMER("GridMate"); + //AZ_PROFILE_SCOPE("GridMate"); SafeGuardWrite(mc.m_outBuffer, [this, &mc, &chunkIndex]() { @@ -269,7 +269,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaChunkBase::Unmarshal(UnmarshalContext& mc, AZ::u32 chunkIndex) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); SafeGuardRead(mc.m_iBuf, [this, &mc, &chunkIndex]() { @@ -334,7 +334,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaChunkBase::MarshalDataSets(MarshalContext& mc, AZ::u32 chunkIndex) { - //AZ_PROFILE_TIMER("GridMate"); + //AZ_PROFILE_SCOPE("GridMate"); AZ::u32 dirtyDataSetMask = CalculateDirtyDataSetMask(mc); AZStd::bitset changebits(dirtyDataSetMask); ReplicaChunkDescriptor* descriptor = GetDescriptor(); @@ -382,7 +382,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaChunkBase::UnmarshalDataSets(UnmarshalContext& mc, AZ::u32 chunkIndex) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); AZStd::bitset changebits; if (!mc.m_iBuf->Read(*changebits.data(), VlqU32Marshaler())) @@ -438,7 +438,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaChunkBase::MarshalRpcs(MarshalContext& mc, AZ::u32 chunkIndex) { - //AZ_PROFILE_TIMER("GridMate"); + //AZ_PROFILE_SCOPE("GridMate"); bool isAuthoritative = (mc.m_marshalFlags & ReplicaMarshalFlags::Authoritative) == ReplicaMarshalFlags::Authoritative; bool isReliable = (mc.m_marshalFlags & ReplicaMarshalFlags::Reliable) == ReplicaMarshalFlags::Reliable; @@ -496,7 +496,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaChunkBase::UnmarshalRpcs(UnmarshalContext& mc, AZ::u32 chunkIndex) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); // Unmarshal RPCs AZ::u32 rpcCount; @@ -629,7 +629,7 @@ namespace GridMate //----------------------------------------------------------------------------- bool ReplicaChunkBase::ProcessRPCs(const ReplicaContext& rc) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); // Process incoming RPCs for (RPCQueue::iterator iRPC = m_rpcQueue.begin(); iRPC != m_rpcQueue.end(); ) @@ -733,7 +733,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaChunkBase::AttachedToReplica(Replica* replica) { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); AZ_Assert(!m_replica, "Should not be attached to a replica"); @@ -748,7 +748,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaChunkBase::DetachedFromReplica() { - AZ_PROFILE_TIMER("GridMate"); + AZ_PROFILE_FUNCTION(GridMate); AZ_Assert(m_replica, "Should be attached to a replica"); EBUS_EVENT(Debug::ReplicaDrillerBus, OnDetachReplicaChunk, this); diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp b/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp index b8eea00871..2582710aa7 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp @@ -867,7 +867,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaManager::UpdateFromReplicas() { - AZ_PROFILE_TIMER("GridMate", __FUNCTION__); + AZ_PROFILE_FUNCTION(GridMate); if (!IsInitialized()) { @@ -888,7 +888,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaManager::UpdateReplicas() { - AZ_PROFILE_TIMER("GridMate", __FUNCTION__); + AZ_PROFILE_FUNCTION(GridMate); if (!IsInitialized()) { @@ -940,7 +940,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaManager::Marshal() { - AZ_PROFILE_TIMER("GridMate", __FUNCTION__); + AZ_PROFILE_FUNCTION(GridMate); if (!IsReady()) { @@ -1287,7 +1287,7 @@ namespace GridMate //----------------------------------------------------------------------------- void ReplicaManager::Unmarshal() { - AZ_PROFILE_TIMER("GridMate", __FUNCTION__); + AZ_PROFILE_FUNCTION(GridMate); if (!IsInitialized()) { diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaUtils.h b/Code/Framework/GridMate/GridMate/Replica/ReplicaUtils.h index 6833aa9234..8de2abab6e 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaUtils.h +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaUtils.h @@ -81,7 +81,7 @@ namespace GridMate #define GM_ENABLE_PROFILE_USER_CALLBACKS 1 #if (GM_ENABLE_PROFILE_USER_CALLBACKS) -#define GM_PROFILE_USER_CALLBACK(callback) AZ_PROFILE_TIMER("GridMate User Code", callback); +#define GM_PROFILE_USER_CALLBACK(callback) AZ_PROFILE_SCOPE(GridMate, "GridMate User Code: %s", callback); #else #define GM_PROFILE_USER_CALLBACK(callback) #endif diff --git a/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp b/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp index 44426f6d01..d1e6a69e5e 100644 --- a/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp +++ b/Code/LauncherUnified/Platform/Windows/Launcher_Windows.cpp @@ -73,8 +73,8 @@ void CVar_OnViewportPosition(const AZ::Vector2& value) if (HWND windowHandle = GetActiveWindow()) { SetWindowPos(windowHandle, nullptr, - value.GetX(), - value.GetY(), + static_cast(value.GetX()), + static_cast(value.GetY()), 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE); } } diff --git a/Code/Legacy/CryCommon/CryHeaders.h b/Code/Legacy/CryCommon/CryHeaders.h index 4d037b52d9..49ea28ee0e 100644 --- a/Code/Legacy/CryCommon/CryHeaders.h +++ b/Code/Legacy/CryCommon/CryHeaders.h @@ -395,7 +395,7 @@ struct MotionParams905 MotionParams905() { m_nAssetFlags = 0; - m_nCompression = -1; + m_nCompression = std::numeric_limits::max(); m_nTicksPerFrame = 0; m_fSecsPerTick = 0; m_nStart = 0; diff --git a/Code/Legacy/CryCommon/FrameProfiler.h b/Code/Legacy/CryCommon/FrameProfiler.h index 12eb6a34a1..ac6d3a52a1 100644 --- a/Code/Legacy/CryCommon/FrameProfiler.h +++ b/Code/Legacy/CryCommon/FrameProfiler.h @@ -43,32 +43,25 @@ enum EProfiledSubsystem }; #undef X -static_assert(static_cast(PROFILE_LAST_SUBSYSTEM) == AZ::Debug::ProfileCategory::LegacyLast, "Mismatched AZ and Legacy profile categories"); #include #define FUNCTION_PROFILER_LEGACYONLY(pISystem, subsystem) -#define FUNCTION_PROFILER(pISystem, subsystem) \ - AZ_PROFILE_FUNCTION(static_cast(subsystem)); +#define FUNCTION_PROFILER(pISystem, subsystem) -#define FUNCTION_PROFILER_FAST(pISystem, subsystem, bProfileEnabled) \ - AZ_PROFILE_FUNCTION(static_cast(subsystem)); +#define FUNCTION_PROFILER_FAST(pISystem, subsystem, bProfileEnabled) -#define FUNCTION_PROFILER_ALWAYS(pISystem, subsystem) \ - AZ_PROFILE_FUNCTION(static_cast(subsystem)); +#define FUNCTION_PROFILER_ALWAYS(pISystem, subsystem) #define FRAME_PROFILER_LEGACYONLY(szProfilerName, pISystem, subsystem) -#define FRAME_PROFILER(szProfilerName, pISystem, subsystem) \ - AZ_PROFILE_SCOPE(static_cast(subsystem), szProfilerName); +#define FRAME_PROFILER(szProfilerName, pISystem, subsystem) -#define FRAME_PROFILER_FAST(szProfilerName, pISystem, subsystem, bProfileEnabled) \ - AZ_PROFILE_SCOPE(static_cast(subsystem), szProfilerName); +#define FRAME_PROFILER_FAST(szProfilerName, pISystem, subsystem, bProfileEnabled) -#define FUNCTION_PROFILER_SYS(subsystem) \ - FUNCTION_PROFILER(gEnv->pSystem, PROFILE_##subsystem) +#define FUNCTION_PROFILER_SYS(subsystem) #define STALL_PROFILER(cause) diff --git a/Code/Legacy/CryCommon/HeightmapUpdateNotificationBus.h b/Code/Legacy/CryCommon/HeightmapUpdateNotificationBus.h deleted file mode 100644 index 618131159e..0000000000 --- a/Code/Legacy/CryCommon/HeightmapUpdateNotificationBus.h +++ /dev/null @@ -1,34 +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 - * - */ - -#pragma once - -#include -#include - -namespace AZ -{ - /** - * the EBus is used to request information about potential vegetation surfaces - */ - class HeightmapUpdateNotification - : public AZ::EBusTraits - { - public: - //////////////////////////////////////////////////////////////////////// - // EBusTraits - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - //////////////////////////////////////////////////////////////////////// - - // Occurs when the terrain height map is modified. - virtual void HeightmapModified(const AZ::Aabb& bounds) = 0; - }; - - typedef AZ::EBus HeightmapUpdateNotificationBus; -} diff --git a/Code/Legacy/CryCommon/ISerialize.h b/Code/Legacy/CryCommon/ISerialize.h index d427e222bb..b153a52487 100644 --- a/Code/Legacy/CryCommon/ISerialize.h +++ b/Code/Legacy/CryCommon/ISerialize.h @@ -31,7 +31,7 @@ class InterpolatedValue_tpl; // Unfortunately this needs to be here - should be in CryNetwork somewhere. struct SNetObjectID { - static const uint16 InvalidId = ~uint16(0); + static const uint16 InvalidId = std::numeric_limits::max(); SNetObjectID() : id(InvalidId) diff --git a/Code/Legacy/CryCommon/ISplines.h b/Code/Legacy/CryCommon/ISplines.h index ad59f1328d..2353489163 100644 --- a/Code/Legacy/CryCommon/ISplines.h +++ b/Code/Legacy/CryCommon/ISplines.h @@ -466,7 +466,7 @@ namespace spline ILINE void flag_clr(int flag) { m_flags &= ~flag; }; ILINE int flag(int flag) { return m_flags & flag; }; - ILINE void ORT(int ort) { m_ORT = ort; }; + ILINE void ORT(int ort) { m_ORT = static_cast(ort); }; ILINE int ORT() const { return m_ORT; }; ILINE int isORT(int o) const { return (m_ORT == o); }; diff --git a/Code/Legacy/CryCommon/ISystem.h b/Code/Legacy/CryCommon/ISystem.h index ff72c2e60f..74153eb39b 100644 --- a/Code/Legacy/CryCommon/ISystem.h +++ b/Code/Legacy/CryCommon/ISystem.h @@ -1149,22 +1149,11 @@ struct DiskOperationInfo #endif -#if defined(ENABLE_LOADING_PROFILER) && AZ_PROFILE_TELEMETRY - -#define LOADING_TIME_PROFILE_SECTION AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore) -#define LOADING_TIME_PROFILE_SECTION_ARGS(...) AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, __VA_ARGS__) -#define LOADING_TIME_PROFILE_SECTION_NAMED(sectionName) AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, sectionName) -#define LOADING_TIME_PROFILE_SECTION_NAMED_ARGS(sectionName, ...) AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, sectionName, __VA_ARGS__) - -#else - #define LOADING_TIME_PROFILE_SECTION #define LOADING_TIME_PROFILE_SECTION_ARGS(...) #define LOADING_TIME_PROFILE_SECTION_NAMED(sectionName) #define LOADING_TIME_PROFILE_SECTION_NAMED_ARGS(sectionName, ...) -#endif - ////////////////////////////////////////////////////////////////////////// // CrySystem DLL Exports. ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Legacy/CryCommon/IXml.h b/Code/Legacy/CryCommon/IXml.h index 80c2415f9c..2434b44664 100644 --- a/Code/Legacy/CryCommon/IXml.h +++ b/Code/Legacy/CryCommon/IXml.h @@ -745,7 +745,7 @@ private: void Update() { - if (m_index >= 0 && m_index < m_parentNode->getChildCount()) + if (m_index < m_parentNode->getChildCount()) { m_currentChildNode = m_parentNode->getChild(static_cast(m_index)); } diff --git a/Code/Legacy/CryCommon/LegacyAllocator.cpp b/Code/Legacy/CryCommon/LegacyAllocator.cpp new file mode 100644 index 0000000000..8438606d17 --- /dev/null +++ b/Code/Legacy/CryCommon/LegacyAllocator.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +namespace AZ +{ + LegacyAllocator::pointer_type LegacyAllocator::Allocate(size_type byteSize, size_type alignment, int flags, const char* name, const char* fileName, int lineNum, unsigned int suppressStackRecord) + { + if (alignment == 0) + { + // Some STL containers, like std::vector, seem to have a requirement where a specific minimum alignment will be chosen when the alignment is set to 0 + // Take a look at _Allocate_manually_vector_aligned in xmemory0 + alignment = sizeof(void*) * 2; + } + + pointer_type ptr = m_schema->Allocate(byteSize, alignment, flags, name, fileName, lineNum, suppressStackRecord); + AZ_PROFILE_MEMORY_ALLOC_EX(MemoryReserved, fileName, lineNum, ptr, byteSize, name ? name : GetName()); + AZ_MEMORY_PROFILE(ProfileAllocation(ptr, byteSize, alignment, name, fileName, lineNum, suppressStackRecord)); + AZ_Assert(ptr || byteSize == 0, "OOM - Failed to allocate %zu bytes from LegacyAllocator", byteSize); + return ptr; + } + + // DeAllocate with file/line, to track when allocs were freed from Cry + void LegacyAllocator::DeAllocate(pointer_type ptr, [[maybe_unused]] const char* file, [[maybe_unused]] const int line, size_type byteSize, size_type alignment) + { + AZ_PROFILE_MEMORY_FREE_EX(MemoryReserved, file, line, ptr); + AZ_MEMORY_PROFILE(ProfileDeallocation(ptr, byteSize, alignment, nullptr)); + m_schema->DeAllocate(ptr, byteSize, alignment); + } + + // Realloc with file/line, because Cry uses realloc(nullptr) and realloc(ptr, 0) to mimic malloc/free + LegacyAllocator::pointer_type LegacyAllocator::ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment, [[maybe_unused]] const char* file, [[maybe_unused]] const int line) + { + if (newAlignment == 0) + { + // Some STL containers, like std::vector, seem to have a requirement where a specific minimum alignment will be chosen when the alignment is set to 0 + // Take a look at _Allocate_manually_vector_aligned in xmemory0 + newAlignment = sizeof(void*) * 2; + } + + AZ_MEMORY_PROFILE(ProfileReallocationBegin(ptr, newSize)); + AZ_PROFILE_MEMORY_FREE_EX(MemoryReserved, file, line, ptr); + pointer_type newPtr = m_schema->ReAllocate(ptr, newSize, newAlignment); + AZ_PROFILE_MEMORY_ALLOC_EX(MemoryReserved, file, line, newPtr, newSize, "LegacyAllocator Realloc"); + AZ_MEMORY_PROFILE(ProfileReallocationEnd(ptr, newPtr, newSize, newAlignment)); + AZ_Assert(newPtr || newSize == 0, "OOM - Failed to reallocate %zu bytes from LegacyAllocator", newSize); + return newPtr; + } + + void LegacyAllocator::DeAllocate(pointer_type ptr, size_type byteSize, size_type alignment) + { + AZ_MEMORY_PROFILE(ProfileDeallocation(ptr, 0, 0, nullptr)); + Base::DeAllocate(ptr, byteSize, alignment); + } + + LegacyAllocator::pointer_type LegacyAllocator::ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) + { + if (newAlignment == 0) + { + // Some STL containers, like std::vector, seem to have a requirement where a specific minimum alignment will be chosen when the alignment is set to 0 + // Take a look at _Allocate_manually_vector_aligned in xmemory0 + newAlignment = sizeof(void*) * 2; + } + + AZ_MEMORY_PROFILE(ProfileReallocationBegin(ptr, newSize)); + pointer_type newPtr = Base::ReAllocate(ptr, newSize, newAlignment); + AZ_MEMORY_PROFILE(ProfileReallocationEnd(ptr, newPtr, newSize, newAlignment)); + AZ_Assert(newPtr || newSize == 0, "OOM - Failed to reallocate %zu bytes from LegacyAllocator", newSize); + return newPtr; + } +} diff --git a/Code/Legacy/CryCommon/LegacyAllocator.h b/Code/Legacy/CryCommon/LegacyAllocator.h index 074c183de4..2b1055958b 100644 --- a/Code/Legacy/CryCommon/LegacyAllocator.h +++ b/Code/Legacy/CryCommon/LegacyAllocator.h @@ -11,118 +11,36 @@ #include #include -#define AZCORE_SYS_ALLOCATOR_HPPA -//#define AZCORE_SYS_ALLOCATOR_MALLOC - -#ifdef AZCORE_SYS_ALLOCATOR_HPPA -# include -#elif defined(AZCORE_SYS_ALLOCATOR_MALLOC) -# include -#else -# include -#endif - namespace AZ { - -#ifdef AZCORE_SYS_ALLOCATOR_HPPA - typedef AZ::HphaSchema LegacyAllocatorSchema; -#elif defined(AZCORE_SYS_ALLOCATOR_MALLOC) - typedef AZ::MallocSchema LegacyAllocatorSchema; -#else - typedef AZ::HeapSchema LegacyAllocatorSchema; -#endif - - struct LegacyAllocatorDescriptor - : public LegacyAllocatorSchema::Descriptor - { - LegacyAllocatorDescriptor() - { - // pull 32MB from the OS at a time -#ifdef AZCORE_SYS_ALLOCATOR_HPPA - m_systemChunkSize = 32 * 1024 * 1024; -#endif - } - }; - class LegacyAllocator - : public SimpleSchemaAllocator + : public SimpleSchemaAllocator { public: AZ_TYPE_INFO(LegacyAllocator, "{17FC25A4-92D9-48C5-BB85-7F860FCA2C6F}"); - using Descriptor = LegacyAllocatorDescriptor; - using Base = SimpleSchemaAllocator; + using Descriptor = AZ::HphaSchema::Descriptor; + using Base = SimpleSchemaAllocator; + using pointer_type = typename Base::pointer_type; + using size_type = typename Base::size_type; + using difference_type = typename Base::difference_type; LegacyAllocator() : Base("LegacyAllocator", "Allocator for Legacy CryEngine systems") { } - pointer_type Allocate(size_type byteSize, size_type alignment, int flags = 0, const char* name = 0, const char* fileName = 0, int lineNum = 0, unsigned int suppressStackRecord = 0) override - { - if (alignment == 0) - { - // Some STL containers, like std::vector, are assuming a specific minimum alignment. seems to have a requirement - // Take a look at _Allocate_manually_vector_aligned in xmemory0 - alignment = sizeof(void*) * 2; - } - - pointer_type ptr = m_schema->Allocate(byteSize, alignment, flags, name, fileName, lineNum, suppressStackRecord); - AZ_PROFILE_MEMORY_ALLOC_EX(AZ::Debug::ProfileCategory::MemoryReserved, fileName, lineNum, ptr, byteSize, name ? name : GetName()); - AZ_MEMORY_PROFILE(ProfileAllocation(ptr, byteSize, alignment, name, fileName, lineNum, suppressStackRecord)); - AZ_Assert(ptr || byteSize == 0, "OOM - Failed to allocate %zu bytes from LegacyAllocator", byteSize); - return ptr; - } + pointer_type Allocate(size_type byteSize, size_type alignment, int flags = 0, const char* name = 0, const char* fileName = 0, int lineNum = 0, unsigned int suppressStackRecord = 0) override; // DeAllocate with file/line, to track when allocs were freed from Cry - void DeAllocate(pointer_type ptr, [[maybe_unused]] const char* file, [[maybe_unused]] const int line, size_type byteSize = 0, size_type alignment = 0) - { - AZ_PROFILE_MEMORY_FREE_EX(AZ::Debug::ProfileCategory::MemoryReserved, file, line, ptr); - AZ_MEMORY_PROFILE(ProfileDeallocation(ptr, byteSize, alignment, nullptr)); - m_schema->DeAllocate(ptr, byteSize, alignment); - } + void DeAllocate(pointer_type ptr, const char* file, const int line, size_type byteSize = 0, size_type alignment = 0); // Realloc with file/line, because Cry uses realloc(nullptr) and realloc(ptr, 0) to mimic malloc/free - pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment, [[maybe_unused]] const char* file, [[maybe_unused]] const int line) - { - if (newAlignment == 0) - { - // Some STL containers, like std::vector, are assuming a specific minimum alignment. seems to have a requirement - // Take a look at _Allocate_manually_vector_aligned in xmemory0 - newAlignment = sizeof(void*) * 2; - } + pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment, const char* file, const int line); - AZ_MEMORY_PROFILE(ProfileReallocationBegin(ptr, newSize)); - AZ_PROFILE_MEMORY_FREE_EX(AZ::Debug::ProfileCategory::MemoryReserved, file, line, ptr); - pointer_type newPtr = m_schema->ReAllocate(ptr, newSize, newAlignment); - AZ_PROFILE_MEMORY_ALLOC_EX(AZ::Debug::ProfileCategory::MemoryReserved, file, line, newPtr, newSize, "LegacyAllocator Realloc"); - AZ_MEMORY_PROFILE(ProfileReallocationEnd(ptr, newPtr, newSize, newAlignment)); - AZ_Assert(newPtr || newSize == 0, "OOM - Failed to reallocate %zu bytes from LegacyAllocator", newSize); - return newPtr; - } + void DeAllocate(pointer_type ptr, size_type byteSize = 0, size_type alignment = 0) override; - void DeAllocate(pointer_type ptr, size_type byteSize = 0, size_type alignment = 0) override - { - AZ_MEMORY_PROFILE(ProfileDeallocation(ptr, 0, 0, nullptr)); - Base::DeAllocate(ptr, byteSize, alignment); - } - - pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) override - { - if (newAlignment == 0) - { - // Some STL containers, like std::vector, are assuming a specific minimum alignment. seems to have a requirement - // Take a look at _Allocate_manually_vector_aligned in xmemory0 - newAlignment = sizeof(void*) * 2; - } - - AZ_MEMORY_PROFILE(ProfileReallocationBegin(ptr, newSize)); - pointer_type newPtr = Base::ReAllocate(ptr, newSize, newAlignment); - AZ_MEMORY_PROFILE(ProfileReallocationEnd(ptr, newPtr, newSize, newAlignment)); - AZ_Assert(newPtr || newSize == 0, "OOM - Failed to reallocate %zu bytes from LegacyAllocator", newSize); - return newPtr; - } + pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) override; }; using StdLegacyAllocator = AZStdAlloc; @@ -133,57 +51,4 @@ namespace AZ class AllocatorInstance : public Internal::AllocatorInstanceBase { }; - -#if defined(AZ_PLATFORM_PROVO) || defined(AZ_PLATFORM_JASPER) - struct GlobalAllocatorDescriptor - : public AZ::HphaSchema::Descriptor - { - GlobalAllocatorDescriptor() - { - // pull 1MB from the OS at a time - m_systemChunkSize = 1024 * 1024; - } - }; - - class GlobalAllocator - : public SimpleSchemaAllocator - { - public: - AZ_TYPE_INFO(GlobalAllocator, "{BC7861DA-AF7F-4FFD-A2F5-BAD89BDD77FD}"); - - using Descriptor = GlobalAllocatorDescriptor; - using Base = SimpleSchemaAllocator; - - GlobalAllocator() - : Base("GlobalAllocator", "Allocator for untracked new/delete/malloc/free") - { - } - - //--------------------------------------------------------------------- - // IAllocatorAllocate - //--------------------------------------------------------------------- - pointer_type Allocate(size_type byteSize, size_type alignment, int flags = 0, const char* name = 0, const char* fileName = 0, int lineNum = 0, unsigned int suppressStackRecord = 0) override - { - // Note: We cannot put the asserts in the AllocateBase class because various allocators depend on allocations failing from some heap classes. - pointer_type ptr = Base::Allocate(byteSize, alignment, flags, name, fileName, lineNum, suppressStackRecord); - AZ_Assert(ptr, "OOM - Failed to allocate %zu bytes from GlobalAllocator", byteSize); - return ptr; - } - - pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) override - { - pointer_type newPtr = Base::ReAllocate(ptr, newSize, newAlignment); - AZ_Assert(newPtr, "OOM - Failed to reallocate %zu bytes from GlobalAllocator", newSize); - return newPtr; - } - - }; - - // Specialize for the GlobalAllocator to provide one per module that does not use the - // environment for its storage - template <> - class AllocatorInstance : public Internal::AllocatorInstanceBase> - { - }; -#endif } diff --git a/Code/Legacy/CryCommon/PNoise3.h b/Code/Legacy/CryCommon/PNoise3.h index 1cb7f0d65b..fe19997ef4 100644 --- a/Code/Legacy/CryCommon/PNoise3.h +++ b/Code/Legacy/CryCommon/PNoise3.h @@ -205,7 +205,7 @@ public: // Initialize the permutation table for(i = 0; i < NOISE_TABLE_SIZE; i++) - m_p[i] = i; + m_p[i] = static_cast(i); for(i = 0; i < NOISE_TABLE_SIZE; i++) { @@ -213,7 +213,7 @@ public: nSwap = m_p[i]; m_p[i] = m_p[j]; - m_p[j] = nSwap; + m_p[j] = static_cast(nSwap); } // Generate the gradient lookup tables diff --git a/Code/Legacy/CryCommon/ProjectDefines.h b/Code/Legacy/CryCommon/ProjectDefines.h index 18b4665fab..f7f73f111b 100644 --- a/Code/Legacy/CryCommon/ProjectDefines.h +++ b/Code/Legacy/CryCommon/ProjectDefines.h @@ -173,7 +173,6 @@ #if defined(ENABLE_PROFILING_CODE) #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/Vertex.h b/Code/Legacy/CryCommon/Vertex.h index 2e61524cab..b9e0b25d38 100644 --- a/Code/Legacy/CryCommon/Vertex.h +++ b/Code/Legacy/CryCommon/Vertex.h @@ -1037,7 +1037,7 @@ namespace AZ } AZ_Assert(stride < (0x1 << (sizeof(m_stride) * 8)), "Vertex stride is larger than the maximum supported, update the type for m_stride in Vertex.h"); - m_stride = stride; + m_stride = static_cast(stride); } diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake index e6e1f5c3e5..ba11de0215 100644 --- a/Code/Legacy/CryCommon/crycommon_files.cmake +++ b/Code/Legacy/CryCommon/crycommon_files.cmake @@ -53,7 +53,6 @@ set(FILES HMDBus.h VRCommon.h StereoRendererBus.h - HeightmapUpdateNotificationBus.h INavigationSystem.h IMNM.h SFunctor.h @@ -90,6 +89,7 @@ set(FILES CryVersion.h FrameProfiler.h HeapAllocator.h + LegacyAllocator.cpp LegacyAllocator.h MetaUtils.h MiniQueue.h diff --git a/Code/Legacy/CryCommon/platform_impl.cpp b/Code/Legacy/CryCommon/platform_impl.cpp index 4263d813b7..ecc196a49f 100644 --- a/Code/Legacy/CryCommon/platform_impl.cpp +++ b/Code/Legacy/CryCommon/platform_impl.cpp @@ -13,7 +13,6 @@ #include #include -#include #include #include #include @@ -94,7 +93,6 @@ extern "C" AZ_DLL_EXPORT void ModuleInitISystem(ISystem* pSystem, [[maybe_unused AZ::Environment::Attach(gEnv->pSharedEnvironment); AZ::AllocatorManager::Instance(); // Force the AllocatorManager to instantiate and register any allocators defined in data sections } - AZ::Debug::ProfileModuleInit(); } // if pSystem } @@ -203,7 +201,7 @@ void __stl_debug_message(const char* format_str, ...) ////////////////////////////////////////////////////////////////////////// void CrySleep(unsigned int dwMilliseconds) { - AZ_PROFILE_FUNCTION_IDLE(AZ::Debug::ProfileCategory::System); + AZ_PROFILE_FUNCTION(System); Sleep(dwMilliseconds); } diff --git a/Code/Legacy/CrySystem/CmdLine.cpp b/Code/Legacy/CrySystem/CmdLine.cpp index 50b8b2c092..702709ffe5 100644 --- a/Code/Legacy/CrySystem/CmdLine.cpp +++ b/Code/Legacy/CrySystem/CmdLine.cpp @@ -192,7 +192,6 @@ AZStd::string CCmdLine::Next(char*& src) return AZStd::string(org, src); } - ch = *src++; } return AZStd::string(); diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp index 68a8a6659b..db77eda3e8 100644 --- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp +++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp @@ -473,7 +473,7 @@ void CLocalizedStringsManager::ParseFirstLine(IXmlTableReader* pXmlTableReader, const char* pFind = strstr(sCellContent.c_str(), sLocalizedColumnNames[i]); if (pFind != 0) { - nCellIndexToType[nCellIndex] = i; + nCellIndexToType[nCellIndex] = static_cast(i); // find SoundMood if (i == ELOCALIZED_COLUMN_SOUNDMOOD) diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp index 872a522a69..be2816c890 100644 --- a/Code/Legacy/CrySystem/Log.cpp +++ b/Code/Legacy/CrySystem/Log.cpp @@ -1228,7 +1228,7 @@ void CLog::CreateBackupFile() const while (!fileSystem->Eof(inFileHandle)) { - uint8 c = AZ::IO::GetC(inFileHandle); + uint8 c = static_cast(AZ::IO::GetC(inFileHandle)); if (c == '\"') { diff --git a/Code/Legacy/CrySystem/System.cpp b/Code/Legacy/CrySystem/System.cpp index 3673088695..d848160b3e 100644 --- a/Code/Legacy/CrySystem/System.cpp +++ b/Code/Legacy/CrySystem/System.cpp @@ -701,7 +701,7 @@ void CSystem::SleepIfNeeded() int sleepMS = (int)(1000.0f * sleepTime + 0.5f); if (sleepMS > 0) { - AZ_PROFILE_FUNCTION_IDLE(AZ::Debug::ProfileCategory::System); + AZ_PROFILE_FUNCTION(System); Sleep(sleepMS); } diff --git a/Code/Legacy/CrySystem/SystemInit.cpp b/Code/Legacy/CrySystem/SystemInit.cpp index 08292a6353..b5a6265493 100644 --- a/Code/Legacy/CrySystem/SystemInit.cpp +++ b/Code/Legacy/CrySystem/SystemInit.cpp @@ -1626,6 +1626,9 @@ AZ_POP_DISABLE_WARNING // Send out EBus event EBUS_EVENT(CrySystemEventBus, OnCrySystemInitialized, *this, startupParams); + // Execute any deferred commands that uses the CVar commands that were just registered + AZ::Interface::Get()->ExecuteDeferredConsoleCommands(); + // Verify that the Maestro Gem initialized the movie system correctly. This can be removed if and when Maestro is not a required Gem if (gEnv->IsEditor() && !gEnv->pMovieSystem) { @@ -1641,7 +1644,7 @@ AZ_POP_DISABLE_WARNING m_bInitializedSuccessfully = true; - return (true); + return true; } diff --git a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp index 6d2d393a11..7cdb62d45a 100644 --- a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp +++ b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp @@ -334,7 +334,7 @@ void CViewSystem::SetActiveView(IView* pView) } else { - m_activeViewId = ~0; + m_activeViewId = ~0u; } m_bActiveViewFromSequence = false; diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp index 36443fb9ee..46eea1528c 100644 --- a/Code/Legacy/CrySystem/XConsole.cpp +++ b/Code/Legacy/CrySystem/XConsole.cpp @@ -2464,8 +2464,9 @@ void CXConsole::DisplayVarValue(ICVar* pVar) sValue += " ("; if (nonAlphaBits != 0) { - char nonAlphaChars[3]; // 1..63 + '\0' - sValue += azitoa(nonAlphaBits, nonAlphaChars, AZ_ARRAY_SIZE(nonAlphaChars), 10); + char nonAlphaChars[3] = { 0 }; // 1..63 + '\0' + azitoa(nonAlphaBits, nonAlphaChars, AZ_ARRAY_SIZE(nonAlphaChars), 10); + sValue += nonAlphaChars; sValue += ", "; } sValue += alphaChars; @@ -2856,7 +2857,7 @@ void CXConsole::Paste() Utf8::Unchecked::octet_iterator end(data.end()); for (Utf8::Unchecked::octet_iterator it(data.begin()); it != end; ++it) { - const wchar_t cp = *it; + const wchar_t cp = static_cast(*it); if (cp != '\r') { // Convert UCS code-point into UTF-8 string @@ -3132,6 +3133,9 @@ char* CXConsole::GetCheatVarAt(uint32 nOffset) ////////////////////////////////////////////////////////////////////////// size_t CXConsole::GetSortedVars(AZStd::vector& pszArray, const char* szPrefix) { + // This method used to insert instead of push_back, so we need to clear first + pszArray.clear(); + size_t iPrefixLen = szPrefix ? strlen(szPrefix) : 0; // variables diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp index e74b457191..841697ecdb 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp +++ b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp @@ -44,7 +44,7 @@ bool CSerializeXMLReaderImpl::Value(const char* name, int8& value) } else { - value = temp; + value = static_cast(temp); } return bResult; } diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryNode.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryNode.cpp index 257fc3ca69..d209478957 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryNode.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryNode.cpp @@ -320,7 +320,7 @@ bool CBinaryXmlNode::getAttr(const char* key, ColorB& value) const // If we only found 3 values, a should be unchanged, and still be 255 if (r < 256 && g < 256 && b < 256 && a < 256) { - value = ColorB(r, g, b, a); + value = ColorB(static_cast(r), static_cast(g), static_cast(b), static_cast(a)); return true; } } diff --git a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp index a2a35cfe8b..265953850f 100644 --- a/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp +++ b/Code/Legacy/CrySystem/XML/XMLBinaryWriter.cpp @@ -244,7 +244,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nPar nd.nContentStringOffset = nContentStringOffset; nd.nParentIndex = nParentIndex; nd.nFirstAttributeIndex = nFirstAttributeIndex; - nd.nAttributeCount = nAttributeCount; + nd.nAttributeCount = static_cast(nAttributeCount); m_nodes.push_back(nd); } @@ -271,7 +271,7 @@ bool XMLBinary::CXMLBinaryWriter::CompileTablesForNode(XmlNodeRef node, int nPar } } - m_nodes[nIndex].nChildCount = nChildCount; + m_nodes[nIndex].nChildCount = static_cast(nChildCount); return true; } diff --git a/Code/Legacy/CrySystem/XML/xml.cpp b/Code/Legacy/CrySystem/XML/xml.cpp index 7a9bb4bc36..adbfcc5f3e 100644 --- a/Code/Legacy/CrySystem/XML/xml.cpp +++ b/Code/Legacy/CrySystem/XML/xml.cpp @@ -641,7 +641,7 @@ bool CXmlNode::getAttr(const char* key, ColorB& value) const // If we only found 3 values, a should be unchanged, and still be 255 if (r < 256 && g < 256 && b < 256 && a < 256) { - value = ColorB(r, g, b, a); + value = ColorB(static_cast(r), static_cast(g), static_cast(b), static_cast(a)); return true; } } diff --git a/Code/Tools/AssetProcessor/AssetBuilder/AssetBuilderComponent.cpp b/Code/Tools/AssetProcessor/AssetBuilder/AssetBuilderComponent.cpp index 7702cc259d..eb6cc4033c 100644 --- a/Code/Tools/AssetProcessor/AssetBuilder/AssetBuilderComponent.cpp +++ b/Code/Tools/AssetProcessor/AssetBuilder/AssetBuilderComponent.cpp @@ -337,7 +337,7 @@ bool AssetBuilderComponent::ConnectToAssetProcessor() AZStd::string overridePort; if (GetParameter(s_paramPort, overridePort, false)) { - connectionSettings.m_assetProcessorPort = AZStd::stoi(overridePort); + connectionSettings.m_assetProcessorPort = static_cast(AZStd::stoi(overridePort)); } //the asset builder may have been given an optional asset platform to use diff --git a/Code/Tools/AssetProcessor/native/resourcecompiler/rcjoblistmodel.cpp b/Code/Tools/AssetProcessor/native/resourcecompiler/rcjoblistmodel.cpp index d22823b496..a64e3bf5b9 100644 --- a/Code/Tools/AssetProcessor/native/resourcecompiler/rcjoblistmodel.cpp +++ b/Code/Tools/AssetProcessor/native/resourcecompiler/rcjoblistmodel.cpp @@ -197,11 +197,11 @@ namespace AssetProcessor m_jobsInFlight.insert(rcJob); - for(size_t jobIndex = m_jobs.size() - 1; jobIndex >= 0; --jobIndex) + for(int jobIndex = static_cast(m_jobs.size()) - 1; jobIndex >= 0; --jobIndex) { if(m_jobs[jobIndex] == rcJob) { - Q_EMIT dataChanged(index(aznumeric_caster(jobIndex), 0, QModelIndex()), index(aznumeric_caster(jobIndex), 0, QModelIndex())); + Q_EMIT dataChanged(index(jobIndex, 0, QModelIndex()), index(jobIndex, 0, QModelIndex())); return; } } @@ -240,7 +240,7 @@ namespace AssetProcessor foundInQueue = m_jobsInQueueLookup.erase(foundInQueue); } - for (size_t jobIndex = m_jobs.size() - 1; jobIndex >= 0; --jobIndex) + for (int jobIndex = static_cast(m_jobs.size()) - 1; jobIndex >= 0; --jobIndex) { if(m_jobs[jobIndex] == rcJob) { @@ -251,7 +251,7 @@ namespace AssetProcessor #if defined(DEBUG_RCJOB_MODEL) AZ_TracePrintf(AssetProcessor::DebugChannel, "JobTrace =>JobCompleted(%i %s,%s,%s)\n", rcJob, rcJob->GetJobEntry().m_databaseSourceName.toUtf8().constData(), rcJob->GetPlatformInfo().m_identifier.c_str(), rcJob->GetJobKey().toUtf8().constData()); #endif - beginRemoveRows(QModelIndex(), aznumeric_caster(jobIndex), aznumeric_caster(jobIndex)); + beginRemoveRows(QModelIndex(), jobIndex, jobIndex); m_jobs.erase(m_jobs.begin() + jobIndex); endRemoveRows(); diff --git a/Code/Tools/AssetProcessor/native/tests/resourcecompiler/RCBuilderTest.cpp b/Code/Tools/AssetProcessor/native/tests/resourcecompiler/RCBuilderTest.cpp index 7a78786258..2465be2b33 100644 --- a/Code/Tools/AssetProcessor/native/tests/resourcecompiler/RCBuilderTest.cpp +++ b/Code/Tools/AssetProcessor/native/tests/resourcecompiler/RCBuilderTest.cpp @@ -814,7 +814,7 @@ public: AssetRecognizer good; good.m_name = "Good"; - good.m_version = versionNumber; + good.m_version = static_cast(versionNumber); good.m_patternMatcher = AssetBuilderSDK::FilePatternMatcher("*.foo", AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard); good.m_platformSpecs["pc"] = good_spec; good.m_productAssetType = builderProductType; diff --git a/Code/Tools/AssetProcessor/native/unittests/RCcontrollerUnitTests.cpp b/Code/Tools/AssetProcessor/native/unittests/RCcontrollerUnitTests.cpp index a3f5c117ea..0f5fea5eb9 100644 --- a/Code/Tools/AssetProcessor/native/unittests/RCcontrollerUnitTests.cpp +++ b/Code/Tools/AssetProcessor/native/unittests/RCcontrollerUnitTests.cpp @@ -147,7 +147,7 @@ void RCcontrollerUnitTests::RunRCControllerTests() if (returnedCount != expectedCount) { - Q_EMIT UnitTestFailed("RCJobListModel has " + QString(returnedCount) + " elements, which is invalid. Expected " + expectedCount); + Q_EMIT UnitTestFailed("RCJobListModel has " + QString(returnedCount) + " elements, which is invalid. Expected " + QString(expectedCount)); return; } diff --git a/Code/Tools/AssetProcessor/native/utilities/BatchApplicationServer.cpp b/Code/Tools/AssetProcessor/native/utilities/BatchApplicationServer.cpp index 8a7974c615..e7ebc030e6 100644 --- a/Code/Tools/AssetProcessor/native/utilities/BatchApplicationServer.cpp +++ b/Code/Tools/AssetProcessor/native/utilities/BatchApplicationServer.cpp @@ -38,7 +38,7 @@ bool BatchApplicationServer::startListening(unsigned short port) // Since we're starting up builders ourselves and informing them of the port chosen, we can scan for a free port - while (!listen(QHostAddress::Any, m_serverListeningPort)) + while (!listen(QHostAddress::Any, static_cast(m_serverListeningPort))) { auto error = serverError(); diff --git a/Code/Tools/AssetProcessor/native/utilities/ByteArrayStream.cpp b/Code/Tools/AssetProcessor/native/utilities/ByteArrayStream.cpp index 187c872e08..4a7128be88 100644 --- a/Code/Tools/AssetProcessor/native/utilities/ByteArrayStream.cpp +++ b/Code/Tools/AssetProcessor/native/utilities/ByteArrayStream.cpp @@ -52,7 +52,6 @@ namespace AssetProcessor SizeType finalPosition = GenericStream::ComputeSeekPosition(bytes, mode); AZ_Assert(finalPosition < INT_MAX, "Overflow of SizeType to int in ByteArrayStream."); - AZ_Assert(finalPosition >= 0, "underflow in seek in ByteArrayStream"); AZ_Assert(finalPosition <= m_activeArray->size(), "You cant seek beyond end of file"); // safety clamp! diff --git a/Code/Tools/AssetProcessor/native/utilities/PlatformConfiguration.cpp b/Code/Tools/AssetProcessor/native/utilities/PlatformConfiguration.cpp index 782e145ad6..07106614cf 100644 --- a/Code/Tools/AssetProcessor/native/utilities/PlatformConfiguration.cpp +++ b/Code/Tools/AssetProcessor/native/utilities/PlatformConfiguration.cpp @@ -197,7 +197,7 @@ namespace AssetProcessor } else if (valueName == "order") { - scanFolderEntry.m_scanOrder = value; + scanFolderEntry.m_scanOrder = static_cast(value); } } @@ -475,7 +475,7 @@ namespace AssetProcessor RCAssetRecognizer& assetRecognizer = *assetRecognizerEntryIt; if (valueName == "priority") { - assetRecognizer.m_recognizer.m_priority = value; + assetRecognizer.m_recognizer.m_priority = static_cast(value); } } diff --git a/Code/Tools/AssetProcessor/native/utilities/UnitTestShaderCompilerServer.cpp b/Code/Tools/AssetProcessor/native/utilities/UnitTestShaderCompilerServer.cpp index 18e1730de5..88e8520e3c 100644 --- a/Code/Tools/AssetProcessor/native/utilities/UnitTestShaderCompilerServer.cpp +++ b/Code/Tools/AssetProcessor/native/utilities/UnitTestShaderCompilerServer.cpp @@ -49,7 +49,7 @@ void UnitTestShaderCompilerServer::startServer() { if (!m_server->isListening()) { - if (!m_server->listen(QHostAddress(m_serverAddress), m_serverPort)) + if (!m_server->listen(QHostAddress(m_serverAddress), static_cast(m_serverPort))) { AZ_TracePrintf(AssetProcessor::DebugChannel, "Server %s could not start.\n", m_serverAddress.toUtf8().data()); emit errorMessage("Server could not start "); diff --git a/Code/Tools/AssetProcessor/native/utilities/assetUtils.cpp b/Code/Tools/AssetProcessor/native/utilities/assetUtils.cpp index 5e005c117d..72a036bdaa 100644 --- a/Code/Tools/AssetProcessor/native/utilities/assetUtils.cpp +++ b/Code/Tools/AssetProcessor/native/utilities/assetUtils.cpp @@ -72,11 +72,6 @@ namespace AssetUtilsInternal bool FileCopyMoveWithTimeout(QString sourceFile, QString outputFile, bool isCopy, unsigned int waitTimeInSeconds) { - if (waitTimeInSeconds < 0) - { - AZ_Warning("Asset Processor", waitTimeInSeconds >= 0, "Invalid timeout specified by the user"); - waitTimeInSeconds = 0; - } bool failureOccurredOnce = false; // used for logging. bool operationSucceeded = false; QFile outFile(outputFile); diff --git a/Code/Tools/CrashHandler/Tools/Uploader/ToolsCrashUploader.cpp b/Code/Tools/CrashHandler/Tools/Uploader/ToolsCrashUploader.cpp index b33aa183f3..74f271e7c0 100644 --- a/Code/Tools/CrashHandler/Tools/Uploader/ToolsCrashUploader.cpp +++ b/Code/Tools/CrashHandler/Tools/Uploader/ToolsCrashUploader.cpp @@ -72,10 +72,15 @@ namespace O3de return true; } #if !AZ_TRAIT_OS_PLATFORM_APPLE - AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option") + #if AZ_TRAIT_USE_SECURE_CRT_FUNCTIONS + char noConfirmation[64]{}; + size_t variableSize = 0; + getenv_s(&variableSize, noConfirmation, AZ_ARRAY_SIZE(noConfirmation), "LY_NO_CONFIRM"); + if (variableSize == 0) + #else const char* noConfirmation = getenv("LY_NO_CONFIRM"); - AZ_POP_DISABLE_WARNING if (noConfirmation == nullptr) + #endif { int argCount = 0; diff --git a/Code/Tools/ProjectManager/Resources/ProjectManager.qss b/Code/Tools/ProjectManager/Resources/ProjectManager.qss index 74acc1c7ef..1bd261da00 100644 --- a/Code/Tools/ProjectManager/Resources/ProjectManager.qss +++ b/Code/Tools/ProjectManager/Resources/ProjectManager.qss @@ -20,8 +20,7 @@ QPushButton:focus { QTabBar { background-color: transparent; } -QTabWidget::tab-bar -{ +QTabWidget::tab-bar { left: 78px; /* make room for the logo */ } QTabBar::tab { @@ -32,27 +31,35 @@ QTabBar::tab { margin-right:40px; border-bottom: 3px solid transparent; } -QTabBar::tab:text -{ +QTabBar::tab:text { text-align:left; } QTabWidget::pane { background-color: #333333; border:0 none; } -QTabBar::tab:selected -{ +QTabBar::tab:selected { + background-color: transparent; border-bottom: 3px solid #1e70eb; color: #1e70eb; + font-weight: 500; } -QTabBar::tab:hover -{ +QTabBar::tab:hover { color: #1e70eb; + font-weight: 500; } -QTabBar::tab:pressed -{ +QTabBar::tab:pressed { color: #0e60eb; } +QTabBar::focus { + outline: 0px; + outline: none; + outline-style: none; +} +QTabBar::tab:focus { + background-color: #525252; + color: #4082eb; +} /************** General (Forms) **************/ diff --git a/Code/Tools/ProjectManager/Source/FormBrowseEditWidget.cpp b/Code/Tools/ProjectManager/Source/FormBrowseEditWidget.cpp index 9cfc6461c2..8cd28fcbb4 100644 --- a/Code/Tools/ProjectManager/Source/FormBrowseEditWidget.cpp +++ b/Code/Tools/ProjectManager/Source/FormBrowseEditWidget.cpp @@ -10,6 +10,7 @@ #include #include +#include namespace O3DE::ProjectManager { @@ -27,4 +28,14 @@ namespace O3DE::ProjectManager : FormBrowseEditWidget(labelText, "", parent) { } + + void FormBrowseEditWidget::keyPressEvent(QKeyEvent* event) + { + int key = event->key(); + if (key == Qt::Key_Return || key == Qt::Key_Enter) + { + HandleBrowseButton(); + } + } + } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/FormBrowseEditWidget.h b/Code/Tools/ProjectManager/Source/FormBrowseEditWidget.h index 7ec2865240..a1f6948ce9 100644 --- a/Code/Tools/ProjectManager/Source/FormBrowseEditWidget.h +++ b/Code/Tools/ProjectManager/Source/FormBrowseEditWidget.h @@ -24,6 +24,9 @@ namespace O3DE::ProjectManager explicit FormBrowseEditWidget(const QString& labelText = "", QWidget* parent = nullptr); ~FormBrowseEditWidget() = default; + protected: + void keyPressEvent(QKeyEvent* event) override; + protected slots: virtual void HandleBrowseButton() = 0; }; diff --git a/Code/Tools/ProjectManager/Source/FormFolderBrowseEditWidget.cpp b/Code/Tools/ProjectManager/Source/FormFolderBrowseEditWidget.cpp index 86f46400b3..4101f02c9b 100644 --- a/Code/Tools/ProjectManager/Source/FormFolderBrowseEditWidget.cpp +++ b/Code/Tools/ProjectManager/Source/FormFolderBrowseEditWidget.cpp @@ -34,7 +34,6 @@ namespace O3DE::ProjectManager { setText(directory); } - } void FormFolderBrowseEditWidget::setText(const QString& text) @@ -42,4 +41,5 @@ namespace O3DE::ProjectManager QString path = QDir::toNativeSeparators(text); FormBrowseEditWidget::setText(path); } + } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp index ac8cf5d794..909cd93cda 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogHeaderWidget.cpp @@ -117,7 +117,7 @@ namespace O3DE::ProjectManager gemNames.reserve(gems.size()); for (const QModelIndex& modelIndex : gems) { - gemNames.push_back(GemModel::GetName(modelIndex)); + gemNames.push_back(GemModel::GetDisplayName(modelIndex)); } return gemNames; } diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp index 863f611ec8..04d4d6999b 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp @@ -156,7 +156,7 @@ namespace O3DE::ProjectManager if (!result.IsSuccess()) { QMessageBox::critical(nullptr, "Operation failed", - QString("Cannot add gem %1 to project.\n\nError:\n%2").arg(GemModel::GetName(modelIndex), result.GetError().c_str())); + QString("Cannot add gem %1 to project.\n\nError:\n%2").arg(GemModel::GetDisplayName(modelIndex), result.GetError().c_str())); return false; } @@ -169,7 +169,7 @@ namespace O3DE::ProjectManager if (!result.IsSuccess()) { QMessageBox::critical(nullptr, "Operation failed", - QString("Cannot remove gem %1 from project.\n\nError:\n%2").arg(GemModel::GetName(modelIndex), result.GetError().c_str())); + QString("Cannot remove gem %1 from project.\n\nError:\n%2").arg(GemModel::GetDisplayName(modelIndex), result.GetError().c_str())); return false; } diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp index 6c1f5f6fec..6dd6c52612 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemInspector.cpp @@ -58,7 +58,7 @@ namespace O3DE::ProjectManager m_mainWidget->hide(); } - m_nameLabel->setText(m_model->GetName(modelIndex)); + m_nameLabel->setText(m_model->GetDisplayName(modelIndex)); m_creatorLabel->setText(m_model->GetCreator(modelIndex)); m_summaryLabel->setText(m_model->GetSummary(modelIndex)); diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp index d5a213e80f..99a2cd8db7 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemItemDelegate.cpp @@ -29,7 +29,7 @@ namespace O3DE::ProjectManager { QPixmap pixmap(iconPath); qreal aspectRatio = static_cast(pixmap.width()) / pixmap.height(); - m_platformIcons.insert(platform, QIcon(iconPath).pixmap(s_platformIconSize * aspectRatio, s_platformIconSize)); + m_platformIcons.insert(platform, QIcon(iconPath).pixmap(static_cast(static_cast(s_platformIconSize) * aspectRatio), s_platformIconSize)); } void GemItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& modelIndex) const @@ -48,7 +48,7 @@ namespace O3DE::ProjectManager CalcRects(options, fullRect, itemRect, contentRect); QFont standardFont(options.font); - standardFont.setPixelSize(s_fontSize); + standardFont.setPixelSize(static_cast(s_fontSize)); QFontMetrics standardFontMetrics(standardFont); painter->save(); @@ -75,10 +75,10 @@ namespace O3DE::ProjectManager } // Gem name - QString gemName = GemModel::GetName(modelIndex); + QString gemName = GemModel::GetDisplayName(modelIndex); QFont gemNameFont(options.font); const int firstColumnMaxTextWidth = s_summaryStartX - 30; - gemNameFont.setPixelSize(s_gemNameFontSize); + gemNameFont.setPixelSize(static_cast(s_gemNameFontSize)); gemNameFont.setBold(true); gemName = QFontMetrics(gemNameFont).elidedText(gemName, Qt::TextElideMode::ElideRight, firstColumnMaxTextWidth); QRect gemNameRect = GetTextRect(gemNameFont, gemName, s_gemNameFontSize); @@ -178,7 +178,7 @@ namespace O3DE::ProjectManager QRect GemItemDelegate::GetTextRect(QFont& font, const QString& text, qreal fontSize) const { - font.setPixelSize(fontSize); + font.setPixelSize(static_cast(fontSize)); return QFontMetrics(font).boundingRect(text); } @@ -208,7 +208,7 @@ namespace O3DE::ProjectManager const QPixmap& pixmap = iterator.value(); painter->drawPixmap(contentRect.left() + startX, contentRect.bottom() - s_platformIconSize, pixmap); qreal aspectRatio = static_cast(pixmap.width()) / pixmap.height(); - startX += s_platformIconSize * aspectRatio + s_platformIconSize / 2.5; + startX += static_cast(s_platformIconSize * aspectRatio + s_platformIconSize / 2.5); } } } diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp index a15dffdc94..7daea174e7 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.cpp @@ -8,6 +8,7 @@ #include #include +#include namespace O3DE::ProjectManager { @@ -29,6 +30,7 @@ namespace O3DE::ProjectManager item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); item->setData(gemInfo.m_name, RoleName); + item->setData(gemInfo.m_displayName, RoleDisplayName); item->setData(gemInfo.m_creator, RoleCreator); item->setData(gemInfo.m_gemOrigin, RoleGemOrigin); item->setData(aznumeric_cast(gemInfo.m_platforms), RolePlatforms); @@ -63,6 +65,20 @@ namespace O3DE::ProjectManager return modelIndex.data(RoleName).toString(); } + QString GemModel::GetDisplayName(const QModelIndex& modelIndex) + { + QString displayName = modelIndex.data(RoleDisplayName).toString(); + + if (displayName.isEmpty()) + { + return GetName(modelIndex); + } + else + { + return displayName; + } + } + QString GemModel::GetCreator(const QModelIndex& modelIndex) { return modelIndex.data(RoleCreator).toString(); @@ -116,7 +132,7 @@ namespace O3DE::ProjectManager QModelIndex modelIndex = FindIndexByNameString(dependingGemString); if (modelIndex.isValid()) { - dependingGemString = GetName(modelIndex); + dependingGemString = GetDisplayName(modelIndex); } } } diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h index 19172d8073..ce004ee875 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemModel.h @@ -37,6 +37,7 @@ namespace O3DE::ProjectManager QStringList GetConflictingGemNames(const QModelIndex& modelIndex); static QString GetName(const QModelIndex& modelIndex); + static QString GetDisplayName(const QModelIndex& modelIndex); static QString GetCreator(const QModelIndex& modelIndex); static GemInfo::GemOrigin GetGemOrigin(const QModelIndex& modelIndex); static GemInfo::Platforms GetPlatforms(const QModelIndex& modelIndex); @@ -69,6 +70,7 @@ namespace O3DE::ProjectManager enum UserRole { RoleName = Qt::UserRole, + RoleDisplayName, RoleCreator, RoleGemOrigin, RolePlatforms, diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemRequirementDelegate.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemRequirementDelegate.cpp index 655f6055f1..0ca5ca836f 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemRequirementDelegate.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemRequirementDelegate.cpp @@ -35,7 +35,7 @@ namespace O3DE::ProjectManager CalcRects(options, fullRect, itemRect, contentRect); QFont standardFont(options.font); - standardFont.setPixelSize(s_fontSize); + standardFont.setPixelSize(static_cast(s_fontSize)); QFontMetrics standardFontMetrics(standardFont); painter->save(); @@ -51,14 +51,14 @@ namespace O3DE::ProjectManager painter->fillRect(itemRect, itemBackgroundColor); // Gem name - QString gemName = GemModel::GetName(modelIndex); + QString gemName = GemModel::GetDisplayName(modelIndex); QFont gemNameFont(options.font); const int firstColumnMaxTextWidth = s_summaryStartX - 30; gemName = QFontMetrics(gemNameFont).elidedText(gemName, Qt::TextElideMode::ElideRight, firstColumnMaxTextWidth); - gemNameFont.setPixelSize(s_gemNameFontSize); + gemNameFont.setPixelSize(static_cast(s_gemNameFontSize)); gemNameFont.setBold(true); QRect gemNameRect = GetTextRect(gemNameFont, gemName, s_gemNameFontSize); - gemNameRect.moveTo(contentRect.left(), contentRect.center().y() - s_gemNameFontSize); + gemNameRect.moveTo(contentRect.left(), contentRect.center().y() - static_cast(s_gemNameFontSize)); painter->setFont(gemNameFont); painter->setPen(m_textColor); diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.cpp index fbcf395910..6edfced6e5 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemSortFilterProxyModel.cpp @@ -28,9 +28,26 @@ namespace O3DE::ProjectManager return false; } - if (!m_sourceModel->GetName(sourceIndex).contains(m_searchString, Qt::CaseInsensitive)) + // Search Bar + if (!m_sourceModel->GetDisplayName(sourceIndex).contains(m_searchString, Qt::CaseInsensitive) && + !m_sourceModel->GetName(sourceIndex).contains(m_searchString, Qt::CaseInsensitive) && + !m_sourceModel->GetCreator(sourceIndex).contains(m_searchString, Qt::CaseInsensitive) && + !m_sourceModel->GetSummary(sourceIndex).contains(m_searchString, Qt::CaseInsensitive)) { - return false; + bool foundFeature = false; + for (const QString& feature : m_sourceModel->GetFeatures(sourceIndex)) + { + if (feature.contains(m_searchString, Qt::CaseInsensitive)) + { + foundFeature = true; + break; + } + } + + if (!foundFeature) + { + return false; + } } // Gem status diff --git a/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp b/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp index 0ff963e539..7981e9d758 100644 --- a/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp @@ -52,6 +52,7 @@ namespace O3DE::ProjectManager if (projectButton) { + projectButton->SetProjectBuilding(); projectButton->SetProjectButtonAction(tr("Cancel Build"), [this] { HandleCancel(); }); if (m_lastProgress != 0) @@ -111,6 +112,10 @@ namespace O3DE::ProjectManager emit Done(false); return; } + else + { + m_projectInfo.m_buildFailed = false; + } emit Done(true); } diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp index 82b4e8d84a..5bae3b807a 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.cpp @@ -162,22 +162,9 @@ namespace O3DE::ProjectManager QDesktopServices::openUrl(m_logUrl); } - ProjectButton::ProjectButton(const ProjectInfo& projectInfo, QWidget* parent, bool processing) + ProjectButton::ProjectButton(const ProjectInfo& projectInfo, QWidget* parent) : QFrame(parent) , m_projectInfo(projectInfo) - { - BaseSetup(); - if (processing) - { - ProcessingSetup(); - } - else - { - ReadySetup(); - } - } - - void ProjectButton::BaseSetup() { setObjectName("projectButton"); @@ -199,50 +186,63 @@ namespace O3DE::ProjectManager } m_projectImageLabel->setPixmap(QPixmap(projectPreviewPath).scaled(m_projectImageLabel->size(), Qt::KeepAspectRatioByExpanding)); - m_projectFooter = new QFrame(this); + QFrame* projectFooter = new QFrame(this); QHBoxLayout* hLayout = new QHBoxLayout(); hLayout->setContentsMargins(0, 0, 0, 0); - m_projectFooter->setLayout(hLayout); + projectFooter->setLayout(hLayout); { QLabel* projectNameLabel = new QLabel(m_projectInfo.GetProjectDisplayName(), this); hLayout->addWidget(projectNameLabel); + + QMenu* menu = new QMenu(this); + menu->addAction(tr("Edit Project Settings..."), this, [this]() { emit EditProject(m_projectInfo.m_path); }); + menu->addAction(tr("Build"), this, [this]() { emit BuildProject(m_projectInfo); }); + menu->addSeparator(); + menu->addAction(tr("Open Project folder..."), this, [this]() + { + AzQtComponents::ShowFileOnDesktop(m_projectInfo.m_path); + }); + menu->addSeparator(); + menu->addAction(tr("Duplicate"), this, [this]() { emit CopyProject(m_projectInfo); }); + menu->addSeparator(); + menu->addAction(tr("Remove from O3DE"), this, [this]() { emit RemoveProject(m_projectInfo.m_path); }); + menu->addAction(tr("Delete this Project"), this, [this]() { emit DeleteProject(m_projectInfo.m_path); }); + + m_projectMenuButton = new QPushButton(this); + m_projectMenuButton->setObjectName("projectMenuButton"); + m_projectMenuButton->setMenu(menu); + hLayout->addWidget(m_projectMenuButton); } - vLayout->addWidget(m_projectFooter); + vLayout->addWidget(projectFooter); + + connect(m_projectImageLabel->GetOpenEditorButton(), &QPushButton::clicked, [this](){ emit OpenProject(m_projectInfo.m_path); }); } - void ProjectButton::ProcessingSetup() + const ProjectInfo& ProjectButton::GetProjectInfo() const { - m_projectImageLabel->SetEnabled(false); - m_projectImageLabel->SetOverlayText(tr("Processing...\n\n")); + return m_projectInfo; + } + + void ProjectButton::RestoreDefaultState() + { + m_projectImageLabel->SetEnabled(true); + m_projectImageLabel->SetOverlayText(""); + m_projectMenuButton->setVisible(true); QProgressBar* progressBar = m_projectImageLabel->GetProgressBar(); - progressBar->setVisible(true); + progressBar->setVisible(false); progressBar->setValue(0); - } - void ProjectButton::ReadySetup() - { - connect(m_projectImageLabel->GetOpenEditorButton(), &QPushButton::clicked, [this](){ emit OpenProject(m_projectInfo.m_path); }); + QPushButton* projectActionButton = m_projectImageLabel->GetActionButton(); + projectActionButton->setVisible(false); + if (m_actionButtonConnection) + { + disconnect(m_actionButtonConnection); + } - QMenu* menu = new QMenu(this); - menu->addAction(tr("Edit Project Settings..."), this, [this]() { emit EditProject(m_projectInfo.m_path); }); - menu->addAction(tr("Build"), this, [this]() { emit BuildProject(m_projectInfo); }); - menu->addSeparator(); - menu->addAction(tr("Open Project folder..."), this, [this]() - { - AzQtComponents::ShowFileOnDesktop(m_projectInfo.m_path); - }); - menu->addSeparator(); - menu->addAction(tr("Duplicate"), this, [this]() { emit CopyProject(m_projectInfo); }); - menu->addSeparator(); - menu->addAction(tr("Remove from O3DE"), this, [this]() { emit RemoveProject(m_projectInfo.m_path); }); - menu->addAction(tr("Delete this Project"), this, [this]() { emit DeleteProject(m_projectInfo.m_path); }); - - QPushButton* projectMenuButton = new QPushButton(this); - projectMenuButton->setObjectName("projectMenuButton"); - projectMenuButton->setMenu(menu); - m_projectFooter->layout()->addWidget(projectMenuButton); + m_projectImageLabel->GetWarningIcon()->setVisible(false); + m_projectImageLabel->GetWarningLabel()->setVisible(false); } void ProjectButton::SetProjectButtonAction(const QString& text, AZStd::function lambda) @@ -292,9 +292,15 @@ namespace O3DE::ProjectManager SetProjectButtonAction(tr("Build Project"), [this]() { emit BuildProject(m_projectInfo); }); } - void ProjectButton::BuildThisProject() + void ProjectButton::SetProjectBuilding() { - emit BuildProject(m_projectInfo); + m_projectImageLabel->SetEnabled(false); + m_projectImageLabel->SetOverlayText(tr("Building...\n\n")); + m_projectMenuButton->setVisible(false); + + QProgressBar* progressBar = m_projectImageLabel->GetProgressBar(); + progressBar->setVisible(true); + progressBar->setValue(0); } void ProjectButton::SetLaunchButtonEnabled(bool enabled) diff --git a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h index ff352e0afd..9f64b74eab 100644 --- a/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h +++ b/Code/Tools/ProjectManager/Source/ProjectButtonWidget.h @@ -56,13 +56,14 @@ namespace O3DE::ProjectManager void OnLinkActivated(const QString& link); private: - QVBoxLayout* m_buildOverlayLayout; - QLabel* m_overlayLabel; - QProgressBar* m_progressBar; - QPushButton* m_openEditorButton; - QPushButton* m_actionButton; - QLabel* m_warningText; - QLabel* m_warningIcon; + QVBoxLayout* m_buildOverlayLayout = nullptr; + QLabel* m_overlayLabel = nullptr; + QProgressBar* m_progressBar = nullptr; + QPushButton* m_openEditorButton = nullptr; + QPushButton* m_actionButton = nullptr; + QLabel* m_warningText = nullptr; + QLabel* m_warningIcon = nullptr; + QUrl m_logUrl; bool m_enabled = true; }; @@ -73,13 +74,18 @@ namespace O3DE::ProjectManager Q_OBJECT // AUTOMOC public: - explicit ProjectButton(const ProjectInfo& m_projectInfo, QWidget* parent = nullptr, bool processing = false); + explicit ProjectButton(const ProjectInfo& m_projectInfo, QWidget* parent = nullptr); ~ProjectButton() = default; + const ProjectInfo& GetProjectInfo() const; + + void RestoreDefaultState(); + void SetProjectButtonAction(const QString& text, AZStd::function lambda); void SetProjectBuildButtonAction(); void SetBuildLogsLink(const QUrl& logUrl); void ShowBuildFailed(bool show, const QUrl& logUrl); + void SetProjectBuilding(); void SetLaunchButtonEnabled(bool enabled); void SetButtonOverlayText(const QString& text); @@ -95,17 +101,14 @@ namespace O3DE::ProjectManager void BuildProject(const ProjectInfo& projectInfo); private: - void BaseSetup(); - void ProcessingSetup(); - void ReadySetup(); void enterEvent(QEvent* event) override; void leaveEvent(QEvent* event) override; - void BuildThisProject(); ProjectInfo m_projectInfo; - LabelButton* m_projectImageLabel; - QFrame* m_projectFooter; - QLayout* m_requiresBuildLayout; + + LabelButton* m_projectImageLabel = nullptr; + QPushButton* m_projectMenuButton = nullptr; + QLayout* m_requiresBuildLayout = nullptr; QMetaObject::Connection m_actionButtonConnection; }; diff --git a/Code/Tools/ProjectManager/Source/ProjectUtils.cpp b/Code/Tools/ProjectManager/Source/ProjectUtils.cpp index fb0ea23ece..fb3f7e0270 100644 --- a/Code/Tools/ProjectManager/Source/ProjectUtils.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectUtils.cpp @@ -117,7 +117,7 @@ namespace O3DE::ProjectManager const int updateStatusEvery = 64; if (outFileCount % updateStatusEvery == 0) { - statusCallback(outFileCount, outTotalSizeInBytes); + statusCallback(outFileCount, static_cast(outTotalSizeInBytes)); } } } @@ -163,7 +163,7 @@ namespace O3DE::ProjectManager } QLocale locale; - const float progressDialogRangeHalf = qFabs(progressDialog->maximum() - progressDialog->minimum()) * 0.5f; + const float progressDialogRangeHalf = static_cast(qFabs(progressDialog->maximum() - progressDialog->minimum()) * 0.5f); for (const QString& file : original.entryList(QDir::Files)) { if (progressDialog->wasCanceled()) @@ -184,7 +184,7 @@ namespace O3DE::ProjectManager // for cases combining many small files and some really large files. const float normalizedNumFiles = static_cast(outNumCopiedFiles) / filesToCopyCount; const float normalizedFileSize = static_cast(outCopiedFileSize) / totalSizeToCopy; - const int progress = normalizedNumFiles * progressDialogRangeHalf + normalizedFileSize * progressDialogRangeHalf; + const int progress = static_cast(normalizedNumFiles * progressDialogRangeHalf + normalizedFileSize * progressDialogRangeHalf); progressDialog->setValue(progress); const QString copiedFileSizeString = locale.formattedDataSize(outCopiedFileSize); diff --git a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp index e27eedd122..27e39926e4 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.cpp @@ -68,9 +68,7 @@ namespace O3DE::ProjectManager } ProjectsScreen::~ProjectsScreen() - { - delete m_currentBuilder; } QFrame* ProjectsScreen::CreateFirstTimeContent() @@ -114,10 +112,8 @@ namespace O3DE::ProjectManager return frame; } - QFrame* ProjectsScreen::CreateProjectsContent(QString buildProjectPath, ProjectButton** projectButton) + QFrame* ProjectsScreen::CreateProjectsContent() { - RemoveInvalidProjects(); - QFrame* frame = new QFrame(this); frame->setObjectName("projectsContent"); { @@ -126,7 +122,7 @@ namespace O3DE::ProjectManager layout->setContentsMargins(0, 0, 0, 0); frame->setLayout(layout); - QFrame* header = new QFrame(this); + QFrame* header = new QFrame(frame); QHBoxLayout* headerLayout = new QHBoxLayout(); { QLabel* titleLabel = new QLabel(tr("My Projects"), this); @@ -150,87 +146,34 @@ namespace O3DE::ProjectManager layout->addWidget(header); - // Get all projects and create a horizontal scrolling list of them - auto projectsResult = PythonBindingsInterface::Get()->GetProjects(); - if (projectsResult.IsSuccess() && !projectsResult.GetValue().isEmpty()) - { - QScrollArea* projectsScrollArea = new QScrollArea(this); - QWidget* scrollWidget = new QWidget(); + QScrollArea* projectsScrollArea = new QScrollArea(this); + QWidget* scrollWidget = new QWidget(); - FlowLayout* flowLayout = new FlowLayout(0, s_spacerSize, s_spacerSize); - scrollWidget->setLayout(flowLayout); + m_projectsFlowLayout = new FlowLayout(0, s_spacerSize, s_spacerSize); + scrollWidget->setLayout(m_projectsFlowLayout); - projectsScrollArea->setWidget(scrollWidget); - projectsScrollArea->setWidgetResizable(true); + projectsScrollArea->setWidget(scrollWidget); + projectsScrollArea->setWidgetResizable(true); - QVector nonProcessingProjects; - buildProjectPath = QDir::fromNativeSeparators(buildProjectPath); - for (auto& project : projectsResult.GetValue()) - { - if (projectButton && !*projectButton) - { - if (QDir::fromNativeSeparators(project.m_path) == buildProjectPath) - { - *projectButton = CreateProjectButton(project, flowLayout, true); - continue; - } - } + ResetProjectsContent(); - nonProcessingProjects.append(project); - } - - for (auto& project : nonProcessingProjects) - { - ProjectButton* projectButtonWidget = CreateProjectButton(project, flowLayout); - - if (BuildQueueContainsProject(project.m_path)) - { - projectButtonWidget->SetProjectButtonAction(tr("Cancel Queued Build"), - [this, project] - { - UnqueueBuildProject(project); - SuggestBuildProjectMsg(project, false); - }); - } - else if (RequiresBuildProjectIterator(project.m_path) != m_requiresBuild.end()) - { - auto buildProjectIterator = RequiresBuildProjectIterator(project.m_path); - if (buildProjectIterator != m_requiresBuild.end()) - { - if (buildProjectIterator->m_buildFailed) - { - projectButtonWidget->ShowBuildFailed(true, buildProjectIterator->m_logUrl); - } - else - { - projectButtonWidget->SetProjectBuildButtonAction(); - } - } - - } - } - - layout->addWidget(projectsScrollArea); - } + layout->addWidget(projectsScrollArea); } return frame; } - ProjectButton* ProjectsScreen::CreateProjectButton(ProjectInfo& project, QLayout* flowLayout, bool processing) + ProjectButton* ProjectsScreen::CreateProjectButton(const ProjectInfo& project) { - ProjectButton* projectButton = new ProjectButton(project, this, processing); + ProjectButton* projectButton = new ProjectButton(project, this); + m_projectButtons.insert(project.m_path, projectButton); + m_projectsFlowLayout->addWidget(projectButton); - flowLayout->addWidget(projectButton); - - if (!processing) - { - connect(projectButton, &ProjectButton::OpenProject, this, &ProjectsScreen::HandleOpenProject); - connect(projectButton, &ProjectButton::EditProject, this, &ProjectsScreen::HandleEditProject); - connect(projectButton, &ProjectButton::CopyProject, this, &ProjectsScreen::HandleCopyProject); - connect(projectButton, &ProjectButton::RemoveProject, this, &ProjectsScreen::HandleRemoveProject); - connect(projectButton, &ProjectButton::DeleteProject, this, &ProjectsScreen::HandleDeleteProject); - } + connect(projectButton, &ProjectButton::OpenProject, this, &ProjectsScreen::HandleOpenProject); + connect(projectButton, &ProjectButton::EditProject, this, &ProjectsScreen::HandleEditProject); + connect(projectButton, &ProjectButton::CopyProject, this, &ProjectsScreen::HandleCopyProject); + connect(projectButton, &ProjectButton::RemoveProject, this, &ProjectsScreen::HandleRemoveProject); + connect(projectButton, &ProjectButton::DeleteProject, this, &ProjectsScreen::HandleDeleteProject); connect(projectButton, &ProjectButton::BuildProject, this, &ProjectsScreen::QueueBuildProject); return projectButton; @@ -238,29 +181,128 @@ namespace O3DE::ProjectManager void ProjectsScreen::ResetProjectsContent() { - // refresh the projects content by re-creating it for now - if (m_projectsContent) + RemoveInvalidProjects(); + + // Get all projects and create a vertical scrolling list of them + // Sort building and queued projects first + auto projectsResult = PythonBindingsInterface::Get()->GetProjects(); + if (projectsResult.IsSuccess() && !projectsResult.GetValue().isEmpty()) { - m_stack->removeWidget(m_projectsContent); - m_projectsContent->deleteLater(); + QVector projectsVector = projectsResult.GetValue(); + // If a project path is in this set then the button for it will be kept + QSet keepProject; + for (const ProjectInfo& project : projectsVector) + { + keepProject.insert(project.m_path); + } + + // Clear flow and delete buttons for removed projects + auto projectButtonsIter = m_projectButtons.begin(); + while (projectButtonsIter != m_projectButtons.end()) + { + m_projectsFlowLayout->removeWidget(projectButtonsIter.value()); + + if (!keepProject.contains(projectButtonsIter.key())) + { + projectButtonsIter = m_projectButtons.erase(projectButtonsIter); + } + else + { + ++projectButtonsIter; + } + } + + QString buildProjectPath = ""; + if (m_currentBuilder) + { + buildProjectPath = m_currentBuilder->GetProjectInfo().m_path; + } + + // Put currently building project in front, then queued projects, then sorts alphabetically + std::sort(projectsVector.begin(), projectsVector.end(), [buildProjectPath, this](const ProjectInfo& arg1, const ProjectInfo& arg2) + { + if (arg1.m_path == buildProjectPath) + { + return true; + } + else if (arg2.m_path == buildProjectPath) + { + return false; + } + + bool arg1InBuildQueue = BuildQueueContainsProject(arg1.m_path); + bool arg2InBuildQueue = BuildQueueContainsProject(arg2.m_path); + if (arg1InBuildQueue && !arg2InBuildQueue) + { + return true; + } + else if (!arg1InBuildQueue && arg2InBuildQueue) + { + return false; + } + else + { + return arg1.m_displayName.toLower() < arg2.m_displayName.toLower(); + } + }); + + // Add any missing project buttons and restore buttons to default state + for (const ProjectInfo& project : projectsVector) + { + if (!m_projectButtons.contains(project.m_path)) + { + m_projectButtons.insert(project.m_path, CreateProjectButton(project)); + } + else + { + auto projectButtonIter = m_projectButtons.find(project.m_path); + if (projectButtonIter != m_projectButtons.end()) + { + projectButtonIter.value()->RestoreDefaultState(); + m_projectsFlowLayout->addWidget(projectButtonIter.value()); + } + } + } + + // Setup building button again + auto buildProjectIter = m_projectButtons.find(buildProjectPath); + if (buildProjectIter != m_projectButtons.end()) + { + m_currentBuilder->SetProjectButton(buildProjectIter.value()); + } + + for (const ProjectInfo& project : m_buildQueue) + { + auto projectIter = m_projectButtons.find(project.m_path); + if (projectIter != m_projectButtons.end()) + { + projectIter.value()->SetProjectButtonAction( + tr("Cancel Queued Build"), + [this, project] + { + UnqueueBuildProject(project); + SuggestBuildProjectMsg(project, false); + }); + } + } + + for (const ProjectInfo& project : m_requiresBuild) + { + auto projectIter = m_projectButtons.find(project.m_path); + if (projectIter != m_projectButtons.end()) + { + if (project.m_buildFailed) + { + projectIter.value()->ShowBuildFailed(true, project.m_logUrl); + } + else + { + projectIter.value()->SetProjectBuildButtonAction(); + } + } + } } - m_background.load(":/Backgrounds/DefaultBackground.jpg"); - - // Make sure to update builder with latest Project Button - if (m_currentBuilder) - { - ProjectButton* projectButtonPtr = nullptr; - - m_projectsContent = CreateProjectsContent(m_currentBuilder->GetProjectInfo().m_path, &projectButtonPtr); - m_currentBuilder->SetProjectButton(projectButtonPtr); - } - else - { - m_projectsContent = CreateProjectsContent(); - } - - m_stack->addWidget(m_projectsContent); m_stack->setCurrentWidget(m_projectsContent); } @@ -466,7 +508,7 @@ namespace O3DE::ProjectManager if (m_buildQueue.empty() && !m_currentBuilder) { StartProjectBuild(projectInfo); - // Projects Content is already reset in fuction + // Projects Content is already reset in function } else { @@ -491,6 +533,7 @@ namespace O3DE::ProjectManager } else { + m_background.load(":/Backgrounds/DefaultBackground.jpg"); ResetProjectsContent(); } } diff --git a/Code/Tools/ProjectManager/Source/ProjectsScreen.h b/Code/Tools/ProjectManager/Source/ProjectsScreen.h index 45605ab678..859f8d0eae 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsScreen.h +++ b/Code/Tools/ProjectManager/Source/ProjectsScreen.h @@ -18,6 +18,7 @@ QT_FORWARD_DECLARE_CLASS(QPaintEvent) QT_FORWARD_DECLARE_CLASS(QFrame) QT_FORWARD_DECLARE_CLASS(QStackedWidget) QT_FORWARD_DECLARE_CLASS(QLayout) +QT_FORWARD_DECLARE_CLASS(FlowLayout) namespace O3DE::ProjectManager { @@ -59,8 +60,8 @@ namespace O3DE::ProjectManager private: QFrame* CreateFirstTimeContent(); - QFrame* CreateProjectsContent(QString buildProjectPath = "", ProjectButton** projectButton = nullptr); - ProjectButton* CreateProjectButton(ProjectInfo& project, QLayout* flowLayout, bool processing = false); + QFrame* CreateProjectsContent(); + ProjectButton* CreateProjectButton(const ProjectInfo& project); void ResetProjectsContent(); bool ShouldDisplayFirstTimeContent(); bool RemoveInvalidProjects(); @@ -75,7 +76,9 @@ namespace O3DE::ProjectManager QPixmap m_background; QFrame* m_firstTimeContent = nullptr; QFrame* m_projectsContent = nullptr; + FlowLayout* m_projectsFlowLayout = nullptr; QStackedWidget* m_stack = nullptr; + QHash m_projectButtons; QList m_requiresBuild; QQueue m_buildQueue; ProjectBuilderController* m_currentBuilder = nullptr; diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp index 8bdfb0f152..18901946f3 100644 --- a/Code/Tools/ProjectManager/Source/PythonBindings.cpp +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -434,8 +434,6 @@ namespace O3DE::ProjectManager { return AZ::Success(AZStd::move(engineInfo)); } - - return AZ::Failure(); } bool PythonBindings::SetEngineInfo(const EngineInfo& engineInfo) diff --git a/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp b/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp index 30b8ef1d34..df0bdb29f4 100644 --- a/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/ScreensCtrl.cpp @@ -30,6 +30,7 @@ namespace O3DE::ProjectManager // add a tab widget at the bottom of the stack m_tabWidget = new QTabWidget(); + m_tabWidget->tabBar()->setFocusPolicy(Qt::TabFocus); m_screenStack->addWidget(m_tabWidget); connect(m_tabWidget, &QTabWidget::currentChanged, this, &ScreensCtrl::TabChanged); } diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp index 6aba261cd2..e1b6d740e2 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp @@ -54,6 +54,7 @@ namespace O3DE::ProjectManager QTabWidget* tabWidget = new QTabWidget(); tabWidget->setObjectName("projectSettingsTab"); tabWidget->tabBar()->setObjectName("projectSettingsTabBar"); + tabWidget->tabBar()->setFocusPolicy(Qt::TabFocus); tabWidget->addTab(m_updateSettingsScreen, tr("General")); QPushButton* gemsButton = new QPushButton(tr("Configure Gems"), this); diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp index 97b5960a8d..16f8d85509 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpAnimationImporter.cpp @@ -49,7 +49,7 @@ namespace AZ double totalFramesAtDefaultTimeStep = totalTicks / AssImpAnimationImporter::s_defaultTimeStepBetweenFrames + 1; if (!AZ::IsClose(totalFramesAtDefaultTimeStep, numKeys, 1)) { - numKeys = AZStd::ceilf(totalFramesAtDefaultTimeStep); + numKeys = static_cast(AZStd::ceilf(static_cast(totalFramesAtDefaultTimeStep))); } return numKeys; } @@ -122,7 +122,7 @@ namespace AZ if (keys[lastIndex + 1].mTime != keys[lastIndex].mTime) { normalizedTimeBetweenFrames = - (time - keys[lastIndex].mTime) / (keys[lastIndex + 1].mTime - keys[lastIndex].mTime); + static_cast((time - keys[lastIndex].mTime) / (keys[lastIndex + 1].mTime - keys[lastIndex].mTime)); } else { @@ -620,7 +620,7 @@ namespace AZ for (unsigned int valIdx = 0; valIdx < key.mNumValuesAndWeights; ++valIdx) { int currentValue = key.mValues[valIdx]; - KeyData thisKey(key.mWeights[valIdx], key.mTime); + KeyData thisKey(static_cast(key.mWeights[valIdx]), static_cast(key.mTime)); valueToKeyDataMap[currentValue].insert( AZStd::upper_bound(valueToKeyDataMap[currentValue].begin(), valueToKeyDataMap[currentValue].end(),thisKey), thisKey); diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpSkinWeightsImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpSkinWeightsImporter.cpp index 1e298aca5c..014d1bc5bf 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpSkinWeightsImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpSkinWeightsImporter.cpp @@ -97,7 +97,7 @@ namespace AZ } Pending pending; pending.m_bone = bone; - pending.m_numVertices = totalVertices; + pending.m_numVertices = static_cast(totalVertices); pending.m_skinWeightData = skinWeightData; pending.m_vertOffset = vertexCount; m_pendingSkinWeights.push_back(pending); diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp index fc0ac15244..9e0d788896 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpUvMapImporter.cpp @@ -88,7 +88,7 @@ namespace AZ AZ_Error( Utilities::ErrorWindow, meshesPerTextureCoordinateIndex[texCoordIndex] == 0 || - meshesPerTextureCoordinateIndex[texCoordIndex] == currentNode->mNumMeshes, + meshesPerTextureCoordinateIndex[texCoordIndex] == static_cast(currentNode->mNumMeshes), "Texture coordinate index %d for node %s is not on all meshes on this node. " "Placeholder arbitrary texture values will be generated to allow the data to process, but the source art " "needs to be fixed to correct this. All meshes on this node should have the same number of texture coordinate channels.", diff --git a/Code/Tools/SceneAPI/SceneCore/SceneBuilderDependencyBus.h b/Code/Tools/SceneAPI/SceneCore/SceneBuilderDependencyBus.h index 6500b5ca28..752d4a431f 100644 --- a/Code/Tools/SceneAPI/SceneCore/SceneBuilderDependencyBus.h +++ b/Code/Tools/SceneAPI/SceneCore/SceneBuilderDependencyBus.h @@ -24,7 +24,12 @@ namespace AZ : public AZ::EBusTraits { public: - virtual void ReportJobDependencies(JobDependencyList& jobDependencyList, const char* platformIdentifier) = 0; + //! Builders can implement this function to add job dependencies on other assets that may be used in the scene file conversion process. + virtual void ReportJobDependencies(JobDependencyList& jobDependencyList, const char* platformIdentifier) { AZ_UNUSED(jobDependencyList); AZ_UNUSED(platformIdentifier); } + + //! Builders can implement this function to append to the job analysis fingerprint. This can be used to trigger rebuilds when global configuration changes. + //! See also AssetBuilderDesc::m_analysisFingerprint. + virtual void AddFingerprintInfo(AZStd::set& fingerprintInfo) { AZ_UNUSED(fingerprintInfo); } }; using SceneBuilderDependencyBus = EBus; } // namespace SceneAPI diff --git a/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.cpp b/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.cpp index e688ebccd4..de727498fc 100644 --- a/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.cpp +++ b/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.cpp @@ -9,6 +9,15 @@ #include "DebugOutput.h" #include +#include +#include +#include +#include +#include +#include +#include +#include + namespace AZ::SceneAPI::Utilities { void DebugOutput::Write(const char* name, const char* data) @@ -118,4 +127,63 @@ namespace AZ::SceneAPI::Utilities { return m_output; } + + void WriteAndLog(AZ::IO::SystemFile& dbgFile, const char* strToWrite) + { + AZ_TracePrintf(AZ::SceneAPI::Utilities::LogWindow, "%s", strToWrite); + dbgFile.Write(strToWrite, strlen(strToWrite)); + dbgFile.Write("\n", strlen("\n")); + } + + void DebugOutput::BuildDebugSceneGraph(const char* outputFolder, AZ::SceneAPI::Events::ExportProductList& productList, const AZStd::shared_ptr& scene, AZStd::string productName) + { + const int debugSceneGraphVersion = 1; + AZStd::string debugSceneFile; + + AzFramework::StringFunc::Path::ConstructFull(outputFolder, productName.c_str(), debugSceneFile); + AZ_TracePrintf(AZ::SceneAPI::Utilities::LogWindow, "outputFolder %s, name %s.\n", outputFolder, productName.c_str()); + + AZ::IO::SystemFile dbgFile; + if (dbgFile.Open(debugSceneFile.c_str(), AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY)) + { + WriteAndLog(dbgFile, AZStd::string::format("ProductName: %s", productName.c_str()).c_str()); + WriteAndLog(dbgFile, AZStd::string::format("debugSceneGraphVersion: %d", debugSceneGraphVersion).c_str()); + WriteAndLog(dbgFile, scene->GetName().c_str()); + + const AZ::SceneAPI::Containers::SceneGraph& sceneGraph = scene->GetGraph(); + auto names = sceneGraph.GetNameStorage(); + auto content = sceneGraph.GetContentStorage(); + auto pairView = AZ::SceneAPI::Containers::Views::MakePairView(names, content); + auto view = AZ::SceneAPI::Containers::Views::MakeSceneGraphDownwardsView< + AZ::SceneAPI::Containers::Views::BreadthFirst>( + sceneGraph, sceneGraph.GetRoot(), pairView.cbegin(), true); + + for (auto&& viewIt : view) + { + if (viewIt.second == nullptr) + { + continue; + } + + AZ::SceneAPI::DataTypes::IGraphObject* graphObject = const_cast(viewIt.second.get()); + + WriteAndLog(dbgFile, AZStd::string::format("Node Name: %s", viewIt.first.GetName()).c_str()); + WriteAndLog(dbgFile, AZStd::string::format("Node Path: %s", viewIt.first.GetPath()).c_str()); + WriteAndLog(dbgFile, AZStd::string::format("Node Type: %s", graphObject->RTTI_GetTypeName()).c_str()); + + AZ::SceneAPI::Utilities::DebugOutput debugOutput; + viewIt.second->GetDebugOutput(debugOutput); + + if (!debugOutput.GetOutput().empty()) + { + WriteAndLog(dbgFile, debugOutput.GetOutput().c_str()); + } + } + dbgFile.Close(); + + static const AZ::Data::AssetType dbgSceneGraphAssetType("{07F289D1-4DC7-4C40-94B4-0A53BBCB9F0B}"); + productList.AddProduct(productName, AZ::Uuid::CreateName(productName.c_str()), dbgSceneGraphAssetType, + AZStd::nullopt, AZStd::nullopt); + } + } } diff --git a/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h b/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h index 5fe5b98243..e05d10e2fa 100644 --- a/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h +++ b/Code/Tools/SceneAPI/SceneCore/Utilities/DebugOutput.h @@ -16,6 +16,22 @@ #include #include +namespace AZ +{ + namespace SceneAPI + { + namespace Containers + { + class Scene; + } + namespace Events + { + struct ExportProduct; + class ExportProductList; + } + } +} + namespace AZ::SceneAPI::Utilities { class DebugOutput @@ -42,6 +58,8 @@ namespace AZ::SceneAPI::Utilities SCENE_CORE_API const AZStd::string& GetOutput() const; + SCENE_CORE_API static void BuildDebugSceneGraph(const char* outputFolder, AZ::SceneAPI::Events::ExportProductList& productList, const AZStd::shared_ptr& scene, AZStd::string productName); + protected: AZStd::string m_output; }; diff --git a/Code/Tools/SceneAPI/SceneUI/SceneWidgets/ManifestWidget.cpp b/Code/Tools/SceneAPI/SceneUI/SceneWidgets/ManifestWidget.cpp index 6cec14a9c5..eba43d2e36 100644 --- a/Code/Tools/SceneAPI/SceneUI/SceneWidgets/ManifestWidget.cpp +++ b/Code/Tools/SceneAPI/SceneUI/SceneWidgets/ManifestWidget.cpp @@ -40,7 +40,7 @@ namespace AZ void ManifestWidget::BuildFromScene(const AZStd::shared_ptr& scene) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); ui->m_tabs->clear(); m_pages.clear(); @@ -80,7 +80,7 @@ namespace AZ bool ManifestWidget::AddObject(const AZStd::shared_ptr& object) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); for (ManifestWidgetPage* page : m_pages) { if (page->SupportsType(object)) diff --git a/Code/Tools/SceneAPI/SceneUI/SceneWidgets/ManifestWidgetPage.cpp b/Code/Tools/SceneAPI/SceneUI/SceneWidgets/ManifestWidgetPage.cpp index 118db8217e..cd80b68509 100644 --- a/Code/Tools/SceneAPI/SceneUI/SceneWidgets/ManifestWidgetPage.cpp +++ b/Code/Tools/SceneAPI/SceneUI/SceneWidgets/ManifestWidgetPage.cpp @@ -76,7 +76,7 @@ namespace AZ bool ManifestWidgetPage::AddObject(const AZStd::shared_ptr& object) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); if (!SupportsType(object)) { return false; @@ -218,7 +218,7 @@ namespace AZ void ManifestWidgetPage::RefreshPage() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); + AZ_PROFILE_FUNCTION(Editor); m_propertyEditor->InvalidateAll(); m_propertyEditor->ExpandAll(); } diff --git a/Code/Tools/Standalone/Source/Driller/AreaChart.cpp b/Code/Tools/Standalone/Source/Driller/AreaChart.cpp index c672e4414a..a0eccc7d45 100644 --- a/Code/Tools/Standalone/Source/Driller/AreaChart.cpp +++ b/Code/Tools/Standalone/Source/Driller/AreaChart.cpp @@ -173,10 +173,7 @@ namespace AreaChart void AreaChart::ConfigureVerticalAxis(QString label, unsigned int minimumHeight) { - if (minimumHeight >= 0) - { - SetMinimumValueRange(minimumHeight); - } + SetMinimumValueRange(minimumHeight); if (m_verticalAxis == nullptr) { @@ -231,14 +228,14 @@ namespace AreaChart void AreaChart::AddPoint(size_t seriesId, int position, unsigned int value) { - AZ_PROFILE_TIMER("Standalone Tools", __FUNCTION__); + AZ_PROFILE_FUNCTION(AzToolsFramework); LinePoint linePoint(position,value); AddPoint(seriesId,linePoint); } void AreaChart::AddPoint(size_t seriesId, const LinePoint& linePoint) { - AZ_PROFILE_TIMER("Standalone Tools", __FUNCTION__); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!IsValidSeriesId(seriesId)) { AZ_Error("AreaChart", false, "Invalid SeriesId given."); @@ -323,7 +320,7 @@ namespace AreaChart // Need to handle the areas right at the edge of the polygons for (int i = -1; i <= 1; ++i) { - if ((counter+i) < 0 || (counter + i) >= m_hitAreas.size()) + if ((counter + i) >= m_hitAreas.size()) { continue; } @@ -419,7 +416,7 @@ namespace AreaChart void AreaChart::paintEvent(QPaintEvent* event) { - AZ_PROFILE_TIMER("Standalone Tools", __FUNCTION__); + AZ_PROFILE_FUNCTION(AzToolsFramework); (void)event; if (m_sizingDirty) @@ -435,7 +432,7 @@ namespace AreaChart if (m_regenGraph) { - AZ_PROFILE_TIMER("Standalone Tools", "Generating Graph Data"); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_regenGraph = false; if (m_verticalAxis) diff --git a/Code/Tools/Standalone/Source/Driller/Replica/BaseDetailView.h b/Code/Tools/Standalone/Source/Driller/Replica/BaseDetailView.h index 8b7e3f36af..2db8966a2e 100644 --- a/Code/Tools/Standalone/Source/Driller/Replica/BaseDetailView.h +++ b/Code/Tools/Standalone/Source/Driller/Replica/BaseDetailView.h @@ -203,7 +203,7 @@ namespace Driller void RedrawGraph() { - AZ_PROFILE_TIMER("Standalone Tools", __FUNCTION__); + AZ_PROFILE_FUNCTION(AzToolsFramework); switch (m_displayMode) { case DisplayMode::Active: @@ -518,7 +518,7 @@ namespace Driller void RefreshView(FrameNumberType frameId) { - AZ_PROFILE_TIMER("Standalone Tools", __FUNCTION__); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::unordered_set< Key > discoveredSet; m_tableViewOrdering.clear(); diff --git a/Code/Tools/Standalone/Source/Driller/Replica/ReplicaDataView.cpp b/Code/Tools/Standalone/Source/Driller/Replica/ReplicaDataView.cpp index e538b47429..be4c7d14ff 100644 --- a/Code/Tools/Standalone/Source/Driller/Replica/ReplicaDataView.cpp +++ b/Code/Tools/Standalone/Source/Driller/Replica/ReplicaDataView.cpp @@ -1628,7 +1628,7 @@ namespace Driller void ReplicaDataView::ParseFrameData(FrameNumberType frameId) { - AZ_PROFILE_TIMER("Standalone Tools", __FUNCTION__); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (frameId < 0 || frameId >= m_aggregator->GetFrameCount() || m_parsedFrames.find(frameId) != m_parsedFrames.end()) { return; diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp index e7430fe90b..a90f2cf4a2 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp @@ -26,8 +26,8 @@ namespace TestImpact void ImpactAnalysisTestSelection(size_t numSelectedTests, size_t numDiscardedTests, size_t numExcludedTests, size_t numDraftedTests) { - const float totalTests = numSelectedTests + numDiscardedTests; - const float saving = (1.0 - (numSelectedTests / totalTests)) * 100.0f; + const float totalTests = static_cast(numSelectedTests + numDiscardedTests); + const float saving = (1.0f - (numSelectedTests / totalTests)) * 100.0f; std::cout << numSelectedTests << " tests selected, " << numDiscardedTests << " tests discarded (" << saving << "% test saving)\n"; std::cout << "Of which " << numExcludedTests << " tests have been excluded and " << numDraftedTests << " tests have been drafted.\n"; diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleUtils.cpp b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleUtils.cpp index 47cdca11b1..61fb0a1707 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleUtils.cpp +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleUtils.cpp @@ -7,6 +7,7 @@ */ #include +#include namespace TestImpact { diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestRunSuiteFactory.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestRunSuiteFactory.cpp index aa03292047..f5d7d3a8a2 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestRunSuiteFactory.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestRunSuiteFactory.cpp @@ -67,7 +67,7 @@ namespace TestImpact const auto getDuration = [&Keys](const AZ::rapidxml::xml_node<>* node) { const AZStd::string duration = node->first_attribute(Keys[DurationKey])->value(); - return AZStd::chrono::milliseconds(AZStd::stof(duration) * 1000.f); + return AZStd::chrono::milliseconds(static_cast(AZStd::stof(duration) * 1000.f)); }; TestRunSuite testSuite; @@ -95,7 +95,7 @@ namespace TestImpact const auto getResult = [](const AZ::rapidxml::xml_node<>* node) { - for (auto child_node = node->first_node("failure"); child_node; child_node = child_node->next_sibling()) + if (auto child_node = node->first_node("failure")) { return TestRunResult::Failed; } diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactTestRunSerializer.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactTestRunSerializer.cpp index 62d251c074..c0ca2caeae 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactTestRunSerializer.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactTestRunSerializer.cpp @@ -52,7 +52,7 @@ namespace TestImpact // Run duration writer.Key(TestRunFields::Keys[TestRunFields::DurationKey]); - writer.Uint(testRun.GetDuration().count()); + writer.Uint(static_cast(testRun.GetDuration().count())); // Suites writer.Key(TestRunFields::Keys[TestRunFields::SuitesKey]); @@ -69,7 +69,7 @@ namespace TestImpact // Suite duration writer.Key(TestRunFields::Keys[TestRunFields::DurationKey]); - writer.Uint(suite.m_duration.count()); + writer.Uint(static_cast(suite.m_duration.count())); // Suite enabled writer.Key(TestRunFields::Keys[TestRunFields::EnabledKey]); @@ -93,7 +93,7 @@ namespace TestImpact // Test duration writer.Key(TestRunFields::Keys[TestRunFields::DurationKey]); - writer.Uint(test.m_duration.count()); + writer.Uint(static_cast(test.m_duration.count())); // Test status writer.Key(TestRunFields::Keys[TestRunFields::StatusKey]); diff --git a/Gems/AWSCore/Code/Include/Public/Framework/AWSApiClientJobConfig.h b/Gems/AWSCore/Code/Include/Public/Framework/AWSApiClientJobConfig.h index 2070bab4b6..e991b2af7e 100644 --- a/Gems/AWSCore/Code/Include/Public/Framework/AWSApiClientJobConfig.h +++ b/Gems/AWSCore/Code/Include/Public/Framework/AWSApiClientJobConfig.h @@ -45,15 +45,10 @@ namespace AWSCore virtual std::shared_ptr GetClient() = 0; }; -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable: 4250 ) // warning C4250: 'AWSCore::AwsApiClientJobConfig': inherits 'AWSCore::AwsApiJobConfig::AWSCore::AwsApiJobConfig::GetJobContext' via dominance // Thanks to http://stackoverflow.com/questions/11965596/diamond-inheritance-scenario-compiles-fine-in-g-but-produces-warnings-errors for the explanation // This is the expected and desired behavior. The warning is superfluous. - -#endif - + AZ_PUSH_DISABLE_WARNING(4250, "-Wunknown-warning-option") /// Configuration for AWS jobs using a specific client type. template class AwsApiClientJobConfig @@ -126,9 +121,6 @@ namespace AWSCore /// Set by ApplySettings std::shared_ptr m_client; }; - -#ifdef _MSC_VER -#pragma warning( pop ) // C4250 -#endif + AZ_POP_DISABLE_WARNING } // namespace AWSCore diff --git a/Gems/AWSCore/Code/Include/Public/Framework/HttpRequestJobConfig.h b/Gems/AWSCore/Code/Include/Public/Framework/HttpRequestJobConfig.h index 9018c167f6..5b348d8630 100644 --- a/Gems/AWSCore/Code/Include/Public/Framework/HttpRequestJobConfig.h +++ b/Gems/AWSCore/Code/Include/Public/Framework/HttpRequestJobConfig.h @@ -27,15 +27,10 @@ namespace AWSCore }; -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable: 4250 ) // warning C4250: 'AWSCore::HttpRequestJobConfig' : inherits 'AWSCore::AwsApiJobConfig::AWSCore::AwsApiJobConfig::GetJobContext' via dominance // Thanks to http://stackoverflow.com/questions/11965596/diamond-inheritance-scenario-compiles-fine-in-g-but-produces-warnings-errors for the explanation // This is the expected and desired behavior. The warning is superfluous. - -#endif - + AZ_PUSH_DISABLE_WARNING(4250, "-Wunknown-warning-option") //! Provides service job configuration using settings properties. class HttpRequestJobConfig : public AwsApiJobConfig @@ -98,9 +93,6 @@ namespace AWSCore std::shared_ptr m_httpClient{ nullptr }; Aws::String m_userAgent{}; }; - -#ifdef _MSC_VER -#pragma warning( pop ) // C4250 -#endif + AZ_POP_DISABLE_WARNING } // namespace AWSCore diff --git a/Gems/AWSCore/Code/Include/Public/Framework/ServiceClientJobConfig.h b/Gems/AWSCore/Code/Include/Public/Framework/ServiceClientJobConfig.h index 239fdfdbc0..9082498e96 100644 --- a/Gems/AWSCore/Code/Include/Public/Framework/ServiceClientJobConfig.h +++ b/Gems/AWSCore/Code/Include/Public/Framework/ServiceClientJobConfig.h @@ -60,16 +60,11 @@ namespace AWSCore static const char* GetRESTApiStageKeyName() { return RESTAPI_STAGE; } \ }; -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable: 4250 ) // warning C4250: 'AWSCore::ServiceClientJobConfig' : inherits 'AWSCore::AwsApiJobConfig::AWSCore::AwsApiJobConfig::GetJobContext' via dominance // Thanks to http://stackoverflow.com/questions/11965596/diamond-inheritance-scenario-compiles-fine-in-g-but-produces-warnings-errors for the explanation // This is the expected and desired behavior. The warning is superfluous. - -#endif - -/// Provides service job configuration using settings properties. + AZ_PUSH_DISABLE_WARNING(4250, "-Wunknown-warning-option") + /// Provides service job configuration using settings properties. template class ServiceClientJobConfig : public ServiceJobConfig @@ -132,10 +127,7 @@ namespace AWSCore } }; - -#ifdef _MSC_VER -#pragma warning( pop ) // C4250 -#endif + AZ_POP_DISABLE_WARNING } // namespace AWSCore diff --git a/Gems/AWSCore/Code/Include/Public/Framework/ServiceJobConfig.h b/Gems/AWSCore/Code/Include/Public/Framework/ServiceJobConfig.h index 0e2e2de96d..f1a01cfb7b 100644 --- a/Gems/AWSCore/Code/Include/Public/Framework/ServiceJobConfig.h +++ b/Gems/AWSCore/Code/Include/Public/Framework/ServiceJobConfig.h @@ -12,28 +12,21 @@ namespace AWSCore { - /// Provides configuration needed by service jobs. class IServiceJobConfig : public virtual IHttpRequestJobConfig { }; -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable: 4250 ) // warning C4250: 'AWSCore::ServiceJobConfig' : inherits 'AWSCore::AwsApiJobConfig::AWSCore::AwsApiJobConfig::GetJobContext' via dominance // Thanks to http://stackoverflow.com/questions/11965596/diamond-inheritance-scenario-compiles-fine-in-g-but-produces-warnings-errors for the explanation // This is the expected and desired behavior. The warning is superfluous. - -#endif - -/// Provides service job configuration using settings properties. + AZ_PUSH_DISABLE_WARNING(4250, "-Wunknown-warning-option") + /// Provides service job configuration using settings properties. class ServiceJobConfig : public HttpRequestJobConfig , public virtual IServiceJobConfig { - public: AZ_CLASS_ALLOCATOR(ServiceJobConfig, AZ::SystemAllocator, 0); @@ -59,13 +52,7 @@ namespace AWSCore } void ApplySettings() override; - - private: - }; - -#ifdef _MSC_VER -#pragma warning( pop ) // C4250 -#endif + AZ_POP_DISABLE_WARNING } // namespace AWSCore diff --git a/Gems/AWSCore/Code/Include/Public/Framework/ServiceRequestJobConfig.h b/Gems/AWSCore/Code/Include/Public/Framework/ServiceRequestJobConfig.h index 8395384427..240331496e 100644 --- a/Gems/AWSCore/Code/Include/Public/Framework/ServiceRequestJobConfig.h +++ b/Gems/AWSCore/Code/Include/Public/Framework/ServiceRequestJobConfig.h @@ -25,15 +25,10 @@ namespace AWSCore virtual bool IsValid() const = 0; }; -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable: 4250 ) // warning C4250: 'AWSCore::ServiceRequestJobConfig' : inherits 'AWSCore::AwsApiJobConfig::AWSCore::AwsApiJobConfig::GetJobContext' via dominance // Thanks to http://stackoverflow.com/questions/11965596/diamond-inheritance-scenario-compiles-fine-in-g-but-produces-warnings-errors for the explanation // This is the expected and desired behavior. The warning is superfluous. - -#endif - + AZ_PUSH_DISABLE_WARNING(4250, "-Wunknown-warning-option") template class ServiceRequestJobConfig : public ServiceClientJobConfig @@ -105,9 +100,6 @@ namespace AWSCore std::shared_ptr m_credentialsProvider; }; - -#ifdef _MSC_VER -#pragma warning( pop ) // C4250 -#endif + AZ_POP_DISABLE_WARNING } // namespace AWSCore diff --git a/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionMetric.cpp b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionMetric.cpp index f54d7f71af..aee766d355 100644 --- a/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionMetric.cpp +++ b/Gems/AWSCore/Code/Source/Editor/Attribution/AWSCoreAttributionMetric.cpp @@ -12,8 +12,6 @@ #include #include -#pragma warning(disable : 4996) - namespace AWSCore { constexpr char AWSAttributionMetricDefaultO3DEVersion[] = "1.1"; @@ -97,7 +95,13 @@ namespace AWSCore time_t now; time(&now); char buffer[50]; - strftime(buffer, sizeof(buffer), "%FT%TZ", gmtime(&now)); + tm time; +#if AZ_TRAIT_USE_SECURE_CRT_FUNCTIONS + gmtime_s(&time, &now); +#else + time = *gmtime(&now); +#endif + strftime(buffer, sizeof(buffer), "%FT%TZ", &time); return buffer; } diff --git a/Gems/AWSCore/cdk/app.py b/Gems/AWSCore/cdk/app.py index ea038f8a51..16773b5f69 100755 --- a/Gems/AWSCore/cdk/app.py +++ b/Gems/AWSCore/cdk/app.py @@ -25,7 +25,7 @@ ACCOUNT = os.environ.get('O3DE_AWS_DEPLOY_ACCOUNT', os.environ.get('CDK_DEFAULT_ PROJECT_NAME = os.environ.get('O3DE_AWS_PROJECT_NAME', f'O3DE-AWS-PROJECT').upper() # The name of this feature -FEATURE_NAME = 'Core' +FEATURE_NAME = 'AWSCore' # The name of this CDK application PROJECT_FEATURE_NAME = f'{PROJECT_NAME}-{FEATURE_NAME}' diff --git a/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftCreateSessionActivity.cpp b/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftCreateSessionActivity.cpp index 667a8de679..0332ea7a76 100644 --- a/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftCreateSessionActivity.cpp +++ b/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftCreateSessionActivity.cpp @@ -48,7 +48,7 @@ namespace AWSGameLift { request.SetFleetId(createSessionRequest.m_fleetId.c_str()); } - request.SetMaximumPlayerSessionCount(createSessionRequest.m_maxPlayer); + request.SetMaximumPlayerSessionCount(static_cast(createSessionRequest.m_maxPlayer)); AZ_TracePrintf(AWSGameLiftCreateSessionActivityName, "Built CreateGameSessionRequest with CreatorId=%s, Name=%s, IdempotencyToken=%s, GameProperties=%s, AliasId=%s, FleetId=%s and MaximumPlayerSessionCount=%d", @@ -90,7 +90,7 @@ namespace AWSGameLift { auto gameliftCreateSessionRequest = azrtti_cast(&createSessionRequest); - return gameliftCreateSessionRequest && gameliftCreateSessionRequest->m_maxPlayer >= 0 && + return gameliftCreateSessionRequest && (!gameliftCreateSessionRequest->m_aliasId.empty() || !gameliftCreateSessionRequest->m_fleetId.empty()); } } // namespace CreateSessionActivity diff --git a/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftCreateSessionOnQueueActivity.cpp b/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftCreateSessionOnQueueActivity.cpp index a8a393aa18..52be365ea5 100644 --- a/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftCreateSessionOnQueueActivity.cpp +++ b/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftCreateSessionOnQueueActivity.cpp @@ -33,7 +33,7 @@ namespace AWSGameLift // Required attributes request.SetGameSessionQueueName(createSessionOnQueueRequest.m_queueName.c_str()); - request.SetMaximumPlayerSessionCount(createSessionOnQueueRequest.m_maxPlayer); + request.SetMaximumPlayerSessionCount(static_cast(createSessionOnQueueRequest.m_maxPlayer)); request.SetPlacementId(createSessionOnQueueRequest.m_placementId.c_str()); AZ_TracePrintf(AWSGameLiftCreateSessionOnQueueActivityName, @@ -79,7 +79,7 @@ namespace AWSGameLift auto gameliftCreateSessionOnQueueRequest = azrtti_cast(&createSessionRequest); - return gameliftCreateSessionOnQueueRequest && gameliftCreateSessionOnQueueRequest->m_maxPlayer >= 0 && + return gameliftCreateSessionOnQueueRequest && !gameliftCreateSessionOnQueueRequest->m_queueName.empty() && !gameliftCreateSessionOnQueueRequest->m_placementId.empty(); } } // namespace CreateSessionOnQueueActivity diff --git a/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftJoinSessionActivity.cpp b/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftJoinSessionActivity.cpp index d54907aa71..a47e59255f 100644 --- a/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftJoinSessionActivity.cpp +++ b/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftJoinSessionActivity.cpp @@ -47,7 +47,7 @@ namespace AWSGameLift //sessionConnectionConfig.m_dnsName = createPlayerSessionResult.GetPlayerSession().GetDnsName().c_str(); sessionConnectionConfig.m_ipAddress = createPlayerSessionResult.GetPlayerSession().GetIpAddress().c_str(); sessionConnectionConfig.m_playerSessionId = createPlayerSessionResult.GetPlayerSession().GetPlayerSessionId().c_str(); - sessionConnectionConfig.m_port = createPlayerSessionResult.GetPlayerSession().GetPort(); + sessionConnectionConfig.m_port = static_cast(createPlayerSessionResult.GetPlayerSession().GetPort()); AZ_TracePrintf(AWSGameLiftJoinSessionActivityName, "Built SessionConnectionConfig with IpAddress=%s, PlayerSessionId=%s and Port=%d", diff --git a/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftSearchSessionsActivity.cpp b/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftSearchSessionsActivity.cpp index ec592735ae..3d29fa2b71 100644 --- a/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftSearchSessionsActivity.cpp +++ b/Gems/AWSGameLift/Code/AWSGameLiftClient/Source/Activity/AWSGameLiftSearchSessionsActivity.cpp @@ -99,7 +99,7 @@ namespace AWSGameLift session.m_currentPlayer = gameSession.GetCurrentPlayerSessionCount(); session.m_ipAddress = gameSession.GetIpAddress().c_str(); session.m_maxPlayer = gameSession.GetMaximumPlayerSessionCount(); - session.m_port = gameSession.GetPort(); + session.m_port = static_cast(gameSession.GetPort()); session.m_sessionId = gameSession.GetGameSessionId().c_str(); session.m_sessionName = gameSession.GetName().c_str(); session.m_status = AWSGameLiftSessionStatusNames[(int)gameSession.GetStatus()]; diff --git a/Gems/AWSGameLift/Code/AWSGameLiftClient/Tests/Activity/AWSGameLiftCreateSessionActivityTest.cpp b/Gems/AWSGameLift/Code/AWSGameLiftClient/Tests/Activity/AWSGameLiftCreateSessionActivityTest.cpp index b1601e248a..70dcdba1af 100644 --- a/Gems/AWSGameLift/Code/AWSGameLiftClient/Tests/Activity/AWSGameLiftCreateSessionActivityTest.cpp +++ b/Gems/AWSGameLift/Code/AWSGameLiftClient/Tests/Activity/AWSGameLiftCreateSessionActivityTest.cpp @@ -44,7 +44,7 @@ TEST_F(AWSGameLiftCreateSessionActivityTest, ValidateCreateSessionRequest_CallWi TEST_F(AWSGameLiftCreateSessionActivityTest, ValidateCreateSessionRequest_CallWithNegativeMaxPlayer_GetFalseResult) { AWSGameLiftCreateSessionRequest request; - request.m_maxPlayer = -1; + request.m_maxPlayer = std::numeric_limits::max(); auto result = CreateSessionActivity::ValidateCreateSessionRequest(request); EXPECT_FALSE(result); diff --git a/Gems/AWSGameLift/Code/AWSGameLiftClient/Tests/Activity/AWSGameLiftCreateSessionOnQueueActivityTest.cpp b/Gems/AWSGameLift/Code/AWSGameLiftClient/Tests/Activity/AWSGameLiftCreateSessionOnQueueActivityTest.cpp index 529179b1fb..8a785d8007 100644 --- a/Gems/AWSGameLift/Code/AWSGameLiftClient/Tests/Activity/AWSGameLiftCreateSessionOnQueueActivityTest.cpp +++ b/Gems/AWSGameLift/Code/AWSGameLiftClient/Tests/Activity/AWSGameLiftCreateSessionOnQueueActivityTest.cpp @@ -40,7 +40,7 @@ TEST_F(AWSGameLiftCreateSessionOnQueueActivityTest, ValidateCreateSessionOnQueue TEST_F(AWSGameLiftCreateSessionOnQueueActivityTest, ValidateCreateSessionOnQueueRequest_CallWithNegativeMaxPlayer_GetFalseResult) { AWSGameLiftCreateSessionOnQueueRequest request; - request.m_maxPlayer = -1; + request.m_maxPlayer = std::numeric_limits::max(); auto result = CreateSessionOnQueueActivity::ValidateCreateSessionOnQueueRequest(request); EXPECT_FALSE(result); diff --git a/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/AWSGameLiftServerManager.cpp b/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/AWSGameLiftServerManager.cpp index f98ae7b6f1..94d6a7dac1 100644 --- a/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/AWSGameLiftServerManager.cpp +++ b/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/AWSGameLiftServerManager.cpp @@ -70,7 +70,7 @@ namespace AWSGameLift sessionConfig.m_ipAddress = gameSession.GetIpAddress().c_str(); sessionConfig.m_maxPlayer = gameSession.GetMaximumPlayerSessionCount(); sessionConfig.m_sessionName = gameSession.GetName().c_str(); - sessionConfig.m_port = gameSession.GetPort(); + sessionConfig.m_port = static_cast(gameSession.GetPort()); sessionConfig.m_status = AWSGameLiftSessionStatusNames[(int)gameSession.GetStatus()]; AZ_TracePrintf(AWSGameLiftServerManagerName, diff --git a/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/GameLiftServerSDKWrapper.cpp b/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/GameLiftServerSDKWrapper.cpp index ae9b868f42..7e216f33be 100644 --- a/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/GameLiftServerSDKWrapper.cpp +++ b/Gems/AWSGameLift/Code/AWSGameLiftServer/Source/GameLiftServerSDKWrapper.cpp @@ -10,8 +10,6 @@ #include -#pragma warning(disable : 4996) - namespace AWSGameLift { Aws::GameLift::GenericOutcome GameLiftServerSDKWrapper::AcceptPlayerSession(const std::string& playerSessionId) @@ -56,7 +54,13 @@ namespace AWSGameLift } char buffer[50]; - strftime(buffer, sizeof(buffer), "%FT%TZ", gmtime(&terminationTime)); + tm time; +#if AZ_TRAIT_USE_SECURE_CRT_FUNCTIONS + gmtime_s(&time, &terminationTime); +#else + time = *gmtime(&terminationTime); +#endif + strftime(buffer, sizeof(buffer), "%FT%TZ", &time); return AZStd::string(buffer); } diff --git a/Gems/AWSMetrics/Code/Source/ClientConfiguration.cpp b/Gems/AWSMetrics/Code/Source/ClientConfiguration.cpp index eabac5a5c3..13cbf924c3 100644 --- a/Gems/AWSMetrics/Code/Source/ClientConfiguration.cpp +++ b/Gems/AWSMetrics/Code/Source/ClientConfiguration.cpp @@ -99,7 +99,7 @@ namespace AWSMetrics AZ::s64 ClientConfiguration::GetMaxQueueSizeInBytes() const { - return m_maxQueueSizeInMb * 1000000; + return static_cast(m_maxQueueSizeInMb * 1000000); } AZ::s64 ClientConfiguration::GetQueueFlushPeriodInSeconds() const diff --git a/Gems/AWSMetrics/Code/Source/MetricsEventBuilder.cpp b/Gems/AWSMetrics/Code/Source/MetricsEventBuilder.cpp index b7d9163fa9..743a8c5849 100644 --- a/Gems/AWSMetrics/Code/Source/MetricsEventBuilder.cpp +++ b/Gems/AWSMetrics/Code/Source/MetricsEventBuilder.cpp @@ -15,9 +15,6 @@ #include -#pragma warning(disable : 4996) - - namespace AWSMetrics { MetricsEventBuilder::MetricsEventBuilder() @@ -58,7 +55,13 @@ namespace AWSMetrics time_t now; time(&now); char buffer[50]; - strftime(buffer, sizeof(buffer), "%FT%TZ", gmtime(&now)); + tm time; +#if AZ_TRAIT_USE_SECURE_CRT_FUNCTIONS + gmtime_s(&time, &now); +#else + time = *gmtime(&now); +#endif + strftime(buffer, sizeof(buffer), "%FT%TZ", &time); m_currentMetricsEvent.AddAttribute(MetricsAttribute(AwsMetricsAttributeKeyEventTimestamp, AZStd::string(buffer))); } diff --git a/Gems/AWSMetrics/cdk/aws_metrics/batch_analytics.py b/Gems/AWSMetrics/cdk/aws_metrics/batch_analytics.py index 5be6562982..8398113bc4 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/batch_analytics.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/batch_analytics.py @@ -96,9 +96,9 @@ class BatchAnalytics: ), athena.CfnNamedQuery( self._stack, - id='NamedQuery-NewUsersLastMonth', + id='NamedQuery-LoginLastMonth', name=resource_name_sanitizer.sanitize_resource_name( - f'{self._stack.stack_name}-NamedQuery-NewUsersLastMonth', 'athena_named_query'), + f'{self._stack.stack_name}-NamedQuery-LoginLastMonth', 'athena_named_query'), database=self._events_database_name, query_string="WITH detail AS (" "SELECT date_trunc('month', date(date_parse(CONCAT(year, '-', month, '-', day), '%Y-%m-%d'))) as event_month, * " @@ -107,9 +107,9 @@ class BatchAnalytics: "date_trunc('month', event_month) as month, " "count(*) as new_accounts " "FROM detail " - "WHERE event_name = 'user_registration' " + "WHERE event_name = 'login' " "GROUP BY date_trunc('month', event_month)", - description='New users over the last month', + description='Total number of login events over the last month', work_group=self._athena_work_group.name ) ] diff --git a/Gems/AWSMetrics/cdk/aws_metrics/data_lake_integration.py b/Gems/AWSMetrics/cdk/aws_metrics/data_lake_integration.py index aaaf03b1fa..e47b1a95c2 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/data_lake_integration.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/data_lake_integration.py @@ -50,8 +50,7 @@ class DataLakeIntegration: # a specific name here, only one customer can deploy the bucket successfully. self._analytics_bucket = s3.Bucket( self._stack, - id=f'AnalyticsBucket'.lower(), - bucket_name=resource_name_sanitizer.sanitize_resource_name( + id=resource_name_sanitizer.sanitize_resource_name( f'{self._stack.stack_name}-AnalyticsBucket'.lower(), 's3_bucket'), encryption=s3.BucketEncryption.S3_MANAGED, block_public_access=s3.BlockPublicAccess( @@ -68,6 +67,13 @@ class DataLakeIntegration: cfn_bucket = self._analytics_bucket.node.find_child('Resource') cfn_bucket.apply_removal_policy(core.RemovalPolicy.DESTROY) + analytics_bucket_output = core.CfnOutput( + self._stack, + id='AnalyticsBucketName', + description='Name of the S3 bucket for storing metrics event data', + export_name=f"{self._application_name}:AnalyticsBucket", + value=self._analytics_bucket.bucket_name) + def _create_events_database(self) -> None: """ Create the Glue database for metrics events. diff --git a/Gems/AWSMetrics/cdk/aws_metrics/real_time_data_processing.py b/Gems/AWSMetrics/cdk/aws_metrics/real_time_data_processing.py index 52fdcdc122..4ef9caa022 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/real_time_data_processing.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/real_time_data_processing.py @@ -182,7 +182,7 @@ class RealTimeDataProcessing: Generate the analytics processing lambda to send processed data to CloudWatch for visualization. """ analytics_processing_function_name = resource_name_sanitizer.sanitize_resource_name( - f'{self._stack.stack_name}-AnalyticsProcessingLambdaName', 'lambda_function') + f'{self._stack.stack_name}-AnalyticsProcessingLambda', 'lambda_function') self._analytics_processing_lambda_role = self._create_analytics_processing_lambda_role( analytics_processing_function_name ) diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/ColorChart.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/ColorChart.cpp index c6046bb5a2..0b06e00a9f 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/ColorChart.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/ColorChart.cpp @@ -76,9 +76,9 @@ namespace ImageProcessingAtom for (int r = 0; r < ePS_Red; ++r) { SColor col; - col.r = 255 * r / (ePS_Red); - col.g = 255 * g / (ePS_Green); - col.b = 255 * b / (ePS_Blue); + col.r = static_cast(255 * r / (ePS_Red)); + col.g = static_cast(255 * g / (ePS_Green)); + col.b = static_cast(255 * b / (ePS_Blue)); int l = 255 - (col.r * 3 + col.g * 6 + col.b) / 10; col.r = col.g = col.b = (unsigned char)l; m_mapping.push_back(col); diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/Cubemap.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/Cubemap.cpp index cd01d955d1..4f13c6f9bf 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/Cubemap.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/Cubemap.cpp @@ -191,7 +191,7 @@ namespace ImageProcessingAtom } //for each pixel in dst image, find it's location in src and copy the data from there - float halfSize = rectSize / 2; + float halfSize = static_cast(rectSize / 2); for (AZ::u32 row = 0; row < rectSize; row++) { for (AZ::u32 col = 0; col < rectSize; col++) @@ -201,8 +201,8 @@ namespace ImageProcessingAtom float dstY = halfSize - row - 0.5f; float srcX = dstX * mtx[0] + dstY * mtx[1]; float srcY = dstX * mtx[2] + dstY * mtx[3]; - AZ::u32 srcCol = srcX + halfSize; - AZ::u32 srcRow = halfSize - srcY; + AZ::u32 srcCol = static_cast(srcX + halfSize); + AZ::u32 srcRow = static_cast(halfSize - srcY); memcpy(&dstImageBuf[(row * rectSize + col) * bytePerPixel], &srcImageBuf[(srcRow * rectSize + srcCol) * bytePerPixel], bytePerPixel); @@ -464,7 +464,7 @@ namespace ImageProcessingAtom else { //transform the image - TransformImage(srcDir, dstDir, buf, tempBuf, sizePerPixel, faceSize); + TransformImage(srcDir, dstDir, buf, tempBuf, static_cast(sizePerPixel), faceSize); dstCubemap->SetFaceData(face, tempBuf, outSize); } } @@ -649,7 +649,7 @@ namespace ImageProcessingAtom preset.m_cubemapSetting->m_mipSlope, //MipAnglePerLevelScale, (int)preset.m_cubemapSetting->m_filter, //FilterType, CP_FILTER_TYPE_COSINE for diffuse cube preset.m_cubemapSetting->m_edgeFixup > 0 ? CP_FIXUP_PULL_LINEAR : CP_FIXUP_NONE, //FixupType, CP_FIXUP_PULL_LINEAR if FixupWidth> 0 - preset.m_cubemapSetting->m_edgeFixup, //FixupWidth, + static_cast(preset.m_cubemapSetting->m_edgeFixup), //FixupWidth, true, //bUseSolidAngle, 16, //GlossScale, 0, //GlossBias diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/FIR-Weights.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/FIR-Weights.cpp index a7689a86ba..170805aa57 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/FIR-Weights.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Converters/FIR-Weights.cpp @@ -17,7 +17,7 @@ namespace ImageProcessingAtom { float round(float x) { - return ((x) >= 0) ? floor((x) + 0.5) : ceil((x)-0.5); + return ((x) >= 0.f) ? floor((x) + 0.5f) : ceil((x) - 0.5f); } void calculateFilterRange(unsigned int srcFactor, int& srcFirst, int& srcLast, @@ -220,7 +220,7 @@ namespace ImageProcessingAtom /* normalize against the peak sumWeights, because the sums are not allowed to leave -32768/32767 */ fWeight = fWeight * nrmWeights; - iWeight = int(round(fWeight)); + iWeight = int(round(static_cast(fWeight))); /* find first nonzero */ if (stillzero && (iWeight == 0)) @@ -246,7 +246,7 @@ namespace ImageProcessingAtom /* add weight to table, interleaved sign */ for (n = 0; n < -numRepetitions; n++) { - *weightsPtr++ = sgnextend(n, -iWeight); + *weightsPtr++ = static_cast(sgnextend(n, -iWeight)); } } else @@ -254,7 +254,7 @@ namespace ImageProcessingAtom /* add weight to table */ for (n = 0; n < numRepetitions; n++) { - *weightsPtr++ = -iWeight; + *weightsPtr++ = static_cast(-iWeight); } } @@ -311,7 +311,7 @@ namespace ImageProcessingAtom for (n = 0, weightsPtr = weightsMem + (i - i0) * numRepetitions; n < numRepetitions; n++) { - *weightsPtr++ -= iWeight; + *weightsPtr++ -= static_cast(iWeight); } } } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.h index 0d6ac5d959..0df628e9cd 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.h @@ -94,3 +94,4 @@ namespace ImageProcessingAtom AZStd::vector> m_assetHandlers; }; }// namespace ImageProcessingAtom + diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageLoader/DdsLoader.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageLoader/DdsLoader.cpp index c1d2d7bf19..b9054a9911 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageLoader/DdsLoader.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageLoader/DdsLoader.cpp @@ -90,7 +90,7 @@ namespace ImageProcessingAtom for (i; i < ePixelFormat_Count; i++) { const PixelFormatInfo* info = CPixelFormats::GetInstance().GetPixelFormatInfo((EPixelFormat)i); - if (info->d3d10Format == dxgiFormat) + if (static_cast(info->d3d10Format) == dxgiFormat) { eFormat = (EPixelFormat)i; break; @@ -509,7 +509,7 @@ namespace ImageProcessingAtom for (i; i < ePixelFormat_Count; i++) { const PixelFormatInfo* info = CPixelFormats::GetInstance().GetPixelFormatInfo((EPixelFormat)i); - if (info->d3d10Format == dxgiFormat) + if (static_cast(info->d3d10Format) == dxgiFormat) { format = (EPixelFormat)i; break; diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageAssetProducer.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageAssetProducer.cpp index 0b0a241d40..c254d172ad 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageAssetProducer.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageAssetProducer.cpp @@ -97,8 +97,8 @@ namespace ImageProcessingAtom RHI::Format format = Utils::PixelFormatToRHIFormat(m_imageObject->GetPixelFormat(), m_imageObject->HasImageFlags(EIF_SRGBRead)); RHI::ImageBindFlags bindFlag = RHI::ImageBindFlags::ShaderRead; - RHI::ImageDescriptor imageDesc = RHI::ImageDescriptor::Create2DArray(bindFlag, imageWidth, imageHeight, arraySize, format); - imageDesc.m_mipLevels = m_imageObject->GetMipCount(); + RHI::ImageDescriptor imageDesc = RHI::ImageDescriptor::Create2DArray(bindFlag, imageWidth, imageHeight, static_cast(arraySize), format); + imageDesc.m_mipLevels = static_cast(m_imageObject->GetMipCount()); if (m_imageObject->HasImageFlags(EIF_Cubemap)) { imageDesc.m_isCubemap = true; @@ -227,7 +227,7 @@ namespace ImageProcessingAtom { RPI::ImageMipChainAssetCreator builder; uint32_t arraySize = m_imageObject->HasImageFlags(EIF_Cubemap) ? 6 : 1; - builder.Begin(chainAssetId, mipLevels, arraySize); + builder.Begin(chainAssetId, static_cast(mipLevels), static_cast(arraySize)); for (uint32_t mip = startMip; mip < startMip + mipLevels; mip++) { diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/PixelFormatInfo.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/PixelFormatInfo.h index 5f1cbf938a..ec1ec1bfaf 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/PixelFormatInfo.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/PixelFormatInfo.h @@ -52,7 +52,7 @@ namespace ImageProcessingAtom Result = ((intValue + 0x0FFFU + ((intValue >> 13U) & 1U)) >> 13U) & 0x7FFFU; } - h = (Result | Sign); + h = static_cast(Result | Sign); } operator float() const @@ -82,7 +82,7 @@ namespace ImageProcessingAtom } else // The value is zero { - Exponent = -112; + Exponent = static_cast(-112); } Result = ((h & 0x8000) << 16) | // Sign diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp index 3ac9c334c5..4b28fbe4ef 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp @@ -269,11 +269,11 @@ namespace UnitTest public: //helper function to save an image object to a file through QtImage - static void SaveImageToFile(const IImageObjectPtr imageObject, const AZStd::string imageName, AZ::u32 maxMipCnt = 100) + static void SaveImageToFile([[maybe_unused]] const IImageObjectPtr imageObject, [[maybe_unused]] const AZStd::string imageName, [[maybe_unused]] AZ::u32 maxMipCnt = 100) { #ifndef DEBUG_OUTPUT_IMAGES return; - #endif + #else if (imageObject == nullptr) { return; @@ -314,6 +314,7 @@ namespace UnitTest QImage qimage(imageBuf, width, height, pitch, QImage::Format_RGBA8888); qimage.save(filePath); } + #endif } static bool GetComparisonResult(IImageObjectPtr image1, IImageObjectPtr image2, QString& output) diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/temp/128x128_RGBA8.tga.streamingimage b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/temp/128x128_RGBA8.tga.streamingimage index b867b7cfb1..6826f2a76e 100644 Binary files a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/temp/128x128_RGBA8.tga.streamingimage and b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/TestAssets/temp/128x128_RGBA8.tga.streamingimage differ diff --git a/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/CCubeMapProcessor.cpp b/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/CCubeMapProcessor.cpp index fa861c739a..8a4d727e8c 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/CCubeMapProcessor.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/CCubeMapProcessor.cpp @@ -8,7 +8,7 @@ #include #include -#define CP_PI 3.14159265358979323846 +#define CP_PI 3.14159265358979323846f namespace ImageProcessingAtom @@ -259,10 +259,10 @@ namespace ImageProcessingAtom //get face idx and u, v texel coordinate in face VectToTexelCoord(a_XYZ, a_Surface[0].m_Width, &faceIdx, &u, &v ); - u = VM_MIN((int32)u, a_Surface[0].m_Width - 1); - v = VM_MIN((int32)v, a_Surface[0].m_Width - 1); + u = static_cast(VM_MIN((int32)u, a_Surface[0].m_Width - 1)); + v = static_cast(VM_MIN((int32)v, a_Surface[0].m_Width - 1)); - return( a_Surface[faceIdx].GetSurfaceTexelPtr(u, v) ); + return( a_Surface[faceIdx].GetSurfaceTexelPtr(static_cast(u), static_cast(v)) ); } //-------------------------------------------------------------------------------------- @@ -357,7 +357,7 @@ namespace ImageProcessingAtom VM_XPROD3_UNTYPED(xProdVect, edgeVect0, edgeVect1 ); texelArea += 0.5f * sqrt( VM_DOTPROD3_UNTYPED(xProdVect, xProdVect ) ); - return texelArea; + return static_cast(texelArea); } @@ -1130,7 +1130,7 @@ namespace ImageProcessingAtom // if p0 = 0 and p1 = 1, and d0 and d1 = 0, the interpolation reduces to // // p(t) = - 2t^3 + 3t^2 - fixupWeight = ((-2.0 * fixupFrac + 3.0) * fixupFrac * fixupFrac); + fixupWeight = ((-2.0f * fixupFrac + 3.0f) * fixupFrac * fixupFrac); } break; case CP_FIXUP_AVERAGE_LINEAR: @@ -1147,7 +1147,7 @@ namespace ImageProcessingAtom break; case CP_FIXUP_AVERAGE_HERMITE: { - fixupWeight = ((-2.0 * fixupFrac + 3.0) * fixupFrac * fixupFrac); + fixupWeight = ((-2.0f * fixupFrac + 3.0f) * fixupFrac * fixupFrac); //perform weighted average of edge tap value and current tap // fade off weight using hermite spline with distance from edge @@ -1538,7 +1538,7 @@ namespace ImageProcessingAtom // Find angle for which: cos(a) ^ cosinePower = epsilon const float epsilon = 0.000001f; float angle = acosf(powf(epsilon, 1.0f / cosinePower)); - angle *= 180.0f / (float)CP_PI; + angle *= 180.0f / CP_PI; angle *= 2.0f; return angle; @@ -1555,7 +1555,7 @@ namespace ImageProcessingAtom bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); - return float(bits) * 2.3283064365386963e-10; // float(bits) * 2^-32 + return float(bits) * 2.3283064365386963e-10f; // float(bits) * 2^-32 } inline void HammersleySequence(uint32 sampleIndex, uint32 sampleCount, float* vXi) @@ -1668,7 +1668,7 @@ namespace ImageProcessingAtom float mip = 0.5f * log2f(solidAngleSample / solidAngleTexel) + 1.0f; //determine surrounding mip levels - uint32 mipA = floor(mip); + uint32 mipA = static_cast(floor(mip)); uint32 mipB = mipA + 1; float lerp = 0.0f; VM_CLAMP(lerp, mip - mipA, 0.0f, 1.0f); @@ -1819,7 +1819,7 @@ namespace ImageProcessingAtom float filterAngle; //min angle a src texel can cover (in degrees) - srcTexelAngle = (180.0f / (float)CP_PI) * atan2f(1.0f, (float)a_SrcCubeMapWidth); + srcTexelAngle = (180.0f / CP_PI) * atan2f(1.0f, (float)a_SrcCubeMapWidth); //filter angle is 1/2 the cone angle filterAngle = a_FilterConeAngle / 2.0f; @@ -1870,7 +1870,7 @@ namespace ImageProcessingAtom const int32 dstSize = a_DstCubeMap[0].m_Width; //min angle a src texel can cover (in degrees) - const float srcTexelAngle = (180.0f / (float)CP_PI) * atan2f(1.0f, (float)srcSize); + const float srcTexelAngle = (180.0f / CP_PI) * atan2f(1.0f, (float)srcSize); //angle about center tap to define filter cone float filterAngle; @@ -1897,7 +1897,7 @@ namespace ImageProcessingAtom //dotProdThresh threshold based on cone angle to determine whether or not taps // reside within the cone angle - const float dotProdThresh = cosf( ((float)CP_PI / 180.0f) * filterAngle ); + const float dotProdThresh = cosf( (CP_PI / 180.0f) * filterAngle ); //thread progress m_ThreadProgress[a_ThreadIdx].m_StartFace = a_FaceIdxStart; @@ -2004,8 +2004,8 @@ namespace ImageProcessingAtom else if( a_FilterType == CP_FILTER_TYPE_ANGULAR_GAUSSIAN ) { //fit 3 standard deviations within angular extent of filter - CP_ITYPE stdDev = (a_FilterAngle * CP_PI / 180.0) / 3.0; - CP_ITYPE inv2Variance = 1.0 / (2.0 * stdDev * stdDev); + CP_ITYPE stdDev = (a_FilterAngle * CP_PI / 180.0f) / 3.0f; + CP_ITYPE inv2Variance = 1.0f / (2.0f * stdDev * stdDev); for(iLUTEntry=0; iLUTEntry>= (23 - 10); //assemble s10e5 number using logical operations - rawf16Data = (signVal << 15) | (exponent << 10) | mantissa; + rawf16Data = static_cast((signVal << 15) | (exponent << 10) | mantissa); //return re-assembled raw data as a 32 bit float return rawf16Data; @@ -386,7 +386,7 @@ namespace ImageProcessingAtom if (k < 3) //only apply gamma and scale to RGB channels { //degamma texel val, by raising to the power gamma - texelVal = pow(texelVal, a_Gamma); + texelVal = static_cast(pow(texelVal, a_Gamma)); //scale texel val in linear space (after degamma) texelVal *= a_Scale; @@ -514,7 +514,7 @@ namespace ImageProcessingAtom texelVal *= a_Scale; //apply gamma to texel val by raising the texelVal to the power of (1/gamma) - texelVal = pow(texelVal, 1.0f / a_Gamma); + texelVal = static_cast(pow(texelVal, 1.0f / a_Gamma)); } //write out texture value diff --git a/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/VectorMacros.h b/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/VectorMacros.h index c293cf1ac7..42ec07e02c 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/VectorMacros.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/External/CubeMapGen/VectorMacros.h @@ -18,9 +18,6 @@ //-------------------------------------------------------------------------------------- // Modified from original -//disable warning about doubles being converted down to float -#pragma warning (disable : 4244 ) - #define VM_LARGE_FLOAT 3.7e37f #define VM_MIN(a, b) (((a) < (b)) ? (a) : (b)) @@ -128,7 +125,7 @@ //normalize vectors #define VM_NORM3_UNTYPED(d, s) {double __idsq; __idsq=1.0/sqrt(VM_DOTPROD3_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; } -#define VM_NORM3_UNTYPED_F32(d, s) {float __idsq; __idsq=1.0/sqrt(VM_DOTPROD3_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; } +#define VM_NORM3_UNTYPED_F32(d, s) {float __idsq; __idsq=1.0f/sqrt(VM_DOTPROD3_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; } #define VM_NORM3(d, s) VM_NORM3_UNTYPED_F32(((float *)(d)), ((float *)(s))) #define VM_NORM4_UNTYPED(d, s) {double __idsq; __idsq=1.0/sqrt(VM_DOTPROD4_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; d[3]=s[3]*__idsq; } diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslCompiler.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslCompiler.cpp index cc42fac422..f5fb73182a 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslCompiler.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslCompiler.cpp @@ -211,11 +211,11 @@ namespace AZ case rapidjson::kNumberType: if (name == "cols") { - inputStructParams.m_variable.m_cols = itr2->value.GetInt(); + inputStructParams.m_variable.m_cols = static_cast(itr2->value.GetInt()); } else if (name == "rows") { - inputStructParams.m_variable.m_rows = itr2->value.GetInt(); + inputStructParams.m_variable.m_rows = static_cast(itr2->value.GetInt()); } else if (name == "semanticIndex") { @@ -304,7 +304,7 @@ namespace AZ case rapidjson::kNumberType: if (name == "cols") { - outputStructParams.m_variable.m_cols = itr2->value.GetInt(); + outputStructParams.m_variable.m_cols = static_cast(itr2->value.GetInt()); } else if (name == "semanticIndex") { diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/CommonTypes.h b/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/CommonTypes.h index d5e5c7132c..fd34251277 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/CommonTypes.h +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/CommonFiles/CommonTypes.h @@ -278,7 +278,7 @@ namespace AZ { AZ::Name m_nameId; uint32_t m_sizeInBytes = 0; - uint32_t m_space = -1; + uint32_t m_space = std::numeric_limits::max(); uint32_t m_registerId = RHI::UndefinedRegisterSlot; }; } // ShaderBuilder diff --git a/Gems/Atom/Asset/Shader/Code/Tests/McppBinderTests.cpp b/Gems/Atom/Asset/Shader/Code/Tests/McppBinderTests.cpp index 926f9b0a76..f1731c0501 100644 --- a/Gems/Atom/Asset/Shader/Code/Tests/McppBinderTests.cpp +++ b/Gems/Atom/Asset/Shader/Code/Tests/McppBinderTests.cpp @@ -32,7 +32,7 @@ namespace UnitTest { for (int bufferPos = 0, rollback = 0; bufferPos < (bufferSize - 1); ++bufferPos) { - const char value = 'a' + rollback++; + const char value = 'a' + static_cast(rollback++); buffer[bufferPos] = value; if (value == 'z') { diff --git a/Gems/Atom/Bootstrap/Code/CMakeLists.txt b/Gems/Atom/Bootstrap/Code/CMakeLists.txt index af09f3a288..1787af04ed 100644 --- a/Gems/Atom/Bootstrap/Code/CMakeLists.txt +++ b/Gems/Atom/Bootstrap/Code/CMakeLists.txt @@ -6,6 +6,8 @@ # # +ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Source/Platform/${PAL_PLATFORM_NAME}) + ly_add_target( NAME Atom_Bootstrap.Headers HEADERONLY NAMESPACE Gem @@ -21,9 +23,12 @@ ly_add_target( NAMESPACE Gem FILES_CMAKE bootstrap_files.cmake + ${pal_dir}/bootstrap_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake + PLATFORM_INCLUDE_FILES INCLUDE_DIRECTORIES PRIVATE Source + ${pal_dir} PUBLIC Include BUILD_DEPENDENCIES diff --git a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp index f9d6ac63f7..11758138e0 100644 --- a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp +++ b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp @@ -38,6 +38,10 @@ #include #include +#include +#include + +AZ_CVAR(AZ::CVarFixedString, r_default_pipeline_name, AZ_TRAIT_BOOTSTRAPSYSTEMCOMPONENT_PIPELINE_NAME, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Default Render pipeline name"); namespace AZ { @@ -50,8 +54,7 @@ namespace AZ if (SerializeContext* serialize = azrtti_cast(context)) { serialize->Class() - ->Version(0) - ->Field("DefaultRenderPipelineAssetFile", &BootstrapSystemComponent::m_defaultPipelineAssetPath) + ->Version(1) ; if (EditContext* ec = serialize->GetEditContext()) @@ -60,8 +63,6 @@ namespace AZ ->ClassElement(Edit::ClassElements::EditorData, "") ->Attribute(Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) ->Attribute(Edit::Attributes::AutoExpand, true) - ->DataElement(Edit::UIHandlers::Default, &BootstrapSystemComponent::m_defaultPipelineAssetPath, "Default RenderPipeline Asset", - "The asset file path of default render pipeline for default window") ; } } @@ -314,13 +315,15 @@ namespace AZ // Create a render pipeline from the specified asset for the window context and add the pipeline to the scene. // When running with no Asset Processor (for example in release), CompileAssetSync will return AssetStatus_Unknown. AzFramework::AssetSystem::AssetStatus status = AzFramework::AssetSystem::AssetStatus_Unknown; - AzFramework::AssetSystemRequestBus::BroadcastResult( - status, &AzFramework::AssetSystemRequestBus::Events::CompileAssetSync, m_defaultPipelineAssetPath); - AZ_Assert(status == AzFramework::AssetSystem::AssetStatus_Compiled || status == AzFramework::AssetSystem::AssetStatus_Unknown, "Could not compile the default render pipeline at '%s'", m_defaultPipelineAssetPath.c_str()); + const AZ::CVarFixedString pipelineName = static_cast(r_default_pipeline_name); + AzFramework::AssetSystemRequestBus::BroadcastResult(status, &AzFramework::AssetSystemRequestBus::Events::CompileAssetSync, pipelineName.data()); + + AZ_Assert(status == AzFramework::AssetSystem::AssetStatus_Compiled || status == AzFramework::AssetSystem::AssetStatus_Unknown, "Could not compile the default render pipeline at '%s'", pipelineName.c_str()); - Data::Asset pipelineAsset = RPI::AssetUtils::LoadAssetByProductPath(m_defaultPipelineAssetPath.c_str(), RPI::AssetUtils::TraceLevel::Error); + Data::Asset pipelineAsset = RPI::AssetUtils::LoadAssetByProductPath(pipelineName.data(), RPI::AssetUtils::TraceLevel::Error); RPI::RenderPipelineDescriptor renderPipelineDescriptor = *RPI::GetDataFromAnyAsset(pipelineAsset); renderPipelineDescriptor.m_name = AZStd::string::format("%s_%i", renderPipelineDescriptor.m_name.c_str(), viewportContext->GetId()); + if (!scene->GetRenderPipeline(AZ::Name(renderPipelineDescriptor.m_name))) { RPI::RenderPipelinePtr renderPipeline = RPI::RenderPipeline::CreateRenderPipelineForWindow(renderPipelineDescriptor, *viewportContext->GetWindowContext().get()); diff --git a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.h b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.h index 142b2d8769..bd5d417b8f 100644 --- a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.h +++ b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.h @@ -112,10 +112,7 @@ namespace AZ // The id of the render pipeline created by this component RPI::RenderPipelineId m_renderPipelineId; - - // Variables which are system component configuration - AZStd::string m_defaultPipelineAssetPath = "passes/MainRenderPipeline.azasset"; - + // Save a reference to the image created by the BRDF pipeline so it doesn't get auto deleted if it's ref count goes to zero // For example, if we delete all the passes, we won't have to recreate the BRDF pipeline to recreate the BRDF texture Data::Instance m_brdfTexture; diff --git a/Gems/RADTelemetry/Code/Source/Platform/Windows/RADTelemetry_Traits_Platform.h b/Gems/Atom/Bootstrap/Code/Source/Platform/Android/BootstrapSystemComponent_Traits_Platform.h similarity index 69% rename from Gems/RADTelemetry/Code/Source/Platform/Windows/RADTelemetry_Traits_Platform.h rename to Gems/Atom/Bootstrap/Code/Source/Platform/Android/BootstrapSystemComponent_Traits_Platform.h index 8b524df127..da63106e29 100644 --- a/Gems/RADTelemetry/Code/Source/Platform/Windows/RADTelemetry_Traits_Platform.h +++ b/Gems/Atom/Bootstrap/Code/Source/Platform/Android/BootstrapSystemComponent_Traits_Platform.h @@ -5,6 +5,5 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#pragma once -#define AZ_TRAIT_RAD_TELEMETRY_OPEN_FLAGS TMOF_INIT_NETWORKING +#define AZ_TRAIT_BOOTSTRAPSYSTEMCOMPONENT_PIPELINE_NAME "passes/LowEndRenderPipeline.azasset" diff --git a/Gems/RADTelemetry/Code/Source/Platform/Android/platform_android_files.cmake b/Gems/Atom/Bootstrap/Code/Source/Platform/Android/bootstrap_android_files.cmake similarity index 82% rename from Gems/RADTelemetry/Code/Source/Platform/Android/platform_android_files.cmake rename to Gems/Atom/Bootstrap/Code/Source/Platform/Android/bootstrap_android_files.cmake index 6e7a9dd5eb..bae11b561e 100644 --- a/Gems/RADTelemetry/Code/Source/Platform/Android/platform_android_files.cmake +++ b/Gems/Atom/Bootstrap/Code/Source/Platform/Android/bootstrap_android_files.cmake @@ -7,5 +7,6 @@ # set(FILES - RADTelemetry_Traits_Platform.h + BootstrapSystemComponent_Traits_Platform.h ) + diff --git a/Gems/RADTelemetry/Code/Source/Platform/Android/RADTelemetry_Traits_Platform.h b/Gems/Atom/Bootstrap/Code/Source/Platform/Linux/BootstrapSystemComponent_Traits_Platform.h similarity index 69% rename from Gems/RADTelemetry/Code/Source/Platform/Android/RADTelemetry_Traits_Platform.h rename to Gems/Atom/Bootstrap/Code/Source/Platform/Linux/BootstrapSystemComponent_Traits_Platform.h index 8b524df127..d467de5e53 100644 --- a/Gems/RADTelemetry/Code/Source/Platform/Android/RADTelemetry_Traits_Platform.h +++ b/Gems/Atom/Bootstrap/Code/Source/Platform/Linux/BootstrapSystemComponent_Traits_Platform.h @@ -5,6 +5,5 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#pragma once -#define AZ_TRAIT_RAD_TELEMETRY_OPEN_FLAGS TMOF_INIT_NETWORKING +#define AZ_TRAIT_BOOTSTRAPSYSTEMCOMPONENT_PIPELINE_NAME "passes/MainRenderPipeline.azasset" diff --git a/Gems/RADTelemetry/Code/Source/Platform/Mac/platform_mac_files.cmake b/Gems/Atom/Bootstrap/Code/Source/Platform/Linux/bootstrap_linux_files.cmake similarity index 82% rename from Gems/RADTelemetry/Code/Source/Platform/Mac/platform_mac_files.cmake rename to Gems/Atom/Bootstrap/Code/Source/Platform/Linux/bootstrap_linux_files.cmake index 6e7a9dd5eb..bae11b561e 100644 --- a/Gems/RADTelemetry/Code/Source/Platform/Mac/platform_mac_files.cmake +++ b/Gems/Atom/Bootstrap/Code/Source/Platform/Linux/bootstrap_linux_files.cmake @@ -7,5 +7,6 @@ # set(FILES - RADTelemetry_Traits_Platform.h + BootstrapSystemComponent_Traits_Platform.h ) + diff --git a/Gems/RADTelemetry/Code/Source/Platform/Linux/RADTelemetry_Traits_Platform.h b/Gems/Atom/Bootstrap/Code/Source/Platform/Mac/BootstrapSystemComponent_Traits_Platform.h similarity index 69% rename from Gems/RADTelemetry/Code/Source/Platform/Linux/RADTelemetry_Traits_Platform.h rename to Gems/Atom/Bootstrap/Code/Source/Platform/Mac/BootstrapSystemComponent_Traits_Platform.h index 8b524df127..d467de5e53 100644 --- a/Gems/RADTelemetry/Code/Source/Platform/Linux/RADTelemetry_Traits_Platform.h +++ b/Gems/Atom/Bootstrap/Code/Source/Platform/Mac/BootstrapSystemComponent_Traits_Platform.h @@ -5,6 +5,5 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#pragma once -#define AZ_TRAIT_RAD_TELEMETRY_OPEN_FLAGS TMOF_INIT_NETWORKING +#define AZ_TRAIT_BOOTSTRAPSYSTEMCOMPONENT_PIPELINE_NAME "passes/MainRenderPipeline.azasset" diff --git a/Gems/RADTelemetry/Code/Source/Platform/Windows/platform_windows_files.cmake b/Gems/Atom/Bootstrap/Code/Source/Platform/Mac/bootstrap_mac_files.cmake similarity index 82% rename from Gems/RADTelemetry/Code/Source/Platform/Windows/platform_windows_files.cmake rename to Gems/Atom/Bootstrap/Code/Source/Platform/Mac/bootstrap_mac_files.cmake index 6e7a9dd5eb..bae11b561e 100644 --- a/Gems/RADTelemetry/Code/Source/Platform/Windows/platform_windows_files.cmake +++ b/Gems/Atom/Bootstrap/Code/Source/Platform/Mac/bootstrap_mac_files.cmake @@ -7,5 +7,6 @@ # set(FILES - RADTelemetry_Traits_Platform.h + BootstrapSystemComponent_Traits_Platform.h ) + diff --git a/Gems/RADTelemetry/Code/Source/Platform/Mac/RADTelemetry_Traits_Platform.h b/Gems/Atom/Bootstrap/Code/Source/Platform/Windows/BootstrapSystemComponent_Traits_Platform.h similarity index 69% rename from Gems/RADTelemetry/Code/Source/Platform/Mac/RADTelemetry_Traits_Platform.h rename to Gems/Atom/Bootstrap/Code/Source/Platform/Windows/BootstrapSystemComponent_Traits_Platform.h index 8b524df127..d467de5e53 100644 --- a/Gems/RADTelemetry/Code/Source/Platform/Mac/RADTelemetry_Traits_Platform.h +++ b/Gems/Atom/Bootstrap/Code/Source/Platform/Windows/BootstrapSystemComponent_Traits_Platform.h @@ -5,6 +5,5 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#pragma once -#define AZ_TRAIT_RAD_TELEMETRY_OPEN_FLAGS TMOF_INIT_NETWORKING +#define AZ_TRAIT_BOOTSTRAPSYSTEMCOMPONENT_PIPELINE_NAME "passes/MainRenderPipeline.azasset" diff --git a/Gems/Atom/Bootstrap/Code/Source/Platform/Windows/bootstrap_windows_files.cmake b/Gems/Atom/Bootstrap/Code/Source/Platform/Windows/bootstrap_windows_files.cmake new file mode 100644 index 0000000000..bae11b561e --- /dev/null +++ b/Gems/Atom/Bootstrap/Code/Source/Platform/Windows/bootstrap_windows_files.cmake @@ -0,0 +1,12 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +set(FILES + BootstrapSystemComponent_Traits_Platform.h +) + diff --git a/Gems/Atom/Bootstrap/Code/Source/Platform/iOS/BootstrapSystemComponent_Traits_Platform.h b/Gems/Atom/Bootstrap/Code/Source/Platform/iOS/BootstrapSystemComponent_Traits_Platform.h new file mode 100644 index 0000000000..da63106e29 --- /dev/null +++ b/Gems/Atom/Bootstrap/Code/Source/Platform/iOS/BootstrapSystemComponent_Traits_Platform.h @@ -0,0 +1,9 @@ +/* + * 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 + * + */ + +#define AZ_TRAIT_BOOTSTRAPSYSTEMCOMPONENT_PIPELINE_NAME "passes/LowEndRenderPipeline.azasset" diff --git a/Gems/Atom/Bootstrap/Code/Source/Platform/iOS/bootstrap_ios_files.cmake b/Gems/Atom/Bootstrap/Code/Source/Platform/iOS/bootstrap_ios_files.cmake new file mode 100644 index 0000000000..bae11b561e --- /dev/null +++ b/Gems/Atom/Bootstrap/Code/Source/Platform/iOS/bootstrap_ios_files.cmake @@ -0,0 +1,12 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +set(FILES + BootstrapSystemComponent_Traits_Platform.h +) + diff --git a/Gems/Atom/Feature/Common/Assets/Config/Platform/Android/Vulkan/PlatformLimits.azasset b/Gems/Atom/Feature/Common/Assets/Config/Platform/Android/Vulkan/PlatformLimits.azasset deleted file mode 100644 index 37becd9eef..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Config/Platform/Android/Vulkan/PlatformLimits.azasset +++ /dev/null @@ -1,11 +0,0 @@ -{ - "Type": "JsonSerialization", - "Version": 0, - "ClassName": "PlatformLimits", - "ClassData": { - "m_platformLimitsDescriptor": - { - "$type": "Vulkan::PlatformLimitsDescriptor" - } - } -} diff --git a/Gems/Atom/Feature/Common/Assets/Config/Platform/Linux/Vulkan/PlatformLimits.azasset b/Gems/Atom/Feature/Common/Assets/Config/Platform/Linux/Vulkan/PlatformLimits.azasset deleted file mode 100644 index 37becd9eef..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Config/Platform/Linux/Vulkan/PlatformLimits.azasset +++ /dev/null @@ -1,11 +0,0 @@ -{ - "Type": "JsonSerialization", - "Version": 0, - "ClassName": "PlatformLimits", - "ClassData": { - "m_platformLimitsDescriptor": - { - "$type": "Vulkan::PlatformLimitsDescriptor" - } - } -} diff --git a/Gems/Atom/Feature/Common/Assets/Config/Platform/Mac/Metal/PlatformLimits.azasset b/Gems/Atom/Feature/Common/Assets/Config/Platform/Mac/Metal/PlatformLimits.azasset deleted file mode 100644 index 573862cc40..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Config/Platform/Mac/Metal/PlatformLimits.azasset +++ /dev/null @@ -1,12 +0,0 @@ -{ - "Type": "JsonSerialization", - "Version": 0, - "ClassName": "PlatformLimits", - "ClassData": { - "m_platformLimitsDescriptor": - { - "$type": "Metal::PlatformLimitsDescriptor" - } - } -} - diff --git a/Gems/Atom/Feature/Common/Assets/Config/Platform/Windows/DX12/PlatformLimits.azasset b/Gems/Atom/Feature/Common/Assets/Config/Platform/Windows/DX12/PlatformLimits.azasset deleted file mode 100644 index 3c88544e62..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Config/Platform/Windows/DX12/PlatformLimits.azasset +++ /dev/null @@ -1,18 +0,0 @@ -{ - "Type": "JsonSerialization", - "Version": 0, - "ClassName": "PlatformLimits", - "ClassData": { - "m_platformLimitsDescriptor": - { - "$type": "DX12::PlatformLimitsDescriptor", - - "m_descriptorHeapLimits": { - "DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV": [1000000, 1000000], - "DESCRIPTOR_HEAP_TYPE_SAMPLER": [2048, 2048], - "DESCRIPTOR_HEAP_TYPE_RTV": [2048, 0], - "DESCRIPTOR_HEAP_TYPE_DSV": [2048, 0] - } - } - } -} diff --git a/Gems/Atom/Feature/Common/Assets/Config/Platform/Windows/Vulkan/PlatformLimits.azasset b/Gems/Atom/Feature/Common/Assets/Config/Platform/Windows/Vulkan/PlatformLimits.azasset deleted file mode 100644 index 37becd9eef..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Config/Platform/Windows/Vulkan/PlatformLimits.azasset +++ /dev/null @@ -1,11 +0,0 @@ -{ - "Type": "JsonSerialization", - "Version": 0, - "ClassName": "PlatformLimits", - "ClassData": { - "m_platformLimitsDescriptor": - { - "$type": "Vulkan::PlatformLimitsDescriptor" - } - } -} diff --git a/Gems/Atom/Feature/Common/Assets/Config/Platform/iOS/Metal/PlatformLimits.azasset b/Gems/Atom/Feature/Common/Assets/Config/Platform/iOS/Metal/PlatformLimits.azasset deleted file mode 100644 index 4556073118..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Config/Platform/iOS/Metal/PlatformLimits.azasset +++ /dev/null @@ -1,12 +0,0 @@ -{ - "Type": "JsonSerialization", - "Version": 0, - "ClassName": "PlatformLimits", - "ClassData": { - "m_platformLimitsDescriptor": - { - "$type": "Metal::PlatformLimitsDescriptor" - } - } -} - diff --git a/Gems/Atom/Feature/Common/Assets/Passes/LowEndRenderPipeline.azasset b/Gems/Atom/Feature/Common/Assets/Passes/LowEndRenderPipeline.azasset new file mode 100644 index 0000000000..fd0c9bd0ed --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Passes/LowEndRenderPipeline.azasset @@ -0,0 +1,15 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "RenderPipelineDescriptor", + "ClassData": { + "Name": "LowEndPipeline", + "MainViewTag": "MainCamera", + "RootPassTemplate": "LowEndPipelineTemplate", + "RenderSettings": { + "MultisampleState": { + "samples": 1 + } + } + } +} diff --git a/Gems/Atom/Feature/Common/Assets/Scripts/material_find_overrides_demo.lua b/Gems/Atom/Feature/Common/Assets/Scripts/material_find_overrides_demo.lua index dda3974043..41df35e355 100644 --- a/Gems/Atom/Feature/Common/Assets/Scripts/material_find_overrides_demo.lua +++ b/Gems/Atom/Feature/Common/Assets/Scripts/material_find_overrides_demo.lua @@ -66,20 +66,20 @@ function FindMaterialAssignmentTest:OnActivate() end function FindMaterialAssignmentTest:UpdateFactor(assignmentId) - local propertyName = Name("baseColor.factor") + local propertyName = "baseColor.factor" local propertyValue = math.random() MaterialComponentRequestBus.Event.SetPropertyOverride(self.entityId, assignmentId, propertyName, propertyValue); end function FindMaterialAssignmentTest:UpdateColor(assignmentId, color) - local propertyName = Name("baseColor.color") + local propertyName = "baseColor.color" local propertyValue = color MaterialComponentRequestBus.Event.SetPropertyOverride(self.entityId, assignmentId, propertyName, propertyValue); end function FindMaterialAssignmentTest:UpdateTexture(assignmentId) if (#self.Properties.Textures > 0) then - local propertyName = Name("baseColor.textureMap") + local propertyName = "baseColor.textureMap" local textureName = self.Properties.Textures[ math.random( #self.Properties.Textures ) ] Debug.Log(textureName) local textureAssetId = AssetCatalogRequestBus.Broadcast.GetAssetIdByPath(textureName, Uuid(), false) diff --git a/Gems/Atom/Feature/Common/Assets/Scripts/material_property_overrides_demo.lua b/Gems/Atom/Feature/Common/Assets/Scripts/material_property_overrides_demo.lua index 685fd8310b..0495dccbc0 100644 --- a/Gems/Atom/Feature/Common/Assets/Scripts/material_property_overrides_demo.lua +++ b/Gems/Atom/Feature/Common/Assets/Scripts/material_property_overrides_demo.lua @@ -64,20 +64,20 @@ function PropertyOverrideTest:OnActivate() end function PropertyOverrideTest:UpdateFactor(assignmentId) - local propertyName = Name("baseColor.factor") + local propertyName = "baseColor.factor" local propertyValue = math.random() MaterialComponentRequestBus.Event.SetPropertyOverride(self.entityId, assignmentId, propertyName, propertyValue); end function PropertyOverrideTest:UpdateColor(assignmentId, color) - local propertyName = Name("baseColor.color") + local propertyName = "baseColor.color" local propertyValue = color MaterialComponentRequestBus.Event.SetPropertyOverride(self.entityId, assignmentId, propertyName, propertyValue); end function PropertyOverrideTest:UpdateTexture(assignmentId) if (#self.Properties.Textures > 0) then - local propertyName = Name("baseColor.textureMap") + local propertyName = "baseColor.textureMap" local textureName = self.Properties.Textures[ math.random( #self.Properties.Textures ) ] Debug.Log(textureName) local textureAssetId = AssetCatalogRequestBus.Broadcast.GetAssetIdByPath(textureName, Uuid(), false) diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PostProcessing/Aces.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PostProcessing/Aces.azsli index f81a8cdf37..b7a6c63dc2 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PostProcessing/Aces.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PostProcessing/Aces.azsli @@ -75,6 +75,8 @@ UNDISCLOSED. //////////////////////////////////////////////////////////////////////////////// // Constants +#pragma once + #include static const float HALF_MAX = 65504.0f; @@ -90,7 +92,8 @@ static const float DIM_SURROUND_GAMMA = 0.9811; enum class ShaperType { ShaperLinear, - ShaperLog2 + ShaperLog2, + PqSmpteSt2084, }; //////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PostProcessing/Shapers.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PostProcessing/Shapers.azsli new file mode 100644 index 0000000000..a101867736 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/PostProcessing/Shapers.azsli @@ -0,0 +1,52 @@ +/* + * 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 + +// Perceptual quantizer coefficients +static const float PqM1 = 1305.0 / 8192.0; +static const float PqM2 = 2533.0 / 32.0; +static const float PqC1 = 102.0 / 128.0; +static const float PqC2 = 2413.0 / 128.0; +static const float PqC3 = 2392.0 / 128.0; +static const float PqMaxNits = 10000.0; + +float3 ShaperToLinear(float3 shaperColor, ShaperType shaperType, float shaperBias, float shaperScale) +{ + // Apply the inverse of the shaper function to give the color in the working color space + switch (shaperType) + { + case ShaperType::ShaperLinear: + return (shaperColor - shaperBias) / shaperScale; + case ShaperType::ShaperLog2: + return pow(2.0, (shaperColor - shaperBias) / shaperScale); + case ShaperType::PqSmpteSt2084: + shaperColor = min(shaperColor, 1.0); + return PqMaxNits * pow(max(pow(shaperColor, 1.0 / PqM2) - PqC1, 0.0) / (PqC2 - PqC3 * pow(shaperColor, 1.0 / PqM2)), 1.0 / PqM1); + } + return shaperColor; +} + +float3 LinearToShaper(float3 linearColor, ShaperType shaperType, float shaperBias, float shaperScale) +{ + // Convert from working color space to lut coordinates by applying the shaper function + switch (shaperType) + { + case ShaperType::ShaperLinear: + return linearColor * shaperScale + shaperBias; + case ShaperType::ShaperLog2: + return log2(linearColor) * shaperScale + shaperBias; + case ShaperType::PqSmpteSt2084: + linearColor = min(linearColor, PqMaxNits); + linearColor = linearColor / PqMaxNits; + return pow((PqC1 + PqC2 * pow(linearColor, PqM1)) / (1.0 + PqC3 * pow(linearColor, PqM1)), PqM2); + } + return linearColor; +} diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ApplyShaperLookupTable.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ApplyShaperLookupTable.azsl index a180b09630..10d2eb1179 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ApplyShaperLookupTable.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/ApplyShaperLookupTable.azsl @@ -11,9 +11,7 @@ #include #include #include - -static const int SHAPER_LINEAR = 0; -static const int SHAPER_LOG2 = 1; +#include ShaderResourceGroup PassSrg : SRG_PerPass { @@ -41,36 +39,22 @@ PSOutput MainPS(VSOutput IN) float2 uvCoord = float2(IN.m_texCoord.x, IN.m_texCoord.y); float3 color = PassSrg::m_colorTexture.Sample(PassSrg::LinearSampler, uvCoord).rgb; + ShaperType shaperType = (ShaperType)PassSrg::m_shaperType; + // Convert from working color space to lut coordinates by applying the shaper function - float3 lutCoordinate = color; - if (PassSrg::m_shaperType == SHAPER_LINEAR) - { - lutCoordinate = color * PassSrg::m_shaperScale + PassSrg::m_shaperBias; - } - else if (PassSrg::m_shaperType == SHAPER_LOG2) - { - lutCoordinate = log2(color) * PassSrg::m_shaperScale + PassSrg::m_shaperBias; - } + float3 lutCoordinate = LinearToShaper(color, shaperType, PassSrg::m_shaperBias, PassSrg::m_shaperScale); // Adjust coordinate to the domain excluding the outer half texel in all directions uint3 outputDimensions; PassSrg::m_lut.GetDimensions(outputDimensions.x, outputDimensions.y, outputDimensions.z); - float3 coordBias = 1.0/(2.0 * outputDimensions); - float3 coordScale = (outputDimensions-1.0)/outputDimensions; + float3 coordBias = 1.0 / (2.0 * outputDimensions); + float3 coordScale = (outputDimensions - 1.0) / outputDimensions; lutCoordinate = (lutCoordinate * coordScale) + coordBias; float3 lutColor = PassSrg::m_lut.Sample(PassSrg::LinearSampler, lutCoordinate).rgb; // Apply the inverse of the shaper function to give the color in the working color space - float3 finalColor = lutColor; - if (PassSrg::m_shaperType == SHAPER_LINEAR) - { - finalColor = (lutColor - PassSrg::m_shaperBias)/PassSrg::m_shaperScale; - } - else if (PassSrg::m_shaperType == SHAPER_LOG2) - { - finalColor = pow(2.0, (lutColor - PassSrg::m_shaperBias)/PassSrg::m_shaperScale); - } + float3 finalColor = ShaperToLinear(lutColor, shaperType, PassSrg::m_shaperBias, PassSrg::m_shaperScale); OUT.m_color.rgb = finalColor; OUT.m_color.a = 1.0; diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/BlendColorGradingLuts.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/BlendColorGradingLuts.azsl index 6f97996c29..746e18cfc2 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/BlendColorGradingLuts.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/BlendColorGradingLuts.azsl @@ -8,6 +8,7 @@ #include #include +#include ShaderResourceGroup PassSrg : SRG_PerPass_WithFallback { @@ -62,40 +63,18 @@ ShaderResourceGroup PassSrg : SRG_PerPass_WithFallback [[range(0, 4)]] option uint o_numSourceLuts = 0; -float3 ShaperToLinear(float3 shaperColor, ShaperType shaperType, float shaperBias, float shaperScale) -{ - // Apply the inverse of the shaper function to give the color in the working color space - float3 linearColor = shaperColor; - if (shaperType == ShaperType::ShaperLinear) - { - linearColor = (shaperColor - shaperBias)/shaperScale; - } - else if (shaperType == ShaperType::ShaperLog2) - { - linearColor = pow(2.0, (shaperColor - shaperBias)/shaperScale); - } - return linearColor; -} - -float3 LinearToShaper(float3 linearColor, ShaperType shaperType, float shaperBias, float shaperScale) -{ - // Convert from working color space to lut coordinates by applying the shaper function - float3 shaperColor = linearColor; - if (shaperType == ShaperType::ShaperLinear) - { - shaperColor = linearColor * shaperScale + shaperBias; - } - else if (shaperType == ShaperType::ShaperLog2) - { - shaperColor = log2(linearColor) * shaperScale + shaperBias; - } - return shaperColor; -} - float3 GetSourceLutLinearColor(float3 baseColor, Texture3D sourceLut, ShaperType shaperType, float shaperBias, float shaperScale) { // Convert from reference linearColor to the lutCoordinate for this Lut float3 lutCoord = LinearToShaper(baseColor, shaperType, shaperBias, shaperScale); + + // Adjust coordinate to the domain excluding the outer half texel in all directions + uint3 outputDimensions; + sourceLut.GetDimensions(outputDimensions.x, outputDimensions.y, outputDimensions.z); + float3 coordBias = 1.0 / (2.0 * outputDimensions); + float3 coordScale = (outputDimensions - 1.0) / outputDimensions; + lutCoord = (lutCoord * coordScale) + coordBias; + float3 lutColor = sourceLut.SampleLevel(PassSrg::LinearSampler, lutCoord, 0).rgb; // Convert to linear float3 linearColor = ShaperToLinear(lutColor, shaperType, shaperBias, shaperScale); @@ -115,11 +94,7 @@ void MainCS(uint3 dispatch_id: SV_DispatchThreadID) } // Get coordinates within the blended LUT 3D texture - float3 baseCoord = float3 ( - (float)(dispatch_id.x)/(float)PassSrg::m_blendedLutDimensions.x, - (float)(dispatch_id.y)/(float)PassSrg::m_blendedLutDimensions.y, - (float)(dispatch_id.z)/(float)PassSrg::m_blendedLutDimensions.z - ); + float3 baseCoord = float3(outPixel) / float3(PassSrg::m_blendedLutDimensions - 1.0); // Convert to the base linear color (this is the color of the identity LUT) float3 baseColor = ShaperToLinear(baseCoord, (ShaperType)PassSrg::m_blendedLutShaperType, PassSrg::m_blendedLutShaperBias, PassSrg::m_blendedLutShaperScale); diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LookModificationTransform.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LookModificationTransform.azsl index 8b1841c5e1..4741b01617 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LookModificationTransform.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LookModificationTransform.azsl @@ -12,6 +12,7 @@ #include #include #include +#include #include "EyeAdaptationUtil.azsli" ShaderResourceGroup PassSrg : SRG_PerPass_WithFallback @@ -42,12 +43,111 @@ option bool o_enableExposureControlFeature = false; // Option shader variable to enable color grading LUT. option bool o_enableColorGradingLut = false; +// Controls the sampling quality of the blended LUT. Setting this higher can improve the quality of particularly tricky luts. +// 0 - linear +// 1 - 7 tap b-spline +// 2 - 19 tap b-spline +[[range(0, 2)]] +option uint o_lutSampleQuality = 0; + +// Sample a 3dtexture with a 7 or 19 tap B-Spline. Consider ripping this out and putting in a more general location. +// This function samples a 4x4x4 neighborhood around the uv. Normally this would take 64 samples, but by taking +// advantage of bilinear filtering this can be done with 27 taps on the edges between pixels. The cost is further +// reduced by dropping either the 8 corners (19 total taps) or also dropping the 12 edges (7 total taps). +float4 SampleBSpline3D(Texture3D texture, SamplerState linearSampler, float3 uv, float3 textureSize, float3 rcpTextureSize) +{ + // Think of sample locations in the 4x4 neighborhood as having a top left coordinate of 0,0 and + // a bottom right coordinate of 3,3. + + // Find the position in texture space then round it to get the center of the 1,1 pixel (tc1) + float3 texelPos = uv * textureSize; + float3 tc1= floor(texelPos - 0.5) + 0.5; + + // Offset from center position to texel + float3 f = texelPos - tc1; + + // Compute B-Spline weights based on the offset + float3 OneMinusF = (1.0 - f); + float3 OneMinusF2 = OneMinusF * OneMinusF; + float3 OneMinusF3 = OneMinusF2 * OneMinusF; + float3 w0 = OneMinusF3; + float3 w1 = 4.0 + 3.0 * f * f * f - 6.0 * f * f; + float3 w2 = 4.0 + 3.0 * OneMinusF3 - 6.0 * OneMinusF2; + float3 w3 = f * f * f; + + float3 w12 = w1 + w2; + + // Compute uv coordinates for sampling the texture + float3 tc0 = (tc1 - 1.0f) * rcpTextureSize; + float3 tc3 = (tc1 + 2.0f) * rcpTextureSize; + float3 tc12 = (tc1 + w2 / w12) * rcpTextureSize; + + // Compute sample weights + float sw0 = w12.x * w0.y * w12.z; + float sw1 = w0.x * w12.y * w12.z; + float sw2 = w12.x * w12.y * w12.z; + float sw3 = w3.x * w12.y * w12.z; + float sw4 = w12.x * w3.y * w12.z; + float sw5 = w12.x * w12.y * w0.z; + float sw6 = w12.x * w12.y * w3.z; + + // total weight of samples to normalize result. + float totalWeight = sw0 + sw1 + sw2 + sw3 + sw4 + sw5 + sw6; + + float4 result = 0.0f; + result += texture.SampleLevel(linearSampler, float3(tc12.x, tc0.y, tc12.z), 0.0) * sw0; + result += texture.SampleLevel(linearSampler, float3( tc0.x, tc12.y, tc12.z), 0.0) * sw1; + result += texture.SampleLevel(linearSampler, float3(tc12.x, tc12.y, tc12.z), 0.0) * sw2; + result += texture.SampleLevel(linearSampler, float3( tc3.x, tc12.y, tc12.z), 0.0) * sw3; + result += texture.SampleLevel(linearSampler, float3(tc12.x, tc3.y, tc12.z), 0.0) * sw4; + result += texture.SampleLevel(linearSampler, float3(tc12.x, tc12.y, tc0.z), 0.0) * sw5; + result += texture.SampleLevel(linearSampler, float3(tc12.x, tc12.y, tc3.z), 0.0) * sw6; + + if (o_lutSampleQuality == 2) + { + // Extra 12 taps for Diagonals to increase the quality further. + + float sw7 = w0.x * w0.y * w12.z; + float sw8 = w0.x * w3.y * w12.z; + float sw9 = w3.x * w0.y * w12.z; + float sw10 = w3.x * w3.y * w12.z; + + float sw11 = w12.x * w0.y * w0.z; + float sw12 = w12.x * w0.y * w3.z; + float sw13 = w12.x * w3.y * w0.z; + float sw14 = w12.x * w3.y * w3.z; + + float sw15 = w0.x * w12.y * w0.z; + float sw16 = w0.x * w12.y * w3.z; + float sw17 = w3.x * w12.y * w0.z; + float sw18 = w3.x * w12.y * w3.z; + + totalWeight += sw7 + sw8 + sw9 + sw10 + sw11 + sw12 + sw13 + sw14 + sw15 + sw16 + sw17 + sw18; + + result += texture.SampleLevel(linearSampler, float3(tc0.x, tc0.y, tc12.z), 0.0) * sw7; + result += texture.SampleLevel(linearSampler, float3(tc0.x, tc3.y, tc12.z), 0.0) * sw8; + result += texture.SampleLevel(linearSampler, float3(tc3.x, tc0.y, tc12.z), 0.0) * sw9; + result += texture.SampleLevel(linearSampler, float3(tc3.x, tc3.y, tc12.z), 0.0) * sw10; + + result += texture.SampleLevel(linearSampler, float3(tc12.x, tc0.y, tc0.z), 0.0) * sw11; + result += texture.SampleLevel(linearSampler, float3(tc12.x, tc0.y, tc3.z), 0.0) * sw12; + result += texture.SampleLevel(linearSampler, float3(tc12.x, tc3.y, tc0.z), 0.0) * sw13; + result += texture.SampleLevel(linearSampler, float3(tc12.x, tc3.y, tc3.z), 0.0) * sw14; + + result += texture.SampleLevel(linearSampler, float3(tc0.x, tc12.y, tc0.z), 0.0) * sw15; + result += texture.SampleLevel(linearSampler, float3(tc0.x, tc12.y, tc3.z), 0.0) * sw16; + result += texture.SampleLevel(linearSampler, float3(tc3.x, tc12.y, tc0.z), 0.0) * sw17; + result += texture.SampleLevel(linearSampler, float3(tc3.x, tc12.y, tc3.z), 0.0) * sw18; + } + return result / totalWeight; +} + PSOutput MainPS(VSOutput IN) { PSOutput OUT; // Fetch the pixel color from the input texture - float3 color = PassSrg::m_framebuffer.Sample(PassSrg::LinearSampler, IN.m_texCoord).rgb; + float3 color = PassSrg::m_framebuffer.SampleLevel(PassSrg::LinearSampler, IN.m_texCoord, 0.0).rgb; if (o_enableExposureControlFeature) { @@ -63,36 +163,28 @@ PSOutput MainPS(VSOutput IN) if (o_enableColorGradingLut) { // Convert from working color space to lut coordinates by applying the shaper function - float3 lutCoordinate = color; - if (shaperType == ShaperType::ShaperLinear) - { - lutCoordinate = color * PassSrg::m_shaperScale + PassSrg::m_shaperBias; - } - else if (shaperType == ShaperType::ShaperLog2) - { - lutCoordinate = log2(color) * PassSrg::m_shaperScale + PassSrg::m_shaperBias; - } + float3 lutCoordinate = LinearToShaper(color, shaperType, PassSrg::m_shaperBias, PassSrg::m_shaperScale); // Adjust coordinate to the domain excluding the outer half texel in all directions uint3 outputDimensions; PassSrg::m_gradingLut.GetDimensions(outputDimensions.x, outputDimensions.y, outputDimensions.z); float3 coordBias = 0.5f / outputDimensions; - float3 coordScale = (outputDimensions-1.0)/outputDimensions; + float3 sizeMinusOne = outputDimensions - 1.0; + float3 coordScale = sizeMinusOne / outputDimensions; lutCoordinate = (lutCoordinate * coordScale) + coordBias; - float3 lutColor = PassSrg::m_gradingLut.Sample(PassSrg::LinearSampler, lutCoordinate).rgb; + float3 lutColor = float3(0.0, 0.0, 0.0); + if (o_lutSampleQuality == 0) + { + lutColor = PassSrg::m_gradingLut.SampleLevel(PassSrg::LinearSampler, lutCoordinate, 0.0).rgb; + } + else + { + lutColor = SampleBSpline3D(PassSrg::m_gradingLut, PassSrg::LinearSampler, lutCoordinate, float3(outputDimensions), 1.0 / float3(outputDimensions)).rgb; + } // Apply the inverse of the shaper function to give the color in the working color space - float3 finalColor = lutColor; - if (shaperType == ShaperType::ShaperLinear) - { - finalColor = (lutColor - PassSrg::m_shaperBias)/PassSrg::m_shaperScale; - } - else if (shaperType == ShaperType::ShaperLog2) - { - finalColor = pow(2.0, (lutColor - PassSrg::m_shaperBias)/PassSrg::m_shaperScale); - } - color = finalColor; + color = ShaperToLinear(lutColor, shaperType, PassSrg::m_shaperBias, PassSrg::m_shaperScale); } OUT.m_color.rgb = color; diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LookModificationTransform.shadervariantlist b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LookModificationTransform.shadervariantlist index 0de004bde6..88d6bf9b4e 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LookModificationTransform.shadervariantlist +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/LookModificationTransform.shadervariantlist @@ -1,9 +1,13 @@ { "Shader" : "LookModificationTransform.shader", "Variants" : [ - { "StableId": 1, "Options" : { "o_enableExposureControlFeature": "true", "o_enableColorGradingLut": "true" } }, - { "StableId": 2, "Options" : { "o_enableExposureControlFeature": "true", "o_enableColorGradingLut": "false" } }, - { "StableId": 3, "Options" : { "o_enableExposureControlFeature": "false", "o_enableColorGradingLut": "true" } }, - { "StableId": 4, "Options" : { "o_enableExposureControlFeature": "false", "o_enableColorGradingLut": "false" } } + { "StableId": 1, "Options" : { "o_enableExposureControlFeature": "true", "o_enableColorGradingLut": "false" } }, + { "StableId": 2, "Options" : { "o_enableExposureControlFeature": "false", "o_enableColorGradingLut": "false" } }, + { "StableId": 3, "Options" : { "o_enableExposureControlFeature": "true", "o_enableColorGradingLut": "true", "o_lutSampleQuality": 0 } }, + { "StableId": 4, "Options" : { "o_enableExposureControlFeature": "false", "o_enableColorGradingLut": "true", "o_lutSampleQuality": 0 } }, + { "StableId": 5, "Options" : { "o_enableExposureControlFeature": "true", "o_enableColorGradingLut": "true", "o_lutSampleQuality": 1 } }, + { "StableId": 6, "Options" : { "o_enableExposureControlFeature": "false", "o_enableColorGradingLut": "true", "o_lutSampleQuality": 1 } }, + { "StableId": 7, "Options" : { "o_enableExposureControlFeature": "true", "o_enableColorGradingLut": "true", "o_lutSampleQuality": 2 } }, + { "StableId": 8, "Options" : { "o_enableExposureControlFeature": "false", "o_enableColorGradingLut": "true", "o_lutSampleQuality": 2 } } ] } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SMAA.azsli b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SMAA.azsli index 58c2bc1ce9..8c03816b26 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SMAA.azsli +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SMAA.azsli @@ -1135,13 +1135,13 @@ float4 SMAABlendingWeightCalculationPS(float2 texcoord, if (!o_enableDiagonalDetectionFeature || weights.r == -weights.g) // weights.r + weights.g == 0.0 { - float2 d; + // NOTE: using separate floats for (dx, dy) and (sqrt_d_x, sqrt_d_y) instead of float2 due to android Mali driver problem crashing the device // Find the distance to the left: float3 coords; coords.x = SMAASearchXLeft(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].xy, offset[2].x); coords.y = offset[1].y; // offset[1].y = texcoord.y - 0.25 * SMAA_RT_METRICS.y (@CROSSING_OFFSET) - d.x = coords.x; + float dx = coords.x; // Now fetch the left crossing edges, two at a time using bilinear // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to @@ -1150,26 +1150,29 @@ float4 SMAABlendingWeightCalculationPS(float2 texcoord, // Find the distance to the right: coords.z = SMAASearchXRight(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].zw, offset[2].y); - d.y = coords.z; + float dy = coords.z; // We want the distances to be in pixel units (doing this here allow to // better interleave arithmetic and memory accesses): - d = abs(round(mad(SMAA_RT_METRICS.zz, d, -pixcoord.xx))); + dx = abs(round(mad(SMAA_RT_METRICS.z, dx, -pixcoord.x))); + dy = abs(round(mad(SMAA_RT_METRICS.z, dy, -pixcoord.x))); // SMAAArea below needs a sqrt, as the areas texture is compressed // quadratically: - float2 sqrt_d = sqrt(d); + float sqrt_d_x = sqrt(dx); + float sqrt_d_y = sqrt(dy); + // Fetch the right crossing edges: float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.zy, int2(1, 0)).r; // Ok, we know how this pattern looks like, now it is time for getting // the actual area: - weights.rg = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.y); + weights.rg = SMAAArea(SMAATexturePass2D(areaTex), float2(sqrt_d_x, sqrt_d_y), e1, e2, subsampleIndices.y); // Fix corners: coords.y = texcoord.y; - SMAADetectHorizontalCornerPattern(SMAATexturePass2D(edgesTex), weights.rg, coords.xyzy, d); + SMAADetectHorizontalCornerPattern(SMAATexturePass2D(edgesTex), weights.rg, coords.xyzy, float2(dx, dy)); } else { @@ -1180,37 +1183,37 @@ float4 SMAABlendingWeightCalculationPS(float2 texcoord, SMAA_BRANCH if (e.r > 0.0) // Edge at west { - float2 d; - // Find the distance to the top: float3 coords; coords.y = SMAASearchYUp(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].xy, offset[2].z); coords.x = offset[0].x; // offset[1].x = texcoord.x - 0.25 * SMAA_RT_METRICS.x; - d.x = coords.y; + float dx = coords.y; // Fetch the top crossing edges: float e1 = SMAASampleLevelZero(edgesTex, coords.xy).g; // Find the distance to the bottom: coords.z = SMAASearchYDown(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].zw, offset[2].w); - d.y = coords.z; + float dy = coords.z; // We want the distances to be in pixel units: - d = abs(round(mad(SMAA_RT_METRICS.ww, d, -pixcoord.yy))); + dx = abs(round(mad(SMAA_RT_METRICS.w, dx, -pixcoord.y))); + dy = abs(round(mad(SMAA_RT_METRICS.w, dy, -pixcoord.y))); // SMAAArea below needs a sqrt, as the areas texture is compressed // quadratically: - float2 sqrt_d = sqrt(d); + float sqrt_d_x = sqrt(dx); + float sqrt_d_y = sqrt(dy); // Fetch the bottom crossing edges: float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.xz, int2(0, 1)).g; // Get the area for this direction: - weights.ba = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.x); + weights.ba = SMAAArea(SMAATexturePass2D(areaTex), float2(sqrt_d_x, sqrt_d_y), e1, e2, subsampleIndices.x); // Fix corners: coords.x = texcoord.x; - SMAADetectVerticalCornerPattern(SMAATexturePass2D(edgesTex), weights.ba, coords.xyxz, d); + SMAADetectVerticalCornerPattern(SMAATexturePass2D(edgesTex), weights.ba, coords.xyxz, float2(dx, dy)); } return weights; diff --git a/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.cpp b/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.cpp index 125614235f..79f16ee628 100644 --- a/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.cpp +++ b/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.cpp @@ -203,47 +203,37 @@ namespace AZ return ODT_48nits; } + ShaperParams GetLog2ShaperParameters(float minStops, float maxStops) + { + ShaperParams shaperParams; + + constexpr float Log2MediumGray = -2.47393118833f; // log2f(0.18f); + shaperParams.m_type = ShaperType::Log2; + shaperParams.m_scale = 1.0f / (maxStops - minStops); + shaperParams.m_bias = -((minStops + Log2MediumGray) * shaperParams.m_scale); + + return shaperParams; + } + ShaperParams GetAcesShaperParameters(OutputDeviceTransformType odtType) { AZ_Assert(static_cast(odtType) < static_cast(NumOutputDeviceTransformTypes), "Invalid ODT type specified."); - ShaperParams shaperParams; - - // These values represent and low and high end of the dynamic range in terms of stops from middle grey (0.18) - float lowerDynamicRangeInStops; - float higherDynamicRangeInStops; - const float MIDDLE_GREY = 0.18f; - switch (odtType) { case OutputDeviceTransformType_48Nits: - lowerDynamicRangeInStops = -6.5f; - higherDynamicRangeInStops = 6.5f; - break; + return GetLog2ShaperParameters(-6.5f, 6.5f); case OutputDeviceTransformType_1000Nits: - lowerDynamicRangeInStops = -12.f; - higherDynamicRangeInStops = 10.f; - break; + return GetLog2ShaperParameters(-12.0f, 10.0f); case OutputDeviceTransformType_2000Nits: - lowerDynamicRangeInStops = -12.f; - higherDynamicRangeInStops = 11.f; - break; + return GetLog2ShaperParameters(-12.0f, 11.0f); case OutputDeviceTransformType_4000Nits: - lowerDynamicRangeInStops = -12.f; - higherDynamicRangeInStops = 12.f; - break; + return GetLog2ShaperParameters(-12.0f, 12.0f); default: AZ_Assert(false, "Invalid output device transform type."); - return shaperParams; break; } - - float logMin = log2(MIDDLE_GREY * exp2(lowerDynamicRangeInStops)); - float logMax = log2(MIDDLE_GREY * exp2(higherDynamicRangeInStops)); - shaperParams.scale = 1.0f / (logMax - logMin); - shaperParams.bias = -shaperParams.scale * logMin; - shaperParams.type = ShaperType::Log2; - return shaperParams; + return ShaperParams(); } Matrix3x3 GetColorConvertionMatrix(ColorConvertionMatrixType type) diff --git a/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.h b/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.h index 94d6434b93..3ec2885a99 100644 --- a/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.h +++ b/Gems/Atom/Feature/Common/Code/3rdParty/ACES/ACES/Aces.h @@ -124,18 +124,19 @@ namespace AZ NumColorConvertionMatrixTypes }; - enum ShaperType + enum class ShaperType : uint32_t { Linear = 0, Log2 = 1, + PqSmpteSt2084 = 2, NumShaperTypes }; struct ShaperParams { - ShaperType type = ShaperType::Linear; - float bias = 0.f; - float scale = 1.f; + ShaperType m_type = ShaperType::Linear; + float m_bias = 0.0f; + float m_scale = 1.0f; }; enum class DisplayMapperOperationType : uint32_t @@ -151,10 +152,14 @@ namespace AZ enum class ShaperPresetType { None = 0, - Log2_48_nits, - Log2_1000_nits, - Log2_2000_nits, - Log2_4000_nits + LinearCustomRange, + Log2_48Nits, + Log2_1000Nits, + Log2_2000Nits, + Log2_4000Nits, + Log2CustomRange, + PqSmpteSt2084, + NumShaperTypes }; enum class ToneMapperType @@ -171,6 +176,7 @@ namespace AZ }; SegmentedSplineParamsC9 GetAcesODTParameters(OutputDeviceTransformType odtType); + ShaperParams GetLog2ShaperParameters(float minStops, float maxStops); ShaperParams GetAcesShaperParameters(OutputDeviceTransformType odtType); Matrix3x3 GetColorConvertionMatrix(ColorConvertionMatrixType type); diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ACES/AcesDisplayMapperFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ACES/AcesDisplayMapperFeatureProcessor.h index 7d2aa18f29..6be81c8cae 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ACES/AcesDisplayMapperFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ACES/AcesDisplayMapperFeatureProcessor.h @@ -78,7 +78,7 @@ namespace AZ static OutputDeviceTransformType GetOutputDeviceTransformType(RHI::Format bufferFormat); static void GetAcesDisplayMapperParameters(DisplayMapperParameters* displayMapperParameters, OutputDeviceTransformType odtType); - static ShaperParams GetShaperParameters(ShaperPresetType shaperPreset); + static ShaperParams GetShaperParameters(ShaperPresetType shaperPreset, float customMinEv = 0.0f, float customMaxEv = 0.0f); static void GetDefaultDisplayMapperConfiguration(DisplayMapperConfigurationDescriptor& config); // DisplayMapperFeatureProcessorInteface overrides... @@ -102,8 +102,6 @@ namespace AZ static constexpr const char* FeatureProcessorName = "AcesDisplayMapperFeatureProcessor"; - static const int LutSize = 32; - static const RHI::Format LutFormat = RHI::Format::R16G16B16A16_FLOAT; static const int ImagePoolBudget = 1 << 20; // 1 Megabyte // LUTs that are baked through shaders diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h index e4986eee93..bcb470d831 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h @@ -38,7 +38,7 @@ namespace AZ float m_cosInnerConeAngle = 0.0f; // cosine of inner cone angle float m_cosOuterConeAngle = 0.0f; // cosine of outer cone angle float m_bulbPositionOffset = 0.0f; // Distance from the light disk surface to the tip of the cone of the light. m_bulbRadius * tanf(pi/2 - m_outerConeAngle). - uint16_t m_shadowIndex = -1; // index for ProjectedShadowData. A value of 0xFFFF indicates an illegal index. + uint16_t m_shadowIndex = std::numeric_limits::max(); // index for ProjectedShadowData. A value of 0xFFFF indicates an illegal index. uint16_t m_padding; // Explicit padding. }; diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h index e58a8397db..599f4c380e 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h @@ -64,7 +64,7 @@ namespace AZ bool operator==(const MaterialAssignmentId& rhs) const; bool operator!=(const MaterialAssignmentId& rhs) const; - static constexpr MaterialAssignmentLodIndex NonLodIndex = -1; + static constexpr MaterialAssignmentLodIndex NonLodIndex = std::numeric_limits::max(); MaterialAssignmentLodIndex m_lodIndex = NonLodIndex; RPI::ModelMaterialSlot::StableId m_materialSlotStableId = RPI::ModelMaterialSlot::InvalidStableId; diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/LookModification/LookModificationParams.inl b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/LookModification/LookModificationParams.inl index 38a1987caa..4c3cf8ac92 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/LookModification/LookModificationParams.inl +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/LookModification/LookModificationParams.inl @@ -10,11 +10,9 @@ // PARAM(NAME, MEMBER_NAME, DEFAULT_VALUE, ...) AZ_GFX_BOOL_PARAM(Enabled, m_enabled, false) - AZ_GFX_COMMON_PARAM(Data::Asset, ColorGradingLut, m_colorGradingLut, {}) - -AZ_GFX_COMMON_PARAM(AZ::Render::ShaperPresetType, ShaperPresetType, m_shaperPresetType, AZ::Render::ShaperPresetType::Log2_48_nits) - +AZ_GFX_COMMON_PARAM(AZ::Render::ShaperPresetType, ShaperPresetType, m_shaperPresetType, AZ::Render::ShaperPresetType::Log2_48Nits) +AZ_GFX_COMMON_PARAM(float, CustomMinExposure, m_customMinExposure, -6.5) +AZ_GFX_COMMON_PARAM(float, CustomMaxExposure, m_customMaxExposure, 6.5) AZ_GFX_FLOAT_PARAM(ColorGradingLutIntensity, m_colorGradingLutIntensity, 1.0) - AZ_GFX_FLOAT_PARAM(ColorGradingLutOverride, m_colorGradingLutOverride, 1.0) diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/SphericalHarmonics/SphericalHarmonicsUtility.inl b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/SphericalHarmonics/SphericalHarmonicsUtility.inl index fb1e70b2a0..7446d2fa8f 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/SphericalHarmonics/SphericalHarmonicsUtility.inl +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/SphericalHarmonics/SphericalHarmonicsUtility.inl @@ -499,7 +499,7 @@ namespace AZ // outSH -> output SH coefficient array void EvalSHRotationFast(const float R[9], const uint32_t maxBand, const float* inSH, float* outSH) { - if (maxBand >= 0 && maxBand <= 2) + if (maxBand <= 2) { ZHF3(R, maxBand, inSH, outSH); } @@ -514,10 +514,7 @@ namespace AZ // outSH -> output SH coefficient array void EvalSHRotation(const float R[9], const uint32_t maxBand, const double* inSH, double* outSH) { - if (maxBand >= 0) - { - WignerD(R, maxBand, inSH, outSH); - } + WignerD(R, maxBand, inSH, outSH); } // Fast evaluation for first 3 bands diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/TransformService/TransformServiceFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/TransformService/TransformServiceFeatureProcessor.h index 1f31701d91..6482871234 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/TransformService/TransformServiceFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/TransformService/TransformServiceFeatureProcessor.h @@ -61,7 +61,7 @@ namespace AZ }; // Flag value for when the buffers have no empty spaces. - static const uint32_t NoAvailableTransformIndices = -1; + static const uint32_t NoAvailableTransformIndices = std::numeric_limits::max(); TransformServiceFeatureProcessor(const TransformServiceFeatureProcessor&) = delete; diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/IndexableList.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/IndexableList.h index fbc524314a..aae229ac9d 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/IndexableList.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/IndexableList.h @@ -9,6 +9,7 @@ #pragma once #include +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/MultiSparseVector.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/MultiSparseVector.h index 2d93b4a7fd..216e90c594 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/MultiSparseVector.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/MultiSparseVector.h @@ -49,7 +49,7 @@ namespace AZ::Render private: - static constexpr size_t NoFreeSlot = -1; + static constexpr size_t NoFreeSlot = std::numeric_limits::max(); static constexpr size_t InitialReservedCount = 128; using Fn = void(&)(AZStd::vector& ...); @@ -103,7 +103,7 @@ namespace AZ::Render template inline size_t MultiSparseVector::Reserve() { - size_t slotToReturn = -1; + size_t slotToReturn = std::numeric_limits::max(); if (m_nextFreeSlot != NoFreeSlot) { // If there's a free slot, then use that space and update the linked list of free slots. diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/SparseVector.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/SparseVector.h index 525288adb0..8f388e23b9 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/SparseVector.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/SparseVector.h @@ -49,7 +49,7 @@ namespace AZ::Render private: - static constexpr size_t NoFreeSlot = -1; + static constexpr size_t NoFreeSlot = std::numeric_limits::max(); static constexpr size_t InitialReservedCount = 128; size_t m_nextFreeSlot = NoFreeSlot; @@ -66,7 +66,7 @@ namespace AZ::Render template inline size_t SparseVector::Reserve() { - size_t slotToReturn = -1; + size_t slotToReturn = std::numeric_limits::max(); if (m_nextFreeSlot != NoFreeSlot) { // If there's a free slot, then use that space and update the linked list of free slots. diff --git a/Gems/Atom/Feature/Common/Code/Source/ACES/AcesDisplayMapperFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/ACES/AcesDisplayMapperFeatureProcessor.cpp index 4c057aab2a..c6c41edb31 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ACES/AcesDisplayMapperFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ACES/AcesDisplayMapperFeatureProcessor.cpp @@ -21,6 +21,7 @@ namespace { + static const AZ::RHI::Format LutFormat = AZ::RHI::Format::R16G16B16A16_FLOAT; uint16_t ConvertFloatToHalf(const float Value) { @@ -56,395 +57,409 @@ namespace } } -namespace AZ +namespace AZ::Render { - namespace Render + void AcesDisplayMapperFeatureProcessor::Reflect(ReflectContext* context) { - void AcesDisplayMapperFeatureProcessor::Reflect(ReflectContext* context) + if (auto* serializeContext = azrtti_cast(context)) { - if (auto* serializeContext = azrtti_cast(context)) - { - serializeContext - ->Class() - ->Version(0); - } + serializeContext + ->Class() + ->Version(0); + } + } + + void AcesDisplayMapperFeatureProcessor::Activate() + { + GetDefaultDisplayMapperConfiguration(m_displayMapperConfiguration); + } + + void AcesDisplayMapperFeatureProcessor::Deactivate() + { + m_ownedLuts.clear(); + } + + void AcesDisplayMapperFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) + { + AZ_TRACE_METHOD(); + AZ_UNUSED(packet); + } + + void AcesDisplayMapperFeatureProcessor::Render([[maybe_unused]] const FeatureProcessor::RenderPacket& packet) + { + } + + void AcesDisplayMapperFeatureProcessor::ApplyLdrOdtParameters(DisplayMapperParameters* displayMapperParameters) + { + AZ_Assert(displayMapperParameters != nullptr, "The pOutParameters must not to be null pointer."); + if (displayMapperParameters == nullptr) + { + return; } - void AcesDisplayMapperFeatureProcessor::Activate() + // These values in the ODT parameter are taken from the reference ACES transform. + // + // The original ACES references. + // Common: + // https://github.com/ampas/aces-dev/blob/master/transforms/ctl/lib/ACESlib.ODT_Common.ctl + // For sRGB: + // https://github.com/ampas/aces-dev/tree/master/transforms/ctl/odt/sRGB + displayMapperParameters->m_cinemaLimits[0] = 0.02f; + displayMapperParameters->m_cinemaLimits[1] = 48.0f; + displayMapperParameters->m_acesSplineParams = GetAcesODTParameters(OutputDeviceTransformType_48Nits); + displayMapperParameters->m_OutputDisplayTransformFlags = AlterSurround | ApplyDesaturation | ApplyCATD60toD65; + displayMapperParameters->m_OutputDisplayTransformMode = Srgb; + ColorConvertionMatrixType colorMatrixType = XYZ_To_Rec709; + switch (displayMapperParameters->m_OutputDisplayTransformMode) { - GetDefaultDisplayMapperConfiguration(m_displayMapperConfiguration); + case Srgb: + colorMatrixType = XYZ_To_Rec709; + break; + case PerceptualQuantizer: + case Ldr: + colorMatrixType = XYZ_To_Bt2020; + break; + default: + break; + } + displayMapperParameters->m_XYZtoDisplayPrimaries = GetColorConvertionMatrix(colorMatrixType); + + displayMapperParameters->m_surroundGamma = 0.9811f; + displayMapperParameters->m_gamma = 2.2f; + } + + void AcesDisplayMapperFeatureProcessor::ApplyHdrOdtParameters(DisplayMapperParameters* displayMapperParameters, const OutputDeviceTransformType& odtType) + { + AZ_Assert(displayMapperParameters != nullptr, "The pOutParameters must not to be null pointer."); + if (displayMapperParameters == nullptr) + { + return; } - void AcesDisplayMapperFeatureProcessor::Deactivate() + // Dynamic range limit values taken from NVIDIA HDR sample. + // These values represent and low and high end of the dynamic range in terms of stops from middle grey (0.18) + float lowerDynamicRangeInStops = -12.f; + float higherDynamicRangeInStops = 10.f; + const float MIDDLE_GREY = 0.18f; + + switch (odtType) { - m_ownedLuts.clear(); + case OutputDeviceTransformType_1000Nits: + higherDynamicRangeInStops = 10.f; + break; + case OutputDeviceTransformType_2000Nits: + higherDynamicRangeInStops = 11.f; + break; + case OutputDeviceTransformType_4000Nits: + higherDynamicRangeInStops = 12.f; + break; + default: + AZ_Assert(false, "Invalid output device transform type."); + break; } - void AcesDisplayMapperFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) + displayMapperParameters->m_cinemaLimits[0] = MIDDLE_GREY * exp2(lowerDynamicRangeInStops); + displayMapperParameters->m_cinemaLimits[1] = MIDDLE_GREY * exp2(higherDynamicRangeInStops); + displayMapperParameters->m_acesSplineParams = GetAcesODTParameters(odtType); + displayMapperParameters->m_OutputDisplayTransformFlags = AlterSurround | ApplyDesaturation | ApplyCATD60toD65; + displayMapperParameters->m_OutputDisplayTransformMode = PerceptualQuantizer; + ColorConvertionMatrixType colorMatrixType = XYZ_To_Bt2020; + displayMapperParameters->m_XYZtoDisplayPrimaries = GetColorConvertionMatrix(colorMatrixType); + + // Surround gamma value is from the dim surround gamma from the ACES reference transforms. + // https://github.com/ampas/aces-dev/blob/master/transforms/ctl/lib/ACESlib.ODT_Common.ctl + displayMapperParameters->m_surroundGamma = 0.9811f; + displayMapperParameters->m_gamma = 1.0f; // gamma not used with perceptual quantizer, but just set to 1.0 anyways + } + + OutputDeviceTransformType AcesDisplayMapperFeatureProcessor::GetOutputDeviceTransformType(RHI::Format bufferFormat) + { + OutputDeviceTransformType outputDeviceTransformType = OutputDeviceTransformType_48Nits; + if (bufferFormat == RHI::Format::R8G8B8A8_UNORM || + bufferFormat == RHI::Format::B8G8R8A8_UNORM) { - AZ_TRACE_METHOD(); - AZ_UNUSED(packet); + outputDeviceTransformType = OutputDeviceTransformType_48Nits; + } + else if (bufferFormat == RHI::Format::R10G10B10A2_UNORM) + { + outputDeviceTransformType = OutputDeviceTransformType_1000Nits; + } + else + { + AZ_Assert(false, "Not yet supported."); + // To work normally on unsupported environment, initialize the display parameters by OutputDeviceTransformType_48Nits. + outputDeviceTransformType = OutputDeviceTransformType_48Nits; + } + return outputDeviceTransformType; + } + + void AcesDisplayMapperFeatureProcessor::GetAcesDisplayMapperParameters(DisplayMapperParameters* displayMapperParameters, OutputDeviceTransformType odtType) + { + switch (odtType) + { + case OutputDeviceTransformType_48Nits: + ApplyLdrOdtParameters(displayMapperParameters); + break; + case OutputDeviceTransformType_1000Nits: + case OutputDeviceTransformType_2000Nits: + case OutputDeviceTransformType_4000Nits: + ApplyHdrOdtParameters(displayMapperParameters, odtType); + break; + default: + AZ_Assert(false, "This ODT type[%d] is not supported.", odtType); + break; + } + } + + void AcesDisplayMapperFeatureProcessor::GetOwnedLut(DisplayMapperLut& displayMapperLut, const AZ::Name& lutName) + { + auto it = m_ownedLuts.find(lutName); + if (it == m_ownedLuts.end()) + { + InitializeLutImage(lutName); + it = m_ownedLuts.find(lutName); + AZ_Assert(it != m_ownedLuts.end(), "AcesDisplayMapperFeatureProcessor unable to create LUT %s", lutName.GetCStr()); + } + displayMapperLut = it->second; + } + + void AcesDisplayMapperFeatureProcessor::GetDisplayMapperLut(DisplayMapperLut& displayMapperLut) + { + const AZ::Name acesLutName("AcesLutImage"); + auto it = m_ownedLuts.find(acesLutName); + if (it == m_ownedLuts.end()) + { + InitializeLutImage(acesLutName); + + it = m_ownedLuts.find(acesLutName); + AZ_Assert(it != m_ownedLuts.end(), "AcesDisplayMapperFeatureProcessor unable to create ACES LUT image"); + } + displayMapperLut = it->second; + } + + void AcesDisplayMapperFeatureProcessor::GetLutFromAssetLocation(DisplayMapperAssetLut& displayMapperAssetLut, const AZStd::string& assetPath) + { + Data::AssetId assetId = RPI::AssetUtils::GetAssetIdForProductPath(assetPath.c_str(), RPI::AssetUtils::TraceLevel::Error); + GetLutFromAssetId(displayMapperAssetLut, assetId); + } + + void AcesDisplayMapperFeatureProcessor::GetLutFromAssetId(DisplayMapperAssetLut& displayMapperAssetLut, const AZ::Data::AssetId assetId) + { + if (!assetId.IsValid()) + { + return; } - void AcesDisplayMapperFeatureProcessor::Render([[maybe_unused]] const FeatureProcessor::RenderPacket& packet) + // Check first if this already exists + auto it = m_assetLuts.find(assetId.ToString()); + if (it != m_assetLuts.end()) { + displayMapperAssetLut = it->second; + return; } - void AcesDisplayMapperFeatureProcessor::ApplyLdrOdtParameters(DisplayMapperParameters* displayMapperParameters) + // Read the lut which is a .3dl file embedded within an azasset file. + Data::Asset asset = RPI::AssetUtils::LoadAssetById(assetId, RPI::AssetUtils::TraceLevel::Error); + const LookupTableAsset* lutAsset = RPI::GetDataFromAnyAsset(asset); + + if (lutAsset == nullptr) { - AZ_Assert(displayMapperParameters != nullptr, "The pOutParameters must not to be null pointer."); - if (displayMapperParameters == nullptr) - { - return; - } - - // These values in the ODT parameter are taken from the reference ACES transform. - // - // The original ACES references. - // Common: - // https://github.com/ampas/aces-dev/blob/master/transforms/ctl/lib/ACESlib.ODT_Common.ctl - // For sRGB: - // https://github.com/ampas/aces-dev/tree/master/transforms/ctl/odt/sRGB - displayMapperParameters->m_cinemaLimits[0] = 0.02f; - displayMapperParameters->m_cinemaLimits[1] = 48.0f; - displayMapperParameters->m_acesSplineParams = GetAcesODTParameters(OutputDeviceTransformType_48Nits); - displayMapperParameters->m_OutputDisplayTransformFlags = AlterSurround | ApplyDesaturation | ApplyCATD60toD65; - displayMapperParameters->m_OutputDisplayTransformMode = Srgb; - ColorConvertionMatrixType colorMatrixType = XYZ_To_Rec709; - switch (displayMapperParameters->m_OutputDisplayTransformMode) - { - case Srgb: - colorMatrixType = XYZ_To_Rec709; - break; - case PerceptualQuantizer: - case Ldr: - colorMatrixType = XYZ_To_Bt2020; - break; - default: - break; - } - displayMapperParameters->m_XYZtoDisplayPrimaries = GetColorConvertionMatrix(colorMatrixType); - - displayMapperParameters->m_surroundGamma = 0.9811f; - displayMapperParameters->m_gamma = 2.2f; + AZ_Error("AcesDisplayMapperFeatureProcessor", false, "Unable to read LUT from asset."); + asset.Release(); + return; } - void AcesDisplayMapperFeatureProcessor::ApplyHdrOdtParameters(DisplayMapperParameters* displayMapperParameters, const OutputDeviceTransformType& odtType) + // The first row of numbers in a 3dl file is a number of vertices that partition the space from [0,..1023] + // This assumes that the vertices are evenly spaced apart. Non-uniform spacing is supported by the format, + // but haven't been encountered yet. + const size_t lutSize = lutAsset->m_intervals.size(); + + if (lutSize == 0) { - AZ_Assert(displayMapperParameters != nullptr, "The pOutParameters must not to be null pointer."); - if (displayMapperParameters == nullptr) - { - return; - } - - // Dynamic range limit values taken from NVIDIA HDR sample. - // These values represent and low and high end of the dynamic range in terms of stops from middle grey (0.18) - float lowerDynamicRangeInStops = -12.f; - float higherDynamicRangeInStops = 10.f; - const float MIDDLE_GREY = 0.18f; - - switch (odtType) - { - case OutputDeviceTransformType_1000Nits: - higherDynamicRangeInStops = 10.f; - break; - case OutputDeviceTransformType_2000Nits: - higherDynamicRangeInStops = 11.f; - break; - case OutputDeviceTransformType_4000Nits: - higherDynamicRangeInStops = 12.f; - break; - default: - AZ_Assert(false, "Invalid output device transform type."); - break; - } - - displayMapperParameters->m_cinemaLimits[0] = MIDDLE_GREY * exp2(lowerDynamicRangeInStops); - displayMapperParameters->m_cinemaLimits[1] = MIDDLE_GREY * exp2(higherDynamicRangeInStops); - displayMapperParameters->m_acesSplineParams = GetAcesODTParameters(odtType); - displayMapperParameters->m_OutputDisplayTransformFlags = AlterSurround | ApplyDesaturation | ApplyCATD60toD65; - displayMapperParameters->m_OutputDisplayTransformMode = PerceptualQuantizer; - ColorConvertionMatrixType colorMatrixType = XYZ_To_Bt2020; - displayMapperParameters->m_XYZtoDisplayPrimaries = GetColorConvertionMatrix(colorMatrixType); - - // Surround gamma value is from the dim surround gamma from the ACES reference transforms. - // https://github.com/ampas/aces-dev/blob/master/transforms/ctl/lib/ACESlib.ODT_Common.ctl - displayMapperParameters->m_surroundGamma = 0.9811f; - displayMapperParameters->m_gamma = 1.0f; // gamma not used with perceptual quantizer, but just set to 1.0 anyways + AZ_Error("AcesDisplayMapperFeatureProcessor", false, "Lut asset has invalid size."); + asset.Release(); + return; } - OutputDeviceTransformType AcesDisplayMapperFeatureProcessor::GetOutputDeviceTransformType(RHI::Format bufferFormat) + // Create a buffer of half floats from the LUT and use it to initialize a 3d texture. + + const size_t kChannels = 4; + const size_t kChannelBytes = 2; + const size_t bytesPerRow = lutSize * kChannels * kChannelBytes; + const size_t bytesPerSlice = bytesPerRow * lutSize; + + AZStd::vector u16Buffer; + const size_t bufferSize = lutSize * lutSize * lutSize * kChannels; + u16Buffer.resize(bufferSize); + + for (size_t slice = 0; slice < lutSize; slice++) { - OutputDeviceTransformType outputDeviceTransformType = OutputDeviceTransformType_48Nits; - if (bufferFormat == RHI::Format::R8G8B8A8_UNORM || - bufferFormat == RHI::Format::B8G8R8A8_UNORM) + for (size_t column = 0; column < lutSize; column++) { - outputDeviceTransformType = OutputDeviceTransformType_48Nits; - } - else if (bufferFormat == RHI::Format::R10G10B10A2_UNORM) - { - outputDeviceTransformType = OutputDeviceTransformType_1000Nits; - } - else - { - AZ_Assert(false, "Not yet supported."); - // To work normally on unsupported environment, initialize the display parameters by OutputDeviceTransformType_48Nits. - outputDeviceTransformType = OutputDeviceTransformType_48Nits; - } - return outputDeviceTransformType; - } - - void AcesDisplayMapperFeatureProcessor::GetAcesDisplayMapperParameters(DisplayMapperParameters* displayMapperParameters, OutputDeviceTransformType odtType) - { - switch (odtType) - { - case OutputDeviceTransformType_48Nits: - ApplyLdrOdtParameters(displayMapperParameters); - break; - case OutputDeviceTransformType_1000Nits: - case OutputDeviceTransformType_2000Nits: - case OutputDeviceTransformType_4000Nits: - ApplyHdrOdtParameters(displayMapperParameters, odtType); - break; - default: - AZ_Assert(false, "This ODT type[%d] is not supported.", odtType); - break; - } - } - - void AcesDisplayMapperFeatureProcessor::GetOwnedLut(DisplayMapperLut& displayMapperLut, const AZ::Name& lutName) - { - auto it = m_ownedLuts.find(lutName); - if (it == m_ownedLuts.end()) - { - InitializeLutImage(lutName); - it = m_ownedLuts.find(lutName); - AZ_Assert(it != m_ownedLuts.end(), "AcesDisplayMapperFeatureProcessor unable to create LUT %s", lutName.GetCStr()); - } - displayMapperLut = it->second; - } - - void AcesDisplayMapperFeatureProcessor::GetDisplayMapperLut(DisplayMapperLut& displayMapperLut) - { - const AZ::Name acesLutName("AcesLutImage"); - auto it = m_ownedLuts.find(acesLutName); - if (it == m_ownedLuts.end()) - { - InitializeLutImage(acesLutName); - - it = m_ownedLuts.find(acesLutName); - AZ_Assert(it != m_ownedLuts.end(), "AcesDisplayMapperFeatureProcessor unable to create ACES LUT image"); - } - displayMapperLut = it->second; - } - - void AcesDisplayMapperFeatureProcessor::GetLutFromAssetLocation(DisplayMapperAssetLut& displayMapperAssetLut, const AZStd::string& assetPath) - { - Data::AssetId assetId = RPI::AssetUtils::GetAssetIdForProductPath(assetPath.c_str(), RPI::AssetUtils::TraceLevel::Error); - GetLutFromAssetId(displayMapperAssetLut, assetId); - } - - void AcesDisplayMapperFeatureProcessor::GetLutFromAssetId(DisplayMapperAssetLut& displayMapperAssetLut, const AZ::Data::AssetId assetId) - { - if (!assetId.IsValid()) - { - return; - } - - // Check first if this already exists - auto it = m_assetLuts.find(assetId.ToString()); - if (it != m_assetLuts.end()) - { - displayMapperAssetLut = it->second; - return; - } - - // Read the lut which is a .3dl file embedded within an azasset file. - Data::Asset asset = RPI::AssetUtils::LoadAssetById(assetId, RPI::AssetUtils::TraceLevel::Error); - const LookupTableAsset* lutAsset = RPI::GetDataFromAnyAsset(asset); - - if (lutAsset == nullptr) - { - AZ_Error("AcesDisplayMapperFeatureProcessor", false, "Unable to read LUT from asset."); - asset.Release(); - return; - } - - // The first row of numbers in a 3dl file is a number of vertices that partition the space from [0,..1023] - // This assumes that the vertices are evenly spaced apart. Non-uniform spacing is supported by the format, - // but haven't been encountered yet. - uint32_t lutSize = static_cast(lutAsset->m_intervals.size()); - - if (lutSize == 0) - { - AZ_Error("AcesDisplayMapperFeatureProcessor", false, "Lut asset has invalid size."); - asset.Release(); - return; - } - - // The vertices in the file are given as a positive integer value in [0,..4095] and need to be normalized - // and stored into a linear unaligned buffer used to initialize the streaming image. - const float normalizeValue = 4095.0f; - const int kChannels = 4; - const int kChannelBytes = 2; - int bytesPerRow = lutSize * kChannels * kChannelBytes; - int bytesPerSlice = bytesPerRow * lutSize; - - AZStd::vector u16Buffer; - size_t bufferSize = (bytesPerSlice * lutSize) / sizeof(uint16_t); - u16Buffer.resize(bufferSize); - uint16_t* data = u16Buffer.data(); - for (int slice = 0; slice < (int)lutSize; slice++) - { - for (int column = 0; column < (int)lutSize; column++) + for (size_t row = 0; row < lutSize; row++) { - for (int row = 0; row < (int)lutSize; row++) - { - // Index in the LUT texture data - int idx = (column * kChannels) + - (bytesPerRow * row / sizeof(uint16_t)) + - ((bytesPerSlice * slice) / sizeof(uint16_t)); + // Index in the LUT texture data + size_t idx = (column * kChannels) + + ((bytesPerRow * row) / kChannelBytes) + + ((bytesPerSlice * slice) / kChannelBytes); - // Vertices the .3dl file are listed first by increasing slice, then row, and finally column coordinate - // This corresponds to blue, green, and red channels, respectively. - int assetIdx = slice + lutSize * row + (lutSize * lutSize * column); + // Vertices the .3dl file are listed first by increasing slice, then row, and finally column coordinate + // This corresponds to blue, green, and red channels, respectively. + size_t assetIdx = slice + lutSize * row + (lutSize * lutSize * column); - AZ::u64 red = lutAsset->m_values[assetIdx * 3 + 0]; - AZ::u64 green = lutAsset->m_values[assetIdx * 3 + 1]; - AZ::u64 blue = lutAsset->m_values[assetIdx * 3 + 2]; - data[idx + 0] = ConvertFloatToHalf(static_cast(red) / normalizeValue); - data[idx + 1] = ConvertFloatToHalf(static_cast(green) / normalizeValue); - data[idx + 2] = ConvertFloatToHalf(static_cast(blue) / normalizeValue); - data[idx + 3] = 0x3b00; // 1.0 in half - } + AZ::u64 red = lutAsset->m_values[assetIdx * 3 + 0]; + AZ::u64 green = lutAsset->m_values[assetIdx * 3 + 1]; + AZ::u64 blue = lutAsset->m_values[assetIdx * 3 + 2]; + + // The vertices in the file are given as a positive integer value in [0,..4095] and need to be normalized + constexpr float NormalizeValue = 4095.0f; + + u16Buffer[idx + 0] = ConvertFloatToHalf(static_cast(red) / NormalizeValue); + u16Buffer[idx + 1] = ConvertFloatToHalf(static_cast(green) / NormalizeValue); + u16Buffer[idx + 2] = ConvertFloatToHalf(static_cast(blue) / NormalizeValue); + u16Buffer[idx + 3] = 0x3b00; // 1.0 in half } } - - asset.Release(); - - Data::Instance streamingImagePool = RPI::ImageSystemInterface::Get()->GetSystemStreamingPool(); - - RHI::Size imageSize; - imageSize.m_width = static_cast(lutSize); - imageSize.m_height = static_cast(lutSize); - imageSize.m_depth = static_cast(lutSize); - size_t imageDataSize = bytesPerSlice * lutSize; - - Data::Instance lutStreamingImage = RPI::StreamingImage::CreateFromCpuData( - *streamingImagePool, RHI::ImageDimension::Image3D, imageSize, LutFormat, data, imageDataSize); - - AZ_Error("AcesDisplayMapperFeatureProcessor", lutStreamingImage, "Failed to initialize the lut assetId %s.", assetId.ToString().c_str()); - - DisplayMapperAssetLut assetLut; - assetLut.m_lutStreamingImage = lutStreamingImage; - - // Add to the list of LUT asset resources - m_assetLuts.insert(AZStd::pair(assetId.ToString(), assetLut)); - displayMapperAssetLut = assetLut; } - void AcesDisplayMapperFeatureProcessor::InitializeImagePool() + asset.Release(); + + Data::Instance streamingImagePool = RPI::ImageSystemInterface::Get()->GetSystemStreamingPool(); + + RHI::Size imageSize; + imageSize.m_width = static_cast(lutSize); + imageSize.m_height = static_cast(lutSize); + imageSize.m_depth = static_cast(lutSize); + size_t imageDataSize = bytesPerSlice * lutSize; + + Data::Instance lutStreamingImage = RPI::StreamingImage::CreateFromCpuData( + *streamingImagePool, RHI::ImageDimension::Image3D, imageSize, LutFormat, u16Buffer.data(), imageDataSize); + + AZ_Error("AcesDisplayMapperFeatureProcessor", lutStreamingImage, "Failed to initialize the lut assetId %s.", assetId.ToString().c_str()); + + DisplayMapperAssetLut assetLut; + assetLut.m_lutStreamingImage = lutStreamingImage; + + // Add to the list of LUT asset resources + m_assetLuts.insert(AZStd::pair(assetId.ToString(), assetLut)); + displayMapperAssetLut = assetLut; + } + + void AcesDisplayMapperFeatureProcessor::InitializeImagePool() + { + AZ::RHI::Factory& factory = RHI::Factory::Get(); + m_displayMapperImagePool = factory.CreateImagePool(); + m_displayMapperImagePool->SetName(Name("DisplayMapperImagePool")); + + RHI::ImagePoolDescriptor imagePoolDesc = {}; + imagePoolDesc.m_bindFlags = RHI::ImageBindFlags::ShaderReadWrite; + imagePoolDesc.m_budgetInBytes = ImagePoolBudget; + + RHI::Device* device = RHI::RHISystemInterface::Get()->GetDevice(); + RHI::ResultCode resultCode = m_displayMapperImagePool->Init(*device, imagePoolDesc); + if (resultCode != RHI::ResultCode::Success) { - AZ::RHI::Factory& factory = RHI::Factory::Get(); - m_displayMapperImagePool = factory.CreateImagePool(); - m_displayMapperImagePool->SetName(Name("DisplayMapperImagePool")); - - RHI::ImagePoolDescriptor imagePoolDesc = {}; - imagePoolDesc.m_bindFlags = RHI::ImageBindFlags::ShaderReadWrite; - imagePoolDesc.m_budgetInBytes = ImagePoolBudget; - - RHI::Device* device = RHI::RHISystemInterface::Get()->GetDevice(); - RHI::ResultCode resultCode = m_displayMapperImagePool->Init(*device, imagePoolDesc); - if (resultCode != RHI::ResultCode::Success) - { - AZ_Error("AcesDisplayMapperFeatureProcessor", false, "Failed to initialize image pool."); - return; - } + AZ_Error("AcesDisplayMapperFeatureProcessor", false, "Failed to initialize image pool."); + return; } + } - void AcesDisplayMapperFeatureProcessor::InitializeLutImage(const AZ::Name& lutName) + void AcesDisplayMapperFeatureProcessor::InitializeLutImage(const AZ::Name& lutName) + { + if (!m_displayMapperImagePool) { - if (!m_displayMapperImagePool) - { - InitializeImagePool(); - } - - DisplayMapperLut lutResource; - lutResource.m_lutImage = RHI::Factory::Get().CreateImage(); - lutResource.m_lutImage->SetName(lutName); - - RHI::ImageInitRequest imageRequest; - imageRequest.m_image = lutResource.m_lutImage.get(); - imageRequest.m_descriptor = RHI::ImageDescriptor::Create3D(RHI::ImageBindFlags::ShaderReadWrite, LutSize, LutSize, LutSize, LutFormat); - RHI::ResultCode resultCode = m_displayMapperImagePool->InitImage(imageRequest); - - if (resultCode != RHI::ResultCode::Success) - { - AZ_Error("AcesDisplayMapperFeatureProcessor", false, "Failed to initialize LUT image."); - return; - } - - lutResource.m_lutImageViewDescriptor = RHI::ImageViewDescriptor::Create(LutFormat, 0, 0); - lutResource.m_lutImageView = lutResource.m_lutImage->GetImageView(lutResource.m_lutImageViewDescriptor); - if (!lutResource.m_lutImageView.get()) - { - AZ_Error("AcesDisplayMapperFeatureProcessor", false, "Failed to initialize LUT image view."); - return; - } - - // Add to the list of lut resources - lutResource.m_lutImageView->SetName(lutName); - m_ownedLuts[lutName] = lutResource; + InitializeImagePool(); } - ShaperParams AcesDisplayMapperFeatureProcessor::GetShaperParameters(ShaperPresetType shaperPreset) + DisplayMapperLut lutResource; + lutResource.m_lutImage = RHI::Factory::Get().CreateImage(); + lutResource.m_lutImage->SetName(lutName); + + RHI::ImageInitRequest imageRequest; + imageRequest.m_image = lutResource.m_lutImage.get(); + static const int LutSize = 32; + imageRequest.m_descriptor = RHI::ImageDescriptor::Create3D(RHI::ImageBindFlags::ShaderReadWrite, LutSize, LutSize, LutSize, LutFormat); + RHI::ResultCode resultCode = m_displayMapperImagePool->InitImage(imageRequest); + + if (resultCode != RHI::ResultCode::Success) { - // Default is a linear shaper with bias 0.0 and scale 1.0. That is, fx = x*1.0 + 0.0 - ShaperParams shaperParams = { ShaperType::Linear, 0.0, 1.f }; - OutputDeviceTransformType outputDeviceTransformType = OutputDeviceTransformType::NumOutputDeviceTransformTypes; - switch (shaperPreset) - { - case ShaperPresetType::None: - break; - case ShaperPresetType::Log2_48_nits: - outputDeviceTransformType = OutputDeviceTransformType::OutputDeviceTransformType_48Nits; - break; - case ShaperPresetType::Log2_1000_nits: - outputDeviceTransformType = OutputDeviceTransformType::OutputDeviceTransformType_1000Nits; - break; - case ShaperPresetType::Log2_2000_nits: - outputDeviceTransformType = OutputDeviceTransformType::OutputDeviceTransformType_2000Nits; - break; - case ShaperPresetType::Log2_4000_nits: - outputDeviceTransformType = OutputDeviceTransformType::OutputDeviceTransformType_4000Nits; - break; - default: - AZ_Error("DisplayMapperPass", false, "Invalid shaper preset type."); - break; - } - if (outputDeviceTransformType < OutputDeviceTransformType::NumOutputDeviceTransformTypes) - { - shaperParams = GetAcesShaperParameters(outputDeviceTransformType); - } - return shaperParams; + AZ_Error("AcesDisplayMapperFeatureProcessor", false, "Failed to initialize LUT image."); + return; } - void AcesDisplayMapperFeatureProcessor::GetDefaultDisplayMapperConfiguration(DisplayMapperConfigurationDescriptor& config) + lutResource.m_lutImageViewDescriptor = RHI::ImageViewDescriptor::Create(LutFormat, 0, 0); + lutResource.m_lutImageView = lutResource.m_lutImage->GetImageView(lutResource.m_lutImageViewDescriptor); + if (!lutResource.m_lutImageView.get()) { - // Default configuration is ACES with LDR color grading LUT disabled. - config.m_operationType = DisplayMapperOperationType::Aces; - config.m_ldrGradingLutEnabled = false; - config.m_ldrColorGradingLut.Release(); + AZ_Error("AcesDisplayMapperFeatureProcessor", false, "Failed to initialize LUT image view."); + return; } - void AcesDisplayMapperFeatureProcessor::RegisterDisplayMapperConfiguration(const DisplayMapperConfigurationDescriptor& config) - { - m_displayMapperConfiguration = config; - } + // Add to the list of lut resources + lutResource.m_lutImageView->SetName(lutName); + m_ownedLuts[lutName] = lutResource; + } - DisplayMapperConfigurationDescriptor AcesDisplayMapperFeatureProcessor::GetDisplayMapperConfiguration() + ShaperParams AcesDisplayMapperFeatureProcessor::GetShaperParameters(ShaperPresetType shaperPreset, float customMinEv, float customMaxEv) + { + // Default is a linear shaper with bias 0.0 and scale 1.0. That is, fx = x*1.0 + 0.0 + ShaperParams shaperParams = { ShaperType::Linear, 0.0, 1.f }; + switch (shaperPreset) { - return m_displayMapperConfiguration; + case ShaperPresetType::None: + break; + case ShaperPresetType::Log2_48Nits: + shaperParams = GetAcesShaperParameters(OutputDeviceTransformType::OutputDeviceTransformType_48Nits); + break; + case ShaperPresetType::Log2_1000Nits: + shaperParams = GetAcesShaperParameters(OutputDeviceTransformType::OutputDeviceTransformType_1000Nits); + break; + case ShaperPresetType::Log2_2000Nits: + shaperParams = GetAcesShaperParameters(OutputDeviceTransformType::OutputDeviceTransformType_2000Nits); + break; + case ShaperPresetType::Log2_4000Nits: + shaperParams = GetAcesShaperParameters(OutputDeviceTransformType::OutputDeviceTransformType_4000Nits); + break; + case ShaperPresetType::LinearCustomRange: + { + // Map the range min exposure - max exposure to 0-1. Convert EV values to linear values here to avoid that work in the shader. + // Shader equation becomes (x - bias) / scale; + constexpr float MediumGray = 0.18f; + const float minValue = MediumGray * powf(2, customMinEv); + const float maxValue = MediumGray * powf(2, customMaxEv); + shaperParams.m_type = ShaperType::Linear; + shaperParams.m_scale = 1.0f / (maxValue - minValue); + shaperParams.m_bias = -minValue * shaperParams.m_scale; + break; } - } // namespace Render -} // namespace AZ + case ShaperPresetType::Log2CustomRange: + shaperParams = GetLog2ShaperParameters(customMinEv, customMaxEv); + break; + case ShaperPresetType::PqSmpteSt2084: + shaperParams.m_type = ShaperType::PqSmpteSt2084; + break; + default: + AZ_Error("DisplayMapperPass", false, "Invalid shaper preset type."); + break; + } + return shaperParams; + } + + void AcesDisplayMapperFeatureProcessor::GetDefaultDisplayMapperConfiguration(DisplayMapperConfigurationDescriptor& config) + { + // Default configuration is ACES with LDR color grading LUT disabled. + config.m_operationType = DisplayMapperOperationType::Aces; + config.m_ldrGradingLutEnabled = false; + config.m_ldrColorGradingLut.Release(); + } + + void AcesDisplayMapperFeatureProcessor::RegisterDisplayMapperConfiguration(const DisplayMapperConfigurationDescriptor& config) + { + m_displayMapperConfiguration = config; + } + + DisplayMapperConfigurationDescriptor AcesDisplayMapperFeatureProcessor::GetDisplayMapperConfiguration() + { + return m_displayMapperConfiguration; + } +} // namespace AZ::Render diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp index 7f9bae7e49..214643505a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/AuxGeomDrawQueue.cpp @@ -649,7 +649,7 @@ namespace AZ AZ::u8 width, int32_t viewProjOverrideIndex) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); // grab a mutex lock for the rest of this function so that a commit cannot happen during it and // other threads can't add geometry during it @@ -720,7 +720,7 @@ namespace AZ AZ::u8 width, int32_t viewProjOverrideIndex) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("AuxGeom", "AuxGeomDrawQueue: DrawPrimitiveWithSharedVerticesCommon"); AZ_Assert(indexCount >= verticesPerPrimitiveType && (indexCount % verticesPerPrimitiveType == 0), diff --git a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp index f2b3a93a53..0045311bef 100644 --- a/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/AuxGeom/FixedShapeProcessor.cpp @@ -127,7 +127,7 @@ namespace AZ void FixedShapeProcessor::ProcessObjects(const AuxGeomBufferData* bufferData, const RPI::FeatureProcessor::RenderPacket& fpPacket) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("AuxGeom", "FixedShapeProcessor: ProcessObjects"); RHI::DrawPacketBuilder drawPacketBuilder; @@ -405,15 +405,15 @@ namespace AZ for (uint16_t ring = 0; ring < numRings - 2; ++ring) { - uint16_t firstVertOfThisRing = 1 + ring * numSections; - uint16_t firstVertOfNextRing = 1 + (ring + 1) * numSections; + uint16_t firstVertOfThisRing = static_cast(1 + ring * numSections); + uint16_t firstVertOfNextRing = static_cast(1 + (ring + 1) * numSections); for (uint16_t section = 0; section < numSections; ++section) { uint32_t nextSection = (section + 1) % numSections; // line around ring indices.push_back(firstVertOfThisRing + section); - indices.push_back(firstVertOfThisRing + nextSection); + indices.push_back(static_cast(firstVertOfThisRing + nextSection)); // line around section indices.push_back(firstVertOfThisRing + section); @@ -423,15 +423,15 @@ namespace AZ // build faces for end caps (to connect "inner" vertices with poles) uint16_t firstPoleVert = 0; - uint16_t firstVertOfFirstRing = 1 + (0) * numSections; + uint16_t firstVertOfFirstRing = static_cast(1 + (0) * numSections); for (uint16_t section = 0; section < numSections; ++section) { indices.push_back(firstPoleVert); indices.push_back(firstVertOfFirstRing + section); } - uint16_t lastPoleVert = (numRings - 1) * numSections + 1; - uint16_t firstVertOfLastRing = 1 + (numRings - 2) * numSections; + uint16_t lastPoleVert = static_cast((numRings - 1) * numSections + 1); + uint16_t firstVertOfLastRing = static_cast(1 + (numRings - 2) * numSections); for (uint16_t section = 0; section < numSections; ++section) { indices.push_back(firstVertOfLastRing + section); @@ -457,13 +457,13 @@ namespace AZ for (uint32_t section = 0; section < numSections; ++section) { uint32_t nextSection = (section + 1) % numSections; - indices.push_back((uint16_t)firstVertOfThisRing + nextSection); - indices.push_back((uint16_t)firstVertOfThisRing + section); - indices.push_back((uint16_t)firstVertOfNextRing + nextSection); + indices.push_back(static_cast(firstVertOfThisRing + nextSection)); + indices.push_back(static_cast(firstVertOfThisRing + section)); + indices.push_back(static_cast(firstVertOfNextRing + nextSection)); - indices.push_back((uint16_t)firstVertOfNextRing + section); - indices.push_back((uint16_t)firstVertOfNextRing + nextSection); - indices.push_back((uint16_t)firstVertOfThisRing + section); + indices.push_back(static_cast(firstVertOfNextRing + section)); + indices.push_back(static_cast(firstVertOfNextRing + nextSection)); + indices.push_back(static_cast(firstVertOfThisRing + section)); } } @@ -473,9 +473,9 @@ namespace AZ for (uint32_t section = 0; section < numSections; ++section) { uint32_t nextSection = (section + 1) % numSections; - indices.push_back((uint16_t)firstVertOfFirstRing + section); - indices.push_back((uint16_t)firstVertOfFirstRing + nextSection); - indices.push_back((uint16_t)firstPoleVert); + indices.push_back(static_cast(firstVertOfFirstRing + section)); + indices.push_back(static_cast(firstVertOfFirstRing + nextSection)); + indices.push_back(static_cast(firstPoleVert)); } uint32_t lastPoleVert = (numRings - 1) * numSections + 1; @@ -483,9 +483,9 @@ namespace AZ for (uint32_t section = 0; section < numSections; ++section) { uint32_t nextSection = (section + 1) % numSections; - indices.push_back((uint16_t)firstVertOfLastRing + nextSection); - indices.push_back((uint16_t)firstVertOfLastRing + section); - indices.push_back((uint16_t)lastPoleVert); + indices.push_back(static_cast(firstVertOfLastRing + nextSection)); + indices.push_back(static_cast(firstVertOfLastRing + section)); + indices.push_back(static_cast(lastPoleVert)); } } } @@ -637,12 +637,12 @@ namespace AZ { // Line from center of disk to outer edge meshData.m_lineIndices.push_back(centerIndex); - meshData.m_lineIndices.push_back(firstSection + section); + meshData.m_lineIndices.push_back(static_cast(firstSection + section)); // Line from outer edge to next edge - meshData.m_lineIndices.push_back(firstSection + section); + meshData.m_lineIndices.push_back(static_cast(firstSection + section)); uint32_t nextSection = (section + 1) % numSections; - meshData.m_lineIndices.push_back(firstSection + nextSection); + meshData.m_lineIndices.push_back(static_cast(firstSection + nextSection)); } // Create triangle indices @@ -652,13 +652,13 @@ namespace AZ meshData.m_triangleIndices.push_back(centerIndex); if (isUp) { - meshData.m_triangleIndices.push_back(firstSection + nextSection); - meshData.m_triangleIndices.push_back(firstSection + section); + meshData.m_triangleIndices.push_back(static_cast(firstSection + nextSection)); + meshData.m_triangleIndices.push_back(static_cast(firstSection + section)); } else { - meshData.m_triangleIndices.push_back(firstSection + section); - meshData.m_triangleIndices.push_back(firstSection + nextSection); + meshData.m_triangleIndices.push_back(static_cast(firstSection + section)); + meshData.m_triangleIndices.push_back(static_cast(firstSection + nextSection)); } } } @@ -776,7 +776,7 @@ namespace AZ normals.push_back(AuxGeomNormal(0.0f, 1.0f, 0.0f)); // vertex indexes for start of the cone sides and for the cone point - uint16_t indexOfSidesStart = numSections + 1; + uint16_t indexOfSidesStart = static_cast(numSections + 1); uint32_t indexOfConePoint = indexOfSidesStart + numRings * numSections; // indices for points @@ -795,8 +795,8 @@ namespace AZ // build lines between already completed cap for each section for (uint16_t section = 0; section < numSections; ++section) { - indices.push_back(indexOfSidesStart + numRings * section); - indices.push_back(indexOfConePoint); + indices.push_back(static_cast(indexOfSidesStart + numRings * section)); + indices.push_back(static_cast(indexOfConePoint)); } } @@ -812,19 +812,19 @@ namespace AZ // faces from end cap to close to point for (uint32_t ring = 0; ring < numRings - 1; ++ring) { - indices.push_back(indexOfSidesStart + numRings * nextSection + ring + 1); - indices.push_back(indexOfSidesStart + numRings * nextSection + ring); - indices.push_back(indexOfSidesStart + numRings * section + ring); + indices.push_back(static_cast(indexOfSidesStart + numRings * nextSection + ring + 1)); + indices.push_back(static_cast(indexOfSidesStart + numRings * nextSection + ring)); + indices.push_back(static_cast(indexOfSidesStart + numRings * section + ring)); - indices.push_back(indexOfSidesStart + numRings * section + ring); - indices.push_back(indexOfSidesStart + numRings * section + ring + 1); - indices.push_back(indexOfSidesStart + numRings * nextSection + ring + 1); + indices.push_back(static_cast(indexOfSidesStart + numRings * section + ring)); + indices.push_back(static_cast(indexOfSidesStart + numRings * section + ring + 1)); + indices.push_back(static_cast(indexOfSidesStart + numRings * nextSection + ring + 1)); } // faces for point (from last ring of verts to point) - indices.push_back(indexOfConePoint); - indices.push_back(indexOfSidesStart + numRings * nextSection + numRings - 1); - indices.push_back(indexOfSidesStart + numRings * section + numRings - 1); + indices.push_back(static_cast(indexOfConePoint)); + indices.push_back(static_cast(indexOfSidesStart + numRings * nextSection + numRings - 1)); + indices.push_back(static_cast(indexOfSidesStart + numRings * section + numRings - 1)); } } } @@ -912,7 +912,7 @@ namespace AZ //uint16_t indexOfBottomStart = 1; //uint16_t indexOfTopCenter = numSections + 1; //uint16_t indexOfTopStart = numSections + 2; - uint16_t indexOfSidesStart = 2 * numSections + 2; + uint16_t indexOfSidesStart = static_cast(2 * numSections + 2); // build point indices { diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.cpp index b75f0481ec..683295cf5b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.cpp @@ -107,8 +107,7 @@ namespace AZ if (m_deviceBufferNeedsUpdate) { - [[maybe_unused]] bool success = m_lightBufferHandler.UpdateBuffer(m_capsuleLightData.GetDataVector()); - AZ_Error(FeatureProcessorName, success, "Unable to update buffer during Simulate()."); + m_lightBufferHandler.UpdateBuffer(m_capsuleLightData.GetDataVector()); m_deviceBufferNeedsUpdate = false; } } diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.cpp index 33123d67a1..5529a2916b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CascadedShadowmapsPass.cpp @@ -126,7 +126,7 @@ namespace AZ return; } - SetCascadesCount(m_arraySize); + SetCascadesCount(static_cast(m_arraySize)); const RHI::Size imageSize { aznumeric_cast(m_shadowmapSize), diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp index 4aa749f7d7..6a418117fc 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp @@ -225,7 +225,7 @@ namespace AZ } if (segmentsNeedUpdate) { - UpdateViewsOfCascadeSegments(m_shadowingLightHandle, cascadeCount); + UpdateViewsOfCascadeSegments(m_shadowingLightHandle, static_cast(cascadeCount)); SetShadowmapImageSizeArraySize(m_shadowingLightHandle); } @@ -933,9 +933,10 @@ namespace AZ uint16_t DirectionalLightFeatureProcessor::GetCascadeCount(LightHandle handle) const { - for (const auto& segmentIt : m_shadowProperties.GetData(handle.GetIndex()).m_segments) + const auto& segments = m_shadowProperties.GetData(handle.GetIndex()).m_segments; + if (!segments.empty()) { - return aznumeric_cast(segmentIt.second.size()); + return aznumeric_cast(segments.begin()->second.size()); } return 0; } @@ -1216,7 +1217,7 @@ namespace AZ else { // If ESM is not used, set filter offsets and filter counts zero in ESM data. - for (uint32_t index = 0; index < GetCascadeCount(handle); ++index) + for (uint16_t index = 0; index < GetCascadeCount(handle); ++index) { EsmShadowmapsPass::FilterParameter& filterParameter = m_esmParameterData.at(cameraView).GetData(index); filterParameter.m_isEnabled = false; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp index a88c587f66..03a423f6db 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.cpp @@ -159,7 +159,7 @@ namespace AZ void LightCullingPass::ResetInternal() { - m_tileDataIndex = -1; + m_tileDataIndex = std::numeric_limits::max(); m_constantDataIndex.Reset(); for (auto& elem : m_lightdata) @@ -234,7 +234,7 @@ namespace AZ return i; } } - return -1; + return std::numeric_limits::max(); } AZ::RHI::Size LightCullingPass::GetTileDataBufferResolution() diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.h index af230b8d57..9fa81bd7de 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingPass.h @@ -94,7 +94,7 @@ namespace AZ Data::Instance m_lightList; - uint32_t m_tileDataIndex = -1; + uint32_t m_tileDataIndex = std::numeric_limits::max(); }; } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp index e4881ed665..1a03b7ef38 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/LightCullingRemap.cpp @@ -101,7 +101,7 @@ namespace AZ return i; } } - return -1; + return std::numeric_limits::max(); } void LightCullingRemap::BuildInternal() diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.h index f1607191fc..dc7df7de78 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ProjectedShadowmapsPass.h @@ -30,7 +30,7 @@ namespace AZ AZ_CLASS_ALLOCATOR(ProjectedShadowmapsPass, SystemAllocator, 0); AZ_RTTI(ProjectedShadowmapsPass, "00024B13-1095-40FA-BEC3-B0F68110BEA2", Base); - static constexpr uint16_t InvalidIndex = ~0; + static constexpr uint16_t InvalidIndex = std::numeric_limits::max(); struct ShadowmapSizeWithIndices { ShadowmapSize m_size = ShadowmapSize::None; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapAtlas.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapAtlas.h index 5081a9ef9e..f0a372ec5b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapAtlas.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapAtlas.h @@ -52,7 +52,7 @@ namespace AZ // then m_nextTableOffset == 0, which works as the terminator for seaching // a shadowmap index in a compute shader. uint32_t m_nextTableOffset = 0; - uint32_t m_shadowmapIndex = ~0; // invalid index + uint32_t m_shadowmapIndex = std::numeric_limits::max(); // invalid index }; //! This initializes the packing of shadowmap sizes. @@ -156,7 +156,7 @@ namespace AZ //! [2,2,2] indicates (0, 1024+512)-(0+511, 1024+512+511) of slice:2 (width 512). using Location = AZStd::vector; static constexpr uint8_t LocationIndexNum = 4; - static constexpr size_t InvalidIndex = ~0; + static constexpr size_t InvalidIndex = std::numeric_limits::max(); struct LocationHasher { diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp index b03d456505..4954ffc01c 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp @@ -112,8 +112,7 @@ namespace AZ if (m_deviceBufferNeedsUpdate) { - [[maybe_unused]] bool success = m_decalBufferHandler.UpdateBuffer(m_decalData.GetDataVector<0>()); - AZ_Error(FeatureProcessorName, success, "Unable to update buffer during Simulate()."); + m_decalBufferHandler.UpdateBuffer(m_decalData.GetDataVector<0>()); m_deviceBufferNeedsUpdate = false; } } diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArray.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArray.cpp index 6531a04e22..ebdc884ecf 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArray.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArray.cpp @@ -147,7 +147,7 @@ namespace AZ RPI::ImageMipChainAssetCreator assetCreator; const uint32_t mipLevels = GetNumMipLevels(); - assetCreator.Begin(Data::AssetId(AZ::Uuid::CreateRandom()), mipLevels, aznumeric_cast(numTexturesToCreate)); + assetCreator.Begin(Data::AssetId(AZ::Uuid::CreateRandom()), static_cast(mipLevels), aznumeric_cast(numTexturesToCreate)); for (uint32_t mipLevel = 0; mipLevel < mipLevels; ++mipLevel) { diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp index bda7e2463b..4ecfd7fc09 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp @@ -145,13 +145,12 @@ namespace AZ void DecalTextureArrayFeatureProcessor::Simulate(const RPI::FeatureProcessor::SimulatePacket& packet) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender) + AZ_PROFILE_FUNCTION(AzRender); AZ_UNUSED(packet); if (m_deviceBufferNeedsUpdate) { - [[maybe_unused]] bool success = m_decalBufferHandler.UpdateBuffer(m_decalData.GetDataVector()); - AZ_Error(FeatureProcessorName, success, "Unable to update buffer during Simulate()."); + m_decalBufferHandler.UpdateBuffer(m_decalData.GetDataVector()); m_deviceBufferNeedsUpdate = false; } } @@ -159,7 +158,7 @@ namespace AZ void DecalTextureArrayFeatureProcessor::Render(const RPI::FeatureProcessor::RenderPacket& packet) { // Note that decals are rendered as part of the forward shading pipeline. We only need to bind the decal buffers/textures in here. - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender) + AZ_PROFILE_FUNCTION(AzRender); for (const RPI::ViewPtr& view : packet.m_views) { @@ -295,7 +294,7 @@ namespace AZ void DecalTextureArrayFeatureProcessor::SetDecalMaterial(const DecalHandle handle, const AZ::Data::AssetId material) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Renderer); + AZ_PROFILE_FUNCTION(AzRender); if (handle.IsNull()) { AZ_Warning("DecalTextureArrayFeatureProcessor", false, "Invalid handle passed to DecalTextureArrayFeatureProcessor::SetDecalMaterial()."); @@ -365,7 +364,7 @@ namespace AZ void DecalTextureArrayFeatureProcessor::OnAssetReady(const Data::Asset asset) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Renderer); + AZ_PROFILE_FUNCTION(AzRender); const Data::AssetId& assetId = asset->GetId(); const RPI::MaterialAsset* materialAsset = asset.GetAs(); diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp index a3927b802d..69a4ecdee5 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendDistancePass.cpp @@ -72,9 +72,9 @@ namespace AZ return; } - m_dispatchArgs.m_threadsPerGroupX = AZStd::any_cast(args[0]); - m_dispatchArgs.m_threadsPerGroupY = AZStd::any_cast(args[1]); - m_dispatchArgs.m_threadsPerGroupZ = AZStd::any_cast(args[2]); + m_dispatchArgs.m_threadsPerGroupX = static_cast(AZStd::any_cast(args[0])); + m_dispatchArgs.m_threadsPerGroupY = static_cast(AZStd::any_cast(args[1])); + m_dispatchArgs.m_threadsPerGroupZ = static_cast(AZStd::any_cast(args[2])); } } diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp index 6ff8bdd867..83ef312bf4 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBlendIrradiancePass.cpp @@ -72,9 +72,9 @@ namespace AZ return; } - m_dispatchArgs.m_threadsPerGroupX = AZStd::any_cast(args[0]); - m_dispatchArgs.m_threadsPerGroupY = AZStd::any_cast(args[1]); - m_dispatchArgs.m_threadsPerGroupZ = AZStd::any_cast(args[2]); + m_dispatchArgs.m_threadsPerGroupX = static_cast(AZStd::any_cast(args[0])); + m_dispatchArgs.m_threadsPerGroupY = static_cast(AZStd::any_cast(args[1])); + m_dispatchArgs.m_threadsPerGroupZ = static_cast(AZStd::any_cast(args[2])); } } diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp index ddfe0f11b1..b251526cb4 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridBorderUpdatePass.cpp @@ -85,9 +85,9 @@ namespace AZ return; } - dispatchArgs.m_threadsPerGroupX = AZStd::any_cast(args[0]); - dispatchArgs.m_threadsPerGroupY = AZStd::any_cast(args[1]); - dispatchArgs.m_threadsPerGroupZ = AZStd::any_cast(args[2]); + dispatchArgs.m_threadsPerGroupX = static_cast(AZStd::any_cast(args[0])); + dispatchArgs.m_threadsPerGroupY = static_cast(AZStd::any_cast(args[1])); + dispatchArgs.m_threadsPerGroupZ = static_cast(AZStd::any_cast(args[2])); } } diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp index 4c6b07d780..2690f90a7d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridClassificationPass.cpp @@ -76,9 +76,9 @@ namespace AZ return; } - m_dispatchArgs.m_threadsPerGroupX = AZStd::any_cast(args[0]); - m_dispatchArgs.m_threadsPerGroupY = AZStd::any_cast(args[1]); - m_dispatchArgs.m_threadsPerGroupZ = AZStd::any_cast(args[2]); + m_dispatchArgs.m_threadsPerGroupX = static_cast(AZStd::any_cast(args[0])); + m_dispatchArgs.m_threadsPerGroupY = static_cast(AZStd::any_cast(args[1])); + m_dispatchArgs.m_threadsPerGroupZ = static_cast(AZStd::any_cast(args[2])); } } diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp index 378e1923f7..543851da0f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp @@ -111,7 +111,7 @@ namespace AZ void DiffuseProbeGridFeatureProcessor::Simulate([[maybe_unused]] const FeatureProcessor::SimulatePacket& packet) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); // update pipeline states if (m_needUpdatePipelineStates) @@ -149,7 +149,7 @@ namespace AZ // if the volumes changed we need to re-sort the probe list if (m_probeGridSortRequired) { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "Sort diffuse probe grids"); + AZ_PROFILE_SCOPE(AzRender, "Sort diffuse probe grids"); // sort the probes by descending inner volume size, so the smallest volumes are rendered last auto sortFn = [](AZStd::shared_ptr const& probe1, AZStd::shared_ptr const& probe2) -> bool diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp index 54cf9783cd..67fb95a833 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridRelocationPass.cpp @@ -76,9 +76,9 @@ namespace AZ return; } - m_dispatchArgs.m_threadsPerGroupX = AZStd::any_cast(args[0]); - m_dispatchArgs.m_threadsPerGroupY = AZStd::any_cast(args[1]); - m_dispatchArgs.m_threadsPerGroupZ = AZStd::any_cast(args[2]); + m_dispatchArgs.m_threadsPerGroupX = static_cast(AZStd::any_cast(args[0])); + m_dispatchArgs.m_threadsPerGroupY = static_cast(AZStd::any_cast(args[1])); + m_dispatchArgs.m_threadsPerGroupZ = static_cast(AZStd::any_cast(args[2])); } } diff --git a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/AcesOutputTransformLutPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/AcesOutputTransformLutPass.cpp index a00f879bca..3b2913aefd 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/AcesOutputTransformLutPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/AcesOutputTransformLutPass.cpp @@ -91,8 +91,8 @@ namespace AZ m_shaderResourceGroup->SetImageView(m_shaderInputLutImageIndex, m_displayMapperLut.m_lutImageView.get()); } - m_shaderResourceGroup->SetConstant(m_shaderInputShaperBiasIndex, m_shaperParams.bias); - m_shaderResourceGroup->SetConstant(m_shaderInputShaperScaleIndex, m_shaperParams.scale); + m_shaderResourceGroup->SetConstant(m_shaderInputShaperBiasIndex, m_shaperParams.m_bias); + m_shaderResourceGroup->SetConstant(m_shaderInputShaperScaleIndex, m_shaperParams.m_scale); } BindPassSrg(context, m_shaderResourceGroup); diff --git a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/ApplyShaperLookupTablePass.cpp b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/ApplyShaperLookupTablePass.cpp index eec511c07a..f4325f0421 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/ApplyShaperLookupTablePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/ApplyShaperLookupTablePass.cpp @@ -109,9 +109,9 @@ namespace AZ { m_shaderResourceGroup->SetImageView(m_shaderInputLutImageIndex, m_lutResource.m_lutStreamingImage->GetImageView()); - m_shaderResourceGroup->SetConstant(m_shaderShaperTypeIndex, m_shaperParams.type); - m_shaderResourceGroup->SetConstant(m_shaderShaperBiasIndex, m_shaperParams.bias); - m_shaderResourceGroup->SetConstant(m_shaderShaperScaleIndex, m_shaperParams.scale); + m_shaderResourceGroup->SetConstant(m_shaderShaperTypeIndex, m_shaperParams.m_type); + m_shaderResourceGroup->SetConstant(m_shaderShaperBiasIndex, m_shaperParams.m_bias); + m_shaderResourceGroup->SetConstant(m_shaderShaperScaleIndex, m_shaperParams.m_scale); } } } diff --git a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/BakeAcesOutputTransformLutPass.cpp b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/BakeAcesOutputTransformLutPass.cpp index f7ecfc3461..a8d1b68d63 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/BakeAcesOutputTransformLutPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DisplayMapper/BakeAcesOutputTransformLutPass.cpp @@ -94,8 +94,8 @@ namespace AZ m_shaderResourceGroup->SetImageView(m_shaderInputLutImageIndex, m_displayMapperLut.m_lutImageView.get()); - m_shaderResourceGroup->SetConstant(m_shaderInputShaperBiasIndex, m_shaperParams.bias); - m_shaderResourceGroup->SetConstant(m_shaderInputShaperScaleIndex, m_shaperParams.scale); + m_shaderResourceGroup->SetConstant(m_shaderInputShaperBiasIndex, m_shaperParams.m_bias); + m_shaderResourceGroup->SetConstant(m_shaderInputShaperScaleIndex, m_shaperParams.m_scale); } BindPassSrg(context, m_shaderResourceGroup); diff --git a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp index cd781390a3..a885708a47 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.cpp @@ -67,8 +67,8 @@ namespace AZ ImGuiPass::ImGuiPass(const RPI::PassDescriptor& descriptor) : Base(descriptor) - , AzFramework::InputChannelEventListener(AzFramework::InputChannelEventListener::GetPriorityUI()) - , AzFramework::InputTextEventListener(AzFramework::InputTextEventListener::GetPriorityUI()) + , AzFramework::InputChannelEventListener(AzFramework::InputChannelEventListener::GetPriorityDebugUI() - 1) // Give ImGui manager priority over the pass + , AzFramework::InputTextEventListener(AzFramework::InputTextEventListener::GetPriorityDebugUI() - 1) // Give ImGui manager priority over the pass { const ImGuiPassData* imguiPassData = RPI::PassUtils::GetPassData(descriptor); @@ -157,11 +157,6 @@ namespace AZ return io.WantTextInput; } - AZ::s32 ImGuiPass::GetPriority() const - { - return AzFramework::InputChannelEventListener::GetPriorityUI(); - } - bool ImGuiPass::OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) { if (!IsEnabled() || GetRenderPipeline()->GetScene() == nullptr) @@ -396,12 +391,12 @@ namespace AZ { auto imguiContextScope = ImguiContextScope(m_imguiContext); - m_viewportWidth = params.m_viewportState.m_maxX - params.m_viewportState.m_minX; - m_viewportHeight = params.m_viewportState.m_maxY - params.m_viewportState.m_minY; + m_viewportWidth = static_cast(params.m_viewportState.m_maxX - params.m_viewportState.m_minX); + m_viewportHeight = static_cast(params.m_viewportState.m_maxY - params.m_viewportState.m_minY); auto& io = ImGui::GetIO(); - io.DisplaySize.x = AZStd::max(1.0f, m_viewportWidth); - io.DisplaySize.y = AZStd::max(1.0f, m_viewportHeight); + io.DisplaySize.x = AZStd::max(1.0f, static_cast(m_viewportWidth)); + io.DisplaySize.y = AZStd::max(1.0f, static_cast(m_viewportHeight)); Matrix4x4 projectionMatrix = Matrix4x4::CreateFromRows( @@ -547,8 +542,8 @@ namespace AZ for (const ImDrawCmd& drawCmd : drawList->CmdBuffer) { AZ_Assert(drawCmd.UserCallback == nullptr, "ImGui UserCallbacks are not supported by the ImGui Pass"); - uint32_t scissorMaxX = drawCmd.ClipRect.z; - uint32_t scissorMaxY = drawCmd.ClipRect.w; + uint32_t scissorMaxX = static_cast(drawCmd.ClipRect.z); + uint32_t scissorMaxY = static_cast(drawCmd.ClipRect.w); //scissorMaxX/scissorMaxY can be a frame stale from imgui (ImGui::NewFrame runs after this) hence we clamp it to viewport bounds //otherwise it is possible to have a frame where scissor bounds can be bigger than window's bounds if we resize the window @@ -559,8 +554,8 @@ namespace AZ { RHI::DrawIndexed(1, 0, vertexOffset, drawCmd.ElemCount, indexOffset), RHI::Scissor( - (drawCmd.ClipRect.x), - (drawCmd.ClipRect.y), + static_cast(drawCmd.ClipRect.x), + static_cast(drawCmd.ClipRect.y), scissorMaxX, scissorMaxY ) @@ -582,7 +577,7 @@ namespace AZ void ImGuiPass::BuildCommandListInternal(const RHI::FrameGraphExecuteContext& context) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("Pass", "ImGuiPass: Execute"); context.GetCommandList()->SetViewport(m_viewportState); @@ -612,7 +607,7 @@ namespace AZ uint32_t ImGuiPass::UpdateImGuiResources() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("Pass", "ImGuiPass: UpdateImGuiResources"); auto imguiContextScope = ImguiContextScope(m_imguiContext); diff --git a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h index 76cf29a573..0bde3edb4f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/ImGui/ImGuiPass.h @@ -84,7 +84,6 @@ namespace AZ // AzFramework::InputChannelEventListener overrides... bool OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) override; - AZ::s32 GetPriority() const override; protected: explicit ImGuiPass(const RPI::PassDescriptor& descriptor); diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialConverterSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialConverterSystemComponent.cpp index d173018ef7..e26a0fb274 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialConverterSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialConverterSystemComponent.cpp @@ -12,12 +12,26 @@ #include #include #include +#include #include +#include + namespace AZ { namespace Render { + void MaterialConverterSettings::Reflect(AZ::ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("Enable", &MaterialConverterSettings::m_enable) + ->Field("DefaultMaterial", &MaterialConverterSettings::m_defaultMaterial); + } + } + void MaterialConverterSystemComponent::Reflect(AZ::ReflectContext* context) { if (auto* serialize = azrtti_cast(context)) @@ -26,10 +40,22 @@ namespace AZ ->Version(3) ->Attribute(Edit::Attributes::SystemComponentTags, AZStd::vector({ AssetBuilderSDK::ComponentTags::AssetBuilder })); } + + MaterialConverterSettings::Reflect(context); + } + + void MaterialConverterSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services) + { + services.emplace_back(AZ_CRC_CE("FingerprintModification")); } void MaterialConverterSystemComponent::Activate() { + if (auto* settingsRegistry = AZ::SettingsRegistry::Get()) + { + settingsRegistry->GetObject(m_settings, "/O3DE/SceneAPI/MaterialConverter"); + } + RPI::MaterialConverterBus::Handler::BusConnect(); } @@ -37,11 +63,21 @@ namespace AZ { RPI::MaterialConverterBus::Handler::BusDisconnect(); } + + bool MaterialConverterSystemComponent::IsEnabled() const + { + return m_settings.m_enable; + } bool MaterialConverterSystemComponent::ConvertMaterial( const AZ::SceneAPI::DataTypes::IMaterialData& materialData, RPI::MaterialSourceData& sourceData) { using namespace AZ::RPI; + + if (!m_settings.m_enable) + { + return false; + } // The source data for generating material asset sourceData.m_materialType = GetMaterialTypePath(); @@ -140,9 +176,20 @@ namespace AZ return true; } - const char* MaterialConverterSystemComponent::GetMaterialTypePath() const + AZStd::string MaterialConverterSystemComponent::GetMaterialTypePath() const { return "Materials/Types/StandardPBR.materialtype"; } + + AZStd::string MaterialConverterSystemComponent::GetDefaultMaterialPath() const + { + if (m_settings.m_defaultMaterial.empty()) + { + AZ_Error("MaterialConverterSystemComponent", m_settings.m_enable, + "Material conversion is disabled but a default material not specified in registry /O3DE/SceneAPI/MaterialConverter/DefaultMaterial"); + } + + return m_settings.m_defaultMaterial; + } } } diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialConverterSystemComponent.h b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialConverterSystemComponent.h index 38d4faedc8..7d95024759 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialConverterSystemComponent.h +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialConverterSystemComponent.h @@ -18,6 +18,16 @@ namespace AZ { namespace Render { + struct MaterialConverterSettings + { + AZ_TYPE_INFO(MaterialConverterSettings, "{8D91601D-570A-4557-99C8-631DB4928040}"); + + static void Reflect(AZ::ReflectContext* context); + + bool m_enable = true; + AZStd::string m_defaultMaterial; + }; + //! Atom's implementation of converting SceneAPI data into Atom's default material: StandardPBR class MaterialConverterSystemComponent final : public AZ::Component @@ -27,13 +37,20 @@ namespace AZ AZ_COMPONENT(MaterialConverterSystemComponent, "{C2338D45-6456-4521-B469-B000A13F2493}"); static void Reflect(AZ::ReflectContext* context); + + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services); void Activate() override; void Deactivate() override; // MaterialConverterBus overrides ... + bool IsEnabled() const override; bool ConvertMaterial(const AZ::SceneAPI::DataTypes::IMaterialData& materialData, RPI::MaterialSourceData& out) override; - const char* GetMaterialTypePath() const override; + AZStd::string GetMaterialTypePath() const override; + AZStd::string GetDefaultMaterialPath() const override; + + private: + MaterialConverterSettings m_settings; }; } } diff --git a/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp index 8e2c6f2e9b..6ed37ce972 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp @@ -75,7 +75,7 @@ namespace AZ void MeshFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RPI", "MeshFeatureProcessor: Simulate"); AZ_UNUSED(packet); @@ -87,7 +87,7 @@ namespace AZ { const auto jobLambda = [&]() -> void { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "MeshFP::Simulate() Lambda"); + AZ_PROFILE_SCOPE(AzRender, "MeshFP::Simulate() Lambda"); for (auto meshDataIter = iteratorRange.first; meshDataIter != iteratorRange.second; ++meshDataIter) { if (!meshDataIter->m_model) @@ -149,7 +149,7 @@ namespace AZ const MeshHandleDescriptor& descriptor, const MaterialAssignmentMap& materials) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); // don't need to check the concurrency during emplace() because the StableDynamicArray won't move the other elements during insertion MeshHandle meshDataHandle = m_meshData.emplace(); @@ -478,7 +478,7 @@ namespace AZ : m_modelAsset(modelAsset) , m_parent(parent) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); if (!m_modelAsset.GetId().IsValid()) { @@ -507,7 +507,7 @@ namespace AZ //! AssetBus::Handler overrides... void MeshDataInstance::MeshLoader::OnAssetReady(Data::Asset asset) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); Data::Asset modelAsset = asset; // Assign the fully loaded asset back to the mesh handle to not only hold asset id, but the actual data as well. @@ -579,7 +579,7 @@ namespace AZ void MeshDataInstance::Init(Data::Instance model) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); m_model = model; const size_t modelLodCount = m_model->GetLodCount(); @@ -611,7 +611,7 @@ namespace AZ void MeshDataInstance::BuildDrawPacketList(size_t modelLodIndex) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); RPI::ModelLod& modelLod = *m_model->GetLods()[modelLodIndex]; const size_t meshCount = modelLod.GetMeshes().size(); @@ -800,19 +800,19 @@ namespace AZ // note that the element count is the size of the entire buffer, even though this mesh may only // occupy a portion of the vertex buffer. This is necessary since we are accessing it using // a ByteAddressBuffer in the raytracing shaders and passing the byte offset to the shader in a constant buffer. - uint32_t positionBufferByteCount = const_cast(streamBufferViews[0].GetBuffer())->GetDescriptor().m_byteCount; + uint32_t positionBufferByteCount = static_cast(const_cast(streamBufferViews[0].GetBuffer())->GetDescriptor().m_byteCount); RHI::BufferViewDescriptor positionBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, positionBufferByteCount); - uint32_t normalBufferByteCount = const_cast(streamBufferViews[1].GetBuffer())->GetDescriptor().m_byteCount; + uint32_t normalBufferByteCount = static_cast(const_cast(streamBufferViews[1].GetBuffer())->GetDescriptor().m_byteCount); RHI::BufferViewDescriptor normalBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, normalBufferByteCount); - uint32_t tangentBufferByteCount = const_cast(streamBufferViews[2].GetBuffer())->GetDescriptor().m_byteCount; + uint32_t tangentBufferByteCount = static_cast(const_cast(streamBufferViews[2].GetBuffer())->GetDescriptor().m_byteCount); RHI::BufferViewDescriptor tangentBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, tangentBufferByteCount); - uint32_t bitangentBufferByteCount = const_cast(streamBufferViews[3].GetBuffer())->GetDescriptor().m_byteCount; + uint32_t bitangentBufferByteCount = static_cast(const_cast(streamBufferViews[3].GetBuffer())->GetDescriptor().m_byteCount); RHI::BufferViewDescriptor bitangentBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, bitangentBufferByteCount); - uint32_t uvBufferByteCount = const_cast(streamBufferViews[4].GetBuffer())->GetDescriptor().m_byteCount; + uint32_t uvBufferByteCount = static_cast(const_cast(streamBufferViews[4].GetBuffer())->GetDescriptor().m_byteCount); RHI::BufferViewDescriptor uvBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, uvBufferByteCount); const RHI::IndexBufferView& indexBufferView = mesh.m_indexBufferView; @@ -985,7 +985,7 @@ namespace AZ void MeshDataInstance::UpdateDrawPackets(bool forceUpdate /*= false*/) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); for (auto& drawPacketList : m_drawPacketListsByLod) { for (auto& drawPacket : drawPacketList) @@ -1000,7 +1000,7 @@ namespace AZ void MeshDataInstance::BuildCullable() { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_Assert(m_cullableNeedsRebuild, "This function only needs to be called if the cullable to be rebuilt"); AZ_Assert(m_model, "The model has not finished loading yet"); @@ -1079,7 +1079,7 @@ namespace AZ void MeshDataInstance::UpdateCullBounds(const TransformServiceFeatureProcessor* transformService) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_Assert(m_cullBoundsNeedsUpdate, "This function only needs to be called if the culling bounds need to be rebuilt"); AZ_Assert(m_model, "The model has not finished loading yet"); diff --git a/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetDispatchItem.cpp b/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetDispatchItem.cpp index 0f8a30d8aa..19f379b17d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetDispatchItem.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/MorphTargets/MorphTargetDispatchItem.cpp @@ -85,9 +85,9 @@ namespace AZ { const auto& args = *numThreads; // Check that the arguments are valid integers, and fall back to 1,1,1 if there is an error - arguments.m_threadsPerGroupX = args[0].type() == azrtti_typeid() ? AZStd::any_cast(args[0]) : 1; - arguments.m_threadsPerGroupY = args[1].type() == azrtti_typeid() ? AZStd::any_cast(args[1]) : 1; - arguments.m_threadsPerGroupZ = args[2].type() == azrtti_typeid() ? AZStd::any_cast(args[2]) : 1; + arguments.m_threadsPerGroupX = static_cast(args[0].type() == azrtti_typeid() ? AZStd::any_cast(args[0]) : 1); + arguments.m_threadsPerGroupY = static_cast(args[1].type() == azrtti_typeid() ? AZStd::any_cast(args[1]) : 1); + arguments.m_threadsPerGroupZ = static_cast(args[2].type() == azrtti_typeid() ? AZStd::any_cast(args[2]) : 1); } arguments.m_totalNumberOfThreadsX = m_morphTargetMetaData.m_vertexCount; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcess/LookModification/LookModificationSettings.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcess/LookModification/LookModificationSettings.cpp index d2e28e3a68..cbc357db61 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcess/LookModification/LookModificationSettings.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcess/LookModification/LookModificationSettings.cpp @@ -26,6 +26,8 @@ namespace AZ seed = TypeHash64(m_overrideStrength, seed); seed = TypeHash64(m_assetId.GetId(), seed); seed = TypeHash64(m_shaperPreset, seed); + seed = TypeHash64(m_customMinExposure, seed); + seed = TypeHash64(m_customMaxExposure, seed); return seed; } @@ -50,6 +52,9 @@ namespace AZ lutBlend.m_intensity = GetColorGradingLutIntensity(); lutBlend.m_overrideStrength = GetColorGradingLutOverride() * alpha; lutBlend.m_assetId = lutAssetId; + lutBlend.m_shaperPreset = GetShaperPresetType(); + lutBlend.m_customMinExposure = GetCustomMinExposure(); + lutBlend.m_customMaxExposure = GetCustomMaxExposure(); target->AddLutBlend(lutBlend); } } @@ -87,6 +92,9 @@ namespace AZ blendItem.m_intensity = GetColorGradingLutIntensity(); blendItem.m_overrideStrength = GetColorGradingLutOverride(); blendItem.m_assetId = GetColorGradingLut(); + blendItem.m_shaperPreset = GetShaperPresetType(); + blendItem.m_customMinExposure = GetCustomMinExposure(); + blendItem.m_customMaxExposure = GetCustomMaxExposure(); m_lutBlendStack.insert(m_lutBlendStack.begin(), blendItem); } } diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcess/LookModification/LookModificationSettings.h b/Gems/Atom/Feature/Common/Code/Source/PostProcess/LookModification/LookModificationSettings.h index 19bf07010b..d91a029ced 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcess/LookModification/LookModificationSettings.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcess/LookModification/LookModificationSettings.h @@ -33,7 +33,10 @@ namespace AZ //! Asset ID of LUT Data::Asset m_assetId; //! Shaper preset type - ShaperPresetType m_shaperPreset = AZ::Render::ShaperPresetType::Log2_48_nits; + ShaperPresetType m_shaperPreset = AZ::Render::ShaperPresetType::Log2_48Nits; + //! When shaper preset is custom, these values set min and max exposure. + float m_customMinExposure = -6.5; + float m_customMaxExposure = 6.5; HashValue64 GetHash(HashValue64 seed) const; }; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.cpp index da680d80cf..f74837bd9a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.cpp @@ -21,7 +21,7 @@ namespace AZ namespace Render { static const char* const NumSourceLutsShaderVariantOptionName{ "o_numSourceLuts" }; - + RPI::Ptr BlendColorGradingLutsPass::Create(const RPI::PassDescriptor& descriptor) { RPI::Ptr pass = aznew BlendColorGradingLutsPass(descriptor); @@ -151,9 +151,9 @@ namespace AZ { m_shaderResourceGroup->SetImageView(m_shaderInputBlendedLutImageIndex, m_blendedLut.m_lutImageView.get()); m_shaderResourceGroup->SetConstant(m_shaderInputBlendedLutDimensionsIndex, m_blendedLutDimensions); - m_shaderResourceGroup->SetConstant(m_shaderInputBlendedLutShaperTypeIndex, m_blendedLutShaperParams.type); - m_shaderResourceGroup->SetConstant(m_shaderInputBlendededLutShaperBiasIndex, m_blendedLutShaperParams.bias); - m_shaderResourceGroup->SetConstant(m_shaderInputBlendededLutShaperScaleIndex, m_blendedLutShaperParams.scale); + m_shaderResourceGroup->SetConstant(m_shaderInputBlendedLutShaperTypeIndex, m_blendedLutShaperParams.m_type); + m_shaderResourceGroup->SetConstant(m_shaderInputBlendededLutShaperBiasIndex, m_blendedLutShaperParams.m_bias); + m_shaderResourceGroup->SetConstant(m_shaderInputBlendededLutShaperScaleIndex, m_blendedLutShaperParams.m_scale); m_shaderResourceGroup->SetConstant(m_shaderInputWeight0Index, m_weights[0]); m_shaderResourceGroup->SetConstant(m_shaderInputWeight1Index, m_weights[1]); m_shaderResourceGroup->SetConstant(m_shaderInputWeight2Index, m_weights[2]); @@ -163,33 +163,33 @@ namespace AZ if (m_colorGradingLuts[0].m_lutStreamingImage) { m_shaderResourceGroup->SetImageView(m_shaderInputSourceLut1ImageIndex, m_colorGradingLuts[0].m_lutStreamingImage->GetImageView()); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut1ShaperTypeIndex, m_colorGradingShaperParams[0].type); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut1ShaperBiasIndex, m_colorGradingShaperParams[0].bias); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut1ShaperScaleIndex, m_colorGradingShaperParams[0].scale); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut1ShaperTypeIndex, m_colorGradingShaperParams[0].m_type); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut1ShaperBiasIndex, m_colorGradingShaperParams[0].m_bias); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut1ShaperScaleIndex, m_colorGradingShaperParams[0].m_scale); } if (m_colorGradingLuts[1].m_lutStreamingImage) { m_shaderResourceGroup->SetImageView(m_shaderInputSourceLut2ImageIndex, m_colorGradingLuts[1].m_lutStreamingImage->GetImageView()); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut2ShaperTypeIndex, m_colorGradingShaperParams[1].type); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut2ShaperBiasIndex, m_colorGradingShaperParams[1].bias); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut2ShaperScaleIndex, m_colorGradingShaperParams[1].scale); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut2ShaperTypeIndex, m_colorGradingShaperParams[1].m_type); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut2ShaperBiasIndex, m_colorGradingShaperParams[1].m_bias); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut2ShaperScaleIndex, m_colorGradingShaperParams[1].m_scale); } if (m_colorGradingLuts[2].m_lutStreamingImage) { m_shaderResourceGroup->SetImageView(m_shaderInputSourceLut3ImageIndex, m_colorGradingLuts[2].m_lutStreamingImage->GetImageView()); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut3ShaperTypeIndex, m_colorGradingShaperParams[2].type); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut3ShaperBiasIndex, m_colorGradingShaperParams[2].bias); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut3ShaperScaleIndex, m_colorGradingShaperParams[2].scale); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut3ShaperTypeIndex, m_colorGradingShaperParams[2].m_type); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut3ShaperBiasIndex, m_colorGradingShaperParams[2].m_bias); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut3ShaperScaleIndex, m_colorGradingShaperParams[2].m_scale); } if (m_colorGradingLuts[3].m_lutStreamingImage) { m_shaderResourceGroup->SetImageView(m_shaderInputSourceLut4ImageIndex, m_colorGradingLuts[3].m_lutStreamingImage->GetImageView()); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut4ShaperTypeIndex, m_colorGradingShaperParams[3].type); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut4ShaperBiasIndex, m_colorGradingShaperParams[3].bias); - m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut4ShaperScaleIndex, m_colorGradingShaperParams[3].scale); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut4ShaperTypeIndex, m_colorGradingShaperParams[3].m_type); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut4ShaperBiasIndex, m_colorGradingShaperParams[3].m_bias); + m_shaderResourceGroup->SetConstant(m_shaderInputSourceLut4ShaperScaleIndex, m_colorGradingShaperParams[3].m_scale); } if (m_shaderResourceGroup->HasShaderVariantKeyFallbackEntry()) @@ -244,7 +244,170 @@ namespace AZ m_blendedLutShaperParams = shaperParams; } + + AZStd::optional BlendColorGradingLutsPass::GetCommonShaperParams() const + { + LookModificationSettings* settings = GetLookModificationSettings(); + if (settings) + { + settings->PrepareLutBlending(); + + ShaperPresetType type = ShaperPresetType::NumShaperTypes; + float customMinExposure = 0.0; + float customMaxExposure = 0.0; + + for (size_t lutIndex = 0; lutIndex < settings->GetLutBlendStackSize(); lutIndex++) + { + LutBlendItem& lutBlendItem = settings->GetLutBlendItem(lutIndex); + + if (lutIndex == 0) + { + type = lutBlendItem.m_shaperPreset; + customMinExposure = lutBlendItem.m_customMinExposure; + customMaxExposure = lutBlendItem.m_customMaxExposure; + } + else if (type != lutBlendItem.m_shaperPreset) + { + // Shapers are different + return AZStd::nullopt; + } + else if (type == ShaperPresetType::LinearCustomRange || type == ShaperPresetType::Log2CustomRange) + { + if (lutBlendItem.m_customMinExposure != customMinExposure || + lutBlendItem.m_customMaxExposure != customMaxExposure) + { + // Shapers are same, but custom exposure for custom type is different. + return AZStd::nullopt; + } + } + } + + // Only calculate shaper params when there's at least one lut blend. + if (settings->GetLutBlendStackSize() > 0) + { + return AcesDisplayMapperFeatureProcessor::GetShaperParameters(type, customMinExposure, customMaxExposure); + } + } + return AZStd::nullopt; + } + void BlendColorGradingLutsPass::CheckLutBlendSettings() + { + LookModificationSettings* settings = GetLookModificationSettings(); + if (settings) + { + settings->PrepareLutBlending(); + + // Early out if the settings have not chanced + HashValue64 hash = settings->GetHash(); + if (hash == m_lutBlendHash) + { + return; + } + m_lutBlendHash = hash; + + m_needToUpdateLut = true; + + // Calculate all the weights and LUT assets and check if there has been a change + // Only the top N LUTs will be blended where N = LookModificationSettings::MaxBlendLuts + // Weight 0 is used for the base color, and the other weights are for the LUTs in increasing priority + size_t numLuts = settings->GetLutBlendStackSize(); + + float intensity[LookModificationSettings::MaxBlendLuts]; + float one_intensity[LookModificationSettings::MaxBlendLuts]; + float over[LookModificationSettings::MaxBlendLuts]; + float one_over[LookModificationSettings::MaxBlendLuts]; + + for (int curLutIndex = 0; curLutIndex < LookModificationSettings::MaxBlendLuts; curLutIndex++) + { + intensity[curLutIndex] = 0.f; + one_intensity[curLutIndex] = 1.f; + over[curLutIndex] = 0.f; + one_over[curLutIndex] = 1.f; + } + + uint32_t current = 0; + for (size_t lutIndex = 0; lutIndex < numLuts; lutIndex++) + { + LutBlendItem& lutBlendItem = settings->GetLutBlendItem(lutIndex); + const auto assetId = lutBlendItem.m_assetId.GetId(); + + if (assetId.IsValid()) + { + AcesDisplayMapperFeatureProcessor* dmfp = GetScene()->GetFeatureProcessor(); + dmfp->GetLutFromAssetId(m_colorGradingLuts[current], assetId); + if (!m_colorGradingLuts[current].m_lutStreamingImage) + { + AZ_Warning("BlendColorGradingLutsPass", false, "Unable to load grading LUT from asset %s", + lutBlendItem.m_assetId.ToString().c_str()); + // Skip this LUT + continue; + } + } + + intensity[current] = lutBlendItem.m_intensity; + one_intensity[current] = 1.0f - lutBlendItem.m_intensity; + over[current] = lutBlendItem.m_overrideStrength; + one_over[current] = 1.0f - lutBlendItem.m_overrideStrength; + + m_colorGradingShaperParams[current] = AcesDisplayMapperFeatureProcessor::GetShaperParameters( + lutBlendItem.m_shaperPreset, + lutBlendItem.m_customMinExposure, + lutBlendItem.m_customMaxExposure + ); + + ++current; + if (current == LookModificationSettings::MaxBlendLuts) + { + break; + } + } + + m_weights[0] = 0.f; + // Handle the case where there are no LUTs to be blended, and hence an identity LUT will be generated + if (current == 0) + { + m_weights[0] = 1.f; + // These weights would not be used in the shader in this case, but setting to zero anyways. + for (int lutIndex = 1; lutIndex < LookModificationSettings::MaxBlendLuts + 1; lutIndex++) + { + m_weights[lutIndex] = 0.f; + } + } + else + { + // Compute all the weights + // First compute the weight of the ungraded color value + for (uint32_t lutIndex = 0; lutIndex < current; lutIndex++) + { + float weight = one_intensity[lutIndex] * over[lutIndex]; + for (int overrideLutIndex = lutIndex + 1; overrideLutIndex < LookModificationSettings::MaxBlendLuts; overrideLutIndex++) + { + weight *= one_over[overrideLutIndex]; + } + m_weights[0] += weight; + } + // Then compute the weights for the LUTs + for (uint32_t weightIndex = 0; weightIndex < current; weightIndex++) + { + m_weights[weightIndex + 1] = intensity[weightIndex] * over[weightIndex]; + for (int lutIndex = weightIndex + 1; lutIndex < LookModificationSettings::MaxBlendLuts; lutIndex++) + { + m_weights[weightIndex + 1] *= one_over[lutIndex]; + } + } + } + + // If the number of source LUTs have changed, the shader variant will need to be updated + if (m_numSourceLuts != current) + { + m_numSourceLuts = current; + m_needToUpdateShaderVariant = true; + } + } + } + + LookModificationSettings* BlendColorGradingLutsPass::GetLookModificationSettings() const { AZ::RPI::Scene* scene = GetScene(); if (scene) @@ -259,109 +422,12 @@ namespace AZ LookModificationSettings* settings = postProcessSettings->GetLookModificationSettings(); if (settings) { - settings->PrepareLutBlending(); - - // Early out if the settings have not chanced - HashValue64 hash = settings->GetHash(); - if (hash == m_lutBlendHash) - { - return; - } - m_lutBlendHash = hash; - - m_needToUpdateLut = true; - - // Calculate all the weights and LUT assets and check if there has been a change - // Only the top N LUTs will be blended where N = LookModificationSettings::MaxBlendLuts - // Weight 0 is used for the base color, and the other weights are for the LUTs in increasing priority - size_t numLuts = settings->GetLutBlendStackSize(); - float intensity[LookModificationSettings::MaxBlendLuts]; - float one_intensity[LookModificationSettings::MaxBlendLuts]; - float over[LookModificationSettings::MaxBlendLuts]; - float one_over[LookModificationSettings::MaxBlendLuts]; - for (int curLutIndex = 0; curLutIndex < LookModificationSettings::MaxBlendLuts; curLutIndex++) - { - intensity[curLutIndex] = 0.f; - one_intensity[curLutIndex] = 1.f; - over[curLutIndex] = 0.f; - one_over[curLutIndex] = 1.f; - } - - int current = 0; - for (size_t lutIndex = 0; lutIndex < numLuts; lutIndex++) - { - LutBlendItem& lutBlendItem = settings->GetLutBlendItem(lutIndex); - auto assetId = lutBlendItem.m_assetId.GetId(); - if (assetId.IsValid()) - { - AcesDisplayMapperFeatureProcessor* dmfp = scene->GetFeatureProcessor(); - dmfp->GetLutFromAssetId(m_colorGradingLuts[lutIndex], assetId); - if (!m_colorGradingLuts[lutIndex].m_lutStreamingImage) - { - AZ_Warning("BlendColorGradingLutsPass", false, "Unable to load grading LUT from asset %s", lutBlendItem.m_assetId.ToString().c_str()); - // Skip this LUT - continue; - } - } - intensity[current] = lutBlendItem.m_intensity; - one_intensity[current] = 1.f - intensity[lutIndex]; - over[current] = lutBlendItem.m_overrideStrength; - one_over[current] = 1.f - over[lutIndex]; - m_colorGradingLutAssets[current] = lutBlendItem.m_assetId; - m_colorGradingShaperPresets[current] = lutBlendItem.m_shaperPreset; - m_colorGradingShaperParams[current] = AcesDisplayMapperFeatureProcessor::GetShaperParameters(m_colorGradingShaperPresets[lutIndex]); - current++; - if (current == LookModificationSettings::MaxBlendLuts) - { - break; - } - } - - m_weights[0] = 0.f; - // Handle the case where there are no LUTs to be blended, and hence an identity LUT will be generated - if (current == 0) - { - m_weights[0] = 1.f; - // These weights would not be used in the shader in this case, but setting to zero anyways. - for (int lutIndex = 1; lutIndex < LookModificationSettings::MaxBlendLuts + 1; lutIndex++) - { - m_weights[lutIndex] = 0.f; - } - } - else - { - // Compute all the weights - // First compute the weight of the ungraded color value - for (int lutIndex = 0; lutIndex < LookModificationSettings::MaxBlendLuts; lutIndex++) - { - float weight = one_intensity[lutIndex] * over[lutIndex]; - for (int overrideLutIndex = lutIndex + 1; overrideLutIndex < LookModificationSettings::MaxBlendLuts; overrideLutIndex++) - { - weight *= one_over[overrideLutIndex]; - } - m_weights[0] += weight; - } - // Then compute the weights for the LUTs - for (int weightIndex = 0; weightIndex < LookModificationSettings::MaxBlendLuts; weightIndex++) - { - m_weights[weightIndex + 1] = intensity[weightIndex] * over[weightIndex]; - for (int lutIndex = weightIndex + 1; lutIndex < LookModificationSettings::MaxBlendLuts; lutIndex++) - { - m_weights[weightIndex + 1] *= one_over[lutIndex]; - } - } - } - - // If the number of source LUTs have changed, the shader variant will need to be updated - if (m_numSourceLuts != current) - { - m_numSourceLuts = current; - m_needToUpdateShaderVariant = true; - } + return settings; } } } } + return nullptr; } } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.h index d0e6aad4aa..7b37d2c4ec 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BlendColorGradingLutsPass.h @@ -47,6 +47,7 @@ namespace AZ static RPI::Ptr Create(const RPI::PassDescriptor& descriptor); void SetShaperParameters(const ShaperParams& shaperParams); + AZStd::optional GetCommonShaperParams() const; private: explicit BlendColorGradingLutsPass(const RPI::PassDescriptor& descriptor); @@ -66,6 +67,7 @@ namespace AZ void ReleaseLutImage(); void CheckLutBlendSettings(); + LookModificationSettings* GetLookModificationSettings() const; bool m_resourcesInitialized = false; @@ -111,8 +113,6 @@ namespace AZ AZStd::array m_blendedLutDimensions; float m_weights[LookModificationSettings::MaxBlendLuts + 1]; // The first index is reserved for the weight of the non color graded value - Data::Asset m_colorGradingLutAssets[LookModificationSettings::MaxBlendLuts]; - ShaperPresetType m_colorGradingShaperPresets[LookModificationSettings::MaxBlendLuts]; Render::ShaperParams m_colorGradingShaperParams[LookModificationSettings::MaxBlendLuts]; Render::DisplayMapperAssetLut m_colorGradingLuts[LookModificationSettings::MaxBlendLuts]; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.cpp index b93e847fd2..3fcff54eaa 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomBlurPass.cpp @@ -153,8 +153,8 @@ namespace AZ inBinding.m_connectedBinding = isHorizontalPass ? &parentInOutBinding : &parentInBinding; RHI::ImageViewDescriptor viewDesc; - viewDesc.m_mipSliceMin = mipLevel; - viewDesc.m_mipSliceMax = mipLevel; + viewDesc.m_mipSliceMin = static_cast(mipLevel); + viewDesc.m_mipSliceMax = static_cast(mipLevel); inBinding.m_unifiedScopeDesc.SetAsImage(viewDesc); pass->AddAttachmentBinding(inBinding); diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.cpp index 11e53e8805..e9b428c877 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomCompositePass.cpp @@ -133,8 +133,8 @@ namespace AZ inBinding.m_connectedBinding = &parentInBinding; RHI::ImageViewDescriptor inViewDesc; - inViewDesc.m_mipSliceMin = mipLevel; - inViewDesc.m_mipSliceMax = mipLevel; + inViewDesc.m_mipSliceMin = static_cast(mipLevel); + inViewDesc.m_mipSliceMax = static_cast(mipLevel); inBinding.m_unifiedScopeDesc.SetAsImage(inViewDesc); pass->AddAttachmentBinding(inBinding); @@ -151,8 +151,8 @@ namespace AZ if (mipLevel != 0) { RHI::ImageViewDescriptor outViewDesc; - outViewDesc.m_mipSliceMin = mipLevel - 1; - outViewDesc.m_mipSliceMax = mipLevel - 1; + outViewDesc.m_mipSliceMin = static_cast(mipLevel - 1); + outViewDesc.m_mipSliceMax = static_cast(mipLevel - 1); outBinding.m_unifiedScopeDesc.SetAsImage(outViewDesc); } diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.cpp index 1481a7999e..8b824a424d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/BloomDownsamplePass.cpp @@ -47,7 +47,7 @@ namespace AZ { RPI::Ptr outAttachment = m_ownedAttachments[0]; - for (uint32_t i = 0; i < Render::Bloom::MaxStageCount; ++i) + for (uint16_t i = 0; i < Render::Bloom::MaxStageCount; ++i) { // Create bindings diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationCompositePass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationCompositePass.cpp index 40f8f8355d..85c45de96b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationCompositePass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationCompositePass.cpp @@ -9,11 +9,15 @@ #include #include #include +#include +#include #include #include #include +#include + #include #include #include @@ -22,6 +26,22 @@ namespace AZ { namespace Render { + AZ_CVAR(uint8_t, + r_lutSampleQuality, + 0, + [](const uint8_t& value) + { + auto passes = RPI::PassSystem::Get()->FindPasses(RPI::PassClassFilter()); + for (auto* pass : passes) + { + LookModificationCompositePass* lookModPass = azrtti_cast(pass); + lookModPass->SetSampleQuality(LookModificationCompositePass::SampleQuality(value)); + } + }, + ConsoleFunctorFlags::Null, + "This can be increased to deal with particularly tricky luts. Range (0-2). 0 (default) - Standard linear sampling. 1 - 7 tap b-spline sampling. 2 - 19 tap b-spline sampling." + ); + RPI::Ptr LookModificationCompositePass::Create(const RPI::PassDescriptor& descriptor) { RPI::Ptr pass = aznew LookModificationCompositePass(descriptor); @@ -30,8 +50,6 @@ namespace AZ LookModificationCompositePass::LookModificationCompositePass(const RPI::PassDescriptor& descriptor) : AZ::RPI::FullscreenTrianglePass(descriptor) - , m_exposureShaderVariantOptionName(ExposureShaderVariantOptionName) - , m_colorGradingShaderVariantOptionName(ColorGradingShaderVariantOptionName) { } @@ -60,19 +78,38 @@ namespace AZ { AZ_Assert(m_shader != nullptr, "LookModificationCompositePass %s has a null shader when calling InitializeShaderVariant.", GetPathName().GetCStr()); - AZStd::vector exposureVariationTypes = { AZ::Name("true"), AZ::Name("false") }; - AZStd::vector colorGradingVariationTypes = { AZ::Name("true"), AZ::Name("false") }; + struct OptionSettings + { + AZ::Name m_enableExposureControl; + AZ::Name m_enableColorGrading; + RPI::ShaderOptionValue m_lutSampleQuality; - auto exposureVariationTypeCount = exposureVariationTypes.size(); - auto totalVariationCount = exposureVariationTypes.size() * colorGradingVariationTypes.size(); + OptionSettings(const char* enableExposureControl, const char* enableColorGrading, SampleQuality sampleQuality) + : m_enableExposureControl(Name(enableExposureControl)) + , m_enableColorGrading(Name(enableColorGrading)) + , m_lutSampleQuality(RPI::ShaderOptionValue(sampleQuality)) + {} + }; + + AZStd::vector options = + { + { "false", "false", SampleQuality::Linear }, + { "true", "false", SampleQuality::Linear }, + { "false", "true", SampleQuality::Linear }, + { "false", "true", SampleQuality::BSpline7Tap }, + { "false", "true", SampleQuality::BSpline19Tap }, + { "true", "true", SampleQuality::Linear }, + { "true", "true", SampleQuality::BSpline7Tap }, + { "true", "true", SampleQuality::BSpline19Tap }, + }; // Caching all pipeline state for each shader variation for performance reason. - for (auto shaderVariantIndex = 0; shaderVariantIndex < totalVariationCount; ++shaderVariantIndex) + for (auto shaderVariantIndex = 0; shaderVariantIndex < options.size(); ++shaderVariantIndex) { auto shaderOption = m_shader->CreateShaderOptionGroup(); - shaderOption.SetValue(m_exposureShaderVariantOptionName, exposureVariationTypes[shaderVariantIndex % exposureVariationTypeCount]); - shaderOption.SetValue(m_colorGradingShaderVariantOptionName, colorGradingVariationTypes[shaderVariantIndex / exposureVariationTypeCount]); - + shaderOption.SetValue(m_exposureShaderVariantOptionName, options.at(shaderVariantIndex).m_enableExposureControl); + shaderOption.SetValue(m_colorGradingShaderVariantOptionName, options.at(shaderVariantIndex).m_enableColorGrading); + shaderOption.SetValue(m_lutSampleQualityShaderVariantOptionName, options.at(shaderVariantIndex).m_lutSampleQuality); PreloadShaderVariant(m_shader, shaderOption, GetRenderAttachmentConfiguration(), GetMultisampleState()); } @@ -173,9 +210,9 @@ namespace AZ { m_shaderResourceGroup->SetImageView(m_shaderColorGradingLutImageIndex, m_blendedColorGradingLut.m_lutImageView.get()); - m_shaderResourceGroup->SetConstant(m_shaderColorGradingShaperTypeIndex, m_colorGradingShaperParams.type); - m_shaderResourceGroup->SetConstant(m_shaderColorGradingShaperBiasIndex, m_colorGradingShaperParams.bias); - m_shaderResourceGroup->SetConstant(m_shaderColorGradingShaperScaleIndex, m_colorGradingShaperParams.scale); + m_shaderResourceGroup->SetConstant(m_shaderColorGradingShaperTypeIndex, m_colorGradingShaperParams.m_type); + m_shaderResourceGroup->SetConstant(m_shaderColorGradingShaperBiasIndex, m_colorGradingShaperParams.m_bias); + m_shaderResourceGroup->SetConstant(m_shaderColorGradingShaperScaleIndex, m_colorGradingShaperParams.m_scale); } } @@ -192,7 +229,8 @@ namespace AZ // Decide which shader to use. shaderOption.SetValue(m_exposureShaderVariantOptionName, m_exposureControlEnabled ? AZ::Name("true") : AZ::Name("false")); shaderOption.SetValue(m_colorGradingShaderVariantOptionName, m_colorGradingLutEnabled ? AZ::Name("true") : AZ::Name("false")); - + shaderOption.SetValue(m_lutSampleQualityShaderVariantOptionName, RPI::ShaderOptionValue(m_sampleQuality)); + UpdateShaderVariant(shaderOption); m_needToUpdateShaderVariant = false; @@ -218,5 +256,12 @@ namespace AZ { m_colorGradingShaperParams = shaperParams; } + + void LookModificationCompositePass::SetSampleQuality(SampleQuality sampleQuality) + { + m_sampleQuality = sampleQuality; + m_needToUpdateShaderVariant = true; + } + } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationCompositePass.h b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationCompositePass.h index 49a0e88a54..b269225445 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationCompositePass.h +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationCompositePass.h @@ -30,8 +30,6 @@ namespace AZ namespace Render { static const char* const LookModificationTransformPassTemplateName{ "LookModificationTransformTemplate" }; - static const char* const ExposureShaderVariantOptionName{ "o_enableExposureControlFeature" }; - static const char* const ColorGradingShaderVariantOptionName{ "o_enableColorGradingLut" }; /** * The look modification composite pass. If color grading LUTs are enabled, this pass will apply the blended LUT. @@ -43,6 +41,14 @@ namespace AZ public: AZ_RTTI(LookModificationCompositePass, "{D7DF3E8A-B642-4D51-ABC2-ADB2B60FCE1D}", AZ::RPI::FullscreenTrianglePass); AZ_CLASS_ALLOCATOR(LookModificationCompositePass, SystemAllocator, 0); + + enum class SampleQuality : uint8_t + { + Linear = 0, + BSpline7Tap = 1, + BSpline19Tap = 2, + }; + virtual ~LookModificationCompositePass() = default; //! Creates a LookModificationPass @@ -54,6 +60,8 @@ namespace AZ //! Set shaper parameters void SetShaperParameters(const ShaperParams& shaperParams); + void SetSampleQuality(SampleQuality sampleQuality); + protected: LookModificationCompositePass(const RPI::PassDescriptor& descriptor); @@ -76,11 +84,15 @@ namespace AZ bool m_exposureControlEnabled = false; bool m_colorGradingLutEnabled = false; + SampleQuality m_sampleQuality = SampleQuality::Linear; + Render::DisplayMapperLut m_blendedColorGradingLut; Render::ShaperParams m_colorGradingShaperParams; - const AZ::Name m_exposureShaderVariantOptionName; - const AZ::Name m_colorGradingShaderVariantOptionName; + const AZ::Name m_exposureShaderVariantOptionName{ "o_enableExposureControlFeature" }; + const AZ::Name m_colorGradingShaderVariantOptionName{ "o_enableColorGradingLut" }; + const AZ::Name m_lutSampleQualityShaderVariantOptionName{ "o_lutSampleQuality" }; + bool m_needToUpdateShaderVariant = true; RHI::ShaderInputNameIndex m_shaderColorGradingLutImageIndex = "m_gradingLut"; diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.cpp index cde7d6586b..e33a63a4bb 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/LookModificationTransformPass.cpp @@ -47,29 +47,32 @@ namespace AZ swapChainFormat = m_swapChainAttachmentBinding->m_attachment->GetTransientImageDescriptor().m_imageDescriptor.m_format; } - if (m_displayBufferFormat != swapChainFormat) + // Update the children passes + RPI::Ptr blendPass = FindChildPass(); + if (blendPass) { - m_displayBufferFormat = swapChainFormat; - m_outputDeviceTransformType = AcesDisplayMapperFeatureProcessor::GetOutputDeviceTransformType(m_displayBufferFormat); - m_shaperParams = GetAcesShaperParameters(m_outputDeviceTransformType); - - // Update the children passes - for (const AZ::RPI::Ptr& child : m_children) + auto commonShaperParams = blendPass->GetCommonShaperParams(); + if (commonShaperParams) { - BlendColorGradingLutsPass* blendPass = azrtti_cast(child.get()); - if (blendPass) - { - blendPass->SetShaperParameters(m_shaperParams); - continue; - } - LookModificationCompositePass* compositePass = azrtti_cast(child.get()); - if (compositePass) - { - compositePass->SetShaperParameters(m_shaperParams); - continue; - } + m_shaperParams = *commonShaperParams; + } + else + { + // Mix of shapers used, so shape them based on the output transform type. + m_displayBufferFormat = swapChainFormat; + m_outputDeviceTransformType = AcesDisplayMapperFeatureProcessor::GetOutputDeviceTransformType(m_displayBufferFormat); + m_shaperParams = GetAcesShaperParameters(m_outputDeviceTransformType); + } + + blendPass->SetShaperParameters(m_shaperParams); + + RPI::Ptr compositePass = FindChildPass(); + if (compositePass) + { + compositePass->SetShaperParameters(m_shaperParams); } } + ParentPass::FrameBeginInternal(params); } } // namespace Render diff --git a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp index d1f42069fb..779f02cba0 100644 --- a/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/PostProcessing/TaaPass.cpp @@ -76,7 +76,7 @@ namespace AZ::Render void TaaPass::FrameBeginInternal(FramePrepareParams params) { RHI::Size inputSize = m_inputColorBinding->m_attachment->m_descriptor.m_image.m_size; - Vector2 rcpInputSize = Vector2(1.0 / inputSize.m_width, 1.0 / inputSize.m_height); + Vector2 rcpInputSize = Vector2(1.0f / inputSize.m_width, 1.0f / inputSize.m_height); RPI::ViewPtr view = GetRenderPipeline()->GetDefaultView(); m_offsetIndex = (m_offsetIndex + 1) % m_subPixelOffsets.size(); diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp index a6e41a3ce1..276ea7683f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp @@ -361,7 +361,7 @@ namespace AZ drawRequest.m_listTag = drawListTag; drawRequest.m_pipelineState = pipelineState->GetRHIPipelineState(); drawRequest.m_streamBufferViews = m_reflectionRenderData->m_boxPositionBufferView; - drawRequest.m_stencilRef = stencilRef; + drawRequest.m_stencilRef = static_cast(stencilRef); drawRequest.m_sortKey = m_sortKey; drawPacketBuilder.AddDrawItem(drawRequest); diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp index c0e25e3da9..341d1a0274 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp @@ -154,7 +154,7 @@ namespace AZ void ReflectionProbeFeatureProcessor::Simulate([[maybe_unused]] const FeatureProcessor::SimulatePacket& packet) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("ReflectionProbe", "ReflectionProbeFeatureProcessor: Simulate"); // update pipeline states @@ -193,7 +193,7 @@ namespace AZ // if the volumes changed we need to re-sort the probe list if (m_probeSortRequired) { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "Sort reflection probes"); + AZ_PROFILE_SCOPE(AzRender, "Sort reflection probes"); AZ_ATOM_PROFILE_FUNCTION("ReflectionProbe", "ReflectionProbeFeatureProcessor: Sort reflection probes"); // sort the probes by descending inner volume size, so the smallest volumes are rendered last diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurChildPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurChildPass.cpp index c3125e0bbe..3e97277594 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurChildPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurChildPass.cpp @@ -38,14 +38,14 @@ namespace AZ if (m_imageSize != size) { m_imageSize = size; - m_outputScale = (m_passType == PassType::Vertical) ? pow(2.0f, m_mipLevel) : 1.0f; + m_outputScale = (m_passType == PassType::Vertical) ? static_cast(pow(2.0f, m_mipLevel)) : 1.0f; m_updateSrg = true; } float inverseScale = 1.0f / m_outputScale; - uint32_t outputWidth = m_imageSize.m_width * inverseScale; - uint32_t outputHeight = m_imageSize.m_height * inverseScale; + uint32_t outputWidth = static_cast(m_imageSize.m_width * inverseScale); + uint32_t outputHeight = static_cast(m_imageSize.m_height * inverseScale); params.m_viewportState = RHI::Viewport(0, static_cast(outputWidth), 0, static_cast(outputHeight)); params.m_scissorState = RHI::Scissor(0, 0, outputWidth, outputHeight); diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp index 4f5caca108..394a6fd406 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionScreenSpace/ReflectionScreenSpaceBlurPass.cpp @@ -190,8 +190,8 @@ namespace AZ RPI::PassAttachmentBinding& outputAttachmentBinding = horizontalBlurChildPass->GetInputOutputBinding(1); uint32_t mipLevel = attachmentIndex + 1; RHI::ImageViewDescriptor outputViewDesc; - outputViewDesc.m_mipSliceMin = mipLevel; - outputViewDesc.m_mipSliceMax = mipLevel; + outputViewDesc.m_mipSliceMin = static_cast(mipLevel); + outputViewDesc.m_mipSliceMax = static_cast(mipLevel); outputAttachmentBinding.m_unifiedScopeDesc.SetAsImage(outputViewDesc); outputAttachmentBinding.SetAttachment(reflectionImageAttachment); diff --git a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp index 5a25951163..0e42c5520e 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp @@ -539,9 +539,10 @@ namespace AZ::Render { esmPass->QueueForBuildAndInitialization(); } - - for (ProjectedShadowmapsPass* shadowPass : m_projectedShadowmapsPasses) + + if (!m_projectedShadowmapsPasses.empty()) { + const ProjectedShadowmapsPass* shadowPass = m_projectedShadowmapsPasses.front(); for (const auto& shadowProperty : shadowProperties) { const int16_t shadowIndexInSrg = shadowProperty.m_shadowId.GetIndex(); @@ -553,7 +554,6 @@ namespace AZ::Render filterData.m_shadowmapOriginInSlice = origin.m_originInSlice; m_deviceBufferNeedsUpdate = true; } - break; } m_shadowmapPassNeedsUpdate = false; @@ -571,8 +571,9 @@ namespace AZ::Render void ProjectedShadowFeatureProcessor::PrepareViews(const PrepareViewsPacket&, AZStd::vector>& outViews) { - for (ProjectedShadowmapsPass* pass : m_projectedShadowmapsPasses) + if (!m_projectedShadowmapsPasses.empty()) { + ProjectedShadowmapsPass* pass = m_projectedShadowmapsPasses.front(); RPI::RenderPipeline* renderPipeline = pass->GetRenderPipeline(); if (renderPipeline) { @@ -598,7 +599,6 @@ namespace AZ::Render outViews.emplace_back(AZStd::make_pair(viewTag, shadowProperty.m_shadowmapView)); } } - break; } } @@ -606,8 +606,9 @@ namespace AZ::Render { AZ_ATOM_PROFILE_FUNCTION("RPI", "ProjectedShadowFeatureProcessor: Render"); - for (const ProjectedShadowmapsPass* pass : m_projectedShadowmapsPasses) + if (!m_projectedShadowmapsPasses.empty()) { + const ProjectedShadowmapsPass* pass = m_projectedShadowmapsPasses.front(); for (const RPI::ViewPtr& view : packet.m_views) { if (view->GetUsageFlags() & RPI::View::UsageFlags::UsageCamera) @@ -622,7 +623,6 @@ namespace AZ::Render m_filterParamBufferHandler.UpdateSrg(srg); } } - break; } } diff --git a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshDispatchItem.cpp b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshDispatchItem.cpp index cd181f7011..bfc533763e 100644 --- a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshDispatchItem.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshDispatchItem.cpp @@ -205,9 +205,9 @@ namespace AZ if (numThreads) { const auto& args = *numThreads; - arguments.m_threadsPerGroupX = args[0].type() == azrtti_typeid() ? AZStd::any_cast(args[0]) : 1; - arguments.m_threadsPerGroupY = args[1].type() == azrtti_typeid() ? AZStd::any_cast(args[1]) : 1; - arguments.m_threadsPerGroupZ = args[2].type() == azrtti_typeid() ? AZStd::any_cast(args[2]) : 1; + arguments.m_threadsPerGroupX = static_cast(args[0].type() == azrtti_typeid() ? AZStd::any_cast(args[0]) : 1); + arguments.m_threadsPerGroupY = static_cast(args[1].type() == azrtti_typeid() ? AZStd::any_cast(args[1]) : 1); + arguments.m_threadsPerGroupZ = static_cast(args[2].type() == azrtti_typeid() ? AZStd::any_cast(args[2]) : 1); } arguments.m_totalNumberOfThreadsX = xThreads; diff --git a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshFeatureProcessor.cpp index ebe52cdafe..0aa72bf2ca 100644 --- a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshFeatureProcessor.cpp @@ -69,13 +69,13 @@ namespace AZ void SkinnedMeshFeatureProcessor::Render(const FeatureProcessor::RenderPacket& packet) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("SkinnedMesh", "SkinnedMeshFeatureProcessor: Render"); #if 0 //[GFX_TODO][ATOM-13564] Temporarily disable skinning culling until we figure out how to hook up visibility & lod selection with skinning: //Setup the culling workgroup (it will be re-used for each view) { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "set up skinned culling workgroup"); + AZ_PROFILE_SCOPE(AzRender, "set up skinned culling workgroup"); azsnprintf(m_workgroup.m_name, AZ_ARRAY_SIZE(m_workgroup.m_name), "SkinnedMeshFP workgroup"); m_workgroup.m_drawListMask.reset(); m_workgroup.m_cullPackets.clear(); @@ -118,11 +118,11 @@ namespace AZ Job* processWorkgroupJob = AZ::CreateJobFunction( [this, cullingSystem, viewPtr](AZ::Job& thisJob) { - AZ_PROFILE_SCOPE_DYNAMIC(Debug::ProfileCategory::AzRender, "skinningMeshFP processWorkgroupJob - View: %s", viewPtr->GetName().GetCStr()); + AZ_PROFILE_SCOPE(AzRender, "skinningMeshFP processWorkgroupJob - View: %s", viewPtr->GetName().GetCStr()); auto dispatchSkinningComputeProgramsCallback = [this](AZStd::shared_ptr results) -> void { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "dispatchSkinningComputePrograms"); + AZ_PROFILE_SCOPE(AzRender, "dispatchSkinningComputePrograms"); //the [1][1] element of a projection matrix stores cot(FovY/2) (equal to 2*nearPlaneDistance/nearPlaneHeight), //which is used to determine the (vertical) projected size in screen space diff --git a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp index af427eb554..4229416066 100644 --- a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp @@ -445,7 +445,7 @@ namespace AZ MorphTargetInstanceMetaData instanceMetaData; // Positions start at the beginning of the allocation - instanceMetaData.m_accumulatedPositionDeltaOffsetInBytes = allocation->GetVirtualAddress().m_ptr; + instanceMetaData.m_accumulatedPositionDeltaOffsetInBytes = static_cast(allocation->GetVirtualAddress().m_ptr); uint32_t deltaStreamSizeInBytes = static_cast(vertexCount * MorphTargetConstants::s_unpackedMorphTargetDeltaSizeInBytes); // Followed by normals, tangents, and bitangents @@ -532,7 +532,7 @@ namespace AZ // lod0 Positions[^ ^] lod0Normals[^ ^] lod1Positions[^ ^] lod1Normals[^ ^] // lod0 subMesh0+1 Positions[^ ^^ ^] lod0 subMesh0+1 Normals[^ ^^ ^] lod1 sm0+1 pos[^ ^^ ^] lod1 sm0+1 norm[^ ^^ ^] - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZStd::intrusive_ptr instance = aznew SkinnedMeshInstance; // Each model gets a unique, random ID, so if the same source model is used for multiple instances, multiple target models will be created. diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/ShaderPlatformInterface.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/ShaderPlatformInterface.h index 5c5898e8d1..b2b16692b5 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/ShaderPlatformInterface.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Edit/ShaderPlatformInterface.h @@ -81,7 +81,7 @@ namespace AZ struct ByProducts { AZStd::set m_intermediatePaths; //!< intermediate file paths (like dxil text form) - static constexpr uint32_t UnknownDynamicBranchCount = -1; + static constexpr uint32_t UnknownDynamicBranchCount = std::numeric_limits::max(); uint32_t m_dynamicBranchCount = UnknownDynamicBranchCount; }; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/CpuTimingStatistics.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/CpuTimingStatistics.h index 99751bbde7..2ab23def08 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/CpuTimingStatistics.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/CpuTimingStatistics.h @@ -12,6 +12,7 @@ #include #include #include +#include namespace AZ { diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceDescriptor.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceDescriptor.h index 87e2b03181..b7f7a6754f 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceDescriptor.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceDescriptor.h @@ -22,14 +22,14 @@ namespace AZ class DeviceDescriptor { public: - virtual ~DeviceDescriptor() = default; AZ_RTTI(DeviceDescriptor, "{8446A34C-A079-44B8-A20F-45D9CAB1FAFD}"); static void Reflect(AZ::ReflectContext* context); DeviceDescriptor() = default; + virtual ~DeviceDescriptor(); uint32_t m_frameCountMax = RHI::Limits::Device::FrameCountMax; - ConstPtr m_platformLimitsDescriptor = nullptr; + Ptr m_platformLimitsDescriptor = nullptr; }; } } diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/PlatformLimitsDescriptor.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/PlatformLimitsDescriptor.h index 4cec15651c..2d85420694 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/PlatformLimitsDescriptor.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/PlatformLimitsDescriptor.h @@ -20,7 +20,7 @@ namespace AZ { struct TransientAttachmentPoolBudgets { - AZ_TYPE_INFO(TransientAttachmentPoolBudgets, "{CE39BBEF-C9CD-4B9A-BA41-C886D9F063BC}"); + AZ_TYPE_INFO(AZ::RHI::TransientAttachmentPoolBudgets, "{CE39BBEF-C9CD-4B9A-BA41-C886D9F063BC}"); static void Reflect(AZ::ReflectContext* context); //! Defines the maximum amount of memory the pool is allowed to consume for transient buffers. @@ -53,8 +53,8 @@ namespace AZ : public AZStd::intrusive_base { public: - AZ_RTTI(PlatformLimitsDescriptor, "{3A7B2BE4-0337-4F59-B4FC-B7E529EBE6C5}"); - AZ_CLASS_ALLOCATOR(PlatformLimitsDescriptor, AZ::SystemAllocator, 0); + AZ_RTTI(AZ::RHI::PlatformLimitsDescriptor, "{3A7B2BE4-0337-4F59-B4FC-B7E529EBE6C5}"); + AZ_CLASS_ALLOCATOR(AZ::RHI::PlatformLimitsDescriptor, AZ::SystemAllocator, 0); static void Reflect(AZ::ReflectContext* context); static RHI::Ptr Create(); @@ -67,13 +67,15 @@ namespace AZ HeapPagingParameters m_pagingParameters; HeapMemoryHintParameters m_usageHintParameters; HeapAllocationStrategy m_heapAllocationStrategy = HeapAllocationStrategy::MemoryHint; + + void LoadPlatformLimitsDescriptor(const char* rhiName); }; class PlatformLimits final { public: - AZ_RTTI(PlatformLimits, "{48158F25-5044-441C-A2B2-2D3E9255B0C3}"); - AZ_CLASS_ALLOCATOR(PlatformLimits, AZ::SystemAllocator, 0); + AZ_RTTI(AZ::RHI::PlatformLimits, "{48158F25-5044-441C-A2B2-2D3E9255B0C3}"); + AZ_CLASS_ALLOCATOR(AZ::RHI::PlatformLimits, AZ::SystemAllocator, 0); static void Reflect(AZ::ReflectContext* context); Ptr m_platformLimitsDescriptor = nullptr; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/RHISystemDescriptor.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/RHISystemDescriptor.h index b9fae5593f..8c512662e7 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/RHISystemDescriptor.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/RHISystemDescriptor.h @@ -26,8 +26,6 @@ namespace AZ //! The set of globally declared draw list tags, which will be registered with the registry at startup. AZStd::vector m_drawListTags; - - const RHI::PlatformLimits* m_platformLimits = nullptr; }; } // namespace RHI } // namespace AZ diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ShaderSemantic.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ShaderSemantic.h index da791bddfb..ee6e0feeb6 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ShaderSemantic.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/ShaderSemantic.h @@ -9,6 +9,7 @@ #include #include +#include namespace AZ { diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/AliasedAttachmentAllocator.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/AliasedAttachmentAllocator.h index 5ccb48bf1c..8527d034d5 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/AliasedAttachmentAllocator.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/AliasedAttachmentAllocator.h @@ -248,7 +248,7 @@ namespace AZ // The no allocation heap is used when doing a 2 pass strategy. Internal::NoAllocationAliasedHeap::Descriptor heapAllocator; heapAllocator.m_alignment = descriptor.m_alignment; - heapAllocator.m_budgetInBytes = ~0; + heapAllocator.m_budgetInBytes = std::numeric_limits::max(); m_noAllocationHeap.Init(device, heapAllocator); typename decltype(m_garbageCollector)::Descriptor collectorDescriptor; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/BufferPool.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/BufferPool.h index abbd316bc7..2d226407c7 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/BufferPool.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/BufferPool.h @@ -223,6 +223,9 @@ namespace AZ /// Called when a buffer is being streamed asynchronously. virtual ResultCode StreamBufferInternal(const BufferStreamRequest& request); + //Called in order to do a simple mem copy allowing Null rhi to opt out + virtual void BufferCopy(void* destination, const void* source, size_t num); + ////////////////////////////////////////////////////////////////////////// BufferPoolDescriptor m_descriptor; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h index 9372977d8e..92b56880b7 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h @@ -173,13 +173,14 @@ namespace AZ static void Reflect(AZ::ReflectContext* context); CpuProfilingStatisticsSerializerEntry() = default; - CpuProfilingStatisticsSerializerEntry(const RHI::CachedTimeRegion& cachedTimeRegion); + CpuProfilingStatisticsSerializerEntry(const RHI::CachedTimeRegion& cachedTimeRegion, AZStd::thread_id threadId); Name m_groupName; Name m_regionName; uint16_t m_stackDepth; AZStd::sys_time_t m_startTick; AZStd::sys_time_t m_endTick; + size_t m_threadId; }; AZ_TYPE_INFO(CpuProfilingStatisticsSerializer, "{D5B02946-0D27-474F-9A44-364C2706DD41}"); diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h index e7ad98c074..f9df29cf74 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/Device.h @@ -60,10 +60,6 @@ namespace AZ //! been called), and an error code is returned. ResultCode Init(PhysicalDevice& physicalDevice); - //! Called to initialize anything that wasn't done as part of Init. DeviceDescriptor is passed down - //! as part of this API. This is called after AssetCatalog is loaded and hence any file can be loaded at this point - ResultCode PostInit(const DeviceDescriptor& descriptor); - //! Begins execution of a frame. The device internally manages a set of command queues. This //! method will synchronize the CPU with the GPU according to the number of in-light frames //! configured on the device. This means you should make sure any manipulation of N-buffered @@ -147,7 +143,9 @@ namespace AZ DeviceFeatures m_features; DeviceLimits m_limits; ResourcePoolDatabase m_resourcePoolDatabase; - + + DeviceDescriptor m_descriptor; + using FormatCapabilitiesList = AZStd::array(Format::Count)>; private: @@ -165,10 +163,6 @@ namespace AZ //! Called when just the device is being initialized. virtual ResultCode InitInternal(PhysicalDevice& physicalDevice) = 0; - - //! Called to initialize anything that wasnt done as part of InitInternal. - //! This is called after AssetCatalog is loaded and hence any file can be loaded at this point - virtual ResultCode PostInitInternal(const DeviceDescriptor& descriptor) = 0; //! Called when the device is being shutdown. virtual void ShutdownInternal() = 0; @@ -190,6 +184,9 @@ namespace AZ //! Fills the capabilities for each format. virtual void FillFormatsCapabilitiesInternal(FormatCapabilitiesList& formatsCapabilities) = 0; + + //! Initialize limits and resources associated with them. + virtual ResultCode InitializeLimits() = 0; /////////////////////////////////////////////////////////////////// void CalculateDepthStencilNearestSupportedFormats(); @@ -198,8 +195,6 @@ namespace AZ //! All platform specific format mappings should be executed before this function is called void FillRemainingSupportedFormats(); - DeviceDescriptor m_descriptor; - // The physical device backing this logical device instance. Ptr m_physicalDevice; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/DispatchItem.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/DispatchItem.h index 93ff1e85b7..72f190dcc8 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/DispatchItem.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/DispatchItem.h @@ -10,6 +10,7 @@ #include #include #include +#include namespace AZ { diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/ImageProperty.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/ImageProperty.h index 00f329059c..23027083a4 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/ImageProperty.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/ImageProperty.h @@ -183,7 +183,7 @@ namespace AZ else { // Insert intervals by mip level. - for (uint32_t mipLevel = subResourceRange.m_mipSliceMin; mipLevel <= subResourceRange.m_mipSliceMax; ++mipLevel) + for (uint16_t mipLevel = subResourceRange.m_mipSliceMin; mipLevel <= subResourceRange.m_mipSliceMax; ++mipLevel) { m_intervalMap.assign( ConvertSubresourceToIndex(aspect, mipLevel, subResourceRange.m_arraySliceMin), @@ -273,7 +273,7 @@ namespace AZ else { // Traverse one mip level at a time. - for (uint32_t mipLevel = subResourceRange.m_mipSliceMin; mipLevel <= subResourceRange.m_mipSliceMax; ++mipLevel) + for (uint16_t mipLevel = subResourceRange.m_mipSliceMin; mipLevel <= subResourceRange.m_mipSliceMax; ++mipLevel) { getIntervals( ConvertSubresourceToIndex(aspect, mipLevel, subResourceRange.m_arraySliceMin), @@ -332,8 +332,8 @@ namespace AZ { const uint32_t subresourcesPerAspect = m_imageDescriptor.m_mipLevels * m_imageDescriptor.m_arraySize; return ImageSubresource( - (index % subresourcesPerAspect) / m_imageDescriptor.m_arraySize, - (index % subresourcesPerAspect) % m_imageDescriptor.m_arraySize, + static_cast((index % subresourcesPerAspect) / m_imageDescriptor.m_arraySize), + static_cast((index % subresourcesPerAspect) % m_imageDescriptor.m_arraySize), static_cast(index/ subresourcesPerAspect)); } diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/RHISystem.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/RHISystem.h index e37fd75148..25026b5b87 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/RHISystem.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/RHISystem.h @@ -68,7 +68,6 @@ namespace AZ RHI::FrameScheduler m_frameScheduler; RHI::FrameSchedulerCompileRequest m_compileRequest; - ConstPtr m_platformLimitsDescriptor = nullptr; RHI::CpuProfilerImpl m_cpuProfiler; }; } // namespace RPI diff --git a/Gems/Atom/RHI/Code/Source/RHI.Reflect/DeviceDescriptor.cpp b/Gems/Atom/RHI/Code/Source/RHI.Reflect/DeviceDescriptor.cpp index 709a870c81..8f36d38934 100644 --- a/Gems/Atom/RHI/Code/Source/RHI.Reflect/DeviceDescriptor.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI.Reflect/DeviceDescriptor.cpp @@ -24,5 +24,11 @@ namespace AZ ; } } + + DeviceDescriptor::~DeviceDescriptor() + { + m_platformLimitsDescriptor = nullptr; + } + } } diff --git a/Gems/Atom/RHI/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp b/Gems/Atom/RHI/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp index 02bcb3432f..250f03716d 100644 --- a/Gems/Atom/RHI/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp @@ -7,6 +7,7 @@ */ #include #include +#include namespace AZ { @@ -17,8 +18,8 @@ namespace AZ if (auto* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(0) - ->Field("m_platformLimitsDescriptor", &PlatformLimits::m_platformLimitsDescriptor) + ->Version(1) + ->Field("PlatformLimitsDescriptor", &PlatformLimits::m_platformLimitsDescriptor) ; } } @@ -28,10 +29,10 @@ namespace AZ if (auto* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(0) - ->Field("m_bufferBudgetInBytes", &TransientAttachmentPoolBudgets::m_bufferBudgetInBytes) - ->Field("m_imageBudgetInBytes", &TransientAttachmentPoolBudgets::m_imageBudgetInBytes) - ->Field("m_renderTargetBudgetInBytes", &TransientAttachmentPoolBudgets::m_renderTargetBudgetInBytes) + ->Version(1) + ->Field("BufferBudgetInBytes", &TransientAttachmentPoolBudgets::m_bufferBudgetInBytes) + ->Field("ImageBudgetInBytes", &TransientAttachmentPoolBudgets::m_imageBudgetInBytes) + ->Field("RenderTargetBudgetInBytes", &TransientAttachmentPoolBudgets::m_renderTargetBudgetInBytes) ; } } @@ -41,13 +42,13 @@ namespace AZ if (auto* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(0) - ->Field("m_stagingBufferBudgetInBytes", &PlatformDefaultValues::m_stagingBufferBudgetInBytes) - ->Field("m_asyncQueueStagingBufferSizeInBytes", &PlatformDefaultValues::m_asyncQueueStagingBufferSizeInBytes) - ->Field("m_mediumStagingBufferPageSizeInBytes", &PlatformDefaultValues::m_mediumStagingBufferPageSizeInBytes) - ->Field("m_largestStagingBufferPageSizeInBytes", &PlatformDefaultValues::m_largestStagingBufferPageSizeInBytes) - ->Field("m_imagePoolPageSizeInBytes", &PlatformDefaultValues::m_imagePoolPageSizeInBytes) - ->Field("m_bufferPoolPageSizeInBytes", &PlatformDefaultValues::m_bufferPoolPageSizeInBytes) + ->Version(1) + ->Field("StagingBufferBudgetInBytes", &PlatformDefaultValues::m_stagingBufferBudgetInBytes) + ->Field("AsyncQueueStagingBufferSizeInBytes", &PlatformDefaultValues::m_asyncQueueStagingBufferSizeInBytes) + ->Field("MediumStagingBufferPageSizeInBytes", &PlatformDefaultValues::m_mediumStagingBufferPageSizeInBytes) + ->Field("LargestStagingBufferPageSizeInBytes", &PlatformDefaultValues::m_largestStagingBufferPageSizeInBytes) + ->Field("ImagePoolPageSizeInBytes", &PlatformDefaultValues::m_imagePoolPageSizeInBytes) + ->Field("BufferPoolPageSizeInBytes", &PlatformDefaultValues::m_bufferPoolPageSizeInBytes) ; } } @@ -58,12 +59,12 @@ namespace AZ if (auto* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(1) - ->Field("m_transientAttachmentPoolBudgets", &PlatformLimitsDescriptor::m_transientAttachmentPoolBudgets) - ->Field("m_platformDefaultValues", &PlatformLimitsDescriptor::m_platformDefaultValues) - ->Field("m_pagingParameters", &PlatformLimitsDescriptor::m_pagingParameters) - ->Field("m_usageHintParameters", &PlatformLimitsDescriptor::m_usageHintParameters) - ->Field("m_heapAllocationStrategy", &PlatformLimitsDescriptor::m_heapAllocationStrategy) + ->Version(2) + ->Field("TransientAttachmentPoolBudgets", &PlatformLimitsDescriptor::m_transientAttachmentPoolBudgets) + ->Field("PlatformDefaultValues", &PlatformLimitsDescriptor::m_platformDefaultValues) + ->Field("PagingParameters", &PlatformLimitsDescriptor::m_pagingParameters) + ->Field("UsageHintParameters", &PlatformLimitsDescriptor::m_usageHintParameters) + ->Field("HeapAllocationStrategy", &PlatformLimitsDescriptor::m_heapAllocationStrategy) ; } } @@ -72,5 +73,18 @@ namespace AZ { return aznew PlatformLimitsDescriptor; } + + void PlatformLimitsDescriptor::LoadPlatformLimitsDescriptor(const char* rhiName) + { + auto settingsRegistry = AZ::SettingsRegistry::Get(); + AZStd::string platformLimitsRegPath = AZStd::string::format("/Amazon/Atom/RHI/PlatformLimits/%s", rhiName); + if (!(settingsRegistry && + settingsRegistry->GetObject(this, azrtti_typeid(this), platformLimitsRegPath.c_str()))) + { + AZ_Warning( + "Device", false, "Platform limits for %s %s is not loaded correctly. Will use default values.", + AZ_TRAIT_OS_PLATFORM_NAME, rhiName); + } + } } } diff --git a/Gems/Atom/RHI/Code/Source/RHI/AsyncWorkQueue.cpp b/Gems/Atom/RHI/Code/Source/RHI/AsyncWorkQueue.cpp index d74ce558cd..a32301276e 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/AsyncWorkQueue.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/AsyncWorkQueue.cpp @@ -7,6 +7,8 @@ */ #include +#include + namespace AZ { namespace RHI @@ -124,7 +126,7 @@ namespace AZ return; } - AZ_PROFILE_FUNCTION_IDLE(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZStd::unique_lock lock(m_waitWorkItemMutex); m_waitWorkItemCondition.wait(lock, [&]() {return HasFinishedWork(workHandle); }); diff --git a/Gems/Atom/RHI/Code/Source/RHI/BufferPool.cpp b/Gems/Atom/RHI/Code/Source/RHI/BufferPool.cpp index 3c0359bf8a..9849db254e 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/BufferPool.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/BufferPool.cpp @@ -143,7 +143,7 @@ namespace AZ resultCode = MapBufferInternal(mapRequest, mapResponse); if (resultCode == ResultCode::Success) { - memcpy(mapResponse.m_data, initRequest.m_initialData, initRequest.m_descriptor.m_byteCount); + BufferCopy(mapResponse.m_data, initRequest.m_initialData, initRequest.m_descriptor.m_byteCount); UnmapBufferInternal(*initRequest.m_buffer); } } @@ -219,6 +219,11 @@ namespace AZ return m_descriptor; } + void BufferPool::BufferCopy(void* destination, const void* source, size_t num) + { + memcpy(destination, source, num); + } + ResultCode BufferPool::StreamBufferInternal([[maybe_unused]] const BufferStreamRequest& request) { return ResultCode::Unimplemented; diff --git a/Gems/Atom/RHI/Code/Source/RHI/BufferPoolBase.cpp b/Gems/Atom/RHI/Code/Source/RHI/BufferPoolBase.cpp index 8d61617da5..64f4454f0f 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/BufferPoolBase.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/BufferPoolBase.cpp @@ -34,7 +34,7 @@ namespace AZ if (!isDataValid) { - AZ_Warning("BufferPoolBase", false, "Failed to map buffer '%s'.", buffer.GetName().GetCStr()); + AZ_Error("BufferPoolBase", false, "Failed to map buffer '%s'.", buffer.GetName().GetCStr()); } ++buffer.m_mapRefCount; ++m_mapRefCount; diff --git a/Gems/Atom/RHI/Code/Source/RHI/CommandQueue.cpp b/Gems/Atom/RHI/Code/Source/RHI/CommandQueue.cpp index ae6a645440..2474967dab 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/CommandQueue.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/CommandQueue.cpp @@ -22,7 +22,7 @@ namespace AZ ResultCode CommandQueue::Init(Device& device, const CommandQueueDescriptor& descriptor) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); #if defined (AZ_RHI_ENABLE_VALIDATION) if (IsInitialized()) @@ -116,7 +116,7 @@ namespace AZ //run a command { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "RHI::CommandQueue - Execute Command"); + AZ_PROFILE_SCOPE(AzRender, "RHI::CommandQueue - Execute Command"); command(GetNativeQueue()); } } diff --git a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp index 5585cc7032..8099fc3a32 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp @@ -320,7 +320,7 @@ namespace AZ m_cachedTimeRegions.clear(); } - timeRegion.m_stackDepth = m_stackLevel; + timeRegion.m_stackDepth = static_cast(m_stackLevel); AZ_Assert(m_timeRegionStack.size() < TimeRegionStackSize, "Adding too many time regions to the stack. Increase the size of TimeRegionStackSize."); m_timeRegionStack.push_back(&timeRegion); @@ -417,14 +417,14 @@ namespace AZ // Create serializable entries for (const auto& timeRegionMap : continuousData) { - for (const auto& threadEntry : timeRegionMap) + for (const auto& [threadId, regionMap] : timeRegionMap) { - for (const auto& cachedRegionEntry : threadEntry.second) + for (const auto& [regionName, regionVec] : regionMap) { - m_cpuProfilingStatisticsSerializerEntries.insert( - m_cpuProfilingStatisticsSerializerEntries.end(), - cachedRegionEntry.second.begin(), - cachedRegionEntry.second.end()); + for (const auto& region : regionVec) + { + m_cpuProfilingStatisticsSerializerEntries.emplace_back(region, threadId); + } } } } @@ -445,13 +445,15 @@ namespace AZ // --- CpuProfilingStatisticsSerializerEntry --- - CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::CpuProfilingStatisticsSerializerEntry(const RHI::CachedTimeRegion& cachedTimeRegion) + CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::CpuProfilingStatisticsSerializerEntry( + const RHI::CachedTimeRegion& cachedTimeRegion, AZStd::thread_id threadId) { m_groupName = cachedTimeRegion.m_groupRegionName->m_groupName; m_regionName = cachedTimeRegion.m_groupRegionName->m_regionName; m_stackDepth = cachedTimeRegion.m_stackDepth; m_startTick = cachedTimeRegion.m_startTick; m_endTick = cachedTimeRegion.m_endTick; + m_threadId = AZStd::hash{}(threadId); } void CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::Reflect(AZ::ReflectContext* context) @@ -465,6 +467,7 @@ namespace AZ ->Field("stackDepth", &CpuProfilingStatisticsSerializerEntry::m_stackDepth) ->Field("startTick", &CpuProfilingStatisticsSerializerEntry::m_startTick) ->Field("endTick", &CpuProfilingStatisticsSerializerEntry::m_endTick) + ->Field("threadId", &CpuProfilingStatisticsSerializerEntry::m_threadId) ; } } diff --git a/Gems/Atom/RHI/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Code/Source/RHI/Device.cpp index b7a1e2315c..3af09717df 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/Device.cpp @@ -77,7 +77,7 @@ namespace AZ m_physicalDevice = &physicalDevice; - const ResultCode resultCode = InitInternal(physicalDevice); + RHI::ResultCode resultCode = InitInternal(physicalDevice); if (resultCode == ResultCode::Success) { @@ -90,6 +90,9 @@ namespace AZ // Assume all formats that haven't been mapped yet are supported and map to themselves FillRemainingSupportedFormats(); + + // Initialize limits and resources that are associated with them + resultCode = InitializeLimits(); } else { @@ -98,29 +101,6 @@ namespace AZ return resultCode; } - - ResultCode Device::PostInit(const DeviceDescriptor& descriptor) - { - if (Validation::IsEnabled()) - { - if (!IsInitialized()) - { - AZ_Error("Device", false, "Device is not initialized."); - return ResultCode::InvalidOperation; - } - } - - m_descriptor = descriptor; - const ResultCode resultCode = PostInitInternal(descriptor); - - if (resultCode != ResultCode::Success) - { - AZ_Error("Device", false, "Device is not initialized."); - return ResultCode::InvalidOperation; - } - - return resultCode; - } void Device::Shutdown() { diff --git a/Gems/Atom/RHI/Code/Source/RHI/Fence.cpp b/Gems/Atom/RHI/Code/Source/RHI/Fence.cpp index 838beb0863..868d2e3317 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/Fence.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/Fence.cpp @@ -81,7 +81,7 @@ namespace AZ return ResultCode::InvalidOperation; } - AZ_PROFILE_FUNCTION_IDLE(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); WaitOnCpuInternal(); return ResultCode::Success; } diff --git a/Gems/Atom/RHI/Code/Source/RHI/FrameGraph.cpp b/Gems/Atom/RHI/Code/Source/RHI/FrameGraph.cpp index d2298cda3f..ff6ecb4df5 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/FrameGraph.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/FrameGraph.cpp @@ -497,7 +497,7 @@ namespace AZ for (const uint32_t edgeIndex : graphEdges[producerIndex]) { const GraphEdge& graphEdge = m_graphEdges[edgeIndex]; - const uint16_t consumerIndex = graphEdge.m_consumerIndex; + const uint16_t consumerIndex = static_cast(graphEdge.m_consumerIndex); if (--m_graphNodes[consumerIndex].m_unsortedProducerCount == 0) { NodeId newNode; diff --git a/Gems/Atom/RHI/Code/Source/RHI/FrameScheduler.cpp b/Gems/Atom/RHI/Code/Source/RHI/FrameScheduler.cpp index 795ab591eb..0793c1ffd0 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/FrameScheduler.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/FrameScheduler.cpp @@ -137,7 +137,7 @@ namespace AZ ResultCode FrameScheduler::ImportScopeProducer(ScopeProducer& scopeProducer) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); if (!ValidateIsProcessing()) { @@ -216,7 +216,7 @@ namespace AZ void FrameScheduler::PrepareProducers() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: PrepareProducers"); for (ScopeProducer* scopeProducer : m_scopeProducers) @@ -237,7 +237,7 @@ namespace AZ void FrameScheduler::CompileProducers() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: CompileProducers"); for (ScopeProducer* scopeProducer : m_scopeProducers) @@ -249,12 +249,12 @@ namespace AZ void FrameScheduler::CompileShaderResourceGroups() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: CompileShaderResourceGroups"); // Execute all queued resource invalidations, which will mark SRG's for compilation. { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Invalidate Resources"); + AZ_PROFILE_SCOPE(AzRender, "Invalidate Resources"); ResourceInvalidateBus::ExecuteQueuedEvents(); } @@ -322,7 +322,7 @@ namespace AZ void FrameScheduler::BuildRayTracingShaderTables() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: BuildRayTracingShaderTables"); for (auto rayTracingShaderTable : m_rayTracingShaderTablesToBuild) @@ -341,7 +341,7 @@ namespace AZ ResultCode FrameScheduler::BeginFrame() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: BeginFrame"); if (!ValidateIsInitialized()) @@ -376,7 +376,7 @@ namespace AZ ResultCode FrameScheduler::EndFrame() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: EndFrame"); if (Validation::IsEnabled()) @@ -417,13 +417,13 @@ namespace AZ void FrameScheduler::ExecuteContextInternal(FrameGraphExecuteGroup& group, uint32_t index) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); FrameGraphExecuteContext* executeContext = group.BeginContext(index); { ScopeProducer* scopeProducer = FindScopeProducer(executeContext->GetScopeId()); - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzRender, "ScopeProducer: %s", scopeProducer->GetScopeId().GetCStr()); + AZ_PROFILE_SCOPE(AzRender, "ScopeProducer: %s", scopeProducer->GetScopeId().GetCStr()); scopeProducer->BuildCommandList(*executeContext); } @@ -432,7 +432,7 @@ namespace AZ void FrameScheduler::ExecuteGroupInternal(AZ::Job* parentJob, uint32_t groupIndex) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: ExecuteGroupInternal"); FrameGraphExecuteGroup* executeGroup = m_frameGraphExecuter->BeginGroup(groupIndex); @@ -475,7 +475,7 @@ namespace AZ void FrameScheduler::Execute(JobPolicy overrideJobPolicy) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RHI", "FrameScheduler: Execute"); const uint32_t groupCount = m_frameGraphExecuter->GetGroupCount(); diff --git a/Gems/Atom/RHI/Code/Source/RHI/Image.cpp b/Gems/Atom/RHI/Code/Source/RHI/Image.cpp index acefcca9e7..e864849a30 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/Image.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/Image.cpp @@ -61,7 +61,7 @@ namespace AZ imageStats->m_bindFlags = descriptor.m_bindFlags; ImageSubresourceRange subresourceRange; - subresourceRange.m_mipSliceMin = GetResidentMipLevel(); + subresourceRange.m_mipSliceMin = static_cast(GetResidentMipLevel()); GetSubresourceLayouts(subresourceRange, nullptr, &imageStats->m_sizeInBytes); } diff --git a/Gems/Atom/RHI/Code/Source/RHI/PipelineStateCache.cpp b/Gems/Atom/RHI/Code/Source/RHI/PipelineStateCache.cpp index 0210d941dc..69eee86108 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/PipelineStateCache.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/PipelineStateCache.cpp @@ -272,7 +272,7 @@ namespace AZ const PipelineState* PipelineStateCache::AcquirePipelineState(PipelineLibraryHandle handle, const PipelineStateDescriptor& descriptor) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); if (handle.IsNull()) { diff --git a/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp b/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp index 49244f776f..8f8b7677fd 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/RHISystem.cpp @@ -30,42 +30,26 @@ namespace AZ void RHISystem::InitDevice() { - m_device = InitInternalDevice(); Interface::Register(this); + m_device = InitInternalDevice(); } void RHISystem::Init(const RHISystemDescriptor& descriptor) { m_cpuProfiler.Init(); + Ptr platformLimitsDescriptor = m_device->GetDescriptor().m_platformLimitsDescriptor; + RHI::FrameSchedulerDescriptor frameSchedulerDescriptor; - if (descriptor.m_platformLimits) - { - m_platformLimitsDescriptor = descriptor.m_platformLimits->m_platformLimitsDescriptor; - } - - //If platformlimits.azasset file is not provided create an object with default config values. - if (!m_platformLimitsDescriptor) - { - m_platformLimitsDescriptor = PlatformLimitsDescriptor::Create(); - } - - RHI::DeviceDescriptor deviceDesc; - deviceDesc.m_platformLimitsDescriptor = m_platformLimitsDescriptor; - if (m_device->PostInit(deviceDesc) != RHI::ResultCode::Success) - { - AZ_Assert(false, "RHISystem", "Unable to initialize RHI! \n"); - return; - } m_drawListTagRegistry = RHI::DrawListTagRegistry::Create(); m_pipelineStateCache = RHI::PipelineStateCache::Create(*m_device); - frameSchedulerDescriptor.m_transientAttachmentPoolDescriptor.m_renderTargetBudgetInBytes = m_platformLimitsDescriptor->m_transientAttachmentPoolBudgets.m_renderTargetBudgetInBytes; - frameSchedulerDescriptor.m_transientAttachmentPoolDescriptor.m_imageBudgetInBytes = m_platformLimitsDescriptor->m_transientAttachmentPoolBudgets.m_imageBudgetInBytes; - frameSchedulerDescriptor.m_transientAttachmentPoolDescriptor.m_bufferBudgetInBytes = m_platformLimitsDescriptor->m_transientAttachmentPoolBudgets.m_bufferBudgetInBytes; + frameSchedulerDescriptor.m_transientAttachmentPoolDescriptor.m_renderTargetBudgetInBytes = platformLimitsDescriptor->m_transientAttachmentPoolBudgets.m_renderTargetBudgetInBytes; + frameSchedulerDescriptor.m_transientAttachmentPoolDescriptor.m_imageBudgetInBytes = platformLimitsDescriptor->m_transientAttachmentPoolBudgets.m_imageBudgetInBytes; + frameSchedulerDescriptor.m_transientAttachmentPoolDescriptor.m_bufferBudgetInBytes = platformLimitsDescriptor->m_transientAttachmentPoolBudgets.m_bufferBudgetInBytes; - switch (m_platformLimitsDescriptor->m_heapAllocationStrategy) + switch (platformLimitsDescriptor->m_heapAllocationStrategy) { case HeapAllocationStrategy::Fixed: { @@ -75,19 +59,19 @@ namespace AZ case HeapAllocationStrategy::Paging: { RHI::HeapPagingParameters heapAllocationParameters; - heapAllocationParameters.m_collectLatency = m_platformLimitsDescriptor->m_pagingParameters.m_collectLatency; - heapAllocationParameters.m_initialAllocationPercentage = m_platformLimitsDescriptor->m_pagingParameters.m_initialAllocationPercentage; - heapAllocationParameters.m_pageSizeInBytes = m_platformLimitsDescriptor->m_pagingParameters.m_pageSizeInBytes; + heapAllocationParameters.m_collectLatency = platformLimitsDescriptor->m_pagingParameters.m_collectLatency; + heapAllocationParameters.m_initialAllocationPercentage = platformLimitsDescriptor->m_pagingParameters.m_initialAllocationPercentage; + heapAllocationParameters.m_pageSizeInBytes = platformLimitsDescriptor->m_pagingParameters.m_pageSizeInBytes; frameSchedulerDescriptor.m_transientAttachmentPoolDescriptor.m_heapParameters = RHI::HeapAllocationParameters(heapAllocationParameters); break; } case HeapAllocationStrategy::MemoryHint: { RHI::HeapMemoryHintParameters heapAllocationParameters; - heapAllocationParameters.m_heapSizeScaleFactor = m_platformLimitsDescriptor->m_usageHintParameters.m_heapSizeScaleFactor; - heapAllocationParameters.m_collectLatency = m_platformLimitsDescriptor->m_usageHintParameters.m_collectLatency; - heapAllocationParameters.m_maxHeapWastedPercentage = m_platformLimitsDescriptor->m_usageHintParameters.m_maxHeapWastedPercentage; - heapAllocationParameters.m_minHeapSizeInBytes = m_platformLimitsDescriptor->m_usageHintParameters.m_minHeapSizeInBytes; + heapAllocationParameters.m_heapSizeScaleFactor = platformLimitsDescriptor->m_usageHintParameters.m_heapSizeScaleFactor; + heapAllocationParameters.m_collectLatency = platformLimitsDescriptor->m_usageHintParameters.m_collectLatency; + heapAllocationParameters.m_maxHeapWastedPercentage = platformLimitsDescriptor->m_usageHintParameters.m_maxHeapWastedPercentage; + heapAllocationParameters.m_minHeapSizeInBytes = platformLimitsDescriptor->m_usageHintParameters.m_minHeapSizeInBytes; frameSchedulerDescriptor.m_transientAttachmentPoolDescriptor.m_heapParameters = RHI::HeapAllocationParameters(heapAllocationParameters); break; } @@ -98,7 +82,7 @@ namespace AZ } } - frameSchedulerDescriptor.m_platformLimitsDescriptor = m_platformLimitsDescriptor; + frameSchedulerDescriptor.m_platformLimitsDescriptor = platformLimitsDescriptor; m_frameScheduler.Init(*m_device, frameSchedulerDescriptor); // Register draw list tags declared from content. @@ -183,6 +167,7 @@ namespace AZ RHI::Ptr device = RHI::Factory::Get().CreateDevice(); if (device->Init(*physicalDeviceFound) == RHI::ResultCode::Success) { + PlatformLimitsDescriptor::Create(); return device; } @@ -195,10 +180,9 @@ namespace AZ Interface::Unregister(this); m_frameScheduler.Shutdown(); - m_platformLimitsDescriptor = nullptr; m_pipelineStateCache = nullptr; if (m_device) - { + { m_device->PreShutdown(); AZ_Assert(m_device->use_count()==1, "The ref count for Device is %i but it should be 1 here to ensure all the resources are released", m_device->use_count()); m_device = nullptr; @@ -209,11 +193,11 @@ namespace AZ void RHISystem::FrameUpdate(FrameGraphCallback frameGraphCallback) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RHI", "RHISystem: FrameUpdate"); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "main per-frame work"); + AZ_PROFILE_SCOPE(AzRender, "main per-frame work"); m_frameScheduler.BeginFrame(); frameGraphCallback(m_frameScheduler); @@ -293,7 +277,7 @@ namespace AZ ConstPtr RHISystem::GetPlatformLimitsDescriptor() const { - return m_platformLimitsDescriptor; + return m_device->GetDescriptor().m_platformLimitsDescriptor; } void RHISystem::QueueRayTracingShaderTableForBuild(RayTracingShaderTable* rayTracingShaderTable) diff --git a/Gems/Atom/RHI/Code/Tests/Device.cpp b/Gems/Atom/RHI/Code/Tests/Device.cpp index 654653ceb9..0f424a5405 100644 --- a/Gems/Atom/RHI/Code/Tests/Device.cpp +++ b/Gems/Atom/RHI/Code/Tests/Device.cpp @@ -17,6 +17,11 @@ namespace UnitTest m_descriptor.m_description = "UnitTest Fake Device"; } + Device::Device() + { + m_descriptor.m_platformLimitsDescriptor = aznew RHI::PlatformLimitsDescriptor; + } + RHI::PhysicalDeviceList PhysicalDevice::Enumerate() { return RHI::PhysicalDeviceList{aznew PhysicalDevice}; @@ -29,7 +34,6 @@ namespace UnitTest RHI::Ptr device = RHI::Factory::Get().CreateDevice(); device->Init(*physicalDevices[0]); - device->PostInit(RHI::DeviceDescriptor{}); return device; } diff --git a/Gems/Atom/RHI/Code/Tests/Device.h b/Gems/Atom/RHI/Code/Tests/Device.h index e11bd75983..d3177fc823 100644 --- a/Gems/Atom/RHI/Code/Tests/Device.h +++ b/Gems/Atom/RHI/Code/Tests/Device.h @@ -31,10 +31,11 @@ namespace UnitTest public: AZ_CLASS_ALLOCATOR(Device, AZ::SystemAllocator, 0); + Device(); + private: AZ::RHI::ResultCode InitInternal(AZ::RHI::PhysicalDevice&) override { return AZ::RHI::ResultCode::Success; } - AZ::RHI::ResultCode PostInitInternal(const AZ::RHI::DeviceDescriptor&) override { return AZ::RHI::ResultCode::Success; } void ShutdownInternal() override {} @@ -54,7 +55,9 @@ namespace UnitTest } void FillFormatsCapabilitiesInternal([[maybe_unused]] FormatCapabilitiesList& formatsCapabilities) override {} - + + AZ::RHI::ResultCode InitializeLimits() override { return AZ::RHI::ResultCode::Success; } + void PreShutdown() override {} AZ::RHI::ResourceMemoryRequirements GetResourceMemoryRequirements([[maybe_unused]] const AZ::RHI::ImageDescriptor& descriptor) { return AZ::RHI::ResourceMemoryRequirements{}; }; diff --git a/Gems/Atom/RHI/Code/Tests/ImagePropertyTests.cpp b/Gems/Atom/RHI/Code/Tests/ImagePropertyTests.cpp index 60d6bfdf96..d53a9d31e6 100644 --- a/Gems/Atom/RHI/Code/Tests/ImagePropertyTests.cpp +++ b/Gems/Atom/RHI/Code/Tests/ImagePropertyTests.cpp @@ -106,7 +106,7 @@ namespace UnitTest range.m_arraySliceMax -= 1; auto overlapInterval = m_property.Get(range); EXPECT_EQ(overlapInterval.size(), m_imageDescriptor.m_mipLevels); - for (uint32_t i = 0; i < overlapInterval.size(); ++i) + for (uint16_t i = 0; i < overlapInterval.size(); ++i) { RHI::ImageSubresourceRange mipRange = range; mipRange.m_mipSliceMin = i; diff --git a/Gems/Atom/RHI/DX12/Code/CMakeLists.txt b/Gems/Atom/RHI/DX12/Code/CMakeLists.txt index a16b958c66..b913ad58bf 100644 --- a/Gems/Atom/RHI/DX12/Code/CMakeLists.txt +++ b/Gems/Atom/RHI/DX12/Code/CMakeLists.txt @@ -11,15 +11,6 @@ ly_get_list_relative_pal_filename(pal_source_dir ${CMAKE_CURRENT_LIST_DIR}/Sourc include(${pal_source_dir}/PAL_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) # PAL_TRAIT_ATOM_RHI_DX12_SUPPORTED -if(PAL_TRAIT_PIX_AVAILABLE) - set(USE_PIX_DEFINE "USE_PIX") - set(PIX_BUILD_DEPENDENCY "3rdParty::pix") -else() - set(USE_PIX_DEFINE "") - set(PIX_BUILD_DEPENDENCY "") -endif() - - if(PAL_TRAIT_AFTERMATH_AVAILABLE) set(USE_NSIGHT_AFTERMATH_DEFINE $,"","USE_NSIGHT_AFTERMATH">) set(AFTERMATH_BUILD_DEPENDENCY "3rdParty::Aftermath") @@ -92,11 +83,7 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE AZ::AzCore - ${PIX_BUILD_DEPENDENCY} Gem::Atom_RHI.Reflect - COMPILE_DEFINITIONS - PRIVATE - ${USE_PIX_DEFINE} ) ly_add_target( @@ -121,10 +108,8 @@ ly_add_target( Gem::Atom_RHI_DX12.Reflect 3rdParty::d3dx12 ${AFTERMATH_BUILD_DEPENDENCY} - ${PIX_BUILD_DEPENDENCY} COMPILE_DEFINITIONS PRIVATE - ${USE_PIX_DEFINE} ${USE_NSIGHT_AFTERMATH_DEFINE} ) @@ -148,10 +133,6 @@ ly_add_target( Gem::Atom_RHI.Public Gem::Atom_RHI_DX12.Reflect Gem::Atom_RHI_DX12.Private.Static - ${PIX_BUILD_DEPENDENCY} - COMPILE_DEFINITIONS - PRIVATE - ${USE_PIX_DEFINE} ) if(PAL_TRAIT_BUILD_HOST_TOOLS) diff --git a/Gems/Atom/RHI/DX12/Code/Include/Atom/RHI.Reflect/DX12/PlatformLimitsDescriptor.h b/Gems/Atom/RHI/DX12/Code/Include/Atom/RHI.Reflect/DX12/PlatformLimitsDescriptor.h index 06e15d0ca6..cbf1fd11f6 100644 --- a/Gems/Atom/RHI/DX12/Code/Include/Atom/RHI.Reflect/DX12/PlatformLimitsDescriptor.h +++ b/Gems/Atom/RHI/DX12/Code/Include/Atom/RHI.Reflect/DX12/PlatformLimitsDescriptor.h @@ -23,11 +23,11 @@ namespace AZ DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, DESCRIPTOR_HEAP_TYPE_SAMPLER, DESCRIPTOR_HEAP_TYPE_RTV, - DESCRIPTOR_HEAP_TYPE_DSV); + DESCRIPTOR_HEAP_TYPE_DSV); struct FrameGraphExecuterData { - AZ_TYPE_INFO(FrameGraphExecuterData, "{C21547F6-DE48-4F82-B812-1A187101AB4E}"); + AZ_TYPE_INFO(AZ::DX12::FrameGraphExecuterData, "{C21547F6-DE48-4F82-B812-1A187101AB4E}"); static void Reflect(AZ::ReflectContext* context); //Cost per draw/dispatch item @@ -52,15 +52,15 @@ namespace AZ { using Base = RHI::PlatformLimitsDescriptor; public: - AZ_RTTI(DX12::PlatformLimitsDescriptor, "{ADCC8071-FCE4-4FA1-A048-DF8982951A0D}", Base); - AZ_CLASS_ALLOCATOR(PlatformLimitsDescriptor, AZ::SystemAllocator, 0); + AZ_RTTI(AZ::DX12::PlatformLimitsDescriptor, "{ADCC8071-FCE4-4FA1-A048-DF8982951A0D}", Base); + AZ_CLASS_ALLOCATOR(AZ::DX12::PlatformLimitsDescriptor, AZ::SystemAllocator, 0); static void Reflect(AZ::ReflectContext* context); PlatformLimitsDescriptor() = default; static const uint32_t NumHeapFlags = 2;// D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE + 1; - //! string key: stringifed version of DESCRIPTOR_HEAP_TYPE. + //! string key: string version of DESCRIPTOR_HEAP_TYPE. //! int array: Max count for descriptors AZStd::unordered_map> m_descriptorHeapLimits; diff --git a/Gems/Atom/RHI/DX12/Code/Source/Platform/Android/PAL_android.cmake b/Gems/Atom/RHI/DX12/Code/Source/Platform/Android/PAL_android.cmake index 240ec6941c..8becd70f81 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/Platform/Android/PAL_android.cmake +++ b/Gems/Atom/RHI/DX12/Code/Source/Platform/Android/PAL_android.cmake @@ -7,5 +7,4 @@ # set(PAL_TRAIT_ATOM_RHI_DX12_SUPPORTED FALSE) -set(PAL_TRAIT_PIX_AVAILABLE FALSE) set(PAL_TRAIT_AFTERMATH_AVAILABLE FALSE) diff --git a/Gems/Atom/RHI/DX12/Code/Source/Platform/Linux/PAL_linux.cmake b/Gems/Atom/RHI/DX12/Code/Source/Platform/Linux/PAL_linux.cmake index 240ec6941c..8becd70f81 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/Platform/Linux/PAL_linux.cmake +++ b/Gems/Atom/RHI/DX12/Code/Source/Platform/Linux/PAL_linux.cmake @@ -7,5 +7,4 @@ # set(PAL_TRAIT_ATOM_RHI_DX12_SUPPORTED FALSE) -set(PAL_TRAIT_PIX_AVAILABLE FALSE) set(PAL_TRAIT_AFTERMATH_AVAILABLE FALSE) diff --git a/Gems/Atom/RHI/DX12/Code/Source/Platform/Mac/PAL_mac.cmake b/Gems/Atom/RHI/DX12/Code/Source/Platform/Mac/PAL_mac.cmake index 240ec6941c..8becd70f81 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/Platform/Mac/PAL_mac.cmake +++ b/Gems/Atom/RHI/DX12/Code/Source/Platform/Mac/PAL_mac.cmake @@ -7,5 +7,4 @@ # set(PAL_TRAIT_ATOM_RHI_DX12_SUPPORTED FALSE) -set(PAL_TRAIT_PIX_AVAILABLE FALSE) set(PAL_TRAIT_AFTERMATH_AVAILABLE FALSE) diff --git a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/PAL_windows.cmake b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/PAL_windows.cmake index a7e4015659..eb733a4d5a 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/PAL_windows.cmake +++ b/Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/PAL_windows.cmake @@ -18,21 +18,8 @@ if(d3d12_dll) set(PAL_TRAIT_ATOM_RHI_DX12_SUPPORTED TRUE) endif() -set(PAL_TRAIT_PIX_AVAILABLE FALSE) unset(pix3_header CACHE) -file(TO_CMAKE_PATH "$ENV{ATOM_PIX_PATH}" ATOM_PIX_PATH_CMAKE_FORMATTED) -find_file(pix3_header - pix3.h - PATHS - "${ATOM_PIX_PATH_CMAKE_FORMATTED}/Include/WinPixEventRuntime" -) - -mark_as_advanced(pix3_header) -if(pix3_header) - set(PAL_TRAIT_PIX_AVAILABLE TRUE) -endif() - set(PAL_TRAIT_AFTERMATH_AVAILABLE FALSE) unset(aftermath_header CACHE) file(TO_CMAKE_PATH "$ENV{ATOM_AFTERMATH_PATH}" ATOM_AFTERMATH_PATH_CMAKE_FORMATTED) diff --git a/Gems/Atom/RHI/DX12/Code/Source/Platform/iOS/PAL_ios.cmake b/Gems/Atom/RHI/DX12/Code/Source/Platform/iOS/PAL_ios.cmake index 240ec6941c..8becd70f81 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/Platform/iOS/PAL_ios.cmake +++ b/Gems/Atom/RHI/DX12/Code/Source/Platform/iOS/PAL_ios.cmake @@ -7,5 +7,4 @@ # set(PAL_TRAIT_ATOM_RHI_DX12_SUPPORTED FALSE) -set(PAL_TRAIT_PIX_AVAILABLE FALSE) set(PAL_TRAIT_AFTERMATH_AVAILABLE FALSE) diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI.Reflect/BufferPoolDescriptor.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI.Reflect/BufferPoolDescriptor.cpp index 0cc8fd0202..5007b21976 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI.Reflect/BufferPoolDescriptor.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI.Reflect/BufferPoolDescriptor.cpp @@ -26,7 +26,7 @@ namespace AZ BufferPoolDescriptor::BufferPoolDescriptor() { - m_bufferPoolPageSizeInBytes = RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_bufferPoolPageSizeInBytes; + m_bufferPoolPageSizeInBytes = static_cast(RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_bufferPoolPageSizeInBytes); } } } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp index 3c685051ea..980264aa9b 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp @@ -19,8 +19,8 @@ namespace AZ { serializeContext->Class() ->Version(0) - ->Field("m_descriptorHeapLimits", &PlatformLimitsDescriptor::m_descriptorHeapLimits) - ->Field("m_frameGraphExecuterData", &PlatformLimitsDescriptor::m_frameGraphExecuterData) + ->Field("DescriptorHeapLimits", &PlatformLimitsDescriptor::m_descriptorHeapLimits) + ->Field("FrameGraphExecuterData", &PlatformLimitsDescriptor::m_frameGraphExecuterData) ; } } @@ -31,11 +31,11 @@ namespace AZ { serializeContext->Class() ->Version(0) - ->Field("m_itemCost", &FrameGraphExecuterData::m_itemCost) - ->Field("m_attachmentCost", &FrameGraphExecuterData::m_attachmentCost) - ->Field("m_swapChainsPerCommandList", &FrameGraphExecuterData::m_swapChainsPerCommandList) - ->Field("m_commandListCostThresholdMin", &FrameGraphExecuterData::m_commandListCostThresholdMin) - ->Field("m_commandListsPerScopeMax", &FrameGraphExecuterData::m_commandListsPerScopeMax) + ->Field("ItemCost", &FrameGraphExecuterData::m_itemCost) + ->Field("AttachmentCost", &FrameGraphExecuterData::m_attachmentCost) + ->Field("SwapChainsPerCommandList", &FrameGraphExecuterData::m_swapChainsPerCommandList) + ->Field("CommandListCostThresholdMin", &FrameGraphExecuterData::m_commandListCostThresholdMin) + ->Field("CommandListsPerScopeMax", &FrameGraphExecuterData::m_commandListsPerScopeMax) ; } } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp index 70c6aa0b7c..81e52d6d3f 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/AsyncUploadQueue.cpp @@ -152,21 +152,21 @@ namespace AZ m_copyQueue->QueueCommand([=](void* commandQueue) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Upload Buffer"); + AZ_PROFILE_SCOPE(AzRender, "Upload Buffer"); size_t pendingByteOffset = 0; size_t pendingByteCount = byteCount; ID3D12CommandQueue* dx12CommandQueue = static_cast(commandQueue); while (pendingByteCount > 0) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Upload Buffer Chunk"); + AZ_PROFILE_SCOPE(AzRender, "Upload Buffer Chunk"); FramePacket* framePacket = BeginFramePacket(); const size_t bytesToCopy = AZStd::min(pendingByteCount, m_descriptor.m_stagingSizeInBytes); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Copy CPU buffer"); + AZ_PROFILE_SCOPE(AzRender, "Copy CPU buffer"); memcpy(framePacket->m_stagingResourceData, sourceData + pendingByteOffset, bytesToCopy); } @@ -196,7 +196,7 @@ namespace AZ AsyncUploadQueue::FramePacket* AsyncUploadQueue::BeginFramePacket() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_Assert(!m_recordingFrame, "The previous frame packet isn't ended"); FramePacket* framePacket = &m_framePackets[m_frameIndex]; @@ -212,7 +212,7 @@ namespace AZ void AsyncUploadQueue::EndFramePacket(ID3D12CommandQueue* commandQueue) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_Assert(m_recordingFrame, "The frame packet wasn't started. You need to call StartFramePacket first."); AssertSuccess(m_commandList->Close()); @@ -229,7 +229,7 @@ namespace AZ // [GFX TODO][ATOM-4205] Stage/Upload 3D streaming images more efficiently. uint64_t AsyncUploadQueue::QueueUpload(const RHI::StreamingImageExpandRequest& request, uint32_t residentMip) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); uint64_t fenceValue = m_uploadFence.Increment(); @@ -243,7 +243,7 @@ namespace AZ m_copyQueue->QueueCommand([=](void* commandQueue) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Upload Image"); + AZ_PROFILE_SCOPE(AzRender, "Upload Image"); ID3D12CommandQueue* dx12CommandQueue = static_cast(commandQueue); FramePacket* framePacket = BeginFramePacket(); @@ -314,7 +314,7 @@ namespace AZ // Copy subresource data to staging memory. { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Copy CPU image"); + AZ_PROFILE_SCOPE(AzRender, "Copy CPU image"); uint8_t* stagingDataStart = framePacket->m_stagingResourceData + framePacket->m_dataOffset; const uint8_t* subresourceSliceDataStart = static_cast(subresource.m_data) + (depth * subresourceSlicePitch); @@ -385,7 +385,7 @@ namespace AZ // Copy subresource data to staging memory { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Copy CPU image"); + AZ_PROFILE_SCOPE(AzRender, "Copy CPU image"); for (uint32_t row = startRow; row < endRow; row++) { uint8_t* stagingDataStart = framePacket->m_stagingResourceData + framePacket->m_dataOffset; @@ -476,7 +476,7 @@ namespace AZ void AsyncUploadQueue::WaitForUpload(uint64_t fenceValue) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); if (!IsUploadFinished(fenceValue)) { @@ -490,7 +490,7 @@ namespace AZ void AsyncUploadQueue::ProcessCallbacks(uint64_t fenceValue) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZStd::lock_guard lock(m_callbackMutex); while (m_callbacks.size() > 0 && m_callbacks.front().second <= fenceValue) { @@ -504,7 +504,7 @@ namespace AZ { m_copyQueue->QueueCommand([=](void* commandQueue) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "QueueTileMapping"); + AZ_PROFILE_SCOPE(AzRender, "QueueTileMapping"); ID3D12CommandQueue* dx12CommandQueue = static_cast(commandQueue); const uint32_t tileCount = request.m_sourceRegionSize.NumTiles; diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/BufferPool.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/BufferPool.cpp index 680669776c..c7b78a3945 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/BufferPool.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/BufferPool.cpp @@ -203,7 +203,7 @@ namespace AZ RHI::HeapMemoryUsage& heapMemoryUsage = m_memoryUsage.GetHeapMemoryUsage(descriptorBase.m_heapMemoryLevel); - uint32_t bufferPageSize = RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_bufferPoolPageSizeInBytes; + uint32_t bufferPageSize = static_cast(RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_bufferPoolPageSizeInBytes); // The DX12 descriptor provides an explicit buffer page size override. if (const DX12::BufferPoolDescriptor* descriptor = azrtti_cast(&descriptorBase)) diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.cpp index 7aa9f5391a..a8ae753294 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.cpp @@ -33,7 +33,7 @@ namespace AZ void CommandListBase::Reset(ID3D12CommandAllocator* commandAllocator) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_Assert(m_queuedBarriers.empty(), "Unflushed barriers in command list."); m_commandList->Reset(commandAllocator, nullptr); @@ -95,7 +95,7 @@ namespace AZ { if (m_queuedBarriers.size()) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRenderDetailed); + AZ_PROFILE_FUNCTION(AzRenderDetailed); m_commandList->ResourceBarrier((UINT)m_queuedBarriers.size(), m_queuedBarriers.data()); m_queuedBarriers.clear(); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.h b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.h index 5337228614..5f3e4dce1e 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.h +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandListBase.h @@ -7,11 +7,15 @@ */ #pragma once +// NOTE: We are careful to include platform headers *before* we include AzCore/Debug/Profiler.h to ensure that d3d12 symbols +// are defined prior to the inclusion of the pix3 runtime. +#include + #include #include +#include #include #include -#include namespace AZ { diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueue.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueue.cpp index 9de706cbe1..b73228e717 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueue.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueue.cpp @@ -110,7 +110,7 @@ namespace AZ { QueueCommand([this, &fence](void* commandQueue) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "SignalFence"); + AZ_PROFILE_SCOPE(AzRender, "SignalFence"); ID3D12CommandQueue* dx12CommandQueue = static_cast(commandQueue); dx12CommandQueue->Signal(fence.Get(), fence.GetPendingValue()); }); @@ -138,7 +138,7 @@ namespace AZ QueueCommand([=](void* commandQueue) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "ExecuteWork"); + AZ_PROFILE_SCOPE(AzRender, "ExecuteWork"); AZ_PROFILE_RHI_VARIABLE(m_lastExecuteDuration); static const uint32_t CommandListCountMax = 128; @@ -195,7 +195,7 @@ namespace AZ void CommandQueue::UpdateTileMappings(CommandList& commandList) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); for (const CommandList::TileMapRequest& request : commandList.GetTileMapRequests()) { const uint32_t tileCount = request.m_sourceRegionSize.NumTiles; @@ -229,7 +229,7 @@ namespace AZ void CommandQueue::WaitForIdle() { - AZ_PROFILE_FUNCTION_IDLE(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); Fence fence; fence.Init(m_device.get(), RHI::FenceState::Reset); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp index 1c5fd6fa05..f35f66f3e8 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/CommandQueueContext.cpp @@ -101,7 +101,7 @@ namespace AZ void CommandQueueContext::WaitForIdle() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); for (uint32_t hardwareQueueIdx = 0; hardwareQueueIdx < RHI::HardwareQueueClassCount; ++hardwareQueueIdx) { if (m_commandQueues[hardwareQueueIdx]) @@ -113,10 +113,10 @@ namespace AZ void CommandQueueContext::Begin() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Clearing Command Queue Timers"); + AZ_PROFILE_SCOPE(AzRender, "Clearing Command Queue Timers"); for (const RHI::Ptr& commandQueue : m_commandQueues) { commandQueue->ClearTimers(); @@ -131,7 +131,7 @@ namespace AZ void CommandQueueContext::End() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("DX12", "CommandQueueContext: End"); QueueGpuSignals(m_frameFences[m_currentFrameIndex]); @@ -145,7 +145,7 @@ namespace AZ m_currentFrameIndex = (m_currentFrameIndex + 1) % aznumeric_cast(m_frameFences.size()); { - AZ_PROFILE_SCOPE_IDLE(AZ::Debug::ProfileCategory::AzRender, "Wait and Reset Fence"); + AZ_PROFILE_SCOPE(AzRender, "Wait and Reset Fence"); AZ_ATOM_PROFILE_TIME_GROUP_REGION("DX12", "CommandQueueContext: Wait on Fences"); FenceEvent event("FrameFence"); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Conversions.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/Conversions.cpp index 98dc2965fb..823ec8e4e0 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Conversions.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Conversions.cpp @@ -353,7 +353,7 @@ namespace AZ if (imageViewDescriptor.m_depthSliceMax == RHI::ImageViewDescriptor::HighestSliceIndex) { - renderTargetView.Texture3D.WSize = -1; + renderTargetView.Texture3D.WSize = std::numeric_limits::max(); } else { @@ -578,7 +578,7 @@ namespace AZ if (imageViewDescriptor.m_depthSliceMax == RHI::ImageViewDescriptor::HighestSliceIndex) { - unorderedAccessView.Texture3D.WSize = -1; + unorderedAccessView.Texture3D.WSize = std::numeric_limits::max(); } else { @@ -1264,7 +1264,7 @@ namespace AZ dst.BlendOpAlpha = ConvertBlendOp(src.m_blendAlphaOp); dst.DestBlend = ConvertBlendFactor(src.m_blendDest); dst.DestBlendAlpha = ConvertBlendFactor(src.m_blendAlphaDest); - dst.RenderTargetWriteMask = ConvertColorWriteMask(src.m_writeMask); + dst.RenderTargetWriteMask = ConvertColorWriteMask(static_cast(src.m_writeMask)); dst.SrcBlend = ConvertBlendFactor(src.m_blendSource); dst.SrcBlendAlpha = ConvertBlendFactor(src.m_blendAlphaSource); dst.LogicOp = D3D12_LOGIC_OP_CLEAR; @@ -1399,8 +1399,8 @@ namespace AZ desc.DepthFunc = ConvertComparisonFunc(depthStencil.m_depth.m_func); desc.DepthWriteMask = ConvertDepthWriteMask(depthStencil.m_depth.m_writeMask); desc.StencilEnable = depthStencil.m_stencil.m_enable; - desc.StencilReadMask = depthStencil.m_stencil.m_readMask; - desc.StencilWriteMask = depthStencil.m_stencil.m_writeMask; + desc.StencilReadMask = static_cast(depthStencil.m_stencil.m_readMask); + desc.StencilWriteMask = static_cast(depthStencil.m_stencil.m_writeMask); return desc; } } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp index 9d23dfa43d..371aa20a84 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp @@ -5,6 +5,7 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ +#include #include #include #include @@ -29,6 +30,13 @@ namespace AZ void DeviceCompileMemoryStatisticsInternal(RHI::MemoryStatisticsBuilder& builder, IDXGIAdapterX* dxgiAdapter); } + Device::Device() + { + RHI::Ptr platformLimitsDescriptor = aznew PlatformLimitsDescriptor(); + platformLimitsDescriptor->LoadPlatformLimitsDescriptor(RHI::Factory::Get().GetName().GetCStr()); + m_descriptor.m_platformLimitsDescriptor = RHI::Ptr(platformLimitsDescriptor); + } + RHI::Ptr Device::Create() { return aznew Device(); @@ -43,35 +51,31 @@ namespace AZ } InitFeatures(); + return RHI::ResultCode::Success; } - RHI::ResultCode Device::PostInitInternal(const RHI::DeviceDescriptor& descriptor) + RHI::ResultCode Device::InitializeLimits() { m_allocationInfoCache.SetInitFunction([](auto& cache) { cache.set_capacity(64); }); { ReleaseQueue::Descriptor releaseQueueDescriptor; - releaseQueueDescriptor.m_collectLatency = descriptor.m_frameCountMax - 1; + releaseQueueDescriptor.m_collectLatency = m_descriptor.m_frameCountMax - 1; m_releaseQueue.Init(releaseQueueDescriptor); } m_descriptorContext = AZStd::make_shared(); - RHI::ConstPtr rhiDescriptor = descriptor.m_platformLimitsDescriptor; - if (RHI::ConstPtr platLimitsDesc = azrtti_cast(rhiDescriptor)) - { - m_descriptorContext->Init(m_dx12Device.get(), platLimitsDesc); - } - else - { - AZ_Assert(false, "Missing PlatformLimits config file for DX12 backend"); - } + RHI::ConstPtr rhiDescriptor = m_descriptor.m_platformLimitsDescriptor; + RHI::ConstPtr platLimitsDesc = azrtti_cast(rhiDescriptor); + AZ_Assert(platLimitsDesc != nullptr, "Missing PlatformLimits config file for DX12 backend"); + m_descriptorContext->Init(m_dx12Device.get(), platLimitsDesc); { CommandListAllocator::Descriptor commandListAllocatorDescriptor; commandListAllocatorDescriptor.m_device = this; - commandListAllocatorDescriptor.m_frameCountMax = descriptor.m_frameCountMax; + commandListAllocatorDescriptor.m_frameCountMax = m_descriptor.m_frameCountMax; commandListAllocatorDescriptor.m_descriptorContext = m_descriptorContext; m_commandListAllocator.Init(commandListAllocatorDescriptor); } @@ -80,9 +84,9 @@ namespace AZ StagingMemoryAllocator::Descriptor allocatorDesc; allocatorDesc.m_device = this; - allocatorDesc.m_mediumPageSizeInBytes = RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_mediumStagingBufferPageSizeInBytes; - allocatorDesc.m_largePageSizeInBytes = RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_largestStagingBufferPageSizeInBytes; - allocatorDesc.m_collectLatency = descriptor.m_frameCountMax; + allocatorDesc.m_mediumPageSizeInBytes = static_cast(platLimitsDesc->m_platformDefaultValues.m_mediumStagingBufferPageSizeInBytes); + allocatorDesc.m_largePageSizeInBytes = static_cast(platLimitsDesc->m_platformDefaultValues.m_largestStagingBufferPageSizeInBytes); + allocatorDesc.m_collectLatency = m_descriptor.m_frameCountMax; m_stagingMemoryAllocator.Init(allocatorDesc); } @@ -90,7 +94,7 @@ namespace AZ m_commandQueueContext.Init(*this); - m_asyncUploadQueue.Init(*this, AsyncUploadQueue::Descriptor(RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_asyncQueueStagingBufferSizeInBytes)); + m_asyncUploadQueue.Init(*this, AsyncUploadQueue::Descriptor(platLimitsDesc->m_platformDefaultValues.m_asyncQueueStagingBufferSizeInBytes)); m_samplerCache.SetCapacity(SamplerCacheCapacity); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h index 9119545342..4d1f2c4ac9 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.h @@ -143,12 +143,11 @@ namespace AZ bool IsAftermathInitialized() const; private: - Device() = default; + Device(); ////////////////////////////////////////////////////////////////////////// // RHI::Device RHI::ResultCode InitInternal(RHI::PhysicalDevice& physicalDevice) override; - RHI::ResultCode PostInitInternal(const RHI::DeviceDescriptor & params) override; void ShutdownInternal() override; void CompileMemoryStatisticsInternal(RHI::MemoryStatisticsBuilder& builder) override; @@ -158,6 +157,7 @@ namespace AZ void WaitForIdleInternal() override; AZStd::chrono::microseconds GpuTimestampToMicroseconds(uint64_t gpuTimestamp, RHI::HardwareQueueClass queueClass) const override; void FillFormatsCapabilitiesInternal(FormatCapabilitiesList& formatsCapabilities) override; + RHI::ResultCode InitializeLimits() override; AZStd::vector GetValidSwapChainImageFormats(const RHI::WindowHandle& windowHandle) const override; void PreShutdown() override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::ImageDescriptor & descriptor) override; diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp index f61aa3f67f..6244089d93 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.cpp @@ -60,7 +60,7 @@ namespace AZ { if (fenceValue > GetCompletedValue()) { - AZ_PROFILE_SCOPE_IDLE_DYNAMIC(AZ::Debug::ProfileCategory::AzRender, "Fence Wait: %s", fenceEvent.GetName()); + AZ_PROFILE_SCOPE(AzRender, "Fence Wait: %s", fenceEvent.GetName()); m_fence->SetEventOnCompletion(fenceValue, fenceEvent.m_EventHandle); WaitForSingleObject(fenceEvent.m_EventHandle, INFINITE); } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.h b/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.h index 064efe5722..ab1a719ae6 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.h +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Fence.h @@ -7,12 +7,15 @@ */ #pragma once +// NOTE: We are careful to include platform headers *before* we include AzCore/Debug/Profiler.h to ensure that d3d12 symbols +// are defined prior to the inclusion of the pix3 runtime. +#include + #include #include #include #include #include -#include namespace AZ { diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/IndirectBufferSignature.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/IndirectBufferSignature.cpp index 42c5f91817..526c913085 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/IndirectBufferSignature.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/IndirectBufferSignature.cpp @@ -111,6 +111,8 @@ namespace AZ void IndirectBufferSignature::ShutdownInternal() { + auto& device = static_cast(GetDevice()); + device.QueueForRelease(m_signature); m_signature = nullptr; m_stride = 0; } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/PipelineLayout.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/PipelineLayout.cpp index 1336642d8b..3fdeec1c51 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/PipelineLayout.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/PipelineLayout.cpp @@ -139,8 +139,8 @@ namespace AZ const RHI::ShaderResourceGroupLayout& groupLayout = *descriptor.GetShaderResourceGroupLayout(groupLayoutIndex); const uint32_t srgLayoutSlot = groupLayout.GetBindingSlot(); - m_slotToIndexTable[srgLayoutSlot] = groupLayoutIndex; - m_indexToSlotTable[groupLayoutIndex] = srgLayoutSlot; + m_slotToIndexTable[srgLayoutSlot] = static_cast(groupLayoutIndex); + m_indexToSlotTable[groupLayoutIndex] = static_cast(srgLayoutSlot); } // Construct a list of indexes sorted by frequency. diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/QueryPool.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/QueryPool.cpp index 5bb2be662d..f5eacfc576 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/QueryPool.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/QueryPool.cpp @@ -237,5 +237,14 @@ namespace AZ static constexpr D3D12_RANGE InvalidRange = {0,0}; m_readBackBuffer->Unmap(0, &InvalidRange); } + + void QueryPool::ShutdownInternal() + { + auto& device = static_cast(GetDevice()); + device.QueueForRelease(m_queryHeap); + m_queryHeap = nullptr; + device.QueueForRelease(m_readBackBuffer); + m_readBackBuffer = nullptr; + } } } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/QueryPool.h b/Gems/Atom/RHI/DX12/Code/Source/RHI/QueryPool.h index eca040b724..7b0ab512cc 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/QueryPool.h +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/QueryPool.h @@ -44,6 +44,7 @@ namespace AZ RHI::ResultCode InitInternal(RHI::Device& device, const RHI::QueryPoolDescriptor& descriptor) override; RHI::ResultCode InitQueryInternal(RHI::Query& query) override; RHI::ResultCode GetResultsInternal(uint32_t startIndex, uint32_t queryCount, uint64_t* results, uint32_t resultsCount, RHI::QueryResultFlagBits flags) override; + void ShutdownInternal() override; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/StreamingImagePool.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/StreamingImagePool.cpp index 6f35bb32ae..11863cb70b 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/StreamingImagePool.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/StreamingImagePool.cpp @@ -129,7 +129,7 @@ namespace AZ residentImageDescriptor.m_size = imageDescriptor.m_size.GetReducedMip(residentMipLevel); residentImageDescriptor.m_size.m_width = RHI::AlignUp(residentImageDescriptor.m_size.m_width, alignment); residentImageDescriptor.m_size.m_height = RHI::AlignUp(residentImageDescriptor.m_size.m_height, alignment); - residentImageDescriptor.m_mipLevels = imageDescriptor.m_mipLevels - residentMipLevel; + residentImageDescriptor.m_mipLevels = static_cast(imageDescriptor.m_mipLevels - residentMipLevel); D3D12_RESOURCE_ALLOCATION_INFO allocationInfo; GetDevice().GetImageAllocationInfo(residentImageDescriptor, allocationInfo); @@ -144,7 +144,7 @@ namespace AZ #ifdef AZ_RHI_USE_TILED_RESOURCES { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "StreamImagePool::CreateHeap"); + AZ_PROFILE_SCOPE(AzRender, "StreamImagePool::CreateHeap"); CD3DX12_HEAP_DESC heapDesc(descriptor.m_budgetInBytes, D3D12_HEAP_TYPE_DEFAULT, 0, D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES); diff --git a/Gems/Atom/RHI/Metal/Code/Include/Atom/RHI.Reflect/Metal/PlatformLimitsDescriptor.h b/Gems/Atom/RHI/Metal/Code/Include/Atom/RHI.Reflect/Metal/PlatformLimitsDescriptor.h index ace3e08142..375b532d39 100644 --- a/Gems/Atom/RHI/Metal/Code/Include/Atom/RHI.Reflect/Metal/PlatformLimitsDescriptor.h +++ b/Gems/Atom/RHI/Metal/Code/Include/Atom/RHI.Reflect/Metal/PlatformLimitsDescriptor.h @@ -18,7 +18,7 @@ namespace AZ { struct FrameGraphExecuterData { - AZ_TYPE_INFO(FrameGraphExecuterData, "{BD831EFB-CC74-46F8-BE48-118B2E8F07D0}"); + AZ_TYPE_INFO(AZ::Metal::FrameGraphExecuterData, "{BD831EFB-CC74-46F8-BE48-118B2E8F07D0}"); static void Reflect(AZ::ReflectContext* context); //Cost per draw/dispatch item @@ -43,8 +43,8 @@ namespace AZ { using Base = RHI::PlatformLimitsDescriptor; public: - AZ_RTTI(Metal::PlatformLimitsDescriptor, "{B89F116F-9FEF-4BCA-9EC7-9FF8F772B7FD}", Base); - AZ_CLASS_ALLOCATOR(PlatformLimitsDescriptor, AZ::SystemAllocator, 0); + AZ_RTTI(AZ::Metal::PlatformLimitsDescriptor, "{B89F116F-9FEF-4BCA-9EC7-9FF8F772B7FD}", Base); + AZ_CLASS_ALLOCATOR(AZ::Metal::PlatformLimitsDescriptor, AZ::SystemAllocator, 0); static void Reflect(AZ::ReflectContext* context); FrameGraphExecuterData m_frameGraphExecuterData; diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI.Reflect/BufferPoolDescriptor.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI.Reflect/BufferPoolDescriptor.cpp index 160dce12d5..c80b04bc73 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI.Reflect/BufferPoolDescriptor.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI.Reflect/BufferPoolDescriptor.cpp @@ -26,7 +26,7 @@ namespace AZ BufferPoolDescriptor::BufferPoolDescriptor() { - m_bufferPoolPageSizeInBytes = RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_bufferPoolPageSizeInBytes; + m_bufferPoolPageSizeInBytes = static_cast(RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_bufferPoolPageSizeInBytes); } } } diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp index bdf405d157..4788244775 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp @@ -18,8 +18,8 @@ namespace AZ if (SerializeContext* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(0) - ->Field("m_frameGraphExecuterData", &PlatformLimitsDescriptor::m_frameGraphExecuterData) + ->Version(1) + ->Field("FrameGraphExecuterData", &PlatformLimitsDescriptor::m_frameGraphExecuterData) ; } } @@ -29,12 +29,12 @@ namespace AZ if (auto* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(0) - ->Field("m_itemCost", &FrameGraphExecuterData::m_itemCost) - ->Field("m_attachmentCost", &FrameGraphExecuterData::m_attachmentCost) - ->Field("m_swapChainsPerCommandList", &FrameGraphExecuterData::m_swapChainsPerCommandList) - ->Field("m_commandListCostThresholdMin", &FrameGraphExecuterData::m_commandListCostThresholdMin) - ->Field("m_commandListsPerScopeMax", &FrameGraphExecuterData::m_commandListsPerScopeMax) + ->Version(1) + ->Field("ItemCost", &FrameGraphExecuterData::m_itemCost) + ->Field("AttachmentCost", &FrameGraphExecuterData::m_attachmentCost) + ->Field("SwapChainsPerCommandList", &FrameGraphExecuterData::m_swapChainsPerCommandList) + ->Field("CommandListCostThresholdMin", &FrameGraphExecuterData::m_commandListCostThresholdMin) + ->Field("CommandListsPerScopeMax", &FrameGraphExecuterData::m_commandListsPerScopeMax) ; } } diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp index 383c5e5a79..05107128ad 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.cpp @@ -204,6 +204,7 @@ namespace AZ { RHI::Ptr nullMtlImagePtr = m_device->GetNullDescriptorManager().GetNullImage(shaderInputImage.m_type).GetMemory(); mtlTextures[imageArrayLen] = nullMtlImagePtr->GetGpuAddress>(); + m_useNullDescriptorHeap = true; } imageArrayLen++; } @@ -282,12 +283,16 @@ namespace AZ { RHI::Ptr nullMtlBufferMemPtr = nullDescriptorManager.GetNullImageBuffer().GetMemory(); mtlTextures[bufferArrayLen] = nullMtlBufferMemPtr->GetGpuAddress>(); + m_useNullDescriptorHeap = true; } else { RHI::Ptr nullMtlBufferMemPtr = nullDescriptorManager.GetNullBuffer().GetMemory(); mtlBuffers[bufferArrayLen] = nullMtlBufferMemPtr->GetGpuAddress>(); mtlBufferOffsets[bufferArrayLen] = nullDescriptorManager.GetNullBuffer().GetOffset(); + m_resourceBindings[shaderInputBuffer.m_name].insert( + ResourceBindingData{nullMtlBufferMemPtr, .m_bufferAccess = shaderInputBuffer.m_access} + ); } } @@ -499,5 +504,26 @@ namespace AZ resourcesToMakeResidentMap[key].emplace(mtlResourceToBind); } } + + bool ArgumentBuffer::IsNullHeapNeededForVertexStage(const ShaderResourceGroupVisibility& srgResourcesVisInfo) const + { + bool isUsedByVertexStage = false; + + //Iterate over all the SRG entries + for (const auto& it : srgResourcesVisInfo.m_resourcesStageMask) + { + //Only the ones not added to m_resourceBindings would require null heap + if( m_resourceBindings.find(it.first) == m_resourceBindings.end()) + { + isUsedByVertexStage |= RHI::CheckBitsAny(it.second, RHI::ShaderStageMask::Vertex); + } + } + return isUsedByVertexStage; + } + + bool ArgumentBuffer::IsNullDescHeapNeeded() const + { + return m_useNullDescriptorHeap; + } } } diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h index cf229aeb75..a680516dc6 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/ArgumentBuffer.h @@ -104,6 +104,8 @@ namespace AZ GraphicsResourcesToMakeResidentMap& resourcesToMakeResidentGraphics) const; void ClearResourceTracking(); + bool IsNullHeapNeededForVertexStage(const ShaderResourceGroupVisibility& srgResourcesVisInfo) const; + bool IsNullDescHeapNeeded() const; ////////////////////////////////////////////////////////////////////////// // RHI::DeviceObject @@ -153,6 +155,7 @@ namespace AZ MemoryView m_argumentBuffer; MemoryView m_constantBuffer; #endif + bool m_useNullDescriptorHeap = false; }; } } diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.cpp index 2614addfe3..3c45e69d8b 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandList.cpp @@ -245,6 +245,8 @@ namespace AZ bool CommandList::SetArgumentBuffers(const PipelineState* pipelineState, RHI::PipelineStateType stateType) { + bool bindNullDescriptorHeap = false; + MTLRenderStages mtlRenderStagesForNullDescHeap = 0; ShaderResourceBindings& bindings = GetShaderResourceBindingsByPipelineType(stateType); const PipelineLayout& pipelineLayout = pipelineState->GetPipelineLayout(); @@ -280,7 +282,8 @@ namespace AZ uint32_t srgVisIndex = pipelineLayout.GetIndexBySlot(shaderResourceGroup->GetBindingSlot()); const RHI::ShaderStageMask& srgVisInfo = pipelineLayout.GetSrgVisibility(srgVisIndex); - + const ShaderResourceGroupVisibility& srgResourcesVisInfo = pipelineLayout.GetSrgResourcesVisibility(srgVisIndex); + bool isSrgUpdatd = bindings.m_srgsByIndex[slot] != shaderResourceGroup; if(isSrgUpdatd) { @@ -291,6 +294,9 @@ namespace AZ if(srgVisInfo != RHI::ShaderStageMask::None) { + bool isNullDescHeapNeeded = compiledArgBuffer.IsNullDescHeapNeeded(); + bindNullDescriptorHeap |= isNullDescHeapNeeded; + //For graphics and compute shader stages, cache all the argument buffers, offsets and track the min/max indices if(m_commandEncoderType == CommandEncoderType::Render) { @@ -300,7 +306,9 @@ namespace AZ mtlVertexArgBuffers[slotIndex] = argBuffer; mtlVertexArgBufferOffsets[slotIndex] = argBufferOffset; bufferVertexRegisterIdMin = AZStd::min(slotIndex, bufferVertexRegisterIdMin); - bufferVertexRegisterIdMax = AZStd::max(slotIndex, bufferVertexRegisterIdMax); + bufferVertexRegisterIdMax = AZStd::max(slotIndex, bufferVertexRegisterIdMax); + mtlRenderStagesForNullDescHeap = shaderResourceGroup->IsNullHeapNeededForVertexStage(srgResourcesVisInfo) ? + mtlRenderStagesForNullDescHeap | MTLRenderStageVertex : mtlRenderStagesForNullDescHeap; } if( numBitsSet > 1 || srgVisInfo == RHI::ShaderStageMask::Fragment) @@ -309,6 +317,7 @@ namespace AZ mtlFragmentOrComputeArgBufferOffsets[slotIndex] = argBufferOffset; bufferFragmentOrComputeRegisterIdMin = AZStd::min(slotIndex, bufferFragmentOrComputeRegisterIdMin); bufferFragmentOrComputeRegisterIdMax = AZStd::max(slotIndex, bufferFragmentOrComputeRegisterIdMax); + mtlRenderStagesForNullDescHeap = isNullDescHeapNeeded ? mtlRenderStagesForNullDescHeap | MTLRenderStageFragment : mtlRenderStagesForNullDescHeap; } } else if(m_commandEncoderType == CommandEncoderType::Compute) @@ -329,7 +338,7 @@ namespace AZ bindings.m_srgVisHashByIndex[slot] = srgResourcesVisHash; if(srgVisInfo != RHI::ShaderStageMask::None) { - const ShaderResourceGroupVisibility& srgResourcesVisInfo = pipelineLayout.GetSrgResourcesVisibility(srgVisIndex); + //For graphics and compute encoder make the resource resident (call UseResource) for the duration //of the work associated with the current scope and ensure that it's in a @@ -396,6 +405,10 @@ namespace AZ stages: key.first.second]; } + if(bindNullDescriptorHeap) + { + MakeHeapsResident(mtlRenderStagesForNullDescHeap); + } return true; } diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandListBase.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandListBase.cpp index b3dd209926..e386c25515 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandListBase.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandListBase.cpp @@ -64,6 +64,7 @@ namespace AZ { [m_encoder endEncoding]; m_encoder = nil; + m_isNullDescHeapBound = false; #if AZ_TRAIT_ATOM_METAL_COUNTER_SAMPLING if (m_supportsInterDrawTimestamps) { @@ -73,18 +74,25 @@ namespace AZ } } - void CommandListBase::MakeHeapsResident() + void CommandListBase::MakeHeapsResident(MTLRenderStages renderStages) { + if(m_isNullDescHeapBound) + { + return; + } + switch(m_commandEncoderType) { case CommandEncoderType::Render: { - id renderEncoder = GetEncoder>(); - for (id residentHeap : *m_residentHeaps) + if(renderStages != 0) { - //MTLRenderStageVertex is not added to this as it was causing an immediate gpu crash on ios (first buffer commit) - [renderEncoder useHeap : residentHeap - stages : MTLRenderStageFragment]; + id renderEncoder = GetEncoder>(); + for (id residentHeap : *m_residentHeaps) + { + [renderEncoder useHeap : residentHeap + stages : renderStages]; + } } break; } @@ -102,6 +110,7 @@ namespace AZ AZ_Assert(false, "Encoder Type not supported"); } } + m_isNullDescHeapBound = true; } void CommandListBase::CreateEncoder(CommandEncoderType encoderType) @@ -119,16 +128,12 @@ namespace AZ m_commandEncoderType = CommandEncoderType::Render; m_encoder = [m_mtlCommandBuffer renderCommandEncoderWithDescriptor : m_renderPassDescriptor]; m_renderPassDescriptor = nil; - MakeHeapsResident(); - break; } case CommandEncoderType::Compute: { m_commandEncoderType = CommandEncoderType::Compute; m_encoder = [m_mtlCommandBuffer computeCommandEncoder]; - MakeHeapsResident(); - break; } case CommandEncoderType::Blit: diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandListBase.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandListBase.h index b2c548c9c5..2f8905d61c 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandListBase.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandListBase.h @@ -89,12 +89,14 @@ namespace AZ /// Cache multisample state. Used mainly to validate the MSAA image descriptor against the one passed into the pipelinestate RHI::MultisampleState m_renderPassMultiSampleState; + //! Go through all the heaps and call UseHeap on them to make them resident for the upcoming pass. + void MakeHeapsResident(MTLRenderStages renderStages); private: - //! Go through all the heaps and call UseHeap on them to make them resident for the upcoming pass. - void MakeHeapsResident(); + bool m_isEncoded = false; + bool m_isNullDescHeapBound = false; RHI::HardwareQueueClass m_hardwareQueueClass = RHI::HardwareQueueClass::Graphics; NSString* m_encoderScopeName = nullptr; id m_mtlCommandBuffer = nil; diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueue.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueue.cpp index 5db3cfb0d3..4bde063d63 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueue.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueue.cpp @@ -114,7 +114,7 @@ namespace AZ //Autoreleasepool is to ensure that the driver is not leaking memory related to the command buffer and encoder @autoreleasepool { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "ExecuteWork"); + AZ_PROFILE_SCOPE(AzRender, "ExecuteWork"); AZ_PROFILE_RHI_VARIABLE(m_lastExecuteDuration); if (request.m_signalFenceValue > 0) diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueueContext.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueueContext.cpp index 814610b4d5..f0ec98be89 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueueContext.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/CommandQueueContext.cpp @@ -79,7 +79,7 @@ namespace AZ void CommandQueueContext::End() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); QueueGpuSignals(m_frameFences[m_currentFrameIndex]); for (uint32_t hardwareQueueIdx = 0; hardwareQueueIdx < RHI::HardwareQueueClassCount; ++hardwareQueueIdx) @@ -91,7 +91,7 @@ namespace AZ m_currentFrameIndex = (m_currentFrameIndex + 1) % aznumeric_cast(m_frameFences.size()); { - AZ_PROFILE_SCOPE_IDLE(AZ::Debug::ProfileCategory::AzRender, "Wait and Reset Fence"); + AZ_PROFILE_SCOPE(AzRender, "Wait and Reset Fence"); AZ_ATOM_PROFILE_TIME_GROUP_REGION("RHI", "CommandQueueContext: Wait on Fences"); //Synchronize the CPU with the GPU by waiting on the fence until signalled by the GPU. CPU can only go upto diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp index 5591bcc843..782ea7174b 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.cpp @@ -5,7 +5,9 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ +#include #include +#include #include #include #include @@ -27,6 +29,13 @@ namespace AZ { namespace Metal { + Device::Device() + { + RHI::Ptr platformLimitsDescriptor = aznew PlatformLimitsDescriptor(); + platformLimitsDescriptor->LoadPlatformLimitsDescriptor(RHI::Factory::Get().GetName().GetCStr()); + m_descriptor.m_platformLimitsDescriptor = RHI::Ptr(platformLimitsDescriptor); + } + RHI::Ptr Device::Create() { return aznew Device(); @@ -42,24 +51,24 @@ namespace AZ return RHI::ResultCode::Success; } - RHI::ResultCode Device::PostInitInternal(const RHI::DeviceDescriptor& descriptor) + RHI::ResultCode Device::InitializeLimits() { { ReleaseQueue::Descriptor releaseQueueDescriptor; - releaseQueueDescriptor.m_collectLatency = descriptor.m_frameCountMax; + releaseQueueDescriptor.m_collectLatency = m_descriptor.m_frameCountMax; m_releaseQueue.Init(releaseQueueDescriptor); } { CommandListAllocator::Descriptor commandListAllocatorDescriptor; - commandListAllocatorDescriptor.m_frameCountMax = descriptor.m_frameCountMax; + commandListAllocatorDescriptor.m_frameCountMax = m_descriptor.m_frameCountMax; m_commandListAllocator.Init(commandListAllocatorDescriptor, this); } m_pipelineLayoutCache.Init(*this); m_commandQueueContext.Init(*this); - m_asyncUploadQueue.Init(*this, AsyncUploadQueue::Descriptor(RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_asyncQueueStagingBufferSizeInBytes)); + m_asyncUploadQueue.Init(*this, AsyncUploadQueue::Descriptor(m_descriptor.m_platformLimitsDescriptor->m_platformDefaultValues.m_asyncQueueStagingBufferSizeInBytes)); BufferMemoryAllocator::Descriptor allocatorDescriptor; allocatorDescriptor.m_device = this; @@ -77,6 +86,7 @@ namespace AZ m_samplerCache = [[NSCache alloc]init]; [m_samplerCache setName:@"SamplerCache"]; + return RHI::ResultCode::Success; } diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h index 9cdeee7eae..90dd4ff4a0 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/Device.h @@ -154,12 +154,11 @@ namespace AZ void ObjectCollectionNotify(RHI::ObjectCollectorNotifyFunction notifyFunction) override; private: - Device() = default; + Device(); ////////////////////////////////////////////////////////////////////////// // RHI::Device RHI::ResultCode InitInternal(RHI::PhysicalDevice& physicalDevice) override; - RHI::ResultCode PostInitInternal(const RHI::DeviceDescriptor& params) override; void ShutdownInternal() override; void CompileMemoryStatisticsInternal(RHI::MemoryStatisticsBuilder& builder) override; void UpdateCpuTimingStatisticsInternal(RHI::CpuTimingStatistics& cpuTimingStatistics) const override; @@ -168,6 +167,7 @@ namespace AZ void WaitForIdleInternal() override; AZStd::chrono::microseconds GpuTimestampToMicroseconds(uint64_t gpuTimestamp, RHI::HardwareQueueClass queueClass) const override; void FillFormatsCapabilitiesInternal(FormatCapabilitiesList& formatsCapabilities) override; + RHI::ResultCode InitializeLimits() override; void PreShutdown() override; AZStd::vector GetValidSwapChainImageFormats(const RHI::WindowHandle& windowHandle) const override; ////////////////////////////////////////////////////////////////////////// diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/NullDescriptorManager.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/NullDescriptorManager.cpp index 5288ec8e5a..e86ba3c2c3 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/NullDescriptorManager.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/NullDescriptorManager.cpp @@ -126,10 +126,10 @@ namespace AZ Device& device = static_cast(GetDevice()); m_nullBuffer.m_name = "NULL_DESCRIPTOR_BUFFER"; - m_nullBuffer.m_bufferDescriptor.m_byteCount = 64; + m_nullBuffer.m_bufferDescriptor.m_byteCount = 1024; m_nullBuffer.m_bufferDescriptor.m_bindFlags = RHI::BufferBindFlags::ShaderWrite; m_nullBuffer.m_memoryView = device.CreateBufferCommitted(m_nullBuffer.m_bufferDescriptor); - + m_nullBuffer.m_memoryView.SetName( m_nullBuffer.m_name.c_str()); if(!m_nullBuffer.m_memoryView.IsValid()) { AZ_Assert(false, "Couldnt create a null buffer for ArgumentTable"); diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/ShaderResourceGroup.cpp b/Gems/Atom/RHI/Metal/Code/Source/RHI/ShaderResourceGroup.cpp index 9c4e13f713..1cba62b988 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/ShaderResourceGroup.cpp +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/ShaderResourceGroup.cpp @@ -36,5 +36,10 @@ namespace AZ { GetCompiledArgumentBuffer().CollectUntrackedResources(commandEncoder, srgResourcesVisInfo, resourcesToMakeResidentCompute, resourcesToMakeResidentGraphics); } + + bool ShaderResourceGroup::IsNullHeapNeededForVertexStage(const ShaderResourceGroupVisibility& srgResourcesVisInfo) const + { + return GetCompiledArgumentBuffer().IsNullHeapNeededForVertexStage(srgResourcesVisInfo); + } } } diff --git a/Gems/Atom/RHI/Metal/Code/Source/RHI/ShaderResourceGroup.h b/Gems/Atom/RHI/Metal/Code/Source/RHI/ShaderResourceGroup.h index 52ffabe106..cb69c0975e 100644 --- a/Gems/Atom/RHI/Metal/Code/Source/RHI/ShaderResourceGroup.h +++ b/Gems/Atom/RHI/Metal/Code/Source/RHI/ShaderResourceGroup.h @@ -47,7 +47,8 @@ namespace AZ const ShaderResourceGroupVisibility& srgResourcesVisInfo, ArgumentBuffer::ComputeResourcesToMakeResidentMap& resourcesToMakeResidentCompute, ArgumentBuffer::GraphicsResourcesToMakeResidentMap& resourcesToMakeResidentGraphics) const; - + bool IsNullHeapNeededForVertexStage(const ShaderResourceGroupVisibility& srgResourcesVisInfo) const; + private: ShaderResourceGroup() = default; diff --git a/Gems/Atom/RHI/Null/Code/Source/RHI/BufferPool.h b/Gems/Atom/RHI/Null/Code/Source/RHI/BufferPool.h index 8d1936fc56..5b69c765f2 100644 --- a/Gems/Atom/RHI/Null/Code/Source/RHI/BufferPool.h +++ b/Gems/Atom/RHI/Null/Code/Source/RHI/BufferPool.h @@ -39,9 +39,10 @@ namespace AZ RHI::ResultCode InitBufferInternal([[maybe_unused]] RHI::Buffer& buffer, [[maybe_unused]] const RHI::BufferDescriptor& rhiDescriptor) override{ return RHI::ResultCode::Success;} void ShutdownResourceInternal([[maybe_unused]] RHI::Resource& resource) override {} RHI::ResultCode OrphanBufferInternal([[maybe_unused]] RHI::Buffer& buffer) override { return RHI::ResultCode::Success;} - RHI::ResultCode MapBufferInternal([[maybe_unused]] const RHI::BufferMapRequest& mapRequest, [[maybe_unused]] RHI::BufferMapResponse& response) override { return RHI::ResultCode::Unimplemented;} + RHI::ResultCode MapBufferInternal([[maybe_unused]] const RHI::BufferMapRequest& mapRequest, [[maybe_unused]] RHI::BufferMapResponse& response) override { return RHI::ResultCode::Success;} void UnmapBufferInternal([[maybe_unused]] RHI::Buffer& buffer) override {} RHI::ResultCode StreamBufferInternal([[maybe_unused]] const RHI::BufferStreamRequest& request) override { return RHI::ResultCode::Success;} + void BufferCopy([[maybe_unused]] void* destination, [[maybe_unused]] const void* source, [[maybe_unused]] size_t num) override {} ////////////////////////////////////////////////////////////////////////// }; diff --git a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp index 08a2c4f411..b056071327 100644 --- a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.cpp @@ -16,6 +16,11 @@ namespace AZ return aznew Device(); } + Device::Device() + { + m_descriptor.m_platformLimitsDescriptor = aznew RHI::PlatformLimitsDescriptor; + } + void Device::FillFormatsCapabilitiesInternal(FormatCapabilitiesList& formatsCapabilities) { formatsCapabilities.fill(static_cast(~0)); diff --git a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h index cd44135e62..27873887d4 100644 --- a/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Null/Code/Source/RHI/Device.h @@ -25,12 +25,11 @@ namespace AZ static RHI::Ptr Create(); private: - Device() = default; + Device(); ////////////////////////////////////////////////////////////////////////// // RHI::Device - RHI::ResultCode InitInternal([[maybe_unused]] RHI::PhysicalDevice& physicalDevice) override { return RHI::ResultCode::Success;} - RHI::ResultCode PostInitInternal([[maybe_unused]] const RHI::DeviceDescriptor& params) override { return RHI::ResultCode::Success;} + RHI::ResultCode InitInternal([[maybe_unused]] RHI::PhysicalDevice& physicalDevice) override { return RHI::ResultCode::Success; } void ShutdownInternal() override {} void CompileMemoryStatisticsInternal([[maybe_unused]] RHI::MemoryStatisticsBuilder& builder) override {} void UpdateCpuTimingStatisticsInternal([[maybe_unused]] RHI::CpuTimingStatistics& cpuTimingStatistics) const override {} @@ -39,6 +38,7 @@ namespace AZ void WaitForIdleInternal() override {} AZStd::chrono::microseconds GpuTimestampToMicroseconds([[maybe_unused]] uint64_t gpuTimestamp, [[maybe_unused]] RHI::HardwareQueueClass queueClass) const override { return AZStd::chrono::microseconds();} void FillFormatsCapabilitiesInternal([[maybe_unused]] FormatCapabilitiesList& formatsCapabilities) override; + RHI::ResultCode InitializeLimits() override { return RHI::ResultCode::Success; } 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();} diff --git a/Gems/Atom/RHI/Registry/Platform/Android/PlatformLimits.setreg b/Gems/Atom/RHI/Registry/Platform/Android/PlatformLimits.setreg new file mode 100644 index 0000000000..6ce3c88bbb --- /dev/null +++ b/Gems/Atom/RHI/Registry/Platform/Android/PlatformLimits.setreg @@ -0,0 +1,27 @@ +// +// Copyright (c) Contributors to the Open 3D Engine Project. +// For complete copyright and license terms please see the LICENSE at the root of this distribution. +// +// SPDX-License-Identifier: Apache-2.0 OR MIT +// +// +// + +{ + "Amazon": + { + "Atom": + { + "RHI": + { + "PlatformLimits": + { + "metal": + { + "$type": "AZ::Vulkan::PlatformLimitsDescriptor" + } + } + } + } + } +} diff --git a/Gems/Atom/RHI/Registry/Platform/Linux/PlatformLimits.setreg b/Gems/Atom/RHI/Registry/Platform/Linux/PlatformLimits.setreg new file mode 100644 index 0000000000..7c60aeb098 --- /dev/null +++ b/Gems/Atom/RHI/Registry/Platform/Linux/PlatformLimits.setreg @@ -0,0 +1,27 @@ +// +// Copyright (c) Contributors to the Open 3D Engine Project. +// For complete copyright and license terms please see the LICENSE at the root of this distribution. +// +// SPDX-License-Identifier: Apache-2.0 OR MIT +// +// +// + +{ + "Amazon": + { + "Atom": + { + "RHI": + { + "PlatformLimits": + { + "vulkan": + { + "$type": "AZ::Vulkan::PlatformLimitsDescriptor" + } + } + } + } + } +} diff --git a/Gems/Atom/RHI/Registry/Platform/Mac/PlatformLimits.setreg b/Gems/Atom/RHI/Registry/Platform/Mac/PlatformLimits.setreg new file mode 100644 index 0000000000..508287b762 --- /dev/null +++ b/Gems/Atom/RHI/Registry/Platform/Mac/PlatformLimits.setreg @@ -0,0 +1,27 @@ +// +// Copyright (c) Contributors to the Open 3D Engine Project. +// For complete copyright and license terms please see the LICENSE at the root of this distribution. +// +// SPDX-License-Identifier: Apache-2.0 OR MIT +// +// +// + +{ + "Amazon": + { + "Atom": + { + "RHI": + { + "PlatformLimits": + { + "metal": + { + "$type": "AZ::Metal::PlatformLimitsDescriptor" + } + } + } + } + } +} diff --git a/Gems/Atom/RHI/Registry/Platform/Windows/PlatformLimits.setreg b/Gems/Atom/RHI/Registry/Platform/Windows/PlatformLimits.setreg new file mode 100644 index 0000000000..dd1273953b --- /dev/null +++ b/Gems/Atom/RHI/Registry/Platform/Windows/PlatformLimits.setreg @@ -0,0 +1,38 @@ +// +// 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 +// +// +// + +{ + "Amazon": + { + "Atom": + { + "RHI": + { + "PlatformLimits": + { + "dx12": + { + "$type": "AZ::DX12::PlatformLimitsDescriptor", + "DescriptorHeapLimits": + { + "DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV": [1000000, 1000000], + "DESCRIPTOR_HEAP_TYPE_SAMPLER": [2048, 2048], + "DESCRIPTOR_HEAP_TYPE_RTV": [2048, 0], + "DESCRIPTOR_HEAP_TYPE_DSV": [2048, 0] + } + }, + "vulkan": + { + "$type": "AZ::Vulkan::PlatformLimitsDescriptor" + } + } + } + } + } +} diff --git a/Gems/Atom/RHI/Registry/Platform/iOS/PlatformLimits.setreg b/Gems/Atom/RHI/Registry/Platform/iOS/PlatformLimits.setreg new file mode 100644 index 0000000000..508287b762 --- /dev/null +++ b/Gems/Atom/RHI/Registry/Platform/iOS/PlatformLimits.setreg @@ -0,0 +1,27 @@ +// +// Copyright (c) Contributors to the Open 3D Engine Project. +// For complete copyright and license terms please see the LICENSE at the root of this distribution. +// +// SPDX-License-Identifier: Apache-2.0 OR MIT +// +// +// + +{ + "Amazon": + { + "Atom": + { + "RHI": + { + "PlatformLimits": + { + "metal": + { + "$type": "AZ::Metal::PlatformLimitsDescriptor" + } + } + } + } + } +} diff --git a/Gems/Atom/RHI/Vulkan/Code/Include/Atom/RHI.Reflect/Vulkan/PlatformLimitsDescriptor.h b/Gems/Atom/RHI/Vulkan/Code/Include/Atom/RHI.Reflect/Vulkan/PlatformLimitsDescriptor.h index d23a51f781..5e41da9627 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Include/Atom/RHI.Reflect/Vulkan/PlatformLimitsDescriptor.h +++ b/Gems/Atom/RHI/Vulkan/Code/Include/Atom/RHI.Reflect/Vulkan/PlatformLimitsDescriptor.h @@ -20,7 +20,7 @@ namespace AZ { struct FrameGraphExecuterData { - AZ_TYPE_INFO(FrameGraphExecuterData, "{648B4414-7208-4BFD-8E8F-CF2CA923ABCF}"); + AZ_TYPE_INFO(AZ::Vulkan::FrameGraphExecuterData, "{648B4414-7208-4BFD-8E8F-CF2CA923ABCF}"); static void Reflect(AZ::ReflectContext* context); //Cost per draw/dispatch item @@ -45,8 +45,8 @@ namespace AZ { using Base = RHI::PlatformLimitsDescriptor; public: - AZ_RTTI(Vulkan::PlatformLimitsDescriptor, "{23673F3F-1562-4D1B-B130-553B35B48C64}", Base); - AZ_CLASS_ALLOCATOR(PlatformLimitsDescriptor, AZ::SystemAllocator, 0); + AZ_RTTI(AZ::Vulkan::PlatformLimitsDescriptor, "{23673F3F-1562-4D1B-B130-553B35B48C64}", Base); + AZ_CLASS_ALLOCATOR(AZ::Vulkan::PlatformLimitsDescriptor, AZ::SystemAllocator, 0); static void Reflect(AZ::ReflectContext* context); FrameGraphExecuterData m_frameGraphExecuterData; diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp index d5692cb4d4..8af53c431b 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI.Reflect/PlatformLimitsDescriptor.cpp @@ -18,8 +18,8 @@ namespace AZ if (SerializeContext* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(0) - ->Field("m_frameGraphExecuterData", &PlatformLimitsDescriptor::m_frameGraphExecuterData) + ->Version(1) + ->Field("FrameGraphExecuterData", &PlatformLimitsDescriptor::m_frameGraphExecuterData) ; } } @@ -30,11 +30,11 @@ namespace AZ { serializeContext->Class() ->Version(0) - ->Field("m_itemCost", &FrameGraphExecuterData::m_itemCost) - ->Field("m_attachmentCost", &FrameGraphExecuterData::m_attachmentCost) - ->Field("m_swapChainsPerCommandList", &FrameGraphExecuterData::m_swapChainsPerCommandList) - ->Field("m_commandListCostThresholdMin", &FrameGraphExecuterData::m_commandListCostThresholdMin) - ->Field("m_commandListsPerScopeMax", &FrameGraphExecuterData::m_commandListsPerScopeMax) + ->Field("ItemCost", &FrameGraphExecuterData::m_itemCost) + ->Field("AttachmentCost", &FrameGraphExecuterData::m_attachmentCost) + ->Field("SwapChainsPerCommandList", &FrameGraphExecuterData::m_swapChainsPerCommandList) + ->Field("CommandListCostThresholdMin", &FrameGraphExecuterData::m_commandListCostThresholdMin) + ->Field("CommandListsPerScopeMax", &FrameGraphExecuterData::m_commandListsPerScopeMax) ; } } diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp index 18b5d83ed3..8f44abccef 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/AsyncUploadQueue.cpp @@ -96,7 +96,7 @@ namespace AZ uploadFence->Init(device, RHI::FenceState::Reset); CommandQueue::Command command = [=, &device](void* queue) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Upload Buffer"); + AZ_PROFILE_SCOPE(AzRender, "Upload Buffer"); size_t pendingByteOffset = 0; size_t pendingByteCount = byteCount; FramePacket* framePacket = nullptr; @@ -110,7 +110,7 @@ namespace AZ while (pendingByteCount > 0) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Upload Buffer Chunk"); + AZ_PROFILE_SCOPE(AzRender, "Upload Buffer Chunk"); framePacket = BeginFramePacket(vulkanQueue); const size_t bytesToCopy = AZStd::min(pendingByteCount, m_descriptor.m_stagingSizeInBytes); @@ -173,7 +173,7 @@ namespace AZ auto* image = static_cast(request.m_image); auto& device = static_cast(GetDevice()); - const uint16_t startMip = residentMip - 1; + const uint16_t startMip = static_cast(residentMip - 1); const uint16_t endMip = static_cast(residentMip - request.m_mipSlices.size()); RHI::Ptr uploadFence = Fence::Create(); @@ -181,7 +181,7 @@ namespace AZ CommandQueue::Command command = [=, &device](void* queue) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Upload Image"); + AZ_PROFILE_SCOPE(AzRender, "Upload Image"); Queue* vulkanQueue = static_cast(queue); FramePacket* framePacket = BeginFramePacket(vulkanQueue); @@ -257,7 +257,7 @@ namespace AZ // Copy subresource data to staging memory. { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Copy CPU image"); + AZ_PROFILE_SCOPE(AzRender, "Copy CPU image"); uint8_t* stagingDataStart = reinterpret_cast(framePacket->m_stagingBuffer->GetBufferMemoryView()->Map(RHI::HostMemoryAccess::Write)) + framePacket->m_dataOffset; for (uint32_t row = 0; row < subresourceLayout.m_rowCount; ++row) { @@ -277,7 +277,7 @@ namespace AZ copyDescriptor.m_sourceSize.m_depth = 1; copyDescriptor.m_destinationImage = image; copyDescriptor.m_destinationSubresource.m_mipSlice = curMip; - copyDescriptor.m_destinationSubresource.m_arraySlice = arraySlice; + copyDescriptor.m_destinationSubresource.m_arraySlice = static_cast(arraySlice); copyDescriptor.m_destinationOrigin.m_left = 0; copyDescriptor.m_destinationOrigin.m_top = 0; copyDescriptor.m_destinationOrigin.m_front = depth; @@ -309,7 +309,7 @@ namespace AZ copyDescriptor.m_sourceSize.m_depth = 1; copyDescriptor.m_destinationImage = image; copyDescriptor.m_destinationSubresource.m_mipSlice = curMip; - copyDescriptor.m_destinationSubresource.m_arraySlice = arraySlice; + copyDescriptor.m_destinationSubresource.m_arraySlice = static_cast(arraySlice); copyDescriptor.m_destinationOrigin.m_left = 0; copyDescriptor.m_destinationOrigin.m_top = 0; copyDescriptor.m_destinationOrigin.m_front = depth; @@ -332,7 +332,7 @@ namespace AZ // Copy subresource data to staging memory. { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "Copy CPU image"); + AZ_PROFILE_SCOPE(AzRender, "Copy CPU image"); uint8_t* stagingDataStart = reinterpret_cast(framePacket->m_stagingBuffer->GetBufferMemoryView()->Map(RHI::HostMemoryAccess::Write)); stagingDataStart += framePacket->m_dataOffset; @@ -458,7 +458,7 @@ namespace AZ AsyncUploadQueue::FramePacket* AsyncUploadQueue::BeginFramePacket(Queue* queue) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_Assert(!m_recordingFrame, "The previous frame packet isn't ended."); auto& device = static_cast(GetDevice()); @@ -478,7 +478,7 @@ namespace AZ void AsyncUploadQueue::EndFramePacket(Queue* queue, Semaphore* semaphoreToSignal /*=nullptr*/) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_Assert(m_recordingFrame, "The frame packet wasn't started. You need to call StartFramePacket first."); m_commandList->EndCommandBuffer(); @@ -644,7 +644,7 @@ namespace AZ void AsyncUploadQueue::ProcessCallback(const RHI::AsyncWorkHandle& handle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZStd::unique_lock lock(m_callbackListMutex); auto findIter = m_callbackList.find(handle); if (findIter != m_callbackList.end()) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/BufferPool.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/BufferPool.cpp index 6371b12526..12d5f9bf79 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/BufferPool.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/BufferPool.cpp @@ -49,7 +49,7 @@ namespace AZ { auto& device = static_cast(deviceBase); - VkDeviceSize bufferPageSizeInBytes = RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_bufferPoolPageSizeInBytes; + VkDeviceSize bufferPageSizeInBytes = device.GetDescriptor().m_platformLimitsDescriptor->m_platformDefaultValues.m_bufferPoolPageSizeInBytes; VkMemoryPropertyFlags additionalMemoryPropertyFlags = 0; if (const auto* descriptor = azrtti_cast(&descriptorBase)) { diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueue.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueue.cpp index 84b4964235..6929b63ac4 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueue.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueue.cpp @@ -54,7 +54,7 @@ namespace AZ const ExecuteWorkRequest& request = static_cast(rhiRequest); QueueCommand([=](void* queue) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "ExecuteWork"); + AZ_PROFILE_SCOPE(AzRender, "ExecuteWork"); AZ_PROFILE_RHI_VARIABLE(m_lastExecuteDuration); Queue* vulkanQueue = static_cast(queue); diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueueContext.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueueContext.cpp index 8635e8edcf..f31132f039 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueueContext.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/CommandQueueContext.cpp @@ -42,7 +42,7 @@ namespace AZ void CommandQueueContext::End() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); for (auto& commandQueue : m_commandQueues) { @@ -54,7 +54,7 @@ namespace AZ m_currentFrameIndex = (m_currentFrameIndex + 1) % GetFrameCount(); { - AZ_PROFILE_SCOPE_IDLE(AZ::Debug::ProfileCategory::AzRender, "Wait on Fences"); + AZ_PROFILE_SCOPE(AzRender, "Wait on Fences"); AZ_ATOM_PROFILE_FUNCTION("RHI", "CommandQueueContext: Wait on Fences"); FencesPerQueue& nextFences = m_frameFences[m_currentFrameIndex]; @@ -79,7 +79,7 @@ namespace AZ void CommandQueueContext::WaitForIdle() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); for (auto& commandQueue : m_commandQueues) { commandQueue->WaitForIdle(); @@ -304,7 +304,7 @@ namespace AZ { uint32_t m_familyIndex = InvalidFamilyIndex; bool m_newQueue = false; - uint32_t m_remainingFlags = ~0; + uint32_t m_remainingFlags = std::numeric_limits::max(); bool operator>(const QueueSelection& other) const { diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Conversion.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Conversion.cpp index 18ddc0f4df..d5671cff05 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Conversion.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Conversion.cpp @@ -257,7 +257,7 @@ namespace AZ state.srcAlphaBlendFactor = ConvertBlendFactor(targetBlendState.m_blendAlphaSource); state.dstAlphaBlendFactor = ConvertBlendFactor(targetBlendState.m_blendAlphaDest); state.alphaBlendOp = ConvertBlendOp(targetBlendState.m_blendAlphaOp); - state.colorWriteMask = ConvertComponentFlags(targetBlendState.m_writeMask); + state.colorWriteMask = ConvertComponentFlags(static_cast(targetBlendState.m_writeMask)); } VkBlendFactor ConvertBlendFactor(const RHI::BlendFactor& blendFactor) diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp index 05ff8bb2a6..15a532f832 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp @@ -7,6 +7,8 @@ */ #include +#include +#include #include #include #include @@ -31,6 +33,13 @@ namespace AZ { namespace Vulkan { + Device::Device() + { + RHI::Ptr platformLimitsDescriptor = aznew PlatformLimitsDescriptor(); + platformLimitsDescriptor->LoadPlatformLimitsDescriptor(RHI::Factory::Get().GetName().GetCStr()); + m_descriptor.m_platformLimitsDescriptor = RHI::Ptr(platformLimitsDescriptor); + } + RHI::Ptr Device::Create() { return aznew Device(); @@ -69,7 +78,7 @@ namespace AZ BuildDeviceQueueInfo(physicalDevice); - m_supportedPipelineStageFlagsMask = ~0; + m_supportedPipelineStageFlagsMask = std::numeric_limits::max(); const auto& deviceFeatures = physicalDevice.GetPhysicalDeviceFeatures(); m_enabledDeviceFeatures.samplerAnisotropy = deviceFeatures.samplerAnisotropy; @@ -232,7 +241,7 @@ namespace AZ return RHI::ResultCode::Success; } - RHI::ResultCode Device::PostInitInternal( const RHI::DeviceDescriptor& descriptor) + RHI::ResultCode Device::InitializeLimits() { CommandQueueContext::Descriptor commandQueueContextDescriptor; commandQueueContextDescriptor.m_frameCountMax = RHI::Limits::Device::FrameCountMax; @@ -241,7 +250,7 @@ namespace AZ // Initialize member variables. ReleaseQueue::Descriptor releaseQueueDescriptor; - releaseQueueDescriptor.m_collectLatency = descriptor.m_frameCountMax - 1; + releaseQueueDescriptor.m_collectLatency = m_descriptor.m_frameCountMax - 1; m_releaseQueue.Init(releaseQueueDescriptor); @@ -272,7 +281,7 @@ namespace AZ poolDesc.m_heapMemoryLevel = RHI::HeapMemoryLevel::Host; poolDesc.m_hostMemoryAccess = RHI::HostMemoryAccess::Write; poolDesc.m_bindFlags = RHI::BufferBindFlags::CopyRead; - poolDesc.m_budgetInBytes = RHI::RHISystemInterface::Get()->GetPlatformLimitsDescriptor()->m_platformDefaultValues.m_stagingBufferBudgetInBytes; + poolDesc.m_budgetInBytes = m_descriptor.m_platformLimitsDescriptor->m_platformDefaultValues.m_stagingBufferBudgetInBytes; result = m_stagingBufferPool->Init(*this, poolDesc); RETURN_RESULT_IF_UNSUCCESSFUL(result); diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h index 28e56d1fa9..13ccf9367b 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.h @@ -110,7 +110,7 @@ namespace AZ void DestroyBufferResource(VkBuffer vkBuffer) const; private: - Device() = default; + Device(); ////////////////////////////////////////////////////////////////////////// // RHI::Object @@ -120,7 +120,6 @@ namespace AZ ////////////////////////////////////////////////////////////////////////// // RHI::Device RHI::ResultCode InitInternal(RHI::PhysicalDevice& physicalDevice) override; - RHI::ResultCode PostInitInternal(const RHI::DeviceDescriptor& params) override; void ShutdownInternal() override; void BeginFrameInternal() override; @@ -131,6 +130,7 @@ namespace AZ AZStd::vector GetValidSwapChainImageFormats(const RHI::WindowHandle& windowHandle) const override; AZStd::chrono::microseconds GpuTimestampToMicroseconds(uint64_t gpuTimestamp, RHI::HardwareQueueClass queueClass) const override; void FillFormatsCapabilitiesInternal(FormatCapabilitiesList& formatsCapabilities) override; + RHI::ResultCode InitializeLimits() override; void PreShutdown() override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::ImageDescriptor& descriptor) override; RHI::ResourceMemoryRequirements GetResourceMemoryRequirements(const RHI::BufferDescriptor& descriptor) override; @@ -152,7 +152,7 @@ namespace AZ VkDevice m_nativeDevice = VK_NULL_HANDLE; VkPhysicalDeviceFeatures m_enabledDeviceFeatures{}; - VkPipelineStageFlags m_supportedPipelineStageFlagsMask = ~0; + VkPipelineStageFlags m_supportedPipelineStageFlagsMask = std::numeric_limits::max(); AZStd::vector m_queueFamilyProperties; RHI::Ptr m_asyncUploadQueue; diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/ImageView.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/ImageView.cpp index d4697cbd32..44c36f5c70 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/ImageView.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/ImageView.cpp @@ -117,8 +117,8 @@ namespace AZ const auto& device = static_cast(GetDevice()); const auto& physicalDevice = static_cast(GetDevice().GetPhysicalDevice()); - const uint16_t width = imgDesc.m_size.m_width; - const uint16_t height = imgDesc.m_size.m_height; + const uint16_t width = static_cast(imgDesc.m_size.m_width); + const uint16_t height = static_cast(imgDesc.m_size.m_height); const uint16_t depth = AZStd::min(static_cast(imgViewDesc.m_depthSliceMax - imgViewDesc.m_depthSliceMin), static_cast(imgDesc.m_size.m_depth - 1)) + 1; const uint16_t samples = imgDesc.m_multisampleState.m_samples; const uint16_t arrayLayers = AZStd::min(static_cast(imgViewDesc.m_arraySliceMax - imgViewDesc.m_arraySliceMin), static_cast(imgDesc.m_arraySize - 1)) + 1; @@ -233,7 +233,7 @@ namespace AZ // https://www.khronos.org/registry/vulkan/specs/1.1/html/chap11.html#VkImageSubresourceRange { range.m_arraySliceMin = descriptor.m_depthSliceMin; - range.m_arraySliceMax = AZStd::GetMin(descriptor.m_depthSliceMax, imageDesc.m_size.m_depth - 1); + range.m_arraySliceMax = AZStd::GetMin(descriptor.m_depthSliceMax, static_cast(imageDesc.m_size.m_depth - 1)); break; } case VK_IMAGE_VIEW_TYPE_3D: diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/MergedShaderResourceGroup.h b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/MergedShaderResourceGroup.h index f285807210..649f9c3b80 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/MergedShaderResourceGroup.h +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/MergedShaderResourceGroup.h @@ -53,7 +53,7 @@ namespace AZ // Helper struct for easy initialization of the frame iteration. struct FrameIteration { - uint64_t m_frameIteration = ~0; + uint64_t m_frameIteration = std::numeric_limits::max(); }; // Utility function that merges multiple ShaderResoruceGroup data into one. diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/PipelineLayout.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/PipelineLayout.cpp index 5c7a78fd89..f627ddf2cc 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/PipelineLayout.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/PipelineLayout.cpp @@ -134,7 +134,7 @@ namespace AZ uint32_t bindingSlot = srgLayout->GetBindingSlot(); m_indexToSlot[bindingInfo.m_spaceId].set(bindingSlot); - m_slotToIndex[bindingSlot] = bindingInfo.m_spaceId; + m_slotToIndex[bindingSlot] = static_cast(bindingInfo.m_spaceId); } m_descriptorSetLayouts.reserve(srgCount); diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/StreamingImagePool.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/StreamingImagePool.cpp index 9189c2e177..586470da0a 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/StreamingImagePool.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/StreamingImagePool.cpp @@ -108,7 +108,7 @@ namespace AZ WaitFinishUploading(image); - const uint16_t residentMipLevelBefore = image.GetResidentMipLevel(); + const uint16_t residentMipLevelBefore = static_cast(image.GetResidentMipLevel()); const uint16_t residentMipLevelAfter = residentMipLevelBefore - static_cast(request.m_mipSlices.size()); const VkMemoryRequirements memoryRequirements = GetMemoryRequirements(image.GetDescriptor(), residentMipLevelAfter); @@ -149,11 +149,11 @@ namespace AZ // Set streamed mip level to target mip level. if (image.GetStreamedMipLevel() < targetMipLevel) { - image.SetStreamedMipLevel(targetMipLevel); + image.SetStreamedMipLevel(static_cast(targetMipLevel)); } const VkMemoryRequirements memoryRequirements = GetMemoryRequirements(image.GetDescriptor(), targetMipLevel); - const uint16_t residentMipLevelBefore = image.GetResidentMipLevel(); + const uint16_t residentMipLevelBefore = static_cast(image.GetResidentMipLevel()); RHI::HeapMemoryUsage& memoryUsage = m_memoryUsage.GetHeapMemoryUsage(RHI::HeapMemoryLevel::Device); const size_t imageSizeBefore = image.GetResidentSizeInBytes(); @@ -203,7 +203,7 @@ namespace AZ residentImageDescriptor.m_size = imageDescriptor.m_size.GetReducedMip(residentMipLevel); residentImageDescriptor.m_size.m_width = RHI::AlignUp(residentImageDescriptor.m_size.m_width, alignment); residentImageDescriptor.m_size.m_height = RHI::AlignUp(residentImageDescriptor.m_size.m_height, alignment); - residentImageDescriptor.m_mipLevels = imageDescriptor.m_mipLevels - residentMipLevel; + residentImageDescriptor.m_mipLevels = imageDescriptor.m_mipLevels - static_cast(residentMipLevel); return device.GetImageMemoryRequirements(imageDescriptor); } diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialConverterBus.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialConverterBus.h index 120c1ee28b..8052fc4feb 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialConverterBus.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialConverterBus.h @@ -29,10 +29,19 @@ namespace AZ : public AZ::EBusTraits { public: - //! Returns true if the converion was successful + + virtual bool IsEnabled() const = 0; + + //! Converts data from a IMaterialData object to an Atom MaterialSourceData. + //! Only works when IsEnabled() is true. + //! @return true if the MaterialSourceData output was populated with converted material data. virtual bool ConvertMaterial(const AZ::SceneAPI::DataTypes::IMaterialData& materialData, MaterialSourceData& out) = 0; - //! Returns the path to the .materialtype file that the materials are based on, such as StandardPBR.materialtype, etc. - virtual const char* GetMaterialTypePath() const = 0; + + //! Returns the path to the .materialtype file that the converted materials are based on, such as StandardPBR.materialtype, etc. + virtual AZStd::string GetMaterialTypePath() const = 0; + + //! Returns the path to a .material file to use as the default material when conversion is disabled. + virtual AZStd::string GetDefaultMaterialPath() const = 0; }; using MaterialConverterBus = AZ::EBus; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h index 7e341d43c3..36994ec03b 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/ParentPass.h @@ -64,6 +64,9 @@ namespace AZ //! Find a child pass with a matching name and returns it. Return nullptr if none found. Ptr FindChildPass(const Name& passName) const; + + template + Ptr FindChildPass() const; //! Searches the tree for the first pass that has same pass name (Depth-first search). Return nullptr if none found. Ptr FindPassByNameRecursive(const Name& passName) const; @@ -132,5 +135,20 @@ namespace AZ // Generates child passes from source PassTemplate void CreatePassesFromTemplate(); }; + + template + inline Ptr ParentPass::FindChildPass() const + { + for (const Ptr& child : m_children) + { + PassType* pass = azrtti_cast(child.get()); + if (pass) + { + return pass; + } + } + return {}; + } + } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialPropertyDescriptor.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialPropertyDescriptor.h index d3c4da27ad..085256f6d8 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialPropertyDescriptor.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialPropertyDescriptor.h @@ -103,7 +103,7 @@ namespace AZ AZ::TypeId GetStorageDataTypeId() const; //! Returns the value of the enum from its name. If this property is not an enum or the name is undefined, InvalidEnumValue is returned. - static constexpr uint32_t InvalidEnumValue = -1; + static constexpr uint32_t InvalidEnumValue = std::numeric_limits::max(); uint32_t GetEnumValue(const AZ::Name& enumName) const; //! Returns the unique name ID of this property diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelMaterialSlot.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelMaterialSlot.h index dd46aca6cd..30088d2d52 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelMaterialSlot.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelMaterialSlot.h @@ -25,6 +25,8 @@ namespace AZ static void Reflect(AZ::ReflectContext* context); + // Note that StableId is uint32_t for legacy reasons: we used to use AssetId::m_subId as the material slot ID. But actually the original MaterialUid + // is 64 bit so we might want to switch this to be uint64_t at some point. using StableId = uint32_t; static const StableId InvalidStableId; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Shader/ShaderVariantTreeAsset.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Shader/ShaderVariantTreeAsset.h index e2e5b5c140..e010024fa3 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Shader/ShaderVariantTreeAsset.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Shader/ShaderVariantTreeAsset.h @@ -75,7 +75,7 @@ namespace AZ private: - static constexpr uint32_t UnspecifiedIndex = -1; + static constexpr uint32_t UnspecifiedIndex = std::numeric_limits::max(); //! Returns the node associated with the provided index. const ShaderVariantTreeNode& GetNode(uint32_t index) const; diff --git a/Gems/Atom/RPI/Code/Source/Platform/Common/VisualStudio/Natvis/shaderoptiongroup.natvis b/Gems/Atom/RPI/Code/Source/Platform/Common/VisualStudio/Natvis/shaderoptiongroup.natvis new file mode 100644 index 0000000000..64ad28af72 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/Platform/Common/VisualStudio/Natvis/shaderoptiongroup.natvis @@ -0,0 +1,23 @@ + + + + + + shader option group + + m_id.m_key + + + + iOption++ + + + + + ((m_id.m_key.m_bits[(int) (m_layout.px->m_options[iOption].m_bitOffset / m_id.m_key.BitsPerWord)] >> (m_layout.px->m_options[iOption].m_bitOffset - ((int) (m_layout.px->m_options[iOption].m_bitOffset / 32) * 32))) & ((1u << (m_layout.px->m_options[iOption].m_bitCount)) - 1u)) + (m_layout.px->m_options[iOption].m_minValue.m_index) + + + + + + diff --git a/Gems/Atom/RPI/Code/Source/Platform/Windows/platform_windows_files.cmake b/Gems/Atom/RPI/Code/Source/Platform/Windows/platform_windows_files.cmake index 057fecfc90..c805aa9577 100644 --- a/Gems/Atom/RPI/Code/Source/Platform/Windows/platform_windows_files.cmake +++ b/Gems/Atom/RPI/Code/Source/Platform/Windows/platform_windows_files.cmake @@ -9,4 +9,5 @@ set(FILES Atom_RPI_Traits_Platform.h Atom_RPI_Traits_Windows.h + ../Common/VisualStudio/Natvis/shaderoptiongroup.natvis ) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.cpp index 7187cb391a..4a4c2156ce 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.cpp @@ -28,6 +28,7 @@ #include #include +#include #include #include @@ -70,28 +71,74 @@ namespace AZ void MaterialAssetDependenciesComponent::ReportJobDependencies(SceneAPI::JobDependencyList& jobDependencyList, const char* platformIdentifier) { - AssetBuilderSDK::SourceFileDependency materialTypeSource; + bool conversionEnabled = false; + RPI::MaterialConverterBus::BroadcastResult(conversionEnabled, &RPI::MaterialConverterBus::Events::IsEnabled); + // Right now, scene file importing only supports a single material type, once that changes, this will have to be re-designed, see ATOM-3554 - RPI::MaterialConverterBus::BroadcastResult(materialTypeSource.m_sourceFileDependencyPath, &RPI::MaterialConverterBus::Events::GetMaterialTypePath); + AZStd::string materialTypePath; + RPI::MaterialConverterBus::BroadcastResult(materialTypePath, &RPI::MaterialConverterBus::Events::GetMaterialTypePath); - AssetBuilderSDK::JobDependency jobDependency; - jobDependency.m_jobKey = "Atom Material Builder"; - jobDependency.m_sourceFile = materialTypeSource; - jobDependency.m_platformIdentifier = platformIdentifier; - jobDependency.m_type = AssetBuilderSDK::JobDependencyType::Order; - - if (!materialTypeSource.m_sourceFileDependencyPath.empty()) + if (conversionEnabled && !materialTypePath.empty()) { + AssetBuilderSDK::SourceFileDependency materialTypeSource; + materialTypeSource.m_sourceFileDependencyPath = materialTypePath; + + AssetBuilderSDK::JobDependency jobDependency; + jobDependency.m_jobKey = "Atom Material Builder"; + jobDependency.m_sourceFile = materialTypeSource; + jobDependency.m_platformIdentifier = platformIdentifier; + jobDependency.m_type = AssetBuilderSDK::JobDependencyType::Order; + jobDependencyList.push_back(jobDependency); } } + + void MaterialAssetDependenciesComponent::AddFingerprintInfo(AZStd::set& fingerprintInfo) + { + // This will cause scene files to be reprocessed whenever the global MaterialConverter settings change. + + bool conversionEnabled = false; + RPI::MaterialConverterBus::BroadcastResult(conversionEnabled, &RPI::MaterialConverterBus::Events::IsEnabled); + fingerprintInfo.insert(AZStd::string::format("[MaterialConverter enabled=%d]", conversionEnabled)); + + if (!conversionEnabled) + { + AZStd::string defaultMaterialPath; + RPI::MaterialConverterBus::BroadcastResult(defaultMaterialPath, &RPI::MaterialConverterBus::Events::GetDefaultMaterialPath); + fingerprintInfo.insert(AZStd::string::format("[MaterialConverter defaultMaterial=%s]", defaultMaterialPath.c_str())); + } + } void MaterialAssetBuilderComponent::Reflect(ReflectContext* context) { if (auto* serialize = azrtti_cast(context)) { serialize->Class() - ->Version(16); // Optional material conversion + ->Version(16); // Optional material conversion + } + } + + Data::Asset MaterialAssetBuilderComponent::GetDefaultMaterialAsset() const + { + AZStd::string defaultMaterialPath; + RPI::MaterialConverterBus::BroadcastResult(defaultMaterialPath, &RPI::MaterialConverterBus::Events::GetDefaultMaterialPath); + + if (defaultMaterialPath.empty()) + { + return {}; + } + else + { + auto defaultMaterialAssetId = RPI::AssetUtils::MakeAssetId(defaultMaterialPath, 0); + if (!defaultMaterialAssetId.IsSuccess()) + { + AZ_Error("MaterialAssetBuilderComponent", false, "Could not find asset '%s'", defaultMaterialPath.c_str()); + return {}; + } + else + { + return Data::AssetManager::Instance().CreateAsset(defaultMaterialAssetId.GetValue(), Data::AssetLoadBehaviorNamespace::PreLoad); + } } } @@ -119,8 +166,8 @@ namespace AZ BindToCall(&MaterialAssetBuilderComponent::BuildMaterials); } - - SceneAPI::Events::ProcessingResult MaterialAssetBuilderComponent::BuildMaterials(MaterialAssetBuilderContext& context) const + + SceneAPI::Events::ProcessingResult MaterialAssetBuilderComponent::ConvertMaterials(MaterialAssetBuilderContext& context) const { const auto& scene = context.m_scene; const Uuid sourceSceneUuid = scene.GetSourceGuid(); @@ -193,6 +240,64 @@ namespace AZ return SceneAPI::Events::ProcessingResult::Success; } + + SceneAPI::Events::ProcessingResult MaterialAssetBuilderComponent::AssignDefaultMaterials(MaterialAssetBuilderContext& context) const + { + Data::Asset defaultMaterialAsset = GetDefaultMaterialAsset(); + + if (!defaultMaterialAsset.GetId().IsValid()) + { + AZ_Warning("MaterialAssetBuilderComponent", false, "Material conversion is disabled but no default material was provided. The model will likely be invisible by default."); + // Return success because it's just a warning. + return SceneAPI::Events::ProcessingResult::Success; + } + + const auto& scene = context.m_scene; + const Uuid sourceSceneUuid = scene.GetSourceGuid(); + const auto& sceneGraph = scene.GetGraph(); + + auto names = sceneGraph.GetNameStorage(); + auto content = sceneGraph.GetContentStorage(); + auto pairView = SceneAPI::Containers::Views::MakePairView(names, content); + + auto view = SceneAPI::Containers::Views::MakeSceneGraphDownwardsView< + SceneAPI::Containers::Views::BreadthFirst>( + sceneGraph, sceneGraph.GetRoot(), pairView.cbegin(), true); + + for (const auto& viewIt : view) + { + if (viewIt.second == nullptr) + { + continue; + } + + if (azrtti_istypeof(viewIt.second.get())) + { + auto materialData = AZStd::static_pointer_cast(viewIt.second); + uint64_t materialUid = materialData->GetUniqueId(); + + context.m_outputMaterialsByUid[materialUid] = { defaultMaterialAsset, materialData->GetMaterialName() }; + } + } + + return SceneAPI::Events::ProcessingResult::Success; + } + + SceneAPI::Events::ProcessingResult MaterialAssetBuilderComponent::BuildMaterials(MaterialAssetBuilderContext& context) const + { + bool conversionEnabled = false; + RPI::MaterialConverterBus::BroadcastResult(conversionEnabled, &RPI::MaterialConverterBus::Events::IsEnabled); + + if (conversionEnabled) + { + return ConvertMaterials(context); + } + else + { + return AssignDefaultMaterials(context); + } + + } } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.h b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.h index f02034c35d..f89ae1cde9 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.h +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.h @@ -39,6 +39,13 @@ namespace AZ // Required for ExportingComponent static void Reflect(AZ::ReflectContext* context); + + private: + + SceneAPI::Events::ProcessingResult ConvertMaterials(MaterialAssetBuilderContext& context) const; + SceneAPI::Events::ProcessingResult AssignDefaultMaterials(MaterialAssetBuilderContext& context) const; + + Data::Asset GetDefaultMaterialAsset() const; }; /** @@ -65,6 +72,7 @@ namespace AZ // SceneAPI::SceneBuilderDependencyBus::Handler overrides... void ReportJobDependencies(SceneAPI::JobDependencyList& jobDependencyList, const char* platformIdentifier) override; + void AddFingerprintInfo(AZStd::set& fingerprintInfo) override; }; } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp index 8e54e5e90f..13e5714b52 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp @@ -1822,7 +1822,7 @@ namespace AZ if (iter != materialAssetsByUid.end()) { ModelMaterialSlot materialSlot; - materialSlot.m_stableId = meshView.m_materialUid; + materialSlot.m_stableId = static_cast(meshView.m_materialUid); materialSlot.m_displayName = iter->second.m_name; materialSlot.m_defaultMaterialAsset = iter->second.m_asset; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelExporterComponent.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelExporterComponent.cpp index ea39ea9031..f7e672ab32 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelExporterComponent.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelExporterComponent.cpp @@ -78,9 +78,17 @@ namespace AZ //Export MaterialAssets for (auto& materialPair : materialsByUid) { + const Data::Asset& asset = materialPair.second.m_asset; + + // MaterialAssetBuilderContext could attach an independent material asset rather than + // generate one using the scene data, so we must skip the export step in that case. + if (asset.GetId().m_guid != exportEventContext.GetScene().GetSourceGuid()) + { + continue; + } + uint64_t materialUid = materialPair.first; const AZStd::string& sceneName = exportEventContext.GetScene().GetName(); - const Data::Asset& asset = materialPair.second.m_asset; // escape the material name acceptable for a filename AZStd::string materialName = materialPair.second.m_name; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp index 87e7605c71..2d812c602f 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/Buffer.cpp @@ -176,8 +176,7 @@ namespace AZ return RHI::ResultCode::Success; } - // ResultCode::Unimplemented is used by Null Renderer and hence is a valid use case - AZ_Error("Buffer", resultCode == AZ::RHI::ResultCode::Unimplemented, "Buffer::Init() failed to initialize RHI buffer. Error code: %d", static_cast(resultCode)); + AZ_Error("Buffer", false, "Buffer::Init() failed to initialize RHI buffer. Error code: %d", static_cast(resultCode)); return resultCode; } @@ -241,11 +240,6 @@ namespace AZ { return response.m_data; } - else if (result == RHI::ResultCode::Unimplemented) - { - // ResultCode::Unimplemented is used by Null Renderer and hence is a valid use case - return nullptr; - } else { AZ_Error("RPI::Buffer", false, "Failed to update RHI buffer. Error code: %d", result); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp index bb66526ea0..77e32cd040 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Buffer/BufferSystem.cpp @@ -136,6 +136,7 @@ namespace AZ return false; } + bufferPool->SetName(Name(AZStd::string::format("RPI::CommonBufferPool_%i", static_cast(poolType)))); RHI::ResultCode resultCode = bufferPool->Init(*device, bufferPoolDesc); if (resultCode != RHI::ResultCode::Success) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index c630fe0e5d..f07262f2ca 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -31,7 +31,7 @@ #include #endif -//Enables more inner-loop profiling scopes (can create high overhead in RadTelemetry if there are many-many objects in a scene) +//Enables more inner-loop profiling scopes (can create high overhead in telemetry if there are many-many objects in a scene) //#define AZ_CULL_PROFILE_DETAILED //Enables more detailed profiling descriptions within the culling system, but adds some performance overhead. @@ -299,7 +299,7 @@ namespace AZ //work function void Process() override { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); const View::UsageFlags viewFlags = m_jobData->m_view->GetUsageFlags(); const RHI::DrawListMask drawListMask = m_jobData->m_view->GetDrawListMask(); @@ -312,7 +312,7 @@ namespace AZ bool nodeIsContainedInFrustum = ShapeIntersection::Contains(m_jobData->m_frustum, nodeData.m_bounds); #ifdef AZ_CULL_PROFILE_VERBOSE - AZ_PROFILE_SCOPE_DYNAMIC(Debug::ProfileCategory::AzRender, "process node (view: %s, skip fine cull: %d", + AZ_PROFILE_SCOPE(AzRender, "process node (view: %s, skip fine cull: %d", m_view->GetName().GetCStr(), nodeIsContainedInFrustum ? 1 : 0); #endif @@ -385,7 +385,7 @@ namespace AZ if (m_jobData->m_debugCtx->m_debugDraw && (m_jobData->m_view->GetName() == m_jobData->m_debugCtx->m_currentViewSelectionName)) { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "debug draw culling"); + AZ_PROFILE_SCOPE(AzRender, "debug draw culling"); AuxGeomDrawPtr auxGeomPtr = AuxGeomFeatureProcessorInterface::GetDrawQueueForScene(m_jobData->m_scene); if (auxGeomPtr) @@ -507,7 +507,7 @@ namespace AZ void CullingScene::ProcessCullables(const Scene& scene, View& view, AZ::Job& parentJob) { - AZ_PROFILE_SCOPE_DYNAMIC(Debug::ProfileCategory::AzRender, "CullingScene::ProcessCullables() - %s", view.GetName().GetCStr()); + AZ_PROFILE_SCOPE(AzRender, "CullingScene::ProcessCullables() - %s", view.GetName().GetCStr()); const Matrix4x4& worldToClip = view.GetWorldToClipMatrix(); Frustum frustum = Frustum::CreateFromMatrixColumnMajor(worldToClip); @@ -598,7 +598,7 @@ namespace AZ auto nodeVisitorLambda = [this, jobData, &parentJob, &frustum, &worklist](const AzFramework::IVisibilityScene::NodeData& nodeData) -> void { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "nodeVisitorLambda()"); + AZ_PROFILE_SCOPE(AzRender, "nodeVisitorLambda()"); AZ_Assert(nodeData.m_entries.size() > 0, "should not get called with 0 entries"); AZ_Assert(worklist.size() < worklist.capacity(), "we should always have room to push a node on the queue"); @@ -645,7 +645,7 @@ namespace AZ uint32_t AddLodDataToView(const Vector3& pos, const Cullable::LodData& lodData, RPI::View& view) { #ifdef AZ_CULL_PROFILE_DETAILED - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); #endif const Matrix4x4& viewToClip = view.GetViewToClipMatrix(); @@ -663,7 +663,7 @@ namespace AZ auto addLodToDrawPacket = [&](const Cullable::LodData::Lod& lod) { #ifdef AZ_CULL_PROFILE_VERBOSE - AZ_PROFILE_SCOPE_DYNAMIC(Debug::ProfileCategory::AzRender, "add draw packets: %zu", lod.m_drawPackets.size()); + AZ_PROFILE_SCOPE(AzRender, "add draw packets: %zu", lod.m_drawPackets.size()); #endif numVisibleDrawPackets += static_cast(lod.m_drawPackets.size()); //don't want to pay the cost of aznumeric_cast<> here so using static_cast<> instead for (const RHI::DrawPacket* drawPacket : lod.m_drawPackets) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Image/StreamingImage.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Image/StreamingImage.cpp index 45070371d6..8629588ea2 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Image/StreamingImage.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Image/StreamingImage.cpp @@ -247,7 +247,7 @@ namespace AZ uint16_t StreamingImage::GetResidentMipLevel() { - return m_image->GetResidentMipLevel(); + return static_cast(m_image->GetResidentMipLevel()); } RHI::ResultCode StreamingImage::TrimToMipChainLevel(size_t mipChainIndex) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Material/Material.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Material/Material.cpp index 4f941463eb..1de6776d9c 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Material/Material.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Material/Material.cpp @@ -310,7 +310,7 @@ namespace AZ if (NeedsCompile() && CanCompile()) { - AZ_PROFILE_EVENT_BEGIN(Debug::ProfileCategory::AzRender, "Material::Compile() Processing Functors"); + AZ_PROFILE_BEGIN(AzRender, "Material::Compile() Processing Functors"); for (const Ptr& functor : m_materialAsset->GetMaterialFunctors()) { if (functor) @@ -339,7 +339,7 @@ namespace AZ AZ_Error(s_debugTraceName, false, "Material functor is null."); } } - AZ_PROFILE_EVENT_END(Debug::ProfileCategory::AzRender); + AZ_PROFILE_END(); m_propertyDirtyFlags.reset(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/MeshDrawPacket.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/MeshDrawPacket.cpp index 5762720913..7fd7133cee 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/MeshDrawPacket.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/MeshDrawPacket.cpp @@ -124,7 +124,7 @@ namespace AZ bool MeshDrawPacket::DoUpdate(const Scene& parentScene) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); const ModelLod::Mesh& mesh = m_modelLod->GetMeshes()[m_modelLodMeshIndex]; if (!m_material) @@ -155,7 +155,7 @@ namespace AZ auto appendShader = [&](const ShaderCollection::Item& shaderItem) { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "appendShader()"); + AZ_PROFILE_SCOPE(AzRender, "appendShader()"); // Skip the shader item without creating the shader instance // if the mesh is not going to be rendered based on the draw tag @@ -256,7 +256,7 @@ namespace AZ Data::Instance drawSrg; if (drawSrgLayout) { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "create drawSrg"); + AZ_PROFILE_SCOPE(AzRender, "create drawSrg"); // If the DrawSrg exists we must create and bind it, otherwise the CommandList will fail validation for SRG being null drawSrg = RPI::ShaderResourceGroup::Create(shader->GetAsset(), shader->GetSupervariantIndex(), drawSrgLayout->GetName()); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp index 32fe297c57..0cbcdbf5f4 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp @@ -42,7 +42,7 @@ namespace AZ Data::Instance Model::CreateInternal(const Data::Asset& modelAsset) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); Data::Instance model = aznew Model(); const RHI::ResultCode resultCode = model->Init(modelAsset); @@ -56,7 +56,7 @@ namespace AZ RHI::ResultCode Model::Init(const Data::Asset& modelAsset) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); m_lods.resize(modelAsset->GetLodAssets().size()); @@ -107,7 +107,7 @@ namespace AZ { if (m_isUploadPending) { - AZ_PROFILE_SCOPE_STALL_DYNAMIC(Debug::ProfileCategory::AzRender, "Model::WaitForUpload - %s", GetDatabaseName()); + AZ_PROFILE_SCOPE(AzRender, "Model::WaitForUpload - %s", GetDatabaseName()); for (const Data::Instance& lod : m_lods) { lod->WaitForUpload(); @@ -128,7 +128,7 @@ namespace AZ bool Model::LocalRayIntersection(const AZ::Vector3& rayStart, const AZ::Vector3& rayDir, float& distanceNormalized, AZ::Vector3& normal) const { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); if (!GetModelAsset()) { @@ -171,7 +171,7 @@ namespace AZ float& distanceNormalized, AZ::Vector3& normal) const { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); const AZ::Vector3 clampedScale = nonUniformScale.GetMax(AZ::Vector3(AZ::MinTransformScale)); const AZ::Transform inverseTM = modelTransform.GetInverse(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLod.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLod.cpp index dc39200a65..cfe0d08270 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLod.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLod.cpp @@ -264,7 +264,7 @@ namespace AZ const MaterialModelUvOverrideMap& materialModelUvMap, const MaterialUvNameMap& materialUvNameMap) const { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); streamBufferViewsOut.clear(); @@ -366,7 +366,7 @@ namespace AZ const MaterialModelUvOverrideMap& materialModelUvMap, const MaterialUvNameMap& materialUvNameMap) const { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); const Mesh& mesh = m_meshes[meshIndex]; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLodUtils.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLodUtils.cpp index dc5c1f5c4d..0fe035dd85 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLodUtils.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLodUtils.cpp @@ -27,7 +27,7 @@ namespace AZ ModelLodIndex SelectLod(const View* view, const Vector3& position, const Model& model, ModelLodIndex lodOverride) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); ModelLodIndex lodIndex; if (model.GetLodCount() == 1) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/FullscreenTrianglePass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/FullscreenTrianglePass.cpp index 94421e2ca4..40dce7d138 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/FullscreenTrianglePass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/FullscreenTrianglePass.cpp @@ -155,7 +155,7 @@ namespace AZ m_item.m_arguments = RHI::DrawArguments(draw); m_item.m_pipelineState = m_shader->AcquirePipelineState(pipelineStateDescriptor); - m_item.m_stencilRef = m_stencilRef; + m_item.m_stencilRef = static_cast(m_stencilRef); } void FullscreenTrianglePass::FrameBeginInternal(FramePrepareParams params) @@ -179,10 +179,10 @@ namespace AZ RHI::Size targetImageSize = outputAttachment->m_descriptor.m_image.m_size; - m_viewportState.m_maxX = AZStd::min(static_cast(params.m_viewportState.m_maxX), targetImageSize.m_width); - m_viewportState.m_maxY = AZStd::min(static_cast(params.m_viewportState.m_maxY), targetImageSize.m_height); - m_viewportState.m_minX = AZStd::min(params.m_viewportState.m_minX, m_viewportState.m_maxX); - m_viewportState.m_minY = AZStd::min(params.m_viewportState.m_minY, m_viewportState.m_maxY); + m_viewportState.m_maxX = static_cast(AZStd::min(static_cast(params.m_viewportState.m_maxX), targetImageSize.m_width)); + m_viewportState.m_maxY = static_cast(AZStd::min(static_cast(params.m_viewportState.m_maxY), targetImageSize.m_height)); + m_viewportState.m_minX = static_cast(AZStd::min(params.m_viewportState.m_minX, m_viewportState.m_maxX)); + m_viewportState.m_minY = static_cast(AZStd::min(params.m_viewportState.m_minY, m_viewportState.m_maxY)); m_scissorState.m_maxX = AZStd::min(static_cast(params.m_scissorState.m_maxX), targetImageSize.m_width); m_scissorState.m_maxY = AZStd::min(static_cast(params.m_scissorState.m_maxY), targetImageSize.m_height); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp index d73521763f..4cf952ee01 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/PassSystem.cpp @@ -189,7 +189,7 @@ namespace AZ void PassSystem::BuildPasses() { m_state = PassSystemState::BuildingPasses; - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: BuildPassAttachments"); m_passHierarchyChanged = m_passHierarchyChanged || !m_buildPassList.empty(); @@ -239,7 +239,7 @@ namespace AZ void PassSystem::InitializePasses() { m_state = PassSystemState::InitializingPasses; - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: BuildPassAttachments"); m_passHierarchyChanged = m_passHierarchyChanged || !m_initializePassList.empty(); @@ -286,7 +286,7 @@ namespace AZ return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); PassValidationResults validationResults; m_rootPass->Validate(validationResults); @@ -307,7 +307,7 @@ namespace AZ void PassSystem::FrameUpdate(RHI::FrameGraphBuilder& frameGraphBuilder) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RPI", "PassSystem: FrameUpdate"); ResetFrameStatistics(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp index ce02e1c570..d37002eb6b 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/RasterPass.cpp @@ -216,7 +216,7 @@ namespace AZ void RasterPass::CompileResources(const RHI::FrameGraphCompileContext& context) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); if (m_shaderResourceGroup == nullptr) { @@ -230,7 +230,7 @@ namespace AZ void RasterPass::BuildCommandListInternal(const RHI::FrameGraphExecuteContext& context) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); RHI::CommandList* commandList = context.GetCommandList(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp index d2a32784ce..5eb9bd2d46 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp @@ -270,7 +270,7 @@ namespace AZ return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZ_ATOM_PROFILE_FUNCTION("RPI", "RPISystem: RenderTick"); // Query system update is to increment the frame count @@ -349,19 +349,6 @@ namespace AZ return; } - //[GFX TODO][ATOM-5867] - Move file loading code within RHI to reduce coupling with RPI - AZStd::string platformLimitsFilePath = AZStd::string::format("config/platform/%s/%s/platformlimits.azasset", AZ_TRAIT_OS_PLATFORM_NAME, GetRenderApiName().GetCStr()); - AZStd::to_lower(platformLimitsFilePath.begin(), platformLimitsFilePath.end()); - - Data::Asset platformLimitsAsset; - platformLimitsAsset = RPI::AssetUtils::LoadCriticalAsset(platformLimitsFilePath.c_str(), RPI::AssetUtils::TraceLevel::None); - // Only read the m_platformLimits if the platformLimitsAsset is ready. - // The platformLimitsAsset may not exist for null renderer which is allowed - if (platformLimitsAsset.IsReady()) - { - m_descriptor.m_rhiSystemDescriptor.m_platformLimits = RPI::GetDataFromAnyAsset(platformLimitsAsset); - } - m_commonShaderAssetForSrgs = AssetUtils::LoadCriticalAsset( m_descriptor.m_commonSrgsShaderAssetPath.c_str()); if (!m_commonShaderAssetForSrgs.IsReady()) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp index 89f7da11e3..a552ac86f2 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp @@ -377,7 +377,7 @@ namespace AZ void RenderPipeline::OnStartFrame(const TickTimeInfo& tick) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); m_lastRenderStartTime = tick.m_currentGameTime; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp index 02a03ee853..26fdae1c54 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp @@ -21,6 +21,7 @@ #include #include +#include #include #include @@ -399,7 +400,7 @@ namespace AZ AZ_ATOM_PROFILE_FUNCTION("RPI", "Scene: PrepareRender"); { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "WaitForSimulationCompletion"); + AZ_PROFILE_SCOPE(AzRender, "WaitForSimulationCompletion"); AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "WaitForSimulationCompletion"); WaitAndCleanCompletionJob(m_simulationCompletion); } @@ -407,7 +408,7 @@ namespace AZ SceneNotificationBus::Event(GetId(), &SceneNotification::OnBeginPrepareRender); { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "m_srgCallback"); + AZ_PROFILE_SCOPE(AzRender, "m_srgCallback"); AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "ShaderResourceGroupCallback: SrgCallback"); // Set values for scene srg if (m_srg && m_srgCallback) @@ -483,7 +484,7 @@ namespace AZ } { - AZ_PROFILE_SCOPE(Debug::ProfileCategory::AzRender, "CollectDrawPackets"); + AZ_PROFILE_SCOPE(AzRender, "CollectDrawPackets"); AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "CollectDrawPackets"); AZ::JobCompletion* collectDrawPacketsCompletion = aznew AZ::JobCompletion(); @@ -533,7 +534,7 @@ namespace AZ } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzRender, "FinalizeDrawLists"); + AZ_PROFILE_BEGIN(AzRender, "FinalizeDrawLists"); AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "FinalizeDrawLists"); if (jobPolicy == RHI::JobPolicy::Serial) { @@ -541,6 +542,7 @@ namespace AZ { view->FinalizeDrawLists(); } + AZ_PROFILE_END(); } else { @@ -556,7 +558,7 @@ namespace AZ finalizeDrawListsJob->SetDependent(finalizeDrawListsCompletion); finalizeDrawListsJob->Start(); } - AZ_PROFILE_EVENT_END(Debug::ProfileCategory::AzRender); + AZ_PROFILE_END(); WaitAndCleanCompletionJob(finalizeDrawListsCompletion); } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Metrics/ShaderMetricsSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Metrics/ShaderMetricsSystem.cpp index d0d76e62de..c0f0e20714 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Metrics/ShaderMetricsSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Metrics/ShaderMetricsSystem.cpp @@ -113,7 +113,7 @@ namespace AZ return; } - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); AZStd::lock_guard lock(m_metricsMutex); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Shader.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Shader.cpp index ff277c5cad..f6dcd02804 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Shader.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/Shader.cpp @@ -297,7 +297,7 @@ namespace AZ const ShaderVariant& Shader::GetVariant(const ShaderVariantId& shaderVariantId) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); Data::Asset shaderVariantAsset = m_asset->GetVariant(shaderVariantId, m_supervariantIndex); if (!shaderVariantAsset || shaderVariantAsset->IsRootVariant()) { @@ -314,14 +314,14 @@ namespace AZ ShaderVariantSearchResult Shader::FindVariantStableId(const ShaderVariantId& shaderVariantId) const { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); ShaderVariantSearchResult variantSearchResult = m_asset->FindVariantStableId(shaderVariantId); return variantSearchResult; } const ShaderVariant& Shader::GetVariant(ShaderVariantStableId shaderVariantStableId) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); if (!shaderVariantStableId.IsValid() || shaderVariantStableId == ShaderAsset::RootShaderVariantStableId) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index 1937afc240..f1f25e3303 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -237,7 +237,7 @@ namespace AZ void View::FinalizeDrawLists() { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); m_drawListContext.FinalizeLists(); SortFinalizedDrawLists(); } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp index 275b056514..e1da50d2fb 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp @@ -96,7 +96,7 @@ namespace AZ const AZ::Vector3& rayStart, const AZ::Vector3& rayDir, bool allowBruteForce, float& distanceNormalized, AZ::Vector3& normal) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); if (!m_modelTriangleCount) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelMaterialSlot.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelMaterialSlot.cpp index 0900949625..b9d9200aaf 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelMaterialSlot.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelMaterialSlot.cpp @@ -15,7 +15,7 @@ namespace AZ { // Normally this would be defined in the header file and substituted by the compiler, but for // some reason clang doesn't accept it. - const ModelMaterialSlot::StableId ModelMaterialSlot::InvalidStableId = -1; + const ModelMaterialSlot::StableId ModelMaterialSlot::InvalidStableId = std::numeric_limits::max(); void ModelMaterialSlot::Reflect(AZ::ReflectContext* context) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderAsset.cpp index f2d82918ea..adeb564675 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderAsset.cpp @@ -172,7 +172,7 @@ namespace AZ Data::Asset ShaderAsset::GetVariant( const ShaderVariantId& shaderVariantId, SupervariantIndex supervariantIndex) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); auto variantFinder = AZ::Interface::Get(); AZ_Assert(variantFinder, "The IShaderVariantFinder doesn't exist"); @@ -189,7 +189,7 @@ namespace AZ ShaderVariantSearchResult ShaderAsset::FindVariantStableId(const ShaderVariantId& shaderVariantId) { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); uint32_t dynamicOptionCount = aznumeric_cast(GetShaderOptionGroupLayout()->GetShaderOptions().size()); ShaderVariantSearchResult variantSearchResult{RootShaderVariantStableId, dynamicOptionCount }; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantTreeAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantTreeAsset.cpp index 46873dc62d..b4a0e2e068 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantTreeAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Shader/ShaderVariantTreeAsset.cpp @@ -72,7 +72,7 @@ namespace AZ ShaderVariantSearchResult ShaderVariantTreeAsset::FindVariantStableId(const ShaderOptionGroupLayout* shaderOptionGroupLayout, const ShaderVariantId& shaderVariantId) const { - AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); + AZ_PROFILE_FUNCTION(AzRender); struct NodeToVisit { @@ -199,7 +199,6 @@ namespace AZ if ((shaderVariantId.m_mask & option.GetBitMask()).any()) { optionValues.push_back(option.DecodeBits(shaderVariantId.m_key)); - AZ_Assert(optionValues.back() >= 0, "Invalid shader variant key"); } else { diff --git a/Gems/Atom/RPI/Code/Tests/Buffer/BufferTests.cpp b/Gems/Atom/RPI/Code/Tests/Buffer/BufferTests.cpp index 3b113b78f8..f648de6997 100644 --- a/Gems/Atom/RPI/Code/Tests/Buffer/BufferTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Buffer/BufferTests.cpp @@ -67,7 +67,8 @@ namespace UnitTest bufferData.resize(bufferSize); // The actual data doesn't matter - for (uint32_t i = 0; i < bufferData.size(); ++i) + const uint8_t bufferDataSize = static_cast(bufferData.size()); + for (uint8_t i = 0; i < bufferDataSize; ++i) { bufferData[i] = i; } diff --git a/Gems/Atom/RPI/Code/Tests/Common/RHI/Factory.cpp b/Gems/Atom/RPI/Code/Tests/Common/RHI/Factory.cpp index 115ccb3819..62af2852e6 100644 --- a/Gems/Atom/RPI/Code/Tests/Common/RHI/Factory.cpp +++ b/Gems/Atom/RPI/Code/Tests/Common/RHI/Factory.cpp @@ -47,7 +47,6 @@ namespace UnitTest RHI::Ptr device = Get().CreateDevice(); device->Init(*physicalDevices[0]); - device->PostInit(RHI::DeviceDescriptor{}); return device; } diff --git a/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.cpp b/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.cpp index 3d40aa27cf..a8d2ac2b0b 100644 --- a/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.cpp +++ b/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.cpp @@ -20,6 +20,11 @@ namespace UnitTest m_descriptor.m_description = "UnitTest Fake Device"; } + Device::Device() + { + m_descriptor.m_platformLimitsDescriptor = aznew RHI::PlatformLimitsDescriptor; + } + RHI::PhysicalDeviceList PhysicalDevice::Enumerate() { return RHI::PhysicalDeviceList{ aznew PhysicalDevice }; diff --git a/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h b/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h index be362c60d6..c3768c1ce6 100644 --- a/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h +++ b/Gems/Atom/RPI/Code/Tests/Common/RHI/Stubs.h @@ -52,10 +52,10 @@ namespace UnitTest { public: AZ_CLASS_ALLOCATOR(Device, AZ::SystemAllocator, 0); + Device(); private: AZ::RHI::ResultCode InitInternal(AZ::RHI::PhysicalDevice&) override { return AZ::RHI::ResultCode::Success; } - AZ::RHI::ResultCode PostInitInternal(const AZ::RHI::DeviceDescriptor&) override { return AZ::RHI::ResultCode::Success; } void ShutdownInternal() override {} void BeginFrameInternal() override {} void EndFrameInternal() override {} @@ -67,6 +67,7 @@ namespace UnitTest return AZStd::chrono::microseconds(); } void FillFormatsCapabilitiesInternal([[maybe_unused]] FormatCapabilitiesList& formatsCapabilities) override {} + AZ::RHI::ResultCode InitializeLimits() override { return AZ::RHI::ResultCode::Success; } 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{}; }; diff --git a/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp b/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp index 21f3239698..ff998ad4d3 100644 --- a/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp @@ -38,7 +38,8 @@ namespace UnitTest bufferData.resize(bufferSize); //The actual data doesn't matter - for (uint32_t i = 0; i < bufferData.size(); ++i) + const uint8_t bufferDataSize = static_cast(bufferData.size()); + for (uint8_t i = 0; i < bufferDataSize; ++i) { bufferData[i] = i; } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h index 3639606f03..d55755a242 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h @@ -19,6 +19,7 @@ #include #include +#include #include #include @@ -46,6 +47,8 @@ namespace AtomToolsFramework AtomToolsApplication(int* argc, char*** argv); ~AtomToolsApplication(); + virtual bool LaunchLocalServer(); + ////////////////////////////////////////////////////////////////////////// // AzFramework::Application void CreateReflectionManager() override; @@ -106,13 +109,13 @@ namespace AtomToolsFramework virtual void UnloadSettings(); virtual void CompileCriticalAssets(); virtual void ProcessCommandLine(const AZ::CommandLine& commandLine); - virtual bool LaunchDiscoveryService(); - virtual void StartInternal(); static void PyIdleWaitFrames(uint32_t frames); AzToolsFramework::TraceLogger m_traceLogger; + AZStd::unique_ptr m_styleManager; + //! Local user settings are used to store material browser tree expansion state AZ::UserSettingsProvider m_localUserSettings; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h index e6a666c640..42fe9a01c9 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h @@ -18,9 +18,22 @@ namespace AtomToolsFramework { class ModularViewportCameraControllerInstance; + //! A reduced ViewportContext interface for use by the ModularViewportCameraController. + //! @note This extra indirection is used to facilitate testing the ModularViewportCameraController. + class ModularCameraViewportContext + { + public: + virtual ~ModularCameraViewportContext() = default; + + virtual AZ::Transform GetCameraTransform() const = 0; + virtual void SetCameraTransform(const AZ::Transform& transform) = 0; + virtual void ConnectViewMatrixChangedHandler(AZ::RPI::ViewportContext::MatrixChangedEvent::Handler& handler) = 0; + }; + //! A function object to represent returning a camera controller priority. using CameraControllerPriorityFn = AZStd::function; + using CameraViewportContextFn = AZStd::function(AzFramework::ViewportId)>; //! The default behavior for what priority the camera controller should respond to events at. //! @note This can change based on the state of the camera controller/system. @@ -38,6 +51,7 @@ namespace AtomToolsFramework using CameraListBuilder = AZStd::function; using CameraPropsBuilder = AZStd::function; using CameraPriorityBuilder = AZStd::function; + using CameraViewportContextBuilder = AZStd::function&)>; //! Sets the camera list builder callback used to populate new ModularViewportCameraControllerInstances. void SetCameraListBuilderCallback(const CameraListBuilder& builder); @@ -45,6 +59,8 @@ namespace AtomToolsFramework void SetCameraPropsBuilderCallback(const CameraPropsBuilder& builder); //! Sets the camera controller priority builder callback used to populate new ModularViewportCameraControllerInstances. void SetCameraPriorityBuilderCallback(const CameraPriorityBuilder& builder); + //! Sets the camera controller viewport context builder callback to populate new ModularViewportCameraControllerInstances. + void SetCameraViewportContextBuilderCallback(const CameraViewportContextBuilder& builder); private: //! Sets up a camera list based on this controller's CameraListBuilderCallback. @@ -53,6 +69,8 @@ namespace AtomToolsFramework void SetupCameraProperties(AzFramework::CameraProps& cameraProps); //! Sets up how the camera controller should decide at what priority level to respond to. void SetupCameraControllerPriority(CameraControllerPriorityFn& cameraPriorityFn); + //! Sets up what viewport context should be used by the camera controller. + void SetupCameraControllerViewportContext(AZStd::unique_ptr& cameraViewportContext); //! Builder to generate a list of CameraInputs to run in the ModularViewportCameraControllerInstance. CameraListBuilder m_cameraListBuilder; @@ -60,6 +78,24 @@ namespace AtomToolsFramework CameraPropsBuilder m_cameraPropsBuilder; //! Builder to define what priority level the camera controller should respond to events at. CameraPriorityBuilder m_cameraControllerPriorityBuilder; + //! Builder to define what viewport context interface the camera controller should use. + CameraViewportContextBuilder m_cameraViewportContextBuilder; + }; + + //! The production modular camera viewport context backed by an AZ::RPI::ViewportContextPtr. + //! @note This is instantiated during normal runtime use. + class ModularCameraViewportContextImpl : public ModularCameraViewportContext + { + public: + explicit ModularCameraViewportContextImpl(AzFramework::ViewportId viewportId); + + // ModularCameraViewportContext overrides ... + AZ::Transform GetCameraTransform() const override; + void SetCameraTransform(const AZ::Transform& transform) override; + void ConnectViewMatrixChangedHandler(AZ::RPI::ViewportContext::MatrixChangedEvent::Handler& handler) override; + + private: + AzFramework::ViewportId m_viewportId; }; //! A customizable camera controller that can be configured to run a varying set of CameraInput instances. @@ -115,5 +151,7 @@ namespace AtomToolsFramework bool m_updatingTransformInternally = false; //! Listen for camera view changes outside of the camera controller. AZ::RPI::ViewportContext::MatrixChangedEvent::Handler m_cameraViewMatrixChangeHandler; + //! The current instance of the modular camera viewport context. + AZStd::unique_ptr m_modularCameraViewportContext; }; } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h index 751b30a907..2a304c9a8c 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h @@ -52,8 +52,11 @@ namespace AtomToolsFramework virtual void SelectPreviousTab(); virtual void SelectNextTab(); + void SetStatusMessage(const QString& message); + void SetStatusWarning(const QString& message); + void SetStatusError(const QString& message); + AzQtComponents::FancyDocking* m_advancedDockManager = nullptr; - QMenuBar* m_menuBar = nullptr; AzQtComponents::TabWidget* m_tabWidget = nullptr; QLabel* m_statusMessage = nullptr; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h index 6edb44bc5c..cb63ff295c 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h @@ -8,9 +8,6 @@ #pragma once -//! Disables "unreferenced formal parameter" warning -#pragma warning(disable : 4100) - #include #include #include @@ -53,10 +50,10 @@ namespace AtomToolsFramework //! Resizes the main window to achieve a requested size for the viewport render target. //! (This indicates the size of the render target, not the desktop-scaled QT widget size). - virtual void ResizeViewportRenderTarget(uint32_t width, uint32_t height) {}; + virtual void ResizeViewportRenderTarget([[maybe_unused]] uint32_t width, [[maybe_unused]] uint32_t height) {}; //! Forces the viewport's render target to use the given resolution, ignoring the size of the viewport widget. - virtual void LockViewportRenderTargetSize(uint32_t width, uint32_t height) {}; + virtual void LockViewportRenderTargetSize([[maybe_unused]] uint32_t width, [[maybe_unused]] uint32_t height) {}; //! Releases the viewport's render target resolution lock, allowing it to match the viewport widget again. virtual void UnlockViewportRenderTargetSize() {}; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp index efd3fec0e8..b8426f7528 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp @@ -21,6 +21,8 @@ #include #include +#include + #include #include #include @@ -61,14 +63,26 @@ namespace AtomToolsFramework : Application(argc, argv) , AzQtApplication(*argc, *argv) { + // Suppress spam from the Source Control system + m_traceLogger.AddWindowFilter(AzToolsFramework::SCC_WINDOW); + + installEventFilter(new AzQtComponents::GlobalEventFilter(this)); + + AZ::IO::FixedMaxPath engineRootPath; + if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) + { + settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder); + } + + m_styleManager.reset(new AzQtComponents::StyleManager(this)); + m_styleManager->initialize(this, engineRootPath); + connect(&m_timer, &QTimer::timeout, this, [&]() { this->PumpSystemEventLoopUntilEmpty(); this->Tick(); }); - // Suppress spam from the Source Control system - m_traceLogger.AddWindowFilter(AzToolsFramework::SCC_WINDOW); } AtomToolsApplication ::~AtomToolsApplication() @@ -152,7 +166,33 @@ namespace AtomToolsFramework Base::StartCommon(systemEntity); - StartInternal(); + m_traceLogger.PrepareLogFile(GetBuildTargetName() + ".log"); + + AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusConnect(); + AzToolsFramework::AssetBrowser::AssetDatabaseLocationNotificationBus::Broadcast( + &AzToolsFramework::AssetBrowser::AssetDatabaseLocationNotifications::OnDatabaseInitialized); + + AZ::Data::AssetCatalogRequestBus::Broadcast(&AZ::Data::AssetCatalogRequestBus::Events::LoadCatalog, "@assets@/assetcatalog.xml"); + + AZ::RPI::RPISystemInterface::Get()->InitializeSystemAssets(); + + LoadSettings(); + + AtomToolsMainWindowNotificationBus::Handler::BusConnect(); + + AtomToolsMainWindowFactoryRequestBus::Broadcast(&AtomToolsMainWindowFactoryRequestBus::Handler::CreateMainWindow); + + auto editorPythonEventsInterface = AZ::Interface::Get(); + if (editorPythonEventsInterface) + { + // The PythonSystemComponent does not call StartPython to allow for lazy python initialization, so start it here + // The PythonSystemComponent will call StopPython when it deactivates, so we do not need our own corresponding call to + // StopPython + editorPythonEventsInterface->StartPython(); + } + + // Delay execution of commands and scripts post initialization + QTimer::singleShot(0, [this]() { ProcessCommandLine(m_commandLine); }); m_timer.start(); } @@ -334,7 +374,7 @@ namespace AtomToolsFramework } } - bool AtomToolsApplication::LaunchDiscoveryService() + bool AtomToolsApplication::LaunchLocalServer() { // Determine if this is the first launch of the tool by attempting to connect to a running server if (m_socket.Connect(QApplication::applicationName())) @@ -376,7 +416,7 @@ namespace AtomToolsFramework { AZ::CommandLine commandLine; commandLine.Parse(tokens); - ProcessCommandLine(commandLine); + QTimer::singleShot(0, [this, commandLine]() { ProcessCommandLine(commandLine); }); } } }); @@ -390,55 +430,6 @@ namespace AtomToolsFramework return true; } - void AtomToolsApplication::StartInternal() - { - if (WasExitMainLoopRequested()) - { - return; - } - - AZStd::string fileName = GetBuildTargetName() + ".log"; - - m_traceLogger.PrepareLogFile(fileName.c_str()); - - if (!LaunchDiscoveryService()) - { - ExitMainLoop(); - return; - } - - AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusConnect(); - AzToolsFramework::AssetBrowser::AssetDatabaseLocationNotificationBus::Broadcast( - &AzToolsFramework::AssetBrowser::AssetDatabaseLocationNotifications::OnDatabaseInitialized); - - AZ::Data::AssetCatalogRequestBus::Broadcast(&AZ::Data::AssetCatalogRequestBus::Events::LoadCatalog, "@assets@/assetcatalog.xml"); - - AZ::RPI::RPISystemInterface::Get()->InitializeSystemAssets(); - - LoadSettings(); - - AtomToolsMainWindowNotificationBus::Handler::BusConnect(); - - AtomToolsMainWindowFactoryRequestBus::Broadcast(&AtomToolsMainWindowFactoryRequestBus::Handler::CreateMainWindow); - - auto editorPythonEventsInterface = AZ::Interface::Get(); - if (editorPythonEventsInterface) - { - // The PythonSystemComponent does not call StartPython to allow for lazy python initialization, so start it here - // The PythonSystemComponent will call StopPython when it deactivates, so we do not need our own corresponding call to - // StopPython - editorPythonEventsInterface->StartPython(); - } - - // Delay execution of commands and scripts post initialization - QTimer::singleShot( - 0, - [this]() - { - ProcessCommandLine(m_commandLine); - }); - } - bool AtomToolsApplication::GetAssetDatabaseLocation(AZStd::string& result) { AZ::SettingsRegistryInterface* settingsRegistry = AZ::SettingsRegistry::Get(); diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocument.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocument.cpp index e8eb9401d4..336737f419 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocument.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocument.cpp @@ -38,35 +38,35 @@ namespace AtomToolsFramework return m_relativePath; } - const AZStd::any& AtomToolsDocument::GetPropertyValue(const AZ::Name& propertyFullName) const + const AZStd::any& AtomToolsDocument::GetPropertyValue([[maybe_unused]] const AZ::Name& propertyFullName) const { AZ_UNUSED(propertyFullName); AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); return m_invalidValue; } - const AtomToolsFramework::DynamicProperty& AtomToolsDocument::GetProperty(const AZ::Name& propertyFullName) const + const AtomToolsFramework::DynamicProperty& AtomToolsDocument::GetProperty([[maybe_unused]] const AZ::Name& propertyFullName) const { AZ_UNUSED(propertyFullName); AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); return m_invalidProperty; } - bool AtomToolsDocument::IsPropertyGroupVisible(const AZ::Name& propertyGroupFullName) const + bool AtomToolsDocument::IsPropertyGroupVisible([[maybe_unused]] const AZ::Name& propertyGroupFullName) const { AZ_UNUSED(propertyGroupFullName); AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); return false; } - void AtomToolsDocument::SetPropertyValue(const AZ::Name& propertyFullName, const AZStd::any& value) + void AtomToolsDocument::SetPropertyValue([[maybe_unused]] const AZ::Name& propertyFullName, [[maybe_unused]] const AZStd::any& value) { AZ_UNUSED(propertyFullName); AZ_UNUSED(value); AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); } - bool AtomToolsDocument::Open(AZStd::string_view loadPath) + bool AtomToolsDocument::Open([[maybe_unused]] AZStd::string_view loadPath) { AZ_UNUSED(loadPath); AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); @@ -85,7 +85,7 @@ namespace AtomToolsFramework return false; } - bool AtomToolsDocument::SaveAsCopy(AZStd::string_view savePath) + bool AtomToolsDocument::SaveAsCopy([[maybe_unused]] AZStd::string_view savePath) { AZ_UNUSED(savePath); AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); @@ -93,7 +93,7 @@ namespace AtomToolsFramework } - bool AtomToolsDocument::SaveAsChild(AZStd::string_view savePath) + bool AtomToolsDocument::SaveAsChild([[maybe_unused]] AZStd::string_view savePath) { AZ_UNUSED(savePath); AZ_Error("AtomToolsDocument", false, "%s not implemented.", __FUNCTION__); diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp index e98df83930..0fc55e2363 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp @@ -41,6 +41,7 @@ namespace AtomToolsFramework display.DrawLine(transform.GetTranslation(), transform.GetTranslation() + transform.GetBasisZ().GetNormalizedSafe() * axisLength); } + // convenience function to access the ViewportContext for the given ViewportId. static AZ::RPI::ViewportContextPtr RetrieveViewportContext(const AzFramework::ViewportId viewportId) { auto viewportContextManager = AZ::Interface::Get(); @@ -58,6 +59,35 @@ namespace AtomToolsFramework return viewportContext; } + ModularCameraViewportContextImpl::ModularCameraViewportContextImpl(const AzFramework::ViewportId viewportId) + : m_viewportId(viewportId) + { + } + + AZ::Transform ModularCameraViewportContextImpl::GetCameraTransform() const + { + if (auto viewportContext = RetrieveViewportContext(m_viewportId)) + { + return viewportContext->GetCameraTransform(); + } + + return AZ::Transform::CreateIdentity(); + } + void ModularCameraViewportContextImpl::SetCameraTransform(const AZ::Transform& transform) + { + if (auto viewportContext = RetrieveViewportContext(m_viewportId)) + { + viewportContext->SetCameraTransform(transform); + } + } + void ModularCameraViewportContextImpl::ConnectViewMatrixChangedHandler(AZ::RPI::ViewportContext::MatrixChangedEvent::Handler& handler) + { + if (auto viewportContext = RetrieveViewportContext(m_viewportId)) + { + viewportContext->ConnectViewMatrixChangedHandler(handler); + } + } + void ModularViewportCameraController::SetCameraListBuilderCallback(const CameraListBuilder& builder) { m_cameraListBuilder = builder; @@ -73,6 +103,11 @@ namespace AtomToolsFramework m_cameraControllerPriorityBuilder = builder; } + void ModularViewportCameraController::SetCameraViewportContextBuilderCallback(const CameraViewportContextBuilder& builder) + { + m_cameraViewportContextBuilder = builder; + } + void ModularViewportCameraController::SetupCameras(AzFramework::Cameras& cameras) { if (m_cameraListBuilder) @@ -97,6 +132,15 @@ namespace AtomToolsFramework } } + void ModularViewportCameraController::SetupCameraControllerViewportContext( + AZStd::unique_ptr& cameraViewportContext) + { + if (m_cameraViewportContextBuilder) + { + m_cameraViewportContextBuilder(cameraViewportContext); + } + } + // what priority should the camera system respond to AzFramework::ViewportControllerPriority DefaultCameraControllerPriority(const AzFramework::CameraSystem& cameraSystem) { @@ -119,23 +163,20 @@ namespace AtomToolsFramework controller->SetupCameras(m_cameraSystem.m_cameras); controller->SetupCameraProperties(m_cameraProps); controller->SetupCameraControllerPriority(m_priorityFn); + controller->SetupCameraControllerViewportContext(m_modularCameraViewportContext); - if (auto viewportContext = RetrieveViewportContext(GetViewportId())) + auto handleCameraChange = [this](const AZ::Matrix4x4&) { - auto handleCameraChange = [this, viewportContext](const AZ::Matrix4x4&) + // ignore these updates if the camera is being updated internally + if (!m_updatingTransformInternally) { - // ignore these updates if the camera is being updated internally - if (!m_updatingTransformInternally) - { - UpdateCameraFromTransform(m_targetCamera, viewportContext->GetCameraTransform()); - m_camera = m_targetCamera; - } - }; + UpdateCameraFromTransform(m_targetCamera, m_modularCameraViewportContext->GetCameraTransform()); + m_camera = m_targetCamera; + } + }; - m_cameraViewMatrixChangeHandler = AZ::RPI::ViewportContext::MatrixChangedEvent::Handler(handleCameraChange); - - viewportContext->ConnectViewMatrixChangedHandler(m_cameraViewMatrixChangeHandler); - } + m_cameraViewMatrixChangeHandler = AZ::RPI::ViewportContext::MatrixChangedEvent::Handler(handleCameraChange); + m_modularCameraViewportContext->ConnectViewMatrixChangedHandler(m_cameraViewMatrixChangeHandler); AzFramework::ViewportDebugDisplayEventBus::Handler::BusConnect(AzToolsFramework::GetEntityContextId()); ModularViewportCameraControllerRequestBus::Handler::BusConnect(viewportId); @@ -151,7 +192,11 @@ namespace AtomToolsFramework { if (event.m_priority == m_priorityFn(m_cameraSystem)) { - return m_cameraSystem.HandleEvents(AzFramework::BuildInputEvent(event.m_inputChannel)); + AzFramework::WindowSize windowSize; + AzFramework::WindowRequestBus::EventResult( + windowSize, event.m_windowHandle, &AzFramework::WindowRequestBus::Events::GetClientAreaSize); + + return m_cameraSystem.HandleEvents(AzFramework::BuildInputEvent(event.m_inputChannel, windowSize)); } return false; @@ -165,61 +210,58 @@ namespace AtomToolsFramework return; } - if (auto viewportContext = RetrieveViewportContext(GetViewportId())) + m_updatingTransformInternally = true; + + if (m_cameraMode == CameraMode::Control) { - m_updatingTransformInternally = true; + m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); + m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_cameraProps, event.m_deltaTime.count()); - if (m_cameraMode == CameraMode::Control) + // if there has been an interpolation, only clear the look at point if it is no longer + // centered in the view (the camera has looked away from it) + if (m_lookAtAfterInterpolation.has_value()) { - m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); - m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_cameraProps, event.m_deltaTime.count()); - - // if there has been an interpolation, only clear the look at point if it is no longer - // centered in the view (the camera has looked away from it) - if (m_lookAtAfterInterpolation.has_value()) + if (const float lookDirection = + (*m_lookAtAfterInterpolation - m_camera.Translation()).GetNormalized().Dot(m_camera.Transform().GetBasisY()); + !AZ::IsCloseMag(lookDirection, 1.0f, 0.001f)) { - if (const float lookDirection = - (*m_lookAtAfterInterpolation - m_camera.Translation()).GetNormalized().Dot(m_camera.Transform().GetBasisY()); - !AZ::IsCloseMag(lookDirection, 1.0f, 0.001f)) - { - m_lookAtAfterInterpolation = {}; - } + m_lookAtAfterInterpolation = {}; } - - viewportContext->SetCameraTransform(m_camera.Transform()); - } - else if (m_cameraMode == CameraMode::Animation) - { - const auto smootherStepFn = [](const float t) - { - return t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f); - }; - - const auto& [transformStart, transformEnd, animationTime] = m_cameraAnimation; - - const float transitionTime = smootherStepFn(animationTime); - const AZ::Transform current = AZ::Transform::CreateFromQuaternionAndTranslation( - transformStart.GetRotation().Slerp(transformEnd.GetRotation(), transitionTime), - transformStart.GetTranslation().Lerp(transformEnd.GetTranslation(), transitionTime)); - - const AZ::Vector3 eulerAngles = AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromTransform(current)); - m_camera.m_pitch = eulerAngles.GetX(); - m_camera.m_yaw = eulerAngles.GetZ(); - m_camera.m_lookAt = current.GetTranslation(); - m_targetCamera = m_camera; - - if (animationTime >= 1.0f) - { - m_cameraMode = CameraMode::Control; - } - - m_cameraAnimation.m_time = AZ::GetClamp(animationTime + event.m_deltaTime.count(), 0.0f, 1.0f); - - viewportContext->SetCameraTransform(current); } - m_updatingTransformInternally = false; + m_modularCameraViewportContext->SetCameraTransform(m_camera.Transform()); } + else if (m_cameraMode == CameraMode::Animation) + { + const auto smootherStepFn = [](const float t) + { + return t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f); + }; + + const auto& [transformStart, transformEnd, animationTime] = m_cameraAnimation; + + const float transitionTime = smootherStepFn(animationTime); + const AZ::Transform current = AZ::Transform::CreateFromQuaternionAndTranslation( + transformStart.GetRotation().Slerp(transformEnd.GetRotation(), transitionTime), + transformStart.GetTranslation().Lerp(transformEnd.GetTranslation(), transitionTime)); + + const AZ::Vector3 eulerAngles = AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromTransform(current)); + m_camera.m_pitch = eulerAngles.GetX(); + m_camera.m_yaw = eulerAngles.GetZ(); + m_camera.m_lookAt = current.GetTranslation(); + m_targetCamera = m_camera; + + if (animationTime >= 1.0f) + { + m_cameraMode = CameraMode::Control; + } + + m_cameraAnimation.m_time = AZ::GetClamp(animationTime + event.m_deltaTime.count(), 0.0f, 1.0f); + + m_modularCameraViewportContext->SetCameraTransform(current); + } + + m_updatingTransformInternally = false; } void ModularViewportCameraControllerInstance::DisplayViewport( diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp index e869e0eb98..cd7d49d8d3 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp @@ -110,9 +110,9 @@ namespace AtomToolsFramework void AtomToolsMainWindow::CreateMenu() { - m_menuBar = new QMenuBar(this); - m_menuBar->setObjectName("MenuBar"); - setMenuBar(m_menuBar); + auto menuBar = new QMenuBar(this); + menuBar->setObjectName("MenuBar"); + setMenuBar(menuBar); } void AtomToolsMainWindow::CreateTabBar() @@ -246,4 +246,19 @@ namespace AtomToolsFramework m_tabWidget->setCurrentIndex((m_tabWidget->currentIndex() + 1) % m_tabWidget->count()); } } + + void AtomToolsMainWindow::SetStatusMessage(const QString& message) + { + m_statusMessage->setText(QString("%1").arg(message)); + } + + void AtomToolsMainWindow::SetStatusWarning(const QString& message) + { + m_statusMessage->setText(QString("%1").arg(message)); + } + + void AtomToolsMainWindow::SetStatusError(const QString& message) + { + m_statusMessage->setText(QString("%1").arg(message)); + } } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index ca938c3745..8922591580 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -131,7 +131,7 @@ namespace MaterialEditor QSize newDeviceSize = m_materialViewport->size(); AZ_Warning( - "Material Editor", newDeviceSize.width() == width && newDeviceSize.height() == height, + "Material Editor", static_cast(newDeviceSize.width()) == width && static_cast(newDeviceSize.height()) == height, "Resizing the window did not give the expected frame size. Requested %d x %d but got %d x %d.", width, height, newDeviceSize.width(), newDeviceSize.height()); } @@ -237,18 +237,14 @@ namespace MaterialEditor const QString documentPath = GetDocumentPath(documentId); if (!documentPath.isEmpty()) { - const QString status = QString("Document opened: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusMessage(tr("Document opened: %1").arg(documentPath)); } } void MaterialEditorWindow::OnDocumentClosed(const AZ::Uuid& documentId) { RemoveTabForDocumentId(documentId); - - const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document closed: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusMessage(tr("Document closed: %1").arg(GetDocumentPath(documentId))); } void MaterialEditorWindow::OnDocumentModified(const AZ::Uuid& documentId) @@ -284,10 +280,7 @@ namespace MaterialEditor AZStd::string filename; AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); - - const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document saved: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusMessage(tr("Document saved: %1").arg(GetDocumentPath(documentId))); } void MaterialEditorWindow::CreateMenu() @@ -295,7 +288,7 @@ namespace MaterialEditor Base::CreateMenu(); // Generating the main menu manually because it's easier and we will have some dynamic or data driven entries - m_menuFile = m_menuBar->addMenu("&File"); + m_menuFile = menuBar()->addMenu("&File"); m_actionNew = m_menuFile->addAction("&New...", [this]() { CreateMaterialDialog createDialog(this); @@ -330,9 +323,7 @@ namespace MaterialEditor AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::SaveDocument, documentId); if (!result) { - const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document save failed: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusError(tr("Document save failed: %1").arg(GetDocumentPath(documentId))); } }, QKeySequence::Save); @@ -345,8 +336,7 @@ namespace MaterialEditor documentId, AtomToolsFramework::GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); if (!result) { - const QString status = QString("Document save failed: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusError(tr("Document save failed: %1").arg(GetDocumentPath(documentId))); } }, QKeySequence::SaveAs); @@ -359,8 +349,7 @@ namespace MaterialEditor documentId, AtomToolsFramework::GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); if (!result) { - const QString status = QString("Document save failed: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusError(tr("Document save failed: %1").arg(GetDocumentPath(documentId))); } }); @@ -369,8 +358,7 @@ namespace MaterialEditor AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::SaveAllDocuments); if (!result) { - const QString status = QString("Document save all failed."); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusError(tr("Document save all failed")); } }); @@ -406,7 +394,7 @@ namespace MaterialEditor close(); }, QKeySequence::Quit); - m_menuEdit = m_menuBar->addMenu("&Edit"); + m_menuEdit = menuBar()->addMenu("&Edit"); m_actionUndo = m_menuEdit->addAction("&Undo", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); @@ -414,9 +402,7 @@ namespace MaterialEditor AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::Undo); if (!result) { - const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document undo failed: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusError(tr("Document undo failed: %1").arg(GetDocumentPath(documentId))); } }, QKeySequence::Undo); @@ -426,9 +412,7 @@ namespace MaterialEditor AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::Redo); if (!result) { - const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document redo failed: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusError(tr("Document redo failed: %1").arg(GetDocumentPath(documentId))); } }, QKeySequence::Redo); @@ -440,7 +424,7 @@ namespace MaterialEditor }, QKeySequence::Preferences); m_actionSettings->setEnabled(true); - m_menuView = m_menuBar->addMenu("&View"); + m_menuView = menuBar()->addMenu("&View"); m_actionAssetBrowser = m_menuView->addAction("&Asset Browser", [this]() { const AZStd::string label = "Asset Browser"; @@ -480,7 +464,7 @@ namespace MaterialEditor SelectNextTab(); }, Qt::CTRL | Qt::Key_Tab); //QKeySequence::NextChild works as expected but mirroring Previous - m_menuHelp = m_menuBar->addMenu("&Help"); + m_menuHelp = menuBar()->addMenu("&Help"); m_actionHelp = m_menuHelp->addAction("&Help...", [this]() { HelpDialog dialog(this); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/LightingPresetComboBox.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/LightingPresetComboBox.cpp index c034977aac..e0bb59cb82 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/LightingPresetComboBox.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/LightingPresetComboBox.cpp @@ -61,7 +61,7 @@ namespace MaterialEditor auto presetItr = AZStd::find(m_presets.begin(), m_presets.end(), preset); if (presetItr != m_presets.end()) { - setCurrentIndex(AZStd::distance(m_presets.begin(), presetItr)); + setCurrentIndex(static_cast(AZStd::distance(m_presets.begin(), presetItr))); } } @@ -80,7 +80,7 @@ namespace MaterialEditor auto presetItr = AZStd::find(m_presets.begin(), m_presets.end(), preset); if (presetItr != m_presets.end()) { - setItemText(AZStd::distance(m_presets.begin(), presetItr), preset->m_displayName.c_str()); + setItemText(static_cast(AZStd::distance(m_presets.begin(), presetItr)), preset->m_displayName.c_str()); } else { diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/ModelPresetComboBox.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/ModelPresetComboBox.cpp index 30b88f6f47..1e8bfec485 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/ModelPresetComboBox.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/ModelPresetComboBox.cpp @@ -61,7 +61,7 @@ namespace MaterialEditor auto presetItr = AZStd::find(m_presets.begin(), m_presets.end(), preset); if (presetItr != m_presets.end()) { - setCurrentIndex(AZStd::distance(m_presets.begin(), presetItr)); + setCurrentIndex(static_cast(AZStd::distance(m_presets.begin(), presetItr))); } } @@ -80,7 +80,7 @@ namespace MaterialEditor auto presetItr = AZStd::find(m_presets.begin(), m_presets.end(), preset); if (presetItr != m_presets.end()) { - setItemText(AZStd::distance(m_presets.begin(), presetItr), preset->m_displayName.c_str()); + setItemText(static_cast(AZStd::distance(m_presets.begin(), presetItr)), preset->m_displayName.c_str()); } else { diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp index 47432ed83c..05a044db0b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp @@ -6,43 +6,19 @@ * */ -#if !defined(Q_MOC_RUN) #include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#endif - int main(int argc, char** argv) { AzQtComponents::AzQtApplication::InitializeDpiScaling(); MaterialEditor::MaterialEditorApplication app(&argc, &argv); - - auto globalEventFilter = new AzQtComponents::GlobalEventFilter(&app); - app.installEventFilter(globalEventFilter); - - AZ::IO::FixedMaxPath engineRootPath; - if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) + if (app.LaunchLocalServer()) { - settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder); + app.Start(AZ::ComponentApplication::Descriptor{}); + app.exec(); + app.Stop(); } - AzQtComponents::StyleManager styleManager(&app); - styleManager.initialize(&app, engineRootPath); - - app.Start(AZ::ComponentApplication::Descriptor{}); - app.exec(); - app.Stop(); return 0; } diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index 0b4802640b..6354f8beba 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -149,18 +149,14 @@ namespace ShaderManagementConsole const QString documentPath = GetDocumentPath(documentId); if (!documentPath.isEmpty()) { - const QString status = QString("Document opened: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusMessage(tr("Document opened: %1").arg(documentPath)); } } void ShaderManagementConsoleWindow::OnDocumentClosed(const AZ::Uuid& documentId) { RemoveTabForDocumentId(documentId); - - const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document closed: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusMessage(tr("Document closed: %1").arg(GetDocumentPath(documentId))); } void ShaderManagementConsoleWindow::OnDocumentModified(const AZ::Uuid& documentId) @@ -196,10 +192,7 @@ namespace ShaderManagementConsole AZStd::string filename; AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); - - const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document saved: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusMessage(tr("Document saved: %1").arg(GetDocumentPath(documentId))); } void ShaderManagementConsoleWindow::CreateMenu() @@ -207,7 +200,7 @@ namespace ShaderManagementConsole Base::CreateMenu(); // Generating the main menu manually because it's easier and we will have some dynamic or data driven entries - m_menuFile = m_menuBar->addMenu("&File"); + m_menuFile = menuBar()->addMenu("&File"); m_actionOpen = m_menuFile->addAction("&Open...", [this]() { const AZStd::vector assetTypes = { @@ -230,9 +223,7 @@ namespace ShaderManagementConsole AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::SaveDocument, documentId); if (!result) { - const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document save failed: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusError(tr("Document save failed: %1").arg(GetDocumentPath(documentId))); } }, QKeySequence::Save); @@ -245,8 +236,7 @@ namespace ShaderManagementConsole documentId, AtomToolsFramework::GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); if (!result) { - const QString status = QString("Document save failed: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusError(tr("Document save failed: %1").arg(GetDocumentPath(documentId))); } }, QKeySequence::SaveAs); @@ -255,8 +245,7 @@ namespace ShaderManagementConsole AtomToolsFramework::AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::SaveAllDocuments); if (!result) { - const QString status = QString("Document save all failed."); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusError(tr("Document save all failed")); } }); @@ -278,7 +267,7 @@ namespace ShaderManagementConsole m_menuFile->addSeparator(); - m_menuFile->addAction("Run Python...", [this]() { + m_menuFile->addAction("Run &Python...", [this]() { const QString script = QFileDialog::getOpenFileName(this, "Run Script", QString(), QString("*.py")); if (!script.isEmpty()) { @@ -292,7 +281,7 @@ namespace ShaderManagementConsole close(); }, QKeySequence::Quit); - m_menuEdit = m_menuBar->addMenu("&Edit"); + m_menuEdit = menuBar()->addMenu("&Edit"); m_actionUndo = m_menuEdit->addAction("&Undo", [this]() { const AZ::Uuid documentId = GetDocumentIdFromTab(m_tabWidget->currentIndex()); @@ -300,9 +289,7 @@ namespace ShaderManagementConsole AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::Undo); if (!result) { - const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document undo failed: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusError(tr("Document undo failed: %1").arg(GetDocumentPath(documentId))); } }, QKeySequence::Undo); @@ -312,9 +299,7 @@ namespace ShaderManagementConsole AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::Redo); if (!result) { - const QString documentPath = GetDocumentPath(documentId); - const QString status = QString("Document redo failed: %1").arg(documentPath); - m_statusMessage->setText(QString("%1").arg(status)); + SetStatusError(tr("Document redo failed: %1").arg(GetDocumentPath(documentId))); } }, QKeySequence::Redo); @@ -324,7 +309,7 @@ namespace ShaderManagementConsole }, QKeySequence::Preferences); m_actionSettings->setEnabled(false); - m_menuView = m_menuBar->addMenu("&View"); + m_menuView = menuBar()->addMenu("&View"); m_actionAssetBrowser = m_menuView->addAction("&Asset Browser", [this]() { const AZStd::string label = "Asset Browser"; @@ -347,7 +332,7 @@ namespace ShaderManagementConsole SelectNextTab(); }, Qt::CTRL | Qt::Key_Tab); //QKeySequence::NextChild works as expected but mirroring Previous - m_menuHelp = m_menuBar->addMenu("&Help"); + m_menuHelp = menuBar()->addMenu("&Help"); m_actionHelp = m_menuHelp->addAction("&Help...", [this]() { }); diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/main.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/main.cpp index d6f017eee8..8291ce587e 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/main.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/main.cpp @@ -6,43 +6,19 @@ * */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include +#include int main(int argc, char** argv) { AzQtComponents::AzQtApplication::InitializeDpiScaling(); ShaderManagementConsole::ShaderManagementConsoleApplication app(&argc, &argv); - - AZ::IO::FixedMaxPath engineRootPath; - if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) + if (app.LaunchLocalServer()) { - settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder); + app.Start(AZ::ComponentApplication::Descriptor{}); + app.exec(); + app.Stop(); } - auto globalEventFilter = new AzQtComponents::GlobalEventFilter(&app); - app.installEventFilter(globalEventFilter); - - AzQtComponents::StyleManager styleManager(&app); - styleManager.initialize(&app, engineRootPath); - - app.Start({}); - app.exec(); - app.Stop(); return 0; } diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h index bdaf38a64a..ea4dd20250 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.h @@ -43,7 +43,7 @@ namespace AZ }; // Update running statistics with new region data - void RecordRegion(const AZ::RHI::CachedTimeRegion& region, AZStd::thread_id threadId); + void RecordRegion(const AZ::RHI::CachedTimeRegion& region, size_t threadId); void ResetPerFrameStatistics(); @@ -58,7 +58,7 @@ namespace AZ u64 m_invocationsLastFrame = 0; // NOTE: set over unordered_set so the threads can be shown in increasing order in tooltip. - AZStd::set m_executingThreads; + AZStd::set m_executingThreads; AZStd::sys_time_t m_lastFrameTotalTicks = 0; @@ -95,7 +95,7 @@ namespace AZ void Draw(bool& keepDrawing, const AZ::RHI::CpuTimingStatistics& cpuTimingStatistics); private: - static constexpr float RowHeight = 50.0; + static constexpr float RowHeight = 35.0; static constexpr int DefaultFramesToCollect = 50; static constexpr float MediumFrameTimeLimit = 16.6; // 60 fps static constexpr float HighFrameTimeLimit = 33.3; // 30 fps @@ -134,7 +134,7 @@ namespace AZ void DrawThreadSeparator(u64 threadBoundary, u64 maxDepth); // Draw the "Thread XXXXX" label onto the viewport - void DrawThreadLabel(u64 baseRow, AZStd::thread_id threadId); + void DrawThreadLabel(u64 baseRow, size_t threadId); // Draw the vertical lines separating frames in the timeline void DrawFrameBoundaries(); @@ -169,7 +169,9 @@ namespace AZ AZStd::sys_time_t m_viewportEndTick; // Map to store each thread's TimeRegions, individual vectors are sorted by start tick - AZStd::unordered_map> m_savedData; + // note: we use size_t as a proxy for thread_id because native_thread_id_type differs differs from + // platform to platform, which causes problems when deserializing saved captures. + AZStd::unordered_map> m_savedData; // Region color cache AZStd::unordered_map m_regionColorMap; @@ -213,6 +215,11 @@ namespace AZ // Index into the file picker, used to determine which file to load when "Load File" is pressed. int m_currentFileIndex = 0; + + + // --- Loading capture state --- + AZStd::unordered_set m_deserializedStringPool; + AZStd::unordered_set m_deserializedGroupRegionNamePool; }; } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl index 9b4eebf043..638927d601 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -30,19 +31,6 @@ namespace AZ { namespace CpuProfilerImGuiHelper { - // NOTE: Fix build error in case AZStd::thread_id is not of an arithmetic type, and instead a pointer - template::value>::type* = nullptr> - AZStd::string TextThreadId(ThreadId threadId) - { - return AZStd::string::format("Thread: %p", threadId); - } - - template::value>::type* = nullptr> - AZStd::string TextThreadId(ThreadId threadId) - { - return AZStd::string::format("Thread: %zu", static_cast(threadId)); - } - inline float TicksToMs(AZStd::sys_time_t ticks) { // Note: converting to microseconds integer before converting to milliseconds float @@ -231,6 +219,7 @@ namespace AZ m_lastCapturedFilePath = resolvedPath; AZ::Render::ProfilingCaptureRequestBus::Broadcast( &AZ::Render::ProfilingCaptureRequestBus::Events::EndContinuousCpuProfilingCapture, frameDataFilePath); + m_paused = true; } else @@ -447,13 +436,65 @@ namespace AZ inline void ImGuiCpuProfiler::LoadFile() { const IO::Path& pathToLoad = m_cachedCapturePaths[m_currentFileIndex]; - auto res = CpuProfilerImGuiHelper::LoadSavedCpuProfilingStatistics(pathToLoad.String()); - if (!res.IsSuccess()) + auto loadResult = CpuProfilerImGuiHelper::LoadSavedCpuProfilingStatistics(pathToLoad.String()); + if (!loadResult.IsSuccess()) { - AZ_TracePrintf("ImGuiCpuProfiler", "%s", res.GetError().c_str()); + AZ_TracePrintf("ImGuiCpuProfiler", "%s", loadResult.GetError().c_str()); return; } - // TODO ATOM-16022 Parse this data and display it in the visualizer widget. + + AZStd::vector deserializedData = loadResult.TakeValue(); + + // Clear visualizer and statistics view state + m_savedRegionCount = deserializedData.size(); + m_savedData.clear(); + m_paused = true; + AZ::RHI::CpuProfiler::Get()->SetProfilerEnabled(false); + m_frameEndTicks.clear(); + + m_tableData.clear(); + m_groupRegionMap.clear(); + + for (const auto& entry : deserializedData) + { + const auto [groupNameItr, wasGroupNameInserted] = m_deserializedStringPool.emplace(entry.m_groupName.GetCStr()); + const auto [regionNameItr, wasRegionNameInserted] = m_deserializedStringPool.emplace(entry.m_regionName.GetCStr()); + const auto [groupRegionNameItr, wasGroupRegionNameInserted] = + m_deserializedGroupRegionNamePool.emplace(groupNameItr->c_str(), regionNameItr->c_str()); + + const RHI::CachedTimeRegion newRegion(&(*groupRegionNameItr), entry.m_stackDepth, entry.m_startTick, entry.m_endTick); + m_savedData[entry.m_threadId].push_back(newRegion); + + // Since we don't serialize the frame boundaries, we need to use the RPI's OnSystemTick event as a heuristic. + const static Name frameBoundaryName = Name("RPISystem: OnSystemTick"); + if (entry.m_regionName == frameBoundaryName) + { + m_frameEndTicks.push_back(entry.m_endTick); + } + + // Update running statistics + if (!m_groupRegionMap[*groupNameItr].contains(*regionNameItr)) + { + m_groupRegionMap[*groupNameItr][*regionNameItr].m_groupName = *groupNameItr; + m_groupRegionMap[*groupNameItr][*regionNameItr].m_regionName = *regionNameItr; + m_tableData.push_back(&m_groupRegionMap[*groupNameItr][*regionNameItr]); + } + m_groupRegionMap[*groupNameItr][*regionNameItr].RecordRegion(newRegion, entry.m_threadId); + } + + // Update viewport bounds with some added UX fudge factor + m_viewportStartTick = deserializedData.back().m_startTick - 1000; + m_viewportEndTick = deserializedData.back().m_endTick + 1000; + + // Invariant: each vector in m_savedData must be sorted so that we can efficiently cull region data. + for (auto& [threadId, singleThreadData] : m_savedData) + { + AZStd::sort(singleThreadData.begin(), singleThreadData.end(), + [](const TimeRegion& lhs, const TimeRegion& rhs) + { + return lhs.m_startTick < rhs.m_startTick; + }); + } } // -- CPU Visualizer -- @@ -465,7 +506,7 @@ namespace AZ if (ImGui::BeginChild("Options and Statistics", { 0, 0 }, true)) { ImGui::Columns(3, "Options", true); - ImGui::SliderInt("Saved Frames", &m_framesToCollect, 10, 10000, "%d", ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_Logarithmic); + ImGui::SliderInt("Saved Frames", &m_framesToCollect, 10, 20000, "%d", ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_Logarithmic); m_visualizerHighlightFilter.Draw("Find Region"); ImGui::NextColumn(); @@ -631,6 +672,7 @@ namespace AZ // Iterate through the entire TimeRegionMap and copy the data since it will get deleted on the next frame for (const auto& [threadId, singleThreadRegionMap] : timeRegionMap) { + const size_t threadIdHashed = AZStd::hash{}(threadId); // The profiler can sometime return threads without any profiling events when dropping threads, FIXME(ATOM-15949) if (singleThreadRegionMap.size() == 0) { @@ -656,7 +698,7 @@ namespace AZ m_tableData.push_back(&m_groupRegionMap[groupName][regionName]); } - m_groupRegionMap[groupName][regionName].RecordRegion(region, threadId); + m_groupRegionMap[groupName][regionName].RecordRegion(region, threadIdHashed); } } @@ -676,7 +718,7 @@ namespace AZ m_savedRegionCount += newVisualizerData.size(); // Move onto the end of the current thread's saved data, sorted order maintained - AZStd::vector& savedDataVec = m_savedData[threadId]; + AZStd::vector& savedDataVec = m_savedData[threadIdHashed]; savedDataVec.insert( savedDataVec.end(), AZStd::make_move_iterator(newVisualizerData.begin()), AZStd::make_move_iterator(newVisualizerData.end())); } @@ -696,6 +738,12 @@ namespace AZ { AZStd::size_t sizeBeforeRemove = savedRegions.size(); + // Early out to avoid the linear erase_if call + if (savedRegions.size() >= 1 && savedRegions.at(0).m_startTick > deleteBeforeTick) + { + continue; + } + // Use erase_if over plain upper_bound + erase to avoid repeated shifts. erase requires a shift of all elements to the right // for each element that is erased, while erase_if squashes all removes into a single shift which significantly improves perf. AZStd::erase_if( @@ -732,12 +780,19 @@ namespace AZ const float startPixel = ConvertTickToPixelSpace(block.m_startTick, m_viewportStartTick, m_viewportEndTick); const float endPixel = ConvertTickToPixelSpace(block.m_endTick, m_viewportStartTick, m_viewportEndTick); - const ImVec2 startPoint = { startPixel, wy + targetRow * RowHeight }; - const ImVec2 endPoint = { endPixel, wy + targetRow * RowHeight + 40 }; + if (endPixel - startPixel < 0.5f) + { + return; + } + + const ImVec2 startPoint = { startPixel, wy + targetRow * RowHeight + 1}; + const ImVec2 endPoint = { endPixel, wy + (targetRow + 1) * RowHeight }; const ImU32 blockColor = GetBlockColor(block); drawList->AddRectFilled(startPoint, endPoint, blockColor, 0); + drawList->AddLine(startPoint, { endPixel, startPoint.y }, IM_COL32_BLACK, 0.5f); + drawList->AddLine({ startPixel, endPoint.y }, endPoint, IM_COL32_BLACK, 0.5f); // Draw the region name if possible // If the block's current width is too small, we skip drawing the label. @@ -751,17 +806,19 @@ namespace AZ if (regionPixelWidth < textWidth) // Not enough space in the block to draw the whole name, draw clipped text. { - // clipRect appears to only clip when a character is fully outside of its bounds which can lead to overflow - // for now subtract the width of a character const ImVec4 clipRect = { startPoint.x, startPoint.y, endPoint.x - maxCharWidth, endPoint.y }; - const float fontSize = ImGui::GetFont()->FontSize; + // NOTE: RenderText calls do not automatically account for the global scale (which is modified at high DPI) + // so we must adjust for the scale manually. + const float scaleFactor = ImGui::GetIO().FontGlobalScale; + const float fontSize = ImGui::GetFont()->FontSize * scaleFactor; + ImGui::GetFont()->RenderText(drawList, fontSize, startPoint, IM_COL32_WHITE, clipRect, label.c_str(), 0); } else // We have enough space to draw the entire label, draw and center text. { const float remainingWidth = regionPixelWidth - textWidth; - const float offset = remainingWidth * .5; + const float offset = remainingWidth * .5f; drawList->AddText({ startPoint.x + offset, startPoint.y }, IM_COL32_WHITE, label.c_str()); } @@ -815,18 +872,18 @@ namespace AZ auto [wx, wy] = ImGui::GetWindowPos(); wy -= ImGui::GetScrollY(); const float windowWidth = ImGui::GetWindowWidth(); - const float boundaryY = wy + (baseRow + maxDepth + 1) * RowHeight - 5; + const float boundaryY = wy + (baseRow + maxDepth + 1) * RowHeight; - ImGui::GetWindowDrawList()->AddLine({ wx, boundaryY }, { wx + windowWidth, boundaryY }, red, 2.0f); + ImGui::GetWindowDrawList()->AddLine({ wx, boundaryY }, { wx + windowWidth, boundaryY }, red, 1.0f); } - inline void ImGuiCpuProfiler::DrawThreadLabel(u64 baseRow, AZStd::thread_id threadId) + inline void ImGuiCpuProfiler::DrawThreadLabel(u64 baseRow, size_t threadId) { auto [wx, wy] = ImGui::GetWindowPos(); wy -= ImGui::GetScrollY(); - const AZStd::string threadIdText = CpuProfilerImGuiHelper::TextThreadId(threadId.m_id); + const AZStd::string threadIdText = AZStd::string::format("Thread: %zu", threadId); - ImGui::GetWindowDrawList()->AddText({ wx + 10, wy + baseRow * RowHeight + 5 }, IM_COL32_WHITE, threadIdText.c_str()); + ImGui::GetWindowDrawList()->AddText({ wx + 10, wy + baseRow * RowHeight}, IM_COL32_WHITE, threadIdText.c_str()); } inline void ImGuiCpuProfiler::DrawFrameBoundaries() @@ -884,8 +941,10 @@ namespace AZ const float textBeginPixel = lastFrameBoundaryPixel + offset; const float textEndPixel = textBeginPixel + labelWidth; + const float verticalOffset = (ImGui::GetWindowHeight() - ImGui::GetFontSize()) / 2; + // Execution time label - drawList->AddText({ textBeginPixel, wy + ImGui::GetWindowHeight() / 4 }, IM_COL32_WHITE, label.c_str()); + drawList->AddText({ textBeginPixel, wy + verticalOffset }, IM_COL32_WHITE, label.c_str()); // Left side drawList->AddLine( @@ -1043,7 +1102,7 @@ namespace AZ // ---- TableRow impl ---- - inline void TableRow::RecordRegion(const AZ::RHI::CachedTimeRegion& region, AZStd::thread_id threadId) + inline void TableRow::RecordRegion(const AZ::RHI::CachedTimeRegion& region, size_t threadId) { const AZStd::sys_time_t deltaTime = region.m_endTick - region.m_startTick; @@ -1072,7 +1131,7 @@ namespace AZ auto threadString = AZStd::string::format("Executed in %zu threads\n", m_executingThreads.size()); for (const auto& threadId : m_executingThreads) { - threadString.append(CpuProfilerImGuiHelper::TextThreadId(threadId.m_id) + "\n"); + threadString.append(AZStd::string::format("Thread: %zu\n", threadId)); } return threadString; } diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiGpuProfiler.inl b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiGpuProfiler.inl index ec7b30cd3e..9ebd0f7a26 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiGpuProfiler.inl +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiGpuProfiler.inl @@ -834,8 +834,10 @@ namespace AZ { // Check whether it should be sorted by name. const uint32_t sortType = static_cast(m_sortType); + AZ_PUSH_DISABLE_WARNING(4296, "-Wunknown-warning-option") bool sortByName = (sortType >= static_cast(ProfilerSortType::Alphabetical) && (sortType < static_cast(ProfilerSortType::AlphabeticalCount))); + AZ_POP_DISABLE_WARNING if (ImGui::Selectable("Pass Names", sortByName)) { @@ -1011,7 +1013,7 @@ namespace AZ const uint32_t countNumerical = static_cast(count); const uint32_t offset = static_cast(m_sortType) - startNumerical; - if (offset < countNumerical && offset >= 0u) + if (offset < countNumerical) { // Change the sorting order. m_sortType = static_cast(((offset + 1u) % countNumerical) + startNumerical); @@ -1092,8 +1094,8 @@ namespace AZ AZStd::sort(m_tableRows.begin(), m_tableRows.end(), [ascending](const TableRow& lhs, const TableRow& rhs) { - const float lhsSize = lhs.m_sizeInBytes; - const float rhsSize = rhs.m_sizeInBytes; + const float lhsSize = static_cast(lhs.m_sizeInBytes); + const float rhsSize = static_cast(rhs.m_sizeInBytes); return ascending ? lhsSize < rhsSize : lhsSize > rhsSize; }); break; @@ -1107,7 +1109,7 @@ namespace AZ { ImGui::TableSetupColumn("Parent pool"); ImGui::TableSetupColumn("Name"); - ImGui::TableSetupColumn("Size (MB)", 0, 100.0f); + ImGui::TableSetupColumn("Size (MB)"); ImGui::TableSetupColumn("BindFlags", ImGuiTableColumnFlags_NoSort); ImGui::TableHeadersRow(); ImGui::TableNextColumn(); @@ -1133,7 +1135,7 @@ namespace AZ ImGui::TableNextColumn(); ImGui::Text(tableRow.m_bufImgName.GetCStr()); ImGui::TableNextColumn(); - ImGui::Text("%.2f", 1.0f * tableRow.m_sizeInBytes / GpuProfilerImGuiHelper::MB); + ImGui::Text("%.4f", 1.0f * tableRow.m_sizeInBytes / GpuProfilerImGuiHelper::MB); ImGui::TableNextColumn(); ImGui::Text(tableRow.m_bindFlags.c_str()); ImGui::TableNextColumn(); @@ -1271,6 +1273,7 @@ namespace AZ m_nameFilter.Draw("Search"); DrawTable(); } + ImGui::End(); } // --- ImGuiGpuProfiler --- diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/StableDynamicArray.h b/Gems/Atom/Utils/Code/Include/Atom/Utils/StableDynamicArray.h index 454a6d4086..58c2a59cbf 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/StableDynamicArray.h +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/StableDynamicArray.h @@ -130,7 +130,7 @@ namespace AZ template struct StableDynamicArray::Page { - static constexpr size_t InvalidPage = -1; + static constexpr size_t InvalidPage = std::numeric_limits::max(); static constexpr uint64_t FullBits = 0xFFFFFFFFFFFFFFFFull; static constexpr size_t NumUint64_t = ElementsPerPage / 64; diff --git a/Gems/Atom/Utils/Code/Source/ImageComparison.cpp b/Gems/Atom/Utils/Code/Source/ImageComparison.cpp index e226d0b2b4..a17d07ed3f 100644 --- a/Gems/Atom/Utils/Code/Source/ImageComparison.cpp +++ b/Gems/Atom/Utils/Code/Source/ImageComparison.cpp @@ -67,9 +67,9 @@ namespace AZ { // We use the max error from a single channel instead of accumulating the error from each channel. // This normalizes differences so that for example black vs red has the same weight as black vs yellow. - const int16_t diffR = abs(aznumeric_cast(bufferA[i]) - aznumeric_cast(bufferB[i])); - const int16_t diffG = abs(aznumeric_cast(bufferA[i + 1]) - aznumeric_cast(bufferB[i + 1])); - const int16_t diffB = abs(aznumeric_cast(bufferA[i + 2]) - aznumeric_cast(bufferB[i + 2])); + const int16_t diffR = static_cast(abs(aznumeric_cast(bufferA[i]) - aznumeric_cast(bufferB[i]))); + const int16_t diffG = static_cast(abs(aznumeric_cast(bufferA[i + 1]) - aznumeric_cast(bufferB[i + 1]))); + const int16_t diffB = static_cast(abs(aznumeric_cast(bufferA[i + 2]) - aznumeric_cast(bufferB[i + 2]))); const int16_t maxDiff = AZ::GetMax(AZ::GetMax(diffR, diffG), diffB); const float finalDiffNormalized = maxDiff / 255.0f; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h index b9bdce6810..f20b0463d9 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FontTexture.h @@ -39,7 +39,7 @@ namespace AZ void Reset() { m_slotUsage = 0; - m_currentCharacter = ~0; + m_currentCharacter = std::numeric_limits::max(); m_horizontalAdvance = 0; m_characterWidth = 0; m_characterHeight = 0; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h index 8c6cf721b3..271b6810d3 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/GlyphCache.h @@ -46,7 +46,7 @@ namespace AZ void Reset() { m_usage = 0; - m_currentCharacter = ~0; + m_currentCharacter = std::numeric_limits::max(); m_characterWidth = 0; m_characterHeight = 0; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp index 9317cae846..b10edfae2e 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp @@ -1070,7 +1070,7 @@ int AZ::FFont::CreateQuadsForText(const RHI::Viewport& viewport, float x, float uint32_t packedColor = 0xffffffff; { ColorB tempColor = color; - tempColor.a = ((uint32_t) tempColor.a * alphaBlend) >> 8; + tempColor.a = static_cast(((uint32_t) tempColor.a * alphaBlend) >> 8); packedColor = tempColor.pack_argb8888(); //note: this ends up in r,g,b,a order on little-endian machines } @@ -1220,7 +1220,7 @@ void AZ::FFont::WrapText(AZStd::string& result, float maxWidth, const char* str, if (ctx.m_processSpecialChars && ch == '$') { ++pChar; - char nextChar = *pChar; + char nextChar = static_cast(*pChar); if (isdigit(nextChar) || nextChar == 'O' || nextChar == 'o') { @@ -1480,7 +1480,7 @@ bool AZ::FFont::UpdateTexture() return false; } - if (m_fontTexture->GetWidth() != m_fontImage->GetDescriptor().m_size.m_width || m_fontTexture->GetHeight() != m_fontImage->GetDescriptor().m_size.m_height) + if (m_fontTexture->GetWidth() != static_cast(m_fontImage->GetDescriptor().m_size.m_width) || m_fontTexture->GetHeight() != static_cast(m_fontImage->GetDescriptor().m_size.m_height)) { AZ_Assert(false, "AtomFont::FFont:::UpdateTexture size mismatch between texture and image!"); return false; @@ -1516,7 +1516,7 @@ bool AZ::FFont::InitCache() char* p = buf; // precache all [normal] printable characters to the string (missing ones are updated on demand) - for (int i = first; i <= last; ++i) + for (char i = first; i <= last; ++i) { *p++ = i; } diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp index 8c023f9353..053a2eb419 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontRenderer.cpp @@ -235,12 +235,12 @@ int AZ::FontRenderer::GetGlyph(GlyphBitmap* glyphBitmap, int* horizontalAdvance, if (glyphWidth) { - *glyphWidth = m_glyph->bitmap.width; + *glyphWidth = static_cast(m_glyph->bitmap.width); } if (glyphHeight) { - *glyphHeight = m_glyph->bitmap.rows; + *glyphHeight = static_cast(m_glyph->bitmap.rows); } unsigned char* buffer = glyphBitmap->GetBuffer(); diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp index 1ee7f80eda..773b19e740 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FontTexture.cpp @@ -496,8 +496,8 @@ int AZ::FontTexture::UpdateSlot(int slotIndex, uint16_t slotUsage, uint32_t char return 0; } - slot->m_characterWidth = width; - slot->m_characterHeight = height; + slot->m_characterWidth = static_cast(width); + slot->m_characterHeight = static_cast(height); // Add a pixel along width and height to avoid artifacts being rendered // from a previous glyph in this slot due to bilinear filtering. The source @@ -519,8 +519,8 @@ void AZ::FontTexture::CreateGradientSlot() assert(slot->m_currentCharacter == (uint32_t)~0); // 0 needs to be unused spot slot->Reset(); - slot->m_characterWidth = m_cellWidth - 2; - slot->m_characterHeight = m_cellHeight - 2; + slot->m_characterWidth = static_cast(m_cellWidth - 2); + slot->m_characterHeight = static_cast(m_cellHeight - 2); slot->SetNotReusable(); int x = slot->m_textureSlot % m_widthCellCount; @@ -533,7 +533,7 @@ void AZ::FontTexture::CreateGradientSlot() { for (uint32_t dwX = 0; dwX < slot->m_characterWidth; ++dwX) { - buffer[dwX + dwY * m_width] = dwY * 255 / (slot->m_characterHeight - 1); + buffer[dwX + dwY * m_width] = static_cast(dwY * 255 / (slot->m_characterHeight - 1)); } } } diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphBitmap.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphBitmap.cpp index 09bc27783b..395a161b83 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphBitmap.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/GlyphBitmap.cpp @@ -118,7 +118,7 @@ int AZ::GlyphBitmap::Blur(AZ::FontSmoothAmount smoothAmount) colorSum += m_buffer[yOffset + x]; } - m_buffer[yOffset + x] = colorSum >> 2; + m_buffer[yOffset + x] = static_cast(colorSum >> 2); } } } diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp index 40c4f8e48f..45757c2c6c 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp @@ -135,7 +135,7 @@ namespace AZ::Render return; } - m_fpsInterval = AZStd::chrono::seconds(r_fpsCalcInterval); + m_fpsInterval = AZStd::chrono::seconds(static_cast(r_fpsCalcInterval)); UpdateFramerate(); @@ -156,7 +156,7 @@ namespace AZ::Render m_drawParams.m_drawViewportId = viewportContext->GetId(); auto viewportSize = viewportContext->GetViewportSize(); - m_drawParams.m_position = AZ::Vector3(viewportSize.m_width, 0.0f, 1.0f) + AZ::Vector3(r_topRightBorderPadding) * viewportContext->GetDpiScalingFactor(); + m_drawParams.m_position = AZ::Vector3(static_cast(viewportSize.m_width), 0.0f, 1.0f) + AZ::Vector3(r_topRightBorderPadding) * viewportContext->GetDpiScalingFactor(); m_drawParams.m_color = AZ::Colors::White; m_drawParams.m_scale = AZ::Vector2(BaseFontSize); m_drawParams.m_hAlign = AzFramework::TextHorizontalAlignment::Right; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h index 234ea99066..01c87fa2fb 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h @@ -41,12 +41,56 @@ namespace AZ virtual const AZ::Data::AssetId GetMaterialOverride(const MaterialAssignmentId& materialAssignmentId) const = 0; //! Clear material override virtual void ClearMaterialOverride(const MaterialAssignmentId& materialAssignmentId) = 0; - //! Set a material property value override - virtual void SetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const Name& propertyName, const AZStd::any& propertyValue) = 0; - //! Get a material property value override - virtual AZStd::any GetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const Name& propertyName) const = 0; + //! Set a material property override value wrapped by an AZStd::any + virtual void SetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZStd::any& value) = 0; + //! Set a material property override value to a bool + virtual void SetPropertyOverrideBool(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const bool& value) = 0; + //! Set a material property override value to a integer + virtual void SetPropertyOverrideInt32(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const int32_t& value) = 0; + //! Set a material property override value to a unsigned integer + virtual void SetPropertyOverrideUInt32(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const uint32_t& value) = 0; + //! Set a material property override value to a float + virtual void SetPropertyOverrideFloat(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const float& value) = 0; + //! Set a material property override value to a Vector2 + virtual void SetPropertyOverrideVector2(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Vector2& value) = 0; + //! Set a material property override value to a Vector3 + virtual void SetPropertyOverrideVector3(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Vector3& value) = 0; + //! Set a material property override value to a Vector4 + virtual void SetPropertyOverrideVector4(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Vector4& value) = 0; + //! Set a material property override value to a color + virtual void SetPropertyOverrideColor(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Color& value) = 0; + //! Set a material property override value to an image asset + virtual void SetPropertyOverrideImageAsset(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Data::Asset& value) = 0; + //! Set a material property override value to an image instance + virtual void SetPropertyOverrideImageInstance(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Data::Instance& value) = 0; + //! Set a material property override value to a string + virtual void SetPropertyOverrideString(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZStd::string& value) = 0; + //! Get a material property override value wrapped by an AZStd::any + virtual AZStd::any GetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; + //! Get a material property override value as a bool + virtual bool GetPropertyOverrideBool(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; + //! Get a material property override value as an integer + virtual int32_t GetPropertyOverrideInt32(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; + //! Get a material property override value as an unsigned integer + virtual uint32_t GetPropertyOverrideUInt32(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; + //! Get a material property override value as a float + virtual float GetPropertyOverrideFloat(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; + //! Get a material property override value as a Vector2 + virtual AZ::Vector2 GetPropertyOverrideVector2(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; + //! Get a material property override value as a Vector3 + virtual AZ::Vector3 GetPropertyOverrideVector3(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; + //! Get a material property override value as a Vector4 + virtual AZ::Vector4 GetPropertyOverrideVector4(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; + //! Get a material property override value as a Color + virtual AZ::Color GetPropertyOverrideColor(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; + //! Get a material property override value as an image asset + virtual AZ::Data::Asset GetPropertyOverrideImageAsset(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; + //! Get a material property override value as an image instance + virtual AZ::Data::Instance GetPropertyOverrideImageInstance(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; + //! Get a material property override value as a string + virtual AZStd::string GetPropertyOverrideString(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const = 0; //! Clear property override for a specific material assignment - virtual void ClearPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const Name& propertyName) = 0; + virtual void ClearPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) = 0; //! Clear property overrides for a specific material assignment virtual void ClearPropertyOverrides(const MaterialAssignmentId& materialAssignmentId) = 0; //! Clear all property overrides diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/LookModification/LookModificationComponentConfig.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/LookModification/LookModificationComponentConfig.h index 5ee348a052..0bf9e752a2 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/LookModification/LookModificationComponentConfig.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/PostProcess/LookModification/LookModificationComponentConfig.h @@ -39,6 +39,11 @@ namespace AZ void CopySettingsTo(LookModificationSettingsInterface* settings); bool ArePropertiesReadOnly() const { return !m_enabled; } + + bool IsUsingCustomShaper() const { + return m_shaperPresetType == ShaperPresetType::LinearCustomRange + || m_shaperPresetType == ShaperPresetType::Log2CustomRange; + } }; } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp index b90b145320..0a5598a74a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp @@ -535,7 +535,7 @@ namespace AZ::Render void AreaLightComponentController::SetPredictionSampleCount(uint32_t count) { - m_configuration.m_predictionSampleCount = count; + m_configuration.m_predictionSampleCount = static_cast(count); if (m_lightShapeDelegate) { m_lightShapeDelegate->SetPredictionSampleCount(count); @@ -549,7 +549,7 @@ namespace AZ::Render void AreaLightComponentController::SetFilteringSampleCount(uint32_t count) { - m_configuration.m_filteringSampleCount = count; + m_configuration.m_filteringSampleCount = static_cast(count); if (m_lightShapeDelegate) { m_lightShapeDelegate->SetFilteringSampleCount(count); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp index 031d935513..642e50d104 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp @@ -259,7 +259,8 @@ namespace AZ void DirectionalLightComponentController::SetCascadeCount(uint32_t cascadeCount) { - const uint16_t cascadeCount16 = cascadeCount = GetMin(Shadow::MaxNumberOfCascades, GetMax(1, aznumeric_cast(cascadeCount))); + const uint16_t cascadeCount16 = GetMin(static_cast(Shadow::MaxNumberOfCascades), GetMax(1, aznumeric_cast(cascadeCount))); + cascadeCount = cascadeCount16; m_configuration.m_cascadeCount = cascadeCount16; if (m_featureProcessor) { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp index c6e4441d57..91856f7ee5 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp @@ -159,7 +159,7 @@ namespace AZ::Render { if (GetShadowsEnabled() && GetLightHandle().IsValid()) { - GetFeatureProcessor()->SetPredictionSampleCount(GetLightHandle(), count); + GetFeatureProcessor()->SetPredictionSampleCount(GetLightHandle(), static_cast(count)); } } @@ -167,7 +167,7 @@ namespace AZ::Render { if (GetShadowsEnabled() && GetLightHandle().IsValid()) { - GetFeatureProcessor()->SetFilteringSampleCount(GetLightHandle(), count); + GetFeatureProcessor()->SetFilteringSampleCount(GetLightHandle(), static_cast(count)); } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp index edf08ba8c9..b4728c0c38 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp @@ -104,7 +104,7 @@ namespace AZ::Render { if (GetShadowsEnabled() && GetLightHandle().IsValid()) { - GetFeatureProcessor()->SetPredictionSampleCount(GetLightHandle(), count); + GetFeatureProcessor()->SetPredictionSampleCount(GetLightHandle(), static_cast(count)); } } @@ -112,7 +112,7 @@ namespace AZ::Render { if (GetShadowsEnabled() && GetLightHandle().IsValid()) { - GetFeatureProcessor()->SetFilteringSampleCount(GetLightHandle(), count); + GetFeatureProcessor()->SetFilteringSampleCount(GetLightHandle(), static_cast(count)); } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h index 79fddf2611..58d6fa9ab0 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h @@ -19,7 +19,7 @@ namespace AZ { namespace Render { - static const size_t DefaultMaterialSlotIndex = -1; + static const size_t DefaultMaterialSlotIndex = std::numeric_limits::max(); //! Details for a single editable material assignment struct EditorMaterialComponentSlot final diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.cpp index e39f5cfad5..6e1e710282 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -44,7 +45,29 @@ namespace AZ ->Event("GetMaterialOverride", &MaterialComponentRequestBus::Events::GetMaterialOverride) ->Event("ClearMaterialOverride", &MaterialComponentRequestBus::Events::ClearMaterialOverride) ->Event("SetPropertyOverride", &MaterialComponentRequestBus::Events::SetPropertyOverride) + ->Event("SetPropertyOverrideBool", &MaterialComponentRequestBus::Events::SetPropertyOverrideBool) + ->Event("SetPropertyOverrideInt32", &MaterialComponentRequestBus::Events::SetPropertyOverrideInt32) + ->Event("SetPropertyOverrideUInt32", &MaterialComponentRequestBus::Events::SetPropertyOverrideUInt32) + ->Event("SetPropertyOverrideFloat", &MaterialComponentRequestBus::Events::SetPropertyOverrideFloat) + ->Event("SetPropertyOverrideVector2", &MaterialComponentRequestBus::Events::SetPropertyOverrideVector2) + ->Event("SetPropertyOverrideVector3", &MaterialComponentRequestBus::Events::SetPropertyOverrideVector3) + ->Event("SetPropertyOverrideVector4", &MaterialComponentRequestBus::Events::SetPropertyOverrideVector4) + ->Event("SetPropertyOverrideColor", &MaterialComponentRequestBus::Events::SetPropertyOverrideColor) + ->Event("SetPropertyOverrideImageAsset", &MaterialComponentRequestBus::Events::SetPropertyOverrideImageAsset) + ->Event("SetPropertyOverrideImageInstance", &MaterialComponentRequestBus::Events::SetPropertyOverrideImageInstance) + ->Event("SetPropertyOverrideString", &MaterialComponentRequestBus::Events::SetPropertyOverrideString) ->Event("GetPropertyOverride", &MaterialComponentRequestBus::Events::GetPropertyOverride) + ->Event("GetPropertyOverrideBool", &MaterialComponentRequestBus::Events::GetPropertyOverrideBool) + ->Event("GetPropertyOverrideInt32", &MaterialComponentRequestBus::Events::GetPropertyOverrideInt32) + ->Event("GetPropertyOverrideUInt32", &MaterialComponentRequestBus::Events::GetPropertyOverrideUInt32) + ->Event("GetPropertyOverrideFloat", &MaterialComponentRequestBus::Events::GetPropertyOverrideFloat) + ->Event("GetPropertyOverrideVector2", &MaterialComponentRequestBus::Events::GetPropertyOverrideVector2) + ->Event("GetPropertyOverrideVector3", &MaterialComponentRequestBus::Events::GetPropertyOverrideVector3) + ->Event("GetPropertyOverrideVector4", &MaterialComponentRequestBus::Events::GetPropertyOverrideVector4) + ->Event("GetPropertyOverrideColor", &MaterialComponentRequestBus::Events::GetPropertyOverrideColor) + ->Event("GetPropertyOverrideImageAsset", &MaterialComponentRequestBus::Events::GetPropertyOverrideImageAsset) + ->Event("GetPropertyOverrideImageInstance", &MaterialComponentRequestBus::Events::GetPropertyOverrideImageInstance) + ->Event("GetPropertyOverrideString", &MaterialComponentRequestBus::Events::GetPropertyOverrideString) ->Event("ClearPropertyOverride", &MaterialComponentRequestBus::Events::ClearPropertyOverride) ->Event("ClearPropertyOverrides", &MaterialComponentRequestBus::Events::ClearPropertyOverrides) ->Event("ClearAllPropertyOverrides", &MaterialComponentRequestBus::Events::ClearAllPropertyOverrides) @@ -111,7 +134,7 @@ namespace AZ { InitializeMaterialInstance(asset); } - + void MaterialComponentController::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { AZStd::unordered_set propertyOverrides; @@ -186,6 +209,7 @@ namespace AZ for (auto& materialPair : m_configuration.m_materials) { auto& materialAsset = materialPair.second.m_materialAsset; + if (materialAsset.GetId().IsValid() && !Data::AssetBus::MultiHandler::BusIsConnectedId(materialAsset.GetId())) { anyQueued = true; @@ -199,7 +223,7 @@ namespace AZ ReleaseMaterials(); } } - + void MaterialComponentController::InitializeMaterialInstance(const Data::Asset& asset) { bool allReady = true; @@ -331,27 +355,97 @@ namespace AZ } } - void MaterialComponentController::SetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const Name& propertyName, const AZStd::any& propertyValue) + void MaterialComponentController::SetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZStd::any& value) { auto& materialAssignment = m_configuration.m_materials[materialAssignmentId]; // When applying property overrides for the first time, new instance needs to be created in case the current instance is already used somewhere else to keep overrides local if (materialAssignment.m_propertyOverrides.empty()) { - materialAssignment.m_propertyOverrides[propertyName] = propertyValue; + materialAssignment.m_propertyOverrides[AZ::Name(propertyName)] = value; materialAssignment.RebuildInstance(); QueueMaterialUpdateNotification(); } else { - materialAssignment.m_propertyOverrides[propertyName] = propertyValue; + materialAssignment.m_propertyOverrides[AZ::Name(propertyName)] = value; } QueuePropertyChanges(materialAssignmentId); MaterialComponentNotificationBus::Event(m_entityId, &MaterialComponentNotifications::OnMaterialsEdited, m_configuration.m_materials); } - AZStd::any MaterialComponentController::GetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const Name& propertyName) const + void MaterialComponentController::SetPropertyOverrideBool( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const bool& value) + { + SetPropertyOverride(materialAssignmentId, propertyName, AZStd::any(value)); + } + + void MaterialComponentController::SetPropertyOverrideInt32( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const int32_t& value) + { + SetPropertyOverride(materialAssignmentId, propertyName, AZStd::any(value)); + } + + void MaterialComponentController::SetPropertyOverrideUInt32( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const uint32_t& value) + { + SetPropertyOverride(materialAssignmentId, propertyName, AZStd::any(value)); + } + + void MaterialComponentController::SetPropertyOverrideFloat( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const float& value) + { + SetPropertyOverride(materialAssignmentId, propertyName, AZStd::any(value)); + } + + void MaterialComponentController::SetPropertyOverrideVector2( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Vector2& value) + { + SetPropertyOverride(materialAssignmentId, propertyName, AZStd::any(value)); + } + + void MaterialComponentController::SetPropertyOverrideVector3( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Vector3& value) + { + SetPropertyOverride(materialAssignmentId, propertyName, AZStd::any(value)); + } + + void MaterialComponentController::SetPropertyOverrideVector4( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Vector4& value) + { + SetPropertyOverride(materialAssignmentId, propertyName, AZStd::any(value)); + } + + void MaterialComponentController::SetPropertyOverrideColor( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Color& value) + { + SetPropertyOverride(materialAssignmentId, propertyName, AZStd::any(value)); + } + + void MaterialComponentController::SetPropertyOverrideImageAsset( + const MaterialAssignmentId& materialAssignmentId, + const AZStd::string& propertyName, + const AZ::Data::Asset& value) + { + SetPropertyOverride(materialAssignmentId, propertyName, AZStd::any(value)); + } + + void MaterialComponentController::SetPropertyOverrideImageInstance( + const MaterialAssignmentId& materialAssignmentId, + const AZStd::string& propertyName, + const AZ::Data::Instance& value) + { + SetPropertyOverride(materialAssignmentId, propertyName, AZStd::any(value)); + } + + void MaterialComponentController::SetPropertyOverrideString( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZStd::string& value) + { + SetPropertyOverride(materialAssignmentId, propertyName, AZStd::any(value)); + } + + AZStd::any MaterialComponentController::GetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const { const auto materialIt = m_configuration.m_materials.find(materialAssignmentId); if (materialIt == m_configuration.m_materials.end()) @@ -360,17 +454,94 @@ namespace AZ return {}; } - const auto propertyIt = materialIt->second.m_propertyOverrides.find(propertyName); + const auto propertyIt = materialIt->second.m_propertyOverrides.find(AZ::Name(propertyName)); if (propertyIt == materialIt->second.m_propertyOverrides.end()) { - AZ_Error("MaterialComponentController", false, "Property not found: %s.", propertyName.GetCStr()); + AZ_Error("MaterialComponentController", false, "Property not found: %s.", propertyName.c_str()); return {}; } return propertyIt->second; } - void MaterialComponentController::ClearPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const Name& propertyName) + bool MaterialComponentController::GetPropertyOverrideBool( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const + { + const AZStd::any& value = GetPropertyOverride(materialAssignmentId, propertyName); + return !value.empty() && value.is() ? AZStd::any_cast(value) : false; + } + + int32_t MaterialComponentController::GetPropertyOverrideInt32( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const + { + const AZStd::any& value = GetPropertyOverride(materialAssignmentId, propertyName); + return !value.empty() && value.is() ? AZStd::any_cast(value) : 0; + } + + uint32_t MaterialComponentController::GetPropertyOverrideUInt32( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const + { + const AZStd::any& value = GetPropertyOverride(materialAssignmentId, propertyName); + return !value.empty() && value.is() ? AZStd::any_cast(value) : 0; + } + + float MaterialComponentController::GetPropertyOverrideFloat( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const + { + const AZStd::any& value = GetPropertyOverride(materialAssignmentId, propertyName); + return !value.empty() && value.is() ? AZStd::any_cast(value) : 0.0f; + } + + AZ::Vector2 MaterialComponentController::GetPropertyOverrideVector2( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const + { + const AZStd::any& value = GetPropertyOverride(materialAssignmentId, propertyName); + return !value.empty() && value.is() ? AZStd::any_cast(value) : AZ::Vector2::CreateZero(); + } + + AZ::Vector3 MaterialComponentController::GetPropertyOverrideVector3( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const + { + const AZStd::any& value = GetPropertyOverride(materialAssignmentId, propertyName); + return !value.empty() && value.is() ? AZStd::any_cast(value) : AZ::Vector3::CreateZero(); + } + + AZ::Vector4 MaterialComponentController::GetPropertyOverrideVector4( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const + { + const AZStd::any& value = GetPropertyOverride(materialAssignmentId, propertyName); + return !value.empty() && value.is() ? AZStd::any_cast(value) : AZ::Vector4::CreateZero(); + } + + AZ::Color MaterialComponentController::GetPropertyOverrideColor( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const + { + const AZStd::any& value = GetPropertyOverride(materialAssignmentId, propertyName); + return !value.empty() && value.is() ? AZStd::any_cast(value) : AZ::Color::CreateZero(); + } + + AZ::Data::Asset MaterialComponentController::GetPropertyOverrideImageAsset( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const + { + const AZStd::any& value = GetPropertyOverride(materialAssignmentId, propertyName); + return !value.empty() && value.is>() ? AZStd::any_cast>(value) : AZ::Data::Asset(); + } + + AZ::Data::Instance MaterialComponentController::GetPropertyOverrideImageInstance( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const + { + const AZStd::any& value = GetPropertyOverride(materialAssignmentId, propertyName); + return !value.empty() && value.is>() ? AZStd::any_cast>(value) : AZ::Data::Instance(); + } + + AZStd::string MaterialComponentController::GetPropertyOverrideString( + const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const + { + const AZStd::any& value = GetPropertyOverride(materialAssignmentId, propertyName); + return !value.empty() && value.is() ? AZStd::any_cast(value) : AZStd::string(); + } + + void MaterialComponentController::ClearPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) { auto materialIt = m_configuration.m_materials.find(materialAssignmentId); if (materialIt == m_configuration.m_materials.end()) @@ -379,10 +550,10 @@ namespace AZ return; } - auto propertyIt = materialIt->second.m_propertyOverrides.find(propertyName); + auto propertyIt = materialIt->second.m_propertyOverrides.find(AZ::Name(propertyName)); if (propertyIt == materialIt->second.m_propertyOverrides.end()) { - AZ_Error("MaterialComponentController", false, "Property not found: %s.", propertyName.GetCStr()); + AZ_Error("MaterialComponentController", false, "Property not found: %s.", propertyName.c_str()); return; } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.h index de7f991d60..9e59bbef19 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentController.h @@ -57,9 +57,33 @@ namespace AZ const AZ::Data::AssetId GetMaterialOverride(const MaterialAssignmentId& materialAssignmentId) const override; void ClearMaterialOverride(const MaterialAssignmentId& materialAssignmentId) override; - void SetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const Name& propertyName, const AZStd::any& propertyValue) override; - AZStd::any GetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const Name& propertyName) const override; - void ClearPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const Name& propertyName) override; + void SetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZStd::any& value) override; + void SetPropertyOverrideBool(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const bool& value) override; + void SetPropertyOverrideInt32(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const int32_t& value) override; + void SetPropertyOverrideUInt32(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const uint32_t& value) override; + void SetPropertyOverrideFloat(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const float& value) override; + void SetPropertyOverrideVector2(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Vector2& value) override; + void SetPropertyOverrideVector3(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Vector3& value) override; + void SetPropertyOverrideVector4(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Vector4& value) override; + void SetPropertyOverrideColor(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Color& value) override; + void SetPropertyOverrideImageAsset(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Data::Asset& value) override; + void SetPropertyOverrideImageInstance(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZ::Data::Instance& value) override; + void SetPropertyOverrideString(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName, const AZStd::string& value) override; + + AZStd::any GetPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + bool GetPropertyOverrideBool(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + int32_t GetPropertyOverrideInt32(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + uint32_t GetPropertyOverrideUInt32(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + float GetPropertyOverrideFloat(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + AZ::Vector2 GetPropertyOverrideVector2(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + AZ::Vector3 GetPropertyOverrideVector3(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + AZ::Vector4 GetPropertyOverrideVector4(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + AZ::Color GetPropertyOverrideColor(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + AZ::Data::Asset GetPropertyOverrideImageAsset(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + AZ::Data::Instance GetPropertyOverrideImageInstance(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + AZStd::string GetPropertyOverrideString(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) const override; + + void ClearPropertyOverride(const MaterialAssignmentId& materialAssignmentId, const AZStd::string& propertyName) override; void ClearPropertyOverrides(const MaterialAssignmentId& materialAssignmentId) override; void ClearAllPropertyOverrides() override; MaterialPropertyOverrideMap GetPropertyOverrides(const MaterialAssignmentId& materialAssignmentId) const override; @@ -68,11 +92,11 @@ namespace AZ AZ_DISABLE_COPY(MaterialComponentController); - //! Data::AssetBus interface + //! Data::AssetBus overrides... void OnAssetReady(Data::Asset asset) override; void OnAssetReloaded(Data::Asset asset) override; - //! AZ::TickBus interface implementation + // AZ::TickBus overrides... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; void LoadMaterials(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp index 68276a7320..bb38f932fb 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp @@ -442,7 +442,7 @@ namespace AZ RPI::Cullable::LodOverride MeshComponentController::GetLodOverride() const { - return m_meshFeatureProcessor->GetSortKey(m_meshHandle); + return static_cast(m_meshFeatureProcessor->GetSortKey(m_meshHandle)); } void MeshComponentController::SetVisibility(bool visible) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/LookModification/EditorLookModificationComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/LookModification/EditorLookModificationComponent.cpp index a7dfb76e95..310762863a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/LookModification/EditorLookModificationComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/LookModification/EditorLookModificationComponent.cpp @@ -48,33 +48,44 @@ namespace AZ &LookModificationComponentConfig::m_enabled, "Enable look modification", "Enable look modification.") - ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - + ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ->DataElement(AZ::Edit::UIHandlers::Default, &LookModificationComponentConfig::m_colorGradingLut, "Color Grading LUT", "Color grading LUT") - ->ClassElement(Edit::ClassElements::EditorData, "") ->DataElement(Edit::UIHandlers::ComboBox, - &LookModificationComponentConfig::m_shaperPresetType, - "Shaper Type", - "Shaper Type.") - ->EnumAttribute(ShaperPresetType::None, "None") - ->EnumAttribute(ShaperPresetType::Log2_48_nits, "Log2_48_nits") - ->EnumAttribute(ShaperPresetType::Log2_1000_nits, "Log2_1000_nits") - ->EnumAttribute(ShaperPresetType::Log2_2000_nits, "Log2_2000_nits") - ->EnumAttribute(ShaperPresetType::Log2_4000_nits, "Log2_4000_nits") - ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - + &LookModificationComponentConfig::m_shaperPresetType, "Shaper Type", "Shaper Type.") + ->EnumAttribute(ShaperPresetType::None, "None") + ->EnumAttribute(ShaperPresetType::LinearCustomRange, "Linear Custom Range") + ->EnumAttribute(ShaperPresetType::Log2_48Nits, "Log2 48 nits") + ->EnumAttribute(ShaperPresetType::Log2_1000Nits, "Log2 1000 nits") + ->EnumAttribute(ShaperPresetType::Log2_2000Nits, "Log2 2000 nits") + ->EnumAttribute(ShaperPresetType::Log2_4000Nits, "Log2 4000 nits") + ->EnumAttribute(ShaperPresetType::Log2CustomRange, "Log2 Custom Range") + ->EnumAttribute(ShaperPresetType::PqSmpteSt2084, "PQ (SMPTE ST 2084)") + ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::EntireTree) + ->DataElement(AZ::Edit::UIHandlers::Slider, &LookModificationComponentConfig::m_customMinExposure, "Minimum Exposure", "The minimum exposure this LUT supports. Values smaller than this will be clamped to 0.") + ->Attribute(AZ::Edit::Attributes::Min, -50.0f) + ->Attribute(AZ::Edit::Attributes::Max, 0.0f) + ->Attribute(AZ::Edit::Attributes::SoftMin, -20.0f) + ->Attribute(AZ::Edit::Attributes::SoftMax, 0.0f) + ->Attribute(Edit::Attributes::Visibility, &LookModificationComponentConfig::IsUsingCustomShaper) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + ->DataElement(AZ::Edit::UIHandlers::Slider, &LookModificationComponentConfig::m_customMaxExposure, "Maximum Exposure", "The maximum exposure this LUT supports. Values larger than this will be clamped.") + ->Attribute(AZ::Edit::Attributes::Min, 0.0f) + ->Attribute(AZ::Edit::Attributes::Max, 50.0f) + ->Attribute(AZ::Edit::Attributes::SoftMin, 0.0f) + ->Attribute(AZ::Edit::Attributes::SoftMax, 20.0f) + ->Attribute(Edit::Attributes::Visibility, &LookModificationComponentConfig::IsUsingCustomShaper) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ->DataElement(AZ::Edit::UIHandlers::Slider, &LookModificationComponentConfig::m_colorGradingLutIntensity, "LUT Intensity", "Blend intensity of this LUT.") - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) - ->Attribute(AZ::Edit::Attributes::Max, 1.0f) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - ->Attribute(Edit::Attributes::ReadOnly, &LookModificationComponentConfig::ArePropertiesReadOnly) - + ->Attribute(AZ::Edit::Attributes::Min, 0.0f) + ->Attribute(AZ::Edit::Attributes::Max, 1.0f) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + ->Attribute(Edit::Attributes::ReadOnly, &LookModificationComponentConfig::ArePropertiesReadOnly) ->DataElement(AZ::Edit::UIHandlers::Slider, &LookModificationComponentConfig::m_colorGradingLutOverride, "LUT Override", "Blend intensity of this LUT.") - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) - ->Attribute(AZ::Edit::Attributes::Max, 1.0f) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - ->Attribute(Edit::Attributes::ReadOnly, &LookModificationComponentConfig::ArePropertiesReadOnly) + ->Attribute(AZ::Edit::Attributes::Min, 0.0f) + ->Attribute(AZ::Edit::Attributes::Max, 1.0f) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) + ->Attribute(Edit::Attributes::ReadOnly, &LookModificationComponentConfig::ArePropertiesReadOnly) // Overrides ->ClassElement(AZ::Edit::ClassElements::Group, "Overrides") diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SurfaceData/SurfaceDataMeshComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SurfaceData/SurfaceDataMeshComponent.cpp index 3c5d45abc2..be4d5186c8 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SurfaceData/SurfaceDataMeshComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SurfaceData/SurfaceDataMeshComponent.cpp @@ -147,7 +147,7 @@ namespace SurfaceData bool SurfaceDataMeshComponent::DoRayTrace(const AZ::Vector3& inPosition, AZ::Vector3& outPosition, AZ::Vector3& outNormal) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_cacheMutex); @@ -233,7 +233,7 @@ namespace SurfaceData void SurfaceDataMeshComponent::UpdateMeshData() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); bool meshValidBeforeUpdate = false; bool meshValidAfterUpdate = false; diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp index d5a48b900d..e85c2b92e7 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp @@ -161,7 +161,7 @@ namespace AZ const AZ::Color skeletonColor(0.604f, 0.804f, 0.196f, 1.0f); RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments lineArgs; lineArgs.m_verts = m_auxVertices.data(); - lineArgs.m_vertCount = aznumeric_caster(m_auxVertices.size()); + lineArgs.m_vertCount = static_cast(m_auxVertices.size()); lineArgs.m_colors = &skeletonColor; lineArgs.m_colorCount = 1; lineArgs.m_depthTest = RPI::AuxGeomDraw::DepthTest::Off; @@ -202,9 +202,9 @@ namespace AZ RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments lineArgs; lineArgs.m_verts = m_auxVertices.data(); - lineArgs.m_vertCount = aznumeric_caster(m_auxVertices.size()); + lineArgs.m_vertCount = static_cast(m_auxVertices.size()); lineArgs.m_colors = m_auxColors.data(); - lineArgs.m_colorCount = aznumeric_caster(m_auxColors.size()); + lineArgs.m_colorCount = static_cast(m_auxColors.size()); lineArgs.m_depthTest = RPI::AuxGeomDraw::DepthTest::Off; auxGeom->DrawLines(lineArgs); } @@ -861,7 +861,7 @@ namespace AZ // Set the weights for any active masks for (size_t i = 0; i < m_wrinkleMaskWeights.size(); ++i) { - wrinkleMaskObjectSrg->SetConstant(wrinkleMaskWeightsIndex, m_wrinkleMaskWeights[i], aznumeric_caster(i)); + wrinkleMaskObjectSrg->SetConstant(wrinkleMaskWeightsIndex, m_wrinkleMaskWeights[i], static_cast(i)); } AZ_Error("AtomActorInstance", m_wrinkleMaskWeights.size() <= s_maxActiveWrinkleMasks, "The skinning shader supports no more than %d active morph targets with wrinkle masks.", s_maxActiveWrinkleMasks); } diff --git a/Gems/AtomLyIntegration/ImguiAtom/Code/Source/DebugConsole.h b/Gems/AtomLyIntegration/ImguiAtom/Code/Source/DebugConsole.h index bdfc28c34c..d4855306be 100644 --- a/Gems/AtomLyIntegration/ImguiAtom/Code/Source/DebugConsole.h +++ b/Gems/AtomLyIntegration/ImguiAtom/Code/Source/DebugConsole.h @@ -122,7 +122,6 @@ namespace AZ int m_currentHistoryIndex = -1; //!< The current index into the input history when browsing. int m_maxEntriesToDisplay = DefaultMaxEntriesToDisplay; //!< The maximum entries to display. int m_maxInputHistorySize = DefaultMaxInputHistorySize; //!< The maximum input history size. - int m_logLevelToSet = 0; //!< The minimum log level to set (see AZ::LogLevel). bool m_isShowing = false; //!< Is the debug console currently being displayed? bool m_autoScroll = true; //!< Should we auto-scroll as new entries are added? bool m_forceScroll = false; //!< Do we need to force scroll after input entered? diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp index e4933728d4..9a95f8bfa0 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp +++ b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -374,7 +375,7 @@ namespace Audio /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystemImpl_wwise::Update([[maybe_unused]] const float updateIntervalMS) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); if (AK::SoundEngine::IsInitialized()) { @@ -731,7 +732,7 @@ namespace Audio /////////////////////////////////////////////////////////////////////////////////////////////////// EAudioRequestStatus CAudioSystemImpl_wwise::UpdateAudioObject(IATLAudioObjectData* const audioObjectData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); EAudioRequestStatus result = eARS_FAILURE; @@ -1779,8 +1780,8 @@ namespace Audio AK::MemoryMgr::CategoryStats categoryStats; AK::MemoryMgr::GetCategoryStats(memInfo.m_poolId, categoryStats); - memInfo.m_memoryUsed = categoryStats.uUsed; - memInfo.m_peakUsed = categoryStats.uPeakUsed; + memInfo.m_memoryUsed = static_cast(categoryStats.uUsed); + memInfo.m_peakUsed = static_cast(categoryStats.uPeakUsed); memInfo.m_numAllocs = categoryStats.uAllocs; memInfo.m_numFrees = categoryStats.uFrees; } @@ -1789,9 +1790,9 @@ namespace Audio AK::MemoryMgr::GetGlobalStats(globalStats); auto& memInfo = m_debugMemoryInfo.back(); - memInfo.m_memoryReserved = globalStats.uReserved; - memInfo.m_memoryUsed = globalStats.uUsed; - memInfo.m_peakUsed = globalStats.uMax; + memInfo.m_memoryReserved = static_cast(globalStats.uReserved); + memInfo.m_memoryUsed = static_cast(globalStats.uUsed); + memInfo.m_peakUsed = static_cast(globalStats.uMax); // return the memory infos... return m_debugMemoryInfo; diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/FileIOHandler_wwise.cpp b/Gems/AudioEngineWwise/Code/Source/Engine/FileIOHandler_wwise.cpp index 30084565d6..07113e09d3 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/FileIOHandler_wwise.cpp +++ b/Gems/AudioEngineWwise/Code/Source/Engine/FileIOHandler_wwise.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -265,7 +266,7 @@ namespace Audio auto callback = [&transferInfo](AZ::IO::FileRequestHandle request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); AZ::IO::IStreamerTypes::RequestStatus status = AZ::Interface::Get()->GetRequestStatus(request); switch (status) { diff --git a/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp b/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp index b65e690f1b..cdd7d937e3 100644 --- a/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp @@ -138,7 +138,7 @@ namespace AudioControls for (int i = 0; i < size; ++i) { QListWidgetItem* listItem = m_connectionList->item(i); - if (listItem && listItem->data(eMDR_ID).toInt() == middlewareControl->GetId()) + if (listItem && listItem->data(eMDR_ID).toInt() == static_cast(middlewareControl->GetId())) { m_connectionList->clearSelection(); listItem->setSelected(true); diff --git a/Gems/AudioSystem/Code/Source/Engine/ATL.cpp b/Gems/AudioSystem/Code/Source/Engine/ATL.cpp index e6700ea610..ff56300b85 100644 --- a/Gems/AudioSystem/Code/Source/Engine/ATL.cpp +++ b/Gems/AudioSystem/Code/Source/Engine/ATL.cpp @@ -148,7 +148,7 @@ namespace Audio /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioTranslationLayer::Update() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); auto current = AZStd::chrono::system_clock::now(); m_elapsedTime = AZStd::chrono::duration_cast(current - m_lastUpdateTime); @@ -2016,7 +2016,7 @@ namespace Audio /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioTranslationLayer::DrawAudioSystemDebugInfo() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); // ToDo: Update to work with Atom? LYN-3677 /*if (CVars::s_debugDrawOptions.GetRawFlags() != 0) diff --git a/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp b/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp index 7010012e87..91340ca9bb 100644 --- a/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp +++ b/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp @@ -9,6 +9,7 @@ #include +#include #include #include #include @@ -304,7 +305,7 @@ namespace Audio /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioObjectManager::Update(const float fUpdateIntervalMS, const SATLWorldPosition& rListenerPosition) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); m_fTimeSinceLastVelocityUpdateMS += fUpdateIntervalMS; const bool bUpdateVelocity = m_fTimeSinceLastVelocityUpdateMS > s_fVelocityUpdateIntervalMS; @@ -317,7 +318,7 @@ namespace Audio if (pObject->HasActiveEvents()) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Audio, "Inner Per-Object CAudioObjectManager::Update"); + AZ_PROFILE_SCOPE(Audio, "Inner Per-Object CAudioObjectManager::Update"); pObject->Update(fUpdateIntervalMS, rListenerPosition); @@ -936,7 +937,7 @@ namespace Audio void CAudioEventListenerManager::NotifyListener(const SAudioRequestInfo* const pResultInfo) { // This should always be on the main thread! - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); auto found = AZStd::find_if(m_cListeners.begin(), m_cListeners.end(), [pResultInfo](const SAudioEventListener& currentListener) diff --git a/Gems/AudioSystem/Code/Source/Engine/ATLUtils.h b/Gems/AudioSystem/Code/Source/Engine/ATLUtils.h index c1bb8251f9..97266e95c3 100644 --- a/Gems/AudioSystem/Code/Source/Engine/ATLUtils.h +++ b/Gems/AudioSystem/Code/Source/Engine/ATLUtils.h @@ -16,6 +16,7 @@ #include #include #include +#include #define ATL_FLOAT_EPSILON (1.0e-6) diff --git a/Gems/AudioSystem/Code/Source/Engine/AudioInternalInterfaces.h b/Gems/AudioSystem/Code/Source/Engine/AudioInternalInterfaces.h index feb1cd8c0f..35d656c337 100644 --- a/Gems/AudioSystem/Code/Source/Engine/AudioInternalInterfaces.h +++ b/Gems/AudioSystem/Code/Source/Engine/AudioInternalInterfaces.h @@ -769,124 +769,6 @@ namespace Audio return (eStatus == eARS_SUCCESS || eStatus == eARS_FAILURE); } -#if !defined(AUDIO_RELEASE) - // Debug Logging Helper - AZStd::string ToString() - { - static const AZStd::unordered_map managerRequests - { - { eAMRT_INIT_AUDIO_IMPL, "INIT IMPL" }, - { eAMRT_RELEASE_AUDIO_IMPL, "RELEASE IMPL" }, - { eAMRT_RESERVE_AUDIO_OBJECT_ID, "RESERVE OBJECT ID" }, - { eAMRT_CREATE_SOURCE, "CREATE SOURCE" }, - { eAMRT_DESTROY_SOURCE, "DESTROY SOURCE" }, - { eAMRT_PARSE_CONTROLS_DATA, "PARSE CONTROLS" }, - { eAMRT_PARSE_PRELOADS_DATA, "PARSE PRELOADS" }, - { eAMRT_CLEAR_CONTROLS_DATA, "CLEAR CONTROLS" }, - { eAMRT_CLEAR_PRELOADS_DATA, "CLEAR PRELOADS" }, - { eAMRT_PRELOAD_SINGLE_REQUEST, "PRELOAD SINGLE" }, - { eAMRT_UNLOAD_SINGLE_REQUEST, "UNLOAD SINGLE" }, - { eAMRT_UNLOAD_AFCM_DATA_BY_SCOPE, "UNLOAD SCOPE" }, - { eAMRT_REFRESH_AUDIO_SYSTEM, "REFRESH AUDIO SYSTEM" }, - { eAMRT_LOSE_FOCUS, "LOSE FOCUS" }, - { eAMRT_GET_FOCUS, "GET FOCUS" }, - { eAMRT_MUTE_ALL, "MUTE" }, - { eAMRT_UNMUTE_ALL, "UNMUTE" }, - { eAMRT_STOP_ALL_SOUNDS, "STOP ALL" }, - { eAMRT_DRAW_DEBUG_INFO, "DRAW DEBUG" }, - { eAMRT_CHANGE_LANGUAGE, "CHANGE LANGUAGE" }, - { eAMRT_SET_AUDIO_PANNING_MODE, "SET PANNING MODE" }, - }; - static const AZStd::unordered_map callbackRequests - { - { eACMRT_REPORT_STARTED_EVENT, "STARTED EVENT" }, - { eACMRT_REPORT_FINISHED_EVENT, "FINISHED EVENT" }, - { eACMRT_REPORT_FINISHED_TRIGGER_INSTANCE, "FINISHED TRIGGER INSTANCE" }, - }; - static const AZStd::unordered_map listenerRequests - { - { eALRT_SET_POSITION, "SET POSITION" }, - }; - static const AZStd::unordered_map objectRequests - { - { eAORT_PREPARE_TRIGGER, "PREPARE TRIGGER" }, - { eAORT_UNPREPARE_TRIGGER, "UNPREPARE TRIGGER" }, - { eAORT_EXECUTE_TRIGGER, "EXECUTE TRIGGER" }, - { eAORT_STOP_TRIGGER, "STOP TRIGGER" }, - { eAORT_STOP_ALL_TRIGGERS, "STOP ALL" }, - { eAORT_SET_POSITION, "SET POSITION" }, - { eAORT_SET_RTPC_VALUE, "SET RTPC" }, - { eAORT_SET_SWITCH_STATE, "SET SWITCH" }, - { eAORT_SET_ENVIRONMENT_AMOUNT, "SET ENV AMOUNT" }, - { eAORT_RESET_ENVIRONMENTS, "RESET ENVS" }, - { eAORT_RESET_RTPCS, "RESET RTPCS" }, - { eAORT_RELEASE_OBJECT, "RELEASE OBJECT" }, - { eAORT_EXECUTE_SOURCE_TRIGGER, "EXECUTE SOURCE TRIGGER" }, - { eAORT_SET_MULTI_POSITIONS, "SET MULTI POSITIONS" }, - }; - - std::stringstream ss; - - ss << "AudioRequest("; - - if (pData->eRequestType == eART_AUDIO_MANAGER_REQUEST) - { - ss << "AUDIO MANAGER : "; - auto requestStr = managerRequests.at(static_cast(pData.get())->eType); - ss << requestStr.c_str(); - } - - if (pData->eRequestType == eART_AUDIO_CALLBACK_MANAGER_REQUEST) - { - ss << "AUDIO CALLBACK MGR : "; - auto requestStr = callbackRequests.at(static_cast(pData.get())->eType); - ss << requestStr.c_str(); - } - - if (pData->eRequestType == eART_AUDIO_LISTENER_REQUEST) - { - ss << "AUDIO LISTENER : "; - auto requestStr = listenerRequests.at(static_cast(pData.get())->eType); - ss << requestStr.c_str(); - } - if (pData->eRequestType == eART_AUDIO_OBJECT_REQUEST) - { - ss << "AUDIO OBJECT : "; - auto requestStr = objectRequests.at(static_cast(pData.get())->eType); - ss << requestStr.c_str(); - } - - ss << "): ["; - if (nFlags & eARF_PRIORITY_NORMAL) - { - ss << "PRIORITY NORMAL, "; - } - if (nFlags & eARF_PRIORITY_HIGH) - { - ss << "PRIORITY HIGH, "; - } - if (nFlags & eARF_EXECUTE_BLOCKING) - { - ss << "EXECUTE BLOCKING, "; - } - if (nFlags & eARF_SYNC_CALLBACK) - { - ss << "SYNC CALLBACK, "; - } - if (nFlags & eARF_SYNC_FINISHED_CALLBACK) - { - ss << "SYNC FINISHED CALLBACK, "; - } - if (nFlags & eARF_THREAD_SAFE_PUSH) - { - ss << "THREAD SAFE PUSH, "; - } - ss << "]"; - - return AZStd::string(ss.str().c_str()); - } -#endif // !AUDIO_RELEASE - TATLEnumFlagsType nFlags; TAudioObjectID nAudioObjectID; void* pOwner; diff --git a/Gems/AudioSystem/Code/Source/Engine/AudioSystem.cpp b/Gems/AudioSystem/Code/Source/Engine/AudioSystem.cpp index 30d815cbec..af1dfedfaa 100644 --- a/Gems/AudioSystem/Code/Source/Engine/AudioSystem.cpp +++ b/Gems/AudioSystem/Code/Source/Engine/AudioSystem.cpp @@ -115,7 +115,7 @@ namespace Audio void CAudioSystem::PushRequestBlocking(const SAudioRequest& audioRequestData) { // Main Thread! - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); CAudioRequestInternal request(audioRequestData); @@ -201,7 +201,7 @@ namespace Audio void CAudioSystem::InternalUpdate() { // Audio Thread! - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); auto startUpdateTime = AZStd::chrono::system_clock::now(); // stamp the start time @@ -225,7 +225,7 @@ namespace Audio #if !defined(AUDIO_RELEASE) #if defined(PROVIDE_GETNAME_SUPPORT) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Audio, "Sync Debug Name Changes"); + AZ_PROFILE_SCOPE(Audio, "Sync Debug Name Changes"); AZStd::lock_guard lock(m_debugNameStoreMutex); m_debugNameStore.SyncChanges(m_oATL.GetDebugStore()); } @@ -238,7 +238,7 @@ namespace Audio auto elapsedUpdateTime = AZStd::chrono::duration_cast(endUpdateTime - startUpdateTime); if (elapsedUpdateTime < m_targetUpdatePeriod) { - AZ_PROFILE_SCOPE_IDLE(AZ::Debug::ProfileCategory::Audio, "Wait Remaining Time in Update Period"); + AZ_PROFILE_SCOPE(Audio, "Wait Remaining Time in Update Period"); m_processingEvent.try_acquire_for(m_targetUpdatePeriod - elapsedUpdateTime); } } @@ -596,7 +596,7 @@ namespace Audio /////////////////////////////////////////////////////////////////////////////////////////////////// void CAudioSystem::ProcessRequestBlocking(CAudioRequestInternal& request) { - AZ_PROFILE_FUNCTION_STALL(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); if (m_oATL.CanProcessRequests()) { @@ -616,7 +616,7 @@ namespace Audio void CAudioSystem::ProcessRequestThreadSafe(CAudioRequestInternal request) { // Audio Thread! - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::Audio, "Thread-Safe Request: %s", request.ToString().c_str()); + AZ_PROFILE_SCOPE(Audio, "Process Thread-Safe Request"); if (m_oATL.CanProcessRequests()) { @@ -641,7 +641,7 @@ namespace Audio { // Todo: This should handle request priority, use request priority as bus Address and process in priority order. - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::Audio, "Normal Request: %s", request.ToString().c_str()); + AZ_PROFILE_SCOPE(Audio, "Process Normal Request"); AZ_Assert(g_mainThreadId != AZStd::this_thread::get_id(), "AudioSystem::ProcessRequestByPriority - called from Main thread!"); @@ -672,7 +672,7 @@ namespace Audio { if (!(request.nInternalInfoFlags & eARIF_WAITING_FOR_REMOVAL)) { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::Audio, "Blocking Request: %s", request.ToString().c_str()); + AZ_PROFILE_SCOPE(Audio, "Process Blocking Request"); if (request.eStatus == eARS_NONE) { diff --git a/Gems/AudioSystem/Code/Source/Engine/FileCacheManager.cpp b/Gems/AudioSystem/Code/Source/Engine/FileCacheManager.cpp index f1a360fd7d..791c86eba8 100644 --- a/Gems/AudioSystem/Code/Source/Engine/FileCacheManager.cpp +++ b/Gems/AudioSystem/Code/Source/Engine/FileCacheManager.cpp @@ -9,6 +9,7 @@ #include +#include #include #include #include @@ -61,7 +62,7 @@ namespace Audio /////////////////////////////////////////////////////////////////////////////////////////////// void CFileCacheManager::Update() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); AudioFileCacheManagerNotficationBus::ExecuteQueuedEvents(); UpdatePreloadRequestsStatus(); @@ -538,7 +539,7 @@ namespace Audio bool CFileCacheManager::FinishCachingFileInternal(CATLAudioFileEntry* const audioFileEntry, [[maybe_unused]] AZ::IO::SizeType bytesRead, AZ::IO::IStreamerTypes::RequestStatus requestState) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); bool success = false; audioFileEntry->m_asyncStreamRequest.reset(); @@ -640,7 +641,7 @@ namespace Audio /////////////////////////////////////////////////////////////////////////////////////////////// bool CFileCacheManager::AllocateMemoryBlockInternal(CATLAudioFileEntry* const audioFileEntry) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); // Must not have valid memory yet. AZ_Assert(!audioFileEntry->m_memoryBlock, "FileCacheManager AllocateMemoryBlockInternal - Memory appears to be set already!"); @@ -786,7 +787,7 @@ namespace Audio const bool overrideUseCount /* = false */, const size_t useCount /* = 0 */) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); bool success = false; @@ -842,7 +843,7 @@ namespace Audio audioFileEntry->m_asyncStreamRequest, [this](AZ::IO::FileRequestHandle request) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Audio); + AZ_PROFILE_FUNCTION(Audio); AudioFileCacheManagerNotficationBus::QueueBroadcast( &AudioFileCacheManagerNotficationBus::Events::FinishAsyncStreamRequest, request); diff --git a/Gems/AudioSystem/Code/Tests/AudioSystemTest.cpp b/Gems/AudioSystem/Code/Tests/AudioSystemTest.cpp index 70d9dec330..ba1603d2e2 100644 --- a/Gems/AudioSystem/Code/Tests/AudioSystemTest.cpp +++ b/Gems/AudioSystem/Code/Tests/AudioSystemTest.cpp @@ -589,7 +589,7 @@ TEST(AudioFlagsTest, AudioFlags_OneFlag_OneFlagIsSet) { const AZ::u8 flagBit = 1 << 4; Audio::Flags testFlags(flagBit); - EXPECT_FALSE(testFlags.AreAnyFlagsActive(~flagBit)); + EXPECT_FALSE(testFlags.AreAnyFlagsActive(static_cast(~flagBit))); EXPECT_TRUE(testFlags.AreAnyFlagsActive(flagBit)); EXPECT_TRUE(testFlags.AreAnyFlagsActive(flagBit | 1)); EXPECT_TRUE(testFlags.AreAllFlagsActive(flagBit)); @@ -603,7 +603,7 @@ TEST(AudioFlagsTest, AudioFlags_MultipleFlags_MultipleFlagsAreSet) { const AZ::u8 flagBits = (1 << 5) | (1 << 2) | (1 << 3); Audio::Flags testFlags(flagBits); - EXPECT_FALSE(testFlags.AreAnyFlagsActive(~flagBits)); + EXPECT_FALSE(testFlags.AreAnyFlagsActive(static_cast(~flagBits))); EXPECT_TRUE(testFlags.AreAnyFlagsActive(flagBits)); EXPECT_TRUE(testFlags.AreAllFlagsActive(flagBits)); EXPECT_FALSE(testFlags.AreAllFlagsActive(flagBits | 1)); diff --git a/Gems/BarrierInput/Code/Source/BarrierInputClient.cpp b/Gems/BarrierInput/Code/Source/BarrierInputClient.cpp index 495ef88467..e6d5399561 100644 --- a/Gems/BarrierInput/Code/Source/BarrierInputClient.cpp +++ b/Gems/BarrierInput/Code/Source/BarrierInputClient.cpp @@ -55,11 +55,35 @@ namespace BarrierInput void Eat(int len) { data += len; } void InsertString(const char* str) { int len = static_cast(strlen(str)); memcpy(end, str, len); end += len; } - void InsertU32(int a) { end[0] = a >> 24; end[1] = a >> 16; end[2] = a >> 8; end[3] = a; end += 4; } - void InsertU16(int a) { end[0] = a >> 8; end[1] = a; end += 2; } - void InsertU8(int a) { end[0] = a; end += 1; } + void InsertU32(int a) + { + end[0] = static_cast(a >> 24); + end[1] = static_cast(a >> 16); + end[2] = static_cast(a >> 8); + end[3] = static_cast(a); + end += 4; + } + void InsertU16(int a) + { + end[0] = static_cast(a >> 8); + end[1] = static_cast(a); + end += 2; + } + void InsertU8(int a) + { + end[0] = static_cast(a); + end += 1; + } void OpenPacket() { packet = end; end += 4; } - void ClosePacket() { int len = GetLength() - sizeof(AZ::u32); packet[0] = len >> 24; packet[1] = len >> 16; packet[2] = len >> 8; packet[3] = len; packet = NULL; } + void ClosePacket() + { + int len = GetLength() - sizeof(AZ::u32); + packet[0] = static_cast(len >> 24); + packet[1] = static_cast(len >> 16); + packet[2] = static_cast(len >> 8); + packet[3] = static_cast(len); + packet = nullptr; + } }; enum ArgType @@ -381,7 +405,7 @@ namespace BarrierInput if (AZ::AzSock::IsAzSocketValid(m_socket)) { AZ::AzSock::AzSocketAddress socketAddress; - if (socketAddress.SetAddress(m_serverHostName.c_str(), m_connectionPort)) + if (socketAddress.SetAddress(m_serverHostName.c_str(), static_cast(m_connectionPort))) { const int result = AZ::AzSock::Connect(m_socket, socketAddress); if (!AZ::AzSock::SocketErrorOccured(result)) diff --git a/Gems/BarrierInput/Code/Source/BarrierInputKeyboard.cpp b/Gems/BarrierInput/Code/Source/BarrierInputKeyboard.cpp index 5e486df680..93c485a790 100644 --- a/Gems/BarrierInput/Code/Source/BarrierInputKeyboard.cpp +++ b/Gems/BarrierInput/Code/Source/BarrierInputKeyboard.cpp @@ -147,7 +147,7 @@ namespace BarrierInput { inputChannelId = InputChannelIdByScanCodeTable[scanCode]; } - else if (0 <= (scanCode - 0x100) && scanCode < InputChannelIdByScanCodeWithExtendedPrefixTable.size()) + else if (0x100 <= scanCode && scanCode < InputChannelIdByScanCodeWithExtendedPrefixTable.size()) { inputChannelId = InputChannelIdByScanCodeWithExtendedPrefixTable[scanCode - 0x100]; } diff --git a/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp b/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp index d05a679733..ec6e7bbbb9 100644 --- a/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp +++ b/Gems/Blast/Code/Source/Components/BlastFamilyComponent.cpp @@ -187,7 +187,7 @@ namespace Blast void BlastFamilyComponent::Activate() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); + AZ_PROFILE_FUNCTION(System); AZ_Assert(m_blastAsset.GetId().IsValid(), "BlastFamilyComponent created with invalid blast asset."); @@ -199,7 +199,7 @@ namespace Blast void BlastFamilyComponent::Deactivate() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); + AZ_PROFILE_FUNCTION(System); // cleanup collision handlers for (auto& itr : m_collisionHandlers) @@ -216,7 +216,7 @@ namespace Blast void BlastFamilyComponent::Spawn() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); if (!m_blastAsset.IsReady()) { @@ -297,7 +297,7 @@ namespace Blast void BlastFamilyComponent::Despawn() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); m_isSpawned = false; @@ -414,7 +414,7 @@ namespace Blast void BlastFamilyComponent::OnCollisionBegin(const AzPhysics::CollisionEvent& collisionEvent) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); for (const auto* body : {collisionEvent.m_body1, collisionEvent.m_body2}) { @@ -493,7 +493,7 @@ namespace Blast void BlastFamilyComponent::ApplyStressDamage() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); if (m_solver) { @@ -589,7 +589,7 @@ namespace Blast // Update positions of entities with render meshes corresponding to their right dynamic bodies. void BlastFamilyComponent::SyncMeshes() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); if (m_actorRenderManager) { diff --git a/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp b/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp index bee94ed116..711d3a0087 100644 --- a/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp +++ b/Gems/Blast/Code/Source/Components/BlastSystemComponent.cpp @@ -112,7 +112,7 @@ namespace Blast void BlastSystemComponent::Activate() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); + AZ_PROFILE_FUNCTION(System); auto blastAssetHandler = aznew BlastAssetHandler(); blastAssetHandler->Register(); m_assetHandlers.emplace_back(blastAssetHandler); @@ -141,7 +141,7 @@ namespace Blast void BlastSystemComponent::Deactivate() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); + AZ_PROFILE_FUNCTION(System); CrySystemEventBus::Handler::BusDisconnect(); AZ::TickBus::Handler::BusDisconnect(); BlastSystemRequestBus::Handler::BusDisconnect(); @@ -185,7 +185,7 @@ namespace Blast void BlastSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); AZ::JobCompletion jobCompletion; @@ -226,18 +226,18 @@ namespace Blast for (auto& group : m_groups) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "ExtGroupTaskManager::process"); + AZ_PROFILE_SCOPE(Physics, "ExtGroupTaskManager::process"); group.m_extGroupTaskManager->process(); } for (auto& group : m_groups) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "ExtGroupTaskManager::wait"); + AZ_PROFILE_SCOPE(Physics, "ExtGroupTaskManager::wait"); group.m_extGroupTaskManager->wait(); } // Clean up damage descriptions and program params now that groups have run. { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "BlastSystemComponent::OnTick::Cleanup"); + AZ_PROFILE_SCOPE(Physics, "BlastSystemComponent::OnTick::Cleanup"); m_radialDamageDescs.clear(); m_capsuleDamageDescs.clear(); m_shearDamageDescs.clear(); @@ -248,7 +248,7 @@ namespace Blast if (gEnv && m_debugRenderMode) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "BlastSystemComponent::OnTick::DebugRender"); + AZ_PROFILE_SCOPE(Physics, "BlastSystemComponent::OnTick::DebugRender"); DebugRenderBuffer buffer; BlastFamilyComponentRequestBus::Broadcast( &BlastFamilyComponentRequests::FillDebugRenderBuffer, buffer, m_debugRenderMode); @@ -428,12 +428,12 @@ namespace Blast void BlastSystemComponent::AZBlastProfilerCallback::zoneStart(const char* eventName) { - AZ_PROFILE_EVENT_BEGIN(AZ::Debug::ProfileCategory::Physics, eventName); + AZ_PROFILE_BEGIN(Physics, eventName); } void BlastSystemComponent::AZBlastProfilerCallback::zoneEnd() { - AZ_PROFILE_EVENT_END(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_END(); } static void CmdToggleBlastDebugVisualization(IConsoleCmdArgs* args) diff --git a/Gems/Blast/Code/Source/Editor/EditorBlastFamilyComponent.cpp b/Gems/Blast/Code/Source/Editor/EditorBlastFamilyComponent.cpp index 58f28ed32a..3bc6da4297 100644 --- a/Gems/Blast/Code/Source/Editor/EditorBlastFamilyComponent.cpp +++ b/Gems/Blast/Code/Source/Editor/EditorBlastFamilyComponent.cpp @@ -96,7 +96,7 @@ namespace Blast void EditorBlastFamilyComponent::Activate() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); + AZ_PROFILE_FUNCTION(System); if (m_blastAsset.GetId().IsValid()) { @@ -107,7 +107,7 @@ namespace Blast void EditorBlastFamilyComponent::Deactivate() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); + AZ_PROFILE_FUNCTION(System); AZ::Data::AssetBus::MultiHandler::BusDisconnect(); } diff --git a/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.cpp b/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.cpp index 23ec5ae524..9d0e4fe2ff 100644 --- a/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.cpp +++ b/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.cpp @@ -86,7 +86,7 @@ namespace Blast void EditorBlastMeshDataComponent::Activate() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); + AZ_PROFILE_FUNCTION(System); OnMeshAssetsChanged(); m_meshFeatureProcessor = @@ -100,7 +100,7 @@ namespace Blast void EditorBlastMeshDataComponent::Deactivate() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); + AZ_PROFILE_FUNCTION(System); EditorComponentBase::Deactivate(); AZ::Render::MaterialComponentNotificationBus::Handler::BusDisconnect(GetEntityId()); AZ::TransformNotificationBus::Handler::BusDisconnect(GetEntityId()); diff --git a/Gems/Blast/Code/Source/Family/ActorRenderManager.cpp b/Gems/Blast/Code/Source/Family/ActorRenderManager.cpp index 98ea7d6741..aca1e94d16 100644 --- a/Gems/Blast/Code/Source/Family/ActorRenderManager.cpp +++ b/Gems/Blast/Code/Source/Family/ActorRenderManager.cpp @@ -33,7 +33,7 @@ namespace Blast void ActorRenderManager::OnActorCreated(const BlastActor& actor) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); const AZStd::vector& chunkIndices = actor.GetChunkIndices(); @@ -47,7 +47,7 @@ namespace Blast void ActorRenderManager::OnActorDestroyed(const BlastActor& actor) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); const AZStd::vector& chunkIndices = actor.GetChunkIndices(); @@ -62,7 +62,7 @@ namespace Blast { // It is more natural to have chunk entities be transform children of rigid body entity, // however having them separate and manually synchronizing transform is more efficient. - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); for (auto chunkId = 0u; chunkId < m_chunkCount; ++chunkId) { diff --git a/Gems/Blast/Code/Source/Family/ActorTracker.cpp b/Gems/Blast/Code/Source/Family/ActorTracker.cpp index 4c81c2d934..e441e7a074 100644 --- a/Gems/Blast/Code/Source/Family/ActorTracker.cpp +++ b/Gems/Blast/Code/Source/Family/ActorTracker.cpp @@ -6,6 +6,7 @@ * */ +#include #include #include #include @@ -46,7 +47,7 @@ namespace Blast BlastActor* ActorTracker::FindClosestActor(const AZ::Vector3& position) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); const auto candidate = std::min_element( m_actors.begin(), m_actors.end(), diff --git a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp index 2690a12f24..56c785b310 100644 --- a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp +++ b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp @@ -122,7 +122,7 @@ namespace Blast void BlastFamilyImpl::HandleEvents(const Nv::Blast::TkEvent* events, uint32_t eventCount) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); AZStd::vector newActors; AZStd::unordered_set actorsToDelete; @@ -150,7 +150,7 @@ namespace Blast const Nv::Blast::TkSplitEvent* splitEvent, AZStd::vector& newActors, AZStd::unordered_set& actorsToDelete) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); AZ_Assert(splitEvent, "Received null TkSplitEvent from the Blast library."); if (!splitEvent) @@ -256,7 +256,7 @@ namespace Blast void BlastFamilyImpl::CreateActors(const AZStd::vector& actorDescs) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); for (auto& actorDesc : actorDescs) { @@ -268,7 +268,7 @@ namespace Blast void BlastFamilyImpl::DestroyActors(const AZStd::unordered_set& actors) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); for (const auto actor : actors) { @@ -294,14 +294,14 @@ namespace Blast void BlastFamilyImpl::DispatchActorCreated(const BlastActor& actor) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); m_listener->OnActorCreated(*this, actor); } void BlastFamilyImpl::DispatchActorDestroyed(const BlastActor& actor) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); m_listener->OnActorDestroyed(*this, actor); } diff --git a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp index 87624b1c8d..7a8d6be020 100644 --- a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp +++ b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp @@ -125,7 +125,7 @@ namespace Camera }); if (cameraIt != m_cameraItems.end()) { - int listIndex = cameraIt - m_cameraItems.begin(); + int listIndex = static_cast(cameraIt - m_cameraItems.begin()); beginRemoveRows(QModelIndex(), listIndex, listIndex); m_cameraItems.erase(cameraIt); endRemoveRows(); diff --git a/Gems/CrashReporting/Code/Platform/Windows/GameCrashUploader_windows.cpp b/Gems/CrashReporting/Code/Platform/Windows/GameCrashUploader_windows.cpp index f65d98d7da..c4ddb50c53 100644 --- a/Gems/CrashReporting/Code/Platform/Windows/GameCrashUploader_windows.cpp +++ b/Gems/CrashReporting/Code/Platform/Windows/GameCrashUploader_windows.cpp @@ -7,16 +7,11 @@ */ #include +#include #include #include -#include -#include -#include - -#pragma warning(disable : 4996) - namespace O3de { @@ -24,21 +19,26 @@ namespace O3de { if (!m_noConfirmation) { +#if AZ_TRAIT_USE_SECURE_CRT_FUNCTIONS + char noConfirmation[64]{}; + size_t variableSize = 0; + getenv_s(&variableSize, noConfirmation, AZ_ARRAY_SIZE(noConfirmation), "LY_NO_CONFIRM"); + if (variableSize == 0) +#else const char* noConfirmation = getenv("LY_NO_CONFIRM"); if (noConfirmation == nullptr) +#endif + { - - std::wstring sendDialogMessage; - - std::wstring_convert> converter; - sendDialogMessage = converter.from_bytes(m_executableName); + AZStd::wstring sendDialogMessage; + AZStd::to_wstring(sendDialogMessage, m_executableName.c_str()); sendDialogMessage += L" has encountered a fatal error. We're sorry for the inconvenience.\n\nA crash debugging file has been created at:\n"; - sendDialogMessage += report.file_path.value(); + sendDialogMessage += report.file_path.value().c_str(); sendDialogMessage += L"\n\nIf you are willing to submit this file to Amazon it will help us improve the Lumberyard experience. We will treat this report as confidential.\n\nWould you like to send the error report?"; int msgboxID = MessageBoxW( - NULL, + nullptr, sendDialogMessage.data(), L"Send Error Report", (MB_ICONEXCLAMATION | MB_YESNO | MB_SYSTEMMODAL) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.cpp index b6a3870073..8396ad7b83 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.cpp @@ -497,13 +497,13 @@ namespace CommandSystem } // verify port ranges - if (m_sourcePort >= static_cast(sourceNode->GetOutputPorts().size()) || m_sourcePort < 0) + if (m_sourcePort >= static_cast(sourceNode->GetOutputPorts().size())) { outResult = AZStd::string::format("The output port number is not valid for the given node. Node '%s' only has %zu output ports.", sourceNode->GetName(), sourceNode->GetOutputPorts().size()); return false; } - if (m_targetPort >= static_cast(targetNode->GetInputPorts().size()) || m_targetPort < 0) + if (m_targetPort >= static_cast(targetNode->GetInputPorts().size())) { outResult = AZStd::string::format("The input port number is not valid for the given node. Node '%s' only has %zu input ports.", targetNode->GetName(), targetNode->GetInputPorts().size()); return false; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index 5a8fcda907..5a4ca95670 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -1115,7 +1115,7 @@ namespace EMotionFX void ActorInstance::EnableAllNodes() { m_enabledNodes.resize(m_actor->GetNumNodes()); - std::iota(m_enabledNodes.begin(), m_enabledNodes.end(), 0); + std::iota(m_enabledNodes.begin(), m_enabledNodes.end(), uint16(0)); } // disable all nodes diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphBindPoseNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphBindPoseNode.h index 042799192d..2d83d21d0d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphBindPoseNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphBindPoseNode.h @@ -28,12 +28,12 @@ namespace EMotionFX AZ_CLASS_ALLOCATOR_DECL // - enum + enum : uint16 { OUTPUTPORT_RESULT = 0 }; - enum + enum : uint16 { PORTID_OUTPUT_POSE = 0 }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.h index a07bbc625c..692b81b70e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.h @@ -32,7 +32,7 @@ namespace EMotionFX AZ_RTTI(AnimGraphMotionNode, "{B8B8AAE6-E532-4BF8-898F-3D40AA41BC82}", AnimGraphNode) AZ_CLASS_ALLOCATOR_DECL - enum + enum : uint16 { INPUTPORT_PLAYSPEED = 0, INPUTPORT_INPLACE = 1, @@ -41,7 +41,7 @@ namespace EMotionFX OUTPUTPORT_MOTION = 1 }; - enum + enum : uint16 { PORTID_INPUT_PLAYSPEED = 0, PORTID_INPUT_INPLACE = 1, diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.h index 9a9b51b5d1..991fb03472 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.h @@ -26,7 +26,7 @@ namespace EMotionFX using WeightedMaskEntry = AZStd::pair; - enum + enum : uint16 { INPUTPORT_POSE_A = 0, INPUTPORT_POSE_B = 1, @@ -34,7 +34,7 @@ namespace EMotionFX OUTPUTPORT_POSE = 0 }; - enum + enum : uint16 { PORTID_INPUT_POSE_A = 0, PORTID_INPUT_POSE_B = 1, diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.h index 72d6ad120c..4f4b8a7ac3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.h @@ -49,7 +49,7 @@ namespace EMotionFX AZ_RTTI(BlendTreeBlendNNode, "{CBFFDE41-008D-45A1-AC2A-E9A25C8CE62A}", AnimGraphNode) AZ_CLASS_ALLOCATOR_DECL - enum + enum : uint16 { INPUTPORT_POSE_0 = 0, INPUTPORT_POSE_1 = 1, @@ -65,7 +65,7 @@ namespace EMotionFX OUTPUTPORT_POSE = 0 }; - enum + enum : uint16 { PORTID_INPUT_POSE_0 = 0, PORTID_INPUT_POSE_1 = 1, diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatConditionNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatConditionNode.h index 756f6a4bab..fc922934ed 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatConditionNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatConditionNode.h @@ -26,7 +26,7 @@ namespace EMotionFX AZ_CLASS_ALLOCATOR_DECL // - enum + enum : uint16 { INPUTPORT_X = 0, INPUTPORT_Y = 1, @@ -34,7 +34,7 @@ namespace EMotionFX OUTPUTPORT_BOOL = 1 }; - enum + enum : uint16 { PORTID_INPUT_X = 0, PORTID_INPUT_Y = 1, diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.h index e39cd7258e..29b497457e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.h @@ -27,7 +27,7 @@ namespace EMotionFX AZ_RTTI(BlendTreeTwoLinkIKNode, "{0C3E8B7F-F810-47A6-B1A9-27BD4E4B5500}", AnimGraphNode) AZ_CLASS_ALLOCATOR_DECL - enum + enum : uint16 { INPUTPORT_POSE = 0, INPUTPORT_GOALPOS = 1, @@ -37,7 +37,7 @@ namespace EMotionFX OUTPUTPORT_POSE = 0 }; - enum + enum : uint16 { PORTID_INPUT_POSE = 0, PORTID_INPUT_GOALPOS = 1, diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp index 82b06c8171..300543c896 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp @@ -190,7 +190,7 @@ namespace EMotionFX // update void EMotionFXManager::Update(float timePassedInSeconds) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Animation, "EMotionFXManager::Update"); + AZ_PROFILE_SCOPE(Animation, "EMotionFXManager::Update"); m_debugDraw->Clear(); m_recorder->UpdatePlayMode(timePassedInSeconds); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h index c2d776bcdb..ebd65f833a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h @@ -64,7 +64,7 @@ namespace EMotionFX * VertexAttributeLayerAbstractData::GetType() values for the vertex data * Use these with the Mesh::FindVertexData() and Mesh::FindOriginalVertexData() methods. */ - enum + enum : uint32 { ATTRIB_POSITIONS = 0, /**< Vertex positions. Typecast to AZ::Vector3. Positions are always exist. */ ATTRIB_NORMALS = 1, /**< Vertex normals. Typecast to AZ::Vector3. Normals are always exist. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h index f41cf29c79..8ca1ab570f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h @@ -20,6 +20,9 @@ #include #include +#if defined GetCurrentTime +#undef GetCurrentTime +#endif namespace EMotionFX { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp index 6f07936fe7..8b7fbad316 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp @@ -165,7 +165,7 @@ namespace EMotionFX AZ::JobContext* jobContext = nullptr; AZ::Job* job = AZ::CreateJobFunction([this, timePassedInSeconds, actorInstance]() { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Animation, "MultiThreadScheduler::Execute::ActorInstanceUpdateJob"); + AZ_PROFILE_SCOPE(Animation, "MultiThreadScheduler::Execute::ActorInstanceUpdateJob"); const AZ::u32 threadIndex = AZ::JobContext::GetGlobalContext()->GetJobManager().GetWorkerThreadId(); actorInstance->SetThreadIndex(threadIndex); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.cpp index d84bbebbc6..728ceb059b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.cpp @@ -114,7 +114,7 @@ namespace EMStudio } // Set the current history index in case the user called undo. - m_list->setCurrentRow(commandManager->GetHistoryIndex()); + m_list->setCurrentRow(static_cast(commandManager->GetHistoryIndex())); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModel.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModel.cpp index 6e68a761de..a6733ee614 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModel.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModel.cpp @@ -562,9 +562,9 @@ namespace EMStudio ModelItemData modelItemData(graphInstance, animGraphObject); AZStd::pair itModelItemData = m_modelItemDataSet.equal_range(&modelItemData); - for (ModelItemDataSet::const_iterator it = itModelItemData.first; it != itModelItemData.second; ++it) + if (itModelItemData.first != itModelItemData.second) { - ModelItemData* modelItemData2 = *it; + ModelItemData* modelItemData2 = *itModelItemData.first; return createIndex(modelItemData2->m_row, 0, modelItemData2); } return QModelIndex(); @@ -590,9 +590,9 @@ namespace EMStudio // Find the model index ModelItemData modelItemData(animGraphInstance, animGraphObject); AZStd::pair itModelItemData = m_modelItemDataSet.equal_range(&modelItemData); - for (ModelItemDataSet::const_iterator it = itModelItemData.first; it != itModelItemData.second; ++it) + if (itModelItemData.first != itModelItemData.second) { - ModelItemData* modelItemData2 = *it; + ModelItemData* modelItemData2 = *itModelItemData.first; return createIndex(modelItemData2->m_row, 0, modelItemData2); } } @@ -603,9 +603,9 @@ namespace EMStudio // Find the model index ModelItemData modelItemData(nullptr, animGraphObject); AZStd::pair itModelItemData = m_modelItemDataSet.equal_range(&modelItemData); - for (ModelItemDataSet::const_iterator it = itModelItemData.first; it != itModelItemData.second; ++it) + if (itModelItemData.first != itModelItemData.second) { - ModelItemData* modelItemData2 = *it; + ModelItemData* modelItemData2 = *itModelItemData.first; return createIndex(modelItemData2->m_row, 0, modelItemData2); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.cpp index c17ff12947..6434799773 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.cpp @@ -1176,7 +1176,7 @@ namespace EMStudio } else { - settingsInfo->m_axis = elementID; + settingsInfo->m_axis = static_cast(elementID); } } else @@ -1188,7 +1188,7 @@ namespace EMStudio } else { - settingsInfo->m_axis = value - 1; + settingsInfo->m_axis = static_cast(value - 1); } } #else @@ -1619,7 +1619,7 @@ namespace EMStudio const uint32 numButtons = m_gameController->GetNumButtons(); for (uint32 i = 0; i < numButtons; ++i) { - const bool isPressed = m_gameController->GetIsButtonPressed(i); + const bool isPressed = m_gameController->GetIsButtonPressed(static_cast(i)); // get the game controller settings info for the given button EMotionFX::AnimGraphGameControllerSettings::ButtonInfo* settingsInfo = activePreset->FindButtonInfo(i); @@ -1792,7 +1792,7 @@ namespace EMStudio m_string.clear(); for (uint32 i = 0; i < numButtons; ++i) { - if (m_gameController->GetIsButtonPressed(i)) + if (m_gameController->GetIsButtonPressed(static_cast(i))) { m_string += AZStd::string::format("%s%d ", (i < 10) ? "0" : "", i); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeGroupInfo.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeGroupInfo.cpp index f25158ae0d..06b87c2bc2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeGroupInfo.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeGroupInfo.cpp @@ -26,7 +26,7 @@ namespace EMStudio const size_t numGroupNodes = nodeGroup->GetNumNodes(); for (size_t j = 0; j < numGroupNodes; ++j) { - const uint16 nodeIndex = nodeGroup->GetNode(j); + const uint16 nodeIndex = nodeGroup->GetNode(static_cast(j)); const EMotionFX::Node* node = actor->GetSkeleton()->GetNode(nodeIndex); m_nodes.emplace_back(node->GetNameString()); } diff --git a/Gems/EMotionFX/Code/Include/Integration/ActorComponentBus.h b/Gems/EMotionFX/Code/Include/Integration/ActorComponentBus.h index c6b18745e6..658f15786f 100644 --- a/Gems/EMotionFX/Code/Include/Integration/ActorComponentBus.h +++ b/Gems/EMotionFX/Code/Include/Integration/ActorComponentBus.h @@ -95,7 +95,7 @@ namespace EMotionFX /// Returns skinning method used by the actor. virtual SkinningMethod GetSkinningMethod() const = 0; - static const size_t s_invalidJointIndex = ~0; + static const size_t s_invalidJointIndex = std::numeric_limits::max(); }; using ActorComponentRequestBus = AZ::EBus; diff --git a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp index 5cdd9c2600..b59f2b69a0 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp @@ -1123,7 +1123,7 @@ namespace MCore for (size_t i = 0; i < numHistoryEntries; ++i) { AZStd::string text = AZStd::string::format("%.3zu: name='%s', num parameters=%zu", i, m_commandHistory[i].m_executedCommand->GetName(), m_commandHistory[i].m_parameters.GetNumParameters()); - if (i == m_historyIndex) + if (i == static_cast(m_historyIndex)) { LogDetailedInfo("-> %s", text.c_str()); } diff --git a/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp b/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp index c6b84a9e04..88a22db245 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp @@ -30,7 +30,7 @@ namespace MCore // find the last letter index from the right size_t lastIndex = AZStd::string::npos; const size_t numCharacters = prefixString.size(); - for (size_t i = numCharacters - 1; i >= 0; --i) + for (int i = static_cast(numCharacters) - 1; i >= 0; --i) { if (!AZStd::is_digit(prefixString[i])) { diff --git a/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp b/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp index 6b381bf9d8..ffedae5a99 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp @@ -10,6 +10,7 @@ #include "KeyboardShortcutManager.h" #include #include +#include #include #include diff --git a/Gems/EMotionFX/Code/Source/Editor/Plugins/Cloth/ClothJointInspectorPlugin.h b/Gems/EMotionFX/Code/Source/Editor/Plugins/Cloth/ClothJointInspectorPlugin.h index ac35a6dfcd..6a920fa10d 100644 --- a/Gems/EMotionFX/Code/Source/Editor/Plugins/Cloth/ClothJointInspectorPlugin.h +++ b/Gems/EMotionFX/Code/Source/Editor/Plugins/Cloth/ClothJointInspectorPlugin.h @@ -28,7 +28,7 @@ namespace EMotionFX Q_OBJECT //AUTOMOC public: - enum + enum : uint32 { CLASS_ID = 0x8efd2bee }; diff --git a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/MotionSetMotionIdHandler.h b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/MotionSetMotionIdHandler.h index f5ef1ffed5..6ea49bf9ef 100644 --- a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/MotionSetMotionIdHandler.h +++ b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/MotionSetMotionIdHandler.h @@ -59,7 +59,7 @@ namespace EMotionFX static void ResetDisplayedRoundingError(); private: - size_t m_id = -1; + size_t m_id = std::numeric_limits::max(); bool m_displayMotionSelectionWeight = false; const IRandomMotionSelectionDataContainer* m_dataContainer = nullptr; static float s_displayedRoundingError; diff --git a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/PropertyTypes.cpp b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/PropertyTypes.cpp index e8c4ee69d8..a93ec07477 100644 --- a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/PropertyTypes.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/PropertyTypes.cpp @@ -89,8 +89,9 @@ namespace EMotionFX AzToolsFramework::PropertyTypeRegistrationMessages::Bus::Broadcast(&AzToolsFramework::PropertyTypeRegistrationMessages::RegisterPropertyType, handler); } return propertyHandlers; -#endif +#else return AZStd::vector {}; +#endif } diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp index 303a7e118b..da4c72b70a 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp @@ -542,7 +542,7 @@ namespace EMotionFX ////////////////////////////////////////////////////////////////////////// void ActorComponent::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Animation); + AZ_PROFILE_FUNCTION(Animation); if (!m_actorInstance || !m_actorInstance->GetIsEnabled()) { diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphDeferredInitTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphDeferredInitTests.cpp index aa1bde295a..0449005659 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphDeferredInitTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphDeferredInitTests.cpp @@ -36,7 +36,7 @@ namespace EMotionFX m_blendTree->AddChildNode(paramNode); paramNode->InitAfterLoading(m_animGraph.get()); paramNode->InvalidateUniqueData(m_animGraphInstance); - m_blend2Node->AddConnection(paramNode, paramNode->FindOutputPortByName("weightParam")->m_portId, BlendTreeBlend2Node::PORTID_INPUT_WEIGHT); + m_blend2Node->AddConnection(paramNode, static_cast(paramNode->FindOutputPortByName("weightParam")->m_portId), BlendTreeBlend2Node::PORTID_INPUT_WEIGHT); } void ConstructGraph() @@ -126,8 +126,8 @@ namespace EMotionFX blendNNode->SetName(blendNNodeName); blendTree->AddChildNode(blendNNode); - const int motionNodeCount = 5; - for (AZ::u32 i = 0; i < motionNodeCount; ++i) + const uint16 motionNodeCount = 5; + for (uint16 i = 0; i < motionNodeCount; ++i) { AnimGraphMotionNode* motionNode = aznew AnimGraphMotionNode(); motionNode->SetName(AZStd::string::format("Motion %i (%s)", i, blendNNodeName).c_str()); @@ -172,7 +172,7 @@ namespace EMotionFX finalNode->AddConnection(blendNNode, BlendTreeBlendNNode::PORTID_OUTPUT_POSE, BlendTreeFinalNode::PORTID_INPUT_POSE); // Creates 5x blend N nodes as input for the blend N node created here. Each of these five blend N nodes have 5x input motions. - for (AZ::u32 i = 0; i < 5; ++i) + for (uint16 i = 0; i < 5; ++i) { BlendTreeBlendNNode* inputNode = CreateBlendNNode(testBlendTree, parameterNode, AZStd::string::format("InputBlendNode%i", i).c_str()); blendNNode->AddConnection(inputNode, AnimGraphMotionNode::PORTID_OUTPUT_POSE, i); diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp index 121f438d82..a377495d6c 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp @@ -303,7 +303,7 @@ namespace EMotionFX TEST_F(AnimGraphMotionNodeFixture, InPlaceInputAndNoEffectOutputsCorrectMotionAndPose) { - m_motionNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("InPlace")->m_portId, AnimGraphMotionNode::INPUTPORT_INPLACE); + m_motionNode->AddConnection(m_paramNode, static_cast(m_paramNode->FindOutputPortByName("InPlace")->m_portId), AnimGraphMotionNode::INPUTPORT_INPLACE); ParamSetValue("InPlace", true); m_animGraphInstance->FindOrCreateUniqueNodeData(m_motionNode); diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineInterruptionTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineInterruptionTests.cpp index 1f700129c0..39fc296d9f 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineInterruptionTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineInterruptionTests.cpp @@ -165,7 +165,7 @@ namespace EMotionFX for (const auto& activeObjects : activeObjectsAtFrame) { - if (activeObjects.m_frameNr == frame) + if (activeObjects.m_frameNr == static_cast(frame)) { // Check which states and transitions are active and compare it to the expected ones. EXPECT_EQ(activeObjects.m_stateA, compareAgainst.m_stateA) diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeBlendNNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeBlendNNodeTests.cpp index 1f9fb9cae3..1f5fb9a512 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeBlendNNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeBlendNNodeTests.cpp @@ -51,8 +51,8 @@ namespace EMotionFX m_blendTree->AddChildNode(finalNode); finalNode->AddConnection(m_blendNNode, BlendTreeBlendNNode::PORTID_OUTPUT_POSE, BlendTreeFinalNode::PORTID_INPUT_POSE); - const int motionNodeCount = 3; - for (int i = 0; i < motionNodeCount; ++i) + const uint16 motionNodeCount = 3; + for (uint16 i = 0; i < motionNodeCount; ++i) { AnimGraphMotionNode* motionNode = aznew AnimGraphMotionNode(); m_blendTree->AddChildNode(motionNode); @@ -213,7 +213,7 @@ namespace EMotionFX finalNode->AddConnection(m_blendNNode, BlendTreeBlendNNode::PORTID_OUTPUT_POSE, BlendTreeFinalNode::PORTID_INPUT_POSE); ASSERT_TRUE(param.m_motionNodeCount <= 10) << "The blend N node only has 10 pose inputs."; - for (AZ::u32 i = 0; i < param.m_motionNodeCount; ++i) + for (uint16 i = 0; i < param.m_motionNodeCount; ++i) { AnimGraphMotionNode* motionNode = aznew AnimGraphMotionNode(); m_blendTree->AddChildNode(motionNode); diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeFloatMath1NodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeFloatMath1NodeTests.cpp index 3ece046845..f4b11a3f8a 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeFloatMath1NodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeFloatMath1NodeTests.cpp @@ -98,7 +98,7 @@ namespace EMotionFX void TestInput(const AZStd::string& paramName, std::vector xInputs) { BlendTreeConnection* connection = m_floatMath1Node->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName(paramName)->m_portId, BlendTreeFloatMath1Node::PORTID_INPUT_X); + static_cast(m_paramNode->FindOutputPortByName(paramName)->m_portId), BlendTreeFloatMath1Node::PORTID_INPUT_X); for (inputType i : xInputs) { diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp index b86041c7aa..8bd66ced88 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp @@ -173,7 +173,7 @@ namespace EMotionFX m_blendTree->AddChildNode(m_basePoseNode); m_maskNode->AddConnection(m_basePoseNode, BlendTreeTestInputNode::OUTPUTPORT_RESULT, BlendTreeMaskNode::INPUTPORT_BASEPOSE); - for (AZ::u32 i = 0; i < m_numMaskInputNodes; ++i) + for (uint16 i = 0; i < m_numMaskInputNodes; ++i) { BlendTreeTestInputNode* inputNode = aznew BlendTreeTestInputNode(static_cast(i)); m_blendTree->AddChildNode(inputNode); diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp index d68bf9db83..eab445ddfe 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp @@ -137,9 +137,9 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, ReachablePositionsOutputCorrectPose) { // Set values for vector3 and twoLinkIKNode weight parameter - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); + m_twoLinkIKNode->AddConnection(m_paramNode, static_cast(m_paramNode->FindOutputPortByName("WeightParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); + static_cast(m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); GetEMotionFX().Update(1.0f / 60.0f); const float weight = testing::get<0>(GetParam()); @@ -179,7 +179,7 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, ReachableAlignToNodeOutputCorrectPose) { - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, + m_twoLinkIKNode->AddConnection(m_paramNode, static_cast(m_paramNode->FindOutputPortByName("WeightParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); GetEMotionFX().Update(1.0f / 60.0f); @@ -224,10 +224,10 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, UnreachablePositionsOutputCorrectPose) { - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, + m_twoLinkIKNode->AddConnection(m_paramNode, static_cast(m_paramNode->FindOutputPortByName("WeightParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); + static_cast(m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); GetEMotionFX().Update(1.0f / 60.0f); const float weight = testing::get<0>(GetParam()); @@ -272,12 +272,12 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, RotatedPositionsOutputCorrectPose) { - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, + m_twoLinkIKNode->AddConnection(m_paramNode, static_cast(m_paramNode->FindOutputPortByName("WeightParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); + static_cast(m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("RotationParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALROT); + static_cast(m_paramNode->FindOutputPortByName("RotationParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_GOALROT); m_twoLinkIKNode->SetRotationEnabled(true); GetEMotionFX().Update(1.0f / 60.0f); @@ -315,12 +315,12 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, BendDirectionOutputCorrectPose) { - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, + m_twoLinkIKNode->AddConnection(m_paramNode, static_cast(m_paramNode->FindOutputPortByName("WeightParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); + static_cast(m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("BendDirParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_BENDDIR); + static_cast(m_paramNode->FindOutputPortByName("BendDirParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_BENDDIR); m_twoLinkIKNode->SetRelativeBendDir(true); GetEMotionFX().Update(1.0f / 60.0f); @@ -382,14 +382,14 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, CombinedFunctionsOutputCorrectPose) { // Two Link IK Node should not break when using all of its functions at the same time - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, + m_twoLinkIKNode->AddConnection(m_paramNode, static_cast(m_paramNode->FindOutputPortByName("WeightParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); + static_cast(m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("RotationParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALROT); + static_cast(m_paramNode->FindOutputPortByName("RotationParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_GOALROT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("BendDirParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_BENDDIR); + static_cast(m_paramNode->FindOutputPortByName("BendDirParam")->m_portId), BlendTreeTwoLinkIKNode::INPUTPORT_BENDDIR); m_twoLinkIKNode->SetRotationEnabled(true); m_twoLinkIKNode->SetRelativeBendDir(true); GetEMotionFX().Update(1.0f / 60.0f); diff --git a/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp index 6214005a71..dbf9f18e9e 100644 --- a/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp @@ -53,8 +53,8 @@ namespace EMotionFX m_blendTree->AddChildNode(finalNode); finalNode->AddConnection(m_blendNNode, BlendTreeBlendNNode::PORTID_OUTPUT_POSE, BlendTreeFinalNode::PORTID_INPUT_POSE); - const int motionNodeCount = 2; - for (int i = 0; i < motionNodeCount; ++i) + const uint16 motionNodeCount = 2; + for (uint16 i = 0; i < motionNodeCount; ++i) { AnimGraphMotionNode* motionNode = aznew AnimGraphMotionNode(); m_blendTree->AddChildNode(motionNode); diff --git a/Gems/EMotionFX/Code/Tests/Vector2ToVector3CompatibilityTests.cpp b/Gems/EMotionFX/Code/Tests/Vector2ToVector3CompatibilityTests.cpp index 26702af550..d5ce41cfeb 100644 --- a/Gems/EMotionFX/Code/Tests/Vector2ToVector3CompatibilityTests.cpp +++ b/Gems/EMotionFX/Code/Tests/Vector2ToVector3CompatibilityTests.cpp @@ -46,8 +46,8 @@ namespace EMotionFX m_blendTree->AddChildNode(finalNode); finalNode->AddUnitializedConnection(m_blendNNode, BlendTreeBlendNNode::PORTID_OUTPUT_POSE, BlendTreeFinalNode::PORTID_INPUT_POSE); - const int motionNodeCount = 3; - for (int i = 0; i < motionNodeCount; ++i) + const uint16 motionNodeCount = 3; + for (uint16 i = 0; i < motionNodeCount; ++i) { AnimGraphMotionNode* motionNode = aznew AnimGraphMotionNode(); m_blendTree->AddChildNode(motionNode); diff --git a/Gems/EditorPythonBindings/Code/Source/PythonMarshalComponent.cpp b/Gems/EditorPythonBindings/Code/Source/PythonMarshalComponent.cpp index d1b59e7ecc..af21420b62 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonMarshalComponent.cpp +++ b/Gems/EditorPythonBindings/Code/Source/PythonMarshalComponent.cpp @@ -795,7 +795,7 @@ namespace EditorPythonBindings } } - AZ_Warning("python", PyDict_Size(pyObj.ptr()) == mapDataContainer->Size(mapInstance.m_address), "Python Dict size:%d does not match the size of the unordered_map:%d", pos, mapDataContainer->Size(mapInstance.m_address)); + AZ_Warning("python", static_cast(PyDict_Size(pyObj.ptr())) == mapDataContainer->Size(mapInstance.m_address), "Python Dict size:%d does not match the size of the unordered_map:%d", pos, mapDataContainer->Size(mapInstance.m_address)); outValue.m_value = mapInstance.m_address; outValue.m_typeId = mapInstance.m_typeId; outValue.m_traits = traits; diff --git a/Gems/EditorPythonBindings/Code/Tests/PythonDictionaryTests.cpp b/Gems/EditorPythonBindings/Code/Tests/PythonDictionaryTests.cpp index 8f6abd5a17..24689bbfe3 100644 --- a/Gems/EditorPythonBindings/Code/Tests/PythonDictionaryTests.cpp +++ b/Gems/EditorPythonBindings/Code/Tests/PythonDictionaryTests.cpp @@ -52,8 +52,8 @@ namespace UnitTest } }; - MapOf m_indexOfu8tou32 { {1, 4}, {2, 5}, {3, 6}, {4, 7} }; - MapOf m_indexOfu16toFloat { {1, 0.4f}, {2, 0.5f}, {3, 0.6f}, {4, 0.7f} }; + MapOf m_indexOfu8tou32 { {AZ::u8(1), 4u}, {AZ::u8(2), 5u}, {AZ::u8(3), 6u}, {AZ::u8(4), 7u} }; + MapOf m_indexOfu16toFloat { {AZ::u16(1u), 0.4f}, {AZ::u16(2u), 0.5f}, {AZ::u16(3u), 0.6f}, {AZ::u16(4u), 0.7f} }; MapOf m_indexOfStringTos32 { {"1", -4}, {"2", 5}, {"3", -6}, {"4", 7} }; MapOf m_indexOfStringToString { {"hello", "foo"}, {"world", "bar"}, {"bye", "baz"}, {"sky", "qux"} }; MapOf m_indexOfStringToVec3{ {"up", AZ::Vector3{ 0, 1.0, 0 }}, {"down", AZ::Vector3{0, -1.0, 0}}, diff --git a/Gems/ExpressionEvaluation/Code/Source/ExpressionEvaluationSystemComponent.cpp b/Gems/ExpressionEvaluation/Code/Source/ExpressionEvaluationSystemComponent.cpp index 42ac124e6e..295d42228d 100644 --- a/Gems/ExpressionEvaluation/Code/Source/ExpressionEvaluationSystemComponent.cpp +++ b/Gems/ExpressionEvaluation/Code/Source/ExpressionEvaluationSystemComponent.cpp @@ -8,6 +8,7 @@ #include +#include #include #include #include @@ -251,7 +252,7 @@ namespace ExpressionEvaluation AZ::Outcome ExpressionEvaluationSystemComponent::ParseRestrictedExpressionInPlace(const AZStd::unordered_set& parsers, AZStd::string_view expressionString, ExpressionTree& expressionTree) const { - AZ_PROFILE_TIMER("ExpressionEvaluation", __FUNCTION__); + AZ_PROFILE_FUNCTION(ExpressionEvaluation); expressionTree.ClearTree(); @@ -513,7 +514,7 @@ namespace ExpressionEvaluation ExpressionResult ExpressionEvaluationSystemComponent::Evaluate(const ExpressionTree& expressionTree) const { - AZ_PROFILE_TIMER("ExpressionEvaluation", __FUNCTION__); + AZ_PROFILE_FUNCTION(ExpressionEvaluation); ExpressionResultStack resultStack; diff --git a/Gems/FastNoise/Code/External/FastNoise/FastNoise.cpp b/Gems/FastNoise/Code/External/FastNoise/FastNoise.cpp index 51980ca08a..de073fe600 100644 --- a/Gems/FastNoise/Code/External/FastNoise/FastNoise.cpp +++ b/Gems/FastNoise/Code/External/FastNoise/FastNoise.cpp @@ -202,13 +202,13 @@ void FastNoise::SetSeed(int seed) std::mt19937_64 gen(seed); for (int i = 0; i < 256; i++) - m_perm[i] = i; + m_perm[i] = static_cast(i); for (int j = 0; j < 256; j++) { int rng = (int)(gen() % (256 - j)); int k = rng + j; - int l = m_perm[j]; + unsigned char l = m_perm[j]; m_perm[j] = m_perm[j + 256] = m_perm[k]; m_perm[k] = l; m_perm12[j] = m_perm12[j + 256] = m_perm[j] % 12; diff --git a/Gems/GameState/Code/CMakeLists.txt b/Gems/GameState/Code/CMakeLists.txt index 7aa99446cb..debedd8500 100644 --- a/Gems/GameState/Code/CMakeLists.txt +++ b/Gems/GameState/Code/CMakeLists.txt @@ -17,8 +17,8 @@ ly_add_target( PUBLIC Include BUILD_DEPENDENCIES - PRIVATE - Legacy::CryCommon + PUBLIC + AZ::AzCore ) ly_add_target( @@ -33,7 +33,6 @@ ly_add_target( Include BUILD_DEPENDENCIES PRIVATE - Legacy::CryCommon Gem::GameState.Static ) @@ -58,7 +57,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) BUILD_DEPENDENCIES PRIVATE AZ::AzTest - Legacy::CryCommon Gem::GameState.Static ) ly_add_googletest( diff --git a/Gems/GameStateSamples/Code/CMakeLists.txt b/Gems/GameStateSamples/Code/CMakeLists.txt index 34132e67b1..5d1d180de0 100644 --- a/Gems/GameStateSamples/Code/CMakeLists.txt +++ b/Gems/GameStateSamples/Code/CMakeLists.txt @@ -21,6 +21,7 @@ ly_add_target( INTERFACE Gem::GameState Gem::LocalUser + Gem::LyShine.Static Gem::SaveData.Static Gem::MessagePopup.Static Legacy::CryCommon @@ -47,6 +48,7 @@ ly_add_target( Gem::LmbrCentral ) -# Clients and Servers use the above module. There is no editor or tools module required. -ly_create_alias(NAME GameStateSamples.Clients NAMESPACE Gem TARGETS GameStateSamples) -ly_create_alias(NAME GameStateSamples.Servers NAMESPACE Gem TARGETS GameStateSamples) +# Clients and Servers use the above module, and it contains assets so is needed by builders. +ly_create_alias(NAME GameStateSamples.Clients NAMESPACE Gem TARGETS Gem::GameStateSamples) +ly_create_alias(NAME GameStateSamples.Servers NAMESPACE Gem TARGETS Gem::GameStateSamples) +ly_create_alias(NAME GameStateSamples.Builders NAMESPACE Gem TARGETS Gem::UiBasics.Builders Gem::LyShineExamples.Builders) diff --git a/Gems/GameStateSamples/Code/Source/GameStateSamplesModule.cpp b/Gems/GameStateSamples/Code/Source/GameStateSamplesModule.cpp index 24a29c97ab..f175619bf4 100644 --- a/Gems/GameStateSamples/Code/Source/GameStateSamplesModule.cpp +++ b/Gems/GameStateSamples/Code/Source/GameStateSamplesModule.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -55,6 +56,7 @@ namespace GameStateSamples //! class GameStateSamplesModule : public CryHooksModule + , public AZ::TickBus::Handler , public GameOptionRequestBus::Handler { public: @@ -86,6 +88,22 @@ namespace GameStateSamples { CryHooksModule::OnCrySystemInitialized(system, systemInitParams); + AZ::TickBus::Handler::BusConnect(); + } + + void OnTick([[maybe_unused]]float deltaTime, [[maybe_unused]]AZ::ScriptTimePoint scriptTimePoint) override + { + // Ideally this would be called at startup (either above in OnCrySystemInitialized, or better during AZ system component + // initialisation), but because the initial game state depends on loading a UI canvas using LYShine we need to wait until + // the first tick, because LyShine in turn is not properly initialized until UiRenderer::OnBootstrapSceneReady has been + // called, which doesn't happen until a queued tick event that gets called right at the end of initialisation before we + // enter the main game loop. + CreateAndPushInitialGameState(); + AZ::TickBus::Handler::BusDisconnect(); + } + + void CreateAndPushInitialGameState() + { REGISTER_INT("sys_primaryUserSelectionEnabled", 2, VF_NULL, "Controls whether the game forces selection of a primary user at startup.\n" "0 : Skip selection of a primary user at startup on all platform.\n" diff --git a/Gems/GradientSignal/Code/Include/GradientSignal/GradientSampler.h b/Gems/GradientSignal/Code/Include/GradientSignal/GradientSampler.h index a7b0338ac1..c06265fb24 100644 --- a/Gems/GradientSignal/Code/Include/GradientSignal/GradientSampler.h +++ b/Gems/GradientSignal/Code/Include/GradientSignal/GradientSampler.h @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -87,7 +88,7 @@ namespace GradientSignal inline float GradientSampler::GetValue(const GradientSampleParams& sampleParams) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (m_opacity <= 0.0f || !m_gradientId.IsValid()) { diff --git a/Gems/GradientSignal/Code/Source/Components/DitherGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/DitherGradientComponent.cpp index 3b71278f86..dbc2cd2827 100644 --- a/Gems/GradientSignal/Code/Source/Components/DitherGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/DitherGradientComponent.cpp @@ -224,7 +224,7 @@ namespace GradientSignal float DitherGradientComponent::GetValue(const GradientSampleParams& sampleParams) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const AZ::Vector3& coordinate = sampleParams.m_position; diff --git a/Gems/GradientSignal/Code/Source/Components/GradientSurfaceDataComponent.cpp b/Gems/GradientSignal/Code/Source/Components/GradientSurfaceDataComponent.cpp index d07f3a2e66..bdda0e48d2 100644 --- a/Gems/GradientSignal/Code/Source/Components/GradientSurfaceDataComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/GradientSurfaceDataComponent.cpp @@ -263,7 +263,7 @@ namespace GradientSignal void GradientSurfaceDataComponent::OnCompositionChanged() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); UpdateRegistryAndCache(m_modifierHandle); } diff --git a/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp b/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp index af92a0e16c..38936dc302 100644 --- a/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp @@ -324,7 +324,7 @@ namespace GradientSignal void GradientTransformComponent::TransformPositionToUVW(const AZ::Vector3& inPosition, AZ::Vector3& outUVW, const bool shouldNormalizeOutput, bool& wasPointRejected) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_cacheMutex); @@ -415,7 +415,7 @@ namespace GradientSignal void GradientTransformComponent::UpdateFromShape() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_cacheMutex); diff --git a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp index 650dba209a..9e01b690e0 100644 --- a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp @@ -190,7 +190,7 @@ namespace GradientSignal float ImageGradientComponent::GetValue(const GradientSampleParams& sampleParams) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZ::Vector3 uvw = sampleParams.m_position; diff --git a/Gems/GradientSignal/Code/Source/Components/LevelsGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/LevelsGradientComponent.cpp index 97dd8faa3c..af26ba494d 100644 --- a/Gems/GradientSignal/Code/Source/Components/LevelsGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/LevelsGradientComponent.cpp @@ -172,7 +172,7 @@ namespace GradientSignal float LevelsGradientComponent::GetValue(const GradientSampleParams& sampleParams) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); float output = 0.0f; diff --git a/Gems/GradientSignal/Code/Source/Components/MixedGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/MixedGradientComponent.cpp index ddf349645b..5f6a18c7fb 100644 --- a/Gems/GradientSignal/Code/Source/Components/MixedGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/MixedGradientComponent.cpp @@ -257,7 +257,7 @@ namespace GradientSignal float MixedGradientComponent::GetValue(const GradientSampleParams& sampleParams) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); //accumulate the mixed/combined result of all layers and operations float result = 0.0f; diff --git a/Gems/GradientSignal/Code/Source/Components/PerlinGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/PerlinGradientComponent.cpp index 6bc7108c64..e150ff4305 100644 --- a/Gems/GradientSignal/Code/Source/Components/PerlinGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/PerlinGradientComponent.cpp @@ -172,7 +172,7 @@ namespace GradientSignal float PerlinGradientComponent::GetValue(const GradientSampleParams& sampleParams) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (m_perlinImprovedNoise) { diff --git a/Gems/GradientSignal/Code/Source/Components/RandomGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/RandomGradientComponent.cpp index 4e02e92db3..d28fe13aff 100644 --- a/Gems/GradientSignal/Code/Source/Components/RandomGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/RandomGradientComponent.cpp @@ -137,7 +137,7 @@ namespace GradientSignal float RandomGradientComponent::GetValue(const GradientSampleParams& sampleParams) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZ::Vector3 uvw = sampleParams.m_position; diff --git a/Gems/GradientSignal/Code/Source/Components/ReferenceGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/ReferenceGradientComponent.cpp index 3c1fea6563..28ffaad7d3 100644 --- a/Gems/GradientSignal/Code/Source/Components/ReferenceGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/ReferenceGradientComponent.cpp @@ -131,7 +131,7 @@ namespace GradientSignal float ReferenceGradientComponent::GetValue(const GradientSampleParams& sampleParams) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); float output = 0.0f; diff --git a/Gems/GradientSignal/Code/Source/Components/ShapeAreaFalloffGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/ShapeAreaFalloffGradientComponent.cpp index 3a3b9a2efd..cdf542bf51 100644 --- a/Gems/GradientSignal/Code/Source/Components/ShapeAreaFalloffGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/ShapeAreaFalloffGradientComponent.cpp @@ -157,7 +157,7 @@ namespace GradientSignal float ShapeAreaFalloffGradientComponent::GetValue(const GradientSampleParams& sampleParams) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); float distance = 0.0f; LmbrCentral::ShapeComponentRequestsBus::EventResult(distance, m_configuration.m_shapeEntityId, &LmbrCentral::ShapeComponentRequestsBus::Events::DistanceFromPoint, sampleParams.m_position); diff --git a/Gems/GradientSignal/Code/Source/Components/SurfaceAltitudeGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/SurfaceAltitudeGradientComponent.cpp index c321fe2a54..476e0971f4 100644 --- a/Gems/GradientSignal/Code/Source/Components/SurfaceAltitudeGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/SurfaceAltitudeGradientComponent.cpp @@ -244,7 +244,7 @@ namespace GradientSignal void SurfaceAltitudeGradientComponent::UpdateFromShape() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_cacheMutex); diff --git a/Gems/GradientSignal/Code/Source/Components/SurfaceMaskGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/SurfaceMaskGradientComponent.cpp index 389fcf3678..7f46ad6e98 100644 --- a/Gems/GradientSignal/Code/Source/Components/SurfaceMaskGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/SurfaceMaskGradientComponent.cpp @@ -161,7 +161,7 @@ namespace GradientSignal float SurfaceMaskGradientComponent::GetValue(const GradientSampleParams& params) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); float result = 0.0f; diff --git a/Gems/GradientSignal/Code/Source/ImageAsset.cpp b/Gems/GradientSignal/Code/Source/ImageAsset.cpp index 5d3397bbbd..c67f86c6b8 100644 --- a/Gems/GradientSignal/Code/Source/ImageAsset.cpp +++ b/Gems/GradientSignal/Code/Source/ImageAsset.cpp @@ -153,7 +153,7 @@ namespace GradientSignal float GetValueFromImageAsset(const AZ::Data::Asset& imageAsset, const AZ::Vector3& uvw, float tilingX, float tilingY, float defaultValue) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (imageAsset.IsReady()) { diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp b/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp index ea9a1d380f..4c22afac76 100644 --- a/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp +++ b/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp @@ -145,7 +145,7 @@ namespace UnitTest { for (AZ::u32 x = 0; x < width; ++x) { - if ((x == pixelX) && (y == pixelY)) + if ((x == static_cast(pixelX)) && (y == static_cast(pixelY))) { m_imageData->m_imageData.push_back(pixelValue); } diff --git a/Gems/GraphCanvas/Code/Source/Components/Nodes/Group/NodeGroupFrameComponent.cpp b/Gems/GraphCanvas/Code/Source/Components/Nodes/Group/NodeGroupFrameComponent.cpp index fa265ad644..c317e8044a 100644 --- a/Gems/GraphCanvas/Code/Source/Components/Nodes/Group/NodeGroupFrameComponent.cpp +++ b/Gems/GraphCanvas/Code/Source/Components/Nodes/Group/NodeGroupFrameComponent.cpp @@ -2493,18 +2493,18 @@ namespace GraphCanvas { if (growOnly) { - int left = blockBoundingRect.left(); + int left = static_cast(blockBoundingRect.left()); if (left >= calculatedBounds.left()) { - left = calculatedBounds.left() - gridStep.GetX(); + left = static_cast(calculatedBounds.left() - gridStep.GetX()); } - int right = blockBoundingRect.right(); + int right = static_cast(blockBoundingRect.right()); if (right <= calculatedBounds.right()) { - right = calculatedBounds.right() + gridStep.GetX(); + right = static_cast(calculatedBounds.right() + gridStep.GetX()); } blockBoundingRect.setX(left); @@ -2521,18 +2521,18 @@ namespace GraphCanvas { if (growOnly) { - int top = blockBoundingRect.top(); + int top = static_cast(blockBoundingRect.top()); if (top >= calculatedBounds.top()) { - top = calculatedBounds.top() - gridStep.GetY(); + top = static_cast(calculatedBounds.top() - gridStep.GetY()); } - int bottom = blockBoundingRect.bottom(); + int bottom = static_cast(blockBoundingRect.bottom()); if (bottom <= calculatedBounds.bottom()) { - bottom = calculatedBounds.bottom() + gridStep.GetY(); + bottom = static_cast(calculatedBounds.bottom() + gridStep.GetY()); } blockBoundingRect.setY(top); diff --git a/Gems/GraphCanvas/Code/Source/Widgets/GraphCanvasLabel.cpp b/Gems/GraphCanvas/Code/Source/Widgets/GraphCanvasLabel.cpp index fd7ac05cd2..e76487a4e8 100644 --- a/Gems/GraphCanvas/Code/Source/Widgets/GraphCanvasLabel.cpp +++ b/Gems/GraphCanvas/Code/Source/Widgets/GraphCanvasLabel.cpp @@ -432,7 +432,5 @@ namespace GraphCanvas default: return QGraphicsWidget::sizeHint(which, constraint); } - - return QGraphicsWidget::sizeHint(which, constraint); } } diff --git a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Components/Nodes/Wrapper/WrapperNodeBus.h b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Components/Nodes/Wrapper/WrapperNodeBus.h index a30915917f..0d45cbe536 100644 --- a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Components/Nodes/Wrapper/WrapperNodeBus.h +++ b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Components/Nodes/Wrapper/WrapperNodeBus.h @@ -34,14 +34,14 @@ namespace GraphCanvas AZ_CLASS_ALLOCATOR(WrappedNodeConfiguration, AZ::SystemAllocator, 0); WrappedNodeConfiguration() - : m_layoutOrder(-1) - , m_elementOrdering(-1) + : m_layoutOrder(std::numeric_limits::max()) + , m_elementOrdering(std::numeric_limits::max()) { } WrappedNodeConfiguration(AZ::u32 layoutOrder) : m_layoutOrder(layoutOrder) - , m_elementOrdering(-1) + , m_elementOrdering(std::numeric_limits::max()) { } diff --git a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Editor/GraphCanvasProfiler.h b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Editor/GraphCanvasProfiler.h index 60c147e98e..ae55baa681 100644 --- a/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Editor/GraphCanvasProfiler.h +++ b/Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Editor/GraphCanvasProfiler.h @@ -9,12 +9,12 @@ #include -#define GRAPH_CANVAS_PROFILE_FUNCTION() AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); -#define GRAPH_CANVAS_PROFILE_SCOPE(message) AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, message); +#define GRAPH_CANVAS_PROFILE_FUNCTION() AZ_PROFILE_FUNCTION(AzToolsFramework); +#define GRAPH_CANVAS_PROFILE_SCOPE(message) AZ_PROFILE_SCOPE(AzToolsFramework, message); #if GRAPH_CANVAS_ENABLE_DETAILED_PROFILING -#define GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION() AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); -#define GRAPH_CANVAS_DETAILED_PROFILE_SCOPE(message) AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, message); +#define GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION() AZ_PROFILE_FUNCTION(AzToolsFramework); +#define GRAPH_CANVAS_DETAILED_PROFILE_SCOPE(message) AZ_PROFILE_SCOPE(AzToolsFramework, message); #else #define GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION() #define GRAPH_CANVAS_DETAILED_PROFILE_SCOPE(message) diff --git a/Gems/GraphModel/Code/Include/GraphModel/Model/Common.h b/Gems/GraphModel/Code/Include/GraphModel/Model/Common.h index 17ce8e8471..ec5901a4b5 100644 --- a/Gems/GraphModel/Code/Include/GraphModel/Model/Common.h +++ b/Gems/GraphModel/Code/Include/GraphModel/Model/Common.h @@ -66,6 +66,6 @@ namespace GraphModel using ModuleGraphManagerPtr = AZStd::shared_ptr; using ConstModuleGraphManagerPtr = AZStd::shared_ptr; - static const AZ::u32 DefaultWrappedNodeLayoutOrder = -1; + static const AZ::u32 DefaultWrappedNodeLayoutOrder = std::numeric_limits::max(); } // namespace GraphModel diff --git a/Gems/GraphModel/Code/Tests/TestEnvironment.cpp b/Gems/GraphModel/Code/Tests/TestEnvironment.cpp index 67d2e7af80..b7724c6799 100644 --- a/Gems/GraphModel/Code/Tests/TestEnvironment.cpp +++ b/Gems/GraphModel/Code/Tests/TestEnvironment.cpp @@ -51,7 +51,7 @@ namespace GraphModelIntegrationTest GraphModel::DataTypePtr TestGraphContext::GetDataType(GraphModel::DataType::Enum typeEnum) const { - if (0 <= typeEnum && typeEnum < m_dataTypes.size()) + if (typeEnum < m_dataTypes.size()) { return m_dataTypes[typeEnum]; } diff --git a/Gems/ImGui/Code/Source/ImGuiManager.h b/Gems/ImGui/Code/Source/ImGuiManager.h index 20695c0825..1b24aa9806 100644 --- a/Gems/ImGui/Code/Source/ImGuiManager.h +++ b/Gems/ImGui/Code/Source/ImGuiManager.h @@ -67,7 +67,7 @@ namespace ImGui // -- AzFramework::InputChannelEventListener and AzFramework::InputTextEventListener Interface ------------ bool OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) override; bool OnInputTextEventFiltered(const AZStd::string& textUTF8) override; - int GetPriority() const override { return AzFramework::InputChannelEventListener::GetPriorityDebug(); } + int GetPriority() const override { return AzFramework::InputChannelEventListener::GetPriorityDebugUI(); } // -- AzFramework::InputChannelEventListener and AzFramework::InputTextEventListener Interface ------------ // AzFramework::WindowNotificationBus::Handler overrides... diff --git a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYEntityOutliner.cpp b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYEntityOutliner.cpp index 8e0e23652c..7f4877347f 100644 --- a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYEntityOutliner.cpp +++ b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYEntityOutliner.cpp @@ -770,8 +770,8 @@ namespace ImGui { AZStd::string name1 = com1->RTTI_GetTypeName(); AZStd::string name2 = com2->RTTI_GetTypeName(); - AZStd::transform(name1.begin(), name1.end(), name1.begin(), ::tolower); - AZStd::transform(name2.begin(), name2.end(), name2.begin(), ::tolower); + AZStd::to_lower(name1.begin(), name1.end()); + AZStd::to_lower(name2.begin(), name2.end()); return name1 < name2; }; AZStd::sort(components.begin(), components.end(), sortByComponentName); @@ -1017,8 +1017,8 @@ namespace ImGui AZStd::string name1, name2; AZ::ComponentApplicationBus::BroadcastResult(name1, &AZ::ComponentApplicationBus::Events::GetEntityName, ent1->m_entityId); AZ::ComponentApplicationBus::BroadcastResult(name2, &AZ::ComponentApplicationBus::Events::GetEntityName, ent2->m_entityId); - AZStd::transform(name1.begin(), name1.end(), name1.begin(), ::tolower); - AZStd::transform(name2.begin(), name2.end(), name2.begin(), ::tolower); + AZStd::to_lower(name1.begin(), name1.end()); + AZStd::to_lower(name2.begin(), name2.end()); return name1 < name2; }; AZStd::sort(entityInfo->m_children.begin(), entityInfo->m_children.end(), sortByEntityName); diff --git a/Gems/LandscapeCanvas/Code/Source/Editor/Core/GraphContext.cpp b/Gems/LandscapeCanvas/Code/Source/Editor/Core/GraphContext.cpp index 9011a82069..615139333c 100644 --- a/Gems/LandscapeCanvas/Code/Source/Editor/Core/GraphContext.cpp +++ b/Gems/LandscapeCanvas/Code/Source/Editor/Core/GraphContext.cpp @@ -102,7 +102,7 @@ namespace LandscapeCanvas GraphModel::DataTypePtr GraphContext::GetDataType(GraphModel::DataType::Enum typeEnum) const { - if (0 <= typeEnum && typeEnum < m_dataTypes.size()) + if (typeEnum < m_dataTypes.size()) { return m_dataTypes[typeEnum]; } diff --git a/Gems/LmbrCentral/Code/Source/Scripting/EditorTagComponent.cpp b/Gems/LmbrCentral/Code/Source/Scripting/EditorTagComponent.cpp index 251f0203b4..fa98601a11 100644 --- a/Gems/LmbrCentral/Code/Source/Scripting/EditorTagComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Scripting/EditorTagComponent.cpp @@ -33,6 +33,7 @@ namespace LmbrCentral editContext->Class("Tag", "The Tag component allows you to apply one or more labels to an entity") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("UI", 0x27ff46b0)) ->Attribute(AZ::Edit::Attributes::Category, "Gameplay") ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Tag.svg") ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Tag.svg") diff --git a/Gems/LmbrCentral/Code/include/LmbrCentral/Component/EditorWrappedComponentBase.inl b/Gems/LmbrCentral/Code/include/LmbrCentral/Component/EditorWrappedComponentBase.inl index 2c49710ddd..6a9fceabbf 100644 --- a/Gems/LmbrCentral/Code/include/LmbrCentral/Component/EditorWrappedComponentBase.inl +++ b/Gems/LmbrCentral/Code/include/LmbrCentral/Component/EditorWrappedComponentBase.inl @@ -212,8 +212,11 @@ namespace LmbrCentral template void EditorWrappedComponentBase::OnEntityVisibilityChanged(bool visibility) { - m_visible = visibility; - ConfigurationChanged(); + if (m_visible != visibility) + { + m_visible = visibility; + ConfigurationChanged(); + } } template diff --git a/Gems/LmbrCentral/Code/include/LmbrCentral/Dependency/DependencyMonitor.h b/Gems/LmbrCentral/Code/include/LmbrCentral/Dependency/DependencyMonitor.h index 4e6e85250a..230655a455 100644 --- a/Gems/LmbrCentral/Code/include/LmbrCentral/Dependency/DependencyMonitor.h +++ b/Gems/LmbrCentral/Code/include/LmbrCentral/Dependency/DependencyMonitor.h @@ -10,6 +10,7 @@ #include #include +#include #include #include #include diff --git a/Gems/LmbrCentral/Code/include/LmbrCentral/Dependency/DependencyMonitor.inl b/Gems/LmbrCentral/Code/include/LmbrCentral/Dependency/DependencyMonitor.inl index d6ad18325a..cc4a3e2740 100644 --- a/Gems/LmbrCentral/Code/include/LmbrCentral/Dependency/DependencyMonitor.inl +++ b/Gems/LmbrCentral/Code/include/LmbrCentral/Dependency/DependencyMonitor.inl @@ -15,7 +15,7 @@ namespace LmbrCentral inline void DependencyMonitor::Reset() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZ::Data::AssetBus::MultiHandler::BusDisconnect(); AZ::EntityBus::MultiHandler::BusDisconnect(); @@ -35,7 +35,7 @@ namespace LmbrCentral inline void DependencyMonitor::ConnectDependency(const AZ::EntityId& entityId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (entityId.IsValid()) { AZ::EntityBus::MultiHandler::BusConnect(entityId); @@ -47,7 +47,7 @@ namespace LmbrCentral inline void DependencyMonitor::ConnectDependencies(const AZStd::vector& entityIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); for (const auto& entityId : entityIds) { @@ -57,7 +57,7 @@ namespace LmbrCentral inline void DependencyMonitor::ConnectDependency(const AZ::Data::AssetId& assetId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (assetId.IsValid()) { @@ -120,7 +120,7 @@ namespace LmbrCentral inline void DependencyMonitor::SendNotification() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); //test if notification is in progress to prevent recursion in case of nested dependencies if (!m_notificationInProgress) diff --git a/Gems/LyShine/Code/Editor/Animation/Controls/UiTimelineCtrl.cpp b/Gems/LyShine/Code/Editor/Animation/Controls/UiTimelineCtrl.cpp index 4140cff935..3f9ba6e813 100644 --- a/Gems/LyShine/Code/Editor/Animation/Controls/UiTimelineCtrl.cpp +++ b/Gems/LyShine/Code/Editor/Animation/Controls/UiTimelineCtrl.cpp @@ -20,9 +20,9 @@ QColor InterpolateColor(const QColor& c1, const QColor& c2, float fraction) { - const int r = (c2.red() - c1.red()) * fraction + c1.red(); - const int g = (c2.green() - c1.green()) * fraction + c1.green(); - const int b = (c2.blue() - c1.blue()) * fraction + c1.blue(); + const int r = static_cast(static_cast(c2.red() - c1.red()) * fraction + c1.red()); + const int g = static_cast(static_cast(c2.green() - c1.green()) * fraction + c1.green()); + const int b = static_cast(static_cast(c2.blue() - c1.blue()) * fraction + c1.blue()); return QColor(r, g, b); } @@ -114,7 +114,7 @@ float TimelineWidget::SnapTime(float time) { double t = floor((double)time * m_ticksStep + 0.5); t = t / m_ticksStep; - return t; + return static_cast(t); } ////////////////////////////////////////////////////////////////////////// @@ -147,10 +147,10 @@ void TimelineWidget::DrawTicks(QPainter* painter) painter->setPen(redpen); int x = TimeToClient(m_fTimeMarker); painter->setBrush(Qt::NoBrush); - painter->drawRect(QRect(QPoint(x - 3, rc.top()), QPoint(x + 4, rc.bottom()))); + painter->drawRect(QRect(QPoint(x - 3, static_cast(rc.top())), QPoint(x + 4, static_cast(rc.bottom())))); painter->setPen(redpen); - painter->drawLine(x, rc.top(), x, rc.bottom()); + painter->drawLine(x, static_cast(rc.top()), x, static_cast(rc.bottom())); painter->setBrush(Qt::NoBrush); // Draw vertical line showing current time. @@ -184,7 +184,7 @@ void TimelineWidget::DrawTicks(QPainter* painter) float keyTime = (m_pKeyTimeSet ? m_pKeyTimeSet->GetKeyTime(keyTimeIndex) : 0.0f); int x2 = TimeToClient(keyTime); - painter->drawRect(QRect(QPoint(x2 - 2, rc.top()), QPoint(x2 + 3, rc.bottom()))); + painter->drawRect(QRect(QPoint(x2 - 2, static_cast(rc.top())), QPoint(x2 + 3, static_cast(rc.bottom())))); } painter->setPen(pOldPen); diff --git a/Gems/LyShine/Code/Editor/Animation/UiAVCustomizeTrackColorsDlg.cpp b/Gems/LyShine/Code/Editor/Animation/UiAVCustomizeTrackColorsDlg.cpp index cd7cb56421..533625c762 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAVCustomizeTrackColorsDlg.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAVCustomizeTrackColorsDlg.cpp @@ -320,12 +320,12 @@ bool CUiAVCustomizeTrackColorsDlg::Import(const QString& fullPath) { return entry.paramType == paramType; }); - int entryIndex = pEntry - g_trackEntries; + int entryIndex = static_cast(pEntry - g_trackEntries); if (entryIndex >= arraysize(g_trackEntries)) // If not found, skip this. { continue; } - COLORREF color = -1; + COLORREF color = std::numeric_limits::max(); childNode->getAttr("color", color); m_colorButtons[entryIndex]->SetColor(color); } @@ -333,7 +333,7 @@ bool CUiAVCustomizeTrackColorsDlg::Import(const QString& fullPath) XmlNodeRef othersNode = customTrackColorsNode->findChild("others"); if (othersNode) { - COLORREF color = -1; + COLORREF color = std::numeric_limits::max(); othersNode->getAttr("color", color); m_colorButtons[kOthersEntryIndex]->SetColor(color); } @@ -341,7 +341,7 @@ bool CUiAVCustomizeTrackColorsDlg::Import(const QString& fullPath) XmlNodeRef disabledNode = customTrackColorsNode->findChild("disabled"); if (disabledNode) { - COLORREF color = -1; + COLORREF color = std::numeric_limits::max(); disabledNode->getAttr("color", color); m_colorButtons[kDisabledEntryIndex]->SetColor(color); } @@ -349,7 +349,7 @@ bool CUiAVCustomizeTrackColorsDlg::Import(const QString& fullPath) XmlNodeRef mutedNode = customTrackColorsNode->findChild("muted"); if (mutedNode) { - COLORREF color = -1; + COLORREF color = std::numeric_limits::max(); mutedNode->getAttr("color", color); m_colorButtons[kMutedEntryIndex]->SetColor(color); } diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewCurveEditor.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewCurveEditor.cpp index 339cb4b5bc..51209c7f02 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewCurveEditor.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewCurveEditor.cpp @@ -177,7 +177,7 @@ void CUiAnimViewCurveEditor::UpdateSplines() std::set newTracks; if (selectedTracks.AreAllOfSameType()) { - for (int i = 0; i < selectedTracks.GetCount(); i++) + for (unsigned int i = 0; i < selectedTracks.GetCount(); i++) { CUiAnimViewTrack* pTrack = selectedTracks.GetTrack(i); diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp index ac210ba2f2..6a3afe2036 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDialog.cpp @@ -989,7 +989,7 @@ void CUiAnimViewDialog::ReloadSequencesComboBox() CUiAnimViewSequenceManager* pSequenceManager = CUiAnimViewSequenceManager::GetSequenceManager(); const unsigned int numSequences = pSequenceManager->GetCount(); - for (int k = 0; k < numSequences; ++k) + for (unsigned int k = 0; k < numSequences; ++k) { CUiAnimViewSequence* pSequence = pSequenceManager->GetSequenceByIndex(k); QString fullname = pSequence->GetName(); @@ -1470,7 +1470,7 @@ void CUiAnimViewDialog::OnSnapFPS() if (ok) { m_wndDopeSheet->SetSnapFPS(fps); - m_wndCurveEditor->SetFPS(fps); + m_wndCurveEditor->SetFPS(static_cast(fps)); SetCursorPosText(m_animationContext->GetTime()); } @@ -1541,7 +1541,7 @@ void CUiAnimViewDialog::ReadMiscSettings() if (settings.contains(s_kFrameSnappingFPSEntry)) { - float fps = settings.value(s_kFrameSnappingFPSEntry).toDouble(); + float fps = settings.value(s_kFrameSnappingFPSEntry).toFloat(); m_wndDopeSheet->SetSnapFPS(FloatToIntRet(fps)); m_wndCurveEditor->SetFPS(fps); } diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp index a38736ff67..4e67fb520e 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewDopeSheetBase.cpp @@ -139,8 +139,7 @@ CUiAnimViewDopeSheetBase::~CUiAnimViewDopeSheetBase() ////////////////////////////////////////////////////////////////////////// int CUiAnimViewDopeSheetBase::TimeToClient(float time) const { - int x = m_leftOffset - m_scrollOffset.x() + (time * m_timeScale); - return x; + return static_cast(m_leftOffset - m_scrollOffset.x() + (time * m_timeScale)); } ////////////////////////////////////////////////////////////////////////// @@ -186,7 +185,7 @@ void CUiAnimViewDopeSheetBase::SetTimeRange(float start, float end) m_timeRange.Set(start, end); - SetHorizontalExtent(-m_leftOffset, m_timeRange.end * m_timeScale - m_leftOffset); + SetHorizontalExtent(-m_leftOffset, static_cast(m_timeRange.end * m_timeScale - m_leftOffset)); } ////////////////////////////////////////////////////////////////////////// @@ -251,11 +250,11 @@ void CUiAnimViewDopeSheetBase::SetTimeScale(float timeScale, float fAnchorTime) while (fPixelsPerTick >= 12.0 && steps < 100); float fCurrentOffset = -fAnchorTime * m_timeScale; - m_scrollOffset.rx() += fOldOffset - fCurrentOffset; + m_scrollOffset.rx() += static_cast(fOldOffset - fCurrentOffset); update(); - SetHorizontalExtent(-m_leftOffset, m_timeRange.end * m_timeScale); + SetHorizontalExtent(-m_leftOffset, static_cast(m_timeRange.end * m_timeScale)); ComputeFrameSteps(GetVisibleRange()); } @@ -346,15 +345,15 @@ float CUiAnimViewDopeSheetBase::TickSnap(float time) const double tickTime = GetTickTime(); double t = floor(((double)time / tickTime) + 0.5); t *= tickTime; - return t; + return static_cast(t); } ////////////////////////////////////////////////////////////////////////// float CUiAnimViewDopeSheetBase::TimeFromPoint(const QPoint& point) const { int x = point.x() - m_leftOffset + m_scrollOffset.x(); - double t = (double)x / m_timeScale; - return (float)TickSnap(t); + float t = static_cast(x) / m_timeScale; + return TickSnap(t); } ////////////////////////////////////////////////////////////////////////// @@ -362,7 +361,7 @@ float CUiAnimViewDopeSheetBase::TimeFromPointUnsnapped(const QPoint& point) cons { int x = point.x() - m_leftOffset + m_scrollOffset.x(); double t = (double)x / m_timeScale; - return t; + return static_cast(t); } void CUiAnimViewDopeSheetBase::mousePressEvent(QMouseEvent* event) @@ -925,12 +924,12 @@ void CUiAnimViewDopeSheetBase::SelectAllKeysWithinTimeFrame(const QRect& rc, con CUiAnimViewTrackBundle tracks = pSequence->GetAllTracks(); CUiAnimViewSequenceNotificationContext context(pSequence); - for (int i = 0; i < tracks.GetCount(); ++i) + for (unsigned int i = 0; i < tracks.GetCount(); ++i) { CUiAnimViewTrack* pTrack = tracks.GetTrack(i); // Check which keys we intersect. - for (int j = 0; j < pTrack->GetKeyCount(); j++) + for (unsigned int j = 0; j < pTrack->GetKeyCount(); j++) { CUiAnimViewKeyHandle keyHandle = pTrack->GetKey(j); const float time = keyHandle.GetTime(); @@ -1311,7 +1310,7 @@ bool CUiAnimViewDopeSheetBase::IsOkToAddKeyHere(const CUiAnimViewTrack* pTrack, { const float timeEpsilon = 0.05f; - for (int i = 0; i < pTrack->GetKeyCount(); ++i) + for (unsigned int i = 0; i < pTrack->GetKeyCount(); ++i) { CUiAnimViewKeyHandle keyHandle = const_cast(pTrack)->GetKey(i); @@ -1425,10 +1424,10 @@ void CUiAnimViewDopeSheetBase::MouseMoveMove(const QPoint& p, [[maybe_unused]] Q const TrackMemento& trackMemento = iter->second; pTrack->RestoreFromMemento(trackMemento.m_memento); - const unsigned int numKeys = trackMemento.m_keySelectionStates.size(); - for (unsigned int i = 0; i < numKeys; ++i) + const size_t numKeys = trackMemento.m_keySelectionStates.size(); + for (size_t i = 0; i < numKeys; ++i) { - pTrack->GetKey(i).Select(trackMemento.m_keySelectionStates[i]); + pTrack->GetKey(static_cast(i)).Select(trackMemento.m_keySelectionStates[i]); } } @@ -1632,7 +1631,7 @@ float CUiAnimViewDopeSheetBase::MagnetSnap(float newTime, const CUiAnimViewAnimN newTime = keys.GetKey(0).GetTime(); // But if there is an in-range key in a sibling track, use it instead. // Here a 'sibling' means a track that belongs to a same node. - for (int i = 0; i < keys.GetKeyCount(); ++i) + for (unsigned int i = 0; i < keys.GetKeyCount(); ++i) { CUiAnimViewKeyHandle keyHandle = keys.GetKey(i); if (keyHandle.GetTrack()->GetAnimNode() == pNode) @@ -1651,7 +1650,7 @@ float CUiAnimViewDopeSheetBase::FrameSnap(float time) const { double t = floor((double)time / m_snapFrameTime + 0.5); t = t * m_snapFrameTime; - return t; + return static_cast(t); } ////////////////////////////////////////////////////////////////////////// @@ -1755,9 +1754,10 @@ bool CUiAnimViewDopeSheetBase::CreateColorKey(CUiAnimViewTrack* pTrack, float ke Vec3 vColor(0, 0, 0); pTrack->GetValue(keyTime, vColor); - const AZ::Color defaultColor = AZ::Color::CreateFromRgba(clamp_tpl(FloatToIntRet(vColor.x), 0, 255), - clamp_tpl(FloatToIntRet(vColor.y), 0, 255), - clamp_tpl(FloatToIntRet(vColor.z), 0, 255), 255); + const AZ::Color defaultColor = AZ::Color::CreateFromRgba( + clamp_tpl(static_cast(FloatToIntRet(vColor.x)), AZ::u8(0), AZ::u8(255)), + clamp_tpl(static_cast(FloatToIntRet(vColor.y)), AZ::u8(0), AZ::u8(255)), + clamp_tpl(static_cast(FloatToIntRet(vColor.z)), AZ::u8(0), AZ::u8(255)), 255); AzQtComponents::ColorPicker dlg(AzQtComponents::ColorPicker::Configuration::RGB, tr("Select Color"), this); dlg.setCurrentColor(defaultColor); dlg.setSelectedColor(defaultColor); @@ -1770,7 +1770,7 @@ bool CUiAnimViewDopeSheetBase::CreateColorKey(CUiAnimViewTrack* pTrack, float ke CUiAnimViewSequenceNotificationContext context(pTrack->GetSequence()); const unsigned int numChildNodes = pTrack->GetChildCount(); - for (int i = 0; i < numChildNodes; ++i) + for (unsigned int i = 0; i < numChildNodes; ++i) { CUiAnimViewTrack* subTrack = static_cast(pTrack->GetChild(i)); if (IsOkToAddKeyHere(subTrack, keyTime)) @@ -1890,7 +1890,7 @@ void CUiAnimViewDopeSheetBase::AddKeys(const QPoint& point, const bool bTryAddKe } else // A compound track { - for (int k = 0; k < pCurrTrack->GetChildCount(); ++k) + for (unsigned int k = 0; k < pCurrTrack->GetChildCount(); ++k) { CUiAnimViewTrack* pSubTrack = static_cast(pCurrTrack->GetChild(k)); if (IsOkToAddKeyHere(pSubTrack, keyTime)) @@ -1921,7 +1921,7 @@ void CUiAnimViewDopeSheetBase::AddKeys(const QPoint& point, const bool bTryAddKe else { RecordTrackUndo(pTrack); - for (int i = 0; i < pTrack->GetChildCount(); ++i) + for (unsigned int i = 0; i < pTrack->GetChildCount(); ++i) { CUiAnimViewTrack* pSubTrack = static_cast(pTrack->GetChild(i)); if (IsOkToAddKeyHere(pSubTrack, keyTime)) @@ -1997,12 +1997,12 @@ void CUiAnimViewDopeSheetBase::DrawTicks(QPainter* painter, const QRect& rc, Ran nNumberTicks = 8; } - double start = TickSnap(timeRange.start); - double step = 1.0 / m_ticksStep; + float start = TickSnap(timeRange.start); + float step = 1.0f / static_cast(m_ticksStep); - for (double t = 0.0f; t <= timeRange.end + step; t += step) + for (float t = 0.0f; t <= timeRange.end + step; t += step) { - double st = TickSnap(t); + float st = TickSnap(t); if (st > timeRange.end) { st = timeRange.end; @@ -2021,7 +2021,7 @@ void CUiAnimViewDopeSheetBase::DrawTicks(QPainter* painter, const QRect& rc, Ran continue; } - int k = RoundFloatToInt(st * m_ticksStep); + int k = RoundFloatToInt(st * static_cast(m_ticksStep)); if (k % nNumberTicks == 0) { if (st >= start) @@ -2619,7 +2619,7 @@ void CUiAnimViewDopeSheetBase::SelectKeys(const QRect& rc, const bool bMultiSele CUiAnimViewTrackBundle tracks = pSequence->GetAllTracks(); - for (int i = 0; i < tracks.GetCount(); ++i) + for (unsigned int i = 0; i < tracks.GetCount(); ++i) { CUiAnimViewTrack* pTrack = tracks.GetTrack(i); @@ -2633,7 +2633,7 @@ void CUiAnimViewDopeSheetBase::SelectKeys(const QRect& rc, const bool bMultiSele (rc.bottom() >= trackRect.top() && rc.bottom() <= trackRect.bottom())) { // Check which keys we intersect. - for (int j = 0; j < pTrack->GetKeyCount(); j++) + for (unsigned int j = 0; j < pTrack->GetKeyCount(); j++) { CUiAnimViewKeyHandle keyHandle = pTrack->GetKey(j); @@ -2700,7 +2700,7 @@ void CUiAnimViewDopeSheetBase::DrawSelectedKeyIndicators(QPainter* painter) painter->setPen(Qt::green); CUiAnimViewKeyBundle keys = pSequence->GetSelectedKeys(); - for (int i = 0; i < keys.GetKeyCount(); ++i) + for (unsigned int i = 0; i < keys.GetKeyCount(); ++i) { CUiAnimViewKeyHandle keyHandle = keys.GetKey(i); int x = TimeToClient(keyHandle.GetTime()); @@ -2743,7 +2743,7 @@ void CUiAnimViewDopeSheetBase::ComputeFrameSteps(const Range& visRange) float nBIntermediateTicks = 5; m_fFrameLabelStep = fFact * afStepTable[nStepIdx]; - if (TimeToClient(m_fFrameLabelStep) - TimeToClient(0) > 1300) + if (TimeToClient(static_cast(m_fFrameLabelStep)) - TimeToClient(0) > 1300) { nBIntermediateTicks = 10; } @@ -2755,7 +2755,7 @@ void CUiAnimViewDopeSheetBase::ComputeFrameSteps(const Range& visRange) void CUiAnimViewDopeSheetBase::DrawTimeLineInFrames(QPainter* painter, const QRect& rc, [[maybe_unused]] const QColor& lineCol, const QColor& textCol, [[maybe_unused]] double step) { float fFramesPerSec = 1.0f / m_snapFrameTime; - float fInvFrameLabelStep = 1.0f / m_fFrameLabelStep; + float fInvFrameLabelStep = 1.0f / static_cast(m_fFrameLabelStep); Range VisRange = GetVisibleRange(); const Range& timeRange = m_timeRange; @@ -2763,9 +2763,9 @@ void CUiAnimViewDopeSheetBase::DrawTimeLineInFrames(QPainter* painter, const QRe const QPen ltgray(QColor(90, 90, 90)); const QPen black(textCol); - for (double t = TickSnap(timeRange.start); t <= timeRange.end + m_fFrameTickStep; t += m_fFrameTickStep) + for (float t = TickSnap(timeRange.start); t <= timeRange.end + static_cast(m_fFrameTickStep); t += static_cast(m_fFrameTickStep)) { - double st = t; + float st = t; if (st > timeRange.end) { st = timeRange.end; @@ -2810,9 +2810,9 @@ void CUiAnimViewDopeSheetBase::DrawTimeLineInSeconds(QPainter* painter, const QR const QPen ltgray(QColor(90, 90, 90)); const QPen black(textCol); - for (double t = TickSnap(timeRange.start); t <= timeRange.end + step; t += step) + for (float t = TickSnap(timeRange.start); t <= timeRange.end + static_cast(step); t += static_cast(step)) { - double st = TickSnap(t); + float st = TickSnap(t); if (st > timeRange.end) { st = timeRange.end; @@ -2831,7 +2831,7 @@ void CUiAnimViewDopeSheetBase::DrawTimeLineInSeconds(QPainter* painter, const QR } int x = TimeToClient(st); - int k = RoundFloatToInt(st * m_ticksStep); + int k = RoundFloatToInt(st * static_cast(m_ticksStep)); if (k % nNumberTicks == 0) { painter->setPen(black); @@ -2951,7 +2951,7 @@ void CUiAnimViewDopeSheetBase::DrawSummary(QPainter* painter, const QRect& rcUpd // Draw a short thick line at each place where there is a key in any tracks. CUiAnimViewKeyBundle keys = pSequence->GetAllKeys(); - for (int i = 0; i < keys.GetKeyCount(); ++i) + for (unsigned int i = 0; i < keys.GetKeyCount(); ++i) { CUiAnimViewKeyHandle keyHandle = keys.GetKey(i); int x = TimeToClient(keyHandle.GetTime()); @@ -3112,7 +3112,7 @@ void CUiAnimViewDopeSheetBase::StoreMementoForTracksWithSelectedKeys() std::set tracks; const unsigned int numKeys = selectedKeys.GetKeyCount(); - for (int keyIndex = 0; keyIndex < numKeys; ++keyIndex) + for (unsigned int keyIndex = 0; keyIndex < numKeys; ++keyIndex) { CUiAnimViewKeyHandle keyHandle = selectedKeys.GetKey(keyIndex); tracks.insert(keyHandle.GetTrack()); diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp index 820849bc93..74d2c7d4fb 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp @@ -95,88 +95,16 @@ public: } protected: - void dragMoveEvent(QDragMoveEvent* event) + void dragMoveEvent([[maybe_unused]] QDragMoveEvent* event) { // For now we do not support any drag and drop in the Nodes pane return; - - CUiAnimViewNodesCtrl::CRecord* pRecord = (CUiAnimViewNodesCtrl::CRecord*) itemAt(event->pos()); - if (!pRecord) - { - return; - } - CUiAnimViewNode* pTargetNode = pRecord->GetNode(); - - QTreeWidget::dragMoveEvent(event); - if (!event->isAccepted()) - { - return; - } - - if (pTargetNode && pTargetNode->IsGroupNode() /*&& !m_draggedNodes.DoesContain(pTargetNode)*/) - { - CUiAnimViewAnimNode* pDragTarget = static_cast(pTargetNode); - bool bAllValidReparenting = true; - QList nodes = draggedNodes(event); - Q_FOREACH(CUiAnimViewAnimNode * pDraggedNode, nodes) - { - if (!pDraggedNode->IsValidReparentingTo(pDragTarget)) - { - bAllValidReparenting = false; - break; - } - } - - if (!bAllValidReparenting) - { - event->ignore(); - } - - return; - } } - void dropEvent(QDropEvent* event) + void dropEvent([[maybe_unused]] QDropEvent* event) { // For now we do not support any drag and drop in the Nodes pane return; - - CUiAnimViewNodesCtrl::CRecord* pRecord = (CUiAnimViewNodesCtrl::CRecord*) itemAt(event->pos()); - if (!pRecord) - { - return; - } - CUiAnimViewNode* pTargetNode = pRecord->GetNode(); - - QTreeWidget::dropEvent(event); - if (!event->isAccepted()) - { - return; - } - - if (pTargetNode && pTargetNode->IsGroupNode() /*&& !m_draggedNodes.DoesContain(pTargetNode)*/) - { - CUiAnimViewAnimNode* pDragTarget = static_cast(pTargetNode); - bool bAllValidReparenting = true; - QList nodes = draggedNodes(event); - Q_FOREACH(CUiAnimViewAnimNode * pDraggedNode, nodes) - { - if (!pDraggedNode->IsValidReparentingTo(pDragTarget)) - { - bAllValidReparenting = false; - break; - } - } - - if (bAllValidReparenting) - { - UiAnimUndo undo("Drag and Drop UiAnimView Nodes"); - Q_FOREACH(CUiAnimViewAnimNode * pDraggedNode, nodes) - { - pDraggedNode->SetNewParent(pDragTarget); - } - } - } } void keyPressEvent(QKeyEvent* event) diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSplineCtrl.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSplineCtrl.cpp index ba4893abb4..8edd13f8cc 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSplineCtrl.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSplineCtrl.cpp @@ -667,7 +667,7 @@ void CUiAnimViewSplineCtrl::mouseMoveEvent(QMouseEvent* event) QString tipText; bool boFoundTheSelectedKey(false); - for (int splineIndex = 0, endSpline = m_splines.size(); splineIndex < endSpline; ++splineIndex) + for (size_t splineIndex = 0, endSpline = m_splines.size(); splineIndex < endSpline; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; CUiAnimViewTrack* pTrack = m_tracks[splineIndex]; @@ -757,7 +757,7 @@ void CUiAnimViewSplineCtrl::AdjustTCB(float d_tension, float d_continuity, float SendNotifyEvent(SPLN_BEFORE_CHANGE); - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; CUiAnimViewTrack* pTrack = m_tracks[splineIndex]; @@ -866,16 +866,16 @@ void CUiAnimViewSplineCtrl::OnUserCommand(UINT cmd) bool CUiAnimViewSplineCtrl::IsUnifiedKeyCurrentlySelected() const { - for (int splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) + for (size_t splineIndex = 0, splineCount = m_splines.size(); splineIndex < splineCount; ++splineIndex) { ISplineInterpolator* pSpline = m_splines[splineIndex].pSpline; - if (pSpline == NULL) + if (!pSpline) { continue; } - for (int i = 0; i < (int)pSpline->GetKeyCount(); i++) + for (int i = 0; i < pSpline->GetKeyCount(); i++) { // If the key is selected in any dimension... for ( diff --git a/Gems/LyShine/Code/Editor/EditorCommon.h b/Gems/LyShine/Code/Editor/EditorCommon.h index ebe5b89cfc..9af5958c67 100644 --- a/Gems/LyShine/Code/Editor/EditorCommon.h +++ b/Gems/LyShine/Code/Editor/EditorCommon.h @@ -34,8 +34,6 @@ #include #include -#pragma warning(disable: 4355) // 'this' : used in base member initializer list - class CanvasSizeToolbarSection; class CommandCanvasPropertiesChange; class CommandCanvasSizeToolbarIndex; diff --git a/Gems/LyShine/Code/Editor/PropertiesContainer.cpp b/Gems/LyShine/Code/Editor/PropertiesContainer.cpp index 21b3b99b02..9f9023f84d 100644 --- a/Gems/LyShine/Code/Editor/PropertiesContainer.cpp +++ b/Gems/LyShine/Code/Editor/PropertiesContainer.cpp @@ -595,7 +595,7 @@ bool PropertiesContainer::DoesIntersectNonSelectedComponentEditor(const QRect& g void PropertiesContainer::ClearComponentEditorSelection() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (auto componentEditor : m_componentEditors) { componentEditor->SetSelected(false); diff --git a/Gems/LyShine/Code/Editor/QtHelpers.cpp b/Gems/LyShine/Code/Editor/QtHelpers.cpp index 8b6063a055..d9147463ed 100644 --- a/Gems/LyShine/Code/Editor/QtHelpers.cpp +++ b/Gems/LyShine/Code/Editor/QtHelpers.cpp @@ -32,8 +32,7 @@ namespace QtHelpers float GetHighDpiScaleFactor(const QWidget& widget) { - float dpiScale = QHighDpiScaling::factor(widget.windowHandle()->screen()); - return dpiScale; + return static_cast(QHighDpiScaling::factor(widget.windowHandle()->screen())); } QSize GetDpiScaledViewportSize(const QWidget& widget) @@ -41,7 +40,7 @@ namespace QtHelpers float dpiScale = GetHighDpiScaleFactor(widget); float width = ceilf(widget.size().width() * dpiScale); float height = ceilf(widget.size().height() * dpiScale); - return QSize(width, height); + return QSize(static_cast(width), static_cast(height)); } } // namespace QtHelpers diff --git a/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp b/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp index f53da64110..04f655123c 100644 --- a/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp +++ b/Gems/LyShine/Code/Editor/SpriteBorderEditor.cpp @@ -310,7 +310,7 @@ void SpriteBorderEditor::AddConfigureSection(QGridLayout* gridLayout, int& rowNu int newNumCols = numColsLineEdit->text().toInt(&colConversionSuccess); const bool positiveInputs = newNumRows > 0 && newNumCols > 0; - const bool valueChanged = m_numRows != newNumRows || m_numCols != newNumCols; + const bool valueChanged = m_numRows != static_cast(newNumRows) || m_numCols != static_cast(newNumCols); // This number of cells is just nearly unusable in the sprite editor UI. Supporting // more would likely require reworking of UX/UI and even implementation. diff --git a/Gems/LyShine/Code/Editor/UiSliceManager.cpp b/Gems/LyShine/Code/Editor/UiSliceManager.cpp index c86da38d80..97e9a51e11 100644 --- a/Gems/LyShine/Code/Editor/UiSliceManager.cpp +++ b/Gems/LyShine/Code/Editor/UiSliceManager.cpp @@ -158,7 +158,7 @@ bool UiSliceManager::MakeNewSlice( bool inheritSlices, AZ::SerializeContext* serializeContext) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (entities.empty()) { @@ -240,7 +240,7 @@ bool UiSliceManager::MakeNewSlice( // Setup and execute transaction for the new slice. // { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "UiSliceManager::MakeNewSlice:SetupAndExecuteTransaction"); + AZ_PROFILE_SCOPE(AzToolsFramework, "UiSliceManager::MakeNewSlice:SetupAndExecuteTransaction"); using AzToolsFramework::SliceUtilities::SliceTransaction; @@ -249,7 +249,7 @@ bool UiSliceManager::MakeNewSlice( [this, &entitiesToInclude, &commonParent, &insertBefore] (SliceTransaction::TransactionPtr transaction, const char* fullPath, const SliceTransaction::SliceAssetPtr& /*asset*/) -> void { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "UiSliceManager::MakeNewSlice:PostSaveCallback"); + AZ_PROFILE_SCOPE(AzToolsFramework, "UiSliceManager::MakeNewSlice:PostSaveCallback"); // Once the asset is processed and ready, we can replace the source entities with an instance of the new slice. UiEditorEntityContextRequestBus::Event(m_entityContextId, &UiEditorEntityContextRequestBus::Events::QueueSliceReplacement, @@ -260,7 +260,7 @@ bool UiSliceManager::MakeNewSlice( // Add entities { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "UiSliceManager::MakeNewSlice:SetupAndExecuteTransaction:AddEntities"); + AZ_PROFILE_SCOPE(AzToolsFramework, "UiSliceManager::MakeNewSlice:SetupAndExecuteTransaction:AddEntities"); for (const AZ::EntityId& entityId : orderedEntityList) { SliceTransaction::Result addResult = transaction->AddEntity(entityId, !inheritSlices ? SliceTransaction::SliceAddEntityFlags::DiscardSliceAncestry : 0); @@ -348,7 +348,7 @@ AzToolsFramework::SliceUtilities::SliceTransaction::Result SlicePreSaveCallbackF [[maybe_unused]] const char* fullPath, AzToolsFramework::SliceUtilities::SliceTransaction::SliceAssetPtr& asset) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "SlicePreSaveCallbackForUiEntities"); + AZ_PROFILE_SCOPE(AzToolsFramework, "SlicePreSaveCallbackForUiEntities"); // we want to ensure that "bad" data never gets pushed to a slice // This mostly relates to the m_childEntityIdOrder array since this is something that diff --git a/Gems/LyShine/Code/Editor/ViewportIcon.cpp b/Gems/LyShine/Code/Editor/ViewportIcon.cpp index e4ada665d5..e3ad68922e 100644 --- a/Gems/LyShine/Code/Editor/ViewportIcon.cpp +++ b/Gems/LyShine/Code/Editor/ViewportIcon.cpp @@ -27,7 +27,7 @@ AZ::Vector2 ViewportIcon::GetTextureSize() const if (m_image) { AZ::RHI::Size size = m_image->GetDescriptor().m_size; - AZ::Vector2 scaledSize(size.m_width, size.m_height); + AZ::Vector2 scaledSize(static_cast(size.m_width), static_cast(size.m_height)); if (m_applyDpiScaleFactorToSize) { scaledSize *= m_dpiScaleFactor; diff --git a/Gems/LyShine/Code/Editor/ViewportWidget.cpp b/Gems/LyShine/Code/Editor/ViewportWidget.cpp index 1ce8f5b64d..e172d43b60 100644 --- a/Gems/LyShine/Code/Editor/ViewportWidget.cpp +++ b/Gems/LyShine/Code/Editor/ViewportWidget.cpp @@ -1001,7 +1001,7 @@ void ViewportWidget::RenderEditMode() // Render this canvas QSize scaledViewportSize = QtHelpers::GetDpiScaledViewportSize(*this); - AZ::Vector2 viewportSize(scaledViewportSize.width(), scaledViewportSize.height()); + AZ::Vector2 viewportSize(static_cast(scaledViewportSize.width()), static_cast(scaledViewportSize.height())); EBUS_EVENT_ID(canvasEntityId, UiEditorCanvasBus, RenderCanvasInEditorViewport, false, viewportSize); m_draw2d->SetSortKey(topLayerKey); @@ -1111,7 +1111,7 @@ void ViewportWidget::UpdatePreviewMode(float deltaTime) if (canvasEntityId.IsValid()) { QSize scaledViewportSize = QtHelpers::GetDpiScaledViewportSize(*this); - AZ::Vector2 viewportSize(scaledViewportSize.width(), scaledViewportSize.height()); + AZ::Vector2 viewportSize(static_cast(scaledViewportSize.width()), static_cast(scaledViewportSize.height())); // Get the canvas size AZ::Vector2 canvasSize = m_editorWindow->GetPreviewCanvasSize(); @@ -1153,7 +1153,7 @@ void ViewportWidget::RenderPreviewMode() if (canvasEntityId.IsValid()) { QSize scaledViewportSize = QtHelpers::GetDpiScaledViewportSize(*this); - AZ::Vector2 viewportSize(scaledViewportSize.width(), scaledViewportSize.height()); + AZ::Vector2 viewportSize(static_cast(scaledViewportSize.width()), static_cast(scaledViewportSize.height())); // Get the canvas size AZ::Vector2 canvasSize = m_editorWindow->GetPreviewCanvasSize(); @@ -1239,7 +1239,7 @@ void ViewportWidget::RenderViewportBackground() Draw2dHelper draw2d(m_draw2d.get()); draw2d.SetImageColor(backgroundColor.GetAsVector3()); - draw2d.DrawImage(image, AZ::Vector2(0.0f, 0.0f), AZ::Vector2(viewportSize.width(), viewportSize.height())); + draw2d.DrawImage(image, AZ::Vector2(0.0f, 0.0f), AZ::Vector2(static_cast(viewportSize.width()), static_cast(viewportSize.height()))); } void ViewportWidget::SetupShortcuts() diff --git a/Gems/LyShine/Code/Source/Animation/2DSpline.h b/Gems/LyShine/Code/Source/Animation/2DSpline.h index 60589e1344..b831bd669a 100644 --- a/Gems/LyShine/Code/Source/Animation/2DSpline.h +++ b/Gems/LyShine/Code/Source/Animation/2DSpline.h @@ -62,7 +62,7 @@ namespace UiSpline ILINE void flag_clr(int flag) { m_flags &= ~flag; }; ILINE int flag(int flag) { return m_flags & flag; }; - ILINE void ORT(int ort) { m_ORT = ort; }; + ILINE void ORT(int ort) { m_ORT = static_cast(ort); }; ILINE int ORT() const { return m_ORT; }; ILINE int isORT(int o) const { return (m_ORT == o); }; diff --git a/Gems/LyShine/Code/Source/Animation/AnimTrack.h b/Gems/LyShine/Code/Source/Animation/AnimTrack.h index f73cd7ede7..df0ae3a805 100644 --- a/Gems/LyShine/Code/Source/Animation/AnimTrack.h +++ b/Gems/LyShine/Code/Source/Animation/AnimTrack.h @@ -221,6 +221,8 @@ protected: float m_lastTime; int m_flags; + static constexpr unsigned int InvalidKey = 0x7FFFFFFF; + UiAnimParamData m_componentParamData; #ifdef UI_ANIMATION_SYSTEM_SUPPORT_EDITING @@ -521,7 +523,7 @@ inline int TUiAnimTrack::GetActiveKey(float time, KeyType* key) if (nkeys == 0) { m_lastTime = time; - m_currKey = -1; + m_currKey = InvalidKey; return m_currKey; } @@ -554,7 +556,7 @@ inline int TUiAnimTrack::GetActiveKey(float time, KeyType* key) } else { - m_currKey = -1; + m_currKey = InvalidKey; } return m_currKey; } @@ -600,6 +602,6 @@ inline int TUiAnimTrack::GetActiveKey(float time, KeyType* key) break; } } - m_currKey = -1; + m_currKey = InvalidKey; return m_currKey; } diff --git a/Gems/LyShine/Code/Source/LyShineDebug.cpp b/Gems/LyShine/Code/Source/LyShineDebug.cpp index c7dccc162f..a30f816c73 100644 --- a/Gems/LyShine/Code/Source/LyShineDebug.cpp +++ b/Gems/LyShine/Code/Source/LyShineDebug.cpp @@ -115,7 +115,7 @@ static int Create2DTexture(int width, int height, byte* data, ETEX_Format format static AZ::Vector2 GetTextureSize(AZ::Data::Instance image) { AZ::RHI::Size size = image->GetDescriptor().m_size; - return AZ::Vector2(size.m_width, size.m_height); + return AZ::Vector2(static_cast(size.m_width), static_cast(size.m_height)); } #endif diff --git a/Gems/LyShine/Code/Source/LyShinePass.cpp b/Gems/LyShine/Code/Source/LyShinePass.cpp index fbf7f34e14..8245294696 100644 --- a/Gems/LyShine/Code/Source/LyShinePass.cpp +++ b/Gems/LyShine/Code/Source/LyShinePass.cpp @@ -135,7 +135,7 @@ namespace LyShine passData->m_pipelineViewTag = AZ::Name("MainCamera"); auto size = attachmentImage->GetRHIImage()->GetDescriptor().m_size; passData->m_overrideScissor = AZ::RHI::Scissor(0, 0, size.m_width, size.m_height); - passData->m_overrideViewport = AZ::RHI::Viewport(0, size.m_width, 0, size.m_height); + passData->m_overrideViewport = AZ::RHI::Viewport(0, static_cast(size.m_width), 0, static_cast(size.m_height)); passTemplate->m_passData = AZStd::move(passData); // Create a pass descriptor for the new child pass AZ::RPI::PassDescriptor childDesc; diff --git a/Gems/LyShine/Code/Source/RenderGraph.cpp b/Gems/LyShine/Code/Source/RenderGraph.cpp index b07aab78c7..51f62fc7ad 100644 --- a/Gems/LyShine/Code/Source/RenderGraph.cpp +++ b/Gems/LyShine/Code/Source/RenderGraph.cpp @@ -386,7 +386,7 @@ namespace LyShine curBaseState.m_stencilState.m_backFace = stencilOpState; // set up for stencil write - dynamicDraw->SetStencilReference(uiRenderer->GetStencilRef()); + dynamicDraw->SetStencilReference(static_cast(uiRenderer->GetStencilRef())); curBaseState.m_stencilState.m_enable = true; curBaseState.m_stencilState.m_writeMask = 0xFF; } @@ -420,7 +420,7 @@ namespace LyShine uiRenderer->DecrementStencilRef(); } - dynamicDraw->SetStencilReference(uiRenderer->GetStencilRef()); + dynamicDraw->SetStencilReference(static_cast(uiRenderer->GetStencilRef())); if (firstPass) { @@ -790,7 +790,7 @@ namespace LyShine { for (int i = 0; i < primitive->m_numVertices; ++i) { - primitive->m_vertices[i].texIndex = texUnit; + primitive->m_vertices[i].texIndex = static_cast(texUnit); } } @@ -881,8 +881,8 @@ namespace LyShine { for (int i = 0; i < primitive->m_numVertices; ++i) { - primitive->m_vertices[i].texIndex = texUnit0; - primitive->m_vertices[i].texIndex2 = texUnit1; + primitive->m_vertices[i].texIndex = aznumeric_cast(texUnit0); + primitive->m_vertices[i].texIndex2 = aznumeric_cast(texUnit1); } } diff --git a/Gems/LyShine/Code/Source/Sprite.cpp b/Gems/LyShine/Code/Source/Sprite.cpp index a097e23dfe..7f293e57a3 100644 --- a/Gems/LyShine/Code/Source/Sprite.cpp +++ b/Gems/LyShine/Code/Source/Sprite.cpp @@ -368,7 +368,7 @@ AZ::Vector2 CSprite::GetSize() } AZ::RHI::Size size = image->GetRHIImage()->GetDescriptor().m_size; - return AZ::Vector2(size.m_width, size.m_height); + return AZ::Vector2(static_cast(size.m_width), static_cast(size.m_height)); } else { diff --git a/Gems/LyShine/Code/Source/StringUtfUtils.h b/Gems/LyShine/Code/Source/StringUtfUtils.h index 40dd22dd33..9c185d48ef 100644 --- a/Gems/LyShine/Code/Source/StringUtfUtils.h +++ b/Gems/LyShine/Code/Source/StringUtfUtils.h @@ -31,7 +31,7 @@ namespace LyShine // work for cases tested but may not in general. // In the long run it would be better to eliminate // this function and use some sequence_lenght function that is not internal. - return Utf8::Internal::sequence_length(&multiByteChar); + return static_cast(Utf8::Internal::sequence_length(&multiByteChar)); } inline int GetByteLengthOfUtf8Chars(const char* utf8String, int numUtf8Chars) diff --git a/Gems/LyShine/Code/Source/UiCanvasManager.cpp b/Gems/LyShine/Code/Source/UiCanvasManager.cpp index 5f2adcd20c..d13a8f5034 100644 --- a/Gems/LyShine/Code/Source/UiCanvasManager.cpp +++ b/Gems/LyShine/Code/Source/UiCanvasManager.cpp @@ -808,7 +808,7 @@ UiCanvasComponent* UiCanvasManager::FindEditorCanvasComponentByPathname(const AZ } //////////////////////////////////////////////////////////////////////////////////////////////////// -bool UiCanvasManager::HandleInputEventForInWorldCanvases(const AzFramework::InputChannel::Snapshot& inputSnapshot, const AZ::Vector2& viewportPos) +bool UiCanvasManager::HandleInputEventForInWorldCanvases([[maybe_unused]] const AzFramework::InputChannel::Snapshot& inputSnapshot, [[maybe_unused]] const AZ::Vector2& viewportPos) { // First we need to construct a ray from the either the center of the screen or the mouse position. // This requires knowledge of the camera @@ -816,86 +816,86 @@ bool UiCanvasManager::HandleInputEventForInWorldCanvases(const AzFramework::Inpu // ToDo: Re-implement by getting the camera from Atom. LYN-3680 return false; - const CCamera cam; - - // construct a ray from the camera position in the view direction of the camera - const float rayLength = 5000.0f; - Vec3 rayOrigin(cam.GetPosition()); - Vec3 rayDirection = cam.GetViewdir() * rayLength; - - // If the mouse cursor is visible we will assume that the ray should be in the direction of the - // mouse pointer. This is a temporary solution. A better solution is to be able to configure the - // LyShine system to say how ray input should be handled. - bool isCursorVisible = false; - UiCursorBus::BroadcastResult(isCursorVisible, &UiCursorInterface::IsUiCursorVisible); - if (isCursorVisible) - { - // for some reason Unproject seems to work when given the viewport pos with (0,0) at the - // bottom left as opposed to the top left - even though that function specifically sets top left - // to (0,0). - const float viewportYInverted = cam.GetViewSurfaceZ() - viewportPos.GetY(); - - // Unproject to get the screen position in world space, use arbitrary Z that is within the depth range - Vec3 flippedViewportRayOrigin(viewportPos.GetX(), viewportYInverted, 0.f); - Vec3 flippedViewportRayForward(viewportPos.GetX(), viewportYInverted, 1.f); - - cam.Unproject(flippedViewportRayOrigin, rayOrigin); - - Vec3 unprojectedPosForward; - cam.Unproject(flippedViewportRayForward, unprojectedPosForward); - - // We want a vector relative to the camera origin - Vec3 rayVec = unprojectedPosForward - rayOrigin; - - // we want to ensure that the ray is a certain length so normalize it and scale it - rayVec.NormalizeSafe(); - rayDirection = rayVec * rayLength; - } - - - AzFramework::EntityContextId gameContextId; - AzFramework::GameEntityContextRequestBus::BroadcastResult(gameContextId, - &AzFramework::GameEntityContextRequests::GetGameEntityContextId); - - AzFramework::RenderGeometry::RayRequest request; - request.m_startWorldPosition = LYVec3ToAZVec3(rayOrigin); - request.m_endWorldPosition = LYVec3ToAZVec3(rayOrigin + rayDirection); - - AzFramework::RenderGeometry::RayResult rayResult; - AzFramework::RenderGeometry::IntersectorBus::EventResult(rayResult, gameContextId, - &AzFramework::RenderGeometry::IntersectorInterface::RayIntersect, request); - - if (rayResult) - { - AZ::EntityId hitEntity = rayResult.m_entityAndComponent.GetEntityId(); - if (hitEntity.IsValid()) - { - AZ::EntityId canvasEntityId; - UiCanvasRefBus::EventResult(canvasEntityId, hitEntity, &UiCanvasRefInterface::GetCanvas); - if (canvasEntityId.IsValid()) - { - // Checkif the UI canvas referenced by the hit entity supports automatic input - bool doesCanvasSupportInput = false; - UiCanvasBus::EventResult(doesCanvasSupportInput, canvasEntityId, &UiCanvasInterface::GetIsPositionalInputSupported); - - if (doesCanvasSupportInput) - { - // set the hit details to the hit entity, it will convert into canvas coords and send to canvas - bool handled = false; - UiCanvasOnMeshBus::EventResult(handled, hitEntity, - &UiCanvasOnMeshInterface::ProcessHitInputEvent, inputSnapshot, rayResult); - - if (handled) - { - return true; - } - } - } - } - } - - - return false; + //const CCamera cam; + // + //// construct a ray from the camera position in the view direction of the camera + //const float rayLength = 5000.0f; + //Vec3 rayOrigin(cam.GetPosition()); + //Vec3 rayDirection = cam.GetViewdir() * rayLength; + // + //// If the mouse cursor is visible we will assume that the ray should be in the direction of the + //// mouse pointer. This is a temporary solution. A better solution is to be able to configure the + //// LyShine system to say how ray input should be handled. + //bool isCursorVisible = false; + //UiCursorBus::BroadcastResult(isCursorVisible, &UiCursorInterface::IsUiCursorVisible); + //if (isCursorVisible) + //{ + // // for some reason Unproject seems to work when given the viewport pos with (0,0) at the + // // bottom left as opposed to the top left - even though that function specifically sets top left + // // to (0,0). + // const float viewportYInverted = cam.GetViewSurfaceZ() - viewportPos.GetY(); + // + // // Unproject to get the screen position in world space, use arbitrary Z that is within the depth range + // Vec3 flippedViewportRayOrigin(viewportPos.GetX(), viewportYInverted, 0.f); + // Vec3 flippedViewportRayForward(viewportPos.GetX(), viewportYInverted, 1.f); + // + // cam.Unproject(flippedViewportRayOrigin, rayOrigin); + // + // Vec3 unprojectedPosForward; + // cam.Unproject(flippedViewportRayForward, unprojectedPosForward); + // + // // We want a vector relative to the camera origin + // Vec3 rayVec = unprojectedPosForward - rayOrigin; + // + // // we want to ensure that the ray is a certain length so normalize it and scale it + // rayVec.NormalizeSafe(); + // rayDirection = rayVec * rayLength; + //} + // + // + //AzFramework::EntityContextId gameContextId; + //AzFramework::GameEntityContextRequestBus::BroadcastResult(gameContextId, + // &AzFramework::GameEntityContextRequests::GetGameEntityContextId); + // + //AzFramework::RenderGeometry::RayRequest request; + //request.m_startWorldPosition = LYVec3ToAZVec3(rayOrigin); + //request.m_endWorldPosition = LYVec3ToAZVec3(rayOrigin + rayDirection); + // + //AzFramework::RenderGeometry::RayResult rayResult; + //AzFramework::RenderGeometry::IntersectorBus::EventResult(rayResult, gameContextId, + // &AzFramework::RenderGeometry::IntersectorInterface::RayIntersect, request); + // + //if (rayResult) + //{ + // AZ::EntityId hitEntity = rayResult.m_entityAndComponent.GetEntityId(); + // if (hitEntity.IsValid()) + // { + // AZ::EntityId canvasEntityId; + // UiCanvasRefBus::EventResult(canvasEntityId, hitEntity, &UiCanvasRefInterface::GetCanvas); + // if (canvasEntityId.IsValid()) + // { + // // Checkif the UI canvas referenced by the hit entity supports automatic input + // bool doesCanvasSupportInput = false; + // UiCanvasBus::EventResult(doesCanvasSupportInput, canvasEntityId, &UiCanvasInterface::GetIsPositionalInputSupported); + // + // if (doesCanvasSupportInput) + // { + // // set the hit details to the hit entity, it will convert into canvas coords and send to canvas + // bool handled = false; + // UiCanvasOnMeshBus::EventResult(handled, hitEntity, + // &UiCanvasOnMeshInterface::ProcessHitInputEvent, inputSnapshot, rayResult); + // + // if (handled) + // { + // return true; + // } + // } + // } + // } + //} + // + // + //return false; } //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/LyShine/Code/Source/UiFaderComponent.cpp b/Gems/LyShine/Code/Source/UiFaderComponent.cpp index f195689a43..e7eca04c59 100644 --- a/Gems/LyShine/Code/Source/UiFaderComponent.cpp +++ b/Gems/LyShine/Code/Source/UiFaderComponent.cpp @@ -463,7 +463,7 @@ void UiFaderComponent::CreateOrResizeRenderTarget(const AZ::Vector2& pixelAligne // Create a render target that this element and its children will be rendered to AZ::EntityId canvasEntityId; EBUS_EVENT_ID_RESULT(canvasEntityId, GetEntityId(), UiElementBus, GetCanvasEntityId); - AZ::RHI::Size imageSize(renderTargetSize.GetX(), renderTargetSize.GetY(), 1); + AZ::RHI::Size imageSize(static_cast(renderTargetSize.GetX()), static_cast(renderTargetSize.GetY()), 1); EBUS_EVENT_ID_RESULT(m_attachmentImageId, canvasEntityId, LyShine::RenderToTextureRequestBus, UseRenderTarget, AZ::Name(m_renderTargetName.c_str()), imageSize); if (m_attachmentImageId.IsEmpty()) { diff --git a/Gems/LyShine/Code/Source/UiImageComponent.cpp b/Gems/LyShine/Code/Source/UiImageComponent.cpp index 83c184cfc8..d279beeee9 100644 --- a/Gems/LyShine/Code/Source/UiImageComponent.cpp +++ b/Gems/LyShine/Code/Source/UiImageComponent.cpp @@ -1666,7 +1666,7 @@ void UiImageComponent::RenderRadialFilledQuad(const AZ::Vector2* positions, cons const int numIndices = 15; uint16 indices[numIndices]; - for (int ix = 0; ix < 5; ++ix) + for (uint16 ix = 0; ix < 5; ++ix) { indices[ix * 3 + firstIndexOffset] = ix + 1; indices[ix * 3 + secondIndexOffset] = ix + 2; @@ -2268,20 +2268,20 @@ int UiImageComponent::ClipToLine(const SVF_P2F_C4B_T2F_F4B* vertices, const uint int indicesAdded = 0; if (verticesAdded == 3) { - renderIndices[renderIndexOffset] = vertexOffset - 3; - renderIndices[renderIndexOffset + 1] = vertexOffset - 2; - renderIndices[renderIndexOffset + 2] = vertexOffset - 1; + renderIndices[renderIndexOffset] = static_cast(vertexOffset - 3); + renderIndices[renderIndexOffset + 1] = static_cast(vertexOffset - 2); + renderIndices[renderIndexOffset + 2] = static_cast(vertexOffset - 1); indicesAdded = 3; } else if (verticesAdded == 4) { - renderIndices[renderIndexOffset] = vertexOffset - 4; - renderIndices[renderIndexOffset + 1] = vertexOffset - 3; - renderIndices[renderIndexOffset + 2] = vertexOffset - 2; + renderIndices[renderIndexOffset] = static_cast(vertexOffset - 4); + renderIndices[renderIndexOffset + 1] = static_cast(vertexOffset - 3); + renderIndices[renderIndexOffset + 2] = static_cast(vertexOffset - 2); - renderIndices[renderIndexOffset + 3] = vertexOffset - 4; - renderIndices[renderIndexOffset + 4] = vertexOffset - 2; - renderIndices[renderIndexOffset + 5] = vertexOffset - 1; + renderIndices[renderIndexOffset + 3] = static_cast(vertexOffset - 4); + renderIndices[renderIndexOffset + 4] = static_cast(vertexOffset - 2); + renderIndices[renderIndexOffset + 5] = static_cast(vertexOffset - 1); indicesAdded = 6; } diff --git a/Gems/LyShine/Code/Source/UiMaskComponent.cpp b/Gems/LyShine/Code/Source/UiMaskComponent.cpp index 2c1763e4ec..d6ed468deb 100644 --- a/Gems/LyShine/Code/Source/UiMaskComponent.cpp +++ b/Gems/LyShine/Code/Source/UiMaskComponent.cpp @@ -564,7 +564,7 @@ void UiMaskComponent::CreateOrResizeRenderTarget(const AZ::Vector2& pixelAligned // Create a render target that this element and its children will be rendered to AZ::EntityId canvasEntityId; EBUS_EVENT_ID_RESULT(canvasEntityId, GetEntityId(), UiElementBus, GetCanvasEntityId); - AZ::RHI::Size imageSize(renderTargetSize.GetX(), renderTargetSize.GetY(), 1); + AZ::RHI::Size imageSize(static_cast(renderTargetSize.GetX()), static_cast(renderTargetSize.GetY()), 1); EBUS_EVENT_ID_RESULT(m_contentAttachmentImageId, canvasEntityId, LyShine::RenderToTextureRequestBus, UseRenderTarget, AZ::Name(m_renderTargetName.c_str()), imageSize); if (m_contentAttachmentImageId.IsEmpty()) { @@ -762,7 +762,7 @@ void UiMaskComponent::RenderUsingGradientMask(LyShine::IRenderGraph* renderGraph { // go through all the cached vertices and update the alpha values UCol desiredPackedColor = m_cachedPrimitive.m_vertices[0].color; - desiredPackedColor.a = desiredPackedAlpha; + desiredPackedColor.a = static_cast(desiredPackedAlpha); for (int i = 0; i < m_cachedPrimitive.m_numVertices; ++i) { m_cachedPrimitive.m_vertices[i].color = desiredPackedColor; diff --git a/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp b/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp index a8b678947b..0adf2fb2de 100644 --- a/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp +++ b/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp @@ -1825,8 +1825,8 @@ void UiParticleEmitterComponent::ResetParticleBuffers() } m_cachedPrimitive.m_indices = new uint16[numIndices]; - const int verticesPerParticle = 4; - int baseIndex = 0; + const uint16 verticesPerParticle = 4; + uint16 baseIndex = 0; for (AZ::u32 i = 0; i < numIndices; i += indicesPerParticle) { m_cachedPrimitive.m_indices[i + 0] = 0 + baseIndex; diff --git a/Gems/LyShine/Code/Source/UiTextComponent.cpp b/Gems/LyShine/Code/Source/UiTextComponent.cpp index 35f351a9e6..f9544a9954 100644 --- a/Gems/LyShine/Code/Source/UiTextComponent.cpp +++ b/Gems/LyShine/Code/Source/UiTextComponent.cpp @@ -1096,7 +1096,7 @@ UiTextComponent::InlineImage::InlineImage(const AZStd::string& texturePathname, if (m_texture) { AZ::RHI::Size size = m_texture->GetDescriptor().m_size; - m_size = AZ::Vector2(size.m_width, size.m_height); + m_size = AZ::Vector2(static_cast(size.m_width), static_cast(size.m_height)); } } @@ -2068,7 +2068,7 @@ int UiTextComponent::GetFontEffect() //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTextComponent::SetFontEffect(int effectIndex) { - if (m_fontEffectIndex != effectIndex) + if (m_fontEffectIndex != static_cast(effectIndex)) { m_fontEffectIndex = effectIndex; @@ -4149,7 +4149,7 @@ void UiTextComponent::RenderDrawBatchLines( imageQuad[i] = transformToViewport * imageQuad[i]; } - static const uint32 packedColor = (255 << 24) | (255 << 16) | (255 << 8) | 255; + static const uint32 packedColor = (255u << 24) | (255u << 16) | (255u << 8) | 255u; RenderCacheImageBatch* cacheImageBatch = new RenderCacheImageBatch; diff --git a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp index 0d9fc09063..df2d85eb74 100644 --- a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp +++ b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp @@ -63,7 +63,7 @@ namespace //! \brief Given a UTF8 string and index, return the raw string buffer index that maps to the UTF8 index. int GetCharArrayIndexFromUtf8CharIndex(const AZStd::string& utf8String, const uint utf8Index) { - int utfIndexIter = 0; + uint utfIndexIter = 0; int rawIndex = 0; const AZStd::string::size_type stringLength = utf8String.length(); diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp b/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp index 9da32d757a..39e84d24a7 100644 --- a/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/AnimPostFXNode.cpp @@ -294,7 +294,7 @@ unsigned int CAnimPostFXNode::GetParamCount() const //----------------------------------------------------------------------------- CAnimParamType CAnimPostFXNode::GetParamType(unsigned int nIndex) const { - if (nIndex >= 0 && nIndex < (int)m_pDescription->m_nodeParams.size()) + if (nIndex < m_pDescription->m_nodeParams.size()) { return m_pDescription->m_nodeParams[nIndex].paramType; } diff --git a/Gems/Maestro/Code/Source/Cinematics/AnimScreenFaderNode.cpp b/Gems/Maestro/Code/Source/Cinematics/AnimScreenFaderNode.cpp index 62cffcefb1..975e31d8cb 100644 --- a/Gems/Maestro/Code/Source/Cinematics/AnimScreenFaderNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/AnimScreenFaderNode.cpp @@ -304,7 +304,7 @@ unsigned int CAnimScreenFaderNode::GetParamCount() const //----------------------------------------------------------------------------- CAnimParamType CAnimScreenFaderNode::GetParamType(unsigned int nIndex) const { - if (nIndex >= 0 && nIndex < (int)s_screenFaderNodeParams.size()) + if (nIndex < s_screenFaderNodeParams.size()) { return s_screenFaderNodeParams[nIndex].paramType; } diff --git a/Gems/Maestro/Code/Source/Cinematics/CommentNode.cpp b/Gems/Maestro/Code/Source/Cinematics/CommentNode.cpp index fc58b91723..98bfef78a0 100644 --- a/Gems/Maestro/Code/Source/Cinematics/CommentNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/CommentNode.cpp @@ -120,7 +120,7 @@ unsigned int CCommentNode::GetParamCount() const //----------------------------------------------------------------------------- CAnimParamType CCommentNode::GetParamType(unsigned int nIndex) const { - if (nIndex >= 0 && nIndex < (int)s_nodeParameters.size()) + if (nIndex < s_nodeParameters.size()) { return s_nodeParameters[nIndex].paramType; } diff --git a/Gems/Maestro/Code/Source/Cinematics/LayerNode.cpp b/Gems/Maestro/Code/Source/Cinematics/LayerNode.cpp index 8c518f5a54..e2a9e816c6 100644 --- a/Gems/Maestro/Code/Source/Cinematics/LayerNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/LayerNode.cpp @@ -144,7 +144,7 @@ unsigned int CLayerNode::GetParamCount() const //----------------------------------------------------------------------------- CAnimParamType CLayerNode::GetParamType(unsigned int nIndex) const { - if (nIndex >= 0 && nIndex < (int)s_nodeParams.size()) + if (nIndex < (int)s_nodeParams.size()) { return s_nodeParams[nIndex].paramType; } diff --git a/Gems/Maestro/Code/Source/Cinematics/MaterialNode.cpp b/Gems/Maestro/Code/Source/Cinematics/MaterialNode.cpp index 08d4d92e8b..74b0fb1063 100644 --- a/Gems/Maestro/Code/Source/Cinematics/MaterialNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/MaterialNode.cpp @@ -180,7 +180,7 @@ unsigned int CAnimMaterialNode::GetParamCount() const ////////////////////////////////////////////////////////////////////////// CAnimParamType CAnimMaterialNode::GetParamType(unsigned int nIndex) const { - if (nIndex >= 0 && nIndex < (int)s_nodeParams.size()) + if (nIndex < s_nodeParams.size()) { return s_nodeParams[nIndex].paramType; } diff --git a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp index d4b894dc92..79841e671b 100644 --- a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp @@ -260,7 +260,7 @@ unsigned int CAnimSceneNode::GetParamCount() const ////////////////////////////////////////////////////////////////////////// CAnimParamType CAnimSceneNode::GetParamType(unsigned int nIndex) const { - if (nIndex >= 0 && nIndex < (int)s_nodeParams.size()) + if (nIndex < s_nodeParams.size()) { return s_nodeParams[nIndex].paramType; } diff --git a/Gems/Maestro/Code/Source/Cinematics/ShadowsSetupNode.cpp b/Gems/Maestro/Code/Source/Cinematics/ShadowsSetupNode.cpp index fd5e30199e..817c37483e 100644 --- a/Gems/Maestro/Code/Source/Cinematics/ShadowsSetupNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/ShadowsSetupNode.cpp @@ -87,7 +87,7 @@ unsigned int CShadowsSetupNode::GetParamCount() const //----------------------------------------------------------------------------- CAnimParamType CShadowsSetupNode::GetParamType(unsigned int nIndex) const { - if (nIndex >= 0 && nIndex < (int)ShadowSetupNode::s_shadowSetupParams.size()) + if (nIndex < ShadowSetupNode::s_shadowSetupParams.size()) { return ShadowSetupNode::s_shadowSetupParams[nIndex].paramType; } diff --git a/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.cpp b/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.cpp index e7736cd30b..2e6491db5b 100644 --- a/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.cpp +++ b/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.cpp @@ -29,7 +29,7 @@ namespace Maestro { /*static*/ AZ::ScriptTimePoint EditorSequenceComponent::s_lastPropertyRefreshTime; /*static*/ const double EditorSequenceComponent::s_refreshPeriodMilliseconds = 200.0; // 5 Hz refresh rate - /*static*/ const int EditorSequenceComponent::s_invalidSequenceId = -1; + /*static*/ const uint32 EditorSequenceComponent::s_invalidSequenceId = std::numeric_limits::max(); namespace ClassConverters { diff --git a/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h b/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h index 597cd30912..83caaeea19 100644 --- a/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h +++ b/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h @@ -110,6 +110,6 @@ namespace Maestro static AZ::ScriptTimePoint s_lastPropertyRefreshTime; static const double s_refreshPeriodMilliseconds; // property refresh period for SetAnimatedPropertyValue events - static const int s_invalidSequenceId; + static const uint32 s_invalidSequenceId; }; } // namespace Maestro diff --git a/Gems/MessagePopup/Code/Include/MessagePopup/MessagePopupBus.h b/Gems/MessagePopup/Code/Include/MessagePopup/MessagePopupBus.h index e6f31ec08d..7dfa2ba5a8 100644 --- a/Gems/MessagePopup/Code/Include/MessagePopup/MessagePopupBus.h +++ b/Gems/MessagePopup/Code/Include/MessagePopup/MessagePopupBus.h @@ -25,7 +25,7 @@ namespace MessagePopup EPopupKind_Toaster }; - static const AZ::u32 InvalidId = -1; + static const AZ::u32 InvalidId = std::numeric_limits::max(); ////////////////////////////////////////////////////////////////////////// struct MessagePopupInfo diff --git a/Gems/Metastream/Code/Source/MetastreamGem.cpp b/Gems/Metastream/Code/Source/MetastreamGem.cpp index 2bb213662c..e8c659474d 100644 --- a/Gems/Metastream/Code/Source/MetastreamGem.cpp +++ b/Gems/Metastream/Code/Source/MetastreamGem.cpp @@ -339,10 +339,9 @@ namespace Metastream // Server already started return true; } -#endif // AZ_TRAIT_METASTREAM_USE_CIVET - - // Metastream only supported on PC +#else return false; +#endif } void Metastream::MetastreamGem::StopHTTPServer() diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/INetworkEntityManager.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/INetworkEntityManager.h index 1c8894d6c2..8a5fec869c 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/INetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/INetworkEntityManager.h @@ -59,7 +59,8 @@ namespace Multiplayer ( const PrefabEntityId& prefabEntryId, NetEntityRole netEntityRole, - const AZ::Transform& transform + const AZ::Transform& transform, + AutoActivate autoActivate = AutoActivate::Activate ) = 0; //! Creates new entities of the given archetype @@ -89,6 +90,11 @@ namespace Multiplayer //! @return the total number of entities tracked by this INetworkEntityManager instance virtual uint32_t GetEntityCount() const = 0; + //! Returns the Net Entity ID for a given AZ Entity ID. + //! @param entityId the AZ Entity ID + //! @return the Net Entity ID + virtual NetEntityId GetNetEntityIdById(const AZ::EntityId& entityId) const = 0; + //! Adds the provided entity to the internal entity map identified by the provided netEntityId. //! @param netEntityId the identifier to use for the added entity //! @param entity the entity to add to the internal entity map diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index 84fdc9ae54..8cde9613b7 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -130,9 +130,9 @@ void {{ PropertyName }}({{ ', '.join(paramDefines) }}); {# #} -{% macro DeclareRpcInvocations(Component, Section, HandleOn, ProctectedSection) %} +{% macro DeclareRpcInvocations(Component, Section, HandleOn, IsProtected) %} {% call(Property) AutoComponentMacros.ParseRemoteProcedures(Component, Section, HandleOn) %} -{% if Property.attrib['IsPublic']|booleanTrue == ProctectedSection %} +{% if Property.attrib['IsPublic']|booleanTrue != IsProtected %} {{ DeclareRpcInvocation(Property, HandleOn) -}} {% endif %} {% endcall %} @@ -386,8 +386,6 @@ namespace {{ Component.attrib['Namespace'] }} {{ DeclareNetworkPropertyAccessors(Component, 'Autonomous', 'Authority', false)|indent(8) -}} {{ DeclareNetworkPropertyAccessors(Component, 'Autonomous', 'Authority', true)|indent(8) -}} {{ DeclareArchetypePropertyGetters(Component)|indent(8) -}} - {{ DeclareRpcInvocations(Component, 'Server', 'Authority', false)|indent(8) -}} - {{ DeclareRpcInvocations(Component, 'Server', 'Authority', true)|indent(8) -}} {{ DeclareRpcInvocations(Component, 'Client', 'Authority', false)|indent(8) -}} {{ DeclareRpcInvocations(Component, 'Client', 'Authority', true)|indent(8) -}} {{ DeclareRpcInvocations(Component, 'Autonomous', 'Authority', false)|indent(8) -}} @@ -445,8 +443,8 @@ namespace {{ Component.attrib['Namespace'] }} static AZStd::unique_ptr AllocateComponentInput(); - {{ ComponentBaseName }}() = default; - ~{{ ComponentBaseName }}() override = default; + {{ ComponentBaseName }}(); + ~{{ ComponentBaseName }}() override; void Init() override; void Activate() override; diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 56ab828ffe..079cac329b 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -318,7 +318,11 @@ void {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.join(par constexpr AzNetworking::ReliabilityType isReliable = Multiplayer::ReliabilityType::Unreliable; {% endif %} +{% if InvokeFrom == 'Server' or InvokeFrom =='Client' %} + const Multiplayer::NetComponentId netComponentId = GetNetComponentId(); +{% else %} const Multiplayer::NetComponentId netComponentId = GetParent().GetNetComponentId(); +{% endif %} Multiplayer::NetworkEntityRpcMessage rpcMessage(Multiplayer::RpcDeliveryType::{{ InvokeFrom }}To{{ HandleOn }}, GetNetEntityId(), netComponentId, rpcId, isReliable); {% if paramNames|count > 0 %} {{ UpperFirst(Component.attrib['Name']) }}Internal::{{ UpperFirst(Property.attrib['Name']) }}RpcStruct rpcStruct({{ ', '.join(paramNames) }}); @@ -345,9 +349,9 @@ void {{ ClassName }}::Signal{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.jo {# #} -{% macro DefineRpcInvocations(Component, ClassName, InvokeFrom, HandleOn, ProctectedSection) %} +{% macro DefineRpcInvocations(Component, ClassName, InvokeFrom, HandleOn, IsProtected) %} {% call(Property) AutoComponentMacros.ParseRemoteProcedures(Component, InvokeFrom, HandleOn) %} -{% if Property.attrib['IsPublic']|booleanTrue == ProctectedSection %} +{% if Property.attrib['IsPublic']|booleanTrue != IsProtected %} {{ DefineRpcInvocation(Component, ClassName, Property, InvokeFrom, HandleOn) -}} {% if Property.attrib['GenerateEventBindings']|booleanTrue == true %} {{ DefineRpcSignal(Component, ClassName, Property, InvokeFrom) -}} @@ -1250,10 +1254,12 @@ namespace {{ Component.attrib['Namespace'] }} bool {{ RecordName }}::CanAttachRecord(Multiplayer::ReplicationRecord& replicationRecord) { bool canAttach{ true }; + AZ_PUSH_DISABLE_WARNING(4296, "-Wunknown-warning-option") // expression is always true canAttach &= replicationRecord.ContainsAuthorityToClientBits() ? (replicationRecord.GetRemainingAuthorityToClientBits() >= static_cast({{ AutoComponentMacros.GetNetPropertiesDirtyEnumName(ComponentName, 'Authority', 'Client') }}::Count)) : true; canAttach &= replicationRecord.ContainsAuthorityToServerBits() ? (replicationRecord.GetRemainingAuthorityToServerBits() >= static_cast({{ AutoComponentMacros.GetNetPropertiesDirtyEnumName(ComponentName, 'Authority', 'Server') }}::Count)) : true; canAttach &= replicationRecord.ContainsAuthorityToAutonomousBits() ? (replicationRecord.GetRemainingAuthorityToAutonomousBits() >= static_cast({{ AutoComponentMacros.GetNetPropertiesDirtyEnumName(ComponentName, 'Authority', 'Autonomous') }}::Count)) : true; canAttach &= replicationRecord.ContainsAutonomousToAuthorityBits() ? (replicationRecord.GetRemainingAutonomousToAuthorityBits() >= static_cast({{ AutoComponentMacros.GetNetPropertiesDirtyEnumName(ComponentName, 'Autonomous', 'Authority') }}::Count)) : true; + AZ_POP_DISABLE_WARNING return canAttach; } @@ -1490,6 +1496,10 @@ namespace {{ Component.attrib['Namespace'] }} {% endif %} } + {{ ComponentBaseName }}::{{ ComponentBaseName }}() = default; + + {{ ComponentBaseName }}::~{{ ComponentBaseName }}() = default; + void {{ ComponentBaseName }}::Init() { if (m_netBindComponent == nullptr) @@ -1568,8 +1578,7 @@ namespace {{ Component.attrib['Namespace'] }} return s_netComponentId; } -#pragma warning(push) -#pragma warning(disable: 4065) // switch statement contains 'default' but no 'case' labels + AZ_PUSH_DISABLE_WARNING(4065, "-Wunknown-warning-option") // switch statement contains 'default' but no 'case' labels bool {{ ComponentBaseName }}::HandleRpcMessage ( [[maybe_unused]] AzNetworking::IConnection* invokingConnection, @@ -1587,10 +1596,8 @@ namespace {{ Component.attrib['Namespace'] }} default: return false; } - AZ_Assert(0, "Got unhandled RpcType %d in {{ ComponentBaseName }}", static_cast(rpcType)); - return false; } -#pragma warning(pop) + AZ_POP_DISABLE_WARNING bool {{ ComponentBaseName }}::SerializeStateDeltaMessage(Multiplayer::ReplicationRecord& replicationRecord, AzNetworking::ISerializer& serializer) { diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp index 72f5aa8e1c..936f2ea92c 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp @@ -277,7 +277,7 @@ namespace Multiplayer input.SetClientInputId(GetLastInputId()); ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), input.GetHostBlendFactor(), invokingConnection->GetConnectionId()); - GetNetBindComponent()->ProcessInput(input, clientInputRateSec); + GetNetBindComponent()->ProcessInput(input, static_cast(clientInputRateSec)); AZLOG(NET_Prediction, "Migrated InputId=%d", aznumeric_cast(input.GetClientInputId())); @@ -345,7 +345,7 @@ namespace Multiplayer // Reprocess the input for this frame NetworkInput& input = m_inputHistory[replayIndex]; ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), input.GetHostBlendFactor(), invokingConnection->GetConnectionId()); - GetNetBindComponent()->ReprocessInput(input, clientInputRateSec); + GetNetBindComponent()->ReprocessInput(input, static_cast(clientInputRateSec)); AZLOG(NET_Prediction, "Replayed InputId=%d", aznumeric_cast(input.GetClientInputId())); } @@ -438,10 +438,10 @@ namespace Multiplayer input.SetHostBlendFactor(multiplayer->GetCurrentBlendFactor()); // Allow components to form the input for this frame - GetNetBindComponent()->CreateInput(input, clientInputRateSec); + GetNetBindComponent()->CreateInput(input, static_cast(clientInputRateSec)); // Process the input for this frame - GetNetBindComponent()->ProcessInput(input, clientInputRateSec); + GetNetBindComponent()->ProcessInput(input, static_cast(clientInputRateSec)); AZLOG(NET_Prediction, "Processed InputId=%d", aznumeric_cast(m_clientInputId)); @@ -464,7 +464,7 @@ namespace Multiplayer { // Clamp to oldest element if history is too small const int64_t historyIndex = AZStd::max(inputHistorySize - 1 - i, 0); - inputArray[i] = m_inputHistory[historyIndex]; + inputArray[static_cast(i)] = m_inputHistory[historyIndex]; } #ifndef AZ_RELEASE_BUILD @@ -506,7 +506,7 @@ namespace Multiplayer NetworkInput& input = m_lastInputReceived[0]; { ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), DefaultBlendFactor, GetNetBindComponent()->GetOwningConnectionId()); - GetNetBindComponent()->ProcessInput(input, clientInputRateSec); + GetNetBindComponent()->ProcessInput(input, static_cast(clientInputRateSec)); } AZLOG(NET_Prediction, "Forced InputId=%d", aznumeric_cast(input.GetClientInputId())); diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp index 45305e3b39..7f904479d1 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugByteReporter.cpp @@ -8,6 +8,8 @@ #include "MultiplayerDebugByteReporter.h" +#include + #include // for std::setfill #include #include diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 61dbf9289f..b0a8350982 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -643,6 +643,7 @@ namespace Multiplayer { controlledEntity.GetNetBindComponent()->SetOwningConnectionId(connection->GetConnectionId()); } + controlledEntity.Activate(); if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so { @@ -763,6 +764,7 @@ namespace Multiplayer { controlledEntityNetBindComponent->SetAllowAutonomy(true); } + controlledEntity.Activate(); } AZLOG_INFO("Multiplayer operating in %s mode", GetEnumString(m_agentType)); @@ -969,7 +971,7 @@ namespace Multiplayer NetworkEntityHandle MultiplayerSystemComponent::SpawnDefaultPlayerPrefab() { PrefabEntityId playerPrefabEntityId(AZ::Name(static_cast(sv_defaultPlayerSpawnAsset).c_str())); - INetworkEntityManager::EntityList entityList = m_networkEntityManager.CreateEntitiesImmediate(playerPrefabEntityId, NetEntityRole::Authority, AZ::Transform::CreateIdentity()); + INetworkEntityManager::EntityList entityList = m_networkEntityManager.CreateEntitiesImmediate(playerPrefabEntityId, NetEntityRole::Authority, AZ::Transform::CreateIdentity(), Multiplayer::AutoActivate::DoNotActivate); NetworkEntityHandle controlledEntity; if (entityList.size() > 0) @@ -1006,7 +1008,7 @@ namespace Multiplayer const char* addressStr = mutableAddress; const char* portStr = &(mutableAddress[portSeparator + 1]); int32_t portNumber = atol(portStr); - AZ::Interface::Get()->Connect(addressStr, portNumber); + AZ::Interface::Get()->Connect(addressStr, static_cast(portNumber)); } } AZ_CONSOLEFREEFUNC(connect, AZ::ConsoleFunctorFlags::DontReplicate, "Opens a multiplayer connection to a remote host"); diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index cff05b9151..69d2726c65 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -73,6 +73,11 @@ namespace Multiplayer return m_networkEntityTracker.Get(netEntityId); } + NetEntityId NetworkEntityManager::GetNetEntityIdById(const AZ::EntityId& entityId) const + { + return m_networkEntityTracker.Get(entityId); + } + uint32_t NetworkEntityManager::GetEntityCount() const { return static_cast(m_networkEntityTracker.size()); @@ -304,7 +309,7 @@ namespace Multiplayer } INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate( - const AzFramework::Spawnable& spawnable, NetEntityRole netEntityRole) + const AzFramework::Spawnable& spawnable, NetEntityRole netEntityRole, AutoActivate autoActivate) { INetworkEntityManager::EntityList returnList; @@ -354,6 +359,11 @@ namespace Multiplayer const NetEntityId netEntityId = NextId(); netBindComponent->PreInit(clone, prefabEntityId, netEntityId, netEntityRole); + if (autoActivate == AutoActivate::DoNotActivate) + { + clone->SetRuntimeActiveByDefault(false); + } + AzFramework::GameEntityContextRequestBus::Broadcast( &AzFramework::GameEntityContextRequestBus::Events::AddGameEntity, clone); @@ -373,10 +383,11 @@ namespace Multiplayer ( const PrefabEntityId& prefabEntryId, NetEntityRole netEntityRole, - const AZ::Transform& transform + const AZ::Transform& transform, + AutoActivate autoActivate ) { - return CreateEntitiesImmediate(prefabEntryId, NextId(), netEntityRole, AutoActivate::Activate, transform); + return CreateEntitiesImmediate(prefabEntryId, NextId(), netEntityRole, autoActivate, transform); } INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate @@ -409,7 +420,7 @@ namespace Multiplayer if (entityIndex == PrefabEntityId::AllIndices) { - return CreateEntitiesImmediate(*netSpawnable, netEntityRole); + return CreateEntitiesImmediate(*netSpawnable, netEntityRole, autoActivate); } const AzFramework::Spawnable::EntityList& entities = netSpawnable->GetEntities(); diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h index fdd0201b7a..9ccc576447 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h @@ -41,13 +41,15 @@ namespace Multiplayer MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() override; HostId GetHostId() const override; ConstNetworkEntityHandle GetEntity(NetEntityId netEntityId) const override; + NetEntityId GetNetEntityIdById(const AZ::EntityId& entityId) const override; - EntityList CreateEntitiesImmediate(const AzFramework::Spawnable& spawnable, NetEntityRole netEntityRole); + EntityList CreateEntitiesImmediate(const AzFramework::Spawnable& spawnable, NetEntityRole netEntityRole, AutoActivate autoActivate); EntityList CreateEntitiesImmediate ( const PrefabEntityId& prefabEntryId, NetEntityRole netEntityRole, - const AZ::Transform& transform + const AZ::Transform& transform, + AutoActivate autoActivate = AutoActivate::Activate ) override; EntityList CreateEntitiesImmediate ( diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp index a70dd74bf9..e31907461b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp @@ -18,6 +18,7 @@ namespace Multiplayer ++m_addChangeDirty; AZ_Assert(m_entityMap.end() == m_entityMap.find(netEntityId), "Attempting to add the same entity to the entity map multiple times"); m_entityMap[netEntityId] = entity; + m_netEntityIdMap[entity->GetId()] = netEntityId; } NetworkEntityHandle NetworkEntityTracker::Get(NetEntityId netEntityId) @@ -32,6 +33,16 @@ namespace Multiplayer return ConstNetworkEntityHandle(entity, netEntityId, this); } + NetEntityId NetworkEntityTracker::Get(const AZ::EntityId& entityId) const + { + auto found = m_netEntityIdMap.find(entityId); + if (found != m_netEntityIdMap.end()) + { + return found->second; + } + return Multiplayer::InvalidNetEntityId; + } + bool NetworkEntityTracker::Exists(NetEntityId netEntityId) const { return (m_entityMap.find(netEntityId) != m_entityMap.end()); @@ -50,12 +61,22 @@ namespace Multiplayer void NetworkEntityTracker::erase(NetEntityId netEntityId) { ++m_deleteChangeDirty; - m_entityMap.erase(netEntityId); + + auto found = m_entityMap.find(netEntityId); + if (found != m_entityMap.end()) + { + m_netEntityIdMap.erase(found->second->GetId()); + m_entityMap.erase(found); + } } NetworkEntityTracker::EntityMap::iterator NetworkEntityTracker::erase(EntityMap::iterator iter) { ++m_deleteChangeDirty; + if (iter != m_entityMap.end()) + { + m_netEntityIdMap.erase(iter->second->GetId()); + } return m_entityMap.erase(iter); } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h index 7ff2d1da24..09238acaee 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h @@ -22,6 +22,7 @@ namespace Multiplayer public: using EntityMap = AZStd::unordered_map; + using NetEntityIdMap = AZStd::unordered_map; using iterator = EntityMap::iterator; using const_iterator = EntityMap::const_iterator; @@ -36,6 +37,8 @@ namespace Multiplayer NetworkEntityHandle Get(NetEntityId netEntityId); ConstNetworkEntityHandle Get(NetEntityId netEntityId) const; + NetEntityId Get(const AZ::EntityId& entityId) const; + //! Returns true if the netEntityId exists. bool Exists(NetEntityId netEntityId) const; @@ -74,6 +77,7 @@ namespace Multiplayer private: EntityMap m_entityMap; + NetEntityIdMap m_netEntityIdMap; uint32_t m_deleteChangeDirty = 0; uint32_t m_addChangeDirty = 0; }; diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.inl b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.inl index c22fbb0da2..44098336be 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.inl +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.inl @@ -48,6 +48,7 @@ namespace Multiplayer inline void NetworkEntityTracker::clear() { m_entityMap.clear(); + m_netEntityIdMap.clear(); } inline uint32_t NetworkEntityTracker::GetChangeDirty(const AZ::Entity* entity) const diff --git a/Gems/MultiplayerCompression/Code/Source/LZ4Compressor.h b/Gems/MultiplayerCompression/Code/Source/LZ4Compressor.h index fc0c9e1089..640cf03ee4 100644 --- a/Gems/MultiplayerCompression/Code/Source/LZ4Compressor.h +++ b/Gems/MultiplayerCompression/Code/Source/LZ4Compressor.h @@ -10,6 +10,7 @@ #include #include +#include namespace MultiplayerCompression { diff --git a/Gems/MultiplayerCompression/Code/Tests/MultiplayerCompressionTest.cpp b/Gems/MultiplayerCompression/Code/Tests/MultiplayerCompressionTest.cpp index 91839b1e23..1c3eda6709 100644 --- a/Gems/MultiplayerCompression/Code/Tests/MultiplayerCompressionTest.cpp +++ b/Gems/MultiplayerCompression/Code/Tests/MultiplayerCompressionTest.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -42,9 +43,9 @@ TEST_F(MultiplayerCompressionTest, MultiplayerCompression_CompressTest) memset(buffer.GetBuffer(), 255, buffer.GetCapacity()); size_t maxCompressedSize = buffer.GetSize() + 32U; - size_t compressedSize = -1; - size_t uncompressedSize = -1; - size_t consumedSize = -1; + size_t compressedSize = std::numeric_limits::max(); + size_t uncompressedSize = std::numeric_limits::max(); + size_t consumedSize = std::numeric_limits::max(); char* pCompressedBuffer = new char[maxCompressedSize]; char* pDecompressedBuffer = new char[buffer.GetSize()]; diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp index 8baea091a2..ef42aba7f0 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp +++ b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp @@ -233,7 +233,7 @@ namespace NvCloth void ActorClothSkinningLinear::UpdateSkinning() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); m_skinningMatrices = Internal::ObtainSkinningMatrices(m_entityId); } @@ -250,7 +250,7 @@ namespace NvCloth return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); const size_t vertexCount = m_simulatedVertices.size(); for (size_t index = 0; index < vertexCount; ++index) @@ -274,7 +274,7 @@ namespace NvCloth return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); for (const AZ::u32 index : m_nonSimulatedVertices) { @@ -342,7 +342,7 @@ namespace NvCloth void ActorClothSkinningDualQuaternion::UpdateSkinning() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); m_skinningDualQuaternions = Internal::ObtainSkinningDualQuaternions(m_entityId, m_jointIndices); } @@ -359,7 +359,7 @@ namespace NvCloth return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); const size_t vertexCount = m_simulatedVertices.size(); for (size_t index = 0; index < vertexCount; ++index) @@ -383,7 +383,7 @@ namespace NvCloth return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); for (const AZ::u32 index : m_nonSimulatedVertices) { diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp index 5a7564d72a..ecf2bd0a54 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp +++ b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp @@ -250,7 +250,7 @@ namespace NvCloth [[maybe_unused]] ClothId clothId, float deltaTime) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); UpdateSimulationCollisions(); @@ -267,7 +267,7 @@ namespace NvCloth [[maybe_unused]] float deltaTime, const AZStd::vector& updatedParticles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); // Next buffer index of the render data m_renderDataBufferIndex = (m_renderDataBufferIndex + 1) % RenderDataBufferSize; @@ -326,7 +326,7 @@ namespace NvCloth { if (m_actorClothColliders) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); m_actorClothColliders->Update(); @@ -342,7 +342,7 @@ namespace NvCloth { if (m_actorClothSkinning) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); m_actorClothSkinning->UpdateSkinning(); @@ -376,7 +376,7 @@ namespace NvCloth void ClothComponentMesh::UpdateSimulationConstraints() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); m_motionConstraints = m_clothConstraints->GetMotionConstraints(); m_separationConstraints = m_clothConstraints->GetSeparationConstraints(); @@ -396,7 +396,7 @@ namespace NvCloth void ClothComponentMesh::UpdateRenderData(const AZStd::vector& particles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); if (!m_cloth) { @@ -449,7 +449,7 @@ namespace NvCloth void ClothComponentMesh::CopyRenderDataToModel() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); // Previous buffer index of the render data const AZ::u32 previousBufferIndex = (m_renderDataBufferIndex + RenderDataBufferSize - 1) % RenderDataBufferSize; @@ -525,7 +525,7 @@ namespace NvCloth const int numVertices = subMeshInfo.m_numVertices; const int firstVertex = subMeshInfo.m_verticesFirstIndex; - if (subMesh.GetVertexCount() != numVertices) + if (subMesh.GetVertexCount() != static_cast(numVertices)) { AZ_Error("ClothComponentMesh", false, "Render mesh to be modified doesn't have the same number of vertices (%d) as the cloth's submesh (%d).", diff --git a/Gems/NvCloth/Code/Source/System/Cloth.cpp b/Gems/NvCloth/Code/Source/System/Cloth.cpp index 2aad4c402f..c71d1bd584 100644 --- a/Gems/NvCloth/Code/Source/System/Cloth.cpp +++ b/Gems/NvCloth/Code/Source/System/Cloth.cpp @@ -165,7 +165,7 @@ namespace NvCloth void Cloth::Update() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); ResolveStaticParticles(); diff --git a/Gems/NvCloth/Code/Source/System/FabricCooker.cpp b/Gems/NvCloth/Code/Source/System/FabricCooker.cpp index 668675aeaa..e9da64f970 100644 --- a/Gems/NvCloth/Code/Source/System/FabricCooker.cpp +++ b/Gems/NvCloth/Code/Source/System/FabricCooker.cpp @@ -6,6 +6,7 @@ * */ +#include #include #include #include @@ -304,7 +305,7 @@ namespace NvCloth const AZ::Vector3& fabricGravity, bool useGeodesicTether) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); return Internal::Cook(particles, indices, fabricGravity, useGeodesicTether); } @@ -317,7 +318,7 @@ namespace NvCloth AZStd::vector& remappedVertices, bool removeStaticTriangles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); // Weld vertices together AZStd::vector weldedParticles; diff --git a/Gems/NvCloth/Code/Source/System/Solver.cpp b/Gems/NvCloth/Code/Source/System/Solver.cpp index 6c20631409..3db9d3a1d9 100644 --- a/Gems/NvCloth/Code/Source/System/Solver.cpp +++ b/Gems/NvCloth/Code/Source/System/Solver.cpp @@ -110,7 +110,7 @@ namespace NvCloth AZ_Assert(!m_isSimulating, "Please make sure the ongoing simulation is finished before attempting to start a new one"); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); m_deltaTime = deltaTime; m_simulationCompletion.Reset(true /*isClearDependent*/); @@ -147,7 +147,7 @@ namespace NvCloth return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); // Waiting for the simulation pass completition. m_simulationCompletion.StartAndWaitForCompletion(); @@ -191,14 +191,14 @@ namespace NvCloth void Solver::ClothsSimulationJob::Process() { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Cloth, "NvCloth::BeginSimulationJob"); + AZ_PROFILE_SCOPE(Cloth, "NvCloth::BeginSimulationJob"); if (m_solver->beginSimulation(m_deltaTime)) { // Setup the end simulation job. AZ::Job* endSimulationJob = AZ::CreateJobFunction([solver = m_solver] { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Cloth, "NvCloth::EndSimulationJob"); + AZ_PROFILE_SCOPE(Cloth, "NvCloth::EndSimulationJob"); solver->endSimulation(); }, true /*isAutoDelete*/); @@ -209,7 +209,7 @@ namespace NvCloth { AZ::Job* chunkSimulationJob = AZ::CreateJobFunction([solver = m_solver, chunkIndex] { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Cloth, "NvCloth::ChunkSimulationJob"); + AZ_PROFILE_SCOPE(Cloth, "NvCloth::ChunkSimulationJob"); solver->simulateChunk(chunkIndex); }, true /*isAutoDelete*/); @@ -241,7 +241,7 @@ namespace NvCloth { AZ::Job* eventSignalJob = AZ::CreateJobFunction([cloth, deltaTime = m_deltaTime] { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Cloth, "NvCloth::PostSimulationJob"); + AZ_PROFILE_SCOPE(Cloth, "NvCloth::PostSimulationJob"); // Update the cloth data after the simulation cloth->Update(); @@ -270,7 +270,7 @@ namespace NvCloth { AZ::Job* eventSignalJob = AZ::CreateJobFunction([cloth, deltaTime = m_deltaTime] { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Cloth, "NvCloth::PreSimulationJob"); + AZ_PROFILE_SCOPE(Cloth, "NvCloth::PreSimulationJob"); // Issue pre-simulation events cloth->m_preSimulationEvent.Signal(cloth->GetId(), deltaTime); diff --git a/Gems/NvCloth/Code/Source/System/SystemComponent.cpp b/Gems/NvCloth/Code/Source/System/SystemComponent.cpp index 083a866a4e..77223ba566 100644 --- a/Gems/NvCloth/Code/Source/System/SystemComponent.cpp +++ b/Gems/NvCloth/Code/Source/System/SystemComponent.cpp @@ -106,26 +106,26 @@ namespace NvCloth { if (detached) { - AZ_PROFILE_INTERVAL_START(AZ::Debug::ProfileCategory::Cloth, AZ::Crc32(eventName), eventName); + AZ_PROFILE_INTERVAL_START(Cloth, AZ::Crc32(eventName), eventName); } else { - AZ_PROFILE_EVENT_BEGIN(AZ::Debug::ProfileCategory::Cloth, eventName); + AZ_PROFILE_BEGIN(Cloth, eventName); } return nullptr; } void zoneEnd([[maybe_unused]] void* profilerData, - const char* eventName, bool detached, + [[maybe_unused]] const char* eventName, bool detached, [[maybe_unused]] uint64_t contextId) override { if (detached) { - AZ_PROFILE_INTERVAL_END(AZ::Debug::ProfileCategory::Cloth, AZ::Crc32(eventName)); + AZ_PROFILE_INTERVAL_END(Cloth, AZ::Crc32(eventName)); } else { - AZ_PROFILE_EVENT_END(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_END(); } } }; @@ -309,7 +309,7 @@ namespace NvCloth const AZStd::vector& initialParticles, const FabricCookedData& fabricCookedData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); FabricId fabricId = FindOrCreateFabric(fabricCookedData); if (!fabricId.IsValid()) @@ -403,7 +403,7 @@ namespace NvCloth float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); for (auto& solverIt : m_solvers) { diff --git a/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp b/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp index 3c47ad46fd..17d8c629e6 100644 --- a/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp +++ b/Gems/NvCloth/Code/Source/System/TangentSpaceHelper.cpp @@ -8,6 +8,8 @@ #include +#include + namespace NvCloth { namespace @@ -20,7 +22,7 @@ namespace NvCloth const AZStd::vector& indices, AZStd::vector& outNormals) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); if ((indices.size() % 3) != 0) { @@ -86,7 +88,7 @@ namespace NvCloth AZStd::vector& outTangents, AZStd::vector& outBitangents) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); if ((indices.size() % 3) != 0) { @@ -174,7 +176,7 @@ namespace NvCloth AZStd::vector& outBitangents, AZStd::vector& outNormals) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); if ((indices.size() % 3) != 0) { diff --git a/Gems/NvCloth/Code/Source/Utils/MeshAssetHelper.cpp b/Gems/NvCloth/Code/Source/Utils/MeshAssetHelper.cpp index da48485dfa..c95c8896ab 100644 --- a/Gems/NvCloth/Code/Source/Utils/MeshAssetHelper.cpp +++ b/Gems/NvCloth/Code/Source/Utils/MeshAssetHelper.cpp @@ -66,7 +66,7 @@ namespace NvCloth MeshNodeInfo& meshNodeInfo, MeshClothInfo& meshClothInfo) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + AZ_PROFILE_FUNCTION(Cloth); AZ::Data::Asset modelDataAsset; AZ::Render::MeshComponentRequestBus::EventResult( diff --git a/Gems/PhysX/Code/CMakeLists.txt b/Gems/PhysX/Code/CMakeLists.txt index 80e8bee8e3..e2c3896356 100644 --- a/Gems/PhysX/Code/CMakeLists.txt +++ b/Gems/PhysX/Code/CMakeLists.txt @@ -226,13 +226,4 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) OUTPUT_SUBDIRECTORY Test.Assets/Gems/PhysX/Code/Tests ) -endif() - -ly_add_source_properties( - SOURCES - Editor/CollisionLayersWidget.cpp - Source/Collision.cpp - Source/Configuration/PhysXConfiguration.cpp - PROPERTY COMPILE_DEFINITIONS - VALUES TOUCHBENDING_LAYER_BIT=${LY_TOUCHBENDING_LAYER_BIT} -) +endif() \ No newline at end of file diff --git a/Gems/PhysX/Code/Editor/CollisionLayersWidget.cpp b/Gems/PhysX/Code/Editor/CollisionLayersWidget.cpp index 76a9c63ec0..49853312c6 100644 --- a/Gems/PhysX/Code/Editor/CollisionLayersWidget.cpp +++ b/Gems/PhysX/Code/Editor/CollisionLayersWidget.cpp @@ -22,9 +22,6 @@ namespace PhysX namespace Editor { const AZStd::string CollisionLayersWidget::s_defaultCollisionLayerName = "Default"; -#ifdef TOUCHBENDING_LAYER_BIT - const AZStd::string CollisionLayersWidget::s_touchBendCollisionLayerName = "TouchBend"; -#endif CollisionLayersWidget::CollisionLayersWidget(QWidget* parent) : QWidget(parent) @@ -150,12 +147,6 @@ namespace PhysX { lineEditCtrl->setEnabled(false); } -#ifdef TOUCHBENDING_LAYER_BIT - else if (lineEditCtrl->value() == s_touchBendCollisionLayerName) - { - lineEditCtrl->setEnabled(false); - } -#endif } } diff --git a/Gems/PhysX/Code/Editor/CollisionLayersWidget.h b/Gems/PhysX/Code/Editor/CollisionLayersWidget.h index ae21147cd2..2fb0af996b 100644 --- a/Gems/PhysX/Code/Editor/CollisionLayersWidget.h +++ b/Gems/PhysX/Code/Editor/CollisionLayersWidget.h @@ -35,9 +35,6 @@ namespace PhysX static const AZ::u32 s_maxCollisionLayerNameLength = 32; static const AZStd::string s_defaultCollisionLayerName; -#ifdef TOUCHBENDING_LAYER_BIT - static const AZStd::string s_touchBendCollisionLayerName; -#endif explicit CollisionLayersWidget(QWidget* parent = nullptr); diff --git a/Gems/PhysX/Code/Source/Collision.cpp b/Gems/PhysX/Code/Source/Collision.cpp index 0476dcfd09..361b1d13eb 100644 --- a/Gems/PhysX/Code/Source/Collision.cpp +++ b/Gems/PhysX/Code/Source/Collision.cpp @@ -38,21 +38,6 @@ namespace PhysX return physx::PxFilterFlag::eDEFAULT; } -//Enable/Disable this macro in the TouchBending Gem wscript -#ifdef TOUCHBENDING_LAYER_BIT - //If any of the actors is in the TouchBend layer then we are not interested - //in contact data, nor interested in eNOTIFY_* callbacks. - const AZ::u64 touchBendLayerMask = AzPhysics::CollisionLayer::TouchBend.GetMask(); - const AZ::u64 layer0 = Combine(filterData0.word0, filterData0.word1); - const AZ::u64 layer1 = Combine(filterData1.word0, filterData1.word1); - if (layer0 == touchBendLayerMask || layer1 == touchBendLayerMask) - { - pairFlags = physx::PxPairFlag::eSOLVE_CONTACT | - physx::PxPairFlag::eDETECT_DISCRETE_CONTACT; - return physx::PxFilterFlag::eDEFAULT; - } -#endif //TOUCHBENDING_LAYER_BIT - // generate contacts for all that were not filtered above pairFlags = physx::PxPairFlag::eCONTACT_DEFAULT | @@ -89,22 +74,6 @@ namespace PhysX return physx::PxFilterFlag::eDEFAULT; } -//Enable/Disable this macro in the TouchBending Gem wscript -#ifdef TOUCHBENDING_LAYER_BIT - //If any of the actors is in the TouchBend layer then we are not interested - //in contact data, nor interested in eNOTIFY_* callbacks. - const AZ::u64 layer0 = Combine(filterData0.word0, filterData0.word1); - const AZ::u64 layer1 = Combine(filterData1.word0, filterData1.word1); - const AZ::u64 touchBendLayerMask = AzPhysics::CollisionLayer::TouchBend.GetMask(); - if (layer0 == touchBendLayerMask || layer1 == touchBendLayerMask) - { - pairFlags = physx::PxPairFlag::eSOLVE_CONTACT | - physx::PxPairFlag::eDETECT_DISCRETE_CONTACT | - physx::PxPairFlag::eDETECT_CCD_CONTACT; - return physx::PxFilterFlag::eDEFAULT; - } -#endif - // generate contacts for all that were not filtered above pairFlags = physx::PxPairFlag::eCONTACT_DEFAULT | diff --git a/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp b/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp index 4e1b66017e..7a441a1c55 100644 --- a/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp +++ b/Gems/PhysX/Code/Source/Configuration/PhysXConfiguration.cpp @@ -23,11 +23,6 @@ namespace PhysX configuration.m_collisionGroups.CreateGroup("All", AzPhysics::CollisionGroup::All, AzPhysics::CollisionGroups::Id(), true); configuration.m_collisionGroups.CreateGroup("None", AzPhysics::CollisionGroup::None, AzPhysics::CollisionGroups::Id::Create(), true); -#ifdef TOUCHBENDING_LAYER_BIT - configuration.m_collisionLayers.SetName(AzPhysics::CollisionLayer::TouchBend, "TouchBend"); - configuration.m_collisionGroups.CreateGroup("All_NoTouchBend", AzPhysics::CollisionGroup::All_NoTouchBend, AzPhysics::CollisionGroups::Id::Create(), true); -#endif - return configuration; } diff --git a/Gems/PhysX/Code/Source/ForceRegionComponent.cpp b/Gems/PhysX/Code/Source/ForceRegionComponent.cpp index af929bbab3..f8f5f1991e 100644 --- a/Gems/PhysX/Code/Source/ForceRegionComponent.cpp +++ b/Gems/PhysX/Code/Source/ForceRegionComponent.cpp @@ -115,7 +115,7 @@ namespace PhysX void ForceRegionComponent::PostPhysicsSubTick(float fixedDeltaTime) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); for (auto entityId : m_entities) { diff --git a/Gems/PhysX/Code/Source/Material.h b/Gems/PhysX/Code/Source/Material.h index 8613be7461..b30b7402c8 100644 --- a/Gems/PhysX/Code/Source/Material.h +++ b/Gems/PhysX/Code/Source/Material.h @@ -89,7 +89,7 @@ namespace PhysX PxMaterialUniquePtr m_pxMaterial; AZ::Crc32 m_surfaceType = 0; - AZ::u32 m_cryEngineSurfaceId = -1; + AZ::u32 m_cryEngineSurfaceId = std::numeric_limits::max(); AZStd::string m_surfaceString; float m_density = 1000.0f; AZ::Color m_debugColor = AZ::Colors::White; diff --git a/Gems/PhysX/Code/Source/Pipeline/HeightFieldAssetHandler.cpp b/Gems/PhysX/Code/Source/Pipeline/HeightFieldAssetHandler.cpp index d21bd02737..e4d64d4139 100644 --- a/Gems/PhysX/Code/Source/Pipeline/HeightFieldAssetHandler.cpp +++ b/Gems/PhysX/Code/Source/Pipeline/HeightFieldAssetHandler.cpp @@ -106,7 +106,7 @@ namespace PhysX AZStd::shared_ptr stream, [[maybe_unused]] const AZ::Data::AssetFilterCB& assetLoadFilterCB) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); HeightFieldAsset* physXHeightFieldAsset = asset.GetAs(); if (!physXHeightFieldAsset) @@ -166,7 +166,7 @@ namespace PhysX bool HeightFieldAssetHandler::SaveAssetData(const AZ::Data::Asset& asset, AZ::IO::GenericStream* stream) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); HeightFieldAsset* physXHeightFieldAsset = asset.GetAs(); if (!physXHeightFieldAsset) diff --git a/Gems/PhysX/Code/Source/RigidBodyStatic.cpp b/Gems/PhysX/Code/Source/RigidBodyStatic.cpp index 325c42960a..2d4d64e518 100644 --- a/Gems/PhysX/Code/Source/RigidBodyStatic.cpp +++ b/Gems/PhysX/Code/Source/RigidBodyStatic.cpp @@ -20,6 +20,8 @@ namespace PhysX { + AZ_CLASS_ALLOCATOR_IMPL(PhysX::StaticRigidBody, AZ::SystemAllocator, 0); + StaticRigidBody::StaticRigidBody(const AzPhysics::StaticRigidBodyConfiguration& configuration) { CreatePhysXActor(configuration); @@ -40,7 +42,7 @@ namespace PhysX // Invalidate user data so it sets m_pxStaticRigidBody->userData to nullptr. // It's appropriate to do this as m_pxStaticRigidBody is a shared pointer and - // techniqucally it could survive m_actorUserData life's spam. + // technically it could survive m_actorUserData life's span. m_actorUserData.Invalidate(); } diff --git a/Gems/PhysX/Code/Source/RigidBodyStatic.h b/Gems/PhysX/Code/Source/RigidBodyStatic.h index 5301fdce08..3226cae836 100644 --- a/Gems/PhysX/Code/Source/RigidBodyStatic.h +++ b/Gems/PhysX/Code/Source/RigidBodyStatic.h @@ -26,8 +26,8 @@ namespace PhysX : public AzPhysics::StaticRigidBody { public: - AZ_CLASS_ALLOCATOR(StaticRigidBody, AZ::SystemAllocator, 0); - AZ_RTTI(StaticRigidBody, "{06E960EF-E1F3-466F-B34F-800E32775092}", AzPhysics::StaticRigidBody); + AZ_CLASS_ALLOCATOR_DECL; + AZ_RTTI(PhysX::StaticRigidBody, "{06E960EF-E1F3-466F-B34F-800E32775092}", AzPhysics::StaticRigidBody); StaticRigidBody() = default; StaticRigidBody(const AzPhysics::StaticRigidBodyConfiguration& configuration); diff --git a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp index a47f0ba16f..a2866b5a09 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp @@ -139,8 +139,9 @@ namespace PhysX else if (auto* shapeColliderPairList = AZStd::get_if>(&shapeData)) { bool shapeAdded = false; - for (const auto& shapeColliderConfigs : *shapeColliderPairList) + if (!shapeColliderPairList->empty()) { + const auto& shapeColliderConfigs = shapeColliderPairList->front(); auto shapePtr = AZStd::make_shared(*(shapeColliderConfigs.first), *(shapeColliderConfigs.second)); AZStd::visit([shapePtr, &shapeAdded](auto&& body) { @@ -529,7 +530,7 @@ namespace PhysX void PhysXScene::StartSimulation(float deltatime) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "PhysXScene::StartSimulation"); + AZ_PROFILE_SCOPE(Physics, "PhysXScene::StartSimulation"); if (!IsEnabled()) { @@ -537,7 +538,7 @@ namespace PhysX } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "OnSceneSimulationStartEvent::Signaled"); + AZ_PROFILE_SCOPE(Physics, "OnSceneSimulationStartEvent::Signaled"); m_sceneSimuationStartEvent.Signal(m_sceneHandle, deltatime); } @@ -549,7 +550,7 @@ namespace PhysX void PhysXScene::FinishSimulation() { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "PhysXScene::FinishSimulation"); + AZ_PROFILE_SCOPE(Physics, "PhysXScene::FinishSimulation"); if (!IsEnabled()) { @@ -557,7 +558,7 @@ namespace PhysX } { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "PhysXScene::CheckResults"); + AZ_PROFILE_SCOPE(Physics, "PhysXScene::CheckResults"); // Wait for the simulation to complete. // In the multithreaded environment we need to make sure we don't lock the scene for write here. @@ -569,7 +570,7 @@ namespace PhysX bool activeActorsEnabled = false; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "PhysXScene::FetchResults"); + AZ_PROFILE_SCOPE(Physics, "PhysXScene::FetchResults"); PHYSX_SCENE_WRITE_LOCK(m_pxScene); activeActorsEnabled = m_pxScene->getFlags() & physx::PxSceneFlag::eENABLE_ACTIVE_ACTORS; @@ -580,7 +581,7 @@ namespace PhysX if (activeActorsEnabled) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "PhysXScene::ActiveActors"); + AZ_PROFILE_SCOPE(Physics, "PhysXScene::ActiveActors"); PHYSX_SCENE_READ_LOCK(m_pxScene); @@ -602,7 +603,7 @@ namespace PhysX ClearDeferedDeletions(); { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "OnSceneSimulationFinishedEvent::Signaled"); + AZ_PROFILE_SCOPE(Physics, "OnSceneSimulationFinishedEvent::Signaled"); m_sceneSimuationFinishEvent.Signal(m_sceneHandle, m_currentDeltaTime); } @@ -1108,7 +1109,7 @@ namespace PhysX void PhysXScene::ProcessTriggerEvents() { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "PhysXScene::ProcessTriggerEvents"); + AZ_PROFILE_SCOPE(Physics, "PhysXScene::ProcessTriggerEvents"); AzPhysics::TriggerEventList& triggers = m_simulationEventCallback.GetQueuedTriggerEvents(); if (triggers.empty()) @@ -1135,7 +1136,7 @@ namespace PhysX void PhysXScene::ProcessCollisionEvents() { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "PhysXScene::ProcessCollisionEvents"); + AZ_PROFILE_SCOPE(Physics, "PhysXScene::ProcessCollisionEvents"); AzPhysics::CollisionEventList& collisions = m_simulationEventCallback.GetQueuedCollisionEvents(); if (collisions.empty()) @@ -1181,7 +1182,7 @@ namespace PhysX return; } - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, "PhysX::Statistics"); + AZ_PROFILE_SCOPE(Physics, "PhysX::Statistics"); physx::PxSimulationStatistics stats; @@ -1193,33 +1194,33 @@ namespace PhysX [[maybe_unused]] const char* RootCategory = "PhysX/%s/%s"; [[maybe_unused]] const char* ShapesSubCategory = "Shapes"; - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbShapes[PxGeometryType::eSPHERE], RootCategory, ShapesSubCategory, "Sphere"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbShapes[PxGeometryType::ePLANE], RootCategory, ShapesSubCategory, "Plane"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbShapes[PxGeometryType::eCAPSULE], RootCategory, ShapesSubCategory, "Capsule"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbShapes[PxGeometryType::eBOX], RootCategory, ShapesSubCategory, "Box"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbShapes[PxGeometryType::eCONVEXMESH], RootCategory, ShapesSubCategory, "ConvexMesh"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbShapes[PxGeometryType::eTRIANGLEMESH], RootCategory, ShapesSubCategory, "TriangleMesh"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbShapes[PxGeometryType::eHEIGHTFIELD], RootCategory, ShapesSubCategory, "Heightfield"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbShapes[PxGeometryType::eSPHERE], RootCategory, ShapesSubCategory, "Sphere"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbShapes[PxGeometryType::ePLANE], RootCategory, ShapesSubCategory, "Plane"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbShapes[PxGeometryType::eCAPSULE], RootCategory, ShapesSubCategory, "Capsule"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbShapes[PxGeometryType::eBOX], RootCategory, ShapesSubCategory, "Box"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbShapes[PxGeometryType::eCONVEXMESH], RootCategory, ShapesSubCategory, "ConvexMesh"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbShapes[PxGeometryType::eTRIANGLEMESH], RootCategory, ShapesSubCategory, "TriangleMesh"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbShapes[PxGeometryType::eHEIGHTFIELD], RootCategory, ShapesSubCategory, "Heightfield"); [[maybe_unused]] const char* ObjectsSubCategory = "Objects"; - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbActiveConstraints, RootCategory, ObjectsSubCategory, "ActiveConstraints"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbActiveDynamicBodies, RootCategory, ObjectsSubCategory, "ActiveDynamicBodies"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbActiveKinematicBodies, RootCategory, ObjectsSubCategory, "ActiveKinematicBodies"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbStaticBodies, RootCategory, ObjectsSubCategory, "StaticBodies"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbDynamicBodies, RootCategory, ObjectsSubCategory, "DynamicBodies"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbKinematicBodies, RootCategory, ObjectsSubCategory, "KinematicBodies"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbAggregates, RootCategory, ObjectsSubCategory, "Aggregates"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbArticulations, RootCategory, ObjectsSubCategory, "Articulations"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbActiveConstraints, RootCategory, ObjectsSubCategory, "ActiveConstraints"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbActiveDynamicBodies, RootCategory, ObjectsSubCategory, "ActiveDynamicBodies"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbActiveKinematicBodies, RootCategory, ObjectsSubCategory, "ActiveKinematicBodies"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbStaticBodies, RootCategory, ObjectsSubCategory, "StaticBodies"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbDynamicBodies, RootCategory, ObjectsSubCategory, "DynamicBodies"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbKinematicBodies, RootCategory, ObjectsSubCategory, "KinematicBodies"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbAggregates, RootCategory, ObjectsSubCategory, "Aggregates"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbArticulations, RootCategory, ObjectsSubCategory, "Articulations"); [[maybe_unused]] const char* SolverSubCategory = "Solver"; - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbAxisSolverConstraints, RootCategory, SolverSubCategory, "AxisSolverConstraints"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.compressedContactSize, RootCategory, SolverSubCategory, "CompressedContactSize"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.requiredContactConstraintMemory, RootCategory, SolverSubCategory, "RequiredContactConstraintMemory"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.peakConstraintMemory, RootCategory, SolverSubCategory, "PeakConstraintMemory"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbAxisSolverConstraints, RootCategory, SolverSubCategory, "AxisSolverConstraints"); + AZ_PROFILE_DATAPOINT(Physics, stats.compressedContactSize, RootCategory, SolverSubCategory, "CompressedContactSize"); + AZ_PROFILE_DATAPOINT(Physics, stats.requiredContactConstraintMemory, RootCategory, SolverSubCategory, "RequiredContactConstraintMemory"); + AZ_PROFILE_DATAPOINT(Physics, stats.peakConstraintMemory, RootCategory, SolverSubCategory, "PeakConstraintMemory"); [[maybe_unused]] const char* BroadphaseSubCategory = "Broadphase"; - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.getNbBroadPhaseAdds(), RootCategory, BroadphaseSubCategory, "BroadPhaseAdds"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.getNbBroadPhaseRemoves(), RootCategory, BroadphaseSubCategory, "BroadPhaseRemoves"); + AZ_PROFILE_DATAPOINT(Physics, stats.getNbBroadPhaseAdds(), RootCategory, BroadphaseSubCategory, "BroadPhaseAdds"); + AZ_PROFILE_DATAPOINT(Physics, stats.getNbBroadPhaseRemoves(), RootCategory, BroadphaseSubCategory, "BroadPhaseRemoves"); // Compute pair stats for all geometry types AZ::u32 ccdPairs = 0; @@ -1240,16 +1241,16 @@ namespace PhysX } [[maybe_unused]] const char* CollisionsSubCategory = "Collisions"; - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, ccdPairs, RootCategory, CollisionsSubCategory, "CCDPairs"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, modifiedPairs, RootCategory, CollisionsSubCategory, "ModifiedPairs"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, triggerPairs, RootCategory, CollisionsSubCategory, "TriggerPairs"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbDiscreteContactPairsTotal, RootCategory, CollisionsSubCategory, "DiscreteContactPairsTotal"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbDiscreteContactPairsWithCacheHits, RootCategory, CollisionsSubCategory, "DiscreteContactPairsWithCacheHits"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbDiscreteContactPairsWithContacts, RootCategory, CollisionsSubCategory, "DiscreteContactPairsWithContacts"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbNewPairs, RootCategory, CollisionsSubCategory, "NewPairs"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbLostPairs, RootCategory, CollisionsSubCategory, "LostPairs"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbNewTouches, RootCategory, CollisionsSubCategory, "NewTouches"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbLostTouches, RootCategory, CollisionsSubCategory, "LostTouches"); - AZ_PROFILE_DATAPOINT(AZ::Debug::ProfileCategory::Physics, stats.nbPartitions, RootCategory, CollisionsSubCategory, "Partitions"); + AZ_PROFILE_DATAPOINT(Physics, ccdPairs, RootCategory, CollisionsSubCategory, "CCDPairs"); + AZ_PROFILE_DATAPOINT(Physics, modifiedPairs, RootCategory, CollisionsSubCategory, "ModifiedPairs"); + AZ_PROFILE_DATAPOINT(Physics, triggerPairs, RootCategory, CollisionsSubCategory, "TriggerPairs"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbDiscreteContactPairsTotal, RootCategory, CollisionsSubCategory, "DiscreteContactPairsTotal"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbDiscreteContactPairsWithCacheHits, RootCategory, CollisionsSubCategory, "DiscreteContactPairsWithCacheHits"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbDiscreteContactPairsWithContacts, RootCategory, CollisionsSubCategory, "DiscreteContactPairsWithContacts"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbNewPairs, RootCategory, CollisionsSubCategory, "NewPairs"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbLostPairs, RootCategory, CollisionsSubCategory, "LostPairs"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbNewTouches, RootCategory, CollisionsSubCategory, "NewTouches"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbLostTouches, RootCategory, CollisionsSubCategory, "LostTouches"); + AZ_PROFILE_DATAPOINT(Physics, stats.nbPartitions, RootCategory, CollisionsSubCategory, "Partitions"); } } diff --git a/Gems/PhysX/Code/Source/System/PhysXJob.cpp b/Gems/PhysX/Code/Source/System/PhysXJob.cpp index d65f2b756e..597c8bea98 100644 --- a/Gems/PhysX/Code/Source/System/PhysXJob.cpp +++ b/Gems/PhysX/Code/Source/System/PhysXJob.cpp @@ -19,7 +19,7 @@ namespace PhysX void PhysXJob::Process() { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Physics, m_pxTask.getName()); + AZ_PROFILE_SCOPE(Physics, m_pxTask.getName()); m_pxTask.run(); m_pxTask.release(); } diff --git a/Gems/PhysX/Code/Source/System/PhysXSdkCallbacks.cpp b/Gems/PhysX/Code/Source/System/PhysXSdkCallbacks.cpp index f0182cdbcc..28981722b6 100644 --- a/Gems/PhysX/Code/Source/System/PhysXSdkCallbacks.cpp +++ b/Gems/PhysX/Code/Source/System/PhysXSdkCallbacks.cpp @@ -45,11 +45,11 @@ namespace PhysX { if (!detached) { - AZ_PROFILE_EVENT_BEGIN(AZ::Debug::ProfileCategory::Physics, eventName); + AZ_PROFILE_BEGIN(Physics, eventName); } else { - AZ_PROFILE_INTERVAL_START(AZ::Debug::ProfileCategory::Physics, AZ::Crc32(eventName), eventName); + AZ_PROFILE_INTERVAL_START(Physics, AZ::Crc32(eventName), eventName); } return nullptr; } @@ -59,11 +59,11 @@ namespace PhysX { if (!detached) { - AZ_PROFILE_EVENT_END(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_END(); } else { - AZ_PROFILE_INTERVAL_END(AZ::Debug::ProfileCategory::Physics, AZ::Crc32(eventName)); + AZ_PROFILE_INTERVAL_END(Physics, AZ::Crc32(eventName)); } } } diff --git a/Gems/PhysX/Code/Source/System/PhysXSystem.cpp b/Gems/PhysX/Code/Source/System/PhysXSystem.cpp index cc55255e24..ebdfc5d417 100644 --- a/Gems/PhysX/Code/Source/System/PhysXSystem.cpp +++ b/Gems/PhysX/Code/Source/System/PhysXSystem.cpp @@ -130,7 +130,7 @@ namespace PhysX void PhysXSystem::Simulate(float deltaTime) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); if (m_state != State::Initialized) { @@ -251,7 +251,7 @@ namespace PhysX if (sceneItr != m_sceneList.end()) { - return AzPhysics::SceneHandle((*sceneItr)->GetId(), AZStd::distance(m_sceneList.begin(), sceneItr)); + return AzPhysics::SceneHandle((*sceneItr)->GetId(), static_cast(AZStd::distance(m_sceneList.begin(), sceneItr))); } return AzPhysics::InvalidSceneHandle; } @@ -312,7 +312,7 @@ namespace PhysX { m_sceneRemovedEvent.Signal(handle); m_sceneList[index].reset(); - m_freeSceneSlots.push(index); + m_freeSceneSlots.push(static_cast(index)); } } } diff --git a/Gems/PhysX/Code/Source/SystemComponent.cpp b/Gems/PhysX/Code/Source/SystemComponent.cpp index d8c4b47a2a..42c78d2c1d 100644 --- a/Gems/PhysX/Code/Source/SystemComponent.cpp +++ b/Gems/PhysX/Code/Source/SystemComponent.cpp @@ -396,7 +396,7 @@ namespace PhysX void SystemComponent::SetCollisionLayerName(int index, const AZStd::string& layerName) { - m_physXSystem->SetCollisionLayerName(aznumeric_cast(index), layerName); + m_physXSystem->SetCollisionLayerName(aznumeric_cast(index), layerName); } void SystemComponent::CreateCollisionGroup(const AZStd::string& groupName, const AzPhysics::CollisionGroup& group) diff --git a/Gems/PhysX/Code/Tests/PhysXCollisionFilteringTest.cpp b/Gems/PhysX/Code/Tests/PhysXCollisionFilteringTest.cpp index dec01392b8..421cf375d9 100644 --- a/Gems/PhysX/Code/Tests/PhysXCollisionFilteringTest.cpp +++ b/Gems/PhysX/Code/Tests/PhysXCollisionFilteringTest.cpp @@ -24,7 +24,6 @@ namespace PhysX { protected: const AZStd::string DefaultLayer = "Default"; - const AZStd::string TouchBendLayer = "TouchBend"; const AZStd::string LayerA = "LayerA"; const AZStd::string LayerB = "LayerB"; const AZStd::string GroupA = "GroupA"; @@ -42,7 +41,6 @@ namespace PhysX AZStd::vector TestCollisionLayers = { DefaultLayer, - TouchBendLayer, // This is needed here as placeholder as collision events are disabled on this layer. LayerA, LayerB }; diff --git a/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp b/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp index ff112a75dd..5b90ef0004 100644 --- a/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp @@ -94,7 +94,7 @@ namespace PhysX //invalid scene handle returns empty AzPhysics::SimulatedBodyHandleList emptyBodies = sceneInterface->AddSimulatedBodies(AzPhysics::InvalidSceneHandle, configs); EXPECT_TRUE(emptyBodies.empty()); - emptyBodies = sceneInterface->AddSimulatedBodies(AzPhysics::SceneHandle(2347892347890, 7), configs); + emptyBodies = sceneInterface->AddSimulatedBodies(AzPhysics::SceneHandle(static_cast(2347892347890), AzPhysics::SceneIndex(7)), configs); EXPECT_TRUE(emptyBodies.empty()); //add some rigid bodies @@ -165,7 +165,7 @@ namespace PhysX //invalid scene handle returns null AzPhysics::SimulatedBody* nullBody = sceneInterface->GetSimulatedBodyFromHandle(AzPhysics::InvalidSceneHandle, newBodies[0]); EXPECT_TRUE(nullBody == nullptr); - nullBody = sceneInterface->GetSimulatedBodyFromHandle(AzPhysics::SceneHandle(2347892347890, 7), newBodies[0]); + nullBody = sceneInterface->GetSimulatedBodyFromHandle(AzPhysics::SceneHandle(static_cast(2347892347890), AzPhysics::SceneIndex(7)), newBodies[0]); EXPECT_TRUE(nullBody == nullptr); //invalid simulated body handle returns null diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 831a7fdf1d..65115f2790 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp @@ -347,7 +347,7 @@ namespace PhysXDebug static const physx::PxRenderBuffer& GetRenderBuffer(physx::PxScene* physxScene) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); PHYSX_SCENE_READ_LOCK(physxScene); return physxScene->getRenderBuffer(); } @@ -439,7 +439,7 @@ namespace PhysXDebug return; } - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); m_currentTime = time; bool dirty = true; @@ -620,7 +620,7 @@ namespace PhysXDebug void SystemComponent::ConfigurePhysXVisualizationParameters() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); if (physx::PxScene* physxScene = GetCurrentPxScene()) { @@ -667,7 +667,7 @@ namespace PhysXDebug void SystemComponent::ConfigureCullingBox() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); // Currently using the Cry view camera to support Editor, Game and Launcher modes. This will be updated in due course. const AZ::Vector3 cameraTranslation = GetViewCameraPosition(); @@ -694,7 +694,7 @@ namespace PhysXDebug void SystemComponent::GatherTriangles(const physx::PxRenderBuffer& rb) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); if (!m_settings.m_visualizationEnabled) { return; @@ -728,7 +728,7 @@ namespace PhysXDebug void SystemComponent::GatherLines(const physx::PxRenderBuffer& rb) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); if (!m_settings.m_visualizationEnabled) { @@ -763,7 +763,7 @@ namespace PhysXDebug void SystemComponent::GatherJointLimits() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); physx::PxScene* scene = GetCurrentPxScene(); @@ -824,7 +824,7 @@ namespace PhysXDebug void SystemComponent::DrawDebugCullingBox(const AZ::Aabb& cullingBoxAabb) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); if (m_settings.m_visualizationEnabled && m_culling.m_boxWireframe) { @@ -842,7 +842,7 @@ namespace PhysXDebug AZ::Color SystemComponent::MapOriginalPhysXColorToUserDefinedValues(const physx::PxU32& originalColor) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); + AZ_PROFILE_FUNCTION(Physics); // color mapping from PhysX to LY user preference: \PhysX_3.4\Include\common\PxRenderBuffer.h switch (static_cast(originalColor)) @@ -878,19 +878,19 @@ namespace PhysXDebug void SystemComponent::InitPhysXColorMappings() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); - m_colorMappings.m_defaultColor.FromU32(physx::PxDebugColor::eARGB_GREEN); - m_colorMappings.m_black.FromU32(physx::PxDebugColor::eARGB_BLACK); - m_colorMappings.m_red.FromU32(physx::PxDebugColor::eARGB_RED); - m_colorMappings.m_green.FromU32(physx::PxDebugColor::eARGB_GREEN); - m_colorMappings.m_blue.FromU32(physx::PxDebugColor::eARGB_BLUE); - m_colorMappings.m_yellow.FromU32(physx::PxDebugColor::eARGB_YELLOW); - m_colorMappings.m_magenta.FromU32(physx::PxDebugColor::eARGB_MAGENTA); - m_colorMappings.m_cyan.FromU32(physx::PxDebugColor::eARGB_CYAN); - m_colorMappings.m_white.FromU32(physx::PxDebugColor::eARGB_WHITE); - m_colorMappings.m_grey.FromU32(physx::PxDebugColor::eARGB_GREY); - m_colorMappings.m_darkRed.FromU32(physx::PxDebugColor::eARGB_DARKRED); - m_colorMappings.m_darkGreen.FromU32(physx::PxDebugColor::eARGB_DARKGREEN); - m_colorMappings.m_darkBlue.FromU32(physx::PxDebugColor::eARGB_DARKBLUE); + AZ_PROFILE_FUNCTION(Physics); + m_colorMappings.m_defaultColor.FromU32(static_cast(physx::PxDebugColor::eARGB_GREEN)); + m_colorMappings.m_black.FromU32(static_cast(physx::PxDebugColor::eARGB_BLACK)); + m_colorMappings.m_red.FromU32(static_cast(physx::PxDebugColor::eARGB_RED)); + m_colorMappings.m_green.FromU32(static_cast(physx::PxDebugColor::eARGB_GREEN)); + m_colorMappings.m_blue.FromU32(static_cast(physx::PxDebugColor::eARGB_BLUE)); + m_colorMappings.m_yellow.FromU32(static_cast(physx::PxDebugColor::eARGB_YELLOW)); + m_colorMappings.m_magenta.FromU32(static_cast(physx::PxDebugColor::eARGB_MAGENTA)); + m_colorMappings.m_cyan.FromU32(static_cast(physx::PxDebugColor::eARGB_CYAN)); + m_colorMappings.m_white.FromU32(static_cast(physx::PxDebugColor::eARGB_WHITE)); + m_colorMappings.m_grey.FromU32(static_cast(physx::PxDebugColor::eARGB_GREY)); + m_colorMappings.m_darkRed.FromU32(static_cast(physx::PxDebugColor::eARGB_DARKRED)); + m_colorMappings.m_darkGreen.FromU32(static_cast(physx::PxDebugColor::eARGB_DARKGREEN)); + m_colorMappings.m_darkBlue.FromU32(static_cast(physx::PxDebugColor::eARGB_DARKBLUE)); } } diff --git a/Gems/PythonAssetBuilder/Code/Source/Platform/Common/MSVC/pythonassetbuilder_tests_msvc.cmake b/Gems/PythonAssetBuilder/Code/Source/Platform/Common/MSVC/pythonassetbuilder_tests_msvc.cmake index b2c4543e99..7a325ca97e 100644 --- a/Gems/PythonAssetBuilder/Code/Source/Platform/Common/MSVC/pythonassetbuilder_tests_msvc.cmake +++ b/Gems/PythonAssetBuilder/Code/Source/Platform/Common/MSVC/pythonassetbuilder_tests_msvc.cmake @@ -5,13 +5,3 @@ # SPDX-License-Identifier: Apache-2.0 OR MIT # # - -ly_add_source_properties( - SOURCES - Tests/PythonAssetBuilderTest.cpp - Tests/PythonBuilderRegisterTest.cpp - Tests/PythonBuilderCreateJobsTest.cpp - Tests/PythonBuilderProcessJobTest.cpp - PROPERTY COMPILE_OPTIONS - VALUES -bigobj -) diff --git a/Gems/RADTelemetry/CMakeLists.txt b/Gems/RADTelemetry/CMakeLists.txt deleted file mode 100644 index 2bb380fae3..0000000000 --- a/Gems/RADTelemetry/CMakeLists.txt +++ /dev/null @@ -1,9 +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 -# -# - -add_subdirectory(Code) diff --git a/Gems/RADTelemetry/Code/CMakeLists.txt b/Gems/RADTelemetry/Code/CMakeLists.txt deleted file mode 100644 index 544540f273..0000000000 --- a/Gems/RADTelemetry/Code/CMakeLists.txt +++ /dev/null @@ -1,47 +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 -# -# - -set(LY_RAD_TELEMETRY_ENABLED OFF CACHE BOOL "Enables RAD Telemetry in Debug/Profile mode.") -set(LY_RAD_TELEMETRY_INSTALL_ROOT "@LY_3RDPARTY_PATH@/RadTelemetry" CACHE PATH "Install path to RAD Telemetry.") -string(CONFIGURE ${LY_RAD_TELEMETRY_INSTALL_ROOT} LY_RAD_TELEMETRY_INSTALL_ROOT @ONLY) - -ly_get_list_relative_pal_filename(pal_source_dir ${CMAKE_CURRENT_LIST_DIR}/Source/Platform/${PAL_PLATFORM_NAME}) - -ly_add_target( - NAME RADTelemetry.Static STATIC - NAMESPACE Gem - FILES_CMAKE - radtelemetry_files.cmake - ${pal_source_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - Source - ${pal_source_dir} - BUILD_DEPENDENCIES - PUBLIC - AZ::AzCore - Legacy::CryCommon -) - -ly_add_target( - NAME RADTelemetry ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} - NAMESPACE Gem - FILES_CMAKE - radtelemetry_shared_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - Source - BUILD_DEPENDENCIES - PRIVATE - Gem::RADTelemetry.Static -) - -# the RADTelemetry module above can be used in all kinds of applications, but we don't enable it in asset builders -ly_create_alias(NAME RADTelemetry.Clients NAMESPACE Gem TARGETS Gem::RADTelemetry) -ly_create_alias(NAME RADTelemetry.Tools NAMESPACE Gem TARGETS Gem::RADTelemetry) -ly_create_alias(NAME RADTelemetry.Servers NAMESPACE Gem TARGETS Gem::RADTelemetry) diff --git a/Gems/RADTelemetry/Code/Source/Platform/iOS/RADTelemetry_Traits_Platform.h b/Gems/RADTelemetry/Code/Source/Platform/iOS/RADTelemetry_Traits_Platform.h deleted file mode 100644 index 8b524df127..0000000000 --- a/Gems/RADTelemetry/Code/Source/Platform/iOS/RADTelemetry_Traits_Platform.h +++ /dev/null @@ -1,10 +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 - * - */ -#pragma once - -#define AZ_TRAIT_RAD_TELEMETRY_OPEN_FLAGS TMOF_INIT_NETWORKING diff --git a/Gems/RADTelemetry/Code/Source/Platform/iOS/platform_ios_files.cmake b/Gems/RADTelemetry/Code/Source/Platform/iOS/platform_ios_files.cmake deleted file mode 100644 index 6e7a9dd5eb..0000000000 --- a/Gems/RADTelemetry/Code/Source/Platform/iOS/platform_ios_files.cmake +++ /dev/null @@ -1,11 +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 -# -# - -set(FILES - RADTelemetry_Traits_Platform.h -) diff --git a/Gems/RADTelemetry/Code/Source/ProfileTelemetryComponent.cpp b/Gems/RADTelemetry/Code/Source/ProfileTelemetryComponent.cpp deleted file mode 100644 index b76d36d189..0000000000 --- a/Gems/RADTelemetry/Code/Source/ProfileTelemetryComponent.cpp +++ /dev/null @@ -1,344 +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 - * - */ - -#ifdef AZ_PROFILE_TELEMETRY - -#include -#include -#include - -#include -#include - -#include "ProfileTelemetryComponent.h" - -namespace RADTelemetry -{ - static const char * ProfileChannel = "RADTelemetry"; - static const AZ::u32 MaxProfileThreadCount = 128; - - static void MessageFrameTickType(AZ::Debug::ProfileFrameAdvanceType type) - { - const char * frameAdvanceTypeMessage = "Profile tick set to %s"; - const char* frameAdvanceTypeString = (type == AZ::Debug::ProfileFrameAdvanceType::Game) ? "Game Thread" : "Render Frame"; - AZ_Printf(ProfileChannel, frameAdvanceTypeMessage, frameAdvanceTypeString); - tmMessage(0, TMMF_SEVERITY_LOG, frameAdvanceTypeMessage, frameAdvanceTypeString); - } - - ProfileTelemetryComponent::ProfileTelemetryComponent() - { - // Connecting in the constructor because we need to catch ALL created threads - AZStd::ThreadEventBus::Handler::BusConnect(); - } - - ProfileTelemetryComponent::~ProfileTelemetryComponent() - { - AZ_Assert(!m_running, "A telemetry session should not be open."); - - AZStd::ThreadEventBus::Handler::BusDisconnect(); - - if (IsInitialized()) - { - tmShutdown(); - AZ_OS_FREE(m_buffer); - m_buffer = nullptr; - } - } - - void ProfileTelemetryComponent::Activate() - { - AZ::Debug::ProfilerRequestBus::Handler::BusConnect(); - ProfileTelemetryRequestBus::Handler::BusConnect(); - AZ::SystemTickBus::Handler::BusConnect(); - } - - void ProfileTelemetryComponent::Deactivate() - { - AZ::SystemTickBus::Handler::BusDisconnect(); - ProfileTelemetryRequestBus::Handler::BusDisconnect(); - AZ::Debug::ProfilerRequestBus::Handler::BusDisconnect(); - - Disable(); - } - - void ProfileTelemetryComponent::OnThreadEnter(const AZStd::thread_id& id, const AZStd::thread_desc* desc) - { - (void)id; - (void)desc; -#if AZ_TRAIT_OS_USE_WINDOWS_THREADS - if (!desc) - { - // Skip unnamed threads - return; - } - - if (IsInitialized()) - { - // We can send the thread name to Telemetry now - const AZ::u32 newProfiledThreadCount = ++m_profiledThreadCount; - AZ_Assert(newProfiledThreadCount <= MaxProfileThreadCount, "RAD Telemetry profiled threadcount exceeded MaxProfileThreadCount!"); - tmThreadName(0, id.m_id, desc->m_name); - return; - } - - // Save off to send on the next connection - ScopedLock lock(m_threadNameLock); - - auto end = m_threadNames.end(); - auto itr = AZStd::find_if(m_threadNames.begin(), end, [id](const ThreadNameEntry& entry) - { - return entry.id == id; - }); - - if (itr != end) - { - itr->name = desc->m_name; - } - else - { - m_threadNames.push_back({ id, desc->m_name }); - } -#else - const AZ::u32 newProfiledThreadCount = ++m_profiledThreadCount; - AZ_Assert(newProfiledThreadCount <= MaxProfileThreadCount, "RAD Telemetry profiled threadcount exceeded MaxProfileThreadCount!"); -#endif - } - - void ProfileTelemetryComponent::OnThreadExit(const AZStd::thread_id& id) - { - (void)id; -#if AZ_TRAIT_OS_USE_WINDOWS_THREADS - { - ScopedLock lock(m_threadNameLock); - - auto end = m_threadNames.end(); - auto itr = AZStd::find_if(m_threadNames.begin(), end, [id](const ThreadNameEntry& entry) - { - return entry.id == id; - }); - if (itr != end) - { - m_threadNames.erase(itr); - } - else - { - // assume it was already sent on to RAD Telemetry - tmEndThread(0, id.m_id); - --m_profiledThreadCount; - } - } -#else - --m_profiledThreadCount; -#endif - } - - void ProfileTelemetryComponent::OnSystemTick() - { - FrameAdvance(AZ::Debug::ProfileFrameAdvanceType::Game); - } - - void ProfileTelemetryComponent::FrameAdvance(AZ::Debug::ProfileFrameAdvanceType type) - { - if (type == m_frameAdvanceType) - { - tmTick(0); - } - } - - bool ProfileTelemetryComponent::IsActive() - { - return m_running; - } - - void ProfileTelemetryComponent::ToggleEnabled() - { - Initialize(); - - if (!m_running) - { - Enable(); - } - else - { - Disable(); - } - } - - tm_api* ProfileTelemetryComponent::GetApiInstance() - { - Initialize(); - - return TM_API_PTR; - } - - void ProfileTelemetryComponent::Enable() - { - AZ_Printf(ProfileChannel, "Attempting to connect to the Telemetry server at %s:%d", m_address, m_port); - - tmSetCaptureMask(m_captureMask); - tm_error result = tmOpen( - 0, // unused - "ly", // program name, don't use slashes or weird character that will screw up a filename - __DATE__ " " __TIME__, // identifier, could be date time, or a build number ... whatever you want - m_address, // telemetry server address - TMCT_TCP, // network capture - m_port, // telemetry server port - AZ_TRAIT_RAD_TELEMETRY_OPEN_FLAGS,// flags - 3000 // timeout in milliseconds ... pass -1 for infinite - ); - - switch (result) - { - case TM_OK: - { - m_running = true; - AZ_Printf(ProfileChannel, "Connected to the Telemetry server at %s:%d", m_address, m_port); - MessageFrameTickType(m_frameAdvanceType); - -#if AZ_TRAIT_OS_USE_WINDOWS_THREADS - ScopedLock lock(m_threadNameLock); - for (const auto& threadNameEntry : m_threadNames) - { - const AZ::u32 newProfiledThreadCount = ++m_profiledThreadCount; - AZ_Assert(newProfiledThreadCount <= MaxProfileThreadCount, "RAD Telemetry profiled thread count exceeded MaxProfileThreadCount!"); - tmThreadName(0, threadNameEntry.id.m_id, threadNameEntry.name.c_str()); - } - m_threadNames.clear(); // Telemetry caches names so we can clear what we have sent on -#endif - break; - } - - case TMERR_DISABLED: - AZ_Printf(ProfileChannel, "Telemetry is disabled via #define NTELEMETRY"); - break; - - case TMERR_UNINITIALIZED: - AZ_Printf(ProfileChannel, "tmInitialize failed or was not called"); - break; - - case TMERR_NETWORK_NOT_INITIALIZED: - AZ_Printf(ProfileChannel, "WSAStartup was not called before tmOpen! Call WSAStartup or pass TMOF_INIT_NETWORKING."); - break; - - case TMERR_NULL_API: - AZ_Printf(ProfileChannel, "There is no Telemetry API (the DLL isn't in the EXE's path)!"); - break; - - case TMERR_COULD_NOT_CONNECT: - AZ_Printf(ProfileChannel, "Unable to connect to the Telemetry server at %s:%d (1. is it running? 2. check firewall settings)", m_address, m_port); - break; - - case TMERR_UNKNOWN: - AZ_Printf(ProfileChannel, "Unknown error occurred"); - break; - - default: - AZ_Assert(false, "Unhandled tmOpen error case %d", result); - break; - } - } - - void ProfileTelemetryComponent::Disable() - { - if (m_running) - { - m_running = false; - tmClose(0); - AZ_Printf(ProfileChannel, "Disconnected from the Telemetry server."); - } - } - - TM_EXPORT_API tm_api* g_tm_api; // Required for the RAD Telemetry as static lib case - void ProfileTelemetryComponent::Initialize() - { - if (IsInitialized()) - { - return; - } - - tmLoadLibrary(TM_RELEASE); - if (!TM_API_PTR) - { - // Work around for UnixLike platforms that do not load RAD Telemetry static lib (they are incorrectly compiled with the dynamic library version of tmLoadLibrary. RAD is aware of the issue.) - TM_API_PTR = g_tm_api; - } - AZ_Assert(TM_API_PTR, "Invalid RAD Telemetry API pointer state"); - - tmSetMaxThreadCount(MaxProfileThreadCount); - - const tm_int32 telemetryBufferSize = 16 * 1024 * 1024; - m_buffer = static_cast(AZ_OS_MALLOC(telemetryBufferSize, sizeof(void*))); - tmInitialize(telemetryBufferSize, m_buffer); - - // Notify so individual modules can update their Telemetry pointer - AZ::Debug::ProfilerNotificationBus::Broadcast(&AZ::Debug::ProfilerNotifications::OnProfileSystemInitialized); - } - - bool ProfileTelemetryComponent::IsInitialized() const { - return m_buffer != nullptr; - } - - void ProfileTelemetryComponent::SetAddress(const char *address, AZ::u16 port) - { - m_address = address; - m_port = port; - } - - void ProfileTelemetryComponent::SetCaptureMask(AZ::Debug::ProfileCategoryPrimitiveType mask) - { - m_captureMask = mask; - if (IsInitialized()) - { - tmSetCaptureMask(m_captureMask); - } - } - - void ProfileTelemetryComponent::SetFrameAdvanceType(AZ::Debug::ProfileFrameAdvanceType type) - { - if (type != m_frameAdvanceType) - { - MessageFrameTickType(type); - m_frameAdvanceType = type; - } - } - - AZ::Debug::ProfileCategoryPrimitiveType ProfileTelemetryComponent::GetDefaultCaptureMaskInternal() - { - using MaskType = AZ::Debug::ProfileCategoryPrimitiveType; - - // Set all the category bits "below" FirstDetailedCategory and do not enable memory capture by default - return (static_cast(1) << static_cast(AZ::Debug::ProfileCategory::FirstDetailedCategory)) - 1; - } - - AZ::Debug::ProfileCategoryPrimitiveType ProfileTelemetryComponent::GetDefaultCaptureMask() - { - return GetDefaultCaptureMaskInternal(); - } - - AZ::Debug::ProfileCategoryPrimitiveType ProfileTelemetryComponent::GetCaptureMask() - { - return m_captureMask; - } - - void ProfileTelemetryComponent::Reflect(AZ::ReflectContext* context) - { - if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ; - } - } - - void ProfileTelemetryComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("ProfilerService")); - } -} - -#endif diff --git a/Gems/RADTelemetry/Code/Source/ProfileTelemetryComponent.h b/Gems/RADTelemetry/Code/Source/ProfileTelemetryComponent.h deleted file mode 100644 index 44fb1e5b4a..0000000000 --- a/Gems/RADTelemetry/Code/Source/ProfileTelemetryComponent.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#ifdef AZ_PROFILE_TELEMETRY - -#include -#include -#include -#include - -#include - -namespace RADTelemetry -{ - class ProfileTelemetryComponent - : public AZ::Component - , private AZStd::ThreadEventBus::Handler - , private AZ::SystemTickBus::Handler - , private AZ::Debug::ProfilerRequestBus::Handler - , private ProfileTelemetryRequestBus::Handler - { - public: - AZ_COMPONENT(ProfileTelemetryComponent, "{51118122-7214-4918-BFF3-237E25FF4918}"); - - ProfileTelemetryComponent(); - ~ProfileTelemetryComponent() override; - - ////////////////////////////////////////////////////////////////////////// - // AZ::Component - void Activate() override; - void Deactivate() override; - - private: - ProfileTelemetryComponent(const ProfileTelemetryComponent&) = delete; - ////////////////////////////////////////////////////////////////////////// - // Thread event bus - void OnThreadEnter(const AZStd::thread_id& id, const AZStd::thread_desc* desc) override; - void OnThreadExit(const AZStd::thread_id& id) override; - - ////////////////////////////////////////////////////////////////////////// - // SystemTickBus - void OnSystemTick() override; - - ////////////////////////////////////////////////////////////////////////// - // ProfilerRequstBus - bool IsActive() override; - void FrameAdvance(AZ::Debug::ProfileFrameAdvanceType type) override; - - ////////////////////////////////////////////////////////////////////////// - // ProfileTelemetryRequestBus - void ToggleEnabled() override; - void SetAddress(const char *address, AZ::u16 port) override; - void SetCaptureMask(AZ::Debug::ProfileCategoryPrimitiveType mask) override; - void SetFrameAdvanceType(AZ::Debug::ProfileFrameAdvanceType type) override; - - AZ::Debug::ProfileCategoryPrimitiveType GetCaptureMask() override; - AZ::Debug::ProfileCategoryPrimitiveType GetDefaultCaptureMask() override; - tm_api* GetApiInstance() override; - - ////////////////////////////////////////////////////////////////////////// - // Component descriptor - static void Reflect(AZ::ReflectContext* context); - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - - ////////////////////////////////////////////////////////////////////////// - // Private helpers - void Enable(); - void Disable(); - void Initialize(); - bool IsInitialized() const; - static AZ::Debug::ProfileCategoryPrimitiveType GetDefaultCaptureMaskInternal(); - - ////////////////////////////////////////////////////////////////////////// - // Data members - struct ThreadNameEntry - { - AZStd::thread_id id; - AZStd::string name; - }; - AZStd::vector m_threadNames; - using LockType = AZStd::mutex; - using ScopedLock = AZStd::lock_guard; - LockType m_threadNameLock; - AZStd::atomic_uint m_profiledThreadCount = { 0 }; - - const char* m_address = "127.0.0.1"; - char* m_buffer = nullptr; - AZ::Debug::ProfileCategoryPrimitiveType m_captureMask = GetDefaultCaptureMaskInternal(); - AZ::Debug::ProfileFrameAdvanceType m_frameAdvanceType = AZ::Debug::ProfileFrameAdvanceType::Game; - AZ::u16 m_port = 4719; - bool m_running = false; - bool m_initialized = false; - }; -} - -#endif diff --git a/Gems/RADTelemetry/Code/Source/RADTelemetryModule.cpp b/Gems/RADTelemetry/Code/Source/RADTelemetryModule.cpp deleted file mode 100644 index 56dc8f310a..0000000000 --- a/Gems/RADTelemetry/Code/Source/RADTelemetryModule.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include -#include -#include // snprintf -#include - -#include "ProfileTelemetryComponent.h" - -namespace RADTelemetry -{ -#ifdef AZ_PROFILE_TELEMETRY - using TelemetryRequestBus = RADTelemetry::ProfileTelemetryRequestBus; - using TelemetryRequests = RADTelemetry::ProfileTelemetryRequests; - using MaskType = AZ::Debug::ProfileCategoryPrimitiveType; - - static const char* s_telemetryAddress; - static int s_telemetryPort; - static const char* s_telemetryCaptureMask; - static int s_memCaptureEnabled; - static int s_frameAdvanceType; - - using FrameAdvanceType = AZ::Debug::ProfileFrameAdvanceType; - - static void MaskCvarChangedCallback(ICVar*) - { - if (!s_telemetryCaptureMask || !s_telemetryCaptureMask[0]) - { - return; - } - - // Parse as a 64-bit hex string - MaskType maskCvarValue = strtoull(s_telemetryCaptureMask, nullptr, 16); - if (maskCvarValue == std::numeric_limits::max()) - { - MaskType defaultMask = 0; - TelemetryRequestBus::BroadcastResult(defaultMask, &TelemetryRequests::GetDefaultCaptureMask); - - AZ_Error("RADTelemetryGem", false, "Invalid RAD Telemetry capture mask cvar value: %s, using default capture mask 0x%" PRIx64, s_telemetryCaptureMask, defaultMask); - maskCvarValue = defaultMask; - } - - // Mask off the memory capture flag and add it back if memory capture is enabled - const MaskType fullCaptureMask = (maskCvarValue & ~AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(AZ::Debug::ProfileCategory::MemoryReserved)) | (s_memCaptureEnabled ? AZ_PROFILE_CAT_TO_RAD_CAPFLAGS(AZ::Debug::ProfileCategory::MemoryReserved) : 0); - TelemetryRequestBus::Broadcast(&TelemetryRequests::SetCaptureMask, fullCaptureMask); - } - - static void FrameAdvancedTypeCvarChangedCallback(ICVar*) - { - TelemetryRequestBus::Broadcast(&TelemetryRequests::SetFrameAdvanceType, (s_frameAdvanceType == 0) ? FrameAdvanceType::Game : FrameAdvanceType::Render); - } - - static void CmdTelemetryToggleEnabled([[maybe_unused]] IConsoleCmdArgs* args) - { - TelemetryRequestBus::Broadcast(&TelemetryRequests::SetAddress, s_telemetryAddress, s_telemetryPort); - - FrameAdvancedTypeCvarChangedCallback(nullptr); // Set frame advance type - MaskCvarChangedCallback(nullptr); // Set the capture mask - - TelemetryRequestBus::Broadcast(&TelemetryRequests::ToggleEnabled); - } -#endif - - class RADTelemetryModule - : public CryHooksModule - { - public: - AZ_RTTI(RADTelemetryModule, "{50BB63A6-4669-41F2-B93D-6EB8529413CD}", CryHooksModule); - - RADTelemetryModule() - : CryHooksModule() - { -#ifdef AZ_PROFILE_TELEMETRY - m_descriptors.insert(m_descriptors.end(), { - ProfileTelemetryComponent::CreateDescriptor(), - }); -#endif - } - - /** - * Add required SystemComponents to the SystemEntity. - */ - AZ::ComponentTypeList GetRequiredSystemComponents() const override - { - AZ::ComponentTypeList components; - -#ifdef AZ_PROFILE_TELEMETRY - components.insert(components.end(), - azrtti_typeid() - ); -#endif - - return components; - } - - void OnCrySystemInitialized(ISystem& system, const SSystemInitParams& initParams) override - { - CryHooksModule::OnCrySystemInitialized(system, initParams); - -#ifdef AZ_PROFILE_TELEMETRY - REGISTER_COMMAND("radtm_ToggleEnabled", &CmdTelemetryToggleEnabled, 0, "Enabled or Disable RAD Telemetry"); - - REGISTER_CVAR2("radtm_Address", &s_telemetryAddress, "127.0.0.1", VF_NULL, "The IP address for the telemetry server"); - REGISTER_CVAR2("radtm_Port", &s_telemetryPort, 4719, VF_NULL, "The port for the RAD telemetry server"); - REGISTER_CVAR2("radtm_MemoryCaptureEnabled", &s_memCaptureEnabled, 0, VF_NULL, "Toggle for telemetry memory capture"); - - const int defaultFrameAdvanceTypeCvarValue = (FrameAdvanceType::Default == FrameAdvanceType::Game) ? 0 : 1; - REGISTER_CVAR2_CB("radtm_FrameAdvanceType", &s_frameAdvanceType, defaultFrameAdvanceTypeCvarValue, VF_NULL, "Advance profile frames from either: =0 the main thread, or =1 render frame advance", FrameAdvancedTypeCvarChangedCallback); - - // Get the default value from ProfileTelemetryComponent - MaskType defaultCaptureMaskValue = 0; - TelemetryRequestBus::BroadcastResult(defaultCaptureMaskValue, &TelemetryRequests::GetCaptureMask); - - char defaultCaptureMaskStr[19]; - azsnprintf(defaultCaptureMaskStr, AZ_ARRAY_SIZE(defaultCaptureMaskStr), "0x%" PRIx64, defaultCaptureMaskValue); - REGISTER_CVAR2_CB("radtm_CaptureMask", &s_telemetryCaptureMask, defaultCaptureMaskStr, VF_NULL, "A hex bitmask for the categories to be captured, 0x0 for all", MaskCvarChangedCallback); -#endif - } - }; -} - -// DO NOT MODIFY THIS LINE UNLESS YOU RENAME THE GEM -// The first parameter should be GemName_GemIdLower -// The second should be the fully qualified name of the class above -AZ_DECLARE_MODULE_CLASS(Gem_RADTelemetry, RADTelemetry::RADTelemetryModule) diff --git a/Gems/RADTelemetry/Code/radtelemetry_files.cmake b/Gems/RADTelemetry/Code/radtelemetry_files.cmake deleted file mode 100644 index 2efee83797..0000000000 --- a/Gems/RADTelemetry/Code/radtelemetry_files.cmake +++ /dev/null @@ -1,12 +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 -# -# - -set(FILES - Source/ProfileTelemetryComponent.cpp - Source/ProfileTelemetryComponent.h -) diff --git a/Gems/RADTelemetry/gem.json b/Gems/RADTelemetry/gem.json deleted file mode 100644 index 932093b4a9..0000000000 --- a/Gems/RADTelemetry/gem.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "gem_name": "RADTelemetry", - "display_name": "RAD Telemetry", - "license": "Apache-2.0 Or MIT", - "origin": "Open 3D Engine - o3de.org", - "type": "Tool", - "summary": "The RAD Telemetry Gem provides support for RAD Telemetry, a performance profiling and visualization middleware, in Open 3D Engine.", - "canonical_tags": ["Gem"], - "user_tags": ["Debug", "SDK"], - "icon_path": "preview.png", - "requirements": "", - "documentation_url": "https://o3de.org/docs/user-guide/gems/reference/debug/rad/rad-telemetry/" -} diff --git a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshBuilder.cpp b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshBuilder.cpp index acbc9ee46e..0f967f644e 100644 --- a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshBuilder.cpp +++ b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshBuilder.cpp @@ -250,7 +250,7 @@ namespace AZ::MeshBuilder AZ::JobContext* jobContext = nullptr; AZ::Job* job = AZ::CreateJobFunction([&subMesh]() { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Animation, "MeshBuilder::GenerateSubMeshVertexOrders::SubMeshJob"); + AZ_PROFILE_SCOPE(Animation, "MeshBuilder::GenerateSubMeshVertexOrders::SubMeshJob"); subMesh->GenerateVertexOrder(); }, true, jobContext); diff --git a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshBuilderSubMesh.cpp b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshBuilderSubMesh.cpp index 170549a25d..c10a8fb2ed 100644 --- a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshBuilderSubMesh.cpp +++ b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshBuilderSubMesh.cpp @@ -7,6 +7,7 @@ */ #include +#include #include "MeshBuilder.h" #include "MeshBuilderSkinningInfo.h" #include "MeshBuilderSubMesh.h" diff --git a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.cpp b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.cpp index 524b79b012..430733f3a1 100644 --- a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.cpp +++ b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.cpp @@ -73,6 +73,13 @@ namespace SceneBuilder required.emplace_back(AZ_CRC_CE("AssetImportRequestHandler")); } + void BuilderPluginComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& services) + { + // Any components that can modify the analysis fingerprint via SceneBuilderDependencyRequests::AddFingerprintInfo must be activated first, + // so they contribute to the fingerprint calculated in BuilderPluginComponent::Activate(). + services.emplace_back(AZ_CRC_CE("FingerprintModification")); + } + void BuilderPluginComponent::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast(context); diff --git a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.h b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.h index b4eee64bc6..0bfe118a4c 100644 --- a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.h +++ b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderComponent.h @@ -29,6 +29,7 @@ namespace SceneBuilder void Deactivate() override; static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& services); private: SceneBuilderWorker m_sceneBuilder; diff --git a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderWorker.cpp b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderWorker.cpp index 18ee0285b8..c1a1252c6b 100644 --- a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderWorker.cpp +++ b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderWorker.cpp @@ -10,9 +10,7 @@ #include #include #include -#include #include -#include #include #include #include @@ -69,6 +67,8 @@ namespace SceneBuilder context->EnumerateDerived(callback, azrtti_typeid(), azrtti_typeid()); context->EnumerateDerived(callback, azrtti_typeid(), azrtti_typeid()); } + + AZ::SceneAPI::SceneBuilderDependencyBus::Broadcast(&AZ::SceneAPI::SceneBuilderDependencyRequests::AddFingerprintInfo, fragments); for (const AZStd::string& element : fragments) { @@ -306,7 +306,10 @@ namespace SceneBuilder if (itr != request.m_jobDescription.m_jobParameters.end() && itr->second == "true") { - BuildDebugSceneGraph(outputFolder.c_str(), productList, scene); + AZStd::string productName; + AzFramework::StringFunc::Path::GetFullFileName(scene->GetSourceFilename().c_str(), productName); + AzFramework::StringFunc::Path::ReplaceExtension(productName, "dbgsg"); + AZ::SceneAPI::Utilities::DebugOutput::BuildDebugSceneGraph(outputFolder.c_str(), productList, scene, productName); } AZ_TracePrintf(Utilities::LogWindow, "Collecting and registering products.\n"); @@ -371,66 +374,4 @@ namespace SceneBuilder return id; } - - void WriteAndLog(AZ::IO::SystemFile& dbgFile, const char* strToWrite) - { - AZ_TracePrintf(AZ::SceneAPI::Utilities::LogWindow, "%s", strToWrite); - dbgFile.Write(strToWrite, strlen(strToWrite)); - dbgFile.Write("\n", strlen("\n")); - - } - - void SceneBuilderWorker::BuildDebugSceneGraph(const char* outputFolder, AZ::SceneAPI::Events::ExportProductList& productList, const AZStd::shared_ptr& scene) const - { - const int debugSceneGraphVersion = 1; - AZStd::string productName, debugSceneFile; - - AzFramework::StringFunc::Path::GetFullFileName(scene->GetSourceFilename().c_str(), productName); - AzFramework::StringFunc::Path::ReplaceExtension(productName, "dbgsg"); - AzFramework::StringFunc::Path::ConstructFull(outputFolder, productName.c_str(), debugSceneFile); - AZ_TracePrintf(AZ::SceneAPI::Utilities::LogWindow, "outputFolder %s, name %s.\n", outputFolder, productName.c_str()); - - AZ::IO::SystemFile dbgFile; - if (dbgFile.Open(debugSceneFile.c_str(), AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY)) - { - WriteAndLog(dbgFile, AZStd::string::format("ProductName: %s", productName.c_str()).c_str()); - WriteAndLog(dbgFile, AZStd::string::format("debugSceneGraphVersion: %d", debugSceneGraphVersion).c_str()); - WriteAndLog(dbgFile, scene->GetName().c_str()); - - const AZ::SceneAPI::Containers::SceneGraph& sceneGraph = scene->GetGraph(); - auto names = sceneGraph.GetNameStorage(); - auto content = sceneGraph.GetContentStorage(); - auto pairView = AZ::SceneAPI::Containers::Views::MakePairView(names, content); - auto view = AZ::SceneAPI::Containers::Views::MakeSceneGraphDownwardsView< - AZ::SceneAPI::Containers::Views::BreadthFirst>( - sceneGraph, sceneGraph.GetRoot(), pairView.cbegin(), true); - - for (auto&& viewIt : view) - { - if (viewIt.second == nullptr) - { - continue; - } - - AZ::SceneAPI::DataTypes::IGraphObject* graphObject = const_cast(viewIt.second.get()); - - WriteAndLog(dbgFile, AZStd::string::format("Node Name: %s", viewIt.first.GetName()).c_str()); - WriteAndLog(dbgFile, AZStd::string::format("Node Path: %s", viewIt.first.GetPath()).c_str()); - WriteAndLog(dbgFile, AZStd::string::format("Node Type: %s", graphObject->RTTI_GetTypeName()).c_str()); - - AZ::SceneAPI::Utilities::DebugOutput debugOutput; - viewIt.second->GetDebugOutput(debugOutput); - - if (!debugOutput.GetOutput().empty()) - { - WriteAndLog(dbgFile, debugOutput.GetOutput().c_str()); - } - } - dbgFile.Close(); - - static const AZ::Data::AssetType dbgSceneGraphAssetType("{07F289D1-4DC7-4C40-94B4-0A53BBCB9F0B}"); - productList.AddProduct(productName, AZ::Uuid::CreateName(productName.c_str()), dbgSceneGraphAssetType, - AZStd::nullopt, AZStd::nullopt); - } - } } // namespace SceneBuilder diff --git a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderWorker.h b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderWorker.h index 895bcf5672..3ecc657a3a 100644 --- a/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderWorker.h +++ b/Gems/SceneProcessing/Code/Source/SceneBuilder/SceneBuilderWorker.h @@ -55,9 +55,6 @@ namespace SceneBuilder void PopulateProductDependencies(const AZ::SceneAPI::Events::ExportProduct& exportProduct, const char* watchFolder, AssetBuilderSDK::JobProduct& jobProduct) const; protected: - - void BuildDebugSceneGraph(const char* outputFolder, AZ::SceneAPI::Events::ExportProductList& productList, const AZStd::shared_ptr& scene) const; - bool LoadScene(AZStd::shared_ptr& result, const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response); diff --git a/Gems/SceneProcessing/Code/Tests/SceneBuilder/SceneBuilderTests.cpp b/Gems/SceneProcessing/Code/Tests/SceneBuilder/SceneBuilderTests.cpp index 4d34725e36..a4da836aeb 100644 --- a/Gems/SceneProcessing/Code/Tests/SceneBuilder/SceneBuilderTests.cpp +++ b/Gems/SceneProcessing/Code/Tests/SceneBuilder/SceneBuilderTests.cpp @@ -109,7 +109,7 @@ protected: TEST_F(SceneBuilderTests, SceneBuilderWorker_ExportProductDependencies_NoDependencies) { - SceneAPI::Events::ExportProduct exportProduct("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), 0, AZStd::nullopt); + SceneAPI::Events::ExportProduct exportProduct("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), u8(0), AZStd::nullopt); TestSuccessCaseNoDependencies(exportProduct); } @@ -122,7 +122,7 @@ TEST_F(SceneBuilderTests, SceneBuilderWorker_ExportProductDependencies_PathDepen #endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS AssetBuilderSDK::ProductPathDependency expectedPathDependency(absolutePathToFile, AssetBuilderSDK::ProductPathDependencyType::SourceFile); - SceneAPI::Events::ExportProduct product("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), 0, AZStd::nullopt); + SceneAPI::Events::ExportProduct product("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), u8(0), AZStd::nullopt); product.m_legacyPathDependencies.push_back(absolutePathToFile); TestSuccessCase(product, &expectedPathDependency); @@ -134,7 +134,7 @@ TEST_F(SceneBuilderTests, SceneBuilderWorker_ExportProductDependencies_PathDepen AssetBuilderSDK::ProductPathDependency expectedPathDependency(relativeDependencyPathToFile, AssetBuilderSDK::ProductPathDependencyType::ProductFile); - SceneAPI::Events::ExportProduct product("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), 0, AZStd::nullopt); + SceneAPI::Events::ExportProduct product("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), u8(0), AZStd::nullopt); product.m_legacyPathDependencies.push_back(relativeDependencyPathToFile); TestSuccessCase(product, &expectedPathDependency); @@ -150,7 +150,7 @@ TEST_F(SceneBuilderTests, SceneBuilderWorker_ExportProductDependencies_PathDepen const char* absolutePathToFile = "/some/test/file.mtl"; #endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - SceneAPI::Events::ExportProduct exportProduct("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), 0, AZStd::nullopt); + SceneAPI::Events::ExportProduct exportProduct("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), u8(0), AZStd::nullopt); exportProduct.m_legacyPathDependencies.push_back(absolutePathToFile); exportProduct.m_legacyPathDependencies.push_back(relativeDependencyPathToFile); @@ -164,8 +164,8 @@ TEST_F(SceneBuilderTests, SceneBuilderWorker_ExportProductDependencies_PathDepen TEST_F(SceneBuilderTests, SceneBuilderWorker_ExportProductDependencies_ProductDependency) { AZ::Uuid dependencyId = AZ::Uuid::CreateRandom(); - SceneAPI::Events::ExportProduct exportProduct("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), 0, AZStd::nullopt); - exportProduct.m_productDependencies.push_back(SceneAPI::Events::ExportProduct("testDependencyFile", dependencyId, AZ::Data::AssetType::CreateNull(), 0, AZStd::nullopt)); + SceneAPI::Events::ExportProduct exportProduct("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), AZ::u8(0), AZStd::nullopt); + exportProduct.m_productDependencies.push_back(SceneAPI::Events::ExportProduct("testDependencyFile", dependencyId, AZ::Data::AssetType::CreateNull(), AZ::u8(0), AZStd::nullopt)); TestSuccessCase(exportProduct, nullptr, &dependencyId); } @@ -173,8 +173,8 @@ TEST_F(SceneBuilderTests, SceneBuilderWorker_ExportProductDependencies_ProductDe TEST_F(SceneBuilderTests, SceneBuilderWorker_ExportProductDependencies_ProductAndPathDependencies) { AZ::Uuid dependencyId = AZ::Uuid::CreateRandom(); - SceneAPI::Events::ExportProduct exportProduct("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), 0, AZStd::nullopt); - exportProduct.m_productDependencies.push_back(SceneAPI::Events::ExportProduct("testDependencyFile", dependencyId, AZ::Data::AssetType::CreateNull(), 0, AZStd::nullopt)); + SceneAPI::Events::ExportProduct exportProduct("testExportFile", AZ::Uuid::CreateRandom(), AZ::Data::AssetType::CreateNull(), AZ::u8(0), AZStd::nullopt); + exportProduct.m_productDependencies.push_back(SceneAPI::Events::ExportProduct("testDependencyFile", dependencyId, AZ::Data::AssetType::CreateNull(), AZ::u8(0), AZStd::nullopt)); const char* relativeDependencyPathToFile = "some/test/file.mtl"; diff --git a/Gems/ScriptCanvas/Code/Editor/Assets/ScriptCanvasMemoryAsset.cpp b/Gems/ScriptCanvas/Code/Editor/Assets/ScriptCanvasMemoryAsset.cpp index 43ef9b3d3a..e7dc2343f2 100644 --- a/Gems/ScriptCanvas/Code/Editor/Assets/ScriptCanvasMemoryAsset.cpp +++ b/Gems/ScriptCanvas/Code/Editor/Assets/ScriptCanvasMemoryAsset.cpp @@ -706,7 +706,7 @@ namespace ScriptCanvasEditor bool savedSuccess; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvasAssetHandler::SaveAssetData"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvasAssetHandler::SaveAssetData"); ScriptCanvasMemoryAsset cloneAsset; m_sourceAsset->CloneTo(cloneAsset); @@ -716,14 +716,14 @@ namespace ScriptCanvasEditor stream.Close(); if (savedSuccess) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "AssetTracker::SaveAssetPostSourceControl : TempToTargetFileReplacement"); + AZ_PROFILE_SCOPE(ScriptCanvas, "AssetTracker::SaveAssetPostSourceControl : TempToTargetFileReplacement"); AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); const bool targetFileExists = fileIO->Exists(m_saveInfo.m_streamName.data()); bool removedTargetFile; { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "AssetTracker::SaveAssetPostSourceControl : TempToTargetFileReplacement : RemoveTarget"); + AZ_PROFILE_SCOPE(ScriptCanvas, "AssetTracker::SaveAssetPostSourceControl : TempToTargetFileReplacement : RemoveTarget"); removedTargetFile = fileIO->Remove(m_saveInfo.m_streamName.data()); } @@ -733,7 +733,7 @@ namespace ScriptCanvasEditor } else { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "AssetTracker::SaveAssetPostSourceControl : TempToTargetFileReplacement : RenameTempFile"); + AZ_PROFILE_SCOPE(ScriptCanvas, "AssetTracker::SaveAssetPostSourceControl : TempToTargetFileReplacement : RenameTempFile"); AZ::IO::Result renameResult = fileIO->Rename(tempPath.data(), m_saveInfo.m_streamName.data()); if (!renameResult) { diff --git a/Gems/ScriptCanvas/Code/Editor/Assets/ScriptCanvasUndoHelper.cpp b/Gems/ScriptCanvas/Code/Editor/Assets/ScriptCanvasUndoHelper.cpp index 24daf5b2b0..388da67987 100644 --- a/Gems/ScriptCanvas/Code/Editor/Assets/ScriptCanvasUndoHelper.cpp +++ b/Gems/ScriptCanvas/Code/Editor/Assets/ScriptCanvasUndoHelper.cpp @@ -103,7 +103,7 @@ namespace ScriptCanvasEditor void UndoHelper::Undo() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::ScriptCanvas); + AZ_PROFILE_FUNCTION(ScriptCanvas); SceneUndoState* sceneUndoState = m_memoryAsset.GetUndoState(); if (sceneUndoState) @@ -123,7 +123,7 @@ namespace ScriptCanvasEditor void UndoHelper::Redo() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::ScriptCanvas); + AZ_PROFILE_FUNCTION(ScriptCanvas); SceneUndoState* sceneUndoState = m_memoryAsset.GetUndoState(); if (sceneUndoState) diff --git a/Gems/ScriptCanvas/Code/Editor/Nodes/NodeCreateUtils.cpp b/Gems/ScriptCanvas/Code/Editor/Nodes/NodeCreateUtils.cpp index 15df6b0261..3bcd940a01 100644 --- a/Gems/ScriptCanvas/Code/Editor/Nodes/NodeCreateUtils.cpp +++ b/Gems/ScriptCanvas/Code/Editor/Nodes/NodeCreateUtils.cpp @@ -99,7 +99,7 @@ namespace ScriptCanvasEditor::Nodes AZStd::pair CreateAndGetNode(const AZ::Uuid& classId, const ScriptCanvas::ScriptCanvasId& scriptCanvasId, const StyleConfiguration& styleConfiguration, AZStd::function onCreateCallback) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); NodeIdPair nodeIdPair; ScriptCanvas::Node* node{}; @@ -134,7 +134,7 @@ namespace ScriptCanvasEditor::Nodes NodeIdPair CreateObjectMethodNode(AZStd::string_view className, AZStd::string_view methodName, const ScriptCanvas::ScriptCanvasId& scriptCanvasId, ScriptCanvas::PropertyStatus propertyStatus) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); NodeIdPair nodeIds; ScriptCanvas::Node* node = nullptr; @@ -161,7 +161,7 @@ namespace ScriptCanvasEditor::Nodes NodeIdPair CreateObjectMethodOverloadNode(AZStd::string_view className, AZStd::string_view methodName, const ScriptCanvas::ScriptCanvasId& scriptCanvasGraphId) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); NodeIdPair nodeIds; ScriptCanvas::Node* node = nullptr; @@ -188,7 +188,7 @@ namespace ScriptCanvasEditor::Nodes NodeIdPair CreateGlobalMethodNode(AZStd::string_view methodName, const ScriptCanvas::ScriptCanvasId& scriptCanvasId) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); NodeIdPair nodeIds; ScriptCanvas::Node* node = nullptr; @@ -215,7 +215,7 @@ namespace ScriptCanvasEditor::Nodes NodeIdPair CreateEbusWrapperNode(AZStd::string_view busName, const ScriptCanvas::ScriptCanvasId& scriptCanvasId) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); NodeIdPair nodeIdPair; ScriptCanvas::Node* node = nullptr; @@ -241,7 +241,7 @@ namespace ScriptCanvasEditor::Nodes { AZ_Assert(assetId.IsValid(), "CreateScriptEventReceiverNode asset Id must be valid"); - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); NodeIdPair nodeIdPair; AZ::Data::Asset asset = AZ::Data::AssetManager::Instance().GetAsset(assetId, AZ::Data::AssetLoadBehavior::Default); @@ -276,7 +276,7 @@ namespace ScriptCanvasEditor::Nodes { AZ_Assert(assetId.IsValid(), "CreateScriptEventSenderNode asset Id must be valid"); - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); NodeIdPair nodeIdPair; AZ::Data::Asset asset = AZ::Data::AssetManager::Instance().GetAsset(assetId, AZ::Data::AssetLoadBehavior::Default); @@ -302,7 +302,7 @@ namespace ScriptCanvasEditor::Nodes NodeIdPair CreateGetVariableNode(const ScriptCanvas::VariableId& variableId, ScriptCanvas::ScriptCanvasId scriptCanvasId) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); const AZ::Uuid k_VariableNodeTypeId = azrtti_typeid(); NodeIdPair nodeIds; @@ -333,7 +333,7 @@ namespace ScriptCanvasEditor::Nodes NodeIdPair CreateSetVariableNode(const ScriptCanvas::VariableId& variableId, ScriptCanvas::ScriptCanvasId scriptCanvasId) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); const AZ::Uuid k_VariableNodeTypeId = azrtti_typeid(); NodeIdPair nodeIds; @@ -366,7 +366,7 @@ namespace ScriptCanvasEditor::Nodes { AZ_Assert(assetId.IsValid(), "CreateFunctionNode source asset Id must be valid"); - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); NodeIdPair nodeIdPair; AZ::Data::Asset asset = AZ::Data::AssetManager::Instance().GetAsset(assetId, AZ::Data::AssetLoadBehavior::PreLoad); @@ -394,7 +394,7 @@ namespace ScriptCanvasEditor::Nodes NodeIdPair CreateAzEventHandlerNode(const AZ::BehaviorMethod& methodWithAzEventReturn, ScriptCanvas::ScriptCanvasId scriptCanvasId, AZ::EntityId connectingMethodNodeId) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); NodeIdPair nodeIdPair; // Make sure the method returns an AZ::Event by reference or pointer diff --git a/Gems/ScriptCanvas/Code/Editor/Nodes/NodeDisplayUtils.cpp b/Gems/ScriptCanvas/Code/Editor/Nodes/NodeDisplayUtils.cpp index c045a1c0da..b9e96938af 100644 --- a/Gems/ScriptCanvas/Code/Editor/Nodes/NodeDisplayUtils.cpp +++ b/Gems/ScriptCanvas/Code/Editor/Nodes/NodeDisplayUtils.cpp @@ -57,7 +57,7 @@ namespace ScriptCanvasEditor::Nodes // Handles the creation of a node through the node configurations for most nodes. AZ::EntityId DisplayGeneralScriptCanvasNode(AZ::EntityId, const ScriptCanvas::Node* node, const NodeConfiguration& nodeConfiguration) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); AZ::Entity* graphCanvasEntity = nullptr; @@ -445,7 +445,7 @@ namespace ScriptCanvasEditor::Nodes AZ::EntityId DisplayEbusEventNode(AZ::EntityId, const AZStd::string& busName, const AZStd::string& eventName, const ScriptCanvas::EBusEventId& eventId) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); AZ::EntityId graphCanvasNodeId; @@ -668,7 +668,7 @@ namespace ScriptCanvasEditor::Nodes AZ::EntityId DisplayScriptEventNode(AZ::EntityId, const AZ::Data::AssetId assetId, const ScriptEvents::Method& methodDefinition) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); AZ::EntityId graphCanvasNodeId; @@ -1001,7 +1001,7 @@ namespace ScriptCanvasEditor::Nodes AZ::EntityId DisplayGetVariableNode(AZ::EntityId graphCanvasGraphId, const ScriptCanvas::Nodes::Core::GetVariableNode* variableNode) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); NodeConfiguration nodeConfiguration; nodeConfiguration.PopulateComponentDescriptors(); @@ -1033,7 +1033,7 @@ namespace ScriptCanvasEditor::Nodes AZ::EntityId DisplaySetVariableNode(AZ::EntityId graphCanvasGraphId, const ScriptCanvas::Nodes::Core::SetVariableNode* variableNode) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); NodeConfiguration nodeConfiguration; nodeConfiguration.PopulateComponentDescriptors(); @@ -1069,7 +1069,7 @@ namespace ScriptCanvasEditor::Nodes /////////////////// AZ::EntityId DisplayScriptCanvasNode(AZ::EntityId graphCanvasGraphId, const ScriptCanvas::Node* node) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); AZ::EntityId graphCanvasNodeId; if (azrtti_istypeof(node)) @@ -1122,7 +1122,7 @@ namespace ScriptCanvasEditor::Nodes static void RegisterAndActivateGraphCanvasSlot(AZ::EntityId graphCanvasNodeId, const ScriptCanvas::SlotId& slotId, AZ::Entity* slotEntity) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); if (slotEntity) { slotEntity->Init(); @@ -1166,7 +1166,7 @@ namespace ScriptCanvasEditor::Nodes return AZ::EntityId(); } - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); AZ::Entity* slotEntity = nullptr; AZ::Uuid typeId = ScriptCanvas::Data::ToAZType(slot.GetDataType()); @@ -1258,7 +1258,7 @@ namespace ScriptCanvasEditor::Nodes::SlotDisplayHelper { AZ::EntityId DisplayPropertySlot(AZ::EntityId graphCanvasNodeId, const ScriptCanvas::VisualExtensionSlotConfiguration& propertyConfiguration) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); GraphCanvas::SlotConfiguration graphCanvasConfiguration; @@ -1284,7 +1284,7 @@ namespace ScriptCanvasEditor::Nodes::SlotDisplayHelper AZ::EntityId DisplayExtendableSlot(AZ::EntityId graphCanvasNodeId, const ScriptCanvas::VisualExtensionSlotConfiguration& extenderConfiguration) { - AZ_PROFILE_TIMER("ScriptCanvas", __FUNCTION__); + AZ_PROFILE_FUNCTION(ScriptCanvas); GraphCanvas::ExtenderSlotConfiguration graphCanvasConfiguration; diff --git a/Gems/ScriptCanvas/Code/Editor/View/Windows/ScriptCanvasContextMenus.cpp b/Gems/ScriptCanvas/Code/Editor/View/Windows/ScriptCanvasContextMenus.cpp index b789c2e675..e4a95d7d19 100644 --- a/Gems/ScriptCanvas/Code/Editor/View/Windows/ScriptCanvasContextMenus.cpp +++ b/Gems/ScriptCanvas/Code/Editor/View/Windows/ScriptCanvasContextMenus.cpp @@ -568,7 +568,7 @@ namespace ScriptCanvasEditor // Show the selection dialog bool createSlot = false; VariablePaletteRequests::SlotSetup selectedSlotSetup; - QPoint scenePoint(scenePos.GetX(), scenePos.GetY()); + QPoint scenePoint(static_cast(scenePos.GetX()), static_cast(scenePos.GetY())); VariablePaletteRequestBus::BroadcastResult(createSlot, &VariablePaletteRequests::ShowSlotTypeSelector, slot, scenePoint, selectedSlotSetup); bool changed = false; diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasGrammar_Header.jinja b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasGrammar_Header.jinja index 00c23b9f35..d743a95ee1 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasGrammar_Header.jinja +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasGrammar_Header.jinja @@ -77,7 +77,7 @@ public: \ {% if Class.attrib['GraphEntryPoint'] is defined %} bool IsEntryPoint() const override { return {%if Class.attrib['GraphEntryPoint'] == "True" %}true{%else%}false{%endif%}; } \ {% endif %} public: \ - friend struct ::{{ className | replace(' ','') }}Property; + friend struct {% if attribute_Namespace is not defined %}::{% endif %}{{ className | replace(' ','') }}Property; // Helpers for easily accessing properties and slots struct {{ className | replace(' ','') }}Property diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasGrammar_Source.jinja b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasGrammar_Source.jinja index 205e6ebd8c..6a381398c1 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasGrammar_Source.jinja +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasGrammar_Source.jinja @@ -26,6 +26,20 @@ SPDX-License-Identifier: Apache-2.0 OR MIT #include "{{ xml.attrib['Include'] }}" {% for Class in xml.iter('Class') %} + +{% set attribute_Namespace = undefined %} +{%- if Class.attrib['Namespace'] is defined %} +{% if Class.attrib['Namespace'] != "None" %} +{% set attribute_Namespace = Class.attrib['Namespace'] %} +{% endif %} +{% endif %} + +{% if attribute_Namespace is defined %} +namespace {{attribute_Namespace}} +{ +{% endif %} + + void {{ Class.attrib['QualifiedName'] }}::ConfigureSlots() { {% if Class.attrib['Base'] is defined %} @@ -269,7 +283,12 @@ void {{ Class.attrib['QualifiedName'] }}::Reflect(AZ::ReflectContext* context) return datumValue ? *datumValue : {{ Property.attrib['Type'] }}(); } - {% endfor %} + +{% if attribute_Namespace is defined %} +} +{% endif %} + + {% endfor %} {% endfor %} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja index 5394ea2355..8bb72bb37f 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja @@ -197,7 +197,8 @@ void {{attribute_QualifiedName}}::Reflect(AZ::ReflectContext* context) {% if item.attrib['Description'] is defined %} {% set description = item.attrib['Description'] %} {% endif %} - // {{ item.attrib['Name'] }} + + // {{ item.attrib['Name'] }} {{preEdit}}->DataElement({{ uihandler }}, &{{ attribute_Name }}::{{ item.attrib['Name'] }}, "{{ item.attrib['Name'] }}", "{{ description }}"){{postEdit}} {% for EditAttribute in item.iter('EditAttribute') %} {{preEdit}}->Attribute({{ EditAttribute.attrib['Key'] }}, {{ EditAttribute.attrib['Value'] }}){{postEdit}} @@ -272,6 +273,9 @@ void Nodes::{{ nodeableNodeName }}::Reflect(AZ::ReflectContext* context) { {% if ExtendReflectionEdit is defined %}auto {{preEdit}} = {%endif%}editContext->Class<{{ nodeableNodeName }}>("{{ attribute_PreferredClassName }}", "{{ attribute_Description }}"){{postEdit}} {{preEdit}}->ClassElement(AZ::Edit::ClassElements::EditorData, ""){{postEdit}} +{% if attribute_Category is defined %} + {{preEdit}}->Attribute(AZ::Edit::Attributes::Category, "{{ attribute_Category }}"){{postEdit}} +{% endif %} {{preEdit}}->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly){{postEdit}} {{preEdit}}->Attribute(AZ::Edit::Attributes::AutoExpand, true){{postEdit}} ; diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/CodeGen/NodeableCodegen.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/CodeGen/NodeableCodegen.h index c09386a5a9..3fdcbc0605 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/CodeGen/NodeableCodegen.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/CodeGen/NodeableCodegen.h @@ -11,345 +11,28 @@ #include #include + +/* + Any class that implements a nodeable AzAutoGen driver (i.e. *.ScriptCanvasNodeable.xml) + requires that the SCRIPTCANVAS_NODE macro be declared within its class declaration. + + Example: + + class CustomNode + : public ScriptCanvas::Nodeable + { + public: + SCRIPTCANVAS_NODE(CustomNode); + }; + + What will happen is that when AzAutoGen runs it will generate a preprocessor directive: + + SCRIPTCANVAS_NODE_CustomNode + + Which will define all of the node's boilerplate code and definitions. When CustomNode + is compiled, the preprocessor will replace the macro with the auto generated + code. +*/ + #define SCRIPTCANVAS_NODE(ClassName) SCRIPTCANVAS_NODE_##ClassName -/* ---------------------------------------------------------------------------------------------------------- -* -* BaseDefinition -* This tag must be included within the body of any custom nodeable class. It generates nodeable code only and it -* should be used as a base class only. -* -* Note: This tag does not generate a node class, so it will be hidden during edit time. -* -* Example: -* BaseDefinition(BaseHelloWorld, "Base Hello World", "My BaseHelloWorld.") -* -* ----------------------------------------------------------------------------------------------------------- */ -#define BaseDefinition(ClassName, Name, Description, ...) AZ_JOIN(AZ_GENERATED_, ClassName) - -/* ---------------------------------------------------------------------------------------------------------- -* -* NodeDefinition -* This tag must be included within the body of any custom nodeable class. It generates the necessary code to support nodes -* and customizes the serialization and reflection parameters(version, converter). -* -* Example: -* NodeDefinition(HelloWorld, "Hello World", "My HelloWorld Node.") -* NodeDefinition(HelloWorld, "Hello World", "My HelloWorld Node.", -* NodeTags::Icon("Icons/ScriptCanvas/HelloWorld.png") -* NodeTags::Version(3, VersionConverter)) -* -* ----------------------------------------------------------------------------------------------------------- */ -#define NodeDefinition(ClassName, Name, Description, ...) AZ_JOIN(AZ_GENERATED_, ClassName) - -/* ---------------------------------------------------------------------------------------------------------- -* InputMethod -* Using InputMethod on a method will create execution in&out slots that is invoked -* automatically. It will also allow the automatic generation of input or output data -* slots according to the method's signature. -* -* Example -* InputMethod("Do Something", "My DoSomething Function.") -* InputMethod("Do Something", "My DoSomething Function.") -* DataInput(int, "DoSomething:Arg", 0, "My DoSomething argument.") -* -* ----------------------------------------------------------------------------------------------------------- */ -#define InputMethod(Name, Description, ...) - -/* ---------------------------------------------------------------------------------------------------------- -* BranchMethod -* Using BranchMethod on a method will create execution input&output slots that is invoked -* automatically. It will also allow the automatic generation of input data -* slots according to the method's signature. BranchMethod should not be used on method -* having return type. -* -* Coupled with macro ExecutionOutput to generate branch out execution slots. -* -* Example -* BranchMethod("Branches", "My Branches Function.") -* ExecutionOutput("Branch1", "My Branch1 Function.", SlotTags::BranchOf("Branches")) -* ExecutionOutput("Branch2", "My Branch2 Function.", SlotTags::BranchOf("Branches")) -* -* ----------------------------------------------------------------------------------------------------------- */ -#define BranchMethod(Name, Description, ...) - -/* ---------------------------------------------------------------------------------------------------------- -* OnInputChangeMethod -* Using OnInputChangeMethod on a method will create one data input slot that is invoked -* automatically, and it should be used only with one input method. -* -* Example -* OnInputChangeMethod("MyInputChangeMethod", "My OnInputChange Function.") -* DataInput(int, "MyInputChangeMethod:Arg", 0, "My MyInputChangeMethod argument.", SlotTags::DisplayGroup("MyInputChangeMethod")) -* -* ----------------------------------------------------------------------------------------------------------- */ -#define OnInputChangeMethod(Name, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* ExecutionInput -* This is a shorthand macro to easily create an execution input slot. -* -* Examples: -* ExecutionInput("Start Process", "Signals this node to begin processing.") -* -* ---------------------------------------------------------------------------------------------------------- */ -#define ExecutionInput(Name, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* ExecutionOutput -* This is a shorthand macro to easily create an execution output slot. -* -* Examples: -* ExecutionOutput("On Start Process", "Output of start process execution."); -* -* ---------------------------------------------------------------------------------------------------------- */ -#define ExecutionOutput(Name, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* ExecutionLatentOutput -* Similar to ExecutionOutput however it is used to make it explicit that the output slot will be latent, -* this means that the node maintains state and may not signal this slot immediately. -* -* Example: -* ExecutionLatentOutput("On Finished", "Will be signaled when the operation is complete."); -* -* ---------------------------------------------------------------------------------------------------------- */ -#define ExecutionLatentOutput(Name, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* Data -* Provides shorthand for exposing data to serialize context and edit context, -* mainly used with SlotTags::PropertyReference for property data. -* -* Example: -* int m_data = 1; -* PropertyData(int, "My Data", "My Serialized Data.", SlotTags::PropertyReference(m_data)); -* -* ---------------------------------------------------------------------------------------------------------- */ -#define PropertyData(Type, Name, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* DataInput -* Provides shorthand for creating an input data slot. -* -* Coupled with macro InputMethod/BranchMethod/OnInputChangeMethod to give parameter editor definition -* -* Example: -* InputMethod("Do Something", "My DoSomething Function.") -* DataInput(int, "DoSomething:Arg", 0, "My DoSomething argument.") -* -* ---------------------------------------------------------------------------------------------------------- */ -#define DataInput(Type, Name, DefaultVal, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* DataOutput -* Provides shorthand for creating an output data slot. -* -* Coupled with macro InputMethod/BranchMethod/OnInputChangeMethod to give result editor definition -* -* Example: -* InputMethod("Do Something", "My DoSomething Function.") -* DataOutput(int, "DoSomething:Result", 0, "My DoSomething result.") -* -* ---------------------------------------------------------------------------------------------------------- */ -#define DataOutput(Type, Name, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* DynamicValueDataInput -* Provides shorthand for creating an input dynamic value data slot. -* -* Examples: -* DynamicValueDataInput("ValueData", "A generic value data.") -* -* ---------------------------------------------------------------------------------------------------------- */ -#define DynamicValueDataInput(Name, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* DynamicValueDataOutput -* Provides shorthand for creating an output dynamic value data slot. -* -* Examples: -* DynamicValueDataOutput("ValueData", "A generic value data.") -* -* ---------------------------------------------------------------------------------------------------------- */ -#define DynamicValueDataOutput(Name, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* DynamicContainerDataInput -* Provides shorthand for creating an input dynamic container data slot. -* -* Coupled with macro ExecutionInput/ExecutionOutput/ExecutionLatentOutput to generate dynamic data input slot -* -* Examples: -* DynamicContainerDataInput("ContainerData", "A generic container data.") -* -* ---------------------------------------------------------------------------------------------------------- */ -#define DynamicContainerDataInput(Name, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* DynamicContainerDataOutput -* Provides shorthand for creating an output dynamic container data slot. -* -* Coupled with macro ExecutionInput/ExecutionOutput/ExecutionLatentOutput to generate dynamic data output slot -* -* Examples: -* DynamicContainerDataOutput("ContainerData", "A generic container data.") -* -* ---------------------------------------------------------------------------------------------------------- */ -#define DynamicContainerDataOutput(Name, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* DynamicAnyDataInput -* Provides shorthand for creating an input dynamic any data slot. -* -* Coupled with macro ExecutionInput/ExecutionOutput/ExecutionLatentOutput to generate dynamic data input slot -* -* Examples: -* DynamicAnyDataInput("AnyData", "A generic any data.") -* -* ---------------------------------------------------------------------------------------------------------- */ -#define DynamicAnyDataInput(Name, Description, ...) - -/* -*---------------------------------------------------------------------------------------------------------- -* -* DynamicAnyDataOutput -* Provides shorthand for creating an output dynamic any data slot. -* -* Coupled with macro ExecutionInput/ExecutionOutput/ExecutionLatentOutput to generate dynamic data output slot -* -* Examples: -* DynamicAnyDataOutput("AnyData", "A generic any data.") -* -* ---------------------------------------------------------------------------------------------------------- */ -#define DynamicAnyDataOutput(Name, Description, ...) - -// Intellisense helpers, the following definitions exist to provide code completion details regarding what attributes are -// supported by the different tags. - -// Revisited common tags, we should be able to remove NodeableCodegen eventually -namespace NodeableCodegen -{ - namespace ScriptCanvasTags - { - using OverrideName = const char*; - using Uuid = const char*; - using Category = const char*; - using Icon = const char*; - using Deprecated = const char*; - - struct Version - { - using ConverterFunction = bool(class AZ::SerializeContext& context, class AZ::SerializeContext::DataElementNode& classElement); - Version(unsigned int /*version*/) {} - Version(unsigned int /*version*/, ConverterFunction /*converter*/) {} - }; - - template - struct EventHandler - { - EventHandler() = default; - }; - - namespace Edit - { - struct UIHandler - { - UIHandler([[maybe_unused]] const AZ::Crc32& uiHandler = AZ::Edit::UIHandlers::Default) {} - }; - } - - struct EditAttributes - { - template - EditAttributes(Args&& ... args) {} - }; - - struct BaseClass - { - BaseClass(AZStd::initializer_list) {} - }; - - //struct Contracts - //{ - // explicit Contracts(AZStd::initializer_list) {} - //}; - - //struct RestrictedTypeContractTag - //{ - // explicit RestrictedTypeContractTag(AZStd::initializer_list) {} - //}; - - struct SupportsMethodContractTag - { - explicit SupportsMethodContractTag(const char*) {} - }; - } -} - -namespace NodeTags -{ - using NodeableCodegen::ScriptCanvasTags::OverrideName; - using NodeableCodegen::ScriptCanvasTags::Uuid; - using NodeableCodegen::ScriptCanvasTags::Version; - using NodeableCodegen::ScriptCanvasTags::Icon; - using NodeableCodegen::ScriptCanvasTags::EditAttributes; - using NodeableCodegen::ScriptCanvasTags::Category; - using NodeableCodegen::ScriptCanvasTags::Deprecated; - - using GraphEntryPoint = bool; -} - -namespace SlotTags -{ - using NodeableCodegen::ScriptCanvasTags::OverrideName; - //using NodeableCodegen::ScriptCanvasTags::Contracts; - - // Data specific - using DisplayGroup = const char*; - - // PropertyData specific - using PropertyReference = const char*; - using PropertyInterface = const char*; - - // ExecutionSlot specific - using BranchOf = const char*; - - // EditContext specific - using NodeableCodegen::ScriptCanvasTags::EditAttributes; - using NodeableCodegen::ScriptCanvasTags::Edit::UIHandler; - using AzCommon::Attributes::ChangeNotify; - using AzCommon::Attributes::Visibility; - using AzCommon::Attributes::AutoExpand; - using AzCommon::Attributes::DescriptionTextOverride; - using AzCommon::Attributes::NameLabelOverride; - using AzCommon::Attributes::Min; - using AzCommon::Attributes::Max; - - // DynamicData specific - //using NodeableCodegen::ScriptCanvasTags::RestrictedTypeContractTag; - using NodeableCodegen::ScriptCanvasTags::SupportsMethodContractTag; - using DynamicGroup = const char*; -} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp index e4569af820..4dae63d71b 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Datum.cpp @@ -2219,7 +2219,7 @@ namespace ScriptCanvas const_cast(this)->InitializeOverloadedStorage(Data::FromAZType(description.m_typeId), eOriginality::Copy); - if (!Data::IsValueType(m_type) && !SatisfiesTraits(description.m_traits)) + if (!Data::IsValueType(m_type) && !SatisfiesTraits(static_cast(description.m_traits))) { return AZ::Failure(AZStd::string("Attempting to convert null value to BehaviorValueParameter that expects reference or value")); } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/EBusHandler.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/EBusHandler.cpp index d878415341..bd19482dd8 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/EBusHandler.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/EBusHandler.cpp @@ -115,7 +115,7 @@ namespace ScriptCanvas void EBusHandler::OnEventGenericHook(void* userData, const char* eventName, int eventIndex, AZ::BehaviorValueParameter* result, int numParameters, AZ::BehaviorValueParameter* parameters) { AZ_UNUSED(eventName); - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::ScriptCanvas, "EBusEventHandler::OnEvent %s", eventName); + AZ_PROFILE_SCOPE(ScriptCanvas, "EBusEventHandler::OnEvent %s", eventName); auto handler = reinterpret_cast(userData); SCRIPT_CANVAS_PERFORMANCE_SCOPE_LATENT(handler->GetScriptCanvasId(), handler->GetAssetId()); handler->OnEvent(nullptr, eventIndex, result, numParameters, parameters); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.cpp index 6e87e52f87..28f0519552 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.cpp @@ -1022,7 +1022,7 @@ namespace ScriptCanvas void Node::SetToDefaultValueOfType(const SlotId& slotId) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::SetToDefaultValueOfType"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::SetToDefaultValueOfType"); Slot* slot = GetSlot(slotId); @@ -1616,7 +1616,7 @@ namespace ScriptCanvas Data::Type Node::GetSlotDataType(const SlotId& slotId) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::GetSlotDataType"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::GetSlotDataType"); const auto* slot = GetSlot(slotId); @@ -1631,7 +1631,7 @@ namespace ScriptCanvas VariableId Node::GetSlotVariableId(const SlotId& slotId) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::GetSlotVariableId"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::GetSlotVariableId"); Slot* slot = GetSlot(slotId); @@ -1645,7 +1645,7 @@ namespace ScriptCanvas void Node::SetSlotVariableId(const SlotId& slotId, const VariableId& variableId) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::SetSlotVariableId"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::SetSlotVariableId"); Slot* slot = GetSlot(slotId); @@ -1664,7 +1664,7 @@ namespace ScriptCanvas void Node::ClearSlotVariableId(const SlotId& slotId) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::ResetSlotVariableId"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::ResetSlotVariableId"); SetSlotVariableId(slotId, VariableId()); } @@ -1861,7 +1861,7 @@ namespace ScriptCanvas AZStd::vector Node::GetAllSlotsByDescriptor(const SlotDescriptor& slotDescriptor, bool allowLatentSlots) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::GetSlotsByType"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::GetSlotsByType"); AZStd::vector slots; @@ -1879,7 +1879,7 @@ namespace ScriptCanvas AZStd::vector Node::GetAllEndpointsByDescriptor(const SlotDescriptor& slotDescriptor, bool allowLatentSlots) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::GetEndpointsByType"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::GetEndpointsByType"); AZStd::vector endpoints; @@ -1898,7 +1898,7 @@ namespace ScriptCanvas AZStd::vector Node::GetSlotIds(AZStd::string_view slotName) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::GetSlotIds"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::GetSlotIds"); auto nameSlotRange = m_slotNameMap.equal_range(slotName); AZStd::vector result; @@ -1911,7 +1911,7 @@ namespace ScriptCanvas Slot* Node::GetSlot(const SlotId& slotId) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::GetSlot"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::GetSlot"); if (slotId.IsValid()) { @@ -1981,7 +1981,7 @@ namespace ScriptCanvas if (slotIter == m_slots.end()) { - retVal = -1; + retVal = std::numeric_limits::max(); } return retVal; @@ -1994,7 +1994,7 @@ namespace ScriptCanvas AZStd::vector Node::GetAllSlots() const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::GetAllSlots"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::GetAllSlots"); const SlotList& slots = GetSlots(); @@ -2011,7 +2011,7 @@ namespace ScriptCanvas AZStd::vector Node::ModAllSlots() { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::ModAllSlots"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::ModAllSlots"); SlotList& slots = GetSlots(); @@ -2408,7 +2408,7 @@ namespace ScriptCanvas NodePtrConstList Node::FindConnectedNodesByDescriptor(const SlotDescriptor& slotDescriptor, bool followLatentConnections) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::GetConnectedNodesByType"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::GetConnectedNodesByType"); NodePtrConstList connectedNodes; @@ -2427,7 +2427,7 @@ namespace ScriptCanvas AZStd::vector> Node::FindConnectedNodesAndSlotsByDescriptor(const SlotDescriptor& slotDescriptor, bool followLatentConnections) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::GetConnectedNodesAndSlotsByType"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::GetConnectedNodesAndSlotsByType"); AZStd::vector> connectedNodes; @@ -2593,7 +2593,7 @@ namespace ScriptCanvas void Node::OnDatumEdited(const Datum* datum) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::OnDatumChanged"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::OnDatumChanged"); SlotId slotId; @@ -2788,7 +2788,7 @@ namespace ScriptCanvas SlotId Node::FindSlotIdForDescriptor(AZStd::string_view slotName, const SlotDescriptor& descriptor) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::FindSlotIdForDescriptor"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::FindSlotIdForDescriptor"); auto slotNameRange = m_slotNameMap.equal_range(slotName); auto nameSlotIt = AZStd::find_if(slotNameRange.first, slotNameRange.second, [descriptor](const AZStd::pair& nameSlotPair) @@ -2801,7 +2801,7 @@ namespace ScriptCanvas int Node::FindSlotIndex(const SlotId& slotId) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::FindSlotIndex"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::FindSlotIndex"); auto slotIdIter = m_slotIdIteratorCache.find(slotId); @@ -2816,7 +2816,7 @@ namespace ScriptCanvas bool Node::IsConnected(const Slot& slot) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::IsConnected"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::IsConnected"); return slot.IsVariableReference() || m_graphRequestBus->IsEndpointConnected(slot.GetEndpoint()); } @@ -2862,7 +2862,7 @@ namespace ScriptCanvas EndpointsResolved Node::GetConnectedNodes(const Slot& slot) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::GetConnectedNodes"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::GetConnectedNodes"); EndpointsResolved connectedNodes; @@ -2906,7 +2906,7 @@ namespace ScriptCanvas AZStd::vector> Node::ModConnectedNodes(const Slot& slot) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::ModConnectedNodes"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::ModConnectedNodes"); AZStd::vector> connectedNodes; ModConnectedNodes(slot, connectedNodes); return connectedNodes; @@ -3481,7 +3481,7 @@ namespace ScriptCanvas AZStd::vector Node::GetSlotsByType(CombinedSlotType slotType) const { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::Node::GetSlotsByType"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::Node::GetSlotsByType"); AZStd::vector slots; diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeFunctionGeneric.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeFunctionGeneric.h index 9cf5d04167..90acd4fdc9 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeFunctionGeneric.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeFunctionGeneric.h @@ -21,9 +21,6 @@ #include "Node.h" #include "Attributes.h" -#pragma warning( push ) -#pragma warning( disable : 5046) // 'function' : Symbol involving type with internal linkage not defined - /** * NodeFunctionGeneric.h * @@ -107,7 +104,9 @@ namespace ScriptCanvas private:\ static AZStd::string_view GetName(size_t i)\ {\ + AZ_PUSH_DISABLE_WARNING(4296, "-Wunknown-warning-option")\ static_assert(s_numArgs <= s_numNames, "Number of arguments is greater than number of names in " #NODE_NAME );\ + AZ_POP_DISABLE_WARNING\ /*static_assert(s_numResults <= s_numNames, "Number of results is greater than number of names in " #NODE_NAME );*/\ /*static_assert((s_numResults + s_numArgs) == s_numNames, "Argument name count + result name count != name count in " #NODE_NAME );*/\ static const AZStd::array s_names = {{ __VA_ARGS__ }};\ @@ -184,9 +183,12 @@ namespace ScriptCanvas : public Node { public: + AZ_PUSH_DISABLE_WARNING(5046, "-Wunknown-warning-option") // 'function' : Symbol involving type with internal linkage not defined AZ_RTTI(((NodeFunctionGenericMultiReturn), "{DC5B1799-6C5B-4190-8D90-EF0C2D1BCE4E}", t_Func, t_Traits), Node); AZ_COMPONENT_INTRUSIVE_DESCRIPTOR_TYPE(NodeFunctionGenericMultiReturn); AZ_COMPONENT_BASE(NodeFunctionGenericMultiReturn, Node); + AZ_POP_DISABLE_WARNING + static const char* GetNodeFunctionName() { @@ -372,5 +374,3 @@ namespace ScriptCanvas } } - -#pragma warning( pop ) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeableNodeOverloaded.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeableNodeOverloaded.cpp index 92039d3394..58af3a75de 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeableNodeOverloaded.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeableNodeOverloaded.cpp @@ -575,7 +575,7 @@ namespace ScriptCanvas const SlotExecution::Map* slotExecutionMap = GetSlotExecutionMap(); const auto& executionIns = slotExecutionMap->GetIns(); - if (methodIndex < 0 || methodIndex >= executionIns.size()) + if (methodIndex >= executionIns.size()) { return; } @@ -655,7 +655,7 @@ namespace ScriptCanvas AZ::Outcome NodeableNodeOverloaded::IsValidConfiguration(size_t methodIndex, const DataIndexMapping& inputMapping, const DataIndexMapping& outputMapping) { - if (methodIndex < 0 || methodIndex >= m_methodConfigurations.size()) + if (methodIndex >= m_methodConfigurations.size()) { return AZ::Failure(AZStd::string("Trying to access unknown method index.")); } @@ -716,7 +716,7 @@ namespace ScriptCanvas const SlotExecution::Map* slotExecutionMap = GetSlotExecutionMap(); const auto& executionIns = slotExecutionMap->GetIns(); - if (methodIndex < 0 || methodIndex >= executionIns.size()) + if (methodIndex >= executionIns.size()) { return AZ::Failure(AZStd::string("Invalid method index given to Nodeable"));; } @@ -785,7 +785,7 @@ namespace ScriptCanvas return AZ::Success(); } - if (methodIndex < 0 || methodIndex >= m_methodConfigurations.size()) + if (methodIndex >= m_methodConfigurations.size()) { return AZ::Failure(AZStd::string("Invalid Method index given to Nodeable Node Overloaded.")); } @@ -826,7 +826,7 @@ namespace ScriptCanvas { static const DataTypeSet k_emptySet; - if (methodIndex >= 0 && methodIndex < m_methodSelections.size()) + if (methodIndex < m_methodSelections.size()) { const OverloadConfiguration& overloadConfiguration = m_methodConfigurations[methodIndex]; size_t startIndex = NodeableNodeOverloadedCpp::AdjustForHiddenNodeableThisPointer(overloadConfiguration, 0); @@ -845,7 +845,7 @@ namespace ScriptCanvas return AZ::Success(); } - if (methodIndex < 0 || methodIndex >= m_methodConfigurations.size()) + if (methodIndex >= m_methodConfigurations.size()) { return AZ::Failure(AZStd::string("Invalid Method index given to Nodeable Node Overloaded.")); } @@ -883,7 +883,7 @@ namespace ScriptCanvas { static const DataTypeSet k_emptySet; - if (methodIndex >= 0 && methodIndex < m_methodSelections.size()) + if (methodIndex < m_methodSelections.size()) { return m_methodSelections[methodIndex].FindPossibleInputTypes(index); } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/SubgraphInterface.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/SubgraphInterface.cpp index 9d1626fb73..5a88036a0f 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/SubgraphInterface.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/SubgraphInterface.cpp @@ -37,7 +37,7 @@ namespace SubgraphInterfaceCpp AZ_INLINE const char* GetTabs(size_t tabs) { - AZ_Assert(tabs >= 0 && tabs <= k_maxTabs, "invalid argument to GetTabs"); + AZ_Assert(tabs <= k_maxTabs, "invalid argument to GetTabs"); static const char* const k_tabs[] = { diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/Interpreted/ExecutionInterpretedEBusAPI.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/Interpreted/ExecutionInterpretedEBusAPI.cpp index 64553ed5e0..d33f78c8b4 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/Interpreted/ExecutionInterpretedEBusAPI.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/Interpreted/ExecutionInterpretedEBusAPI.cpp @@ -116,7 +116,7 @@ namespace ScriptCanvas auto nodeable = AZ::ScriptValue::StackRead(lua, k_nodeableIndex); AZ_Assert(nodeable, "Failed to read EBusHandler"); - const int eventIndex = lua_tointeger(lua, k_eventNameIndex); + const int eventIndex = static_cast(lua_tointeger(lua, k_eventNameIndex)); AZ_Assert(eventIndex != -1, "Event index was not found for %s", nodeable->GetEBusName().data()); // install the generic hook for the event nodeable->HandleEvent(eventIndex); @@ -143,7 +143,7 @@ namespace ScriptCanvas auto nodeable = AZ::ScriptValue::StackRead(lua, k_nodeableIndex); AZ_Assert(nodeable, "Failed to read EBusHandler"); - const int eventIndex = lua_tointeger(lua, k_eventNameIndex); + const int eventIndex = static_cast(lua_tointeger(lua, k_eventNameIndex)); AZ_Assert(eventIndex != -1, "Event index was not found for %s", nodeable->GetEBusName().data()); // install the generic hook for the event nodeable->HandleEvent(eventIndex); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp index ac19028fd5..89c69ee4c5 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp @@ -61,7 +61,7 @@ namespace ScriptCanvas void RuntimeComponent::Execute() { - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::ScriptCanvas, "RuntimeComponent::Execute (%s)", m_runtimeOverrides.m_runtimeAsset.GetId().ToString().c_str()); + AZ_PROFILE_SCOPE(ScriptCanvas, "RuntimeComponent::Execute (%s)", m_runtimeOverrides.m_runtimeAsset.GetId().ToString().c_str()); AZ_Assert(m_executionState, "RuntimeComponent::Execute called without an execution state"); SC_EXECUTION_TRACE_GRAPH_ACTIVATED(CreateActivationInfo()); SCRIPT_CANVAS_PERFORMANCE_SCOPE_EXECUTION(m_executionState->GetScriptCanvasId(), m_runtimeOverrides.m_runtimeAsset.GetId()); @@ -117,7 +117,7 @@ namespace ScriptCanvas AZ_Assert(m_runtimeAsset.Get(), "RuntimeComponent::m_runtimeAsset AssetId: %s was valid, but the data was not pre-loaded, so this script will not run", m_runtimeOverrides.m_runtimeAsset.GetId().ToString().data()); #endif - AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::ScriptCanvas, "RuntimeComponent::InitializeExecution (%s)", m_runtimeOverrides.m_runtimeAsset.GetId().ToString().c_str()); + AZ_PROFILE_SCOPE(ScriptCanvas, "RuntimeComponent::InitializeExecution (%s)", m_runtimeOverrides.m_runtimeAsset.GetId().ToString().c_str()); SCRIPT_CANVAS_PERFORMANCE_SCOPE_INITIALIZATION(m_scriptCanvasId, m_runtimeOverrides.m_runtimeAsset.GetId()); m_executionState = ExecutionState::Create(ExecutionStateConfig(m_runtimeOverrides.m_runtimeAsset, *this)); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodeables/BaseTimer.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodeables/BaseTimer.cpp index 8c8eac5e1b..d6454ef4a4 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodeables/BaseTimer.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodeables/BaseTimer.cpp @@ -46,7 +46,7 @@ namespace ScriptCanvas void BaseTimer::OnTick(float delta, AZ::ScriptTimePoint) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::ScriptCanvas); + AZ_PROFILE_FUNCTION(ScriptCanvas); SCRIPT_CANVAS_PERFORMANCE_SCOPE_LATENT(GetScriptCanvasId(), GetAssetId()); switch (m_timeUnits) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodes/StringFormatted.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodes/StringFormatted.cpp index b2741f4498..552e04a850 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodes/StringFormatted.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Internal/Nodes/StringFormatted.cpp @@ -191,7 +191,7 @@ namespace ScriptCanvas AZStd::string StringFormatted::ProcessFormat() { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::ScriptCanvas, "ScriptCanvas::StringFormatted::ProcessFormat"); + AZ_PROFILE_SCOPE(ScriptCanvas, "ScriptCanvas::StringFormatted::ProcessFormat"); AZStd::string text; diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/AABBNodes.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/AABBNodes.h index ec44953ba9..198ff0c421 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/AABBNodes.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/AABBNodes.h @@ -92,7 +92,7 @@ namespace ScriptCanvas AZ_INLINE AABBType FromCenterRadius(const Vector3Type center, const NumberType radius) { - return AABBType::CreateCenterRadius(center, radius); + return AABBType::CreateCenterRadius(center, static_cast(radius)); } SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(FromCenterRadius, k_categoryName, "{5FEFD1BF-DC5B-4AFA-892F-082D92492548}", "returns the AABB with Min = Center - Vector3(radius, radius, radius), Max = Center + Vector3(radius, radius, radius)", "Center", "Radius"); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Math.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Math.cpp index 67c79aaa05..62ca21f1b6 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Math.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Math.cpp @@ -10,8 +10,6 @@ #include -#pragma warning (disable:4503) // decorated name length exceeded, name was truncated - namespace ScriptCanvas { namespace Nodes diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h index f2088dbf6d..8af9ee8ca2 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/TransformNodes.h @@ -55,7 +55,7 @@ namespace ScriptCanvas AZ_INLINE TransformType FromScale(NumberType scale) { - return TransformType::CreateUniformScale(scale); + return TransformType::CreateUniformScale(static_cast(scale)); } SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(FromScale, k_categoryName, "{4B6454BC-015C-41BB-9C78-34ADBCF70187}", "returns a transform which applies the specified uniform Scale, but no rotation or translation", "Scale"); @@ -143,7 +143,7 @@ namespace ScriptCanvas AZ_INLINE TransformType MultiplyByUniformScale(TransformType source, NumberType scale) { - source.MultiplyByUniformScale(scale); + source.MultiplyByUniformScale(static_cast(scale)); return source; } SCRIPT_CANVAS_GENERIC_FUNCTION_NODE(MultiplyByUniformScale, k_categoryName, "{90472D62-65A8-40C1-AB08-FA66D793F689}", "returns Source multiplied uniformly by Scale", "Source", "Scale"); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector2Nodes.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector2Nodes.h index 670c9f31a1..c815470540 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector2Nodes.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector2Nodes.h @@ -254,7 +254,7 @@ namespace ScriptCanvas { Vector2Type r = to - from; float length = r.NormalizeWithLength(); - r.SetLength(optionalScale); + r.SetLength(static_cast(optionalScale)); return std::make_tuple(r, length); } SCRIPT_CANVAS_GENERIC_FUNCTION_NODE_WITH_DEFAULTS(DirectionTo, DirectionToDefaults, k_categoryName, "{49A2D7F6-6CD3-420E-8A79-D46B00DB6CED}", "Returns a direction vector between two points and the distance between them, by default the direction will be normalized, but it may be optionally scaled using the Scale parameter if different from 1.0", "From", "To", "Scale"); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector3Nodes.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector3Nodes.h index 492bc83e33..3e70d1fed7 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector3Nodes.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector3Nodes.h @@ -340,7 +340,7 @@ namespace ScriptCanvas { Vector3Type r = to - from; float length = r.NormalizeWithLength(); - r.SetLength(optionalScale); + r.SetLength(static_cast(optionalScale)); return std::make_tuple(r, length); } SCRIPT_CANVAS_GENERIC_FUNCTION_NODE_WITH_DEFAULTS(DirectionTo, DirectionToDefaults, k_categoryName, "{28FBD529-4C9A-4E34-B8A0-A13B5DB3C331}", "Returns a direction vector between two points and the distance between them, by default the direction will be normalized, but it may be optionally scaled using the Scale parameter if different from 1.0", "From", "To", "Scale"); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector4Nodes.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector4Nodes.h index 14256fc969..d7bee1f940 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector4Nodes.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector4Nodes.h @@ -225,7 +225,7 @@ namespace ScriptCanvas { Vector4Type r = to - from; float length = r.NormalizeWithLength(); - r.SetLength(optionalScale); + r.SetLength(static_cast(optionalScale)); return std::make_tuple(r, length); } SCRIPT_CANVAS_GENERIC_FUNCTION_NODE_WITH_DEFAULTS(DirectionTo, DirectionToDefaults, k_categoryName, "{463762DE-E541-4AFE-80C2-FED1C5273319}", "Returns a direction vector between two points and the distance between them, by default the direction will be normalized, but it may be optionally scaled using the Scale parameter if different from 1.0", "From", "To", "Scale"); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Operators/Math/OperatorMul.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Operators/Math/OperatorMul.cpp index abbb4d8b6c..06ccb617ff 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Operators/Math/OperatorMul.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Operators/Math/OperatorMul.cpp @@ -58,7 +58,7 @@ namespace ScriptCanvas void OperatorMul::Operator(Data::eType type, const ArithmeticOperands& operands, Datum& result) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::ScriptCanvas); + AZ_PROFILE_FUNCTION(ScriptCanvas); switch (type) { diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp index 4c92c9408a..d11e916d42 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Spawning/SpawnNodeable.cpp @@ -114,7 +114,7 @@ namespace ScriptCanvas::Nodeables::Spawning AZ::Vector3 rotationCopy = rotation; AZ::Quaternion rotationQuat = AZ::Quaternion::CreateFromEulerAnglesDegrees(rotationCopy); - entityTransform->SetWorldTM(AZ::Transform(translation, rotationQuat, scale)); + entityTransform->SetWorldTM(AZ::Transform(translation, rotationQuat, static_cast(scale))); } }; diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/String/StringGenerics.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/String/StringGenerics.h index b3a4faae30..d5ee52cdb1 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/String/StringGenerics.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/String/StringGenerics.h @@ -34,7 +34,7 @@ namespace ScriptCanvas { length = AZ::GetClamp(length, 0, aznumeric_cast(sourceString.size())); - if (length == 0 || index < 0 || index >= sourceString.size()) + if (length == 0 || index >= sourceString.size()) { return {}; } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/DelayNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/DelayNodeable.cpp index 168b6d825a..27a1a95f37 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/DelayNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/DelayNodeable.cpp @@ -49,7 +49,7 @@ namespace ScriptCanvas void DelayNodeable::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::ScriptCanvas); + AZ_PROFILE_FUNCTION(ScriptCanvas); SCRIPT_CANVAS_PERFORMANCE_SCOPE_LATENT(GetScriptCanvasId(), GetAssetId()); m_currentTime -= static_cast(deltaTime); if (m_currentTime <= 0.f) @@ -82,12 +82,12 @@ namespace ScriptCanvas void DelayNodeable::Reset(Data::NumberType countdownSeconds, Data::BooleanType looping, Data::NumberType holdTime) { - InitiateCountdown(true, countdownSeconds, looping, holdTime); + InitiateCountdown(true, static_cast(countdownSeconds), looping, static_cast(holdTime)); } void DelayNodeable::Start(Data::NumberType countdownSeconds, Data::BooleanType looping, Data::NumberType holdTime) { - InitiateCountdown(false, countdownSeconds, looping, holdTime); + InitiateCountdown(false, static_cast(countdownSeconds), looping, static_cast(holdTime)); } } } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/DurationNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/DurationNodeable.cpp index 942271ad3a..874e25eb3d 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/DurationNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/DurationNodeable.cpp @@ -28,7 +28,7 @@ namespace ScriptCanvas void DurationNodeable::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::ScriptCanvas); + AZ_PROFILE_FUNCTION(ScriptCanvas); SCRIPT_CANVAS_PERFORMANCE_SCOPE_LATENT(GetScriptCanvasId(), GetAssetId()); if (m_elapsedTime <= m_duration) @@ -47,7 +47,7 @@ namespace ScriptCanvas void DurationNodeable::Start(Data::NumberType duration) { m_elapsedTime = 0.0f; - m_duration = duration; + m_duration = static_cast(duration); AZ::TickBus::Handler::BusConnect(); } } diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/TimerNodeable.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/TimerNodeable.cpp index db50f66f35..37d4d026c1 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/TimerNodeable.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Time/TimerNodeable.cpp @@ -16,7 +16,7 @@ namespace ScriptCanvas { void TimerNodeable::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint time) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::ScriptCanvas); + AZ_PROFILE_FUNCTION(ScriptCanvas); SCRIPT_CANVAS_PERFORMANCE_SCOPE_LATENT(GetScriptCanvasId(), GetAssetId()); double milliseconds = time.GetMilliseconds() - m_start.GetMilliseconds(); double seconds = time.GetSeconds() - m_start.GetSeconds(); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Translation/TranslationUtilities.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Translation/TranslationUtilities.cpp index 7c03102a71..a9ca526373 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Translation/TranslationUtilities.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Translation/TranslationUtilities.cpp @@ -30,7 +30,7 @@ namespace TranslationUtilitiesCPP AZ_INLINE const char* GetTabs(size_t tabs) { - AZ_Assert(tabs >= 0 && tabs <= k_maxTabs, "invalid argument to GetTabs"); + AZ_Assert(tabs <= k_maxTabs, "invalid argument to GetTabs"); static const char* const k_tabs[] = { diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Utils/NodeUtils.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Utils/NodeUtils.cpp index d54e9457c1..5aa922d627 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Utils/NodeUtils.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Utils/NodeUtils.cpp @@ -77,8 +77,6 @@ namespace ScriptCanvas { return ConstructCustomNodeIdentifier(scriptCanvasNode->RTTI_GetType()); } - - return NodeTypeIdentifier(0); } NodeTypeIdentifier NodeUtils::ConstructEBusIdentifier(ScriptCanvas::EBusBusId ebusIdentifier) diff --git a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/EditorKeyActions.cpp b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/EditorKeyActions.cpp index a20e674063..4114292938 100644 --- a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/EditorKeyActions.cpp +++ b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/EditorKeyActions.cpp @@ -30,7 +30,7 @@ namespace ScriptCanvasDeveloper #if defined(AZ_COMPILER_MSVC) INPUT osInput = { 0 }; osInput.type = INPUT_KEYBOARD; - osInput.ki.wVk = m_keyValue; + osInput.ki.wVk = static_cast(m_keyValue); switch (m_keyAction) { diff --git a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/EditorMouseActions.cpp b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/EditorMouseActions.cpp index a5ed19a8d7..cf757af1ec 100644 --- a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/EditorMouseActions.cpp +++ b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/EditorMouseActions.cpp @@ -174,8 +174,8 @@ namespace ScriptCanvasDeveloper osInput.type = INPUT_MOUSE; osInput.mi.mouseData = 0; osInput.mi.time = 0; - osInput.mi.dx = targetPoint.x() - currentPosition.x(); - osInput.mi.dy = targetPoint.y() - currentPosition.y(); + osInput.mi.dx = static_cast(targetPoint.x() - currentPosition.x()); + osInput.mi.dy = static_cast(targetPoint.y() - currentPosition.y()); osInput.mi.dwFlags = MOUSEEVENTF_MOVE; ::SendInput(1, &osInput, sizeof(osInput)); diff --git a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/ScriptCanvasActions/CreateElementsActions.cpp b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/ScriptCanvasActions/CreateElementsActions.cpp index 71b157e0a9..0fa3765ac3 100644 --- a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/ScriptCanvasActions/CreateElementsActions.cpp +++ b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/ScriptCanvasActions/CreateElementsActions.cpp @@ -539,8 +539,8 @@ namespace ScriptCanvasDeveloper AZ::Vector2 stepDirection = AZ::Vector2::CreateZero(); - stepDirection.SetX(jutDirection.x() * stepSize.GetX()); - stepDirection.SetY(jutDirection.y() * stepSize.GetY()); + stepDirection.SetX(static_cast(jutDirection.x() * stepSize.GetX())); + stepDirection.SetY(static_cast(jutDirection.y() * stepSize.GetY())); m_scenePoint.setX(m_scenePoint.x() + stepDirection.GetX() * 2); } diff --git a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/ScriptCanvasActions/ElementInteractions.cpp b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/ScriptCanvasActions/ElementInteractions.cpp index 411d176356..9a8165b5e8 100644 --- a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/ScriptCanvasActions/ElementInteractions.cpp +++ b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/ScriptCanvasActions/ElementInteractions.cpp @@ -78,8 +78,8 @@ namespace ScriptCanvasDeveloper { CompoundAction* compoundAction = aznew CompoundAction(); - QPoint startPoint(m_scenePoint.x() - 5, m_scenePoint.y() - 5); - QPoint endPoint(m_scenePoint.x() + 5, m_scenePoint.y() + 5); + QPoint startPoint(static_cast(m_scenePoint.x() - 5.0), static_cast(m_scenePoint.y() - 5.0)); + QPoint endPoint(static_cast(m_scenePoint.x() + 5.0), static_cast(m_scenePoint.y() + 5.0)); QRect sceneRect = QRect(startPoint, endPoint); @@ -150,8 +150,8 @@ namespace ScriptCanvasDeveloper { CompoundAction* compoundAction = aznew CompoundAction(); - QPoint startPoint(m_scenePoint.x() - 5, m_scenePoint.y() - 5); - QPoint endPoint(m_scenePoint.x() + 5, m_scenePoint.y() + 5); + QPoint startPoint(static_cast(m_scenePoint.x() - 5.0), static_cast(m_scenePoint.y() - 5.0)); + QPoint endPoint(static_cast(m_scenePoint.x() + 5.0), static_cast(m_scenePoint.y() + 5.0)); QRect sceneRect = QRect(startPoint, endPoint); diff --git a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/WidgetActions.cpp b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/WidgetActions.cpp index 5601c89c97..46c98ca48c 100644 --- a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/WidgetActions.cpp +++ b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationActions/WidgetActions.cpp @@ -40,7 +40,7 @@ namespace ScriptCanvasDeveloper { ClearActionQueue(); - QPoint targetPoint = m_targetEdit->mapToGlobal(QPoint(5, m_targetEdit->height() * 0.5f)); + QPoint targetPoint = m_targetEdit->mapToGlobal(QPoint(5, static_cast(m_targetEdit->height() * 0.5f))); // Cheaty clear for right now. m_targetEdit->clear(); diff --git a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationStates/CreateElementsStates.cpp b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationStates/CreateElementsStates.cpp index 679cf5690e..bfb36235ef 100644 --- a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationStates/CreateElementsStates.cpp +++ b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationStates/CreateElementsStates.cpp @@ -70,7 +70,7 @@ namespace ScriptCanvasDeveloper if (dropPoint) { - QPointF qPoint = QPoint(dropPoint->GetX(), dropPoint->GetY()); + QPointF qPoint = QPoint(static_cast(dropPoint->GetX()), static_cast(dropPoint->GetY())); m_createNodeAction = aznew CreateNodeFromPaletteAction(m_nodePaletteWidget, (*graphId), m_nodeName, qPoint); } break; @@ -218,7 +218,7 @@ namespace ScriptCanvasDeveloper if (dropPoint) { - QPointF qPoint = QPoint(dropPoint->GetX(), dropPoint->GetY()); + QPointF qPoint = QPoint(static_cast(dropPoint->GetX()), static_cast(dropPoint->GetY())); m_createNodeAction = aznew CreateNodeFromContextMenuAction((*graphId), m_nodeName, qPoint); } break; diff --git a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationStates/UtilityStates.cpp b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationStates/UtilityStates.cpp index c8e82bdf90..459dc82542 100644 --- a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationStates/UtilityStates.cpp +++ b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomation/EditorAutomationStates/UtilityStates.cpp @@ -54,7 +54,7 @@ namespace ScriptCanvasDeveloper qreal verticalPoint = boundingRect.top() + boundingRect.height() * m_offsets.m_verticalPosition; verticalPoint += m_offsets.m_verticalOffset; - AZ::Vector2 scenePoint(horizontalPoint, verticalPoint); + AZ::Vector2 scenePoint(static_cast(horizontalPoint), static_cast(verticalPoint)); GetStateModel()->SetStateData(m_outputId, scenePoint); } } @@ -92,7 +92,7 @@ namespace ScriptCanvasDeveloper qreal verticalPoint = groupBoundingBox.top() + groupBoundingBox.height() * m_offsets.m_verticalPosition; verticalPoint += m_offsets.m_verticalPosition; - AZ::Vector2 scenePoint(horizontalPoint, verticalPoint); + AZ::Vector2 scenePoint(static_cast(horizontalPoint), static_cast(verticalPoint)); GetStateModel()->SetStateData(m_outputId, scenePoint); } else diff --git a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomationTests/GroupTests.cpp b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomationTests/GroupTests.cpp index cfe5996530..0428eb6640 100644 --- a/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomationTests/GroupTests.cpp +++ b/Gems/ScriptCanvasDeveloper/Code/Editor/Source/EditorAutomationTests/GroupTests.cpp @@ -70,8 +70,8 @@ namespace ScriptCanvasDeveloper AZ::Vector2 modifiedValue = (*position); QRectF sceneBoundingBox = nodeItem->sceneBoundingRect(); - modifiedValue.SetX(position->GetX() + sceneBoundingBox.width() * m_horizontalDimension); - modifiedValue.SetY(position->GetY() + sceneBoundingBox.height() * m_verticalDimension); + modifiedValue.SetX(position->GetX() + static_cast(sceneBoundingBox.width()) * m_horizontalDimension); + modifiedValue.SetY(position->GetY() + static_cast(sceneBoundingBox.height()) * m_verticalDimension); GetStateModel()->SetStateData(m_positionId, modifiedValue); } diff --git a/Gems/ScriptCanvasTesting/Code/CMakeLists.txt b/Gems/ScriptCanvasTesting/Code/CMakeLists.txt index 23c9627e83..29360912d8 100644 --- a/Gems/ScriptCanvasTesting/Code/CMakeLists.txt +++ b/Gems/ScriptCanvasTesting/Code/CMakeLists.txt @@ -87,8 +87,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) NAMESPACE Gem FILES_CMAKE scriptcanvastestingeditor_tests_files.cmake - PLATFORM_INCLUDE_FILES - Platform/Common/${PAL_TRAIT_COMPILER_ID}/scriptcanvastesting_editor_tests_${PAL_TRAIT_COMPILER_ID_LOWERCASE}.cmake INCLUDE_DIRECTORIES PRIVATE . diff --git a/Gems/ScriptCanvasTesting/Code/Platform/Common/Clang/scriptcanvastesting_editor_tests_clang.cmake b/Gems/ScriptCanvasTesting/Code/Platform/Common/Clang/scriptcanvastesting_editor_tests_clang.cmake deleted file mode 100644 index 7a325ca97e..0000000000 --- a/Gems/ScriptCanvasTesting/Code/Platform/Common/Clang/scriptcanvastesting_editor_tests_clang.cmake +++ /dev/null @@ -1,7 +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 -# -# diff --git a/Gems/ScriptCanvasTesting/Code/Platform/Common/MSVC/scriptcanvastesting_editor_tests_msvc.cmake b/Gems/ScriptCanvasTesting/Code/Platform/Common/MSVC/scriptcanvastesting_editor_tests_msvc.cmake deleted file mode 100644 index 3ea56febcb..0000000000 --- a/Gems/ScriptCanvasTesting/Code/Platform/Common/MSVC/scriptcanvastesting_editor_tests_msvc.cmake +++ /dev/null @@ -1,28 +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 -# -# - -ly_add_source_properties( - SOURCES - Source/Framework/ScriptCanvasTestUtilities.cpp - Tests/ScriptCanvas_BehaviorContext.cpp - Tests/ScriptCanvas_ContainerSupport.cpp - Tests/ScriptCanvas_Core.cpp - Tests/ScriptCanvas_EventHandlers.cpp - Tests/ScriptCanvas_Math.cpp - Tests/ScriptCanvas_MethodOverload.cpp - Tests/ScriptCanvas_NodeGenerics.cpp - Tests/ScriptCanvas_Regressions.cpp - Tests/ScriptCanvas_RuntimeInterpreted.cpp - Tests/ScriptCanvas_Slots.cpp - Tests/ScriptCanvas_StringNodes.cpp - Tests/ScriptCanvas_UnitTesting.cpp - Tests/ScriptCanvas_Variables.cpp - Tests/ScriptCanvas_VM.cpp - PROPERTY COMPILE_OPTIONS - VALUES -bigobj -) diff --git a/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_NodeGenerics.cpp b/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_NodeGenerics.cpp index 09ebd3d360..cbbe77fbba 100644 --- a/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_NodeGenerics.cpp +++ b/Gems/ScriptCanvasTesting/Code/Tests/ScriptCanvas_NodeGenerics.cpp @@ -13,9 +13,6 @@ #include -#pragma warning( push ) -#pragma warning( disable : 5046) //'function' : Symbol involving type with internal linkage not defined - using namespace ScriptCanvasTests; namespace @@ -110,7 +107,7 @@ namespace ScriptCanvas AZ_INLINE AZ::Vector3 NormalizeWithDefault(const AZ::Vector3& source, const Data::NumberType tolerance, [[maybe_unused]] const Data::BooleanType fakeValueForTestingDefault) { AZ_TracePrintf("SC", "The fake value for testing default is %s\n", fakeValueForTestingDefault ? "True" : "False"); - return source.GetNormalizedSafe(tolerance); + return source.GetNormalizedSafe(static_cast(tolerance)); } void NormalizeWithDefaultInputOverrides(Node& node) { SetDefaultValuesByIndex< 1, 2 >::_(node, 3.3, true); } @@ -163,6 +160,3 @@ TEST_F(ScriptCanvasTestFixture, NodeGenerics) delete graph->GetEntity(); } - - -#pragma warning( pop ) diff --git a/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/BehaviorContextBinding/ScriptEventBroadcast.cpp b/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/BehaviorContextBinding/ScriptEventBroadcast.cpp index c55495efad..1e5e741b5d 100644 --- a/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/BehaviorContextBinding/ScriptEventBroadcast.cpp +++ b/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/BehaviorContextBinding/ScriptEventBroadcast.cpp @@ -111,7 +111,7 @@ namespace ScriptEvents { // Iterate from end of parameters and count the number of consecutive valid BehaviorValue objects size_t numDefaultArguments = 0; - for (size_t i = GetNumArguments() - 1; i >= 0 && GetDefaultValue(i); --i, ++numDefaultArguments) + for (int i = static_cast(GetNumArguments()) - 1; i >= 0 && GetDefaultValue(static_cast(i)); --i, ++numDefaultArguments) { } return GetNumArguments() - numDefaultArguments; diff --git a/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/BehaviorContextBinding/ScriptEventMethod.cpp b/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/BehaviorContextBinding/ScriptEventMethod.cpp index 37f437670d..7153fda8bd 100644 --- a/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/BehaviorContextBinding/ScriptEventMethod.cpp +++ b/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/BehaviorContextBinding/ScriptEventMethod.cpp @@ -121,7 +121,7 @@ namespace ScriptEvents { // Iterate from end of parameters and count the number of consecutive valid BehaviorValue objects size_t numDefaultArguments = 0; - for (size_t i = GetNumArguments() - 1; i >= 0 && GetDefaultValue(i); --i, ++numDefaultArguments) + for (int i = static_cast(GetNumArguments()) - 1; i >= 0 && GetDefaultValue(static_cast(i)); --i, ++numDefaultArguments) { } return GetNumArguments() - numDefaultArguments; diff --git a/Gems/ScriptedEntityTweener/Code/Include/ScriptedEntityTweener/ScriptedEntityTweenerEnums.h b/Gems/ScriptedEntityTweener/Code/Include/ScriptedEntityTweener/ScriptedEntityTweenerEnums.h index 46bba2f1b9..4c85c18382 100644 --- a/Gems/ScriptedEntityTweener/Code/Include/ScriptedEntityTweener/ScriptedEntityTweenerEnums.h +++ b/Gems/ScriptedEntityTweener/Code/Include/ScriptedEntityTweener/ScriptedEntityTweenerEnums.h @@ -79,7 +79,7 @@ namespace ScriptedEntityTweener struct AnimationProperties { static const float UninitializedParamFloat; - static const unsigned int InvalidCallbackId; + static const int InvalidCallbackId; static const unsigned int InvalidTimelineId; EasingMethod m_easeMethod; diff --git a/Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweenerTask.cpp b/Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweenerTask.cpp index 8be0efdbdc..cd52583ff6 100644 --- a/Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweenerTask.cpp +++ b/Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweenerTask.cpp @@ -15,7 +15,7 @@ namespace ScriptedEntityTweener const AZStd::any ScriptedEntityTweenerTask::QueuedSubtaskInfo::m_emptyInitialValue; const float AnimationProperties::UninitializedParamFloat = FLT_MIN; - const unsigned int AnimationProperties::InvalidCallbackId = 0; + const int AnimationProperties::InvalidCallbackId = 0; const unsigned int AnimationProperties::InvalidTimelineId = 0; ScriptedEntityTweenerTask::ScriptedEntityTweenerTask(AZ::EntityId id) diff --git a/Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweenerTask.h b/Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweenerTask.h index 91528c08c0..a0d453c593 100644 --- a/Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweenerTask.h +++ b/Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweenerTask.h @@ -150,7 +150,7 @@ namespace ScriptedEntityTweener bool IsTimelineIdValid(int timelineId) { - return timelineId != AnimationProperties::InvalidTimelineId; + return timelineId != static_cast(AnimationProperties::InvalidTimelineId); } bool InitializeSubtask(ScriptedEntityTweenerSubtask& subtask, const AZStd::pair initData, AnimationParameters params); diff --git a/Gems/SurfaceData/Code/Include/SurfaceData/Utility/SurfaceDataUtility.h b/Gems/SurfaceData/Code/Include/SurfaceData/Utility/SurfaceDataUtility.h index 18899ac3b1..29b3fac8c7 100644 --- a/Gems/SurfaceData/Code/Include/SurfaceData/Utility/SurfaceDataUtility.h +++ b/Gems/SurfaceData/Code/Include/SurfaceData/Utility/SurfaceDataUtility.h @@ -9,11 +9,11 @@ #pragma once #include +#include #include #include #include #include -#include namespace AZ { @@ -33,7 +33,7 @@ namespace SurfaceData AZ::Vector3& outPosition, AZ::Vector3& outNormal) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const size_t vertexCount = vertices.size(); if (vertexCount > 0 && vertexCount % 4 == 0) diff --git a/Gems/SurfaceData/Code/Source/Components/SurfaceDataColliderComponent.cpp b/Gems/SurfaceData/Code/Source/Components/SurfaceDataColliderComponent.cpp index 22328fc73f..eef9179194 100644 --- a/Gems/SurfaceData/Code/Source/Components/SurfaceDataColliderComponent.cpp +++ b/Gems/SurfaceData/Code/Source/Components/SurfaceDataColliderComponent.cpp @@ -184,7 +184,7 @@ namespace SurfaceData bool SurfaceDataColliderComponent::DoRayTrace(const AZ::Vector3& inPosition, bool queryPointOnly, AZ::Vector3& outPosition, AZ::Vector3& outNormal) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_cacheMutex); @@ -249,7 +249,7 @@ namespace SurfaceData void SurfaceDataColliderComponent::ModifySurfacePoints(SurfacePointList& surfacePointList) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_cacheMutex); @@ -303,7 +303,7 @@ namespace SurfaceData void SurfaceDataColliderComponent::UpdateColliderData() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); bool colliderValidBeforeUpdate = false; bool colliderValidAfterUpdate = false; diff --git a/Gems/SurfaceData/Code/Source/Components/SurfaceDataShapeComponent.cpp b/Gems/SurfaceData/Code/Source/Components/SurfaceDataShapeComponent.cpp index 6129094115..890f8fba54 100644 --- a/Gems/SurfaceData/Code/Source/Components/SurfaceDataShapeComponent.cpp +++ b/Gems/SurfaceData/Code/Source/Components/SurfaceDataShapeComponent.cpp @@ -143,7 +143,7 @@ namespace SurfaceData void SurfaceDataShapeComponent::GetSurfacePoints(const AZ::Vector3& inPosition, SurfacePointList& surfacePointList) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_cacheMutex); @@ -168,7 +168,7 @@ namespace SurfaceData void SurfaceDataShapeComponent::ModifySurfacePoints(SurfacePointList& surfacePointList) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_cacheMutex); @@ -221,7 +221,7 @@ namespace SurfaceData void SurfaceDataShapeComponent::UpdateShapeData() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); bool shapeValidBeforeUpdate = false; bool shapeValidAfterUpdate = false; diff --git a/Gems/SurfaceData/Code/Source/SurfaceDataModule.cpp b/Gems/SurfaceData/Code/Source/SurfaceDataModule.cpp index 6c96ee9d27..35064bf4a4 100644 --- a/Gems/SurfaceData/Code/Source/SurfaceDataModule.cpp +++ b/Gems/SurfaceData/Code/Source/SurfaceDataModule.cpp @@ -10,7 +10,6 @@ #include #include #include -#include namespace SurfaceData { @@ -20,7 +19,6 @@ namespace SurfaceData SurfaceDataSystemComponent::CreateDescriptor(), SurfaceDataColliderComponent::CreateDescriptor(), SurfaceDataShapeComponent::CreateDescriptor(), - TerrainSurfaceDataSystemComponent::CreateDescriptor(), }); } @@ -28,7 +26,6 @@ namespace SurfaceData { return AZ::ComponentTypeList{ azrtti_typeid(), - azrtti_typeid(), }; } } diff --git a/Gems/SurfaceData/Code/Source/SurfaceDataSystemComponent.cpp b/Gems/SurfaceData/Code/Source/SurfaceDataSystemComponent.cpp index 356785df35..7638b6720e 100644 --- a/Gems/SurfaceData/Code/Source/SurfaceDataSystemComponent.cpp +++ b/Gems/SurfaceData/Code/Source/SurfaceDataSystemComponent.cpp @@ -6,6 +6,7 @@ * */ +#include #include #include #include @@ -180,7 +181,7 @@ namespace SurfaceData void SurfaceDataSystemComponent::GetSurfacePoints(const AZ::Vector3& inPosition, const SurfaceTagVector& desiredTags, SurfacePointList& surfacePointList) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const bool hasDesiredTags = HasValidTags(desiredTags); const bool hasModifierTags = hasDesiredTags && HasMatchingTags(desiredTags, m_registeredModifierTags); @@ -228,7 +229,7 @@ namespace SurfaceData void SurfaceDataSystemComponent::GetSurfacePointsFromRegion(const AZ::Aabb& inRegion, const AZ::Vector2 stepSize, const SurfaceTagVector& desiredTags, SurfacePointListPerPosition& surfacePointListPerPosition) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard registrationLock(m_registrationMutex); @@ -317,7 +318,7 @@ namespace SurfaceData void SurfaceDataSystemComponent::CombineSortAndFilterNeighboringPoints(SurfacePointList& sourcePointList, bool hasDesiredTags, const SurfaceTagVector& desiredTags) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (sourcePointList.empty()) { diff --git a/Gems/SurfaceData/Code/Source/SurfaceDataUtility.cpp b/Gems/SurfaceData/Code/Source/SurfaceDataUtility.cpp index d55f79faea..ba21d0a616 100644 --- a/Gems/SurfaceData/Code/Source/SurfaceDataUtility.cpp +++ b/Gems/SurfaceData/Code/Source/SurfaceDataUtility.cpp @@ -17,7 +17,7 @@ namespace SurfaceData const AZ::Vector3& rayStart, const AZ::Vector3& rayEnd, AZ::Vector3& outPosition, AZ::Vector3& outNormal) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const AZ::Vector3 clampedScale = nonUniformScale.GetMax(AZ::Vector3(AZ::MinTransformScale)); diff --git a/Gems/SurfaceData/Code/Source/SurfaceTag.cpp b/Gems/SurfaceData/Code/Source/SurfaceTag.cpp index 70a2669b19..f986509140 100644 --- a/Gems/SurfaceData/Code/Source/SurfaceTag.cpp +++ b/Gems/SurfaceData/Code/Source/SurfaceTag.cpp @@ -88,7 +88,7 @@ namespace SurfaceData AZStd::vector> SurfaceTag::GetRegisteredTags() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); SurfaceTagNameSet labels; SurfaceDataTagProviderRequestBus::Broadcast(&SurfaceDataTagProviderRequestBus::Events::GetRegisteredSurfaceTagNames, labels); @@ -134,7 +134,7 @@ namespace SurfaceData AZStd::vector> SurfaceTag::BuildSelectableTagList() const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::vector> selectableTags = GetRegisteredTags(); @@ -152,7 +152,7 @@ namespace SurfaceData AZStd::string SurfaceTag::GetDisplayName() const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::string name; FindDisplayName(GetRegisteredTags(), name); diff --git a/Gems/SurfaceData/Code/surfacedata_files.cmake b/Gems/SurfaceData/Code/surfacedata_files.cmake index 487dcb70e5..4b8ac914d7 100644 --- a/Gems/SurfaceData/Code/surfacedata_files.cmake +++ b/Gems/SurfaceData/Code/surfacedata_files.cmake @@ -19,8 +19,6 @@ set(FILES Include/SurfaceData/Utility/SurfaceDataUtility.h Source/SurfaceDataSystemComponent.cpp Source/SurfaceDataSystemComponent.h - Source/TerrainSurfaceDataSystemComponent.cpp - Source/TerrainSurfaceDataSystemComponent.h Source/SurfaceTag.cpp Source/Components/SurfaceDataColliderComponent.cpp Source/Components/SurfaceDataColliderComponent.h diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainHeight.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainHeight.svg new file mode 100644 index 0000000000..57835e9c20 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainHeight.svg @@ -0,0 +1,7 @@ + + + icon / Environmental / Terrain Height + + + + \ No newline at end of file diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainLayerRenderer.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainLayerRenderer.svg new file mode 100644 index 0000000000..fb9590ae7b --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainLayerRenderer.svg @@ -0,0 +1,7 @@ + + + icon / Environmental / Terrain Mesh + + + + \ No newline at end of file diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainLayerSpawner.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainLayerSpawner.svg new file mode 100644 index 0000000000..df73d78276 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainLayerSpawner.svg @@ -0,0 +1,7 @@ + + + icon / Environmental / Generate Terrian + + + + \ No newline at end of file diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorld.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorld.svg new file mode 100644 index 0000000000..c6388d6215 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorld.svg @@ -0,0 +1,8 @@ + + + icon / Environmental / Terrain Refactor + + + + + \ No newline at end of file diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldDebugger.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldDebugger.svg new file mode 100644 index 0000000000..bd1512afda --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldDebugger.svg @@ -0,0 +1,8 @@ + + + icon / Environmental / Terrain World Debugger + + + + + \ No newline at end of file diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldRenderer.svg b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldRenderer.svg new file mode 100644 index 0000000000..ab3716ad5d --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/TerrainWorldRenderer.svg @@ -0,0 +1,8 @@ + + + icon / Environmental / Terrain World Renderer + + + + + \ No newline at end of file diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainHeight.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainHeight.svg new file mode 100644 index 0000000000..b87a0b4d7e --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainHeight.svg @@ -0,0 +1,25 @@ + + + icon / Environmental / Terrain Height - box + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainLayerRenderer.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainLayerRenderer.svg new file mode 100644 index 0000000000..521d56784c --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainLayerRenderer.svg @@ -0,0 +1,25 @@ + + + icon / Environmental / Terrain Mesh - box + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainLayerSpawner.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainLayerSpawner.svg new file mode 100644 index 0000000000..c078d32fe5 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainLayerSpawner.svg @@ -0,0 +1,25 @@ + + + icon / Environmental / Generate Terrian - box + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorld.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorld.svg new file mode 100644 index 0000000000..2aee65f2a8 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorld.svg @@ -0,0 +1,25 @@ + + + icon / Environmental / Terrain Refactor - box + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldDebugger.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldDebugger.svg new file mode 100644 index 0000000000..1b729ab73f --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldDebugger.svg @@ -0,0 +1,25 @@ + + + icon / Environmental / Terrain World Debugger - box + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldRenderer.svg b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldRenderer.svg new file mode 100644 index 0000000000..4287508f10 --- /dev/null +++ b/Gems/Terrain/Assets/Editor/Icons/Components/Viewport/TerrainWorldRenderer.svg @@ -0,0 +1,25 @@ + + + icon / Environmental / Terrain World Renderer - box + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Gems/Terrain/CMakeLists.txt b/Gems/Terrain/CMakeLists.txt new file mode 100644 index 0000000000..34bce0825f --- /dev/null +++ b/Gems/Terrain/CMakeLists.txt @@ -0,0 +1,8 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +add_subdirectory(Code) diff --git a/Gems/Terrain/Code/CMakeLists.txt b/Gems/Terrain/Code/CMakeLists.txt new file mode 100644 index 0000000000..f40dd17ede --- /dev/null +++ b/Gems/Terrain/Code/CMakeLists.txt @@ -0,0 +1,139 @@ +# +# 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 +# +# + +ly_add_target( + NAME Terrain.Static STATIC + NAMESPACE Gem + FILES_CMAKE + terrain_files.cmake + INCLUDE_DIRECTORIES + PUBLIC + Include + PRIVATE + Source + BUILD_DEPENDENCIES + PUBLIC + AZ::AzCore + AZ::AzFramework + Gem::Atom_RPI.Public + Gem::Atom_Utils.Static + Gem::GradientSignal + Gem::SurfaceData + Gem::LmbrCentral +) + +ly_add_target( + NAME Terrain ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} + NAMESPACE Gem + FILES_CMAKE + terrain_shared_files.cmake + INCLUDE_DIRECTORIES + PUBLIC + Include + PRIVATE + Source + BUILD_DEPENDENCIES + PRIVATE + Gem::Terrain.Static + Gem::LmbrCentral + RUNTIME_DEPENDENCIES + Gem::LmbrCentral +) + +# the above module is for use in all client/server types +ly_create_alias(NAME Terrain.Servers NAMESPACE Gem TARGETS Gem::Terrain) +ly_create_alias(NAME Terrain.Clients NAMESPACE Gem TARGETS Gem::Terrain) + +# If we are on a host platform, we want to add the host tools targets like the Terrain.Editor target which +# will also depend on Terrain.Static +if(PAL_TRAIT_BUILD_HOST_TOOLS) + ly_add_target( + NAME Terrain.Editor MODULE + NAMESPACE Gem + AUTOMOC + OUTPUT_NAME Gem.Terrain.Editor + FILES_CMAKE + terrain_editor_shared_files.cmake + COMPILE_DEFINITIONS + PRIVATE + TERRAIN_EDITOR + INCLUDE_DIRECTORIES + PRIVATE + Source + PUBLIC + Include + BUILD_DEPENDENCIES + PUBLIC + AZ::AzToolsFramework + Gem::GradientSignal + Gem::LmbrCentral + Gem::Terrain.Static + ) + + # the above module is for use in dev tool situations + ly_create_alias(NAME Terrain.Builders NAMESPACE Gem TARGETS Gem::Terrain.Editor) + ly_create_alias(NAME Terrain.Tools NAMESPACE Gem TARGETS Gem::Terrain.Editor) +endif() + +################################################################################ +# Tests +################################################################################ +# See if globally, tests are supported +if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) + # We globally support tests, see if we support tests on this platform for Terrain.Static + if(PAL_TRAIT_TERRAIN_TEST_SUPPORTED) + # We support Terrain.Tests on this platform, add Terrain.Tests target which depends on Terrain.Static + ly_add_target( + NAME Terrain.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} + NAMESPACE Gem + FILES_CMAKE + terrain_files.cmake + terrain_tests_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Tests + Source + BUILD_DEPENDENCIES + PRIVATE + AZ::AzTest + AZ::AzFramework + Gem::Terrain.Static + ) + + # Add Terrain.Tests to googletest + ly_add_googletest( + NAME Gem::Terrain.Tests + ) + endif() + + # If we are a host platform we want to add tools test like editor tests here + if(PAL_TRAIT_BUILD_HOST_TOOLS) + # We are a host platform, see if Editor tests are supported on this platform + if(PAL_TRAIT_TERRAIN_EDITOR_TEST_SUPPORTED) + # We support Terrain.Editor.Tests on this platform, add Terrain.Editor.Tests target which depends on Terrain.Editor + ly_add_target( + NAME Terrain.Editor.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} + NAMESPACE Gem + FILES_CMAKE + terrain_editor_tests_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Tests + Source + BUILD_DEPENDENCIES + PRIVATE + AZ::AzTest + Gem::Terrain.Editor + ) + + # Add Terrain.Editor.Tests to googletest + ly_add_googletest( + NAME Gem::Terrain.Editor.Tests + ) + endif() + endif() +endif() diff --git a/Gems/SurfaceData/Code/Source/TerrainSurfaceDataSystemComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainSurfaceDataSystemComponent.cpp similarity index 67% rename from Gems/SurfaceData/Code/Source/TerrainSurfaceDataSystemComponent.cpp rename to Gems/Terrain/Code/Source/Components/TerrainSurfaceDataSystemComponent.cpp index 0f6eec73cd..04c94b24d6 100644 --- a/Gems/SurfaceData/Code/Source/TerrainSurfaceDataSystemComponent.cpp +++ b/Gems/Terrain/Code/Source/Components/TerrainSurfaceDataSystemComponent.cpp @@ -6,20 +6,16 @@ * */ -#include "TerrainSurfaceDataSystemComponent.h" +#include #include #include #include #include -#include -#include #include #include #include -#include - -namespace SurfaceData +namespace Terrain { ////////////////////////////////////////////////////////////////////////// // TerrainSurfaceDataSystemConfig @@ -62,7 +58,7 @@ namespace SurfaceData editContext->Class("Terrain Surface Data System", "Manages surface data requests against legacy terrain") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "Surface Data") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("System")) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(0, &TerrainSurfaceDataSystemComponent::m_configuration, "Configuration", "") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) @@ -82,42 +78,39 @@ namespace SurfaceData void TerrainSurfaceDataSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services) { - services.push_back(AZ_CRC("SurfaceDataProviderService", 0xfe9fb95e)); - services.push_back(AZ_CRC("TerrainSurfaceDataProviderService", 0xa1ac7717)); + services.push_back(AZ_CRC_CE("SurfaceDataProviderService")); + services.push_back(AZ_CRC_CE("TerrainSurfaceDataProviderService")); } void TerrainSurfaceDataSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services) { - services.push_back(AZ_CRC("TerrainSurfaceDataProviderService", 0xa1ac7717)); + services.push_back(AZ_CRC_CE("TerrainSurfaceDataProviderService")); } void TerrainSurfaceDataSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services) { - services.push_back(AZ_CRC("SurfaceDataSystemService", 0x1d44d25f)); + services.push_back(AZ_CRC_CE("SurfaceDataSystemService")); } void TerrainSurfaceDataSystemComponent::Activate() { - m_providerHandle = InvalidSurfaceDataRegistryHandle; - m_system = GetISystem(); - CrySystemEventBus::Handler::BusConnect(); - AZ::HeightmapUpdateNotificationBus::Handler::BusConnect(); + m_providerHandle = SurfaceData::InvalidSurfaceDataRegistryHandle; + AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusConnect(); UpdateTerrainData(AZ::Aabb::CreateNull()); } void TerrainSurfaceDataSystemComponent::Deactivate() { - if (m_providerHandle != InvalidSurfaceDataRegistryHandle) + if (m_providerHandle != SurfaceData::InvalidSurfaceDataRegistryHandle) { - SurfaceDataSystemRequestBus::Broadcast(&SurfaceDataSystemRequestBus::Events::UnregisterSurfaceDataProvider, m_providerHandle); - m_providerHandle = InvalidSurfaceDataRegistryHandle; + SurfaceData::SurfaceDataSystemRequestBus::Broadcast( + &SurfaceData::SurfaceDataSystemRequestBus::Events::UnregisterSurfaceDataProvider, m_providerHandle); + m_providerHandle = SurfaceData::InvalidSurfaceDataRegistryHandle; } - SurfaceDataProviderRequestBus::Handler::BusDisconnect(); - AZ::HeightmapUpdateNotificationBus::Handler::BusDisconnect(); - CrySystemEventBus::Handler::BusDisconnect(); - m_system = nullptr; + SurfaceData::SurfaceDataProviderRequestBus::Handler::BusDisconnect(); + AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusDisconnect(); // Clear the cached terrain bounds data { @@ -146,17 +139,8 @@ namespace SurfaceData return false; } - void TerrainSurfaceDataSystemComponent::OnCrySystemInitialized(ISystem& system, [[maybe_unused]] const SSystemInitParams& systemInitParams) - { - m_system = &system; - } - - void TerrainSurfaceDataSystemComponent::OnCrySystemShutdown([[maybe_unused]] ISystem& system) - { - m_system = nullptr; - } - - void TerrainSurfaceDataSystemComponent::GetSurfacePoints(const AZ::Vector3& inPosition, SurfacePointList& surfacePointList) const + void TerrainSurfaceDataSystemComponent::GetSurfacePoints( + const AZ::Vector3& inPosition, SurfaceData::SurfacePointList& surfacePointList) const { if (m_terrainBoundsIsValid) { @@ -168,12 +152,13 @@ namespace SurfaceData const float terrainHeight = terrain->GetHeight(inPosition, AzFramework::Terrain::TerrainDataRequests::Sampler::BILINEAR, &isTerrainValidAtPoint); const bool isHole = !isTerrainValidAtPoint; - SurfacePoint point; + SurfaceData::SurfacePoint point; point.m_entityId = GetEntityId(); point.m_position = AZ::Vector3(inPosition.GetX(), inPosition.GetY(), terrainHeight); point.m_normal = terrain->GetNormal(inPosition); - const AZ::Crc32 terrainTag = isHole ? Constants::s_terrainHoleTagCrc : Constants::s_terrainTagCrc; - AddMaxValueForMasks(point.m_masks, terrainTag, 1.0f); + const AZ::Crc32 terrainTag = + isHole ? SurfaceData::Constants::s_terrainHoleTagCrc : SurfaceData::Constants::s_terrainTagCrc; + SurfaceData::AddMaxValueForMasks(point.m_masks, terrainTag, 1.0f); surfacePointList.push_back(point); } // Only one handler should exist. @@ -189,11 +174,11 @@ namespace SurfaceData return terrain ? terrain->GetTerrainAabb() : AZ::Aabb::CreateNull(); } - SurfaceTagVector TerrainSurfaceDataSystemComponent::GetSurfaceTags() const + SurfaceData::SurfaceTagVector TerrainSurfaceDataSystemComponent::GetSurfaceTags() const { - SurfaceTagVector tags; - tags.push_back(Constants::s_terrainHoleTagCrc); - tags.push_back(Constants::s_terrainTagCrc); + SurfaceData::SurfaceTagVector tags; + tags.push_back(SurfaceData::Constants::s_terrainHoleTagCrc); + tags.push_back(SurfaceData::Constants::s_terrainTagCrc); return tags; } @@ -203,7 +188,7 @@ namespace SurfaceData bool terrainValidAfterUpdate = false; AZ::Aabb terrainBoundsBeforeUpdate = m_terrainBounds; - SurfaceDataRegistryEntry registryEntry; + SurfaceData::SurfaceDataRegistryEntry registryEntry; registryEntry.m_entityId = GetEntityId(); registryEntry.m_bounds = GetSurfaceAabb(); registryEntry.m_tags = GetSurfaceTags(); @@ -215,38 +200,44 @@ namespace SurfaceData if (terrainValidBeforeUpdate && terrainValidAfterUpdate) { - AZ_Assert((m_providerHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle"); + AZ_Assert((m_providerHandle != SurfaceData::InvalidSurfaceDataRegistryHandle), "Invalid surface data handle"); // Our terrain was valid before and after, it just changed in some way. If we have a valid dirty region passed in // then it's possible that the heightmap has been modified in the Editor. Otherwise, just notify that the entire // terrain has changed in some way. if (dirtyRegion.IsValid()) { - SurfaceDataSystemRequestBus::Broadcast(&SurfaceDataSystemRequestBus::Events::RefreshSurfaceData, dirtyRegion); + SurfaceData::SurfaceDataSystemRequestBus::Broadcast( + &SurfaceData::SurfaceDataSystemRequestBus::Events::RefreshSurfaceData, dirtyRegion); } else { - SurfaceDataSystemRequestBus::Broadcast(&SurfaceDataSystemRequestBus::Events::UpdateSurfaceDataProvider, m_providerHandle, registryEntry); + SurfaceData::SurfaceDataSystemRequestBus::Broadcast( + &SurfaceData::SurfaceDataSystemRequestBus::Events::UpdateSurfaceDataProvider, m_providerHandle, registryEntry); } } else if (!terrainValidBeforeUpdate && terrainValidAfterUpdate) { // Our terrain has become valid, so register as a provider and save off the registry handles - AZ_Assert((m_providerHandle == InvalidSurfaceDataRegistryHandle), "Surface Provider data handle is initialized before our terrain became valid"); - SurfaceDataSystemRequestBus::BroadcastResult(m_providerHandle, &SurfaceDataSystemRequestBus::Events::RegisterSurfaceDataProvider, registryEntry); + AZ_Assert( + (m_providerHandle == SurfaceData::InvalidSurfaceDataRegistryHandle), + "Surface Provider data handle is initialized before our terrain became valid"); + SurfaceData::SurfaceDataSystemRequestBus::BroadcastResult( + m_providerHandle, &SurfaceData::SurfaceDataSystemRequestBus::Events::RegisterSurfaceDataProvider, registryEntry); // Start listening for surface data events - AZ_Assert((m_providerHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle"); - SurfaceDataProviderRequestBus::Handler::BusConnect(m_providerHandle); + AZ_Assert((m_providerHandle != SurfaceData::InvalidSurfaceDataRegistryHandle), "Invalid surface data handle"); + SurfaceData::SurfaceDataProviderRequestBus::Handler::BusConnect(m_providerHandle); } else if (terrainValidBeforeUpdate && !terrainValidAfterUpdate) { // Our terrain has stopped being valid, so unregister and stop listening for surface data events - AZ_Assert((m_providerHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle"); - SurfaceDataSystemRequestBus::Broadcast(&SurfaceDataSystemRequestBus::Events::UnregisterSurfaceDataProvider, m_providerHandle); - m_providerHandle = InvalidSurfaceDataRegistryHandle; + AZ_Assert((m_providerHandle != SurfaceData::InvalidSurfaceDataRegistryHandle), "Invalid surface data handle"); + SurfaceData::SurfaceDataSystemRequestBus::Broadcast( + &SurfaceData::SurfaceDataSystemRequestBus::Events::UnregisterSurfaceDataProvider, m_providerHandle); + m_providerHandle = SurfaceData::InvalidSurfaceDataRegistryHandle; - SurfaceDataProviderRequestBus::Handler::BusDisconnect(); + SurfaceData::SurfaceDataProviderRequestBus::Handler::BusDisconnect(); } else { @@ -255,8 +246,9 @@ namespace SurfaceData } - void TerrainSurfaceDataSystemComponent::HeightmapModified(const AZ::Aabb& bounds) + void TerrainSurfaceDataSystemComponent::OnTerrainDataChanged( + const AZ::Aabb& dirtyRegion, [[maybe_unused]] TerrainDataChangedMask dataChangedMask) { - UpdateTerrainData(bounds); + UpdateTerrainData(dirtyRegion); } } diff --git a/Gems/SurfaceData/Code/Source/TerrainSurfaceDataSystemComponent.h b/Gems/Terrain/Code/Source/Components/TerrainSurfaceDataSystemComponent.h similarity index 75% rename from Gems/SurfaceData/Code/Source/TerrainSurfaceDataSystemComponent.h rename to Gems/Terrain/Code/Source/Components/TerrainSurfaceDataSystemComponent.h index aa5f4ab04c..a742eab78c 100644 --- a/Gems/SurfaceData/Code/Source/TerrainSurfaceDataSystemComponent.h +++ b/Gems/Terrain/Code/Source/Components/TerrainSurfaceDataSystemComponent.h @@ -10,12 +10,11 @@ #include #include #include -#include -#include +#include #include #include -namespace SurfaceData +namespace Terrain { class TerrainSurfaceDataSystemConfig : public AZ::ComponentConfig @@ -31,9 +30,8 @@ namespace SurfaceData */ class TerrainSurfaceDataSystemComponent : public AZ::Component - , private SurfaceDataProviderRequestBus::Handler - , private AZ::HeightmapUpdateNotificationBus::Handler - , private CrySystemEventBus::Handler + , private SurfaceData::SurfaceDataProviderRequestBus::Handler + , private AzFramework::Terrain::TerrainDataNotificationBus::Handler { friend class EditorTerrainSurfaceDataSystemComponent; TerrainSurfaceDataSystemComponent(const TerrainSurfaceDataSystemConfig&); @@ -58,25 +56,19 @@ namespace SurfaceData ////////////////////////////////////////////////////////////////////////// // SurfaceDataProviderRequestBus - void GetSurfacePoints(const AZ::Vector3& inPosition, SurfacePointList& surfacePointList) const; - - //////////////////////////////////////////////////////////////////////////// - // CrySystemEvents - void OnCrySystemInitialized(ISystem& system, const SSystemInitParams& systemInitParams) override; - void OnCrySystemShutdown(ISystem& system) override; + void GetSurfacePoints(const AZ::Vector3& inPosition, SurfaceData::SurfacePointList& surfacePointList) const; ////////////////////////////////////////////////////////////////////////// - // AZ::HeightmapUpdateNotificationBus - void HeightmapModified(const AZ::Aabb& bounds) override; + // AzFramework::Terrain::TerrainDataNotificationBus + void OnTerrainDataChanged(const AZ::Aabb& dirtyRegion, TerrainDataChangedMask dataChangedMask) override; private: void UpdateTerrainData(const AZ::Aabb& dirtyRegion); AZ::Aabb GetSurfaceAabb() const; - SurfaceTagVector GetSurfaceTags() const; - SurfaceDataRegistryHandle m_providerHandle = InvalidSurfaceDataRegistryHandle; + SurfaceData::SurfaceTagVector GetSurfaceTags() const; + SurfaceData::SurfaceDataRegistryHandle m_providerHandle = SurfaceData::InvalidSurfaceDataRegistryHandle; TerrainSurfaceDataSystemConfig m_configuration; - ISystem* m_system = nullptr; AZ::Aabb m_terrainBounds = AZ::Aabb::CreateNull(); AZStd::atomic_bool m_terrainBoundsIsValid{ false }; diff --git a/Gems/Terrain/Code/Source/Components/TerrainSystemComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainSystemComponent.cpp new file mode 100644 index 0000000000..dea7babbbc --- /dev/null +++ b/Gems/Terrain/Code/Source/Components/TerrainSystemComponent.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + + +#include + +#include +#include +#include + +#include + +namespace Terrain +{ + void TerrainSystemComponent::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serialize = azrtti_cast(context)) + { + serialize->Class() + ->Version(0); + + if (AZ::EditContext* ec = serialize->GetEditContext()) + { + ec->Class("Terrain", "The Terrain System Component enables Terrain.") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("System")) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ; + } + } + } + + void TerrainSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC_CE("TerrainService")); + } + + void TerrainSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("TerrainService")); + } + + void TerrainSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + required.push_back(AZ_CRC_CE("RPISystem")); + } + + void TerrainSystemComponent::GetDependentServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& dependent) + { + } + + void TerrainSystemComponent::Init() + { + } + + void TerrainSystemComponent::Activate() + { + } + + void TerrainSystemComponent::Deactivate() + { + } +} diff --git a/Gems/Terrain/Code/Source/Components/TerrainSystemComponent.h b/Gems/Terrain/Code/Source/Components/TerrainSystemComponent.h new file mode 100644 index 0000000000..b294c0473a --- /dev/null +++ b/Gems/Terrain/Code/Source/Components/TerrainSystemComponent.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace Terrain +{ + class TerrainSystem; + + class TerrainSystemComponent + : public AZ::Component + { + public: + AZ_COMPONENT(TerrainSystemComponent, "{CD5A517E-3BD8-49AE-8F9B-33C6FC47EC67}"); + + static void Reflect(AZ::ReflectContext* context); + + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); + + protected: + //////////////////////////////////////////////////////////////////////// + // AZ::Component interface implementation + void Init() override; + void Activate() override; + void Deactivate() override; + //////////////////////////////////////////////////////////////////////// + + TerrainSystem* m_terrainSystem{ nullptr }; + }; +} diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSystemComponent.cpp b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSystemComponent.cpp new file mode 100644 index 0000000000..7fa35cc81c --- /dev/null +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSystemComponent.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +namespace Terrain +{ + void EditorTerrainSystemComponent::Reflect(AZ::ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class()->Version(1); + } + } + + void EditorTerrainSystemComponent::Activate() + { + AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); + } + + void EditorTerrainSystemComponent::Deactivate() + { + AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect(); + } + +} // namespace Terrain diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSystemComponent.h b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSystemComponent.h new file mode 100644 index 0000000000..274e561ace --- /dev/null +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSystemComponent.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +#include + +namespace Terrain +{ + /// System component for Terrain editor + class EditorTerrainSystemComponent + : public AZ::Component + , private AzToolsFramework::EditorEvents::Bus::Handler + { + public: + AZ_COMPONENT(EditorTerrainSystemComponent, "{5E9f2200-9099-4325-BABD-6A533A1ABEA8}"); + static void Reflect(AZ::ReflectContext* context); + + EditorTerrainSystemComponent() = default; + + private: + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC_CE("TerrainEditorService")); + } + + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + required.push_back(AZ_CRC_CE("TerrainService")); + } + + // AZ::Component + void Activate() override; + void Deactivate() override; + }; +} // namespace Terrain diff --git a/Gems/Terrain/Code/Source/EditorTerrainModule.cpp b/Gems/Terrain/Code/Source/EditorTerrainModule.cpp new file mode 100644 index 0000000000..bd4c94f4bf --- /dev/null +++ b/Gems/Terrain/Code/Source/EditorTerrainModule.cpp @@ -0,0 +1,36 @@ +/* + * 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 Terrain +{ + EditorTerrainModule::EditorTerrainModule() + { + m_descriptors.insert( + m_descriptors.end(), + { + Terrain::EditorTerrainSystemComponent::CreateDescriptor(), + }); + } + + AZ::ComponentTypeList EditorTerrainModule::GetRequiredSystemComponents() const + { + AZ::ComponentTypeList requiredComponents = TerrainModule::GetRequiredSystemComponents(); + requiredComponents.insert( + requiredComponents.end(), + { + azrtti_typeid(), + }); + + return requiredComponents; + } +} + +AZ_DECLARE_MODULE_CLASS(Gem_TerrainEditor, Terrain::EditorTerrainModule) diff --git a/Gems/Terrain/Code/Source/EditorTerrainModule.h b/Gems/Terrain/Code/Source/EditorTerrainModule.h new file mode 100644 index 0000000000..76c4706478 --- /dev/null +++ b/Gems/Terrain/Code/Source/EditorTerrainModule.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace Terrain +{ + class EditorTerrainModule + : public TerrainModule + { + public: + AZ_RTTI(EditorTerrainModule, "{68693F28-7051-4C14-85EA-DE6FD8CFCBD6}", TerrainModule); + AZ_CLASS_ALLOCATOR(EditorTerrainModule, AZ::SystemAllocator, 0); + + EditorTerrainModule(); + + AZ::ComponentTypeList GetRequiredSystemComponents() const override; + }; +} diff --git a/Gems/Terrain/Code/Source/TerrainModule.cpp b/Gems/Terrain/Code/Source/TerrainModule.cpp new file mode 100644 index 0000000000..ec9325eb5c --- /dev/null +++ b/Gems/Terrain/Code/Source/TerrainModule.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +#include +#include +#include + +namespace Terrain +{ + TerrainModule::TerrainModule() + : AZ::Module() + { + m_descriptors.insert(m_descriptors.end(), { + TerrainSystemComponent::CreateDescriptor(), + TerrainSurfaceDataSystemComponent::CreateDescriptor(), + }); + } + + AZ::ComponentTypeList TerrainModule::GetRequiredSystemComponents() const + { + return AZ::ComponentTypeList{ + azrtti_typeid(), + azrtti_typeid(), + }; + } +} + +#if !defined(TERRAIN_EDITOR) +// DO NOT MODIFY THIS LINE UNLESS YOU RENAME THE GEM +// The first parameter should be GemName_GemIdLower +// The second should be the fully qualified name of the class above +AZ_DECLARE_MODULE_CLASS(Gem_Terrain, Terrain::TerrainModule) +#endif + diff --git a/Gems/Terrain/Code/Source/TerrainModule.h b/Gems/Terrain/Code/Source/TerrainModule.h new file mode 100644 index 0000000000..c665ee44eb --- /dev/null +++ b/Gems/Terrain/Code/Source/TerrainModule.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace Terrain +{ + class TerrainModule + : public AZ::Module + { + public: + AZ_RTTI(TerrainModule, "{B1CFB3A0-EA27-4AF0-A16D-E943C98FED88}", AZ::Module); + AZ_CLASS_ALLOCATOR(TerrainModule, AZ::SystemAllocator, 0); + + TerrainModule(); + + AZ::ComponentTypeList GetRequiredSystemComponents() const override; + }; +} diff --git a/Gems/Terrain/Code/Tests/TerrainEditorTest.cpp b/Gems/Terrain/Code/Tests/TerrainEditorTest.cpp new file mode 100644 index 0000000000..47492dfe40 --- /dev/null +++ b/Gems/Terrain/Code/Tests/TerrainEditorTest.cpp @@ -0,0 +1,31 @@ +/* + * 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 + +class TerrainEditorTest + : public ::testing::Test +{ +protected: + void SetUp() override + { + + } + + void TearDown() override + { + + } +}; + +TEST_F(TerrainEditorTest, SanityTest) +{ + ASSERT_TRUE(true); +} + +AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Gems/Terrain/Code/Tests/TerrainTest.cpp b/Gems/Terrain/Code/Tests/TerrainTest.cpp new file mode 100644 index 0000000000..9b47c91a31 --- /dev/null +++ b/Gems/Terrain/Code/Tests/TerrainTest.cpp @@ -0,0 +1,31 @@ +/* + * 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 + +class TerrainTest + : public ::testing::Test +{ +protected: + void SetUp() override + { + + } + + void TearDown() override + { + + } +}; + +TEST_F(TerrainTest, SanityTest) +{ + ASSERT_TRUE(true); +} + +AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Gems/Terrain/Code/terrain_editor_shared_files.cmake b/Gems/Terrain/Code/terrain_editor_shared_files.cmake new file mode 100644 index 0000000000..68ec9aeb54 --- /dev/null +++ b/Gems/Terrain/Code/terrain_editor_shared_files.cmake @@ -0,0 +1,16 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +set(FILES + Source/EditorComponents/EditorTerrainSystemComponent.cpp + Source/EditorComponents/EditorTerrainSystemComponent.h + Source/EditorTerrainModule.cpp + Source/EditorTerrainModule.h + Source/TerrainModule.cpp + Source/TerrainModule.h +) diff --git a/Gems/RADTelemetry/Code/radtelemetry_shared_files.cmake b/Gems/Terrain/Code/terrain_editor_tests_files.cmake similarity index 86% rename from Gems/RADTelemetry/Code/radtelemetry_shared_files.cmake rename to Gems/Terrain/Code/terrain_editor_tests_files.cmake index 9b07af44d4..d5d0ec5393 100644 --- a/Gems/RADTelemetry/Code/radtelemetry_shared_files.cmake +++ b/Gems/Terrain/Code/terrain_editor_tests_files.cmake @@ -7,5 +7,5 @@ # set(FILES - Source/RADTelemetryModule.cpp + Tests/TerrainEditorTest.cpp ) diff --git a/Code/Framework/AzCore/Platform/Common/azcore_profile_telemetry_files.cmake b/Gems/Terrain/Code/terrain_files.cmake similarity index 51% rename from Code/Framework/AzCore/Platform/Common/azcore_profile_telemetry_files.cmake rename to Gems/Terrain/Code/terrain_files.cmake index d23f8df790..c67d0c63b4 100644 --- a/Code/Framework/AzCore/Platform/Common/azcore_profile_telemetry_files.cmake +++ b/Gems/Terrain/Code/terrain_files.cmake @@ -7,6 +7,8 @@ # set(FILES - RadTelemetry/ProfileTelemetry.h - RadTelemetry/ProfileTelemetryBus.h + Source/Components/TerrainSurfaceDataSystemComponent.cpp + Source/Components/TerrainSurfaceDataSystemComponent.h + Source/Components/TerrainSystemComponent.cpp + Source/Components/TerrainSystemComponent.h ) diff --git a/Gems/Terrain/Code/terrain_shared_files.cmake b/Gems/Terrain/Code/terrain_shared_files.cmake new file mode 100644 index 0000000000..211182b0fa --- /dev/null +++ b/Gems/Terrain/Code/terrain_shared_files.cmake @@ -0,0 +1,12 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +set(FILES + Source/TerrainModule.h + Source/TerrainModule.cpp +) diff --git a/Gems/RADTelemetry/Code/Source/Platform/Linux/platform_linux_files.cmake b/Gems/Terrain/Code/terrain_tests_files.cmake similarity index 86% rename from Gems/RADTelemetry/Code/Source/Platform/Linux/platform_linux_files.cmake rename to Gems/Terrain/Code/terrain_tests_files.cmake index 6e7a9dd5eb..beed6bd83d 100644 --- a/Gems/RADTelemetry/Code/Source/Platform/Linux/platform_linux_files.cmake +++ b/Gems/Terrain/Code/terrain_tests_files.cmake @@ -7,5 +7,5 @@ # set(FILES - RADTelemetry_Traits_Platform.h + Tests/TerrainTest.cpp ) diff --git a/Gems/Terrain/gem.json b/Gems/Terrain/gem.json new file mode 100644 index 0000000000..ccf034d399 --- /dev/null +++ b/Gems/Terrain/gem.json @@ -0,0 +1,10 @@ +{ + "gem_name": "Terrain", + "display_name": "Terrain (WIP)", + "license": "Apache-2.0 Or MIT", + "origin": "Open 3D Engine - o3de.org", + "summary": "The Terrain Gem is a WIP (work-in-progress) Gem for providing terrain services including authoring workflows, rendering, and physics.", + "canonical_tags": [ "Gem" ], + "user_tags": [ "Environment", "Terrain" ], + "icon_path": "preview.png" +} diff --git a/Gems/RADTelemetry/preview.png b/Gems/Terrain/preview.png similarity index 100% rename from Gems/RADTelemetry/preview.png rename to Gems/Terrain/preview.png diff --git a/Gems/Vegetation/Code/Source/AreaSystemComponent.cpp b/Gems/Vegetation/Code/Source/AreaSystemComponent.cpp index 7ce1a2c0a3..4ffed260de 100644 --- a/Gems/Vegetation/Code/Source/AreaSystemComponent.cpp +++ b/Gems/Vegetation/Code/Source/AreaSystemComponent.cpp @@ -617,7 +617,7 @@ namespace Vegetation void AreaSystemComponent::EnumerateInstancesInOverlappingSectors(const AZ::Aabb& bounds, AreaSystemEnumerateCallback callback) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (!bounds.IsValid()) { @@ -644,7 +644,7 @@ namespace Vegetation void AreaSystemComponent::EnumerateInstancesInAabb(const AZ::Aabb& bounds, AreaSystemEnumerateCallback callback) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (!bounds.IsValid()) { @@ -723,7 +723,7 @@ namespace Vegetation void AreaSystemComponent::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (m_configuration.m_sectorSizeInMeters < 0) { @@ -792,7 +792,7 @@ namespace Vegetation m_threadData.m_vegetationThreadState = PersistentThreadData::VegetationThreadState::Running; auto job = AZ::CreateJobFunction([this]() { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Entity, "Vegetation::AreaSystemComponent::VegetationThread"); + AZ_PROFILE_SCOPE(Entity, "Vegetation::AreaSystemComponent::VegetationThread"); UpdateContext context; context.Run(&m_threadData, &m_vegTasks, &m_cachedMainThreadData); @@ -830,7 +830,7 @@ namespace Vegetation bool AreaSystemComponent::CalculateViewRect() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); //Get the active camera. bool cameraPositionIsValid = false; @@ -983,7 +983,7 @@ namespace Vegetation void AreaSystemComponent::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); switch (event) { @@ -1016,7 +1016,7 @@ namespace Vegetation void AreaSystemComponent::VegetationThreadTasks::ProcessVegetationThreadTasks(UpdateContext* context, PersistentThreadData* threadData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); VegetationThreadTasks::VegetationThreadTaskList tasks; { @@ -1056,7 +1056,7 @@ namespace Vegetation const AreaSystemComponent::SectorInfo* AreaSystemComponent::VegetationThreadTasks::GetSector(const SectorId& sectorId) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_sectorRollingWindowMutex); auto itSector = m_sectorRollingWindow.find(sectorId); @@ -1065,7 +1065,7 @@ namespace Vegetation AreaSystemComponent::SectorInfo* AreaSystemComponent::VegetationThreadTasks::GetSector(const SectorId& sectorId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_sectorRollingWindowMutex); auto itSector = m_sectorRollingWindow.find(sectorId); @@ -1074,7 +1074,7 @@ namespace Vegetation AreaSystemComponent::SectorInfo* AreaSystemComponent::VegetationThreadTasks::CreateSector(const SectorId& sectorId, int sectorDensity, int sectorSizeInMeters, SnapMode sectorPointSnapMode) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); SectorInfo sectorInfo; sectorInfo.m_id = sectorId; @@ -1089,7 +1089,7 @@ namespace Vegetation void AreaSystemComponent::VegetationThreadTasks::UpdateSectorPoints(SectorInfo& sectorInfo, int sectorDensity, int sectorSizeInMeters, SnapMode sectorPointSnapMode) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const float vegStep = sectorSizeInMeters / static_cast(sectorDensity); //build a free list of all points in the sector for areas to consume @@ -1190,7 +1190,7 @@ namespace Vegetation void AreaSystemComponent::VegetationThreadTasks::DeleteSector(const SectorId& sectorId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_sectorRollingWindowMutex); auto itSector = m_sectorRollingWindow.find(sectorId); @@ -1249,7 +1249,7 @@ namespace Vegetation void AreaSystemComponent::VegetationThreadTasks::ReleaseUnregisteredClaims(SectorInfo& sectorInfo) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (!m_unregisteredVegetationAreaSet.empty()) { @@ -1275,7 +1275,7 @@ namespace Vegetation void AreaSystemComponent::VegetationThreadTasks::ReleaseUnusedClaims(SectorInfo& sectorInfo) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::unordered_map> claimsToRelease; @@ -1310,7 +1310,7 @@ namespace Vegetation void AreaSystemComponent::VegetationThreadTasks::FillSector(SectorInfo& sectorInfo, const VegetationAreaVector& activeAreas) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); VEG_PROFILE_METHOD(DebugNotificationBus::TryQueueBroadcast(&DebugNotificationBus::Events::FillSectorStart, sectorInfo.GetSectorX(), sectorInfo.GetSectorY(), AZStd::chrono::system_clock::now())); ReleaseUnregisteredClaims(sectorInfo); @@ -1352,7 +1352,7 @@ namespace Vegetation void AreaSystemComponent::VegetationThreadTasks::EmptySector(SectorInfo& sectorInfo) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::unordered_map> claimsToRelease; @@ -1384,7 +1384,7 @@ namespace Vegetation void AreaSystemComponent::VegetationThreadTasks::ClearSectors() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_sectorRollingWindowMutex); for (auto& sectorPair : m_sectorRollingWindow) @@ -1399,13 +1399,13 @@ namespace Vegetation void AreaSystemComponent::VegetationThreadTasks::CreateClaim(SectorInfo& sectorInfo, const ClaimHandle handle, const InstanceData& instanceData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); sectorInfo.m_claimedWorldPoints[handle] = instanceData; } ClaimHandle AreaSystemComponent::VegetationThreadTasks::CreateClaimHandle(const SectorInfo& sectorInfo, uint32_t index) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); ClaimHandle handle = 0; AreaSystemUtil::hash_combine_64(handle, sectorInfo.m_id.first); @@ -1456,7 +1456,7 @@ namespace Vegetation void AreaSystemComponent::UpdateContext::Run(PersistentThreadData* threadData, VegetationThreadTasks* vegTasks, CachedMainThreadData* cachedMainThreadData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); // Ensure that the main thread doesn't activate or deactivate the component until after this thread finishes. // Note that this does *not* prevent the main thread from running OnTick, which can communicate data changes @@ -1466,7 +1466,7 @@ namespace Vegetation bool keepProcessing = true; while (keepProcessing && (threadData->m_vegetationThreadState != PersistentThreadData::VegetationThreadState::InterruptRequested)) { - AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Entity, "Vegetation::AreaSystemComponent::UpdateContext::Run-InnerLoop"); + AZ_PROFILE_SCOPE(Entity, "Vegetation::AreaSystemComponent::UpdateContext::Run-InnerLoop"); // Update thread state if its dirty PersistentThreadData::VegetationDataSyncState expected = PersistentThreadData::VegetationDataSyncState::Dirty; if (threadData->m_vegetationDataSyncState.compare_exchange_strong(expected, PersistentThreadData::VegetationDataSyncState::Updating)) @@ -1501,7 +1501,7 @@ namespace Vegetation void AreaSystemComponent::UpdateContext::UpdateActiveVegetationAreas(PersistentThreadData* threadData, const ViewRect& viewRect) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); //build a priority sorted list of all active areas if (threadData->m_activeAreasDirty) @@ -1553,7 +1553,7 @@ namespace Vegetation bool AreaSystemComponent::UpdateContext::UpdateSectorWorkLists(PersistentThreadData* threadData, VegetationThreadTasks* vegTasks) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); auto& worldToSector = m_cachedMainThreadData.m_worldToSector; auto& currViewRect = m_cachedMainThreadData.m_currViewRect; @@ -1761,7 +1761,7 @@ namespace Vegetation bool AreaSystemComponent::UpdateContext::UpdateOneSector(PersistentThreadData* threadData, VegetationThreadTasks* vegTasks) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); // This chooses work in the following order: // 1) Delete if we have more sectors than the total that should be in the view rectangle diff --git a/Gems/Vegetation/Code/Source/Components/AreaBlenderComponent.cpp b/Gems/Vegetation/Code/Source/Components/AreaBlenderComponent.cpp index d31a6be69d..8bf48de58e 100644 --- a/Gems/Vegetation/Code/Source/Components/AreaBlenderComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/AreaBlenderComponent.cpp @@ -220,7 +220,7 @@ namespace Vegetation bool AreaBlenderComponent::PrepareToClaim(EntityIdStack& stackIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); bool result = true; @@ -257,7 +257,7 @@ namespace Vegetation void AreaBlenderComponent::ClaimPositions(EntityIdStack& stackIds, ClaimContext& context) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (context.m_availablePoints.empty()) { @@ -293,7 +293,7 @@ namespace Vegetation void AreaBlenderComponent::UnclaimPosition(const ClaimHandle handle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZ_WarningOnce("Vegetation", !m_isRequestInProgress, "Detected cyclic dependences with vegetation entity references"); if (!m_isRequestInProgress) @@ -311,7 +311,7 @@ namespace Vegetation AZ::Aabb AreaBlenderComponent::GetEncompassingAabb() const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZ::Aabb bounds = AZ::Aabb::CreateNull(); @@ -340,7 +340,7 @@ namespace Vegetation AZ::u32 AreaBlenderComponent::GetProductCount() const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZ::u32 count = 0; diff --git a/Gems/Vegetation/Code/Source/Components/AreaComponentBase.cpp b/Gems/Vegetation/Code/Source/Components/AreaComponentBase.cpp index 6e87154e5b..6a9060c6d4 100644 --- a/Gems/Vegetation/Code/Source/Components/AreaComponentBase.cpp +++ b/Gems/Vegetation/Code/Source/Components/AreaComponentBase.cpp @@ -279,13 +279,13 @@ namespace Vegetation void AreaComponentBase::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& /*world*/) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); OnCompositionChanged(); } void AreaComponentBase::OnShapeChanged([[maybe_unused]] ShapeComponentNotifications::ShapeChangeReasons reasons) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); OnCompositionChanged(); } } diff --git a/Gems/Vegetation/Code/Source/Components/BlockerComponent.cpp b/Gems/Vegetation/Code/Source/Components/BlockerComponent.cpp index d980f7e45a..e26f1aee47 100644 --- a/Gems/Vegetation/Code/Source/Components/BlockerComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/BlockerComponent.cpp @@ -185,7 +185,7 @@ namespace Vegetation bool BlockerComponent::ClaimPosition(EntityIdStack& processedIds, const ClaimPoint& point, InstanceData& instanceData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); #if VEG_BLOCKER_ENABLE_CACHING { @@ -245,7 +245,7 @@ namespace Vegetation void BlockerComponent::ClaimPositions(EntityIdStack& stackIds, ClaimContext& context) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); //adding entity id to the stack of entity ids affecting vegetation EntityIdStack emptyIds; @@ -285,7 +285,7 @@ namespace Vegetation AZ::Aabb BlockerComponent::GetEncompassingAabb() const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZ::Aabb bounds = AZ::Aabb::CreateNull(); LmbrCentral::ShapeComponentRequestsBus::EventResult(bounds, GetEntityId(), &LmbrCentral::ShapeComponentRequestsBus::Events::GetEncompassingAabb); diff --git a/Gems/Vegetation/Code/Source/Components/DescriptorListCombinerComponent.cpp b/Gems/Vegetation/Code/Source/Components/DescriptorListCombinerComponent.cpp index bcb42fb2e3..abdec31b98 100644 --- a/Gems/Vegetation/Code/Source/Components/DescriptorListCombinerComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/DescriptorListCombinerComponent.cpp @@ -187,7 +187,7 @@ namespace Vegetation void DescriptorListCombinerComponent::GetDescriptors(DescriptorPtrVec& descriptors) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); for (const auto& entityId : m_configuration.m_descriptorProviders) { @@ -200,7 +200,7 @@ namespace Vegetation void DescriptorListCombinerComponent::GetInclusionSurfaceTags(SurfaceData::SurfaceTagVector& tags, bool& includeAll) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); for (const auto& entityId : m_configuration.m_descriptorProviders) { @@ -213,7 +213,7 @@ namespace Vegetation void DescriptorListCombinerComponent::GetExclusionSurfaceTags(SurfaceData::SurfaceTagVector& tags) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); for (const auto& entityId : m_configuration.m_descriptorProviders) { diff --git a/Gems/Vegetation/Code/Source/Components/DescriptorWeightSelectorComponent.cpp b/Gems/Vegetation/Code/Source/Components/DescriptorWeightSelectorComponent.cpp index 5e4781302d..093de396dd 100644 --- a/Gems/Vegetation/Code/Source/Components/DescriptorWeightSelectorComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/DescriptorWeightSelectorComponent.cpp @@ -144,7 +144,7 @@ namespace Vegetation void DescriptorWeightSelectorComponent::SelectDescriptors(const DescriptorSelectorParams& params, DescriptorPtrVec& descriptors) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); switch (m_configuration.m_sortBehavior) { diff --git a/Gems/Vegetation/Code/Source/Components/DistanceBetweenFilterComponent.cpp b/Gems/Vegetation/Code/Source/Components/DistanceBetweenFilterComponent.cpp index 489862a797..e6d5701f64 100644 --- a/Gems/Vegetation/Code/Source/Components/DistanceBetweenFilterComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/DistanceBetweenFilterComponent.cpp @@ -187,7 +187,7 @@ namespace Vegetation bool DistanceBetweenFilterComponent::Evaluate(const InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); bool intersects = false; diff --git a/Gems/Vegetation/Code/Source/Components/DistributionFilterComponent.cpp b/Gems/Vegetation/Code/Source/Components/DistributionFilterComponent.cpp index 18a83347d4..2505b243ad 100644 --- a/Gems/Vegetation/Code/Source/Components/DistributionFilterComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/DistributionFilterComponent.cpp @@ -188,7 +188,7 @@ namespace Vegetation bool DistributionFilterComponent::Evaluate(const InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const GradientSignal::GradientSampleParams sampleParams(instanceData.m_position); const float noise = m_configuration.m_gradientSampler.GetValue(sampleParams); diff --git a/Gems/Vegetation/Code/Source/Components/MeshBlockerComponent.cpp b/Gems/Vegetation/Code/Source/Components/MeshBlockerComponent.cpp index 58f23bff72..52461e691c 100644 --- a/Gems/Vegetation/Code/Source/Components/MeshBlockerComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/MeshBlockerComponent.cpp @@ -197,7 +197,7 @@ namespace Vegetation bool MeshBlockerComponent::PrepareToClaim([[maybe_unused]] EntityIdStack& stackIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard cacheLock(m_cacheMutex); @@ -217,7 +217,7 @@ namespace Vegetation bool MeshBlockerComponent::ClaimPosition(EntityIdStack& processedIds, const ClaimPoint& point, InstanceData& instanceData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard cacheLock(m_cacheMutex); @@ -283,7 +283,7 @@ namespace Vegetation void MeshBlockerComponent::ClaimPositions(EntityIdStack& stackIds, ClaimContext& context) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); //adding entity id to the stack of entity ids affecting vegetation EntityIdStack emptyIds; @@ -371,7 +371,7 @@ namespace Vegetation void MeshBlockerComponent::UpdateMeshData() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard cacheLock(m_cacheMutex); diff --git a/Gems/Vegetation/Code/Source/Components/PositionModifierComponent.cpp b/Gems/Vegetation/Code/Source/Components/PositionModifierComponent.cpp index 4d3b4f9867..17457786f2 100644 --- a/Gems/Vegetation/Code/Source/Components/PositionModifierComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/PositionModifierComponent.cpp @@ -281,7 +281,7 @@ namespace Vegetation void PositionModifierComponent::Execute(InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const GradientSignal::GradientSampleParams sampleParams(instanceData.m_position); float factorX = m_configuration.m_gradientSamplerX.GetValue(sampleParams); diff --git a/Gems/Vegetation/Code/Source/Components/RotationModifierComponent.cpp b/Gems/Vegetation/Code/Source/Components/RotationModifierComponent.cpp index df52222edb..1c13c08c2f 100644 --- a/Gems/Vegetation/Code/Source/Components/RotationModifierComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/RotationModifierComponent.cpp @@ -239,7 +239,7 @@ namespace Vegetation void RotationModifierComponent::Execute(InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const GradientSignal::GradientSampleParams sampleParams(instanceData.m_position); float factorX = m_configuration.m_gradientSamplerX.GetValue(sampleParams); diff --git a/Gems/Vegetation/Code/Source/Components/ScaleModifierComponent.cpp b/Gems/Vegetation/Code/Source/Components/ScaleModifierComponent.cpp index 74d11d6f6c..8c8099599d 100644 --- a/Gems/Vegetation/Code/Source/Components/ScaleModifierComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/ScaleModifierComponent.cpp @@ -162,7 +162,7 @@ namespace Vegetation void ScaleModifierComponent::Execute(InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const GradientSignal::GradientSampleParams sampleParams(instanceData.m_position); float factor = m_configuration.m_gradientSampler.GetValue(sampleParams); diff --git a/Gems/Vegetation/Code/Source/Components/ShapeIntersectionFilterComponent.cpp b/Gems/Vegetation/Code/Source/Components/ShapeIntersectionFilterComponent.cpp index 27dabfd76e..968d711e04 100644 --- a/Gems/Vegetation/Code/Source/Components/ShapeIntersectionFilterComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/ShapeIntersectionFilterComponent.cpp @@ -147,7 +147,7 @@ namespace Vegetation bool ShapeIntersectionFilterComponent::Evaluate(const InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); bool inside = false; LmbrCentral::ShapeComponentRequestsBus::EventResult(inside, m_configuration.m_shapeEntityId, &LmbrCentral::ShapeComponentRequestsBus::Events::IsPointInside, instanceData.m_position); diff --git a/Gems/Vegetation/Code/Source/Components/SlopeAlignmentModifierComponent.cpp b/Gems/Vegetation/Code/Source/Components/SlopeAlignmentModifierComponent.cpp index 75a468b751..5e8e784bc6 100644 --- a/Gems/Vegetation/Code/Source/Components/SlopeAlignmentModifierComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/SlopeAlignmentModifierComponent.cpp @@ -159,7 +159,7 @@ namespace Vegetation void SlopeAlignmentModifierComponent::Execute(InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const bool useOverrides = m_configuration.m_allowOverrides && instanceData.m_descriptorPtr && instanceData.m_descriptorPtr->m_surfaceAlignmentOverrideEnabled; const float min = useOverrides ? instanceData.m_descriptorPtr->m_surfaceAlignmentMin : m_configuration.m_rangeMin; diff --git a/Gems/Vegetation/Code/Source/Components/SpawnerComponent.cpp b/Gems/Vegetation/Code/Source/Components/SpawnerComponent.cpp index b373edf051..404e425489 100644 --- a/Gems/Vegetation/Code/Source/Components/SpawnerComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/SpawnerComponent.cpp @@ -206,7 +206,7 @@ namespace Vegetation bool SpawnerComponent::PrepareToClaim(EntityIdStack& stackIds) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); //adding entity id to the stack of entity ids affecting vegetation EntityIdStack emptyIds; @@ -259,7 +259,7 @@ namespace Vegetation bool SpawnerComponent::CreateInstance([[maybe_unused]] const ClaimPoint &point, InstanceData& instanceData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); instanceData.m_instanceId = InvalidInstanceId; if (instanceData.m_descriptorPtr && instanceData.m_descriptorPtr->IsSpawnable()) @@ -279,7 +279,7 @@ namespace Vegetation bool SpawnerComponent::EvaluateFilters(EntityIdStack& processedIds, InstanceData& instanceData, const FilterStage intendedStage) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); bool accepted = true; for (const auto& id : processedIds) @@ -302,7 +302,7 @@ namespace Vegetation bool SpawnerComponent::ProcessInstance(EntityIdStack& processedIds, const ClaimPoint& point, InstanceData& instanceData, DescriptorPtr descriptorPtr) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (!descriptorPtr) { @@ -353,7 +353,7 @@ namespace Vegetation bool SpawnerComponent::ClaimPosition(EntityIdStack& processedIds, const ClaimPoint& point, InstanceData& instanceData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); #if VEG_SPAWNER_ENABLE_CACHING { @@ -413,7 +413,7 @@ namespace Vegetation void SpawnerComponent::ClaimPositions(EntityIdStack& stackIds, ClaimContext& context) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); //reject entire spawner if there are inclusion tags to consider that don't exist in the context if (SurfaceData::HasValidTags(context.m_masks) && @@ -497,7 +497,7 @@ namespace Vegetation void SpawnerComponent::UnclaimPosition(const ClaimHandle handle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); InstanceId instanceId = InvalidInstanceId; { @@ -518,7 +518,7 @@ namespace Vegetation AZ::Aabb SpawnerComponent::GetEncompassingAabb() const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZ::Aabb bounds = AZ::Aabb::CreateNull(); LmbrCentral::ShapeComponentRequestsBus::EventResult(bounds, GetEntityId(), &LmbrCentral::ShapeComponentRequestsBus::Events::GetEncompassingAabb); @@ -533,7 +533,7 @@ namespace Vegetation void SpawnerComponent::OnCompositionChanged() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AreaComponentBase::OnCompositionChanged(); #if VEG_SPAWNER_ENABLE_CACHING @@ -546,7 +546,7 @@ namespace Vegetation void SpawnerComponent::DestroyAllInstances() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); ClaimInstanceMapping claimInstanceMapping; { diff --git a/Gems/Vegetation/Code/Source/Components/SurfaceAltitudeFilterComponent.cpp b/Gems/Vegetation/Code/Source/Components/SurfaceAltitudeFilterComponent.cpp index e2a1404bf1..1f1dfd7a54 100644 --- a/Gems/Vegetation/Code/Source/Components/SurfaceAltitudeFilterComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/SurfaceAltitudeFilterComponent.cpp @@ -175,7 +175,7 @@ namespace Vegetation bool SurfaceAltitudeFilterComponent::Evaluate(const InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const bool useOverrides = m_configuration.m_allowOverrides && instanceData.m_descriptorPtr && instanceData.m_descriptorPtr->m_altitudeFilterOverrideEnabled; const float min = useOverrides ? instanceData.m_descriptorPtr->m_altitudeFilterMin : m_configuration.m_altitudeMin; diff --git a/Gems/Vegetation/Code/Source/Components/SurfaceMaskDepthFilterComponent.cpp b/Gems/Vegetation/Code/Source/Components/SurfaceMaskDepthFilterComponent.cpp index f4bd07e816..b4e65beb3f 100644 --- a/Gems/Vegetation/Code/Source/Components/SurfaceMaskDepthFilterComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/SurfaceMaskDepthFilterComponent.cpp @@ -203,7 +203,7 @@ namespace Vegetation bool SurfaceMaskDepthFilterComponent::Evaluate(const InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const bool useOverrides = m_configuration.m_allowOverrides && instanceData.m_descriptorPtr && !instanceData.m_descriptorPtr->m_surfaceTagDistance.m_tags.empty(); const SurfaceData::SurfaceTagVector& surfaceTagsToCompare = useOverrides ? instanceData.m_descriptorPtr->m_surfaceTagDistance.m_tags : m_configuration.m_depthComparisonTags; diff --git a/Gems/Vegetation/Code/Source/Components/SurfaceMaskFilterComponent.cpp b/Gems/Vegetation/Code/Source/Components/SurfaceMaskFilterComponent.cpp index 8dd9821cb1..9be6764460 100644 --- a/Gems/Vegetation/Code/Source/Components/SurfaceMaskFilterComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/SurfaceMaskFilterComponent.cpp @@ -268,7 +268,7 @@ namespace Vegetation bool SurfaceMaskFilterComponent::Evaluate(const InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); //determine if tags provided by the component should be considered bool useCompTags = !m_configuration.m_allowOverrides || (instanceData.m_descriptorPtr && instanceData.m_descriptorPtr->m_surfaceFilterOverrideMode != OverrideMode::Replace); diff --git a/Gems/Vegetation/Code/Source/Components/SurfaceSlopeFilterComponent.cpp b/Gems/Vegetation/Code/Source/Components/SurfaceSlopeFilterComponent.cpp index b99c2b7c81..fb0673bdf2 100644 --- a/Gems/Vegetation/Code/Source/Components/SurfaceSlopeFilterComponent.cpp +++ b/Gems/Vegetation/Code/Source/Components/SurfaceSlopeFilterComponent.cpp @@ -162,7 +162,7 @@ namespace Vegetation bool SurfaceSlopeFilterComponent::Evaluate(const InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); const bool useOverrides = m_configuration.m_allowOverrides && instanceData.m_descriptorPtr && instanceData.m_descriptorPtr->m_slopeFilterOverrideEnabled; const float min = useOverrides ? instanceData.m_descriptorPtr->m_slopeFilterMin : m_configuration.m_slopeMin; diff --git a/Gems/Vegetation/Code/Source/InstanceSystemComponent.cpp b/Gems/Vegetation/Code/Source/InstanceSystemComponent.cpp index 74fb2696ea..d4185fde6c 100644 --- a/Gems/Vegetation/Code/Source/InstanceSystemComponent.cpp +++ b/Gems/Vegetation/Code/Source/InstanceSystemComponent.cpp @@ -169,7 +169,7 @@ namespace Vegetation DescriptorPtr InstanceSystemComponent::RegisterUniqueDescriptor(const Descriptor& descriptor) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_uniqueDescriptorsMutex); @@ -217,7 +217,7 @@ namespace Vegetation void InstanceSystemComponent::ReleaseUniqueDescriptor(DescriptorPtr descriptorPtr) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard lock(m_uniqueDescriptorsMutex); @@ -267,7 +267,7 @@ namespace Vegetation void InstanceSystemComponent::CreateInstance(InstanceData& instanceData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (!IsDescriptorValid(instanceData.m_descriptorPtr)) { @@ -299,7 +299,7 @@ namespace Vegetation void InstanceSystemComponent::DestroyInstance(InstanceId instanceId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (instanceId == InvalidInstanceId) { @@ -439,7 +439,7 @@ namespace Vegetation bool InstanceSystemComponent::IsInstanceSkippable(const InstanceData& instanceData) const { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); //if the instance was queued for deletion before its creation task executed then skip it AZStd::lock_guard instanceDeletionSet(m_instanceDeletionSetMutex); @@ -448,7 +448,7 @@ namespace Vegetation void InstanceSystemComponent::CreateInstanceNode(const InstanceData& instanceData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); if (IsInstanceSkippable(instanceData)) { @@ -489,7 +489,7 @@ namespace Vegetation void InstanceSystemComponent::ReleaseInstanceNode(InstanceId instanceId) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); DescriptorPtr descriptor = nullptr; InstancePtr opaqueInstanceData = nullptr; @@ -521,7 +521,7 @@ namespace Vegetation void InstanceSystemComponent::AddTask(const Task& task) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard mainThreadTaskLock(m_mainThreadTaskMutex); if (m_mainThreadTaskQueue.empty() || m_mainThreadTaskQueue.back().size() >= m_configuration.m_maxInstanceTaskBatchSize) @@ -534,7 +534,7 @@ namespace Vegetation void InstanceSystemComponent::ClearTasks() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard mainThreadTaskInProgressLock(m_mainThreadTaskInProgressMutex); AZStd::lock_guard mainThreadTaskLock(m_mainThreadTaskMutex); @@ -546,7 +546,7 @@ namespace Vegetation bool InstanceSystemComponent::GetTasks(TaskList& removedTasks) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard mainThreadTaskLock(m_mainThreadTaskMutex); if (!m_mainThreadTaskQueue.empty()) @@ -559,7 +559,7 @@ namespace Vegetation void InstanceSystemComponent::ExecuteTasks() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); AZStd::lock_guard scopedLock(m_mainThreadTaskInProgressMutex); @@ -588,7 +588,7 @@ namespace Vegetation void InstanceSystemComponent::ProcessMainThreadTasks() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Entity); + AZ_PROFILE_FUNCTION(Entity); ExecuteTasks(); } diff --git a/Gems/Vegetation/Code/Source/VegetationSystemComponent.cpp b/Gems/Vegetation/Code/Source/VegetationSystemComponent.cpp index dd0e63c15b..345c27d27a 100644 --- a/Gems/Vegetation/Code/Source/VegetationSystemComponent.cpp +++ b/Gems/Vegetation/Code/Source/VegetationSystemComponent.cpp @@ -47,19 +47,24 @@ namespace Vegetation void VegetationSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services) { - services.push_back(AZ_CRC("VegetationSystemService", 0xa2322728)); + services.push_back(AZ_CRC_CE("VegetationSystemService")); } void VegetationSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services) { - services.push_back(AZ_CRC("VegetationSystemService", 0xa2322728)); + services.push_back(AZ_CRC_CE("VegetationSystemService")); } void VegetationSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services) { - services.push_back(AZ_CRC("VegetationAreaSystemService", 0x36da2b62)); - services.push_back(AZ_CRC("VegetationInstanceSystemService", 0x823a6007)); - services.push_back(AZ_CRC("SurfaceDataProviderService", 0xfe9fb95e)); + services.push_back(AZ_CRC_CE("VegetationAreaSystemService")); + services.push_back(AZ_CRC_CE("VegetationInstanceSystemService")); + services.push_back(AZ_CRC_CE("SurfaceDataSystemService")); + } + + void VegetationSystemComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& services) + { + services.push_back(AZ_CRC_CE("SurfaceDataProviderService")); } void VegetationSystemComponent::Reflect(AZ::ReflectContext* context) diff --git a/Gems/Vegetation/Code/Source/VegetationSystemComponent.h b/Gems/Vegetation/Code/Source/VegetationSystemComponent.h index ff4ab17586..bbe92e2cf8 100644 --- a/Gems/Vegetation/Code/Source/VegetationSystemComponent.h +++ b/Gems/Vegetation/Code/Source/VegetationSystemComponent.h @@ -22,6 +22,7 @@ namespace Vegetation static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services); static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services); + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& services); static void Reflect(AZ::ReflectContext* context); VegetationSystemComponent(); diff --git a/Gems/WhiteBox/Code/Source/Core/WhiteBoxToolApi.cpp b/Gems/WhiteBox/Code/Source/Core/WhiteBoxToolApi.cpp index 3bcd2dbd94..961eef2176 100644 --- a/Gems/WhiteBox/Code/Source/Core/WhiteBoxToolApi.cpp +++ b/Gems/WhiteBox/Code/Source/Core/WhiteBoxToolApi.cpp @@ -30,6 +30,7 @@ #include // OpenMesh includes +AZ_PUSH_DISABLE_WARNING(4702, "-Wunknown-warning-option") // OpenMesh\Core\Utils\Property.hh has unreachable code #include #include #include @@ -37,6 +38,7 @@ #include #include #include +AZ_POP_DISABLE_WARNING namespace OpenMesh { @@ -253,7 +255,7 @@ namespace OpenMesh::IO // return binary size of the value static size_t size_of(const value_type& _v) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (_v.empty()) { @@ -274,7 +276,7 @@ namespace OpenMesh::IO static size_t store(std::ostream& _os, const value_type& _v, bool _swap = false) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); size_t bytes = 0; const auto count = static_cast(_v.size()); @@ -291,7 +293,7 @@ namespace OpenMesh::IO static size_t restore(std::istream& _is, value_type& _v, bool _swap = false) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); size_t bytes = 0; uint32_t count = 0; @@ -325,7 +327,7 @@ namespace OpenMesh::IO // return binary size of the value static size_t size_of(const value_type& _v) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (_v.empty()) { @@ -347,7 +349,7 @@ namespace OpenMesh::IO static size_t store(std::ostream& _os, const value_type& _v, bool _swap = false) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); size_t bytes = 0; const auto count = static_cast(_v.size()); @@ -365,7 +367,7 @@ namespace OpenMesh::IO static size_t restore(std::istream& _is, value_type& _v, bool _swap = false) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); size_t bytes = 0; uint32_t count = 0; @@ -483,7 +485,7 @@ namespace WhiteBox FaceHandlesInternal InternalFaceHandlesFromPolygon(const Api::PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); FaceHandlesInternal faceHandlesInternal; faceHandlesInternal.reserve(polygonHandle.m_faceHandles.size()); @@ -586,7 +588,7 @@ namespace WhiteBox VertexHandles MeshVertexHandles(const WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); VertexHandles vertexHandles; vertexHandles.reserve(whiteBox.mesh.n_vertices()); @@ -600,7 +602,7 @@ namespace WhiteBox FaceHandles MeshFaceHandles(const WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); FaceHandles faceHandles; faceHandles.reserve(whiteBox.mesh.n_faces()); @@ -614,7 +616,7 @@ namespace WhiteBox PolygonHandles MeshPolygonHandles(const WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); PolygonPropertyHandle polygonPropsHandle; whiteBox.mesh.get_property_handle(polygonPropsHandle, PolygonProps); @@ -637,7 +639,7 @@ namespace WhiteBox EdgeHandlesCollection PolygonBorderEdgeHandles(const WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const HalfedgeHandlesCollection halfedgeHandlesCollection = PolygonBorderHalfedgeHandles(whiteBox, polygonHandle); @@ -663,7 +665,7 @@ namespace WhiteBox EdgeHandles PolygonBorderEdgeHandlesFlattened(const WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const EdgeHandlesCollection borderEdgeHandlesCollection = PolygonBorderEdgeHandles(whiteBox, polygonHandle); @@ -679,7 +681,7 @@ namespace WhiteBox EdgeHandles MeshPolygonEdgeHandles(const WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto polygonHandles = MeshPolygonHandles(whiteBox); @@ -698,7 +700,7 @@ namespace WhiteBox EdgeHandles MeshEdgeHandles(const WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EdgeHandles edgeHandles; edgeHandles.reserve(whiteBox.mesh.n_edges()); @@ -712,7 +714,7 @@ namespace WhiteBox EdgeTypes MeshUserEdgeHandles(const WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EdgeHandles userEdgeHandles = MeshPolygonEdgeHandles(whiteBox); AZStd::sort(userEdgeHandles.begin(), userEdgeHandles.end()); @@ -732,7 +734,7 @@ namespace WhiteBox AZStd::vector MeshVertexPositions(const WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return VertexPositions(whiteBox, MeshVertexHandles(whiteBox)); } @@ -794,7 +796,7 @@ namespace WhiteBox AZStd::vector FacesPositions(const WhiteBoxMesh& whiteBox, const FaceHandles& faceHandles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::vector triangles; triangles.reserve(faceHandles.size() * 3); @@ -866,7 +868,7 @@ namespace WhiteBox HalfedgeHandles VertexHalfedgeHandles(const WhiteBoxMesh& whiteBox, const VertexHandle vertexHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); HalfedgeHandles outgoingHandles = VertexOutgoingHalfedgeHandles(whiteBox, vertexHandle); HalfedgeHandles incomingHandles = VertexIncomingHalfedgeHandles(whiteBox, vertexHandle); @@ -881,7 +883,7 @@ namespace WhiteBox EdgeHandles VertexEdgeHandles(const WhiteBoxMesh& whiteBox, const VertexHandle vertexHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto omVertexHandle = om_vh(vertexHandle); @@ -898,7 +900,7 @@ namespace WhiteBox const WhiteBoxMesh& whiteBox, const FaceHandle faceHandle, FaceHandles& faceHandles, const AZ::Vector3& normal) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto* const found_fh = AZStd::find(faceHandles.cbegin(), faceHandles.cend(), faceHandle); @@ -917,7 +919,7 @@ namespace WhiteBox static FaceHandle OppositeFaceHandle(const WhiteBoxMesh& whiteBox, const HalfedgeHandle halfedgeHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const HalfedgeHandle oppositeHalfedgeHandle = HalfedgeOppositeHalfedgeHandle(whiteBox, halfedgeHandle); @@ -936,7 +938,7 @@ namespace WhiteBox const WhiteBoxMesh& whiteBox, const FaceHandle faceHandle, FaceHandles& faceHandles, const AZ::Vector3& normal) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (BuildFaceHandles(whiteBox, faceHandle, faceHandles, normal)) { @@ -957,7 +959,7 @@ namespace WhiteBox FaceHandles SideFaceHandles(const WhiteBoxMesh& whiteBox, const FaceHandle faceHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); FaceHandles faceHandles; SideFaceHandlesInternal( @@ -969,7 +971,7 @@ namespace WhiteBox static HalfedgeHandlesCollection BorderHalfedgeHandles( const WhiteBoxMesh& whiteBox, const FaceHandles& faceHandles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // build all possible halfedge handles HalfedgeHandles halfedgeHandles; @@ -1069,7 +1071,7 @@ namespace WhiteBox HalfedgeHandlesCollection SideBorderHalfedgeHandles(const WhiteBoxMesh& whiteBox, const FaceHandle faceHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // find all face handles for a side return BorderHalfedgeHandles(whiteBox, SideFaceHandles(whiteBox, faceHandle)); @@ -1078,7 +1080,7 @@ namespace WhiteBox static VertexHandlesCollection BorderVertexHandles( const WhiteBoxMesh& whiteBox, const HalfedgeHandlesCollection& halfedgeHandlesCollection) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); VertexHandlesCollection orderedVertexHandlesCollection; orderedVertexHandlesCollection.reserve(halfedgeHandlesCollection.size()); @@ -1101,14 +1103,14 @@ namespace WhiteBox VertexHandlesCollection SideBorderVertexHandles(const WhiteBoxMesh& whiteBox, const FaceHandle faceHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return BorderVertexHandles(whiteBox, SideBorderHalfedgeHandles(whiteBox, faceHandle)); } static VertexHandles FacesVertexHandles(const WhiteBoxMesh& whiteBox, const FaceHandles& faceHandles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); VertexHandles vertexHandles; for (const FaceHandle faceHandle : faceHandles) @@ -1132,7 +1134,7 @@ namespace WhiteBox VertexHandles SideVertexHandles(const WhiteBoxMesh& whiteBox, const FaceHandle faceHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return FacesVertexHandles(whiteBox, SideFaceHandles(whiteBox, faceHandle)); } @@ -1252,7 +1254,7 @@ namespace WhiteBox static bool EdgeIsUser( const WhiteBoxMesh& whiteBox, const HalfedgeHandle halfedgeHandle, const EdgeHandle edgeHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto polygonEdgeHandles = PolygonBorderEdgeHandlesFlattened( whiteBox, FacePolygonHandle(whiteBox, HalfedgeFaceHandle(whiteBox, halfedgeHandle))); @@ -1276,7 +1278,7 @@ namespace WhiteBox EdgeHandles EdgeGrouping(const WhiteBoxMesh& whiteBox, const EdgeHandle edgeHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // a non-user ('mesh') edge is never part of a grouping so if one is passed // in ensure we return an empty group @@ -1349,7 +1351,7 @@ namespace WhiteBox bool EdgeIsHidden(const WhiteBoxMesh& whiteBox, const EdgeHandle edgeHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const EdgeHandles userEdgeHandles = MeshPolygonEdgeHandles(whiteBox); return AZStd::find(userEdgeHandles.cbegin(), userEdgeHandles.cend(), edgeHandle) == userEdgeHandles.cend(); @@ -1357,7 +1359,7 @@ namespace WhiteBox AZStd::vector EdgeFaceHandles(const WhiteBoxMesh& whiteBox, const EdgeHandle edgeHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto openMeshEdgeHandle = om_eh(edgeHandle); const auto firstHalfedgeHandle = whiteBox.mesh.halfedge_handle(openMeshEdgeHandle, 0); @@ -1405,7 +1407,7 @@ namespace WhiteBox HalfedgeHandles EdgeHalfedgeHandles(const WhiteBoxMesh& whiteBox, EdgeHandle edgeHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZStd::array halfedgeHandles = { EdgeHalfedgeHandle(whiteBox, edgeHandle, EdgeHalfedge::First), @@ -1429,7 +1431,7 @@ namespace WhiteBox WHITEBOX_LOG( "White Box", "TranslateEdge eh(%s) %s", ToString(edgeHandle).c_str(), AZ::ToString(displacement).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto vertexHandles = EdgeVertexHandles(whiteBox, edgeHandle); for (const auto& vertexHandle : vertexHandles) @@ -1450,7 +1452,7 @@ namespace WhiteBox static HalfedgeHandle FindBestFitHalfedge( WhiteBoxMesh& whiteBox, const EdgeHandle edgeHandle, const AZ::Vector3& displacement) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // get both halfedge handles for the edge (0 and 1 just correspond to each halfedge) const HalfedgeHandle firstHalfedgeHandle = EdgeHalfedgeHandle(whiteBox, edgeHandle, EdgeHalfedge::First); @@ -1495,7 +1497,7 @@ namespace WhiteBox static Internal::EdgeAppendVertexHandles CalculateEdgeAppendVertexHandles( WhiteBoxMesh& whiteBox, const EdgeHandle edgeHandle, const AZ::Vector3& displacement) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // based on the displacement find which halfedge is a better fit (which direction did we move in) const HalfedgeHandle halfedgeHandle = FindBestFitHalfedge(whiteBox, edgeHandle, displacement); @@ -1575,7 +1577,7 @@ namespace WhiteBox static Internal::EdgeAppendPolygonHandles AddNewPolygonsForEdgeAppend( WhiteBoxMesh& whiteBox, const Internal::EdgeAppendVertexHandles& edgeAppendVertexHandles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); Internal::EdgeAppendPolygonHandles edgeAppendPolygonHandles; @@ -1636,7 +1638,7 @@ namespace WhiteBox static EdgeHandle FindSelectedEdgeHandle( const WhiteBoxMesh& whiteBox, const PolygonHandle& nearPolygonHandle, const PolygonHandle& farPolygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // actually find the new edge we created const EdgeHandles nearEdgeHandles = PolygonBorderEdgeHandlesFlattened(whiteBox, nearPolygonHandle); @@ -1670,7 +1672,7 @@ namespace WhiteBox WHITEBOX_LOG( "White Box", "TranslateEdgeAppend eh(%s) %s", ToString(edgeHandle).c_str(), AZ::ToString(displacement).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // the new and existing handles required for an edge append const Internal::EdgeAppendVertexHandles edgeAppendVertexHandles = @@ -1698,7 +1700,7 @@ namespace WhiteBox AZ::Vector3 PolygonNormal(const WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return AZStd::accumulate( polygonHandle.m_faceHandles.cbegin(), polygonHandle.m_faceHandles.cend(), @@ -1712,7 +1714,7 @@ namespace WhiteBox PolygonHandle FacePolygonHandle(const WhiteBoxMesh& whiteBox, const FaceHandle faceHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); PolygonPropertyHandle polygonPropsHandle; whiteBox.mesh.get_property_handle(polygonPropsHandle, PolygonProps); @@ -1730,7 +1732,7 @@ namespace WhiteBox VertexHandles PolygonVertexHandles(const WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return FacesVertexHandles(whiteBox, polygonHandle.m_faceHandles); } @@ -1738,7 +1740,7 @@ namespace WhiteBox VertexHandlesCollection PolygonBorderVertexHandles( const WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return BorderVertexHandles(whiteBox, PolygonBorderHalfedgeHandles(whiteBox, polygonHandle)); } @@ -1746,7 +1748,7 @@ namespace WhiteBox VertexHandles PolygonBorderVertexHandlesFlattened( const WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const VertexHandlesCollection borderVertexHandlesCollection = BorderVertexHandles(whiteBox, PolygonBorderHalfedgeHandles(whiteBox, polygonHandle)); @@ -1764,7 +1766,7 @@ namespace WhiteBox HalfedgeHandles PolygonBorderHalfedgeHandlesFlattened( const WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const HalfedgeHandlesCollection borderHalfedgeHandlesCollection = PolygonBorderHalfedgeHandles(whiteBox, polygonHandle); @@ -1781,7 +1783,7 @@ namespace WhiteBox HalfedgeHandles PolygonHalfedgeHandles(const WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return AZStd::accumulate( polygonHandle.m_faceHandles.cbegin(), polygonHandle.m_faceHandles.cend(), HalfedgeHandles{}, @@ -1802,7 +1804,7 @@ namespace WhiteBox AZStd::vector PolygonVertexPositions( const WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return VertexPositions(whiteBox, PolygonVertexHandles(whiteBox, polygonHandle)); } @@ -1810,7 +1812,7 @@ namespace WhiteBox VertexPositionsCollection PolygonBorderVertexPositions( const WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto polygonBorderVertexHandlesCollection = PolygonBorderVertexHandles(whiteBox, polygonHandle); VertexPositionsCollection polygonBorderVertexPositionsCollection; @@ -1827,7 +1829,7 @@ namespace WhiteBox AZStd::vector PolygonFacesPositions( const WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return FacesPositions(whiteBox, polygonHandle.m_faceHandles); } @@ -1854,7 +1856,7 @@ namespace WhiteBox EdgeHandles VertexUserEdgeHandles(const WhiteBoxMesh& whiteBox, const VertexHandle vertexHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto vertexEdgeHandles = VertexEdgeHandles(whiteBox, vertexHandle); @@ -1874,7 +1876,7 @@ namespace WhiteBox static AZStd::vector VertexUserEdges( const WhiteBoxMesh& whiteBox, const VertexHandle vertexHandle, EdgeFn&& edgeFn) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto vertexEdgeHandles = VertexUserEdgeHandles(whiteBox, vertexHandle); @@ -1931,13 +1933,13 @@ namespace WhiteBox AZ::Vector3 FaceNormal(const WhiteBoxMesh& whiteBox, const FaceHandle faceHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return whiteBox.mesh.normal(om_fh(faceHandle)); } AZ::Vector2 HalfedgeUV(const WhiteBoxMesh& whiteBox, const HalfedgeHandle halfedgeHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return whiteBox.mesh.texcoord2D(om_heh(halfedgeHandle)); } @@ -1964,7 +1966,7 @@ namespace WhiteBox Faces MeshFaces(const WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); Faces faces; faces.reserve(MeshFaceCount(whiteBox)); @@ -1989,7 +1991,7 @@ namespace WhiteBox void CalculatePlanarUVs(WhiteBoxMesh& whiteBox, const FaceHandles& faceHandles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); auto& mesh = whiteBox.mesh; for (const auto faceHandle : faceHandles) @@ -2012,7 +2014,7 @@ namespace WhiteBox void CalculatePlanarUVs(WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); CalculatePlanarUVs(whiteBox, MeshFaceHandles(whiteBox)); } @@ -2022,7 +2024,7 @@ namespace WhiteBox const HalfedgeHandle oppositeHalfedgeHandle, const HalfedgeHandles& borderHalfedgeHandles, const EdgeHandles& buildingEdgeHandles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // the polygon handle to build PolygonHandle polygonHandle; @@ -2119,7 +2121,7 @@ namespace WhiteBox WhiteBoxMesh& whiteBox, const EdgeHandle edgeHandle, EdgeHandles& restoringEdgeHandles) { WHITEBOX_LOG("White Box", "RestoreEdge eh(%s)", ToString(edgeHandle).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // check we're not selecting an existing user edge if (!EdgeIsHidden(whiteBox, edgeHandle)) @@ -2231,7 +2233,7 @@ namespace WhiteBox PolygonHandle HideEdge(WhiteBoxMesh& whiteBox, const EdgeHandle edgeHandle) { WHITEBOX_LOG("White Box", "HideEdge eh(%s)", ToString(edgeHandle).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (MeshHalfedgeCount(whiteBox) == 0) { @@ -2296,7 +2298,7 @@ namespace WhiteBox VertexHandle SplitFace(WhiteBoxMesh& whiteBox, const FaceHandle faceHandle, const AZ::Vector3& position) { WHITEBOX_LOG("White Box", "SplitFace fh(%s)", ToString(faceHandle).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto omFaceHandle = om_fh(faceHandle); const auto omVertexHandle = whiteBox.mesh.split_copy(omFaceHandle, position); @@ -2340,7 +2342,7 @@ namespace WhiteBox VertexHandle SplitEdge(WhiteBoxMesh& whiteBox, const EdgeHandle edgeHandle, const AZ::Vector3& position) { WHITEBOX_LOG("White Box", "SplitEdge eh(%s)", ToString(edgeHandle).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const HalfedgeHandle halfedgeHandle = EdgeHalfedgeHandle(whiteBox, edgeHandle, EdgeHalfedge::First); const VertexHandle tailVertexHandle = HalfedgeVertexHandleAtTail(whiteBox, halfedgeHandle); @@ -2441,7 +2443,7 @@ namespace WhiteBox void Clear(WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); PolygonPropertyHandle polygonPropsHandle; whiteBox.mesh.get_property_handle(polygonPropsHandle, PolygonProps); @@ -2462,7 +2464,7 @@ namespace WhiteBox WHITEBOX_LOG( "White Box", "AddTriPolygon vh(%s), vh(%s), vh(%s)", ToString(vh0).c_str(), ToString(vh1).c_str(), ToString(vh2).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return AddPolygon(whiteBox, AZStd::vector{{vh0, vh1, vh2}}); } @@ -2474,7 +2476,7 @@ namespace WhiteBox WHITEBOX_LOG( "White Box", "AddQuadPolygon vh(%s), vh(%s), vh(%s), vh(%s)", ToString(vh0).c_str(), ToString(vh1).c_str(), ToString(vh2).c_str(), ToString(vh3).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return AddPolygon(whiteBox, AZStd::vector{{vh0, vh1, vh2}, {vh0, vh2, vh3}}); } @@ -2482,7 +2484,7 @@ namespace WhiteBox PolygonHandle AddPolygon(WhiteBoxMesh& whiteBox, const FaceVertHandlesList& faceVertHandles) { WHITEBOX_LOG("White Box", "AddPolygon [%s]", ToString(faceVertHandles).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); PolygonPropertyHandle polygonPropsHandle; whiteBox.mesh.get_property_handle(polygonPropsHandle, PolygonProps); @@ -2510,7 +2512,7 @@ namespace WhiteBox PolygonHandles InitializeAsUnitCube(WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // generate vertices VertexHandle vertexHandles[8]; @@ -2550,7 +2552,7 @@ namespace WhiteBox PolygonHandle InitializeAsUnitQuad(WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // generate vertices VertexHandle vertexHandles[4]; @@ -2573,7 +2575,7 @@ namespace WhiteBox PolygonHandle InitializeAsUnitTriangle(WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // generate vertices VertexHandle vertexHandles[3]; @@ -2602,7 +2604,7 @@ namespace WhiteBox WHITEBOX_LOG( "White Box", "SetVertexPosition vh(%s) %s", ToString(vertexHandle).c_str(), AZ::ToString(position).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); whiteBox.mesh.set_point(om_vh(vertexHandle), position); } @@ -2613,7 +2615,7 @@ namespace WhiteBox WHITEBOX_LOG( "White Box", "SetVertexPositionAndUpdateUVs vh(%s) %s", ToString(vertexHandle).c_str(), AZ::ToString(position).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); SetVertexPosition(whiteBox, vertexHandle, position); CalculatePlanarUVs(whiteBox); @@ -2622,7 +2624,7 @@ namespace WhiteBox VertexHandle AddVertex(WhiteBoxMesh& whiteBox, const AZ::Vector3& vertex) { WHITEBOX_LOG("White Box", "AddVertex %s", AZ::ToString(vertex).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return wb_vh(whiteBox.mesh.add_vertex(vertex)); } @@ -2632,21 +2634,21 @@ namespace WhiteBox WHITEBOX_LOG( "White Box", "AddFace vh(%s), vh(%s), vh(%s)", ToString(v0).c_str(), ToString(v1).c_str(), ToString(v2).c_str()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return wb_fh(whiteBox.mesh.add_face(om_vh(v0), om_vh(v1), om_vh(v2))); } void CalculateNormals(WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); whiteBox.mesh.update_normals(); } void ZeroUVs(WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); for (const Mesh::FaceHandle faceHandle : whiteBox.mesh.faces()) { @@ -2692,7 +2694,7 @@ namespace WhiteBox AZ::Vector3 VerticesMidpoint(const WhiteBoxMesh& whiteBox, const VertexHandles& vertexHandles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AzToolsFramework::MidpointCalculator midpointCalculator; for (const auto vertexHandle : vertexHandles) @@ -2707,7 +2709,7 @@ namespace WhiteBox const WhiteBoxMesh& whiteBox, const Internal::VertexHandlePair vertexHandlePair, const PolygonHandle& selectedPolygonHandle, const PolygonHandle& adjacentPolygonHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto selectedPolygonEdgeHandles = PolygonBorderEdgeHandlesFlattened(whiteBox, selectedPolygonHandle); const auto adjacentPolygonEdgeHandles = PolygonBorderEdgeHandlesFlattened(whiteBox, adjacentPolygonHandle); @@ -2744,7 +2746,7 @@ namespace WhiteBox const PolygonHandle& selectedPolygonHandle, const PolygonHandle& adjacentPolygonHandle, FaceVertHandlesCollection& vertsForLinkingAdjacentPolygons) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // if we found a valid halfedge if (const HalfedgeHandle foundHalfedgeHandle = FindHalfedgeInAdjacentPolygon( @@ -2851,7 +2853,7 @@ namespace WhiteBox FaceVertHandlesCollection& vertsForExistingAdjacentPolygons, FaceVertHandlesCollection& vertsForLinkingAdjacentPolygons) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // adjacent faces for (size_t index = 0; index < borderVertexHandles.size(); ++index) @@ -2912,7 +2914,7 @@ namespace WhiteBox // during garbage_collect void RemoveFaces(WhiteBoxMesh& whiteBox, const FaceHandles& faceHandles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); whiteBox.mesh.request_face_status(); whiteBox.mesh.request_edge_status(); @@ -3014,7 +3016,7 @@ namespace WhiteBox AZStd::vector BuildNewVertexFaceHandles( WhiteBoxMesh& whiteBox, const Internal::AppendedVerts& appendedVerts, const FaceHandles& existingFaces) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::vector faces; faces.reserve(existingFaces.size()); @@ -3068,7 +3070,7 @@ namespace WhiteBox WhiteBoxMesh& whiteBox, const VertexHandles& existingVertexHandles, const PolygonHandle& polygonHandle, AppendVertFn&& appendFn) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::Vector3 polygonNormal = PolygonNormal(whiteBox, polygonHandle); const auto polygonHalfedgeHandles = PolygonHalfedgeHandles(whiteBox, polygonHandle); @@ -3146,7 +3148,7 @@ namespace WhiteBox static AppendedPolygonHandles Extrude( WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle, AppendVertexFn&& appendFn) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // find border vertex handles for polygon const auto polygonBorderVertexHandlesCollection = PolygonBorderVertexHandles(whiteBox, polygonHandle); @@ -3261,7 +3263,7 @@ namespace WhiteBox WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle, const float distance) { WHITEBOX_LOG("White Box", "TranslatePolygonAppend ph(%s) %f", ToString(polygonHandle).c_str(), distance) - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); return TranslatePolygonAppendAdvanced(whiteBox, polygonHandle, distance).m_appendedPolygonHandle; } @@ -3271,7 +3273,7 @@ namespace WhiteBox { WHITEBOX_LOG( "White Box", "TranslatePolygonAppendAdvanced ph(%s) %f", ToString(polygonHandle).c_str(), distance) - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // check mesh has faces if (whiteBox.mesh.n_faces() == 0) @@ -3288,7 +3290,7 @@ namespace WhiteBox void TranslatePolygon(WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle, const float distance) { WHITEBOX_LOG("White Box", "TranslatePolygon ph(%s) %d", ToString(polygonHandle).c_str(), distance) - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto vertexHandles = PolygonVertexHandles(whiteBox, polygonHandle); const auto vertexPositions = VertexPositions(whiteBox, vertexHandles); @@ -3306,7 +3308,7 @@ namespace WhiteBox WhiteBoxMesh& whiteBox, const PolygonHandle& polygonHandle, const float scale) { WHITEBOX_LOG("White Box", "ScalePolygonAppendRelative ph(%s) %f", ToString(polygonHandle).c_str(), scale); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // check mesh has faces if (whiteBox.mesh.n_faces() == 0) @@ -3329,7 +3331,7 @@ namespace WhiteBox static AZ::Transform BuildSpace(const AZ::Vector3& normal, const AZ::Vector3& pivot) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZ::Vector3 axis1; AZ::Vector3 axis2; @@ -3359,7 +3361,7 @@ namespace WhiteBox WHITEBOX_LOG( "White Box", "ScalePolygonRelative ph(%s) pivot %s scale: %f", ToString(polygonHandle).c_str(), AZ::ToString(pivot).c_str(), scaleDelta); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const AZ::Transform polygonSpace = PolygonSpace(whiteBox, polygonHandle, pivot); for (const auto vertexHandle : PolygonVertexHandles(whiteBox, polygonHandle)) @@ -3375,7 +3377,7 @@ namespace WhiteBox bool WriteMesh(const WhiteBoxMesh& whiteBox, WhiteBoxMeshStream& output) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); AZStd::lock_guard lg(g_omSerializationLock); @@ -3399,7 +3401,7 @@ namespace WhiteBox ReadResult ReadMesh(WhiteBoxMesh& whiteBox, const WhiteBoxMeshStream& input) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (input.empty()) { @@ -3434,7 +3436,7 @@ namespace WhiteBox WhiteBoxMeshPtr CloneMesh(const WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); WhiteBoxMeshStream clonedData; if (!WriteMesh(whiteBox, clonedData)) diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp index ad59da63d5..61796bde58 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp @@ -61,7 +61,7 @@ namespace WhiteBox // to be used to generate concrete render mesh static WhiteBoxRenderData CreateWhiteBoxRenderData(const WhiteBoxMesh& whiteBox, const WhiteBoxMaterial& material) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); WhiteBoxRenderData renderData; WhiteBoxFaces& faceData = renderData.m_faces; @@ -407,7 +407,7 @@ namespace WhiteBox void EditorWhiteBoxComponent::RebuildRenderMesh() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // reset caches when the mesh changes m_worldAabb.reset(); @@ -474,7 +474,7 @@ namespace WhiteBox void EditorWhiteBoxComponent::OnTransformChanged( [[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); m_worldAabb.reset(); m_localAabb.reset(); @@ -490,7 +490,7 @@ namespace WhiteBox void EditorWhiteBoxComponent::RebuildPhysicsMesh() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); EditorWhiteBoxColliderRequestBus::Event( GetEntityId(), &EditorWhiteBoxColliderRequests::CreatePhysics, *GetWhiteBoxMesh()); @@ -673,7 +673,7 @@ namespace WhiteBox AZ::Aabb EditorWhiteBoxComponent::GetWorldBounds() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!m_worldAabb.has_value()) { @@ -686,7 +686,7 @@ namespace WhiteBox AZ::Aabb EditorWhiteBoxComponent::GetLocalBounds() { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!m_localAabb.has_value()) { @@ -708,7 +708,7 @@ namespace WhiteBox [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, const AZ::Vector3& src, const AZ::Vector3& dir, float& distance) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (!m_faces.has_value()) { @@ -905,7 +905,7 @@ namespace WhiteBox void EditorWhiteBoxComponent::DisplayEntityViewport( [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (DebugDrawingEnabled()) { diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp index 3d04c87e6a..cd9e8090cd 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp @@ -209,7 +209,7 @@ namespace WhiteBox bool EditorWhiteBoxComponentMode::HandleMouseInteraction( const AzToolsFramework::ViewportInteraction::MouseInteractionEvent& mouseInteraction) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); WhiteBoxMesh* whiteBox = nullptr; EditorWhiteBoxComponentRequestBus::EventResult( @@ -301,7 +301,7 @@ namespace WhiteBox void EditorWhiteBoxComponentMode::DisplayEntityViewport( [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const auto modifiers = m_keyboardMofifierQueryFn(); @@ -374,7 +374,7 @@ namespace WhiteBox void EditorWhiteBoxComponentMode::RecalculateWhiteBoxIntersectionData(const EdgeSelectionType edgeSelectionMode) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); WhiteBoxMesh* whiteBox = nullptr; EditorWhiteBoxComponentRequestBus::EventResult( diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentModeTypes.cpp b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentModeTypes.cpp index 239c8a3066..cbde5f4f4b 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentModeTypes.cpp +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentModeTypes.cpp @@ -8,6 +8,7 @@ #include "EditorWhiteBoxComponentModeTypes.h" +#include #include namespace WhiteBox @@ -16,7 +17,7 @@ namespace WhiteBox AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Color& color, const AZStd::vector& edgeBoundsWithHandle, const Api::EdgeHandles& excludedEdgeHandles) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); debugDisplay.SetColor(color); for (const EdgeBoundWithHandle& edge : edgeBoundsWithHandle) diff --git a/Gems/WhiteBox/Code/Source/SubComponentModes/EditorWhiteBoxDefaultMode.cpp b/Gems/WhiteBox/Code/Source/SubComponentModes/EditorWhiteBoxDefaultMode.cpp index 136db8802c..3d6d9a4c0a 100644 --- a/Gems/WhiteBox/Code/Source/SubComponentModes/EditorWhiteBoxDefaultMode.cpp +++ b/Gems/WhiteBox/Code/Source/SubComponentModes/EditorWhiteBoxDefaultMode.cpp @@ -212,7 +212,7 @@ namespace WhiteBox AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Transform& worldFromLocal, const AzFramework::CameraState& cameraState, const IntersectionAndRenderData& renderData) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); const float vertexIndicatorLength = cl_whiteBoxVertexIndicatorLength; const float vertexIndicatorWidth = cl_whiteBoxVertexIndicatorWidth; @@ -252,7 +252,7 @@ namespace WhiteBox const IntersectionAndRenderData& renderData, [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); TryDestroyModifier(m_polygonTranslationModifier); TryDestroyModifier(m_edgeTranslationModifier); @@ -276,7 +276,7 @@ namespace WhiteBox Api::EdgeHandles DefaultMode::FindInteractiveEdgeHandles(const WhiteBoxMesh& whiteBox) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); // get all edge handles for hovered polygon const Api::EdgeHandles polygonHoveredEdgeHandles = m_polygonTranslationModifier @@ -322,7 +322,7 @@ namespace WhiteBox const WhiteBoxMesh& whiteBox, const PolygonScaleModifier* polygonScaleModifier, const EdgeScaleModifier* edgeScaleModifier, const Api::VertexHandle vertexHandle) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); if (Api::VertexIsHidden(whiteBox, vertexHandle)) { @@ -371,7 +371,7 @@ namespace WhiteBox const AZStd::optional& polygonIntersection, const AZStd::optional& vertexIntersection) { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); + AZ_PROFILE_FUNCTION(AzToolsFramework); WhiteBoxMesh* whiteBox = nullptr; EditorWhiteBoxComponentRequestBus::EventResult( diff --git a/README.md b/README.md index a783139eef..1191a0f0ee 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ O3DE (Open 3D Engine) is an open-source, real-time, multi-platform 3D engine that enables developers and content creators to build AAA games, cinema-quality 3D worlds, and high-fidelity simulations without any fees or commercial obligations. ## Contribute -For information about contributing to Open 3D Engine, visit https://o3de.org/docs/contributing/ +For information about contributing to Open 3D Engine, visit [https://o3de.org/docs/contributing/](https://o3de.org/docs/contributing/). ## Download and Install @@ -14,7 +14,7 @@ Verify you have Git LFS installed by running the following command to print the git lfs --version ``` -If Git LFS is not installed, download and run the installer from: https://git-lfs.github.com/. +If Git LFS is not installed, download and run the installer from: [https://git-lfs.github.com/](https://git-lfs.github.com/). ### Install Git LFS hooks ``` @@ -29,78 +29,100 @@ git clone https://github.com/o3de/o3de.git ``` ## Building the Engine -### Build Requirements and redistributables + +### Build requirements and redistributables + +For the latest details and system requirements, refer to [System Requirements](https://o3de.org/docs/welcome-guide/requirements/) in the documentation. + #### Windows -* Visual Studio 2019 16.9.2 minimum (All versions supported, including Community): [https://visualstudio.microsoft.com/downloads/](https://visualstudio.microsoft.com/downloads/) +* Visual Studio 2019 16.9.2 minimum (All editions supported, including Community): [https://visualstudio.microsoft.com/downloads/](https://visualstudio.microsoft.com/downloads/) + * Check [System Requirements](https://o3de.org/docs/welcome-guide/requirements/) for other supported versions. * Install the following workloads: * Game Development with C++ * MSVC v142 - VS 2019 C++ x64/x86 * C++ 2019 redistributable update -* CMake 3.20 minimum: [https://cmake.org/download/](https://cmake.org/download/) +* CMake 3.20.5 minimum: [https://cmake.org/download/](https://cmake.org/download/) #### Optional -* Wwise version 2021.1.1.7601 minimum: [https://www.audiokinetic.com/download/](https://www.audiokinetic.com/download/) - * Note: This requires registration and installation of a client application to download - * Note: It is generally okay to use a more recent version of Wwise, but some SDK updates will require code changes - * Make sure to select the `SDK(C++)` component during installation of Wwise - * CMake can find the Wwise install location in two ways: - * The `LY_WWISE_INSTALL_PATH` CMake cache variable -- this is checked first - * The `WWISEROOT` environment variable which is set when installing Wwise SDK +* Wwise audio SDK + * For the latest version requirements and setup instructions, refer to the [Wwise Audio Engine Gem](https://o3de.org/docs/user-guide/gems/reference/audio/wwise/audio-engine-wwise/) reference in the documentation. -### Quick Start Build Steps +### Quick start engine setup -1. Create a writable folder to cache 3rd Party dependencies. You can also use this to store other redistributable SDKs. +To set up a project-centric source engine, complete the following steps. For other build options, refer to [Setting up O3DE from GitHub](https://o3de.org/docs/welcome-guide/setup/setup-from-github/) in the documentation. + +1. Create a writable folder to cache downloadable third-party packages. You can also use this to store other redistributable SDKs. -1. Install the following redistributables to the following: - - Visual Studio and VC++ redistributable can be installed to any location - - CMake can be installed to any location, as long as it's available in the system path +1. Install the following redistributables: + - Visual Studio and VC++ redistributable can be installed to any location. + - CMake can be installed to any location, as long as it's available in the system path. -1. Configure the source into a solution using this command line, replacing and <3rdParty cache path> to a path you've created: +1. Configure the engine source into a solution using this command line, replacing ``, ``, and `<3rdParty package path>` with the paths you've created: ``` - cmake -B -S -G "Visual Studio 16" -DLY_3RDPARTY_PATH=<3rdParty cache path> -DLY_UNITY_BUILD=ON -DLY_PROJECTS=AutomatedTesting + cmake -B -S -G "Visual Studio 16" -DLY_3RDPARTY_PATH=<3rdParty package path> ``` - > Note: Do not use trailing slashes for the <3rdParty cache path> + + Example: + ``` + cmake -B C:\o3de\build\windows_vs2019 -S C:\o3de -G "Visual Studio 16" -DLY_3RDPARTY_PATH=C:\o3de-packages + ``` + + > Note: Do not use trailing slashes for the <3rdParty package path>. 1. Alternatively, you can do this through the CMake GUI: - 1. Start `cmake-gui.exe` - 1. Select the local path of the repo under "Where is the source code" - 1. Select a path where to build binaries under "Where to build the binaries" - 1. Click "Configure" - 1. Wait for the key values to populate. Fill in the fields that are relevant, including `LY_3RDPARTY_PATH` and `LY_PROJECTS` - 1. Click "Generate" + 1. Start `cmake-gui.exe`. + 1. Select the local path of the repo under "Where is the source code". + 1. Select a path where to build binaries under "Where to build the binaries". + 1. Click **Add Entry** and add a cache entry for the <3rdParty package path> folder you created, using the following values: + 1. **Name:** LY_3RDPARTY_PATH + 1. **Type:** STRING + 1. **Value:** `<3rdParty package path>` + 1. Click **Configure**. + 1. Wait for the key values to populate. Update or add any additional fields that are needed for your project. + 1. Click **Generate**. -1. The configuration of the solution is complete. To build the Editor and AssetProcessor to binaries, run this command inside your repo: - ``` - cmake --build --target AutomatedTesting.GameLauncher AssetProcessor Editor --config profile -- /m - ``` - -1. This will compile after some time and binaries will be available in the build path you've specified - -### Setting up new projects -1. While still within the repo folder, register the engine with this command: +1. Register the engine with this command: ``` scripts\o3de.bat register --this-engine ``` -1. Setup new projects using the `o3de create-project` command. + +1. The configuration of the solution is complete. You are now ready to create a project and build the engine. + +For more details on the steps above, refer to [Setting up O3DE from GitHub](https://o3de.org/docs/welcome-guide/setup/setup-from-github/) in the documentation. + +### Setting up new projects and building the engine + +1. From the O3DE repo folder, set up a new project using the `o3de create-project` command. ``` - \scripts\o3de.bat create-project --project-path + scripts\o3de.bat create-project --project-path ``` -1. Register the engine to the project - ``` - \scripts\o3de.bat register --project-path - ``` -1. Once you're ready to build the project, run the same set of commands to configure and build: + +1. Configure a solution for your project. ``` cmake -B -S -G "Visual Studio 16" -DLY_3RDPARTY_PATH=<3rdParty cache path> - - cmake --build --target .GameLauncher --config profile -- /m ``` - -For a tutorial on project configuration, see [Creating Projects Using the Command Line](https://docs.o3de.org/docs/welcome-guide/get-started/project-config/creating-projects-using-cli) in the documentation. + + Example: + ``` + cmake -B C:\my-project\build\windows_vs2019 -S C:\my-project -G "Visual Studio 16" -DLY_3RDPARTY_PATH=C:\o3de-packages + ``` + + > Note: Do not use trailing slashes for the <3rdParty cache path>. + +1. Build the project, Asset Processor, and Editor to binaries by running this command inside your project: + ``` + cmake --build --target .GameLauncher Editor --config profile -- /m + ``` + + > Note: Your project name used in the build target is the same as the directory name of your project. + +This will compile after some time and binaries will be available in the project build path you've specified, under `bin/profile`. + +For a complete tutorial on project configuration, see [Creating Projects Using the Command Line Interface](https://o3de.org/docs/welcome-guide/create/creating-projects-using-cli/) in the documentation. ## License -For terms please see the LICENSE*.TXT file at the root of this distribution. +For terms please see the LICENSE*.TXT files at the root of this distribution. diff --git a/Registry/sceneassetimporter.setreg b/Registry/sceneassetimporter.setreg index bd7c4d0705..6fef3a40dc 100644 --- a/Registry/sceneassetimporter.setreg +++ b/Registry/sceneassetimporter.setreg @@ -10,6 +10,11 @@ ".fbx", ".stl" ] + }, + "MaterialConverter": + { + "Enable": true, + "DefaultMaterial": "Materials/Presets/PBR/default_grid.material" } } } diff --git a/Tools/LyTestTools/ly_test_tools/report/rad_telemetry.py b/Tools/LyTestTools/ly_test_tools/report/rad_telemetry.py deleted file mode 100755 index 865cc4671c..0000000000 --- a/Tools/LyTestTools/ly_test_tools/report/rad_telemetry.py +++ /dev/null @@ -1,98 +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 - -Helpers for RAD Telemetry, currently only for Windows -""" - -import logging -import subprocess -import os - -import ly_test_tools.environment.process_utils as process_utils -from ly_test_tools import WINDOWS - -_RAD_DEFAULT_PORT = 4719 - -_CREATE_NEW_PROCESS_GROUP = 0x00000200 -_DETACHED_PROCESS = 0x00000008 -_WINDOWS_FLAGS = _CREATE_NEW_PROCESS_GROUP | _DETACHED_PROCESS - -RAD_TOOLS_SUBPATH = os.path.join("dev", "Gems", "RADTelemetry", "Tools") - -log = logging.getLogger(__name__) - - -def __set_firewall_rule(direction, port): - """ - Adds a Windows firewall rule if one does not yet exist. Requires administrator privilege. - - :param direction: Must be 'in' or 'out' - :param port: target port to open - :return: None - """ - - assert WINDOWS, "Only implemented for Windows platforms" - log.info(f"Setting firewall rule on port '{port}' for direction '{direction}'") - - show_rule = ['netsh', 'advfirewall', 'firewall', 'show', 'rule', 'name=RADTelemetry', f'dir={direction}'] - show_result = process_utils.safe_check_call(show_rule) - - if show_result == 0: - log.debug("Rule already exists") - else: - add_rule = ['netsh', 'advfirewall', 'firewall', 'add', 'rule', 'name=RADTelemetry', f'dir={direction}', - 'action=allow', 'protocol=TCP', f'localport={port}'] - process_utils.check_call(add_rule) - log.debug("Added new rule") - - -def set_firewall_rules(): - """ - Opens firewall ports necessary for a remote device to communicate with the RAD Telemetry server. - Requires administrator privilege. - - :return: None - """ - assert WINDOWS, "Only implemented for Windows platforms" - __set_firewall_rule(direction="in", port=_RAD_DEFAULT_PORT) - __set_firewall_rule(direction="out", port=_RAD_DEFAULT_PORT) - - -def launch_server(dev_path): - """ - Launches the RAD Telemetry server to collect telemetry captures. - - :param dev_path: path to the folder containing engineroot.txt - :return: None - """ - assert WINDOWS, "Only implemented for Windows platforms" - server_path = os.path.join(dev_path, RAD_TOOLS_SUBPATH, "tm_server.exe") - subprocess.Popen([server_path], creationflags=_WINDOWS_FLAGS, close_fds=True) - log.info(f"Launched RAD Server from {server_path}") - - -def terminate_servers(dev_path): - """ - Terminate the RAD Telemetry server and all related tools, important before collecting any of its captures - - :param dev_path: path to the folder containing engineroot.txt - :return: None - """ - assert WINDOWS, "Only implemented for Windows platforms" - rad_path = os.path.join(dev_path, RAD_TOOLS_SUBPATH) - process_utils.kill_processes_started_from(rad_path) - - -def get_capture_path(dev_path): - """ - Returns the path of the tm_server.exe file - - :return: path to the folder containing output for local servers - """ - assert WINDOWS, "Only implemented for Windows platforms" - get_folder_path = os.path.join(dev_path, RAD_TOOLS_SUBPATH, "tm_server.exe") - output = process_utils.check_output([get_folder_path]) - return output.strip() diff --git a/Tools/LyTestTools/tests/unit/test_builtin_helpers.py b/Tools/LyTestTools/tests/unit/test_builtin_helpers.py index 63dd051a62..9eb8a1703d 100755 --- a/Tools/LyTestTools/tests/unit/test_builtin_helpers.py +++ b/Tools/LyTestTools/tests/unit/test_builtin_helpers.py @@ -7,6 +7,7 @@ SPDX-License-Identifier: Apache-2.0 OR MIT Unit tests for ly_test_tools.builtin.helpers functions. """ import unittest.mock as mock +import os import pytest @@ -41,6 +42,8 @@ class MockedWorkspaceManager(ly_test_tools._internal.managers.workspace.Abstract ) +@mock.patch('ly_test_tools._internal.managers.abstract_resource_locator._find_project_json', + mock.MagicMock(return_value=os.path.join("mocked", "path"))) @mock.patch( 'ly_test_tools._internal.managers.abstract_resource_locator.AbstractResourceLocator', mock.MagicMock(return_value=MockedAbstractResourceLocator) diff --git a/Tools/LyTestTools/tests/unit/test_rad_telemetry.py b/Tools/LyTestTools/tests/unit/test_rad_telemetry.py deleted file mode 100755 index 76db056215..0000000000 --- a/Tools/LyTestTools/tests/unit/test_rad_telemetry.py +++ /dev/null @@ -1,88 +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 - -Unit Tests for ~/ly_test_tools/report/rad_telemetry.py -""" - -import unittest.mock as mock -import os -import pytest - -import ly_test_tools.report.rad_telemetry -from ly_test_tools import WINDOWS - -pytestmark = pytest.mark.SUITE_smoke - - -_RAD_DEFAULT_PORT = 4719 - -_CREATE_NEW_PROCESS_GROUP = 0x00000200 -_DETACHED_PROCESS = 0x00000008 -_WINDOWS_FLAGS = _CREATE_NEW_PROCESS_GROUP | _DETACHED_PROCESS - -RAD_TOOLS_SUBPATH = os.path.join("dev", "Gems", "RADTelemetry", "Tools") - - -@pytest.mark.skipif( - not WINDOWS, - reason="tests.unit.test_rad_telemetry is restricted to the Windows platform.") -class TestRADTelemetry: - - @mock.patch('ly_test_tools.environment.process_utils.check_call') - @mock.patch('ly_test_tools.environment.process_utils.safe_check_call') - def test_SetFirewallRules_ShowRuleResultNotZero_CallsAddRule(self, mock_safe_call, mock_call): - ly_test_tools.report.rad_telemetry.set_firewall_rules() - - mock_safe_call.call_args_list = [ - mock.call(['netsh', 'advfirewall', 'firewall', 'show', 'rule', 'name=RADTelemetry', 'dir=in']), - mock.call(['netsh', 'advfirewall', 'firewall', 'show', 'rule', 'name=RADTelemetry', 'dir=out']), - ] - mock_call.call_args_list = [ - mock.call( - ['netsh', 'advfirewall', 'firewall', 'add', 'rule', 'name=RADTelemetry', 'dir=in', - 'action=allow', 'protocol=TCP', 'localport={}'.format(_RAD_DEFAULT_PORT)]), - mock.call( - ['netsh', 'advfirewall', 'firewall', 'add', 'rule', 'name=RADTelemetry', 'dir=out', - 'action=allow', 'protocol=TCP', 'localport={}'.format(_RAD_DEFAULT_PORT)]), - ] - - assert mock_call.call_count == 2 - assert mock_safe_call.call_count == 2 - - @mock.patch('ly_test_tools.environment.process_utils.check_call') - @mock.patch('ly_test_tools.environment.process_utils.safe_check_call') - def test_SetFirewallRules_ShowRuleResultEqualsZero_AddRuleNotCalled(self, mock_safe_call, mock_call): - mock_safe_call.return_value = 0 - ly_test_tools.report.rad_telemetry.set_firewall_rules() - - mock_call.assert_not_called() - assert mock_safe_call.call_count == 2 - - @mock.patch('subprocess.Popen') - def test_LaunchServer_ValidDevPath_PopenSuccess(self, mock_popen): - mock_server_path = os.path.join('dev_path', RAD_TOOLS_SUBPATH, "tm_server.exe") - - ly_test_tools.report.rad_telemetry.launch_server('dev_path') - - mock_popen.assert_called_once_with([mock_server_path], creationflags=_WINDOWS_FLAGS, close_fds=True) - - @mock.patch('ly_test_tools.environment.process_utils.kill_processes_started_from') - def test_TerminateServer_ValidDevPath_KillsRADProcess(self, mock_kill_process): - mock_rad_path = os.path.join('dev_path', RAD_TOOLS_SUBPATH) - - ly_test_tools.report.rad_telemetry.terminate_servers('dev_path') - - mock_kill_process.assert_called_once_with(mock_rad_path) - - @mock.patch('ly_test_tools.environment.process_utils.check_output') - def test_TerminateServer_ValidDevPath_KillsRADProcess(self, mock_call): - mock_get_folder_path = os.path.join('dev_path', RAD_TOOLS_SUBPATH, "tm_server.exe") - mock_call.return_value = 'test' - - under_test = ly_test_tools.report.rad_telemetry.get_capture_path('dev_path') - - mock_call.assert_called_once_with([mock_get_folder_path]) - assert under_test == 'test' diff --git a/Gems/Atom/RHI/DX12/3rdParty/Findpix.cmake b/cmake/3rdParty/FindPIX.cmake similarity index 59% rename from Gems/Atom/RHI/DX12/3rdParty/Findpix.cmake rename to cmake/3rdParty/FindPIX.cmake index b8e7118953..e4652467ac 100644 --- a/Gems/Atom/RHI/DX12/3rdParty/Findpix.cmake +++ b/cmake/3rdParty/FindPIX.cmake @@ -6,15 +6,14 @@ # # -file(TO_CMAKE_PATH "$ENV{ATOM_PIX_PATH}" ATOM_PIX_PATH_CMAKE_FORMATTED) +if(LY_PIX_ENABLED) + file(TO_CMAKE_PATH "${LY_PIX_PATH}" PIX_PATH) + message(STATUS "PIX found: ${PIX_PATH}") -if(EXISTS "${ATOM_PIX_PATH_CMAKE_FORMATTED}/include/WinPixEventRuntime/pix3.h") ly_add_external_target( NAME pix + 3RDPARTY_ROOT_DIRECTORY "${PIX_PATH}" VERSION - 3RDPARTY_ROOT_DIRECTORY ${ATOM_PIX_PATH_CMAKE_FORMATTED} INCLUDE_DIRECTORIES include ) endif() - - diff --git a/cmake/3rdParty/FindRadTelemetry.cmake b/cmake/3rdParty/FindRadTelemetry.cmake deleted file mode 100644 index 4af7423526..0000000000 --- a/cmake/3rdParty/FindRadTelemetry.cmake +++ /dev/null @@ -1,14 +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 -# -# - -ly_add_external_target( - NAME RadTelemetry - 3RDPARTY_ROOT_DIRECTORY "${LY_RAD_TELEMETRY_INSTALL_ROOT}" - VERSION 3.5.0.17 - INCLUDE_DIRECTORIES Include -) diff --git a/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake b/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake index ab7432e09e..a65e8b45e4 100644 --- a/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake +++ b/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake @@ -8,7 +8,7 @@ # shared by other platforms: ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) -ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-multiplatform TARGETS RapidJSON PACKAGE_HASH 18b0aef4e6e849389916ff6de6682ab9c591ebe15af6ea6017014453c1119ea1) +ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) ly_associate_package(PACKAGE_NAME lz4-r128-multiplatform TARGETS lz4 PACKAGE_HASH d7b1d5651191db2c339827ad24f669d9d37754143e9173abc986184532f57c9d) diff --git a/cmake/3rdParty/Platform/Android/RadTelemetry_android.cmake b/cmake/3rdParty/Platform/Android/RadTelemetry_android.cmake deleted file mode 100644 index 658c9440b2..0000000000 --- a/cmake/3rdParty/Platform/Android/RadTelemetry_android.cmake +++ /dev/null @@ -1,9 +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 -# -# - -set(RADTELEMETRY_LIBS ${BASE_PATH}/Lib/librad_tm_android_arm64.a) diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index bb70a54d6f..7df364121b 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -8,12 +8,11 @@ # shared by other platforms: ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) -ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) -ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-multiplatform TARGETS RapidJSON PACKAGE_HASH 18b0aef4e6e849389916ff6de6682ab9c591ebe15af6ea6017014453c1119ea1) +ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) @@ -42,7 +41,7 @@ ly_associate_package(PACKAGE_NAME unwind-1.2.1-linux ly_associate_package(PACKAGE_NAME qt-5.15.2-rev5-linux TARGETS Qt PACKAGE_HASH 76b395897b941a173002845c7219a5f8a799e44b269ffefe8091acc048130f28) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-linux TARGETS libsamplerate PACKAGE_HASH 41643c31bc6b7d037f895f89d8d8d6369e906b92eff42b0fe05ee6a100f06261) ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev2-linux TARGETS OpenSSL PACKAGE_HASH b779426d1e9c5ddf71160d5ae2e639c3b956e0fb5e9fcaf9ce97c4526024e3bc) -ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev2-linux TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 235606f98512c076a1ba84a8402ad24ac21945998abcea264e8e204678efc0ba) +ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev3-linux TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 88c4a359325d749bc34090b9ac466424847f3b71ba0de15045cf355c17c07099) ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-linux TARGETS SPIRVCross PACKAGE_HASH 7889ee5460a688e9b910c0168b31445c0079d363affa07b25d4c8aeb608a0b80) ly_associate_package(PACKAGE_NAME azslc-1.7.23-rev2-linux TARGETS azslc PACKAGE_HASH 1ba84d8321a566d35a1e9aa7400211ba8e6d1c11c08e4be3c93e6e74b8f7aef1) ly_associate_package(PACKAGE_NAME zlib-1.2.11-rev1-linux TARGETS zlib PACKAGE_HASH 6418e93b9f4e6188f3b62cbd3a7822e1c4398a716e786d1522b809a727d08ba9) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index a0001d3e4e..353956a495 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -8,12 +8,11 @@ # shared by other platforms: ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) -ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) -ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-multiplatform TARGETS RapidJSON PACKAGE_HASH 18b0aef4e6e849389916ff6de6682ab9c591ebe15af6ea6017014453c1119ea1) +ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) @@ -28,7 +27,7 @@ ly_associate_package(PACKAGE_NAME xxhash-0.7.4-rev1-multiplatform ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform TARGETS PVRTexTool PACKAGE_HASH d0d6da61c7557de0d2c71fc35ba56c3be49555b703f0e853d4c58225537acf1e) # platform-specific: -ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev2-mac TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 2bede9a7ef3573027c005e38139237559eebf845c13ffb54c33c5b8675f962e2) +ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev3-mac TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 3f77367dbb0342136ec4ebbd44bc1fedf7198089a0f83c5631248530769b2be6) ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-mac TARGETS SPIRVCross PACKAGE_HASH 78c6376ed2fd195b9b1f5fb2b56e5267a32c3aa21fb399e905308de470eb4515) ly_associate_package(PACKAGE_NAME freetype-2.10.4.14-mac-ios TARGETS freetype PACKAGE_HASH 67b4f57aed92082d3fd7c16aa244a7d908d90122c296b0a63f73e0a0b8761977) ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-mac-ios TARGETS tiff PACKAGE_HASH a23ae1f8991a29f8e5df09d6d5b00d7768a740f90752cef465558c1768343709) diff --git a/cmake/3rdParty/Platform/Mac/RadTelemetry_mac.cmake b/cmake/3rdParty/Platform/Mac/RadTelemetry_mac.cmake deleted file mode 100644 index 572d798868..0000000000 --- a/cmake/3rdParty/Platform/Mac/RadTelemetry_mac.cmake +++ /dev/null @@ -1,11 +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 -# -# - -set(RADTELEMETRY_LIBS ${BASE_PATH}/Lib/librad_tm_mac_x64_link.a) - -set(RADTELEMETRY_RUNTIME_DEPENDENCIES ${BASE_PATH}/Lib/librad_tm_mac_x64.dylib) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index 4ac5fea18c..2aded62bcd 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -8,12 +8,11 @@ # shared by other platforms: ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) -ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) -ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-multiplatform TARGETS RapidJSON PACKAGE_HASH 18b0aef4e6e849389916ff6de6682ab9c591ebe15af6ea6017014453c1119ea1) +ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) @@ -30,7 +29,7 @@ ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform # platform-specific: ly_associate_package(PACKAGE_NAME AWSGameLiftServerSDK-3.4.1-rev1-windows TARGETS AWSGameLiftServerSDK PACKAGE_HASH a0586b006e4def65cc25f388de17dc475e417dc1e6f9d96749777c88aa8271b0) ly_associate_package(PACKAGE_NAME Blast-v1.1.7_rc2-9-geb169fe-rev1-windows TARGETS Blast PACKAGE_HASH 216df71f4ffaf4a6ea3f2e77e5f27d68f2325e717fbd1626b00c785b82cd1b67) -ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev2-windows TARGETS DirectXShaderCompilerDxc PACKAGE_HASH decc53e97c7ddda9c7f853a30af7808a7b652a912f59ad2cd4bca5d308aae2c4) +ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev3-windows TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 803e10b94006b834cbbdd30f562a8ddf04174c2cb6956c8399ec164ef8418d1f) ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-windows TARGETS SPIRVCross PACKAGE_HASH 7d601ea9d625b1d509d38bd132a1f433d7e895b16adab76bac6103567a7a6817) ly_associate_package(PACKAGE_NAME freetype-2.10.4.14-windows TARGETS freetype PACKAGE_HASH 88dedc86ccb8c92f14c2c033e51ee7d828fa08eafd6475c6aa963938a99f4bf3) ly_associate_package(PACKAGE_NAME tiff-4.2.0.14-windows TARGETS tiff PACKAGE_HASH ab60d1398e4e1e375ec0f1a00cdb1d812a07c0096d827db575ce52dd6d714207) diff --git a/cmake/3rdParty/Platform/Windows/RadTelemetry_windows.cmake b/cmake/3rdParty/Platform/Windows/RadTelemetry_windows.cmake deleted file mode 100644 index 1caa62e5c5..0000000000 --- a/cmake/3rdParty/Platform/Windows/RadTelemetry_windows.cmake +++ /dev/null @@ -1,11 +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 -# -# - -set(RADTELEMETRY_LIBS ${BASE_PATH}/Lib/rad_tm_win64.lib) - -set(RADTELEMETRY_RUNTIME_DEPENDENCIES ${BASE_PATH}/Dll/rad_tm_win64.dll) diff --git a/Gems/Atom/RHI/DX12/3rdParty/Platform/Windows/pix_windows.cmake b/cmake/3rdParty/Platform/Windows/pix_windows.cmake similarity index 100% rename from Gems/Atom/RHI/DX12/3rdParty/Platform/Windows/pix_windows.cmake rename to cmake/3rdParty/Platform/Windows/pix_windows.cmake diff --git a/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake b/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake index ac7a7427ca..c288460dd0 100644 --- a/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake +++ b/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake @@ -8,7 +8,7 @@ # shared by other platforms: ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) -ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-multiplatform TARGETS RapidJSON PACKAGE_HASH 18b0aef4e6e849389916ff6de6682ab9c591ebe15af6ea6017014453c1119ea1) +ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) ly_associate_package(PACKAGE_NAME lz4-r128-multiplatform TARGETS lz4 PACKAGE_HASH d7b1d5651191db2c339827ad24f669d9d37754143e9173abc986184532f57c9d) diff --git a/cmake/3rdParty/Platform/iOS/RadTelemetry_ios.cmake b/cmake/3rdParty/Platform/iOS/RadTelemetry_ios.cmake deleted file mode 100644 index 0da6750cbe..0000000000 --- a/cmake/3rdParty/Platform/iOS/RadTelemetry_ios.cmake +++ /dev/null @@ -1,9 +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 -# -# - -set(RADTELEMETRY_LIBS ${BASE_PATH}/Lib/librad_tm_ios.a) diff --git a/cmake/3rdParty/Platform/iOS/cmake_ios_files.cmake b/cmake/3rdParty/Platform/iOS/cmake_ios_files.cmake index dc02644f5b..10e3ad7ec2 100644 --- a/cmake/3rdParty/Platform/iOS/cmake_ios_files.cmake +++ b/cmake/3rdParty/Platform/iOS/cmake_ios_files.cmake @@ -8,6 +8,5 @@ set(FILES BuiltInPackages_ios.cmake - RadTelemetry_ios.cmake Wwise_ios.cmake ) diff --git a/cmake/3rdParty/cmake_files.cmake b/cmake/3rdParty/cmake_files.cmake index 99e83da4fe..5f67355965 100644 --- a/cmake/3rdParty/cmake_files.cmake +++ b/cmake/3rdParty/cmake_files.cmake @@ -9,7 +9,7 @@ set(FILES BuiltInPackages.cmake FindOpenGLInterface.cmake - FindRadTelemetry.cmake + FindPIX.cmake FindVkValidation.cmake FindWwise.cmake ) diff --git a/cmake/Configurations.cmake b/cmake/Configurations.cmake index a580f1c572..693cc23c7d 100644 --- a/cmake/Configurations.cmake +++ b/cmake/Configurations.cmake @@ -20,24 +20,33 @@ include_guard(GLOBAL) # \arg:LINK_STATIC_${CONFIGURATION} # \arg:LINK_NON_STATIC # \arg:LINK_NON_STATIC_${CONFIGURATION} -# \arg:LINK_EXECUTABLE -# \arg:LINK_EXECUTABLE_${CONFIGURATION} +# \arg:LINK_EXE +# \arg:LINK_EXE_${CONFIGURATION} +# \arg:LINK_MODULE +# \arg:LINK_MODULE_${CONFIGURATION} +# \arg:LINK_SHARED +# \arg:LINK_SHARED_${CONFIGURATION} # function(ly_append_configurations_options) set(options) set(oneValueArgs) - set(multiValueArgs + set(multiArgs DEFINES COMPILATION LINK LINK_STATIC LINK_NON_STATIC - LINK_EXECUTABLE + LINK_EXE + LINK_MODULE + LINK_SHARED ) - foreach(conf IN LISTS CMAKE_CONFIGURATION_TYPES) - string(TOUPPER ${conf} UCONF) - set(multiValueArgs ${multiValueArgs} DEFINES_${UCONF} COMPILATION_${UCONF} LINK_${UCONF} LINK_STATIC_${UCONF} LINK_NON_STATIC_${UCONF} LINK_EXECUTABLE_${UCONF}) + foreach(arg IN LISTS multiArgs) + list(APPEND multiValueArgs ${arg}) + foreach(conf IN LISTS CMAKE_CONFIGURATION_TYPES) + string(TOUPPER ${conf} UCONF) + list(APPEND multiValueArgs ${arg}_${UCONF}) + endforeach() endforeach() cmake_parse_arguments(ly_append_configurations_options "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) @@ -45,48 +54,46 @@ function(ly_append_configurations_options) if(ly_append_configurations_options_DEFINES) add_compile_definitions(${ly_append_configurations_options_DEFINES}) endif() + if(ly_append_configurations_options_COMPILATION) string(REPLACE ";" " " COMPILATION_STR "${ly_append_configurations_options_COMPILATION}") - string(APPEND CMAKE_C_FLAGS " " ${COMPILATION_STR}) - string(APPEND CMAKE_CXX_FLAGS " " ${COMPILATION_STR}) - set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} PARENT_SCOPE) - set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} PARENT_SCOPE) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COMPILATION_STR}" PARENT_SCOPE) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COMPILATION_STR}" PARENT_SCOPE) endif() + if(ly_append_configurations_options_LINK) string(REPLACE ";" " " LINK_STR "${ly_append_configurations_options_LINK}") - string(APPEND LINK_OPTIONS " " ${LINK_STR}) - set(LINK_OPTIONS ${LINK_OPTIONS} PARENT_SCOPE) - - # Not defining these issue warnings, TODO: investigate - set(CMAKE_STATIC_LINKER_FLAGS ${LINK_OPTIONS} PARENT_SCOPE) - set(CMAKE_MODULE_LINKER_FLAGS ${LINK_OPTIONS} PARENT_SCOPE) - set(CMAKE_SHARED_LINKER_FLAGS ${LINK_OPTIONS} PARENT_SCOPE) - set(CMAKE_EXE_LINKER_FLAGS ${LINK_OPTIONS} PARENT_SCOPE) + set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} ${LINK_STR}" PARENT_SCOPE) + set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${LINK_STR}" PARENT_SCOPE) + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${LINK_STR}" PARENT_SCOPE) + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${LINK_OPTIONS}" PARENT_SCOPE) endif() - if(ly_append_configurations_options_LINK_STATIC) - string(REPLACE ";" " " LINK_STATIC_STR "${ly_append_configurations_options_LINK_STATIC}") - string(APPEND LINK_STATIC_OPTIONS " " ${LINK_STATIC_STR}) - set(LINK_STATIC_OPTIONS ${LINK_STATIC_OPTIONS} PARENT_SCOPE) - set(CMAKE_STATIC_LINKER_FLAGS ${LINK_STATIC_OPTIONS} PARENT_SCOPE) + if(ly_append_configurations_options_LINK_STATIC) + string(REPLACE ";" " " LINK_STR "${ly_append_configurations_options_LINK_STATIC}") + set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} ${LINK_STR}" PARENT_SCOPE) endif() if(ly_append_configurations_options_LINK_NON_STATIC) - string(REPLACE ";" " " LINK_NON_STATIC_STR "${ly_append_configurations_options_LINK_NON_STATIC}") - string(APPEND LINK_NON_STATIC_OPTIONS " " ${LINK_NON_STATIC_STR}) - set(LINK_NON_STATIC_OPTIONS ${LINK_NON_STATIC_OPTIONS} PARENT_SCOPE) - - set(CMAKE_MODULE_LINKER_FLAGS ${LINK_NON_STATIC_OPTIONS} PARENT_SCOPE) - set(CMAKE_SHARED_LINKER_FLAGS ${LINK_NON_STATIC_OPTIONS} PARENT_SCOPE) - set(CMAKE_EXE_LINKER_FLAGS ${LINK_NON_STATIC_OPTIONS} PARENT_SCOPE) + string(REPLACE ";" " " LINK_STR "${ly_append_configurations_options_LINK_NON_STATIC}") + set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${LINK_STR}" PARENT_SCOPE) + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${LINK_STR}" PARENT_SCOPE) + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${LINK_STR}" PARENT_SCOPE) endif() - if(ly_append_configurations_options_LINK_EXECUTABLE) - string(REPLACE ";" " " LINK_EXECUTABLE_STR "${ly_append_configurations_options_LINK_EXECUTABLE}") - string(APPEND LINK_EXECUTABLE_OPTIONS " " ${LINK_EXECUTABLE_STR}) - set(LINK_EXECUTABLE_OPTIONS ${LINK_EXECUTABLE_OPTIONS} PARENT_SCOPE) + if(ly_append_configurations_options_LINK_EXE) + string(REPLACE ";" " " LINK_STR "${ly_append_configurations_options_LINK_EXE}") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${LINK_STR}" PARENT_SCOPE) + endif() - set(CMAKE_EXE_LINKER_FLAGS ${LINK_EXECUTABLE_OPTIONS} PARENT_SCOPE) + if(ly_append_configurations_options_LINK_MODULE) + string(REPLACE ";" " " LINK_STR "${ly_append_configurations_options_LINK_MODULE}") + set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${LINK_STR}" PARENT_SCOPE) + endif() + + if(ly_append_configurations_options_LINK_SHARED) + string(REPLACE ";" " " LINK_STR "${ly_append_configurations_options_LINK_SHARED}") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${LINK_STR}" PARENT_SCOPE) endif() foreach(conf IN LISTS CMAKE_CONFIGURATION_TYPES) @@ -100,43 +107,33 @@ function(ly_append_configurations_options) endif() if(ly_append_configurations_options_COMPILATION_${UCONF}) string(REPLACE ";" " " COMPILATION_STR "${ly_append_configurations_options_COMPILATION_${UCONF}}") - string(APPEND CMAKE_C_FLAGS_${UCONF} " " ${COMPILATION_STR}) - string(APPEND CMAKE_CXX_FLAGS_${UCONF} " " ${COMPILATION_STR}) - set(CMAKE_C_FLAGS_${UCONF} ${CMAKE_C_FLAGS_${UCONF}} PARENT_SCOPE) - set(CMAKE_CXX_FLAGS_${UCONF} ${CMAKE_CXX_FLAGS_${UCONF}} PARENT_SCOPE) + set(CMAKE_C_FLAGS_${UCONF} "${CMAKE_C_FLAGS_${UCONF}} ${COMPILATION_STR}" PARENT_SCOPE) + set(CMAKE_CXX_FLAGS_${UCONF} "${CMAKE_CXX_FLAGS_${UCONF}} ${COMPILATION_STR}" PARENT_SCOPE) endif() if(ly_append_configurations_options_LINK_${UCONF}) string(REPLACE ";" " " LINK_STR "${ly_append_configurations_options_LINK_${UCONF}}") - string(APPEND LINK_OPTIONS_${UCONF} " " ${LINK_STR}) - set(LINK_OPTIONS_${UCONF} ${LINK_OPTIONS_${UCONF}} PARENT_SCOPE) - - set(CMAKE_STATIC_LINKER_FLAGS_${UCONF} ${LINK_OPTIONS_${UCONF}} PARENT_SCOPE) - set(CMAKE_MODULE_LINKER_FLAGS_${UCONF} ${LINK_OPTIONS_${UCONF}} PARENT_SCOPE) - set(CMAKE_SHARED_LINKER_FLAGS_${UCONF} ${LINK_OPTIONS_${UCONF}} PARENT_SCOPE) - set(CMAKE_EXE_LINKER_FLAGS_${UCONF} ${LINK_OPTIONS_${UCONF}} PARENT_SCOPE) + set(CMAKE_STATIC_LINKER_FLAGS_${UCONF} "${CMAKE_STATIC_LINKER_FLAGS_${UCONF}} ${LINK_STR}" PARENT_SCOPE) + set(CMAKE_MODULE_LINKER_FLAGS_${UCONF} "${CMAKE_MODULE_LINKER_FLAGS_${UCONF}} ${LINK_STR}" PARENT_SCOPE) + set(CMAKE_SHARED_LINKER_FLAGS_${UCONF} "${CMAKE_SHARED_LINKER_FLAGS_${UCONF}} ${LINK_STR}" PARENT_SCOPE) + set(CMAKE_EXE_LINKER_FLAGS_${UCONF} "${CMAKE_EXE_LINKER_FLAGS_${UCONF}} ${LINK_STR}" PARENT_SCOPE) endif() if(ly_append_configurations_options_LINK_STATIC_${UCONF}) - string(REPLACE ";" " " LINK_STATIC_STR "${ly_append_configurations_options_LINK_STATIC_${UCONF}}") - string(APPEND LINK_STATIC_OPTIONS_${UCONF} " " ${LINK_STATIC_STR}) - set(LINK_STATIC_OPTIONS_${UCONF} ${LINK_STATIC_OPTIONS_${UCONF}} PARENT_SCOPE) - - set(CMAKE_STATIC_LINKER_FLAGS_${UCONF} ${LINK_STATIC_OPTIONS_${UCONF}} PARENT_SCOPE) + string(REPLACE ";" " " LINK_STR "${ly_append_configurations_options_LINK_STATIC_${UCONF}}") + set(CMAKE_STATIC_LINKER_FLAGS_${UCONF} "${CMAKE_STATIC_LINKER_FLAGS_${UCONF}} ${LINK_STR}" PARENT_SCOPE) endif() if(ly_append_configurations_options_LINK_NON_STATIC_${UCONF}) - string(REPLACE ";" " " LINK_NON_STATIC_STR "${ly_append_configurations_options_LINK_NON_STATIC_${UCONF}}") - string(APPEND LINK_NON_STATIC_OPTIONS_${UCONF} " " ${LINK_NON_STATIC_STR}) - set(LINK_NON_STATIC_OPTIONS_${UCONF} ${LINK_NON_STATIC_OPTIONS_${UCONF}} PARENT_SCOPE) - - set(CMAKE_MODULE_LINKER_FLAGS_${UCONF} ${LINK_NON_STATIC_OPTIONS_${UCONF}} PARENT_SCOPE) - set(CMAKE_SHARED_LINKER_FLAGS_${UCONF} ${LINK_NON_STATIC_OPTIONS_${UCONF}} PARENT_SCOPE) - set(CMAKE_EXE_LINKER_FLAGS_${UCONF} ${LINK_NON_STATIC_OPTIONS_${UCONF}} PARENT_SCOPE) + string(REPLACE ";" " " LINK_STR "${ly_append_configurations_options_LINK_NON_STATIC_${UCONF}}") + set(CMAKE_MODULE_LINKER_FLAGS_${UCONF} "${CMAKE_MODULE_LINKER_FLAGS_${UCONF}} ${LINK_STR}" PARENT_SCOPE) + set(CMAKE_SHARED_LINKER_FLAGS_${UCONF} "${CMAKE_SHARED_LINKER_FLAGS_${UCONF}} ${LINK_STR}" PARENT_SCOPE) + set(CMAKE_EXE_LINKER_FLAGS_${UCONF} "${CMAKE_EXE_LINKER_FLAGS_${UCONF}} ${LINK_STR}" PARENT_SCOPE) endif() - if(ly_append_configurations_options_LINK_EXECUTABLE_${UCONF}) - string(REPLACE ";" " " LINK_EXECUTABLE_STR "${ly_append_configurations_options_LINK_EXECUTABLE_${UCONF}}") - string(APPEND LINK_EXECUTABLE_OPTIONS_${UCONF} " " ${LINK_EXECUTABLE_STR}) - set(LINK_EXECUTABLE_OPTIONS_${UCONF} ${LINK_EXECUTABLE_OPTIONS_${UCONF}} PARENT_SCOPE) - - set(CMAKE_EXE_LINKER_FLAGS_${UCONF} ${LINK_EXECUTABLE_OPTIONS_${UCONF}} PARENT_SCOPE) + if(ly_append_configurations_options_LINK_EXE_${UCONF}) + string(REPLACE ";" " " LINK_STR "${ly_append_configurations_options_LINK_EXE_${UCONF}}") + set(CMAKE_EXE_LINKER_FLAGS_${UCONF} "${CMAKE_EXE_LINKER_FLAGS_${UCONF}} ${LINK_STR}" PARENT_SCOPE) + endif() + if(ly_append_configurations_options_LINK_MODULE_${UCONF}) + string(REPLACE ";" " " LINK_STR "${ly_append_configurations_options_LINK_MODULE_${UCONF}}") + set(CMAKE_MODULE_LINKER_FLAGS_${UCONF} "${CMAKE_MODULE_LINKER_FLAGS_${UCONF}} ${LINK_STR}" PARENT_SCOPE) endif() endforeach() diff --git a/cmake/Platform/Android/PAL_android.cmake b/cmake/Platform/Android/PAL_android.cmake index 8a7c6406b7..1ef36b1af6 100644 --- a/cmake/Platform/Android/PAL_android.cmake +++ b/cmake/Platform/Android/PAL_android.cmake @@ -18,6 +18,8 @@ ly_set(PAL_TRAIT_BUILD_UNITY_EXCLUDE_EXTENSIONS) ly_set(PAL_TRAIT_BUILD_EXCLUDE_ALL_TEST_RUNS_FROM_IDE TRUE) ly_set(PAL_TRAIT_BUILD_CPACK_SUPPORTED FALSE) +ly_set(PAL_TRAIT_PROF_PIX_SUPPORTED FALSE) + # Test library support ly_set(PAL_TRAIT_TEST_GOOGLE_TEST_SUPPORTED FALSE) ly_set(PAL_TRAIT_TEST_GOOGLE_BENCHMARK_SUPPORTED FALSE) diff --git a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake index 118a515e30..9353e4eb1c 100644 --- a/cmake/Platform/Common/MSVC/Configurations_msvc.cmake +++ b/cmake/Platform/Common/MSVC/Configurations_msvc.cmake @@ -37,18 +37,13 @@ ly_append_configurations_options( # Disabling some warnings /wd4201 # nonstandard extension used: nameless struct/union. This actually became part of the C++11 std, MS has an open issue: https://developercommunity.visualstudio.com/t/warning-level-4-generates-a-bogus-warning-c4201-no/103064 - # Disabling these warnings while they get fixed - /wd4244 # conversion, possible loss of data - /wd4245 # conversion, signed/unsigned mismatch - /wd4389 # comparison, signed/unsigned mismatch - # Enabling warnings that are disabled by default from /W4 # https://docs.microsoft.com/en-us/cpp/preprocessor/compiler-warnings-that-are-off-by-default?view=vs-2019 - # /we4296 # 'operator': expression is always false + /we4296 # 'operator': expression is always false # /we4426 # optimization flags changed after including header, may be due to #pragma optimize() # /we4464 # relative include path contains '..' # /we4619 # #pragma warning: there is no warning number 'number' - # /we4777 # 'function' : format string 'string' requires an argument of type 'type1', but variadic argument number has type 'type2' looks useful + # /we4777 # 'function' : format string 'string' requires an argument of type 'type1', but variadic argument number has type 'type2' # /we5031 # #pragma warning(pop): likely mismatch, popping warning state pushed in different file # /WE5032 # detected #pragma warning(push) with no corresponding #pragma warning(pop) @@ -64,9 +59,6 @@ ly_append_configurations_options( # It also causes the compiler to place the library name MSVCRTD.lib into the .obj file. /Ob0 # Disables inline expansions /Od # Disables optimization - /RTCsu # Run-Time Error Checks: c Reports when a value is assigned to a smaller data type and results in a data loss (Not supoported by the STL) - # s Enables stack frame run-time error checking - # u Reports when a variable is used without having been initialized COMPILATION_PROFILE /GF # Enable string pooling /Gy # Function level linking @@ -96,6 +88,26 @@ ly_append_configurations_options( /INCREMENTAL:NO ) +set(LY_BUILD_WITH_ADDRESS_SANITIZER FALSE CACHE BOOL "Builds using AddressSanitizer (ASan). Will disable Edit/Continue, Incremental building and Run-Time checks (default = FALSE)") +if(LY_BUILD_WITH_ADDRESS_SANITIZER) + set(LY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG FALSE) + ly_append_configurations_options( + COMPILATION_DEBUG + /fsanitize=address + ) + get_filename_component(link_tools_dir ${CMAKE_LINKER} DIRECTORY) + file(COPY + ${link_tools_dir}/clang_rt.asan_dbg_dynamic-x86_64.dll + DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG}) +else() + ly_append_configurations_options( + COMPILATION_DEBUG + /RTCsu # Run-Time Error Checks: c Reports when a value is assigned to a smaller data type and results in a data loss (Not supoported by the STL) + # s Enables stack frame run-time error checking + # u Reports when a variable is used without having been initialized + ) +endif() + set(LY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG FALSE CACHE BOOL "Indicates if incremental linking is used in debug configurations (default = FALSE)") if(LY_BUILD_WITH_INCREMENTAL_LINKING_DEBUG) ly_append_configurations_options( @@ -118,8 +130,6 @@ endif() ly_set(LY_CXX_SYSTEM_INCLUDE_CONFIGURATION_FLAG /experimental:external # Turns on "external" headers feature for MSVC compilers /external:W0 # Set warning level in external headers to 0. This is used to suppress warnings 3rdParty libraries which uses the "system_includes" option in their json configuration - /wd4193 # Temporary workaround for the /experiment:external feature generating warning C4193: #pragma warning(pop): no matching '#pragma warning(push)' - /wd4702 # Despite we set it to W0, we found that 3rdParty::OpenMesh was issuing these warnings while using some template functions. Disabling it here does the trick ) if(NOT CMAKE_INCLUDE_SYSTEM_FLAG_CXX) ly_set(CMAKE_INCLUDE_SYSTEM_FLAG_CXX /external:I) diff --git a/cmake/Platform/Linux/Install_linux.cmake b/cmake/Platform/Linux/Install_linux.cmake index 08bb9f807e..b3e2093b65 100644 --- a/cmake/Platform/Linux/Install_linux.cmake +++ b/cmake/Platform/Linux/Install_linux.cmake @@ -6,4 +6,20 @@ # # -include(cmake/Platform/Common/Install_common.cmake) \ No newline at end of file +#! ly_install_code_function_override: Linux-specific copy function to handle RPATH fixes +set(ly_copy_template [[ +function(ly_copy source_file target_directory) + file(COPY "${source_file}" DESTINATION "${target_directory}" FILE_PERMISSIONS @LY_COPY_PERMISSIONS@ FOLLOW_SYMLINK_CHAIN) + get_filename_component(target_filename_ext "${source_file}" LAST_EXT) + if("${source_file}" MATCHES "qt/plugins" AND "${target_filename_ext}" STREQUAL ".so") + get_filename_component(target_filename "${source_file}" NAME) + file(RPATH_CHANGE FILE "${target_directory}/${target_filename}" OLD_RPATH "\$ORIGIN/../../lib" NEW_RPATH "\$ORIGIN/..") + endif() +endfunction()]]) + +function(ly_install_code_function_override) + string(CONFIGURE "${ly_copy_template}" ly_copy_function_linux @ONLY) + install(CODE "${ly_copy_function_linux}") +endfunction() + +include(cmake/Platform/Common/Install_common.cmake) diff --git a/cmake/Platform/Linux/PAL_linux.cmake b/cmake/Platform/Linux/PAL_linux.cmake index c137538ac0..528bb5794c 100644 --- a/cmake/Platform/Linux/PAL_linux.cmake +++ b/cmake/Platform/Linux/PAL_linux.cmake @@ -18,6 +18,8 @@ ly_set(PAL_TRAIT_BUILD_UNITY_EXCLUDE_EXTENSIONS) ly_set(PAL_TRAIT_BUILD_EXCLUDE_ALL_TEST_RUNS_FROM_IDE FALSE) ly_set(PAL_TRAIT_BUILD_CPACK_SUPPORTED FALSE) +ly_set(PAL_TRAIT_PROF_PIX_SUPPORTED FALSE) + # Test library support ly_set(PAL_TRAIT_TEST_GOOGLE_TEST_SUPPORTED TRUE) ly_set(PAL_TRAIT_TEST_GOOGLE_BENCHMARK_SUPPORTED TRUE) diff --git a/cmake/Platform/Mac/PAL_mac.cmake b/cmake/Platform/Mac/PAL_mac.cmake index 7ddb4a1b5e..b415daf44a 100644 --- a/cmake/Platform/Mac/PAL_mac.cmake +++ b/cmake/Platform/Mac/PAL_mac.cmake @@ -18,6 +18,8 @@ ly_set(PAL_TRAIT_BUILD_UNITY_EXCLUDE_EXTENSIONS ".mm") ly_set(PAL_TRAIT_BUILD_EXCLUDE_ALL_TEST_RUNS_FROM_IDE FALSE) ly_set(PAL_TRAIT_BUILD_CPACK_SUPPORTED FALSE) +ly_set(PAL_TRAIT_PROF_PIX_SUPPORTED FALSE) + # Test library support ly_set(PAL_TRAIT_TEST_GOOGLE_TEST_SUPPORTED TRUE) ly_set(PAL_TRAIT_TEST_GOOGLE_BENCHMARK_SUPPORTED TRUE) diff --git a/cmake/Platform/Windows/PAL_windows.cmake b/cmake/Platform/Windows/PAL_windows.cmake index f4fa2e676a..f329425cd3 100644 --- a/cmake/Platform/Windows/PAL_windows.cmake +++ b/cmake/Platform/Windows/PAL_windows.cmake @@ -18,6 +18,8 @@ ly_set(PAL_TRAIT_BUILD_UNITY_EXCLUDE_EXTENSIONS) ly_set(PAL_TRAIT_BUILD_EXCLUDE_ALL_TEST_RUNS_FROM_IDE FALSE) ly_set(PAL_TRAIT_BUILD_CPACK_SUPPORTED TRUE) +ly_set(PAL_TRAIT_PROF_PIX_SUPPORTED TRUE) + # Test library support ly_set(PAL_TRAIT_TEST_GOOGLE_TEST_SUPPORTED TRUE) ly_set(PAL_TRAIT_TEST_GOOGLE_BENCHMARK_SUPPORTED TRUE) diff --git a/cmake/Platform/iOS/PAL_ios.cmake b/cmake/Platform/iOS/PAL_ios.cmake index 3da4a13ed2..e1c4b6d37e 100644 --- a/cmake/Platform/iOS/PAL_ios.cmake +++ b/cmake/Platform/iOS/PAL_ios.cmake @@ -18,6 +18,8 @@ ly_set(PAL_TRAIT_BUILD_UNITY_EXCLUDE_EXTENSIONS ".mm") ly_set(PAL_TRAIT_BUILD_EXCLUDE_ALL_TEST_RUNS_FROM_IDE TRUE) ly_set(PAL_TRAIT_BUILD_CPACK_SUPPORTED FALSE) +ly_set(PAL_TRAIT_PROF_PIX_SUPPORTED FALSE) + # Test library support ly_set(PAL_TRAIT_TEST_GOOGLE_TEST_SUPPORTED FALSE) ly_set(PAL_TRAIT_TEST_GOOGLE_BENCHMARK_SUPPORTED FALSE) diff --git a/cmake/TestImpactFramework/LYTestImpactFramework.cmake b/cmake/TestImpactFramework/LYTestImpactFramework.cmake index 7dd2617582..4b8ea226a1 100644 --- a/cmake/TestImpactFramework/LYTestImpactFramework.cmake +++ b/cmake/TestImpactFramework/LYTestImpactFramework.cmake @@ -448,8 +448,9 @@ function(ly_test_impact_post_step) # Directory for binaries built for this profile set(bin_dir "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/$") - # Erase any existing non-persistent data to avoid getting test impact framework out of sync with current repo state + # Erase any existing artifact and non-persistent data to avoid getting test impact framework out of sync with current repo state file(REMOVE_RECURSE "${LY_TEST_IMPACT_TEMP_DIR}") + file(REMOVE_RECURSE "${LY_TEST_IMPACT_ARTIFACT_DIR}") # Export the soruce to target mapping files ly_test_impact_export_source_target_mappings( diff --git a/engine.json b/engine.json index 5d862779c0..63bddc9548 100644 --- a/engine.json +++ b/engine.json @@ -62,7 +62,6 @@ "Gems/PrimitiveAssets", "Gems/PythonAssetBuilder", "Gems/QtForPython", - "Gems/RADTelemetry", "Gems/SaveData", "Gems/SceneLoggingExample", "Gems/SceneProcessing", @@ -77,6 +76,7 @@ "Gems/StartingPointInput", "Gems/StartingPointMovement", "Gems/SurfaceData", + "Gems/Terrain", "Gems/TestAssetBuilder", "Gems/TextureAtlas", "Gems/TickBusOrderViewer", diff --git a/scripts/build/Jenkins/Jenkinsfile b/scripts/build/Jenkins/Jenkinsfile index 1c0409ceec..6231f9006d 100644 --- a/scripts/build/Jenkins/Jenkinsfile +++ b/scripts/build/Jenkins/Jenkinsfile @@ -338,6 +338,11 @@ def PreBuildCommonSteps(Map pipelineConfig, String snapshot, String repositoryNa else command += '.cmd' command += " -u ${pipelineConfig.BUILD_ENTRY_POINT} --platform ${platform} --type clean" palSh(command, "Running ${platform} clean") + + if(fileExists('.lfsconfig')) { + palSh("git lfs install", "LFS config exists. Installing LFS hooks to local repo") + palSh("git lfs pull", "Pulling new LFS objects") + } } } @@ -619,7 +624,7 @@ try { } pipelineProperties.add(disableConcurrentBuilds()) - echo "Running repository: \"${repositoryName}\", pipeline: \"${pipelineName}\", branch: \"${branchName}\"..." + echo "Running repository: \"${repositoryName}\", pipeline: \"${pipelineName}\", branch: \"${branchName}\", CHANGE_ID: \"${env.CHANGE_ID}\", GIT_COMMMIT: \"${scm.GIT_COMMIT}\"..." CheckoutBootstrapScripts(branchName) @@ -643,7 +648,7 @@ try { defaultValue = jenkinsParameter['default_value'] // Use last run's value as default value so we can save values in different Jenkins environment if (jenkinsParameter['use_last_run_value']?.toBoolean()) { - defaultValue = params."$jenkinsParameter['parameter_name']" ?: jenkinsParameter['default_value'] + defaultValue = params."${jenkinsParameter['parameter_name']}" ?: jenkinsParameter['default_value'] } switch (jenkinsParameter['parameter_type']) { case 'string': diff --git a/scripts/build/Platform/Windows/pipeline.json b/scripts/build/Platform/Windows/pipeline.json index 4cfc6f696a..4c736d2292 100644 --- a/scripts/build/Platform/Windows/pipeline.json +++ b/scripts/build/Platform/Windows/pipeline.json @@ -24,28 +24,28 @@ "parameter_type": "string", "default_value": "", "use_last_run_value": true, - "description": "" + "description": "The name of the O3DE project that stacks should be deployed for." }, { "parameter_name": "O3DE_AWS_DEPLOY_REGION", "parameter_type": "string", "default_value": "", "use_last_run_value": true, - "description": "" + "description": "The region to deploy the stacks into." }, { "parameter_name": "ASSUME_ROLE_ARN", "parameter_type": "string", "default_value": "", "use_last_run_value": true, - "description": "" + "description": "The ARN of the IAM role to assume to retrieve temporary AWS credentials." }, { "parameter_name": "COMMIT_ID", "parameter_type": "string", "default_value": "", "use_last_run_value": true, - "description": "" + "description": "The commit ID for locking the version of CDK applications to deploy." } ] } diff --git a/scripts/build/package/Platform/3rdParty/package_filelists/3rdParty.json b/scripts/build/package/Platform/3rdParty/package_filelists/3rdParty.json index a9ed45daca..915368dd0b 100644 --- a/scripts/build/package/Platform/3rdParty/package_filelists/3rdParty.json +++ b/scripts/build/package/Platform/3rdParty/package_filelists/3rdParty.json @@ -12,7 +12,6 @@ "FbxSdk/2016.1.2-az.1/**": "#include", "OpenSSL/1.1.1b-noasm-az/**": "#include", "Qt/5.15.1.2-az/**": "#include", - "RadTelemetry/3.5.0.17/**": "#include", "tiff/3.9.5-az.3/**": "#include", "Wwise/2019.2.8.7432/**": "#include" }