Merge branch 'main' into Atom/antonmic/PassChanges
This commit is contained in:
@@ -13,6 +13,7 @@ AllowShortFunctionsOnASingleLine: None
|
||||
AllowShortLambdasOnASingleLine: None
|
||||
AlwaysBreakAfterReturnType: None
|
||||
AlwaysBreakTemplateDeclarations: true
|
||||
BinPackParameters: false
|
||||
BreakBeforeBraces: Custom
|
||||
BraceWrapping:
|
||||
AfterClass: true
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
|
||||
its licensors.
|
||||
|
||||
For complete copyright and license terms please see the LICENSE at the root of this
|
||||
distribution (the "License"). All use of this software is governed by the License,
|
||||
or, if provided, by the license below or the license accompanying this file. Do not
|
||||
remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
"""
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
|
||||
its licensors.
|
||||
|
||||
For complete copyright and license terms please see the LICENSE at the root of this
|
||||
distribution (the "License"). All use of this software is governed by the License,
|
||||
or, if provided, by the license below or the license accompanying this file. Do not
|
||||
remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import pytest
|
||||
import time
|
||||
import typing
|
||||
|
||||
from datetime import datetime
|
||||
import ly_test_tools.log.log_monitor
|
||||
|
||||
from assetpipeline.ap_fixtures.asset_processor_fixture import asset_processor as asset_processor
|
||||
from AWS.common.aws_utils import aws_utils
|
||||
from AWS.common.aws_credentials import aws_credentials
|
||||
from AWS.Windows.resource_mappings.resource_mappings import resource_mappings
|
||||
from AWS.Windows.cdk.cdk import cdk
|
||||
from .aws_metrics_utils import aws_metrics_utils
|
||||
|
||||
AWS_METRICS_FEATURE_NAME = 'AWSMetrics'
|
||||
GAME_LOG_NAME = 'Game.log'
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def setup(launcher: ly_test_tools.launchers.Launcher,
|
||||
cdk: cdk,
|
||||
asset_processor: asset_processor,
|
||||
resource_mappings: resource_mappings,
|
||||
context_variable: str = '') -> typing.Tuple[ly_test_tools.log.log_monitor.LogMonitor, str, str]:
|
||||
"""
|
||||
Set up the CDK application and start the log monitor.
|
||||
:param launcher: Client launcher for running the test level.
|
||||
:param cdk: CDK application for deploying the AWS resources.
|
||||
:param asset_processor: asset_processor fixture.
|
||||
:param resource_mappings: resource_mappings fixture.
|
||||
:param context_variable: context_variable for enable optional CDK feature.
|
||||
:return log monitor object, metrics file path and the metrics stack name.
|
||||
"""
|
||||
logger.info(f'Cdk stack names:\n{cdk.list()}')
|
||||
stacks = cdk.deploy(context_variable=context_variable)
|
||||
resource_mappings.populate_output_keys(stacks)
|
||||
|
||||
asset_processor.start()
|
||||
asset_processor.wait_for_idle()
|
||||
|
||||
metrics_file_path = os.path.join(launcher.workspace.paths.project(), 'user',
|
||||
AWS_METRICS_FEATURE_NAME, 'metrics.json')
|
||||
remove_file(metrics_file_path)
|
||||
|
||||
file_to_monitor = os.path.join(launcher.workspace.paths.project_log(), GAME_LOG_NAME)
|
||||
remove_file(file_to_monitor)
|
||||
|
||||
# Initialize the log monitor.
|
||||
log_monitor = ly_test_tools.log.log_monitor.LogMonitor(launcher=launcher, log_file_path=file_to_monitor)
|
||||
|
||||
return log_monitor, metrics_file_path, stacks[0]
|
||||
|
||||
|
||||
def monitor_metrics_submission(log_monitor: ly_test_tools.log.log_monitor.LogMonitor) -> None:
|
||||
"""
|
||||
Monitor the messages and notifications for submitting metrics.
|
||||
:param log_monitor: Log monitor to check the log messages.
|
||||
"""
|
||||
expected_lines = [
|
||||
'(Script) - Submitted metrics without buffer.',
|
||||
'(Script) - Submitted metrics with buffer.',
|
||||
'(Script) - Metrics is sent successfully.'
|
||||
]
|
||||
|
||||
unexpected_lines = [
|
||||
'(Script) - Failed to submit metrics without buffer.',
|
||||
'(Script) - Failed to submit metrics with buffer.',
|
||||
'(Script) - Failed to send metrics.'
|
||||
]
|
||||
|
||||
result = log_monitor.monitor_log_for_lines(
|
||||
expected_lines=expected_lines,
|
||||
unexpected_lines=unexpected_lines,
|
||||
halt_on_unexpected=True)
|
||||
|
||||
# Assert the log monitor detected expected lines and did not detect any unexpected lines.
|
||||
assert result, (
|
||||
f'Log monitoring failed. Used expected_lines values: {expected_lines} & '
|
||||
f'unexpected_lines values: {unexpected_lines}')
|
||||
|
||||
|
||||
def remove_file(file_path: str) -> None:
|
||||
"""
|
||||
Remove a local file and its directory.
|
||||
:param file_path: Path to the local file.
|
||||
"""
|
||||
if os.path.exists(file_path):
|
||||
os.remove(file_path)
|
||||
|
||||
file_dir = os.path.dirname(file_path)
|
||||
if os.path.exists(file_dir) and len(os.listdir(file_dir)) == 0:
|
||||
os.rmdir(file_dir)
|
||||
|
||||
|
||||
@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.parametrize('resource_mappings_filename', ['aws_resource_mappings.json'])
|
||||
@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.parametrize('session_name', ['o3de-Automation-session'])
|
||||
class TestAWSMetrics_Windows(object):
|
||||
def test_AWSMetrics_RealTimeAnalytics_MetricsSentToCloudWatch(self,
|
||||
level: str,
|
||||
launcher: ly_test_tools.launchers.Launcher,
|
||||
asset_processor: pytest.fixture,
|
||||
workspace: pytest.fixture,
|
||||
aws_utils: aws_utils,
|
||||
aws_credentials: aws_credentials,
|
||||
resource_mappings: resource_mappings,
|
||||
cdk: cdk,
|
||||
aws_metrics_utils: aws_metrics_utils,
|
||||
):
|
||||
"""
|
||||
Tests that the submitted metrics are sent to CloudWatch for real-time analytics.
|
||||
"""
|
||||
log_monitor, metrics_file_path, stack_name = setup(launcher, cdk, asset_processor, resource_mappings)
|
||||
|
||||
# Start the Kinesis Data Analytics application for real-time analytics.
|
||||
analytics_application_name = f'{stack_name}-AnalyticsApplication'
|
||||
aws_metrics_utils.start_kinesis_data_analytics_application(analytics_application_name)
|
||||
|
||||
launcher.args = ['+LoadLevel', level]
|
||||
launcher.args.extend(['-rhi=null'])
|
||||
|
||||
with launcher.start(launch_ap=False):
|
||||
start_time = datetime.utcnow()
|
||||
monitor_metrics_submission(log_monitor)
|
||||
# Verify that operational health metrics are delivered to CloudWatch.
|
||||
aws_metrics_utils.verify_cloud_watch_delivery(
|
||||
'AWS/Lambda',
|
||||
'Invocations',
|
||||
[{'Name': 'FunctionName',
|
||||
'Value': f'{stack_name}-AnalyticsProcessingLambda'}],
|
||||
start_time)
|
||||
logger.info('Operational health metrics sent to CloudWatch.')
|
||||
|
||||
aws_metrics_utils.verify_cloud_watch_delivery(
|
||||
AWS_METRICS_FEATURE_NAME,
|
||||
'TotalLogins',
|
||||
[],
|
||||
start_time)
|
||||
logger.info('Real-time metrics sent to CloudWatch.')
|
||||
|
||||
# Stop the Kinesis Data Analytics application.
|
||||
aws_metrics_utils.stop_kinesis_data_analytics_application(analytics_application_name)
|
||||
|
||||
def test_AWSMetrics_UnauthorizedUser_RequestRejected(self,
|
||||
level: str,
|
||||
launcher: ly_test_tools.launchers.Launcher,
|
||||
cdk: cdk,
|
||||
aws_credentials: aws_credentials,
|
||||
asset_processor: pytest.fixture,
|
||||
resource_mappings: resource_mappings,
|
||||
workspace: pytest.fixture):
|
||||
"""
|
||||
Tests that unauthorized users cannot send metrics events to the AWS backed backend.
|
||||
"""
|
||||
log_monitor, metrics_file_path, stack_name = setup(launcher, cdk, asset_processor, resource_mappings)
|
||||
# Set invalid AWS credentials.
|
||||
launcher.args = ['+LoadLevel', level, '+cl_awsAccessKey', 'AKIAIOSFODNN7EXAMPLE',
|
||||
'+cl_awsSecretKey', 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY']
|
||||
launcher.args.extend(['-rhi=null'])
|
||||
|
||||
with launcher.start(launch_ap=False):
|
||||
result = log_monitor.monitor_log_for_lines(
|
||||
expected_lines=['(Script) - Failed to send metrics.'],
|
||||
unexpected_lines=['(Script) - Metrics is sent successfully.'],
|
||||
halt_on_unexpected=True)
|
||||
assert result, 'Metrics events are sent successfully by unauthorized user'
|
||||
logger.info('Unauthorized user is rejected to send metrics.')
|
||||
|
||||
def test_AWSMetrics_BatchAnalytics_MetricsDeliveredToS3(self,
|
||||
level: str,
|
||||
launcher: ly_test_tools.launchers.Launcher,
|
||||
cdk: cdk,
|
||||
aws_credentials: aws_credentials,
|
||||
asset_processor: pytest.fixture,
|
||||
resource_mappings: resource_mappings,
|
||||
aws_utils: aws_utils,
|
||||
aws_metrics_utils: aws_metrics_utils,
|
||||
workspace: pytest.fixture):
|
||||
"""
|
||||
Tests that the submitted metrics are sent to the data lake for batch analytics.
|
||||
"""
|
||||
log_monitor, metrics_file_path, stack_name = setup(launcher, cdk, asset_processor, resource_mappings,
|
||||
context_variable='batch_processing=true')
|
||||
|
||||
analytics_bucket_name = aws_metrics_utils.get_analytics_bucket_name(stack_name)
|
||||
|
||||
launcher.args = ['+LoadLevel', level]
|
||||
launcher.args.extend(['-rhi=null'])
|
||||
|
||||
with launcher.start(launch_ap=False):
|
||||
start_time = datetime.utcnow()
|
||||
monitor_metrics_submission(log_monitor)
|
||||
# Verify that operational health metrics are delivered to CloudWatch.
|
||||
aws_metrics_utils.verify_cloud_watch_delivery(
|
||||
'AWS/Lambda',
|
||||
'Invocations',
|
||||
[{'Name': 'FunctionName',
|
||||
'Value': f'{stack_name}-EventsProcessingLambda'}],
|
||||
start_time)
|
||||
logger.info('Operational health metrics sent to CloudWatch.')
|
||||
|
||||
aws_metrics_utils.verify_s3_delivery(analytics_bucket_name)
|
||||
logger.info('Metrics sent to S3.')
|
||||
|
||||
# Run the glue crawler to populate the AWS Glue Data Catalog with tables.
|
||||
aws_metrics_utils.run_glue_crawler(f'{stack_name}-EventsCrawler')
|
||||
# Run named queries on the table to verify the batch analytics.
|
||||
aws_metrics_utils.run_named_queries(f'{stack_name}-AthenaWorkGroup')
|
||||
logger.info('Query metrics from S3 successfully.')
|
||||
|
||||
# Kinesis Data Firehose buffers incoming data before it delivers it to Amazon S3. Sleep for the
|
||||
# default interval (60s) to make sure that all the metrics are sent to the bucket before cleanup.
|
||||
time.sleep(60)
|
||||
# Empty the S3 bucket. S3 buckets can only be deleted successfully when it doesn't contain any object.
|
||||
aws_metrics_utils.empty_s3_bucket(analytics_bucket_name)
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
"""
|
||||
All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
|
||||
its licensors.
|
||||
|
||||
For complete copyright and license terms please see the LICENSE at the root of this
|
||||
distribution (the "License"). All use of this software is governed by the License,
|
||||
or, if provided, by the license below or the license accompanying this file. Do not
|
||||
remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import pathlib
|
||||
import pytest
|
||||
import typing
|
||||
|
||||
from datetime import datetime
|
||||
from botocore.exceptions import WaiterError
|
||||
|
||||
from AWS.common.aws_utils import AwsUtils
|
||||
from .aws_metrics_waiters import KinesisAnalyticsApplicationUpdatedWaiter, \
|
||||
CloudWatchMetricsDeliveredWaiter, DataLakeMetricsDeliveredWaiter, GlueCrawlerReadyWaiter
|
||||
|
||||
logging.getLogger('boto').setLevel(logging.CRITICAL)
|
||||
|
||||
# Expected directory and file extension for the S3 objects.
|
||||
EXPECTED_S3_DIRECTORY = 'firehose_events/'
|
||||
EXPECTED_S3_OBJECT_EXTENSION = '.parquet'
|
||||
|
||||
|
||||
class AWSMetricsUtils:
|
||||
"""
|
||||
Provide utils functions for the AWSMetrics gem to interact with the deployed resources.
|
||||
"""
|
||||
|
||||
def __init__(self, aws_utils: AwsUtils):
|
||||
self._aws_util = aws_utils
|
||||
|
||||
def start_kinesis_data_analytics_application(self, application_name: str) -> None:
|
||||
"""
|
||||
Start the Kenisis Data Analytics application for real-time analytics.
|
||||
:param application_name: Name of the Kenisis Data Analytics application.
|
||||
"""
|
||||
input_id = self.get_kinesis_analytics_application_input_id(application_name)
|
||||
assert input_id, 'invalid Kinesis Data Analytics application input.'
|
||||
|
||||
client = self._aws_util.client('kinesisanalytics')
|
||||
try:
|
||||
client.start_application(
|
||||
ApplicationName=application_name,
|
||||
InputConfigurations=[
|
||||
{
|
||||
'Id': input_id,
|
||||
'InputStartingPositionConfiguration': {
|
||||
'InputStartingPosition': 'NOW'
|
||||
}
|
||||
},
|
||||
]
|
||||
)
|
||||
except client.exceptions.ResourceInUseException:
|
||||
# The application has been started.
|
||||
return
|
||||
|
||||
try:
|
||||
KinesisAnalyticsApplicationUpdatedWaiter(client, 'RUNNING').wait(application_name=application_name)
|
||||
except WaiterError as e:
|
||||
assert False, f'Failed to start the Kinesis Data Analytics application: {str(e)}.'
|
||||
|
||||
def get_kinesis_analytics_application_input_id(self, application_name: str) -> str:
|
||||
"""
|
||||
Get the input ID for the Kenisis Data Analytics application.
|
||||
:param application_name: Name of the Kenisis Data Analytics application.
|
||||
:return: Input ID for the Kenisis Data Analytics application.
|
||||
"""
|
||||
client = self._aws_util.client('kinesisanalytics')
|
||||
response = client.describe_application(
|
||||
ApplicationName=application_name
|
||||
)
|
||||
if not response:
|
||||
return ''
|
||||
input_descriptions = response.get('ApplicationDetail', {}).get('InputDescriptions', [])
|
||||
if len(input_descriptions) != 1:
|
||||
return ''
|
||||
|
||||
return input_descriptions[0].get('InputId', '')
|
||||
|
||||
def stop_kinesis_data_analytics_application(self, application_name: str) -> None:
|
||||
"""
|
||||
Stop the Kenisis Data Analytics application.
|
||||
:param application_name: Name of the Kenisis Data Analytics application.
|
||||
"""
|
||||
client = self._aws_util.client('kinesisanalytics')
|
||||
client.stop_application(
|
||||
ApplicationName=application_name
|
||||
)
|
||||
|
||||
try:
|
||||
KinesisAnalyticsApplicationUpdatedWaiter(client, 'READY').wait(application_name=application_name)
|
||||
except WaiterError as e:
|
||||
assert False, f'Failed to stop the Kinesis Data Analytics application: {str(e)}.'
|
||||
|
||||
def verify_cloud_watch_delivery(self, namespace: str, metrics_name: str,
|
||||
dimensions: typing.List[dict], start_time: datetime) -> None:
|
||||
"""
|
||||
Verify that the expected metrics is delivered to CloudWatch.
|
||||
:param namespace: Namespace of the metrics.
|
||||
:param metrics_name: Name of the metrics.
|
||||
:param dimensions: Dimensions of the metrics.
|
||||
:param start_time: Start time for generating the metrics.
|
||||
"""
|
||||
client = self._aws_util.client('cloudwatch')
|
||||
|
||||
try:
|
||||
CloudWatchMetricsDeliveredWaiter(client).wait(
|
||||
namespace=namespace,
|
||||
metrics_name=metrics_name,
|
||||
dimensions=dimensions,
|
||||
start_time=start_time
|
||||
)
|
||||
except WaiterError as e:
|
||||
assert False, f'Failed to deliver metrics to CloudWatch: {str(e)}.'
|
||||
|
||||
def verify_s3_delivery(self, analytics_bucket_name: str) -> None:
|
||||
"""
|
||||
Verify that metrics are delivered to S3 for batch analytics successfully.
|
||||
:param analytics_bucket_name: Name of the deployed S3 bucket.
|
||||
"""
|
||||
client = self._aws_util.client('s3')
|
||||
bucket_name = analytics_bucket_name
|
||||
|
||||
try:
|
||||
DataLakeMetricsDeliveredWaiter(client).wait(bucket_name=bucket_name, prefix=EXPECTED_S3_DIRECTORY)
|
||||
except WaiterError as e:
|
||||
assert False, f'Failed to find the S3 directory for storing metrics data: {str(e)}.'
|
||||
|
||||
# Check whether the data is converted to the expected data format.
|
||||
response = client.list_objects_v2(
|
||||
Bucket=bucket_name,
|
||||
Prefix=EXPECTED_S3_DIRECTORY
|
||||
)
|
||||
assert response.get('KeyCount', 0) != 0, f'Failed to deliver metrics to the S3 bucket {bucket_name}.'
|
||||
|
||||
s3_objects = response.get('Contents', [])
|
||||
for s3_object in s3_objects:
|
||||
key = s3_object.get('Key', '')
|
||||
assert pathlib.Path(key).suffix == EXPECTED_S3_OBJECT_EXTENSION, \
|
||||
f'Invalid data format is found in the S3 bucket {bucket_name}'
|
||||
|
||||
def run_glue_crawler(self, crawler_name: str) -> None:
|
||||
"""
|
||||
Run the Glue crawler and wait for it to finish.
|
||||
:param crawler_name: Name of the Glue crawler
|
||||
"""
|
||||
client = self._aws_util.client('glue')
|
||||
try:
|
||||
client.start_crawler(
|
||||
Name=crawler_name
|
||||
)
|
||||
except client.exceptions.CrawlerRunningException:
|
||||
# The crawler has already been started.
|
||||
return
|
||||
|
||||
try:
|
||||
GlueCrawlerReadyWaiter(client).wait(crawler_name=crawler_name)
|
||||
except WaiterError as e:
|
||||
assert False, f'Failed to run the Glue crawler: {str(e)}.'
|
||||
|
||||
def run_named_queries(self, work_group: str) -> None:
|
||||
"""
|
||||
Run the named queries under the specific Athena work group.
|
||||
:param work_group: Name of the Athena work group.
|
||||
"""
|
||||
client = self._aws_util.client('athena')
|
||||
# List all the named queries.
|
||||
response = client.list_named_queries(
|
||||
WorkGroup=work_group
|
||||
)
|
||||
named_query_ids = response.get('NamedQueryIds', [])
|
||||
|
||||
# Run each of the queries.
|
||||
for named_query_id in named_query_ids:
|
||||
get_named_query_response = client.get_named_query(
|
||||
NamedQueryId=named_query_id
|
||||
)
|
||||
named_query = get_named_query_response.get('NamedQuery', {})
|
||||
|
||||
start_query_execution_response = client.start_query_execution(
|
||||
QueryString=named_query.get('QueryString', ''),
|
||||
QueryExecutionContext={
|
||||
'Database': named_query.get('Database', '')
|
||||
},
|
||||
WorkGroup=work_group
|
||||
)
|
||||
|
||||
# Wait for the query to finish.
|
||||
state = 'RUNNING'
|
||||
while state == 'QUEUED' or state == 'RUNNING':
|
||||
get_query_execution_response = client.get_query_execution(
|
||||
QueryExecutionId=start_query_execution_response.get('QueryExecutionId', '')
|
||||
)
|
||||
|
||||
state = get_query_execution_response.get('QueryExecution', {}).get('Status', {}).get('State', '')
|
||||
|
||||
assert state == 'SUCCEEDED', f'Failed to run the named query {named_query.get("Name", {})}'
|
||||
|
||||
def empty_s3_bucket(self, bucket_name: str) -> None:
|
||||
"""
|
||||
Empty the S3 bucket following:
|
||||
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/migrations3.html
|
||||
|
||||
:param bucket_name: Name of the S3 bucket.
|
||||
"""
|
||||
|
||||
s3 = self._aws_util.resource('s3')
|
||||
bucket = s3.Bucket(bucket_name)
|
||||
|
||||
for key in bucket.objects.all():
|
||||
key.delete()
|
||||
|
||||
def get_analytics_bucket_name(self, stack_name: str) -> str:
|
||||
"""
|
||||
Get the name of the deployed S3 bucket.
|
||||
:param stack_name: Name of the CloudFormation stack.
|
||||
:return: Name of the deployed S3 bucket.
|
||||
"""
|
||||
|
||||
client = self._aws_util.client('cloudformation')
|
||||
|
||||
response = client.describe_stack_resources(
|
||||
StackName=stack_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')
|
||||
def aws_metrics_utils(
|
||||
request: pytest.fixture,
|
||||
aws_utils: pytest.fixture):
|
||||
"""
|
||||
Fixture for the AWS metrics util functions.
|
||||
:param request: _pytest.fixtures.SubRequest class that handles getting
|
||||
a pytest fixture from a pytest function/fixture.
|
||||
:param aws_utils: aws_utils fixture.
|
||||
"""
|
||||
aws_utils_obj = AWSMetricsUtils(aws_utils)
|
||||
return aws_utils_obj
|
||||
@@ -0,0 +1,142 @@
|
||||
"""
|
||||
All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
|
||||
its licensors.
|
||||
|
||||
For complete copyright and license terms please see the LICENSE at the root of this
|
||||
distribution (the "License"). All use of this software is governed by the License,
|
||||
or, if provided, by the license below or the license accompanying this file. Do not
|
||||
remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
"""
|
||||
|
||||
import botocore.client
|
||||
import logging
|
||||
|
||||
from datetime import timedelta
|
||||
from AWS.common.custom_waiter import CustomWaiter, WaitState
|
||||
|
||||
logging.getLogger('boto').setLevel(logging.CRITICAL)
|
||||
|
||||
|
||||
class KinesisAnalyticsApplicationUpdatedWaiter(CustomWaiter):
|
||||
"""
|
||||
Subclass of the base custom waiter class.
|
||||
Wait for the Kinesis analytics application being updated to a specific status.
|
||||
"""
|
||||
def __init__(self, client: botocore.client, status: str):
|
||||
"""
|
||||
Initialize the waiter.
|
||||
|
||||
:param client: Boto3 client to use.
|
||||
:param status: Expected status.
|
||||
"""
|
||||
super().__init__(
|
||||
'KinesisAnalyticsApplicationUpdated',
|
||||
'DescribeApplication',
|
||||
'ApplicationDetail.ApplicationStatus',
|
||||
{status: WaitState.SUCCESS},
|
||||
client)
|
||||
|
||||
def wait(self, application_name: str):
|
||||
"""
|
||||
Wait for the expected status.
|
||||
|
||||
:param application_name: Name of the Kinesis analytics application.
|
||||
"""
|
||||
self._wait(ApplicationName=application_name)
|
||||
|
||||
|
||||
class GlueCrawlerReadyWaiter(CustomWaiter):
|
||||
"""
|
||||
Subclass of the base custom waiter class.
|
||||
Wait for the Glue crawler to finish its processing.
|
||||
"""
|
||||
def __init__(self, client: botocore.client):
|
||||
"""
|
||||
Initialize the waiter.
|
||||
|
||||
:param client: Boto3 client to use.
|
||||
"""
|
||||
super().__init__(
|
||||
'GlueCrawlerReady',
|
||||
'GetCrawler',
|
||||
'Crawler.State',
|
||||
{'READY': WaitState.SUCCESS},
|
||||
client)
|
||||
|
||||
def wait(self, crawler_name):
|
||||
"""
|
||||
Wait for the expected status.
|
||||
|
||||
:param crawler_name: Name of the Glue crawler.
|
||||
"""
|
||||
self._wait(Name=crawler_name)
|
||||
|
||||
|
||||
class DataLakeMetricsDeliveredWaiter(CustomWaiter):
|
||||
"""
|
||||
Subclass of the base custom waiter class.
|
||||
Wait for the expected directory being created in the S3 bucket.
|
||||
"""
|
||||
def __init__(self, client: botocore.client):
|
||||
"""
|
||||
Initialize the waiter.
|
||||
|
||||
:param client: Boto3 client to use.
|
||||
"""
|
||||
super().__init__(
|
||||
'DataLakeMetricsDelivered',
|
||||
'ListObjectsV2',
|
||||
'KeyCount > `0`',
|
||||
{True: WaitState.SUCCESS},
|
||||
client)
|
||||
|
||||
def wait(self, bucket_name, prefix):
|
||||
"""
|
||||
Wait for the expected directory being created.
|
||||
|
||||
:param bucket_name: Name of the S3 bucket.
|
||||
:param prefix: Name of the expected directory prefix.
|
||||
"""
|
||||
self._wait(Bucket=bucket_name, Prefix=prefix)
|
||||
|
||||
|
||||
class CloudWatchMetricsDeliveredWaiter(CustomWaiter):
|
||||
"""
|
||||
Subclass of the base custom waiter class.
|
||||
Wait for the expected metrics being delivered to CloudWatch.
|
||||
"""
|
||||
def __init__(self, client: botocore.client):
|
||||
"""
|
||||
Initialize the waiter.
|
||||
|
||||
:param client: Boto3 client to use.
|
||||
"""
|
||||
super().__init__(
|
||||
'CloudWatchMetricsDelivered',
|
||||
'GetMetricStatistics',
|
||||
'length(Datapoints) > `0`',
|
||||
{True: WaitState.SUCCESS},
|
||||
client)
|
||||
|
||||
def wait(self, namespace, metrics_name, dimensions, start_time):
|
||||
"""
|
||||
Wait for the expected metrics being delivered.
|
||||
|
||||
:param namespace: Namespace of the metrics.
|
||||
:param metrics_name: Name of the metrics.
|
||||
:param dimensions: Dimensions of the metrics.
|
||||
:param start_time: Start time for generating the metrics.
|
||||
"""
|
||||
self._wait(
|
||||
Namespace=namespace,
|
||||
MetricName=metrics_name,
|
||||
Dimensions=dimensions,
|
||||
StartTime=start_time,
|
||||
EndTime=start_time + timedelta(0, self.timeout),
|
||||
Period=60,
|
||||
Statistics=[
|
||||
'SampleCount'
|
||||
],
|
||||
Unit='Count'
|
||||
)
|
||||
@@ -16,12 +16,15 @@ import boto3
|
||||
import ly_test_tools.environment.process_utils as process_utils
|
||||
from typing import List
|
||||
|
||||
BOOTSTRAP_STACK_NAME = 'CDKToolkit'
|
||||
BOOTSTRAP_STAGING_BUCKET_LOGIC_ID = 'StagingBucket'
|
||||
|
||||
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, cdk_path: str, project: str, account_id: str,
|
||||
workspace: pytest.fixture, session: boto3.session.Session):
|
||||
"""
|
||||
@@ -49,12 +52,24 @@ class Cdk:
|
||||
env=self._cdk_env,
|
||||
shell=True)
|
||||
|
||||
def bootstrap(self) -> None:
|
||||
"""
|
||||
Deploy the bootstrap stack.
|
||||
"""
|
||||
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)
|
||||
|
||||
def list(self) -> List[str]:
|
||||
"""
|
||||
lists cdk stack names
|
||||
:return List of cdk stack names
|
||||
"""
|
||||
|
||||
if not self._cdk_path:
|
||||
return []
|
||||
|
||||
@@ -82,16 +97,19 @@ class Cdk:
|
||||
env=self._cdk_env,
|
||||
shell=True)
|
||||
|
||||
def deploy(self, context_variable: str = '') -> List[str]:
|
||||
def deploy(self, context_variable: str = '', additonal_params: List[str] = None) -> List[str]:
|
||||
"""
|
||||
Deploys all the CDK stacks.
|
||||
:param context_variable: Context variable for enabling optional features.
|
||||
:param additonal_params: Additonal 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 additonal_params:
|
||||
deploy_cdk_application_cmd.extend(additonal_params)
|
||||
if context_variable:
|
||||
deploy_cdk_application_cmd.extend(['-c', f'{context_variable}'])
|
||||
|
||||
@@ -123,6 +141,38 @@ class Cdk:
|
||||
self._stacks = []
|
||||
self._cdk_path = ''
|
||||
|
||||
@staticmethod
|
||||
def remove_bootstrap_stack(aws_utils: pytest.fixture) -> None:
|
||||
"""
|
||||
Remove the CDK bootstrap stack.
|
||||
:param aws_utils: aws_utils fixture.
|
||||
"""
|
||||
# Check if the bootstrap stack exists.
|
||||
response = aws_utils.client('cloudformation').describe_stacks(
|
||||
StackName=BOOTSTRAP_STACK_NAME
|
||||
)
|
||||
stacks = response.get('Stacks', [])
|
||||
if not stacks:
|
||||
return
|
||||
|
||||
# Clear the bootstrap staging bucket before deleting the bootstrap stack.
|
||||
response = aws_utils.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 = aws_utils.resource('s3')
|
||||
bucket = s3.Bucket(staging_bucket_name)
|
||||
for key in bucket.objects.all():
|
||||
key.delete()
|
||||
|
||||
# Delete the bootstrap stack.
|
||||
aws_utils.client('cloudformation').delete_stack(
|
||||
StackName=BOOTSTRAP_STACK_NAME
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
def cdk(
|
||||
@@ -131,6 +181,7 @@ def cdk(
|
||||
feature_name: str,
|
||||
workspace: pytest.fixture,
|
||||
aws_utils: pytest.fixture,
|
||||
bootstrap_required: bool = True,
|
||||
destroy_stacks_on_teardown: bool = True) -> Cdk:
|
||||
"""
|
||||
Fixture for setting up a Cdk
|
||||
@@ -140,6 +191,8 @@ def cdk(
|
||||
: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 bootstrap_required: Whether the bootstrap stack needs to be created to
|
||||
provision resources the AWS CDK needs to perform the deployment.
|
||||
:param destroy_stacks_on_teardown: option to control calling destroy ot the end of test.
|
||||
:return Cdk class object.
|
||||
"""
|
||||
@@ -147,9 +200,14 @@ def cdk(
|
||||
cdk_path = f'{workspace.paths.engine_root()}/Gems/{feature_name}/cdk'
|
||||
cdk_obj = Cdk(cdk_path, project, aws_utils.assume_account_id(), workspace, aws_utils.assume_session())
|
||||
|
||||
if bootstrap_required:
|
||||
cdk_obj.bootstrap()
|
||||
|
||||
def teardown():
|
||||
if destroy_stacks_on_teardown:
|
||||
cdk_obj.destroy()
|
||||
cdk_obj.remove_bootstrap_stack(aws_utils)
|
||||
|
||||
request.addfinalizer(teardown)
|
||||
|
||||
return cdk_obj
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
|
||||
its licensors.
|
||||
For complete copyright and license terms please see the LICENSE at the root of this
|
||||
distribution (the "License"). All use of this software is governed by the License,
|
||||
or, if provided, by the license below or the license accompanying this file. Do not
|
||||
remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
"""
|
||||
|
||||
import boto3
|
||||
import configparser
|
||||
import logging
|
||||
import os
|
||||
import pytest
|
||||
import typing
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.getLogger('boto').setLevel(logging.CRITICAL)
|
||||
|
||||
|
||||
class AwsCredentials:
|
||||
def __init__(self, profile_name: str):
|
||||
self._profile_name = profile_name
|
||||
|
||||
self._credentials_path = os.environ.get('AWS_SHARED_CREDENTIALS_FILE')
|
||||
if not self._credentials_path:
|
||||
# Home directory location varies based on the operating system, but is referred to using the environment
|
||||
# variables %UserProfile% in Windows and $HOME or ~ (tilde) in Unix-based systems.
|
||||
self._credentials_path = os.path.join(os.environ.get('UserProfile', os.path.expanduser('~')),
|
||||
'.aws', 'credentials')
|
||||
self._credentials_file_exists = os.path.exists(self._credentials_path)
|
||||
|
||||
self._credentials = configparser.ConfigParser()
|
||||
self._credentials.read(self._credentials_path)
|
||||
|
||||
def get_aws_credentials(self) -> typing.Tuple[str, str, str]:
|
||||
"""
|
||||
Get aws credentials stored in the specific named profile.
|
||||
|
||||
:return AWS credentials.
|
||||
"""
|
||||
access_key_id = self._get_aws_credential_attribute_value('aws_access_key_id')
|
||||
secret_access_key = self._get_aws_credential_attribute_value('aws_secret_access_key')
|
||||
session_token = self._get_aws_credential_attribute_value('aws_session_token')
|
||||
|
||||
return access_key_id, secret_access_key, session_token
|
||||
|
||||
def set_aws_credentials_by_session(self, session: boto3.Session) -> None:
|
||||
"""
|
||||
Set AWS credentials stored in the specific named profile using an assumed role session.
|
||||
|
||||
:param session: assumed role session.
|
||||
"""
|
||||
credentials = session.get_credentials().get_frozen_credentials()
|
||||
self.set_aws_credentials(credentials.access_key, credentials.secret_key, credentials.token)
|
||||
|
||||
def set_aws_credentials(self, aws_access_key_id: str, aws_secret_access_key: str,
|
||||
aws_session_token: str) -> None:
|
||||
"""
|
||||
Set AWS credentials stored in the specific named profile.
|
||||
|
||||
:param aws_access_key_id: AWS access key id.
|
||||
:param aws_secret_access_key: AWS secrete access key.
|
||||
:param aws_session_token: AWS assumed role session.
|
||||
"""
|
||||
self._set_aws_credential_attribute_value('aws_access_key_id', aws_access_key_id)
|
||||
self._set_aws_credential_attribute_value('aws_secret_access_key', aws_secret_access_key)
|
||||
self._set_aws_credential_attribute_value('aws_session_token', aws_session_token)
|
||||
|
||||
if (len(self._credentials.sections()) == 0) and (not self._credentials_file_exists):
|
||||
os.remove(self._credentials_path)
|
||||
return
|
||||
|
||||
with open(self._credentials_path, 'w+') as credential_file:
|
||||
self._credentials.write(credential_file)
|
||||
|
||||
def _get_aws_credential_attribute_value(self, attribute_name: str) -> str:
|
||||
"""
|
||||
Get the value of an AWS credential attribute stored in the specific named profile.
|
||||
|
||||
:param attribute_name: Name of the AWS credential attribute.
|
||||
:return Value of the AWS credential attribute.
|
||||
"""
|
||||
try:
|
||||
value = self._credentials.get(self._profile_name, attribute_name)
|
||||
except configparser.NoSectionError:
|
||||
# Named profile or key doesn't exist
|
||||
value = None
|
||||
except configparser.NoOptionError:
|
||||
# Named profile doesn't have the specified attribute
|
||||
value = None
|
||||
|
||||
return value
|
||||
|
||||
def _set_aws_credential_attribute_value(self, attribute_name: str, attribute_value: str) -> None:
|
||||
"""
|
||||
Set the value of an AWS credential attribute stored in the specific named profile.
|
||||
|
||||
:param attribute_name: Name of the AWS credential attribute.
|
||||
:param attribute_value: Value of the AWS credential attribute.
|
||||
"""
|
||||
if self._profile_name not in self._credentials:
|
||||
self._credentials[self._profile_name] = {}
|
||||
|
||||
if attribute_value is None:
|
||||
self._credentials.remove_option(self._profile_name, attribute_name)
|
||||
# Remove the named profile if it doesn't have any AWS credential attribute.
|
||||
if len(self._credentials[self._profile_name]) == 0:
|
||||
self._credentials.remove_section(self._profile_name)
|
||||
else:
|
||||
self._credentials[self._profile_name][attribute_name] = attribute_value
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
def aws_credentials(request: pytest.fixture, aws_utils: pytest.fixture, profile_name: str):
|
||||
"""
|
||||
Fixture for setting up temporary AWS credentials from assume role.
|
||||
|
||||
:param request: _pytest.fixtures.SubRequest class that handles getting
|
||||
a pytest fixture from a pytest function/fixture.
|
||||
:param aws_utils: aws_utils fixture.
|
||||
:param profile_name: Named AWS profile to store temporary credentials.
|
||||
"""
|
||||
aws_credentials_obj = AwsCredentials(profile_name)
|
||||
original_access_key, original_secret_access_key, original_token = aws_credentials_obj.get_aws_credentials()
|
||||
aws_credentials_obj.set_aws_credentials_by_session(aws_utils.assume_session())
|
||||
|
||||
def teardown():
|
||||
# Reset to the named profile using the original AWS credentials
|
||||
aws_credentials_obj.set_aws_credentials(original_access_key, original_secret_access_key, original_token)
|
||||
request.addfinalizer(teardown)
|
||||
|
||||
return aws_credentials_obj
|
||||
@@ -1,82 +1,90 @@
|
||||
"""
|
||||
All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
|
||||
its licensors.
|
||||
For complete copyright and license terms please see the LICENSE at the root of this
|
||||
distribution (the "License"). All use of this software is governed by the License,
|
||||
or, if provided, by the license below or the license accompanying this file. Do not
|
||||
remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
"""
|
||||
import boto3
|
||||
import pytest
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AwsUtils:
|
||||
|
||||
def __init__(self, arn: str, session_name: str, region_name: str):
|
||||
local_session = boto3.Session(profile_name='default')
|
||||
local_sts_client = local_session.client('sts')
|
||||
self._local_account_id = local_sts_client.get_caller_identity()["Account"]
|
||||
logger.info(f'Local Account Id: {self._local_account_id}')
|
||||
|
||||
response = local_sts_client.assume_role(RoleArn=arn, RoleSessionName=session_name)
|
||||
|
||||
self._assume_session = boto3.Session(aws_access_key_id=response['Credentials']['AccessKeyId'],
|
||||
aws_secret_access_key=response['Credentials']['SecretAccessKey'],
|
||||
aws_session_token=response['Credentials']['SessionToken'],
|
||||
region_name=region_name)
|
||||
|
||||
assume_sts_client = self._assume_session.client('sts')
|
||||
assume_account_id = assume_sts_client.get_caller_identity()["Account"]
|
||||
logger.info(f'Assume Account Id: {assume_account_id}')
|
||||
self._assume_account_id = assume_account_id
|
||||
|
||||
def client(self, service: str):
|
||||
"""
|
||||
Get the client for a specific AWS service from configured session
|
||||
:return: Client for the AWS service.
|
||||
"""
|
||||
return self._assume_session.client(service)
|
||||
|
||||
def assume_session(self):
|
||||
return self._assume_session
|
||||
|
||||
def local_account_id(self):
|
||||
return self._local_account_id
|
||||
|
||||
def assume_account_id(self):
|
||||
return self._assume_account_id
|
||||
|
||||
def destroy(self) -> None:
|
||||
"""
|
||||
clears stored session
|
||||
"""
|
||||
self._assume_session = None
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
def aws_utils(
|
||||
request: pytest.fixture,
|
||||
assume_role_arn: str,
|
||||
session_name: str,
|
||||
region_name: str):
|
||||
"""
|
||||
Fixture for setting up a Cdk
|
||||
:param request: _pytest.fixtures.SubRequest class that handles getting
|
||||
a pytest fixture from a pytest function/fixture.
|
||||
:param assume_role_arn: Role used to fetch temporary aws credentials, configure service clients with obtained credentials.
|
||||
:param session_name: Session name to set.
|
||||
:param region_name: AWS account region to set for session.
|
||||
:return AWSUtils class object.
|
||||
"""
|
||||
aws_utils_obj = AwsUtils(assume_role_arn, session_name, region_name)
|
||||
|
||||
def teardown():
|
||||
aws_utils_obj.destroy()
|
||||
|
||||
request.addfinalizer(teardown)
|
||||
|
||||
return aws_utils_obj
|
||||
"""
|
||||
All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
|
||||
its licensors.
|
||||
For complete copyright and license terms please see the LICENSE at the root of this
|
||||
distribution (the "License"). All use of this software is governed by the License,
|
||||
or, if provided, by the license below or the license accompanying this file. Do not
|
||||
remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
"""
|
||||
import boto3
|
||||
import pytest
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.getLogger('boto').setLevel(logging.CRITICAL)
|
||||
|
||||
|
||||
class AwsUtils:
|
||||
|
||||
def __init__(self, arn: str, session_name: str, region_name: str):
|
||||
local_session = boto3.Session(profile_name='default')
|
||||
local_sts_client = local_session.client('sts')
|
||||
self._local_account_id = local_sts_client.get_caller_identity()["Account"]
|
||||
logger.info(f'Local Account Id: {self._local_account_id}')
|
||||
|
||||
response = local_sts_client.assume_role(RoleArn=arn, RoleSessionName=session_name)
|
||||
|
||||
self._assume_session = boto3.Session(aws_access_key_id=response['Credentials']['AccessKeyId'],
|
||||
aws_secret_access_key=response['Credentials']['SecretAccessKey'],
|
||||
aws_session_token=response['Credentials']['SessionToken'],
|
||||
region_name=region_name)
|
||||
|
||||
assume_sts_client = self._assume_session.client('sts')
|
||||
assume_account_id = assume_sts_client.get_caller_identity()["Account"]
|
||||
logger.info(f'Assume Account Id: {assume_account_id}')
|
||||
self._assume_account_id = assume_account_id
|
||||
|
||||
def client(self, service: str):
|
||||
"""
|
||||
Get the client for a specific AWS service from configured session
|
||||
:return: Client for the AWS service.
|
||||
"""
|
||||
return self._assume_session.client(service)
|
||||
|
||||
def resource(self, service: str):
|
||||
"""
|
||||
Get the resource for a specific AWS service from configured session
|
||||
:return: Client for the AWS service.
|
||||
"""
|
||||
return self._assume_session.resource(service)
|
||||
|
||||
def assume_session(self):
|
||||
return self._assume_session
|
||||
|
||||
def local_account_id(self):
|
||||
return self._local_account_id
|
||||
|
||||
def assume_account_id(self):
|
||||
return self._assume_account_id
|
||||
|
||||
def destroy(self) -> None:
|
||||
"""
|
||||
clears stored session
|
||||
"""
|
||||
self._assume_session = None
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
def aws_utils(
|
||||
request: pytest.fixture,
|
||||
assume_role_arn: str,
|
||||
session_name: str,
|
||||
region_name: str):
|
||||
"""
|
||||
Fixture for AWS util functions
|
||||
:param request: _pytest.fixtures.SubRequest class that handles getting
|
||||
a pytest fixture from a pytest function/fixture.
|
||||
:param assume_role_arn: Role used to fetch temporary aws credentials, configure service clients with obtained credentials.
|
||||
:param session_name: Session name to set.
|
||||
:param region_name: AWS account region to set for session.
|
||||
:return AWSUtils class object.
|
||||
"""
|
||||
aws_utils_obj = AwsUtils(assume_role_arn, session_name, region_name)
|
||||
|
||||
def teardown():
|
||||
aws_utils_obj.destroy()
|
||||
|
||||
request.addfinalizer(teardown)
|
||||
|
||||
return aws_utils_obj
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
|
||||
its licensors.
|
||||
|
||||
For complete copyright and license terms please see the LICENSE at the root of this
|
||||
distribution (the "License"). All use of this software is governed by the License,
|
||||
or, if provided, by the license below or the license accompanying this file. Do not
|
||||
remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
"""
|
||||
|
||||
from enum import Enum
|
||||
import botocore.client
|
||||
import botocore.waiter
|
||||
import logging
|
||||
|
||||
logging.getLogger('boto').setLevel(logging.CRITICAL)
|
||||
|
||||
|
||||
class WaitState(Enum):
|
||||
SUCCESS = 'success'
|
||||
FAILURE = 'failure'
|
||||
|
||||
|
||||
class CustomWaiter:
|
||||
"""
|
||||
Base class for a custom waiter.
|
||||
|
||||
Modified from:
|
||||
https://docs.aws.amazon.com/code-samples/latest/catalog/python-demo_tools-custom_waiter.py.html
|
||||
"""
|
||||
def __init__(
|
||||
self, name: str, operation: str, argument: str,
|
||||
acceptors: dict, client: botocore.client, delay: int = 30, max_tries: int = 10,
|
||||
matcher='path'):
|
||||
"""
|
||||
Subclasses should pass specific operations, arguments, and acceptors to
|
||||
their superclass.
|
||||
|
||||
:param name: The name of the waiter. This can be any descriptive string.
|
||||
:param operation: The operation to wait for. This must match the casing of
|
||||
the underlying operation model, which is typically in
|
||||
CamelCase.
|
||||
:param argument: The dict keys used to access the result of the operation, in
|
||||
dot notation. For example, 'Job.Status' will access
|
||||
result['Job']['Status'].
|
||||
:param acceptors: The list of acceptors that indicate the wait is over. These
|
||||
can indicate either success or failure. The acceptor values
|
||||
are compared to the result of the operation after the
|
||||
argument keys are applied.
|
||||
:param client: The Boto3 client.
|
||||
:param delay: The number of seconds to wait between each call to the operation. Default to 30 seconds.
|
||||
:param max_tries: The maximum number of tries before exiting. Default to 10.
|
||||
:param matcher: The kind of matcher to use. Default to 'path'.
|
||||
"""
|
||||
self.name = name
|
||||
self.operation = operation
|
||||
self.argument = argument
|
||||
self.client = client
|
||||
self.waiter_model = botocore.waiter.WaiterModel({
|
||||
'version': 2,
|
||||
'waiters': {
|
||||
name: {
|
||||
"delay": delay,
|
||||
"operation": operation,
|
||||
"maxAttempts": max_tries,
|
||||
"acceptors": [{
|
||||
"state": state.value,
|
||||
"matcher": matcher,
|
||||
"argument": argument,
|
||||
"expected": expected
|
||||
} for expected, state in acceptors.items()]
|
||||
}}})
|
||||
self.waiter = botocore.waiter.create_waiter_with_client(
|
||||
self.name, self.waiter_model, self.client)
|
||||
|
||||
self._timeout = delay * max_tries
|
||||
|
||||
def _wait(self, **kwargs):
|
||||
"""
|
||||
Starts the botocore wait loop.
|
||||
|
||||
:param kwargs: Keyword arguments that are passed to the operation being polled.
|
||||
"""
|
||||
self.waiter.wait(**kwargs)
|
||||
|
||||
@property
|
||||
def timeout(self):
|
||||
return self._timeout
|
||||
|
||||
|
||||
@@ -128,16 +128,5 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS)
|
||||
RUNTIME_DEPENDENCIES
|
||||
AZ::AssetProcessorBatch
|
||||
)
|
||||
|
||||
# Need performance improvements LYN-1218
|
||||
# ly_add_pytest(
|
||||
# NAME AssetPipelineTests.AssetRelocator
|
||||
# PATH ${CMAKE_CURRENT_LIST_DIR}/asset_relocator_tests.py
|
||||
# EXCLUDE_TEST_RUN_TARGET_FROM_IDE
|
||||
# TEST_SUITE periodic
|
||||
# TEST_SERIAL
|
||||
# RUNTIME_DEPENDENCIES
|
||||
# AZ::AssetProcessorBatch
|
||||
# )
|
||||
|
||||
endif()
|
||||
|
||||
+9
@@ -64,6 +64,15 @@ class TestsAssetBuilder_WindowsAndMac(object):
|
||||
):
|
||||
"""
|
||||
Verifying -debug parameter for AssetBuilder
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary workspace
|
||||
2. Launch Asset Processor GUI
|
||||
3. Add test assets to workspace
|
||||
4. Run Asset Builder with debug on an intact slice
|
||||
5. Check Asset Builder didn't fail to build
|
||||
6. Run Asset Builder with debug on a corrupted slice
|
||||
7. Verify corrupted slice produced an error
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
intact_slice_failed = False
|
||||
|
||||
+107
-1
@@ -80,6 +80,8 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
def test_WindowsAndMac_RunHelpCmd_ZeroExitCode(self, workspace, bundler_batch_helper):
|
||||
"""
|
||||
Simple calls to all AssetBundlerBatch --help to make sure a non-zero exit codes are returned.
|
||||
|
||||
Test will call each Asset Bundler Batch sub-command with help and will error on a non-0 exit code
|
||||
"""
|
||||
bundler_batch_helper.call_bundlerbatch(help="")
|
||||
bundler_batch_helper.call_seeds(help="")
|
||||
@@ -98,6 +100,12 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
r"""
|
||||
Tests that an asset list created maps dependencies correctly.
|
||||
testdependencieslevel\level.pak and lists of known dependencies are used for validation
|
||||
|
||||
Test Steps:
|
||||
1. Create an asset list from the level.pak
|
||||
2. Create Lists of expected assets in the level.pak
|
||||
3. Add lists of expected assets to a single list
|
||||
4. Compare list of expected assets to actual assets
|
||||
"""
|
||||
helper = bundler_batch_helper
|
||||
|
||||
@@ -300,6 +308,15 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
"""
|
||||
Validates destructive overwriting for asset lists and
|
||||
that generating debug information does not affect asset list creation
|
||||
|
||||
1. Create an asset list from seed_list
|
||||
2. Validate asset list was created
|
||||
3. Read and store contents of asset list into memory
|
||||
4. Attempt to create a new asset list in without using --allowOverwrites
|
||||
5. Verify that Asset Bundler returns false
|
||||
6. Verify that file contents of the orignally created asset list did not change from what was stored in memory
|
||||
7. Attempt to create a new asset list without debug while allowing overwrites
|
||||
8. Verify that file contents of the orignally created asset list changed from what was stored in memory
|
||||
"""
|
||||
helper = bundler_batch_helper
|
||||
seed_list = os.path.join(workspace.paths.engine_root(), "Assets", "Engine", "SeedAssetList.seed") # Engine seed list
|
||||
@@ -375,6 +392,14 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
"""
|
||||
Validates bundle creation both through the 'bundles' and 'bundlesettings'
|
||||
subcommands.
|
||||
|
||||
Test Steps:
|
||||
1. Create an asset list
|
||||
2. Create a bundle with the asset list and without a bundle settings file
|
||||
3. Create a bundle with the asset list and a bundle settings file
|
||||
4. Validate calling bundle doesn't perform destructive overwrite without --allowOverwrites
|
||||
5. Calling bundle again with --alowOverwrites performs destructive overwrite
|
||||
6. Validate contents of original bundle and overwritten bundle
|
||||
"""
|
||||
helper = bundler_batch_helper
|
||||
seed_list = os.path.join(workspace.paths.engine_root(), "Assets", "Engine", "SeedAssetList.seed") # Engine seed list
|
||||
@@ -457,6 +482,16 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
"""
|
||||
Creates bundles using the same asset list and compares that they are created equally. Also
|
||||
validates that platform bundles exclude/include an expected file. (excluded for WIN, included for MAC)
|
||||
|
||||
Test Steps:
|
||||
1. Create an asset list
|
||||
2. Create bundles for both PC & Mac
|
||||
3. Validate that bundles were created
|
||||
4. Verify that expected missing file is not in windows bundle
|
||||
5. Verify that expected file is in the mac bundle
|
||||
6. Create duplicate bundles with allowOverwrites
|
||||
7. Verify that files were generated
|
||||
8. Verify original bundle checksums are equal to new bundle checksums
|
||||
"""
|
||||
helper = bundler_batch_helper
|
||||
# fmt:off
|
||||
@@ -571,6 +606,24 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
"""
|
||||
Validates that the 'seeds' subcommand can add and remove seeds and seed platforms properly.
|
||||
Also checks that destructive overwrites require the --allowOverwrites flag
|
||||
|
||||
Test Steps:
|
||||
|
||||
1. Create a PC Seed List from a test asset
|
||||
2. Validate that seed list was generated with proper platform flag
|
||||
3. Add Mac & PC as platforms to the seed list
|
||||
4. Verify that seed has both Mac & PC platform flags
|
||||
5. Remove Mac as a platform from the seed list
|
||||
6. Verify that seed only has PC as a platform flag
|
||||
7. Attempt to add a platform without using the --platform argument
|
||||
8. Verify that asset bundler returns False and file contents did not change
|
||||
9. Add Mac platform via --addPlatformToSeeds
|
||||
10. Validate that seed has both Mac & PC platform flags
|
||||
11. Attempt to remove platform without specifying a platform
|
||||
12. Validate that seed has both Mac & PC platform flags
|
||||
13. Validate that seed list contents did not change
|
||||
14. Remove seed
|
||||
15. Validate that seed was removed from the seed list
|
||||
"""
|
||||
helper = bundler_batch_helper
|
||||
|
||||
@@ -692,6 +745,12 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
"""
|
||||
Tests asset list comparison, both by file and by comparison type. Uses a set
|
||||
of controlled test assets to compare resulting output asset lists
|
||||
|
||||
1. Create comparison rules files
|
||||
2. Create seed files for different sets of test assets
|
||||
3. Create assetlist files for seed files
|
||||
4. Validate assetlists were created properly
|
||||
5. Compare using comparison rules files and just command line arguments
|
||||
"""
|
||||
helper = bundler_batch_helper
|
||||
env = ap_setup_fixture
|
||||
@@ -1021,6 +1080,16 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
"""
|
||||
Tests that assetlists are created equivalent to the output while being created, and
|
||||
makes sure overwriting an existing file without the --allowOverwrites fails
|
||||
|
||||
Test Steps:
|
||||
1. Check that Asset List creation requires PC platform flag
|
||||
2. Create a PC Asset List using asset info file and default seed lists using --print
|
||||
3. Validate all assets output are present in the asset list
|
||||
4. Create a seed file
|
||||
5. Attempt to overwrite Asset List without using --allowOverwrites
|
||||
6. Validate that command returned an error and file contents did not change
|
||||
7. Specifying platform but not "add" or "remove" should fail
|
||||
8. Verify file Has changed
|
||||
"""
|
||||
helper = bundler_batch_helper
|
||||
|
||||
@@ -1102,7 +1171,16 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
def test_WindowsAndMac_AP_BundleProcessing_BundleProcessedAtRuntime(self, workspace, bundler_batch_helper,
|
||||
asset_processor, request):
|
||||
# fmt:on
|
||||
"""Test to make sure the AP GUI will process a newly created bundle file"""
|
||||
"""
|
||||
Test to make sure the AP GUI will process a newly created bundle file
|
||||
|
||||
Test Steps:
|
||||
1. Make asset list file (used for bundle creation)
|
||||
2. Start Asset Processor GUI
|
||||
3. Make bundle in <project_folder>/Bundles
|
||||
4. Validate file was created in Bundles folder
|
||||
5. Make sure bundle now exists in cache
|
||||
"""
|
||||
# Set up helpers and variables
|
||||
helper = bundler_batch_helper
|
||||
|
||||
@@ -1131,6 +1209,8 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
addSeed=level_pak,
|
||||
assetListFile=helper["asset_info_file_request"],
|
||||
)
|
||||
|
||||
# Run Asset Processor GUI
|
||||
result, _ = asset_processor.gui_process()
|
||||
assert result, "AP GUI failed"
|
||||
|
||||
@@ -1155,6 +1235,12 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
# fmt:off
|
||||
def test_WindowsAndMac_FilesMarkedSkip_FilesAreSkipped(self, workspace, bundler_batch_helper):
|
||||
"""
|
||||
Test Steps:
|
||||
1. Create an asset list with a file marked as skip
|
||||
2. Verify file was created
|
||||
3. Verify that only the expected assets are present in the created asset list
|
||||
"""
|
||||
expected_assets = [
|
||||
"ui/canvases/lyshineexamples/animation/multiplesequences.uicanvas",
|
||||
"ui/textures/prefab/button_normal.sprite"
|
||||
@@ -1178,6 +1264,12 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
# fmt:off
|
||||
def test_WindowsAndMac_AssetListSkipOneOfTwoParents_SharedDependencyIsIncluded(self, workspace,
|
||||
bundler_batch_helper):
|
||||
"""
|
||||
Test Steps:
|
||||
1. Create Asset List with a parent asset that is skipped
|
||||
2. Verify that Asset List was created
|
||||
3. Verify that only the expected assets are present in the asset list
|
||||
"""
|
||||
expected_assets = [
|
||||
"testassets/bundlerskiptest_grandparent.dynamicslice",
|
||||
"testassets/bundlerskiptest_parenta.dynamicslice",
|
||||
@@ -1206,6 +1298,13 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
# fmt:off
|
||||
def test_WindowsAndMac_AssetLists_SkipRoot_ExcludesAll(self, workspace, bundler_batch_helper):
|
||||
"""
|
||||
Negative scenario test that skips the same file being used as the parent seed.
|
||||
|
||||
Test Steps:
|
||||
1. Create an asset list that skips the root asset
|
||||
2. Verify that asset list was not generated
|
||||
"""
|
||||
|
||||
result, _ = bundler_batch_helper.call_assetLists(
|
||||
assetListFile=bundler_batch_helper['asset_info_file_request'],
|
||||
@@ -1222,6 +1321,13 @@ class TestsAssetBundlerBatch_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
# fmt:off
|
||||
def test_WindowsAndMac_AssetLists_SkipUniversalWildcard_ExcludesAll(self, workspace, bundler_batch_helper):
|
||||
"""
|
||||
Negative scenario test that uses the all wildcard when generating an asset list.
|
||||
|
||||
Test Steps:
|
||||
1. Create an Asset List while using the universal all wildcard "*"
|
||||
2. Verify that asset list was not generated
|
||||
"""
|
||||
|
||||
result, _ = bundler_batch_helper.call_assetLists(
|
||||
assetListFile=bundler_batch_helper['asset_info_file_request'],
|
||||
|
||||
+17
@@ -67,7 +67,19 @@ class TestsAssetProcessorBatch_DependenycyTests(object):
|
||||
libs/materialeffects/surfacetypes.xml is listed as an entry engine_dependencies.xml
|
||||
libs/materialeffects/surfacetypes.xml is not listed as a missing dependency
|
||||
in the 'assetprocessorbatch' console output
|
||||
|
||||
Test Steps:
|
||||
1. Assets are pre-processed
|
||||
2. Verify that engine_dependencies.xml exists
|
||||
3. Verify engine_dependencies.xml has surfacetypes.xml present
|
||||
4. Run Missing Dependency scanner against the engine_dependenciese.xml
|
||||
5. Verify that Surfacetypes.xml is NOT in the missing depdencies output
|
||||
6. Add the schema file which allows our xml parser to understand dependencies for our engine_dependencies file
|
||||
7. Process assets
|
||||
8. Run Missing Dependency scanner against the engine_dependenciese.xml
|
||||
9. Verify that surfacetypes.xml is in the missing dependencies out
|
||||
"""
|
||||
|
||||
env = ap_setup_fixture
|
||||
BATCH_LOG_PATH = env["ap_batch_log_file"]
|
||||
asset_processor.create_temp_asset_root()
|
||||
@@ -137,6 +149,11 @@ class TestsAssetProcessorBatch_DependenycyTests(object):
|
||||
def test_WindowsMacPlatforms_BatchCheckSchema_ValidateErrorChecking(self, workspace, asset_processor,
|
||||
ap_setup_fixture, folder, schema):
|
||||
# fmt:on
|
||||
"""
|
||||
Test Steps:
|
||||
1. Run the Missing Dependency Scanner against everything
|
||||
2. Verify that there are no missing dependencies.
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
|
||||
def missing_dependency_log_lines(log) -> [str]:
|
||||
|
||||
+9
@@ -60,6 +60,15 @@ class TestsAssetProcessorBatch_DependenycyTests(object):
|
||||
Verify that Schemas can be loaded via Gems utilizing the fonts schema
|
||||
|
||||
:returns: None
|
||||
|
||||
Test Steps:
|
||||
1. Run Missing Dependency Scanner against %fonts%.xml when no fonts are present
|
||||
2. Verify fonts are scanned
|
||||
3. Verify that missing dependencies are found for fonts
|
||||
4. Add fonts to game project
|
||||
5. Run Missing Dependency Scanner against %fonts%.xml when fonts are present
|
||||
6. Verify that same amount of fonts are scanned
|
||||
7. Verify that there are no missing dependencies.
|
||||
"""
|
||||
schema_name = "Font.xmlschema"
|
||||
asset_processor.create_temp_asset_root()
|
||||
|
||||
+155
@@ -100,6 +100,14 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
@pytest.mark.BAT
|
||||
@pytest.mark.assetpipeline
|
||||
def test_RunAPBatch_TwoPlatforms_ExitCodeZero(self, asset_processor):
|
||||
"""
|
||||
Tests Process assets for PC & Mac and verifies that processing exited without error
|
||||
|
||||
Test Steps:
|
||||
1. Add Mac and PC as enabled platforms
|
||||
2. Process Assets
|
||||
3. Validate that AP exited cleanly
|
||||
"""
|
||||
asset_processor.create_temp_asset_root()
|
||||
asset_processor.enable_asset_processor_platform("pc")
|
||||
asset_processor.enable_asset_processor_platform("mac")
|
||||
@@ -111,6 +119,14 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id('C1571826')
|
||||
def test_RunAPBatch_OnlyIncludeInvalidAssets_NoAssetsAdded(self, asset_processor, ap_setup_fixture):
|
||||
"""
|
||||
Tests processing invalid assets and validating that no assets were moved to the cache
|
||||
|
||||
Test Steps:
|
||||
1. Create a test environment with invalid assets
|
||||
2. Run asset processor
|
||||
3. Validate that no assets were found in the cache
|
||||
"""
|
||||
asset_processor.prepare_test_environment(ap_setup_fixture["tests_dir"], "test_ProcessAssets_OnlyIncludeInvalidAssets_NoAssetsAdded")
|
||||
|
||||
result, _ = asset_processor.batch_process()
|
||||
@@ -127,6 +143,16 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
"recognized as failing in the logs. There appears to be a window where the AutoFailJob doesn't complete"
|
||||
"before the shutdown completes and the failure doesn't end up counting")
|
||||
def test_ProcessAssets_IncludeTwoAssetsWithSameProduct_FailingOnSecondAsset(self, asset_processor, ap_setup_fixture):
|
||||
"""
|
||||
Tests processing two source assets with the same product file and validates that the second source will error
|
||||
|
||||
Test Steps:
|
||||
1. Create a test environment that has two source files with the same product
|
||||
2. Run asset processor
|
||||
3. Validate that 1 asset failed to process
|
||||
4. Validate that only one product file with the expected name is found in the cache
|
||||
"""
|
||||
|
||||
asset_processor.prepare_test_environment(ap_setup_fixture["tests_dir"], "test_ProcessAssets_IncludeTwoAssetsWithSameProduct_FailingOnSecondAsset")
|
||||
result, output = asset_processor.batch_process(capture_output = True, expect_failure = True)
|
||||
|
||||
@@ -143,6 +169,17 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id('C1587615')
|
||||
def test_ProcessAndDeleteCache_APBatchShouldReprocess(self, asset_processor, ap_setup_fixture):
|
||||
"""
|
||||
Tests processing once, deleting the generated cache, then processing again and validates the cache is created
|
||||
|
||||
Test Steps:
|
||||
1. Run asset processor
|
||||
2. Compare the cache with expected output
|
||||
3. Delete Cache
|
||||
4. Compare the cache with expected output to verify that cache is gone
|
||||
5. Run asset processor with fastscan disabled
|
||||
6. Compare the cache with expected output
|
||||
"""
|
||||
# Deleting assets from Cache will make them re-processed in AP (after start)
|
||||
|
||||
# Copying test assets to project folder and deleting them from cache to make sure APBatch will process them
|
||||
@@ -174,6 +211,18 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id('C1591564')
|
||||
def test_ProcessAndChangeSource_APBatchShouldReprocess(self, asset_processor, ap_setup_fixture):
|
||||
"""
|
||||
Tests reprocessing of a modified asset and verifies that it was reprocessed
|
||||
|
||||
Test Steps:
|
||||
1. Prepare test environment and copy test asset over
|
||||
2. Run asset processor
|
||||
3. Verify asset processed
|
||||
4. Verify asset is in cache
|
||||
4. Modify asset
|
||||
5. Re-run asset processor
|
||||
6. Verify asset was processed
|
||||
"""
|
||||
# AP Batch Processing changed files (after start)
|
||||
|
||||
# Copying test assets to project folder and deleting them from cache to make sure APBatch will process them
|
||||
@@ -208,6 +257,18 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
@pytest.mark.BAT
|
||||
@pytest.mark.assetpipeline
|
||||
def test_ProcessByBothApAndBatch_Md5ShouldMatch(self, asset_processor, ap_setup_fixture):
|
||||
"""
|
||||
Tests that a cache generated by AP GUI is the same as AP Batch
|
||||
|
||||
Test Steps:
|
||||
1. Create test environment with test assets
|
||||
2. Call asset processor batch
|
||||
3. Get checksum for file cache
|
||||
4. Clean up test environment
|
||||
5. Call asset processor gui with quitonidle
|
||||
6. Get checksum for file cache
|
||||
7. Verify that checksums are equal
|
||||
"""
|
||||
# AP Batch and AP app processed assets MD5 sums should be the same
|
||||
|
||||
# Copying test assets to project folder and deleting them from cache to make sure APBatch will process them
|
||||
@@ -240,6 +301,16 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id('C1612446')
|
||||
def test_AddSameAssetsDifferentNames_ShouldProcess(self, asset_processor, ap_setup_fixture):
|
||||
"""
|
||||
Tests Asset Processing of duplicate assets with different names and verifies that both assets are processed
|
||||
|
||||
Test Steps:
|
||||
1. Create test environment with two identical source assets with different names
|
||||
2. Run asset processor
|
||||
3. Verify that assets didn't fail to process
|
||||
4. Verify the correct number of jobs were performed
|
||||
5. Verify that product files are in the cache
|
||||
"""
|
||||
# Feed two similar slices and texture with different names - should process without any issues
|
||||
|
||||
# Copying test assets to project folder and deleting them from cache to make sure APBatch will process them
|
||||
@@ -277,6 +348,19 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
"recognized as failing in the logs. There appears to be a window where the AutoFailJob doesn't complete"
|
||||
"before the shutdown completes and the failure doesn't end up counting")
|
||||
def test_AddTwoTexturesWithSameName_ShouldProcessAfterRename(self, asset_processor, ap_setup_fixture):
|
||||
"""
|
||||
Tests processing of two textures with the same name then verifies that AP will successfully process after
|
||||
renaming one of the textures
|
||||
|
||||
Test Steps:
|
||||
1. Create test environment with two textures that have the same name
|
||||
2. Launch Asset Processor
|
||||
3. Validate that Asset Processor generates an error
|
||||
4. Rename texture files
|
||||
5. Run asset processor
|
||||
6. Verify that asset processor does not error
|
||||
7. Verify that expected product files are in the cache
|
||||
"""
|
||||
# Feed two different textures with same name (but different extensions) - ap will fail
|
||||
# Rename one of textures and failure should go away
|
||||
|
||||
@@ -312,6 +396,15 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
@pytest.mark.BAT
|
||||
@pytest.mark.assetpipeline
|
||||
def test_InvalidServerAddress_Warning_Logs(self, asset_processor):
|
||||
"""
|
||||
Tests running Asset Processor with an invalid server address and verifies that AP returns a warning about
|
||||
an invalid server address
|
||||
|
||||
Test Steps:
|
||||
1. Launch asset processor while providing an invalid server address
|
||||
2. Verify asset processor does not fail
|
||||
3. Verify that asset processor generated a warning informing the user about an invalid server address
|
||||
"""
|
||||
|
||||
asset_processor.create_temp_asset_root()
|
||||
# Launching AP and making sure that the warning exists
|
||||
@@ -327,6 +420,12 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
def test_AllSupportedPlatforms_IncludeValidAssets_AssetsProcessed(self, asset_processor, ap_setup_fixture):
|
||||
"""
|
||||
AssetProcessorBatch is successfully processing newly added assets
|
||||
|
||||
Test Steps:
|
||||
1. Create a test environment with test assets
|
||||
2. Launch Asset Processor
|
||||
3. Verify that asset processor does not fail to process
|
||||
4. Verify assets are not missing from the cache
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
|
||||
@@ -350,6 +449,14 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
def test_AllSupportedPlatforms_DeletedAssets_DeletedFromCache(self, asset_processor, ap_setup_fixture):
|
||||
"""
|
||||
AssetProcessor successfully deletes cached items when removed from project
|
||||
|
||||
Test Steps:
|
||||
1. Create a test environment with test assets
|
||||
2. Run asset processor
|
||||
3. Verify expected assets are in the cache
|
||||
4. Delete test assets
|
||||
5. Run asset processor
|
||||
6. Verify expected assets are in the cache
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
|
||||
@@ -385,6 +492,10 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
"""
|
||||
Tests that when cache is deleted (no cache) and AssetProcessorBatch runs,
|
||||
it successfully starts and processes assets.
|
||||
|
||||
Test Steps:
|
||||
1. Run asset processor
|
||||
2. Verify asset processor exits cleanly
|
||||
"""
|
||||
asset_processor.create_temp_asset_root()
|
||||
|
||||
@@ -402,6 +513,14 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
# fmt:on
|
||||
"""
|
||||
AssetProcessor successfully recovers assets from cache when deleted.
|
||||
|
||||
Test Steps:
|
||||
1. Create test enviornment with test assets
|
||||
2. Run Asset Processor and verify it exits cleanly
|
||||
3. Make sure cache folder was generated
|
||||
4. Delete temp cache assets but leave database behind
|
||||
5. Run asset processor and verify it exits cleanly
|
||||
6. Verify expected files were generated in the cache
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
|
||||
@@ -434,6 +553,14 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
@pytest.mark.assetpipeline
|
||||
# fmt:off
|
||||
def test_AllSupportedPlatforms_RunFastScanOnEmptyCache_FullScanRuns(self, ap_setup_fixture, asset_processor):
|
||||
"""
|
||||
Tests fast scan processing on an empty cache and verifies that a full analyis will be peformed
|
||||
|
||||
Test Steps:
|
||||
1. Create a test environment
|
||||
2. Execute asset processor batch with fast scan enabled
|
||||
3. Verify that a full analysis is performed
|
||||
"""
|
||||
# fmt:on
|
||||
env = ap_setup_fixture
|
||||
asset_processor.create_temp_asset_root()
|
||||
@@ -455,6 +582,11 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
"""
|
||||
After running the APBatch and AP GUI, Logs directory should exist (C1564055),
|
||||
JobLogs, Batch log, and GUI log should exist in the logs directory (C1564056)
|
||||
|
||||
Test Steps:
|
||||
1. Run asset processor batch
|
||||
2. Run asset processor gui with quit on idle
|
||||
3. Verify that logs exist for both AP Batch & AP GUI
|
||||
"""
|
||||
asset_processor.create_temp_asset_root()
|
||||
LOG_PATH = {
|
||||
@@ -536,6 +668,11 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
"""
|
||||
Utilizing corrupted test assets, run the batch process to verify the
|
||||
AP logs the failure to process the corrupted file.
|
||||
|
||||
Test Steps:
|
||||
1. Create test environment with corrupted slice
|
||||
2. Launch Asset Processor
|
||||
3. Verify that asset processor fails to process corrupted slice
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
error_line_found = False
|
||||
@@ -552,6 +689,15 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
@pytest.mark.BAT
|
||||
@pytest.mark.assetpipeline
|
||||
def test_validateDirectPreloadDependency_Found(self, asset_processor, ap_setup_fixture, workspace):
|
||||
"""
|
||||
Tests processing an asset with a circular dependency and verifies that Asset Processor will return an error
|
||||
notifying the user about a circular dependency.
|
||||
|
||||
Test Steps:
|
||||
1. Create test environment with an asset that has a circular dependency
|
||||
2. Launch asset processor
|
||||
3. Verify that error is returned informing the user that the asset has a circular dependency
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
error_line_found = False
|
||||
|
||||
@@ -567,6 +713,15 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
@pytest.mark.BAT
|
||||
@pytest.mark.assetpipeline
|
||||
def test_validateNestedPreloadDependency_Found(self, asset_processor, ap_setup_fixture, workspace):
|
||||
"""
|
||||
Tests processing of a nested circular dependency and verifies that Asset Processor will return an error
|
||||
notifying the user about a circular depdency
|
||||
|
||||
Test Steps:
|
||||
1. Create test environment with an asset that has a nested circular dependency
|
||||
2. Launch asset processor
|
||||
3. Verify that error is returned informing the user that the asset has a circular dependency
|
||||
"""
|
||||
|
||||
env = ap_setup_fixture
|
||||
error_line_found = False
|
||||
|
||||
+33
-64
@@ -80,6 +80,15 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
# fmt:on
|
||||
"""
|
||||
Tests that fast scan mode can be used and is faster than full scan mode.
|
||||
|
||||
Test Steps:
|
||||
1. Ensure all assets are processed
|
||||
2. Run Asset Processor without fast scan and measure the time it takes to run
|
||||
3. Capture Full Analysis was performed and number of assets processed
|
||||
4. Run Asset Processor with full scan and measure the time it takes to run
|
||||
5. Capture Full Analysis wans't performed and number of assets processed
|
||||
6. Verify that fast scan was faster than full scan
|
||||
7. Verify that full scan scanned more assets
|
||||
"""
|
||||
|
||||
asset_processor.create_temp_asset_root()
|
||||
@@ -111,76 +120,23 @@ class TestsAssetProcessorBatch_AllPlatforms(object):
|
||||
assert full_scan_time > fast_scan_time, "Fast scan was slower that full scan"
|
||||
assert full_scan_analysis[0] > fast_scan_analysis[0], "Full scan did not process more assets than fast scan"
|
||||
|
||||
@pytest.mark.test_case_id("C18787404")
|
||||
@pytest.mark.BAT
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.skip(reason="External project is currently broken.") # LY-119863
|
||||
def test_AllSupportedPlatforms_ExternalProject_APRuns(self, workspace, ap_external_project_setup_fixture):
|
||||
|
||||
external_resources = ap_external_project_setup_fixture
|
||||
logger.info(f"Running external project test at path {external_resources['project_dir']}")
|
||||
# Delete existing "external project" build if it exists
|
||||
if os.path.exists(external_resources["project_dir"]):
|
||||
fs.delete([external_resources["project_dir"]], True, True)
|
||||
|
||||
# fmt:off
|
||||
assert not os.path.exists(external_resources["project_dir"]), \
|
||||
f'{external_resources["project_dir"]} was not deleted'
|
||||
# fmt:on
|
||||
|
||||
lmbr_cmd = [
|
||||
workspace.paths.lmbr(),
|
||||
"projects",
|
||||
"create",
|
||||
external_resources["project_name"],
|
||||
"--template",
|
||||
"EmptyTemplate",
|
||||
"--app-root",
|
||||
external_resources["project_dir"],
|
||||
]
|
||||
|
||||
logger.info(f"Running lmbr projects create command '{lmbr_cmd}'")
|
||||
|
||||
try:
|
||||
subprocess.check_call(lmbr_cmd)
|
||||
except subprocess.CalledProcessError as e:
|
||||
assert False, f"lmbr projects create failed\n{e.stderr}"
|
||||
|
||||
logger.info("...lmbr finished")
|
||||
assert os.path.exists(external_resources["project_dir"]), "Project folder was not created"
|
||||
|
||||
# AssetProcessor for new External project. Uses mock workspace to emulate external project workspace
|
||||
external_ap = AssetProcessor(external_resources["external_workspace"])
|
||||
|
||||
# fmt:off
|
||||
assert external_ap.batch_process(fastscan=False), \
|
||||
"Asset Processor Batch failed on external project"
|
||||
# fmt:on
|
||||
|
||||
# Parse log looking for errors or failures
|
||||
log = APLogParser(workspace.paths.ap_batch_log())
|
||||
failures, errors = log.runs[-1]["Failures"], log.runs[-1]["Errors"]
|
||||
assert failures == 0, f"There were {failures} asset processing failures"
|
||||
assert errors == 0, f"There were {errors} asset processing errors"
|
||||
|
||||
# Check that project cache was created (DNE until AP makes it)
|
||||
project_cache = os.path.join(external_resources["project_dir"], "Cache")
|
||||
assert os.path.exists(project_cache), f"{project_cache} was not created by AP"
|
||||
|
||||
# Clean up external project
|
||||
fs.delete([external_resources["project_dir"]], True, True)
|
||||
|
||||
# fmt:off
|
||||
assert not os.path.exists(external_resources["project_dir"]), \
|
||||
f"{external_resources['project_dir']} was not deleted"
|
||||
# fmt:on
|
||||
|
||||
@pytest.mark.test_case_id("C4874121")
|
||||
@pytest.mark.BAT
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.parametrize("clear_type", ["rewrite", "delete_asset", "delete_dir"])
|
||||
def test_AllSupportedPlatforms_DeleteBadAssets_BatchFailedJobsCleared(
|
||||
self, workspace, request, ap_setup_fixture, asset_processor, clear_type):
|
||||
"""
|
||||
Tests the ability of Asset Processor to recover from processing of bad assets by removing them from scan folder
|
||||
|
||||
Test Steps:
|
||||
1. Create testing environment with good and multiple bad assets
|
||||
2. Run Asset Processor
|
||||
3. Verify that bad assets fail to process
|
||||
4. Fix a bad asset & delete the others
|
||||
5. Run Asset Processor
|
||||
6. Verify Asset Processor does not have any asset failues
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
error_search_terms = ["WWWWWWWWWWWW"]
|
||||
|
||||
@@ -250,6 +206,14 @@ class TestsAssetProcessorBatch_Windows(object):
|
||||
Verify the AP batch and Gui can run and process assets independent of the Editor
|
||||
We do not want or need to kill running Editors here as they can be involved in other tests
|
||||
or simply being run locally in this branch or another
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Run asset processor GUI
|
||||
3. Verify AP GUI doesn't error
|
||||
4. Stop AP GUI
|
||||
5. Run Asset Processor Batch with Fast Scan
|
||||
5. Verify Asset Processor Batch exits cleanly
|
||||
"""
|
||||
|
||||
asset_processor.create_temp_asset_root()
|
||||
@@ -272,6 +236,11 @@ class TestsAssetProcessorBatch_Windows(object):
|
||||
"""
|
||||
Request a run for an invalid platform
|
||||
"AssetProcessor: Error: Platform in config file or command line 'notaplatform'" should be present in the logs
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Run Asset Processor with an invalid platform
|
||||
3. Check that asset processor returns an Error notifying the user that the invalid platform is not supported
|
||||
"""
|
||||
asset_processor.create_temp_asset_root()
|
||||
error_search_terms = 'AssetProcessor: Error: The list of enabled platforms in the settings registry does not contain platform ' \
|
||||
|
||||
+75
-4
@@ -77,6 +77,13 @@ class TestsAssetProcessorGUI_Windows(object):
|
||||
def test_SendInputOnControlChannel_ReceivedAndResponded(self, asset_processor):
|
||||
"""
|
||||
Test that the control channel connects and that communication works both directions
|
||||
|
||||
Test Steps:
|
||||
1. Start Asset Processor
|
||||
2. Send a Ping message to Asset Processor
|
||||
3. Listen for Asset Processor response
|
||||
4. Verify Asset Processor responds
|
||||
5. Stop asset Processor
|
||||
"""
|
||||
|
||||
asset_processor.create_temp_asset_root()
|
||||
@@ -129,7 +136,15 @@ class TestsAssetProcessorGUI_Windows(object):
|
||||
# fmt:on
|
||||
"""
|
||||
Asset Processor Deletes processed assets when source is removed from project folder (while running)
|
||||
|
||||
Test Steps:
|
||||
1. Create a temporary test environment
|
||||
2. Run Asset Processor GUI set to stay open on idle and verify that it does not fail
|
||||
3. Verify that assets were copied to the cache
|
||||
4. Delete the source test asset directory
|
||||
5. Verify assets are deleted from the cache
|
||||
"""
|
||||
|
||||
env = ap_setup_fixture
|
||||
|
||||
# Copy test assets to project folder and verify test assets folder exists
|
||||
@@ -170,7 +185,18 @@ class TestsAssetProcessorGUI_Windows(object):
|
||||
# fmt:on
|
||||
"""
|
||||
Processing changed files (while running)
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary test environment with test assets
|
||||
2. Open Asset Processor GUI with set to stay open after idle and verify it does not fail
|
||||
3. Verify contents of source asset for later comparison
|
||||
4. Verify contents of product asset for later comparison
|
||||
5. Modify contents of source asset
|
||||
6. Wait for Asset Processor to go back to idle state
|
||||
7. Verify contents of source asset are the modified version
|
||||
8. Verify contents of product asset are the modified version
|
||||
"""
|
||||
|
||||
env = ap_setup_fixture
|
||||
|
||||
# Copy test assets to project folder and verify test assets folder exists
|
||||
@@ -184,7 +210,7 @@ class TestsAssetProcessorGUI_Windows(object):
|
||||
result, _ = asset_processor.gui_process(quitonidle=False)
|
||||
assert result, "AP GUI failed"
|
||||
|
||||
# Verify contents of test asset in project folder before modication
|
||||
# Verify contents of test asset in project folder before modification
|
||||
with open(project_asset_path, "r") as project_asset_file:
|
||||
assert project_asset_file.read() == "before_state"
|
||||
|
||||
@@ -217,7 +243,14 @@ class TestsAssetProcessorGUI_Windows(object):
|
||||
def test_WindowsPlatforms_RunAP_ProcessesIdle(self, asset_processor):
|
||||
"""
|
||||
Asset Processor goes idle
|
||||
|
||||
Test Steps:
|
||||
1. Create a temporary testing evnironment
|
||||
2. Run Asset Processor GUI without quitonidle
|
||||
3. Verify AP Goes Idle
|
||||
4. Verify AP goes below 1% CPU usage
|
||||
"""
|
||||
|
||||
CPU_USAGE_THRESHOLD = 1.0 # CPU usage percentage delimiting idle from active
|
||||
CPU_USAGE_WIND_DOWN = 10 # Time allowed in seconds for idle processes to stop using CPU
|
||||
|
||||
@@ -245,7 +278,16 @@ class TestsAssetProcessorGUI_Windows(object):
|
||||
):
|
||||
"""
|
||||
Processing newly added files to project folder (while running)
|
||||
|
||||
Test Steps:
|
||||
1. Create a temporary testing environment with test assets
|
||||
2. Create a secondary set of testing assets that have not been copied into the the testing environment
|
||||
3. Start Asset Processor without quitonidle
|
||||
4. While Asset Processor is running add secondary set of testing assets to the testing environment
|
||||
5. Wait for Asset Processor to go idle
|
||||
6. Verify that all assets are in the cache
|
||||
"""
|
||||
|
||||
env = ap_setup_fixture
|
||||
level_name = "C1564064_level"
|
||||
new_asset = "C1564064.scriptcanvas"
|
||||
@@ -316,7 +358,14 @@ class TestsAssetProcessorGUI_Windows(object):
|
||||
def test_WindowsPlatforms_LaunchAP_LogReportsIdle(self, asset_processor, workspace, ap_idle):
|
||||
"""
|
||||
Asset Processor creates a log entry when it goes idle
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Run Asset Processor batch to pre-process assets
|
||||
3. Run Asset Processor GUI
|
||||
4. Check if Asset Processor GUI reports that it has gone idle
|
||||
"""
|
||||
|
||||
asset_processor.create_temp_asset_root()
|
||||
# Run batch process to ensure project assets are processed
|
||||
assert asset_processor.batch_process(), "AP Batch failed"
|
||||
@@ -331,6 +380,17 @@ class TestsAssetProcessorGUI_Windows(object):
|
||||
|
||||
@pytest.mark.assetpipeline
|
||||
def test_APStopTimesOut_ExceptionThrown(self, ap_setup_fixture, asset_processor):
|
||||
"""
|
||||
Tests whether or not Asset Processor will Time Out
|
||||
|
||||
Test Steps:
|
||||
1. Create a temporary testing environment
|
||||
2. Start the Asset Processor
|
||||
3. Copy in assets to the test environment
|
||||
4. Try to stop the Asset Processor with a timeout of 1 second (This cannot be done manually).
|
||||
5. Verify that Asset Processor times out and returns the expected error
|
||||
"""
|
||||
|
||||
asset_processor.create_temp_asset_root()
|
||||
asset_processor.start()
|
||||
|
||||
@@ -347,9 +407,20 @@ class TestsAssetProcessorGUI_Windows(object):
|
||||
|
||||
@pytest.mark.assetpipeline
|
||||
def test_APStopDefaultTimeout_NoException(self, asset_processor):
|
||||
# If this test fails, it means other tests using the default timeout may have issues.
|
||||
# In that case, either the default timeout should either be raised, or the performance
|
||||
# of AP launching should be improved.
|
||||
"""
|
||||
Tests the default timeout of the Asset Processor
|
||||
|
||||
If this test fails, it means other tests using the default timeout may have issues.
|
||||
In that case, either the default timeout should either be raised, or the performance
|
||||
of AP launching should be improved.
|
||||
|
||||
Test Steps:
|
||||
1. Create a temporary testing environment
|
||||
2. Start the Asset Processor
|
||||
3. Stop the asset Processor without sending a timeout to it
|
||||
4. Verify that the asset processor times out and returns the expected error
|
||||
"""
|
||||
|
||||
asset_processor.create_temp_asset_root()
|
||||
asset_processor.start()
|
||||
ap_quit_timed_out = False
|
||||
|
||||
+47
-1
@@ -75,10 +75,17 @@ class TestsAssetProcessorGUI_WindowsAndMac(object):
|
||||
@pytest.mark.test_case_id("C3540434")
|
||||
@pytest.mark.BAT
|
||||
@pytest.mark.assetpipeline
|
||||
def test_WindowsAndMacPlatforms_AP_GUI_FastScanSettingCreated(self, asset_processor, fast_scan_backup):
|
||||
def test_WindowsAndMacPlatforms_GUIFastScanNoSettingSet_FastScanSettingCreated(self, asset_processor, fast_scan_backup):
|
||||
"""
|
||||
Tests that a fast scan settings entry gets created for the AP if it does not exist
|
||||
and ensures that the entry is defaulted to fast-scan enabled
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Delete existing fast scan setting if exists
|
||||
3. Run Asset Processor GUI without setting FastScan setting (default:true) and without quitonidle
|
||||
4. Wait and check to see if Windows Registry fast scan setting is created
|
||||
5. Verify that Fast Scan setting is set to true
|
||||
"""
|
||||
|
||||
asset_processor.create_temp_asset_root()
|
||||
@@ -119,6 +126,14 @@ class TestsAssetProcessorGUI_WindowsAndMac(object):
|
||||
Make sure game launcher working with Asset Processor set to turbo mode
|
||||
Validate that no fatal errors (crashes) are reported within a certain
|
||||
time frame for the AP and the GameLauncher
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Set fast scan to true
|
||||
3. Verify fast scan is set to true
|
||||
4. Launch game launcher
|
||||
5. Verify launcher has launched without error
|
||||
6. Verify that asset processor has launched
|
||||
"""
|
||||
CHECK_ALIVE_SECONDS = 15
|
||||
|
||||
@@ -166,6 +181,14 @@ class TestsAssetProcessorGUI_AllPlatforms(object):
|
||||
# fmt:on
|
||||
"""
|
||||
Deleting slices and uicanvases while AP is running
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment with test assets
|
||||
2. Launch Asset Processor and wait for it to go idle
|
||||
3. Verify product assets were created in the cache
|
||||
4. Delete test assets from the cache
|
||||
5. Wait for Asset Processor to go idle
|
||||
6. Verify product assets were regenerated in the cache
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
|
||||
@@ -201,6 +224,15 @@ class TestsAssetProcessorGUI_AllPlatforms(object):
|
||||
):
|
||||
"""
|
||||
Process slice files and uicanvas files from the additional scanfolder
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Run asset processor batch
|
||||
3. Validate that product assets were generated in the cache
|
||||
4. Create an additional scan folder with assets
|
||||
5. Create additional scan folder params to pass to Asset Processor
|
||||
6. Run Asset Processor GUI with QuitOnIdle and pass in params for the additional scan folder settings
|
||||
7. Verify additional product assets from additional scan folder are present in the cache
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
# Copy test assets to new folder in dev folder
|
||||
@@ -250,6 +282,12 @@ class TestsAssetProcessorGUI_AllPlatforms(object):
|
||||
"""
|
||||
Launch AP with invalid address in bootstrap.cfg
|
||||
Assets should process regardless of the new address
|
||||
|
||||
Test Steps:
|
||||
1. Create a temporary testing environment
|
||||
2. Set an invalid ip address in Asset Processor settings file
|
||||
3. Launch Asset Processor GUI
|
||||
4. Verify that it processes assets and exits cleanly even though it has an invalid IP.
|
||||
"""
|
||||
test_ip_address = "1.1.1.1" # an IP address without Asset Processor
|
||||
|
||||
@@ -269,6 +307,14 @@ class TestsAssetProcessorGUI_AllPlatforms(object):
|
||||
def test_AllSupportedPlatforms_ModifyAssetInfo_AssetsReprocessed(self, ap_setup_fixture, asset_processor):
|
||||
"""
|
||||
Modifying assetinfo files triggers file reprocessing
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment with test assets
|
||||
2. Run Asset Processor GUI
|
||||
3. Verify that Asset Processor exited cleanly and product assets are in the cache
|
||||
4. Modify the .assetinfo file by adding a newline
|
||||
5. Wait for Asset Processor to go idle
|
||||
6. Verify that product files were regenerated (Time Stamp compare)
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
|
||||
|
||||
+89
-3
@@ -85,6 +85,18 @@ class TestsAssetRelocator_WindowsAndMac(object):
|
||||
def test_WindowsMacPlatforms_RelocatorMoveFileWithConfirm_MoveSuccess(self, request, workspace, asset_processor,
|
||||
ap_setup_fixture, testId, readonly, confirm,
|
||||
success):
|
||||
"""
|
||||
Tests whether tests with Move File Confirm are successful
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Set move location
|
||||
3. Determine if confirm flag is set
|
||||
4. Attempt to move the files
|
||||
5. If confirm flag set:
|
||||
* Validate Move was successful
|
||||
* Else: Validate move was not successful
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
copied_asset = ''
|
||||
|
||||
@@ -141,6 +153,11 @@ class TestsAssetRelocator_WindowsAndMac(object):
|
||||
User should be warned that LeaveEmptyFolders needs to be used with the move or delete command
|
||||
|
||||
:return: None
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Attempt to move with --LeaveEmptyFolders set
|
||||
3. Verify user is given a message that command requires to be used with --move or --delete
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
expected_message = "Command --leaveEmptyFolders must be used with command --move or --delete"
|
||||
@@ -162,6 +179,11 @@ class TestsAssetRelocator_WindowsAndMac(object):
|
||||
Asset with UUID/AssetId reference in non-standard format is
|
||||
successfully scanned and relocated to the MoveOutput folder.
|
||||
This test uses a pre-corrupted .slice file.
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment with a corrupted slice
|
||||
2. Attempt to move the corrupted slice
|
||||
3. Verify that corrupted slice was moved successfully
|
||||
"""
|
||||
|
||||
env = ap_setup_fixture
|
||||
@@ -194,6 +216,11 @@ class TestsAssetRelocator_WindowsAndMac(object):
|
||||
def test_WindowsMacPlatforms_UpdateReferences_MoveCommandMessage(self, ap_setup_fixture, asset_processor):
|
||||
"""
|
||||
UpdateReferences without move or delete
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Attempt to move with UpdateReferences but without move or delete flags
|
||||
3. Verify that message is returned to the user that additional flags are required
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
expected_message = "Command --updateReferences must be used with command --move"
|
||||
@@ -215,6 +242,11 @@ class TestsAssetRelocator_WindowsAndMac(object):
|
||||
"""
|
||||
When running the relocator command --AllowBrokenDependencies without the move or delete flags, the user should
|
||||
be warned that the flags are necessary for the functionality to be used
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Attempt to move with AllowBrokenDependencies without the move or delete flag
|
||||
3. Verify that message is returned to the user that additional flags are required
|
||||
"""
|
||||
|
||||
env = ap_setup_fixture
|
||||
@@ -302,10 +334,19 @@ class TestsAssetRelocator_WindowsAndMac(object):
|
||||
project
|
||||
):
|
||||
"""
|
||||
Dynamic data test for deleting a file with Asset Relocator:
|
||||
|
||||
C21968355 Delete a file with confirm
|
||||
C21968356 Delete a file without confirm
|
||||
C21968359 Delete a file that is marked as ReadOnly
|
||||
C21968360 Delete a file that is not marked as ReadOnly
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Set the read-only status of the file based on the test case
|
||||
3. Run asset relocator with --delete and the confirm status based on the test case
|
||||
4. Assert file existence or nonexistence based on the test case
|
||||
5. Validate the relocation report based on expected and unexpected messages
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
test_file = "testFile.txt"
|
||||
@@ -430,6 +471,15 @@ class TestsAssetRelocator_WindowsAndMac(object):
|
||||
Test the LeaveEmptyFolders flag in various configurations
|
||||
|
||||
:returns: None
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Build the various move/delete commands here based on test data
|
||||
3. Run the move command with the various triggers based on test data
|
||||
4. Verify the original assets folder still exists based on test data
|
||||
5. Verify the files successfully moved to new location based on test data
|
||||
6. Verify that the files were removed from original location based on test data
|
||||
7. Verify the files have not been deleted or moved from original location based on test data
|
||||
"""
|
||||
# # Start test setup # #
|
||||
env = ap_setup_fixture
|
||||
@@ -517,6 +567,12 @@ class TestsAssetRelocator_WindowsAndMac(object):
|
||||
"""
|
||||
The test will attempt to move test assets that are not tracked under P4 source control using the EnableSCM flag
|
||||
Because the files are not tracked by source control, the relocation should fail
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Set ReadOnly or Not-ReadOnly for the test files based on test data
|
||||
3. Generate and run the enableSCM command
|
||||
4. Verify the move failed and expected messages are present
|
||||
"""
|
||||
# Move the test assets into the project folder
|
||||
env = ap_setup_fixture
|
||||
@@ -1037,6 +1093,13 @@ class TestsAssetRelocator_WindowsAndMac(object):
|
||||
C21968370 AllowBrokenDependencies with move and confirm
|
||||
C21968371 AllowBrokenDependencies with move and without confirm
|
||||
C21968375 AllowBrokenDependencies with delete
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Run Asset Processor to Process Assets
|
||||
3. Build primary AP Batch parameter value and destination paths
|
||||
4. Validate resulting file paths in source and output directories
|
||||
5. Validate the log based on expected and unexpected messages
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
all_test_asset_rel_paths = [
|
||||
@@ -1254,6 +1317,18 @@ class TestsAssetRelocator_WindowsAndMac(object):
|
||||
@pytest.mark.parametrize("test", tests)
|
||||
def test_WindowsAndMac_MoveMetadataFiles_PathExistenceAndMessage(self, workspace, request, ap_setup_fixture,
|
||||
asset_processor, test):
|
||||
"""
|
||||
Tests whether moving metadata files can be moved
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Determine if using wildcards on paths or not
|
||||
3. Determine if excludeMetaDataFiles is set or not
|
||||
4. Build primary AP Batch parameter value and destination paths
|
||||
5. Build and run the AP Batch command with parameters
|
||||
6. Validate resulting file paths in source and output directories
|
||||
7. Validate the log based on expected and unexpected messages
|
||||
"""
|
||||
env = ap_setup_fixture
|
||||
|
||||
def teardown():
|
||||
@@ -1342,7 +1417,7 @@ class TestsAssetRelocator_WindowsAndMac(object):
|
||||
|
||||
@dataclass
|
||||
class MoveTest:
|
||||
description: str # test case title directly copied from Testrail
|
||||
description: str # test case title
|
||||
asset_folder: str # which folder in ./assets will be used for this test
|
||||
encoded_command: str # the command to execute
|
||||
encoded_output_dir: str # the destination directory to validate
|
||||
@@ -1350,7 +1425,7 @@ class MoveTest:
|
||||
name_change_map: dict = None
|
||||
files_that_stay: List[str] = field(default_factory=lambda: [])
|
||||
output_messages: List[str] = field(default_factory=lambda: [])
|
||||
step: str = None # the step of the test from Testrail
|
||||
step: str = None # the step of the test from test repository
|
||||
prefix_commands: List[str] = field(default_factory=lambda: ["AssetProcessorBatch", "--zeroAnalysisMode"])
|
||||
suffix_commands: List[str] = field(default_factory=lambda: ["--confirm"])
|
||||
env: dict = field(init=False, default=None) # inject the ap_setup_fixture at runtime
|
||||
@@ -3718,7 +3793,18 @@ class TestsAssetProcessorMove_WindowsAndMac:
|
||||
# -k C19462747
|
||||
|
||||
@pytest.mark.parametrize("test", move_a_file_tests + move_a_folder_tests)
|
||||
def test_WindowsMacPlatforms_MoveCommand(self, asset_processor, ap_setup_fixture, test: MoveTest, project):
|
||||
def test_WindowsMacPlatforms_MoveCommand_CommandResult(self, asset_processor, ap_setup_fixture, test: MoveTest, project):
|
||||
"""
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment based on test data
|
||||
2. Validate that temporary testing environment was created successfully
|
||||
3. Execute the move command based upon the test data
|
||||
4. Validate that files are where they're expected according to the test data
|
||||
5. Validate unexpected files are not found according to the test data
|
||||
6. Validate output messages according to the test data
|
||||
7. Validate move status according to the test data
|
||||
"""
|
||||
|
||||
source_folder, _ = asset_processor.prepare_test_environment(ap_setup_fixture["tests_dir"], test.asset_folder)
|
||||
test.map_env(ap_setup_fixture, source_folder)
|
||||
|
||||
+129
-13
@@ -75,6 +75,15 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
def do_missing_dependency_test(self, source_product, expected_dependencies,
|
||||
dsp_param,
|
||||
platforms=None, max_iterations=0):
|
||||
"""
|
||||
Test Steps:
|
||||
1. Determine what platforms to run against
|
||||
2. Process assets for that platform
|
||||
3. Determine the missing dependency params to set
|
||||
4. Set the max iteration param
|
||||
5. Run missing dependency scanner against target platforms and search params based on test data
|
||||
6. Validate missing dependencies against test data
|
||||
"""
|
||||
|
||||
platforms = platforms or ASSET_PROCESSOR_PLATFORM_MAP[self._workspace.asset_processor_platform]
|
||||
if not isinstance(platforms, list):
|
||||
@@ -104,7 +113,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id("C17226567")
|
||||
def test_WindowsAndMac_ValidUUIDNotDependency_ReportsMissingDependency(self):
|
||||
"""Tests that a valid UUID referenced in a file will report any missing dependencies"""
|
||||
"""
|
||||
Tests that a valid UUID referenced in a file will report any missing dependencies
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
# Relative path to the txt file with missing dependencies
|
||||
expected_product = f"testassets\\validuuidsnotdependency.txt"
|
||||
@@ -141,7 +157,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id("C17226567")
|
||||
def test_WindowsAndMac_InvalidUUIDsNotDependencies_NoReportedMessage(self):
|
||||
"""Tests that invalid UUIDs do not count as missing dependencies"""
|
||||
"""
|
||||
Tests that invalid UUIDs do not count as missing dependencies
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
# Relative path to the txt file with invalid UUIDs
|
||||
expected_product = f"testassets\\invaliduuidnoreport.txt"
|
||||
expected_dependencies = [] # No expected missing dependencies
|
||||
@@ -153,7 +176,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id("C17226567")
|
||||
def test_WindowsAndMac_ValidAssetIdsNotDependencies_ReportsMissingDependency(self):
|
||||
"""Tests that valid asset IDs but not dependencies, show missing dependencies"""
|
||||
"""
|
||||
Tests that valid asset IDs but not dependencies, show missing dependencies
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
# Relative path to the txt file with valid asset ids but not dependencies
|
||||
expected_product = f"testassets\\validassetidnotdependency.txt"
|
||||
@@ -173,7 +203,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id("C17226567")
|
||||
def test_WindowsAndMac_InvalidAssetsIDNotDependencies_NoReportedMessage(self):
|
||||
"""Tests that invalid asset IDs do not count as missing dependencies"""
|
||||
"""
|
||||
Tests that invalid asset IDs do not count as missing dependencies
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
# Relative path to the txt file with invalid asset IDs
|
||||
expected_product = f"testassets\\invalidassetidnoreport.txt"
|
||||
@@ -188,7 +225,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
# fmt:off
|
||||
def test_WindowsAndMac_ValidSourcePathsNotDependencies_ReportsMissingDependencies(self):
|
||||
# fmt:on
|
||||
"""Tests that valid source paths can translate to missing dependencies"""
|
||||
"""
|
||||
Tests that valid source paths can translate to missing dependencies
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
# Relative path to the txt file with missing dependencies as source paths
|
||||
expected_product = f"testassets\\relativesourcepathsnotdependencies.txt"
|
||||
@@ -212,7 +256,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id("C17226567")
|
||||
def test_WindowsAndMac_InvalidARelativePathsNotDependencies_NoReportedMessage(self):
|
||||
"""Tests that invalid relative paths do not resolve to missing dependencies"""
|
||||
"""
|
||||
Tests that invalid relative paths do not resolve to missing dependencies
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
# Relative path to the txt file with invalid relative paths
|
||||
expected_product = f"testassets\\invalidrelativepathsnoreport.txt"
|
||||
@@ -227,7 +278,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
# fmt:off
|
||||
def test_WindowsAndMac_ValidProductPathsNotDependencies_ReportsMissingDependencies(self):
|
||||
# fmt:on
|
||||
"""Tests that valid product paths can resolve to missing dependencies"""
|
||||
"""
|
||||
Tests that valid product paths can resolve to missing dependencies
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
self._asset_processor.add_source_folder_assets(f"Gems\\LyShineExamples\\Assets\\UI\\Fonts\\LyShineExamples")
|
||||
self._asset_processor.add_scan_folder(f"Gems\\LyShineExamples\\Assets")
|
||||
@@ -260,7 +318,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id("C17226567")
|
||||
def test_WindowsAndMac_WildcardScan_FindsAllExpectedFiles(self):
|
||||
"""Tests that the wildcard scanning will pick up multiple files"""
|
||||
"""
|
||||
Tests that the wildcard scanning will pick up multiple files
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
helper = self._missing_dep_helper
|
||||
|
||||
@@ -291,6 +356,11 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
For these references that are valid, all but one have available, matching dependencies. This test is
|
||||
primarily meant to verify that the missing dependency reporter checks the product dependency table before
|
||||
emitting missing dependencies.
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
# Relative path to target test file
|
||||
expected_product = f"testassets\\reportonemissingdependency.txt"
|
||||
@@ -305,7 +375,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id("C17226567")
|
||||
def test_WindowsAndMac_ReferencesSelfPath_NoReportedMessage(self):
|
||||
"""Tests that a file that references itself via relative path does not report itself as a missing dependency"""
|
||||
"""
|
||||
Tests that a file that references itself via relative path does not report itself as a missing dependency
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
# Relative path to file that references itself via relative path
|
||||
expected_product = f"testassets\\selfreferencepath.txt"
|
||||
expected_dependencies = []
|
||||
@@ -317,7 +394,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id("C17226567")
|
||||
def test_WindowsAndMac_ReferencesSelfUUID_NoReportedMessage(self):
|
||||
"""Tests that a file that references itself via its UUID does not report itself as a missing dependency"""
|
||||
"""
|
||||
Tests that a file that references itself via its UUID does not report itself as a missing dependency
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
# Relative path to file that references itself via its UUID
|
||||
expected_product = f"testassets\\selfreferenceuuid.txt"
|
||||
@@ -330,7 +414,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
@pytest.mark.assetpipeline
|
||||
@pytest.mark.test_case_id("C17226567")
|
||||
def test_WindowsAndMac_ReferencesSelfAssetID_NoReportedMessage(self):
|
||||
"""Tests that a file that references itself via its Asset ID does not report itself as a missing dependency"""
|
||||
"""
|
||||
Tests that a file that references itself via its Asset ID does not report itself as a missing dependency
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
# Relative path to file that references itself via its Asset ID
|
||||
expected_product = f"testassets\\selfreferenceassetid.txt"
|
||||
@@ -347,6 +438,11 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
Tests that the scan limit fails to find a missing dependency that is out of reach.
|
||||
The max iteration count is set to just under where a valid missing dependency is on a line in the file,
|
||||
so this will not report any missing dependencies.
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
# Relative path to file that has a missing dependency at 31 iterations deep
|
||||
@@ -364,7 +460,13 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
Tests that the scan limit succeeds in finding a missing dependency that is barely in reach.
|
||||
In the previous test, the scanner was set to stop recursion just before a missing dependency was found.
|
||||
This test runs with the recursion limit set deep enough to actually find the missing dependency.
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
# Relative path to file that has a missing dependency at 31 iterations deep
|
||||
expected_product = f"testassets\\maxiteration31deep.txt"
|
||||
|
||||
@@ -383,7 +485,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
# fmt:off
|
||||
def test_WindowsAndMac_PotentialMatchesLongerThanUUIDString_OnlyReportsCorrectLengthUUIDs(self):
|
||||
# fmt:on
|
||||
"""Tests that dependency references that are longer than expected are ignored"""
|
||||
"""
|
||||
Tests that dependency references that are longer than expected are ignored
|
||||
|
||||
Test Steps:
|
||||
1. Set the expected product
|
||||
2. Set the expected missing dependencies
|
||||
3. Execute test
|
||||
"""
|
||||
|
||||
# Relative path to text file with varying length UUID references
|
||||
expected_product = f"testassets\\onlymatchescorrectlengthuuids.txt"
|
||||
@@ -408,7 +517,14 @@ class TestsMissingDependencies_WindowsAndMac(object):
|
||||
def test_WindowsAndMac_MissingDependencyScanner_GradImageSuccess(
|
||||
self, ap_setup_fixture
|
||||
):
|
||||
"""Tests the Missing Dependency Scanner can scan gradimage files"""
|
||||
"""
|
||||
Tests the Missing Dependency Scanner can scan gradimage files
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary testing environment
|
||||
2. Run the move dependency scanner against the gradimage
|
||||
2. Validate that the expected product files and and expected depdencies match
|
||||
"""
|
||||
|
||||
env = ap_setup_fixture
|
||||
helper = self._missing_dep_helper
|
||||
|
||||
+10
@@ -51,6 +51,11 @@ class TestAuxiliaryContent:
|
||||
def test_CreateAuxiliaryContent_DontSkipLevelPaks(self, workspace, level):
|
||||
"""
|
||||
This test ensure that Auxiliary Content contain level.pak files
|
||||
|
||||
Test Steps:
|
||||
1. Run auxiliary content against project under test
|
||||
2. Validate auxiliary content exists
|
||||
3. Verifies that level.pak exists
|
||||
"""
|
||||
|
||||
path_to_dev = workspace.paths.engine_root()
|
||||
@@ -70,6 +75,11 @@ class TestAuxiliaryContent:
|
||||
def test_CreateAuxiliaryContent_SkipLevelPaks(self, workspace, level):
|
||||
"""
|
||||
This test ensure that Auxiliary Content contain no level.pak file
|
||||
|
||||
Test Steps:
|
||||
1. Run auxiliary content against project under test with skiplevelPaks flag
|
||||
2. Validate auxiliary content exists
|
||||
3. Validate level.pak was added to auxiliary content
|
||||
"""
|
||||
|
||||
path_to_dev = workspace.paths.engine_root()
|
||||
|
||||
@@ -533,6 +533,14 @@ class TestsFBX_AllPlatforms(object):
|
||||
def test_FBXBlackboxTest_SourceFiles_Processed_ResultInExpectedProducts(self, workspace,
|
||||
ap_setup_fixture, asset_processor, project,
|
||||
blackbox_param):
|
||||
"""
|
||||
Please see run_fbx_test(...) for details
|
||||
|
||||
Test Steps:
|
||||
1. Determine if blackbox is set to none
|
||||
2. Run FBX Test
|
||||
"""
|
||||
|
||||
if blackbox_param == None:
|
||||
return
|
||||
self.run_fbx_test(workspace, ap_setup_fixture,
|
||||
@@ -544,6 +552,15 @@ class TestsFBX_AllPlatforms(object):
|
||||
workspace, ap_setup_fixture,
|
||||
asset_processor, project,
|
||||
blackbox_param):
|
||||
"""
|
||||
Please see run_fbx_test(...) for details
|
||||
|
||||
Test Steps:
|
||||
1. Determine if blackbox is set to none
|
||||
2. Run FBX Test
|
||||
2. Re-run FBX test and validate the information in override assets
|
||||
"""
|
||||
|
||||
if blackbox_param == None:
|
||||
return
|
||||
self.run_fbx_test(workspace, ap_setup_fixture,
|
||||
@@ -567,6 +584,19 @@ class TestsFBX_AllPlatforms(object):
|
||||
|
||||
def run_fbx_test(self, workspace, ap_setup_fixture, asset_processor,
|
||||
project, blackbox_params: BlackboxAssetTest, overrideAsset = False):
|
||||
"""
|
||||
These tests work by having the test case ingest the test data and determine the run pattern.
|
||||
Tests will process scene settings files and will additionally do a verification against a provided debug file
|
||||
Additionally, if an override is passed, the output is checked against the override.
|
||||
|
||||
Test Steps:
|
||||
1. Create temporary test environment
|
||||
2. Process Assets
|
||||
3. Determine what assets to validate based upon test data
|
||||
4. Validate assets were created in cache
|
||||
5. If debug file provided, verify scene files were generated correctly
|
||||
6. Verify that each given source asset resulted in the expected jobs and products
|
||||
"""
|
||||
|
||||
test_assets_folder = blackbox_params.override_asset_folder if overrideAsset else blackbox_params.asset_folder
|
||||
logger.info(f"{blackbox_params.test_name}: Processing assets in folder '"
|
||||
|
||||
+172
-37
@@ -26,6 +26,18 @@ def soundbank_metadata_generator_setup_fixture(workspace):
|
||||
|
||||
|
||||
def success_case_test(test_folder, expected_dependencies_dict, bank_info, expected_result_code=0):
|
||||
"""
|
||||
Test Steps:
|
||||
1. Make sure the return code is what was expected, and that the expected number of banks were returned.
|
||||
2. Validate bank is in the expected dependencies dictionary.
|
||||
3. Validate the path to output the metadata file to was assembled correctly.
|
||||
4. Validate metadata object for this bank is set, and that it has an object assigned to its dependencies field
|
||||
and its includedEvents field
|
||||
5. Validate metadata object has the correct number of dependencies, and validated that every expected dependency
|
||||
exists in the dependencies list of the metadata object.
|
||||
6. Validate metadata object has the correct number of events, and validate that every expected event exists in the
|
||||
events of the metadata object.
|
||||
"""
|
||||
expected_bank_count = len(expected_dependencies_dict)
|
||||
|
||||
banks, result_code = bank_info.generate_metadata(
|
||||
@@ -80,8 +92,17 @@ class TestSoundBankMetadataGenerator:
|
||||
|
||||
|
||||
def test_NoMetadataTooFewBanks_ReturnCodeIsError(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# Trying to generate metadata for banks in a folder with one or fewer banks and no metadata is not possible
|
||||
# and should fail.
|
||||
"""
|
||||
Trying to generate metadata for banks in a folder with one or fewer banks and no metadata is not possible
|
||||
and should fail.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment with only 1 bank file
|
||||
2. Get Sound Bank Info
|
||||
3. Attempt to generate sound bank metadata
|
||||
4. Verify that proper error code is returned
|
||||
"""
|
||||
#
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_NoMetadataTooFewBanks_ReturnCodeIsError')
|
||||
if not os.path.isdir(test_assets_folder):
|
||||
@@ -97,15 +118,30 @@ class TestSoundBankMetadataGenerator:
|
||||
assert error_code is 2, 'Metadata was generated when there were fewer than two banks in the target directory.'
|
||||
|
||||
def test_NoMetadataNoContentBank_NoMetadataGenerated(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
"""
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. No expected dependencies
|
||||
3. Call success case test
|
||||
"""
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_NoMetadataNoContentBank_NoMetadataGenerated')
|
||||
expected_dependencies = dict()
|
||||
success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace))
|
||||
|
||||
def test_NoMetadataOneContentBank_NoStreamedFiles_OneDependency(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# When no Wwise metadata is present, and there is only one content bank in the target directory with no wem
|
||||
# files, then only the content bank should have metadata associated with it. The generated metadata should
|
||||
# only describe a dependency on the init bank.
|
||||
"""
|
||||
When no Wwise metadata is present, and there is only one content bank in the target directory with no wem
|
||||
files, then only the content bank should have metadata associated with it. The generated metadata should
|
||||
only describe a dependency on the init bank.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_NoMetadataOneContentBank_NoStreamedFiles_OneDependency')
|
||||
|
||||
@@ -116,9 +152,18 @@ class TestSoundBankMetadataGenerator:
|
||||
|
||||
def test_NoMetadataOneContentBank_StreamedFiles_MultipleDependencies(self, workspace,
|
||||
soundbank_metadata_generator_setup_fixture):
|
||||
# When no Wwise metadata is present, and there is only one content bank in the target directory with wem files
|
||||
# present, then only the content bank should have metadata associated with it. The generated metadata should
|
||||
# describe a dependency on the init bank and all wem files in the folder.
|
||||
"""
|
||||
When no Wwise metadata is present, and there is only one content bank in the target directory with wem files
|
||||
present, then only the content bank should have metadata associated with it. The generated metadata should
|
||||
describe a dependency on the init bank and all wem files in the folder.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_NoMetadataOneContentBank_StreamedFiles_MultipleDependencies')
|
||||
|
||||
@@ -136,10 +181,19 @@ class TestSoundBankMetadataGenerator:
|
||||
success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace))
|
||||
|
||||
def test_NoMetadataMultipleBanks_OneDependency_ReturnCodeIsWarning(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# When no Wwise metadata is present, and there are multiple content banks in the target directory with wem files
|
||||
# present, there is no way to tell which bank requires which wem files. A warning should be emitted,
|
||||
# stating that the full dependency graph could not be created, and only dependencies on the init bank are
|
||||
# described in the generated metadata files.
|
||||
"""
|
||||
When no Wwise metadata is present, and there are multiple content banks in the target directory with wem files
|
||||
present, there is no way to tell which bank requires which wem files. A warning should be emitted,
|
||||
stating that the full dependency graph could not be created, and only dependencies on the init bank are
|
||||
described in the generated metadata files.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_NoMetadataMultipleBanks_OneDependency_ReturnCodeIsWarning')
|
||||
bank_info = get_bank_info(workspace)
|
||||
@@ -150,8 +204,17 @@ class TestSoundBankMetadataGenerator:
|
||||
success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace), expected_result_code=1)
|
||||
|
||||
def test_OneContentBank_NoStreamedFiles_OneDependency(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# Wwise metadata describes one content bank that contains all media needed by its events. Generated metadata
|
||||
# describes a dependency only on the init bank.
|
||||
"""
|
||||
Wwise metadata describes one content bank that contains all media needed by its events. Generated metadata
|
||||
describes a dependency only on the init bank.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_OneContentBank_NoStreamedFiles_OneDependency')
|
||||
|
||||
@@ -165,8 +228,17 @@ class TestSoundBankMetadataGenerator:
|
||||
success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace))
|
||||
|
||||
def test_OneContentBank_StreamedFiles_MultipleDependencies(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# Wwise metadata describes one content bank that references streamed media files needed by its events. Generated
|
||||
# metadata describes dependencies on the init bank and wems named by the IDs of referenced streamed media.
|
||||
"""
|
||||
Wwise metadata describes one content bank that references streamed media files needed by its events. Generated
|
||||
metadata describes dependencies on the init bank and wems named by the IDs of referenced streamed media.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_OneContentBank_StreamedFiles_MultipleDependencies')
|
||||
|
||||
@@ -187,8 +259,17 @@ class TestSoundBankMetadataGenerator:
|
||||
success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace))
|
||||
|
||||
def test_MultipleContentBanks_NoStreamedFiles_OneDependency(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# Wwise metadata describes multiple content banks. Each bank contains all media needed by its events. Generated
|
||||
# metadata describes each bank having a dependency only on the init bank.
|
||||
"""
|
||||
Wwise metadata describes multiple content banks. Each bank contains all media needed by its events. Generated
|
||||
metadata describes each bank having a dependency only on the init bank.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_MultipleContentBanks_NoStreamedFiles_OneDependency')
|
||||
|
||||
@@ -206,8 +287,17 @@ class TestSoundBankMetadataGenerator:
|
||||
success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace))
|
||||
|
||||
def test_MultipleContentBanks_Bank1StreamedFiles(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# Wwise metadata describes multiple content banks. Bank 1 references streamed media files needed by its events,
|
||||
# while bank 2 contains all media need by its events.
|
||||
"""
|
||||
Wwise metadata describes multiple content banks. Bank 1 references streamed media files needed by its events,
|
||||
while bank 2 contains all media need by its events.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_MultipleContentBanks_Bank1StreamedFiles')
|
||||
|
||||
@@ -228,9 +318,18 @@ class TestSoundBankMetadataGenerator:
|
||||
success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace))
|
||||
|
||||
def test_MultipleContentBanks_SplitBanks_OnlyBankDependenices(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# Wwise metadata describes multiple content banks. Bank 3 events require media that is contained in bank 4.
|
||||
# Generated metadata describes each bank having a dependency on the init bank, while bank 3 has an additional
|
||||
# dependency on bank 4.
|
||||
"""
|
||||
Wwise metadata describes multiple content banks. Bank 3 events require media that is contained in bank 4.
|
||||
Generated metadata describes each bank having a dependency on the init bank, while bank 3 has an additional
|
||||
dependency on bank 4.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_MultipleContentBanks_SplitBanks_OnlyBankDependenices')
|
||||
|
||||
@@ -248,9 +347,18 @@ class TestSoundBankMetadataGenerator:
|
||||
success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace))
|
||||
|
||||
def test_MultipleContentBanks_ReferencedEvent_MediaEmbeddedInBank(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# Wwise metadata describes multiple content banks. Bank 1 contains all media required by its events, while bank
|
||||
# 5 contains a reference to an event in bank 1, but no media for that event. Generated metadata describes both
|
||||
# banks having a dependency on the init bank, while bank 5 has an additional dependency on bank 1.
|
||||
"""
|
||||
Wwise metadata describes multiple content banks. Bank 1 contains all media required by its events, while bank
|
||||
5 contains a reference to an event in bank 1, but no media for that event. Generated metadata describes both
|
||||
banks having a dependency on the init bank, while bank 5 has an additional dependency on bank 1.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_MultipleContentBanks_ReferencedEvent_MediaEmbeddedInBank')
|
||||
|
||||
@@ -271,10 +379,19 @@ class TestSoundBankMetadataGenerator:
|
||||
success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace))
|
||||
|
||||
def test_MultipleContentBanks_ReferencedEvent_MediaStreamed(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# Wwise metadata describes multiple content banks. Bank 1 references streamed media files needed by its events,
|
||||
# while bank 5 contains a reference to an event in bank 1. This causes bank 5 to also describe a reference to
|
||||
# the streamed media file referenced by the event from bank 1. Generated metadata describes both banks having
|
||||
# dependencies on the init bank, as well as the wem named by the ID of referenced streamed media.
|
||||
"""
|
||||
Wwise metadata describes multiple content banks. Bank 1 references streamed media files needed by its events,
|
||||
while bank 5 contains a reference to an event in bank 1. This causes bank 5 to also describe a reference to
|
||||
the streamed media file referenced by the event from bank 1. Generated metadata describes both banks having
|
||||
dependencies on the init bank, as well as the wem named by the ID of referenced streamed media.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_MultipleContentBanks_ReferencedEvent_MediaStreamed')
|
||||
|
||||
@@ -298,11 +415,20 @@ class TestSoundBankMetadataGenerator:
|
||||
success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace))
|
||||
|
||||
def test_MultipleContentBanks_ReferencedEvent_MixedSources(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# Wwise metadata describes multiple content banks. Bank 1 references a streamed media files needed by one of its
|
||||
# events, and contains all media needed for its other events, while bank 5 contains a reference to two events
|
||||
# in bank 1: one that requires streamed media, and one that requires media embedded in bank 1. Generated
|
||||
# metadata describes both banks having dependencies on the init bank and the wem named by the ID of referenced
|
||||
# streamed media, while bank 5 has an additional dependency on bank 1.
|
||||
"""
|
||||
Wwise metadata describes multiple content banks. Bank 1 references a streamed media files needed by one of its
|
||||
events, and contains all media needed for its other events, while bank 5 contains a reference to two events
|
||||
in bank 1: one that requires streamed media, and one that requires media embedded in bank 1. Generated
|
||||
metadata describes both banks having dependencies on the init bank and the wem named by the ID of referenced
|
||||
streamed media, while bank 5 has an additional dependency on bank 1.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_MultipleContentBanks_ReferencedEvent_MixedSources')
|
||||
|
||||
@@ -332,8 +458,17 @@ class TestSoundBankMetadataGenerator:
|
||||
success_case_test(test_assets_folder, expected_dependencies, get_bank_info(workspace))
|
||||
|
||||
def test_MultipleContentBanks_VaryingDependencies_MixedSources(self, workspace, soundbank_metadata_generator_setup_fixture):
|
||||
# Wwise metadata describes multiple content banks that have varying dependencies on each other, and dependencies
|
||||
# on streamed media files.
|
||||
"""
|
||||
Wwise metadata describes multiple content banks that have varying dependencies on each other, and dependencies
|
||||
on streamed media files.
|
||||
|
||||
Test Steps:
|
||||
1. Setup testing environment
|
||||
2. Get current bank info
|
||||
3. Build expected dependencies
|
||||
4. Call success case test
|
||||
"""
|
||||
|
||||
test_assets_folder = os.path.join(soundbank_metadata_generator_setup_fixture['tests_dir'], 'assets',
|
||||
'test_MultipleContentBanks_VaryingDependencies_MixedSources')
|
||||
|
||||
|
||||
@@ -9,11 +9,6 @@ remove or modify any license notices. This file is distributed on an "AS IS" BAS
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
"""
|
||||
|
||||
"""
|
||||
C24064528: The File menu options function normally
|
||||
C16780778: The File menu options function normally-New view interaction Model enabled
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -54,7 +49,10 @@ class TestFileMenuOptions(EditorTestHelper):
|
||||
("Save",),
|
||||
("Save As",),
|
||||
("Save Level Statistics",),
|
||||
("Project Settings", "Project Settings Tool"),
|
||||
("Edit Project Settings",),
|
||||
("Edit Platform Settings",),
|
||||
("New Project",),
|
||||
("Open Project",),
|
||||
("Show Log File",),
|
||||
("Resave All Slices",),
|
||||
("Exit",),
|
||||
|
||||
@@ -15,6 +15,7 @@ import pytest
|
||||
# Bail on the test if ly_test_tools doesn't exist.
|
||||
pytest.importorskip('ly_test_tools')
|
||||
import ly_test_tools.environment.file_system as file_system
|
||||
import ly_test_tools._internal.pytest_plugin as internal_plugin
|
||||
import editor_python_test_tools.hydra_test_utils as hydra
|
||||
|
||||
test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts")
|
||||
@@ -40,6 +41,10 @@ class TestBasicEditorWorkflows(object):
|
||||
@pytest.mark.SUITE_main
|
||||
def test_BasicEditorWorkflows_LevelEntityComponentCRUD(self, request, editor, level, launcher_platform):
|
||||
|
||||
# Skip test if running against Debug build
|
||||
if "debug" in internal_plugin.build_directory:
|
||||
pytest.skip("Does not execute against debug builds.")
|
||||
|
||||
expected_lines = [
|
||||
"Create and load new level: True",
|
||||
"New entity creation: True",
|
||||
|
||||
@@ -7,8 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens
|
||||
or, if provided, by the license below or the license accompanying this file. Do not
|
||||
remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
|
||||
C16780783: Base Edit Menu Options (New Viewport Interaction Model)
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -17,6 +15,7 @@ import pytest
|
||||
# Bail on the test if ly_test_tools doesn't exist.
|
||||
pytest.importorskip('ly_test_tools')
|
||||
import ly_test_tools.environment.file_system as file_system
|
||||
import ly_test_tools.environment.process_utils as process_utils
|
||||
import editor_python_test_tools.hydra_test_utils as hydra
|
||||
|
||||
test_directory = os.path.join(os.path.dirname(__file__), "EditorScripts")
|
||||
@@ -33,6 +32,7 @@ class TestMenus(object):
|
||||
def setup_teardown(self, request, workspace, project, level):
|
||||
def teardown():
|
||||
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
|
||||
process_utils.kill_processes_named("o3de", ignore_extensions=True) # Kill ProjectManager windows
|
||||
|
||||
request.addfinalizer(teardown)
|
||||
|
||||
@@ -80,8 +80,7 @@ class TestMenus(object):
|
||||
expected_lines,
|
||||
cfg_args=[level],
|
||||
run_python="--runpython",
|
||||
auto_test_mode=True,
|
||||
timeout=log_monitor_timeout,
|
||||
timeout=log_monitor_timeout
|
||||
)
|
||||
|
||||
@pytest.mark.test_case_id("C16780807")
|
||||
@@ -107,13 +106,13 @@ class TestMenus(object):
|
||||
"Menus_ViewMenuOptions.py",
|
||||
expected_lines,
|
||||
cfg_args=[level],
|
||||
auto_test_mode=True,
|
||||
run_python="--runpython",
|
||||
timeout=log_monitor_timeout,
|
||||
timeout=log_monitor_timeout
|
||||
)
|
||||
|
||||
@pytest.mark.test_case_id("C16780778")
|
||||
@pytest.mark.SUITE_sandbox
|
||||
@pytest.mark.xfail # LYN-4208
|
||||
def test_Menus_FileMenuOptions_Work(self, request, editor, level, launcher_platform):
|
||||
expected_lines = [
|
||||
"New Level Action triggered",
|
||||
@@ -122,7 +121,10 @@ class TestMenus(object):
|
||||
"Save Action triggered",
|
||||
"Save As Action triggered",
|
||||
"Save Level Statistics Action triggered",
|
||||
"Project Settings Tool Action triggered",
|
||||
"Edit Project Settings Action triggered",
|
||||
"Edit Platform Settings Action triggered",
|
||||
"New Project Action triggered",
|
||||
"Open Project Action triggered",
|
||||
"Show Log File Action triggered",
|
||||
"Resave All Slices Action triggered",
|
||||
"Exit Action triggered",
|
||||
@@ -135,7 +137,6 @@ class TestMenus(object):
|
||||
"Menus_FileMenuOptions.py",
|
||||
expected_lines,
|
||||
cfg_args=[level],
|
||||
auto_test_mode=True,
|
||||
run_python="--runpython",
|
||||
timeout=log_monitor_timeout,
|
||||
)
|
||||
timeout=log_monitor_timeout
|
||||
)
|
||||
|
||||
+6
@@ -16,6 +16,7 @@ import logging
|
||||
# Bail on the test if ly_test_tools doesn't exist.
|
||||
pytest.importorskip('ly_test_tools')
|
||||
import ly_test_tools.environment.file_system as file_system
|
||||
import ly_test_tools._internal.pytest_plugin as internal_plugin
|
||||
import editor_python_test_tools.hydra_test_utils as hydra
|
||||
from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole
|
||||
|
||||
@@ -46,6 +47,11 @@ class TestDynamicSliceInstanceSpawner(object):
|
||||
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
|
||||
def test_DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks(self, request, editor, level, workspace, project,
|
||||
launcher_platform):
|
||||
|
||||
# Skip test if running against Debug build
|
||||
if "debug" in internal_plugin.build_directory:
|
||||
pytest.skip("Does not execute against debug builds.")
|
||||
|
||||
# Ensure temp level does not already exist
|
||||
file_system.delete([os.path.join(workspace.paths.engine_root(), project, "Levels", level)], True, True)
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import logging
|
||||
# Bail on the test if ly_test_tools doesn't exist.
|
||||
pytest.importorskip('ly_test_tools')
|
||||
import ly_test_tools.environment.file_system as file_system
|
||||
import ly_test_tools._internal.pytest_plugin as internal_plugin
|
||||
import editor_python_test_tools.hydra_test_utils as hydra
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -40,6 +41,11 @@ class TestEmptyInstanceSpawner(object):
|
||||
@pytest.mark.SUITE_main
|
||||
@pytest.mark.dynveg_area
|
||||
def test_EmptyInstanceSpawner_EmptySpawnerWorks(self, request, editor, level, launcher_platform):
|
||||
|
||||
# Skip test if running against Debug build
|
||||
if "debug" in internal_plugin.build_directory:
|
||||
pytest.skip("Does not execute against debug builds.")
|
||||
|
||||
cfg_args = [level]
|
||||
|
||||
expected_lines = [
|
||||
|
||||
+11
@@ -23,6 +23,7 @@ import pytest
|
||||
# Bail on the test if ly_test_tools doesn't exist.
|
||||
pytest.importorskip('ly_test_tools')
|
||||
import ly_test_tools.environment.file_system as file_system
|
||||
import ly_test_tools._internal.pytest_plugin as internal_plugin
|
||||
import editor_python_test_tools.hydra_test_utils as hydra
|
||||
|
||||
test_directory = os.path.join(os.path.dirname(__file__), 'EditorScripts')
|
||||
@@ -46,6 +47,11 @@ class TestGraphComponentSync(object):
|
||||
@pytest.mark.BAT
|
||||
@pytest.mark.SUITE_main
|
||||
def test_LandscapeCanvas_SlotConnections_UpdateComponentReferences(self, request, editor, level, launcher_platform):
|
||||
|
||||
# Skip test if running against Debug build
|
||||
if "debug" in internal_plugin.build_directory:
|
||||
pytest.skip("Does not execute against debug builds.")
|
||||
|
||||
cfg_args = [level]
|
||||
|
||||
expected_lines = [
|
||||
@@ -122,6 +128,11 @@ class TestGraphComponentSync(object):
|
||||
"""
|
||||
Verifies a Gradient Mixer can be setup in Landscape Canvas and all references are property set.
|
||||
"""
|
||||
|
||||
# Skip test if running against Debug build
|
||||
if "debug" in internal_plugin.build_directory:
|
||||
pytest.skip("Does not execute against debug builds.")
|
||||
|
||||
cfg_args = [level]
|
||||
|
||||
expected_lines = [
|
||||
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
"""
|
||||
All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
|
||||
its licensors.
|
||||
|
||||
For complete copyright and license terms please see the LICENSE at the root of this
|
||||
distribution (the "License"). All use of this software is governed by the License,
|
||||
or, if provided, by the license below or the license accompanying this file. Do not
|
||||
remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
"""
|
||||
|
||||
|
||||
# fmt: off
|
||||
class Tests():
|
||||
new_event_created = ("Successfully created a new event", "Failed to create a new event")
|
||||
child_event_created = ("Successfully created Child Event", "Failed to create Child Event")
|
||||
file_saved = ("Successfully saved event asset", "Failed to save event asset")
|
||||
parameter_created = ("Successfully added parameter", "Failed to add parameter")
|
||||
parameter_removed = ("Successfully removed parameter", "Failed to remove parameter")
|
||||
# fmt: on
|
||||
|
||||
|
||||
def ScriptEvent_AddRemoveParameter_ActionsSuccessful():
|
||||
"""
|
||||
Summary:
|
||||
Parameter can be removed from a Script Event method
|
||||
|
||||
Expected Behavior:
|
||||
Upon saving the updated .scriptevents asset the removed paramenter should no longer be present on the Script Event
|
||||
|
||||
Test Steps:
|
||||
1) Open Asset Editor
|
||||
2) Get Asset Editor Qt object
|
||||
3) Create new Script Event Asset
|
||||
4) Add Parameter to Event
|
||||
5) Remove Parameter from Event
|
||||
|
||||
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
|
||||
from PySide2 import QtWidgets
|
||||
|
||||
from editor_python_test_tools.utils import Report
|
||||
from editor_python_test_tools.utils import TestHelper as helper
|
||||
import editor_python_test_tools.pyside_utils as pyside_utils
|
||||
|
||||
import azlmbr.bus as bus
|
||||
import azlmbr.editor as editor
|
||||
import azlmbr.legacy.general as general
|
||||
|
||||
GENERAL_WAIT = 1.0 # seconds
|
||||
FILE_PATH = os.path.join("AutomatedTesting", "ScriptCanvas", "test_file.scriptevent")
|
||||
QtObject = object
|
||||
|
||||
def create_script_event(asset_editor: QtObject, file_path: str) -> None:
|
||||
action = pyside_utils.find_child_by_pattern(menu_bar, {"type": QtWidgets.QAction, "text": "Script Events"})
|
||||
action.trigger()
|
||||
result = helper.wait_for_condition(
|
||||
lambda: container.findChild(QtWidgets.QFrame, "Events") is not None, 3 * GENERAL_WAIT
|
||||
)
|
||||
Report.result(Tests.new_event_created, result)
|
||||
|
||||
# Add new child event
|
||||
add_event = container.findChild(QtWidgets.QFrame, "Events").findChild(QtWidgets.QToolButton, "")
|
||||
add_event.click()
|
||||
result = helper.wait_for_condition(
|
||||
lambda: asset_editor.findChild(QtWidgets.QFrame, "EventName") is not None, GENERAL_WAIT
|
||||
)
|
||||
Report.result(Tests.child_event_created, result)
|
||||
# Save the Script Event file
|
||||
editor.AssetEditorWidgetRequestsBus(bus.Broadcast, "SaveAssetAs", file_path)
|
||||
|
||||
# Verify if file is created
|
||||
result = helper.wait_for_condition(lambda: os.path.exists(file_path), 3 * GENERAL_WAIT)
|
||||
Report.result(Tests.file_saved, result)
|
||||
|
||||
def create_parameter(file_path: str) -> None:
|
||||
add_param = container.findChild(QtWidgets.QFrame, "Parameters").findChild(QtWidgets.QToolButton, "")
|
||||
add_param.click()
|
||||
result = helper.wait_for_condition(
|
||||
lambda: asset_editor_widget.findChild(QtWidgets.QFrame, "[0]") is not None, GENERAL_WAIT
|
||||
)
|
||||
Report.result(Tests.parameter_created, result)
|
||||
editor.AssetEditorWidgetRequestsBus(bus.Broadcast, "SaveAssetAs", file_path)
|
||||
|
||||
def remove_parameter(file_path: str) -> None:
|
||||
remove_param = container.findChild(QtWidgets.QFrame, "[0]").findChild(QtWidgets.QToolButton, "")
|
||||
remove_param.click()
|
||||
result = helper.wait_for_condition(
|
||||
lambda: asset_editor_widget.findChild(QtWidgets.QFrame, "[0]") is None, GENERAL_WAIT
|
||||
)
|
||||
Report.result(Tests.parameter_removed, result)
|
||||
editor.AssetEditorWidgetRequestsBus(bus.Broadcast, "SaveAssetAs", file_path)
|
||||
|
||||
# 1) Open Asset Editor
|
||||
general.idle_enable(True)
|
||||
# Initially close the Asset Editor and then reopen to ensure we don't have any existing assets open
|
||||
general.close_pane("Asset Editor")
|
||||
general.open_pane("Asset Editor")
|
||||
helper.wait_for_condition(lambda: general.is_pane_visible("Asset Editor"), 5.0)
|
||||
|
||||
# 2) Get Asset Editor Qt object
|
||||
editor_window = pyside_utils.get_editor_main_window()
|
||||
asset_editor_widget = editor_window.findChild(QtWidgets.QDockWidget, "Asset Editor").findChild(
|
||||
QtWidgets.QWidget, "AssetEditorWindowClass"
|
||||
)
|
||||
container = asset_editor_widget.findChild(QtWidgets.QWidget, "ContainerForRows")
|
||||
menu_bar = asset_editor_widget.findChild(QtWidgets.QMenuBar)
|
||||
|
||||
# 3) Create new Script Event Asset
|
||||
create_script_event(asset_editor_widget, FILE_PATH)
|
||||
|
||||
# 4) Add Parameter to Event
|
||||
create_parameter(FILE_PATH)
|
||||
|
||||
# 5) Remove Parameter from Event
|
||||
remove_parameter(FILE_PATH)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import ImportPathHelper as imports
|
||||
|
||||
imports.init()
|
||||
from editor_python_test_tools.utils import Report
|
||||
|
||||
Report.start_test(ScriptEvent_AddRemoveParameter_ActionsSuccessful)
|
||||
@@ -186,6 +186,18 @@ class TestAutomation(TestAutomationBase):
|
||||
from . import Node_HappyPath_DuplicateNode as test_module
|
||||
self._run_test(request, workspace, editor, test_module)
|
||||
|
||||
def test_ScriptEvent_AddRemoveParameter_ActionsSuccessful(self, request, workspace, editor, launcher_platform):
|
||||
def teardown():
|
||||
file_system.delete(
|
||||
[os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True
|
||||
)
|
||||
request.addfinalizer(teardown)
|
||||
file_system.delete(
|
||||
[os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True
|
||||
)
|
||||
from . import ScriptEvent_AddRemoveParameter_ActionsSuccessful as test_module
|
||||
self._run_test(request, workspace, editor, test_module)
|
||||
|
||||
# NOTE: We had to use hydra_test_utils.py, as TestAutomationBase run_test method
|
||||
# fails because of pyside_utils import
|
||||
@pytest.mark.SUITE_periodic
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:804193a2afd68cd1e6bec8155ea11400566f2941fbd6eb0c324839ebcd10192d
|
||||
size 8492
|
||||
oid sha256:302d6172156e8ed665e44e206d81f54f1b0f1008d73327300ea92f8c1159780b
|
||||
size 11820
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
{
|
||||
"AWSCore":
|
||||
{
|
||||
"ProfileName": "default",
|
||||
"ProfileName": "AWSAutomationTest",
|
||||
"ResourceMappingConfigFileName": "aws_resource_mappings.json"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:40949893ed7009eeaa90b7ce6057cb6be9dfaf7b162e3c26ba9dadf985939d7d
|
||||
size 2038
|
||||
oid sha256:b9cd9d6f67440c193a85969ec5c082c6343e6d1fff3b6f209a0a6931eb22dd47
|
||||
size 2949
|
||||
|
||||
@@ -4,17 +4,152 @@
|
||||
<Class name="AZStd::vector" field="Properties" type="{A8E59F8C-2F9A-525A-B549-A9E197EB9632}">
|
||||
<Class name="Physics::MaterialFromAssetConfiguration" field="element" version="1" type="{FBD76628-DE57-435E-BE00-6FFAE64DDF1D}">
|
||||
<Class name="Physics::MaterialConfiguration" field="Configuration" version="3" type="{8807CAA1-AD08-4238-8FDB-2154ADD084A1}">
|
||||
<Class name="AZStd::string" field="SurfaceType" value="Debug" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
|
||||
<Class name="float" field="DynamicFriction" value="0.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="StaticFriction" value="0.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="Restitution" value="0.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="unsigned char" field="FrictionCombine" value="0" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="unsigned char" field="RestitutionCombine" value="0" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="float" field="Density" value="1000.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="Color" field="DebugColor" value="1.0000000 1.0000000 1.0000000 1.0000000" type="{7894072A-9050-4F0F-901B-34B1A0D29417}"/>
|
||||
<Class name="AZStd::string" field="SurfaceType" value="Character" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
|
||||
<Class name="float" field="DynamicFriction" value="0.7000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="StaticFriction" value="0.8000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="Restitution" value="0.3000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="unsigned char" field="FrictionCombine" value="2" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="unsigned char" field="RestitutionCombine" value="3" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="float" field="Density" value="985.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="Color" field="DebugColor" value="0.9183642 0.6973526 0.4447700 1.0000000" type="{7894072A-9050-4F0F-901B-34B1A0D29417}"/>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialId" field="UID" version="1" type="{744CCE6C-9F69-4E2F-B950-DAB8514F870B}">
|
||||
<Class name="AZ::Uuid" field="MaterialId" value="{B072A405-BAFA-4B0A-9164-B3A424E642A9}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
|
||||
<Class name="AZ::Uuid" field="MaterialId" value="{FDECD8B6-5BAF-42CB-AEFE-C66E1E1CF557}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
|
||||
</Class>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialFromAssetConfiguration" field="element" version="1" type="{FBD76628-DE57-435E-BE00-6FFAE64DDF1D}">
|
||||
<Class name="Physics::MaterialConfiguration" field="Configuration" version="3" type="{8807CAA1-AD08-4238-8FDB-2154ADD084A1}">
|
||||
<Class name="AZStd::string" field="SurfaceType" value="Concrete" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
|
||||
<Class name="float" field="DynamicFriction" value="0.8000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="StaticFriction" value="0.9000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="Restitution" value="0.3800000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="unsigned char" field="FrictionCombine" value="3" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="unsigned char" field="RestitutionCombine" value="0" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="float" field="Density" value="2400.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="Color" field="DebugColor" value="0.5918365 0.4927596 0.3795224 1.0000000" type="{7894072A-9050-4F0F-901B-34B1A0D29417}"/>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialId" field="UID" version="1" type="{744CCE6C-9F69-4E2F-B950-DAB8514F870B}">
|
||||
<Class name="AZ::Uuid" field="MaterialId" value="{A9CACCFF-E0D2-4149-8891-E92319229B2D}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
|
||||
</Class>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialFromAssetConfiguration" field="element" version="1" type="{FBD76628-DE57-435E-BE00-6FFAE64DDF1D}">
|
||||
<Class name="Physics::MaterialConfiguration" field="Configuration" version="3" type="{8807CAA1-AD08-4238-8FDB-2154ADD084A1}">
|
||||
<Class name="AZStd::string" field="SurfaceType" value="Glass" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
|
||||
<Class name="float" field="DynamicFriction" value="0.4000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="StaticFriction" value="0.5000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="Restitution" value="0.7000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="unsigned char" field="FrictionCombine" value="3" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="unsigned char" field="RestitutionCombine" value="0" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="float" field="Density" value="2500.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="Color" field="DebugColor" value="0.4825971 0.8975662 0.9523766 1.0000000" type="{7894072A-9050-4F0F-901B-34B1A0D29417}"/>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialId" field="UID" version="1" type="{744CCE6C-9F69-4E2F-B950-DAB8514F870B}">
|
||||
<Class name="AZ::Uuid" field="MaterialId" value="{FD59CBE9-D1C4-4119-81CB-CD7AD72FC295}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
|
||||
</Class>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialFromAssetConfiguration" field="element" version="1" type="{FBD76628-DE57-435E-BE00-6FFAE64DDF1D}">
|
||||
<Class name="Physics::MaterialConfiguration" field="Configuration" version="3" type="{8807CAA1-AD08-4238-8FDB-2154ADD084A1}">
|
||||
<Class name="AZStd::string" field="SurfaceType" value="Metal" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
|
||||
<Class name="float" field="DynamicFriction" value="0.4200000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="StaticFriction" value="0.7800000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="Restitution" value="0.4000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="unsigned char" field="FrictionCombine" value="0" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="unsigned char" field="RestitutionCombine" value="0" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="float" field="Density" value="8050.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="Color" field="DebugColor" value="0.2312963 0.2312963 0.2312963 1.0000000" type="{7894072A-9050-4F0F-901B-34B1A0D29417}"/>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialId" field="UID" version="1" type="{744CCE6C-9F69-4E2F-B950-DAB8514F870B}">
|
||||
<Class name="AZ::Uuid" field="MaterialId" value="{76CDC778-ACA9-449F-BFD7-C361F89F3207}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
|
||||
</Class>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialFromAssetConfiguration" field="element" version="1" type="{FBD76628-DE57-435E-BE00-6FFAE64DDF1D}">
|
||||
<Class name="Physics::MaterialConfiguration" field="Configuration" version="3" type="{8807CAA1-AD08-4238-8FDB-2154ADD084A1}">
|
||||
<Class name="AZStd::string" field="SurfaceType" value="Plastic" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
|
||||
<Class name="float" field="DynamicFriction" value="0.3500000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="StaticFriction" value="0.3000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="Restitution" value="0.6900000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="unsigned char" field="FrictionCombine" value="3" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="unsigned char" field="RestitutionCombine" value="0" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="float" field="Density" value="900.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="Color" field="DebugColor" value="0.9394675 1.0000000 0.2735485 1.0000000" type="{7894072A-9050-4F0F-901B-34B1A0D29417}"/>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialId" field="UID" version="1" type="{744CCE6C-9F69-4E2F-B950-DAB8514F870B}">
|
||||
<Class name="AZ::Uuid" field="MaterialId" value="{E2FFB000-D15B-4760-A819-9E490D1D3741}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
|
||||
</Class>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialFromAssetConfiguration" field="element" version="1" type="{FBD76628-DE57-435E-BE00-6FFAE64DDF1D}">
|
||||
<Class name="Physics::MaterialConfiguration" field="Configuration" version="3" type="{8807CAA1-AD08-4238-8FDB-2154ADD084A1}">
|
||||
<Class name="AZStd::string" field="SurfaceType" value="Rubber" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
|
||||
<Class name="float" field="DynamicFriction" value="1.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="StaticFriction" value="1.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="Restitution" value="0.8500000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="unsigned char" field="FrictionCombine" value="3" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="unsigned char" field="RestitutionCombine" value="0" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="float" field="Density" value="1200.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="Color" field="DebugColor" value="0.1088426 0.1088426 0.1088426 1.0000000" type="{7894072A-9050-4F0F-901B-34B1A0D29417}"/>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialId" field="UID" version="1" type="{744CCE6C-9F69-4E2F-B950-DAB8514F870B}">
|
||||
<Class name="AZ::Uuid" field="MaterialId" value="{8C7A6011-61C2-46B7-9BF4-8D4DD2A624F1}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
|
||||
</Class>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialFromAssetConfiguration" field="element" version="1" type="{FBD76628-DE57-435E-BE00-6FFAE64DDF1D}">
|
||||
<Class name="Physics::MaterialConfiguration" field="Configuration" version="3" type="{8807CAA1-AD08-4238-8FDB-2154ADD084A1}">
|
||||
<Class name="AZStd::string" field="SurfaceType" value="Terrain_Dirt" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
|
||||
<Class name="float" field="DynamicFriction" value="0.4000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="StaticFriction" value="0.4000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="Restitution" value="0.3000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="unsigned char" field="FrictionCombine" value="0" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="unsigned char" field="RestitutionCombine" value="3" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="float" field="Density" value="1600.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="Color" field="DebugColor" value="0.3333333 0.2619974 0.1973144 1.0000000" type="{7894072A-9050-4F0F-901B-34B1A0D29417}"/>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialId" field="UID" version="1" type="{744CCE6C-9F69-4E2F-B950-DAB8514F870B}">
|
||||
<Class name="AZ::Uuid" field="MaterialId" value="{303C5A49-22F2-45A8-B24C-9F2C3CA13402}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
|
||||
</Class>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialFromAssetConfiguration" field="element" version="1" type="{FBD76628-DE57-435E-BE00-6FFAE64DDF1D}">
|
||||
<Class name="Physics::MaterialConfiguration" field="Configuration" version="3" type="{8807CAA1-AD08-4238-8FDB-2154ADD084A1}">
|
||||
<Class name="AZStd::string" field="SurfaceType" value="Terrain_Grass" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
|
||||
<Class name="float" field="DynamicFriction" value="0.2500000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="StaticFriction" value="0.3500000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="Restitution" value="0.2000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="unsigned char" field="FrictionCombine" value="3" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="unsigned char" field="RestitutionCombine" value="0" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="float" field="Density" value="1400.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="Color" field="DebugColor" value="0.1483177 0.5986419 0.1073777 1.0000000" type="{7894072A-9050-4F0F-901B-34B1A0D29417}"/>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialId" field="UID" version="1" type="{744CCE6C-9F69-4E2F-B950-DAB8514F870B}">
|
||||
<Class name="AZ::Uuid" field="MaterialId" value="{53733840-A095-40C4-B653-C40D233B3BE1}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
|
||||
</Class>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialFromAssetConfiguration" field="element" version="1" type="{FBD76628-DE57-435E-BE00-6FFAE64DDF1D}">
|
||||
<Class name="Physics::MaterialConfiguration" field="Configuration" version="3" type="{8807CAA1-AD08-4238-8FDB-2154ADD084A1}">
|
||||
<Class name="AZStd::string" field="SurfaceType" value="Vehicle" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
|
||||
<Class name="float" field="DynamicFriction" value="0.2000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="StaticFriction" value="0.5000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="Restitution" value="0.3000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="unsigned char" field="FrictionCombine" value="1" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="unsigned char" field="RestitutionCombine" value="1" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="float" field="Density" value="140.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="Color" field="DebugColor" value="1.0000000 0.0000000 0.0000000 1.0000000" type="{7894072A-9050-4F0F-901B-34B1A0D29417}"/>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialId" field="UID" version="1" type="{744CCE6C-9F69-4E2F-B950-DAB8514F870B}">
|
||||
<Class name="AZ::Uuid" field="MaterialId" value="{4080A6D4-AF4E-41CE-B7C9-7699C07123E7}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
|
||||
</Class>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialFromAssetConfiguration" field="element" version="1" type="{FBD76628-DE57-435E-BE00-6FFAE64DDF1D}">
|
||||
<Class name="Physics::MaterialConfiguration" field="Configuration" version="3" type="{8807CAA1-AD08-4238-8FDB-2154ADD084A1}">
|
||||
<Class name="AZStd::string" field="SurfaceType" value="Wood" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
|
||||
<Class name="float" field="DynamicFriction" value="0.5000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="StaticFriction" value="0.6000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="float" field="Restitution" value="0.6000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="unsigned char" field="FrictionCombine" value="3" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="unsigned char" field="RestitutionCombine" value="0" type="{72B9409A-7D1A-4831-9CFE-FCB3FADD3426}"/>
|
||||
<Class name="float" field="Density" value="540.0000000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
|
||||
<Class name="Color" field="DebugColor" value="1.0000000 0.7318379 0.3004501 1.0000000" type="{7894072A-9050-4F0F-901B-34B1A0D29417}"/>
|
||||
</Class>
|
||||
<Class name="Physics::MaterialId" field="UID" version="1" type="{744CCE6C-9F69-4E2F-B950-DAB8514F870B}">
|
||||
<Class name="AZ::Uuid" field="MaterialId" value="{6ACE67AA-CB32-41CD-8740-58371CCCD3F3}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
|
||||
</Class>
|
||||
</Class>
|
||||
</Class>
|
||||
|
||||
@@ -137,5 +137,6 @@ enum class AnimParamType
|
||||
Invalid = static_cast<int>(0xFFFFFFFF)
|
||||
};
|
||||
|
||||
static const int OLD_APARAM_USER = 100;
|
||||
|
||||
#endif // CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMPARAMTYPE_H
|
||||
|
||||
@@ -561,7 +561,7 @@ void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex)
|
||||
|
||||
if (pex)
|
||||
{
|
||||
MINIDUMP_TYPE mdumpValue;
|
||||
MINIDUMP_TYPE mdumpValue = MiniDumpNormal;
|
||||
bool bDump = true;
|
||||
switch (g_cvars.sys_dump_type)
|
||||
{
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
|
||||
#include <AzFramework/IO/FileOperations.h>
|
||||
#include <AzCore/IO/FileIO.h>
|
||||
#include <AzCore/IO/Path/Path.h>
|
||||
|
||||
#ifdef WIN32
|
||||
#include <time.h>
|
||||
@@ -88,7 +89,6 @@ CLog::CLog(ISystem* pSystem)
|
||||
|
||||
m_nMainThreadId = CryGetCurrentThreadId();
|
||||
|
||||
m_logFileHandle = AZ::IO::InvalidHandle;
|
||||
#if defined(KEEP_LOG_FILE_OPEN)
|
||||
m_bFirstLine = true;
|
||||
#endif
|
||||
@@ -162,35 +162,6 @@ void CLog::RegisterConsoleVariables()
|
||||
REGISTER_COMMAND("log_flush", &LogFlushFile, 0, "Flush the log file");
|
||||
#endif
|
||||
}
|
||||
/*
|
||||
//testbed
|
||||
{
|
||||
int iSave0 = m_pLogVerbosity->GetIVal();
|
||||
int iSave1 = m_pLogFileVerbosity->GetIVal();
|
||||
|
||||
for(int i=0;i<=4;++i)
|
||||
{
|
||||
m_pLogVerbosity->Set(i);
|
||||
m_pLogFileVerbosity->Set(i);
|
||||
|
||||
LogWithType(eAlways,"CLog selftest: Verbosity=%d FileVerbosity=%d",m_pLogVerbosity->GetIVal(),m_pLogFileVerbosity->GetIVal());
|
||||
LogWithType(eAlways,"--------------");
|
||||
|
||||
LogWithType(eError,"eError");
|
||||
LogWithType(eWarning,"eWarning");
|
||||
LogWithType(eMessage,"eMessage");
|
||||
LogWithType(eInput,"eInput");
|
||||
LogWithType(eInputResponse,"eInputResponse");
|
||||
|
||||
LogWarning("LogWarning()");
|
||||
LogError("LogError()");
|
||||
LogWithType(eAlways,"--------------");
|
||||
}
|
||||
|
||||
m_pLogVerbosity->Set(iSave0);
|
||||
m_pLogFileVerbosity->Set(iSave1);
|
||||
}
|
||||
*/
|
||||
#undef DEFAULT_VERBOSITY
|
||||
}
|
||||
|
||||
@@ -210,7 +181,7 @@ CLog::~CLog()
|
||||
|
||||
UnregisterConsoleVariables();
|
||||
|
||||
CloseLogFile(true);
|
||||
CloseLogFile();
|
||||
}
|
||||
|
||||
void CLog::UnregisterConsoleVariables()
|
||||
@@ -224,31 +195,36 @@ void CLog::UnregisterConsoleVariables()
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
void CLog::CloseLogFile([[maybe_unused]] bool forceClose)
|
||||
void CLog::CloseLogFile()
|
||||
{
|
||||
if (m_logFileHandle != AZ::IO::InvalidHandle)
|
||||
{
|
||||
AZ::IO::FileIOBase::GetDirectInstance()->Close(m_logFileHandle);
|
||||
m_logFileHandle = AZ::IO::InvalidHandle;
|
||||
}
|
||||
m_logFileHandle.Close();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
AZ::IO::HandleType CLog::OpenLogFile(const char* filename, const char* mode)
|
||||
bool CLog::OpenLogFile(const char* filename, int mode)
|
||||
{
|
||||
using namespace AZ::IO;
|
||||
|
||||
AZ_Assert(m_logFileHandle == AZ::IO::InvalidHandle, "Attempt to open log file when one is already open. This would lead to a handle leak.");
|
||||
|
||||
if ((!filename) || (filename[0] == 0))
|
||||
if (m_logFileHandle.IsOpen())
|
||||
{
|
||||
return m_logFileHandle;
|
||||
// Can only AZ_Assert if a file is open, otherwise the AZ_Assert
|
||||
// would eventually lead to OpenLogFile being opened up again
|
||||
AZ_Assert(false, "Attempt to open log file when one is already open. This would lead to a handle leak.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (filename == nullptr || filename[0] == '\0')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// it is assumed that @log@ points at the appropriate place (so for apple, to the user profile dir)
|
||||
AZ::IO::FileIOBase::GetDirectInstance()->Open(filename, AZ::IO::GetOpenModeFromStringMode(mode), m_logFileHandle);
|
||||
AZ::IO::FileIOBase* fileSystem = AZ::IO::FileIOBase::GetDirectInstance();
|
||||
if (AZ::IO::FixedMaxPath logFilePath; fileSystem->ReplaceAlias(logFilePath, filename))
|
||||
{
|
||||
logFilePath = logFilePath.LexicallyNormal();
|
||||
m_logFileHandle.Open(logFilePath.c_str(), mode);
|
||||
}
|
||||
|
||||
if (m_logFileHandle != AZ::IO::InvalidHandle)
|
||||
if (m_logFileHandle.IsOpen())
|
||||
{
|
||||
#if defined(KEEP_LOG_FILE_OPEN)
|
||||
m_bFirstLine = true;
|
||||
@@ -257,11 +233,11 @@ AZ::IO::HandleType CLog::OpenLogFile(const char* filename, const char* mode)
|
||||
else
|
||||
{
|
||||
#if defined(LINUX) || defined(APPLE)
|
||||
syslog(LOG_NOTICE, "Failed to open log file [%s], mode [%s]", filename, mode);
|
||||
syslog(LOG_NOTICE, "Failed to open log file [%s], mode [%d]", filename, mode);
|
||||
#endif
|
||||
}
|
||||
|
||||
return m_logFileHandle;
|
||||
return m_logFileHandle.IsOpen();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
@@ -1114,12 +1090,15 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
|
||||
|
||||
if (logToFile)
|
||||
{
|
||||
if (m_logFileHandle == AZ::IO::InvalidHandle)
|
||||
if (!m_logFileHandle.IsOpen())
|
||||
{
|
||||
OpenLogFile(m_szFilename, "w+t");
|
||||
constexpr auto openMode = AZ::IO::SystemFile::OpenMode::SF_OPEN_APPEND
|
||||
| AZ::IO::SystemFile::OpenMode::SF_OPEN_CREATE
|
||||
| AZ::IO::SystemFile::OpenMode::SF_OPEN_WRITE_ONLY;
|
||||
OpenLogFile(m_szFilename, openMode);
|
||||
}
|
||||
|
||||
if (m_logFileHandle != AZ::IO::InvalidHandle)
|
||||
if (m_logFileHandle.IsOpen())
|
||||
{
|
||||
#if defined(KEEP_LOG_FILE_OPEN)
|
||||
if (m_bFirstLine)
|
||||
@@ -1130,9 +1109,9 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
|
||||
if (bAdd)
|
||||
{
|
||||
// if adding to a prior line erase the \n at the end.
|
||||
AZ::IO::FileIOBase::GetDirectInstance()->Seek(m_logFileHandle, -2, AZ::IO::SeekType::SeekFromEnd);
|
||||
m_logFileHandle.Seek(-2, AZ::IO::SystemFile::SeekMode::SF_SEEK_END);
|
||||
}
|
||||
AZ::IO::FPutS(tempString.c_str(), m_logFileHandle);
|
||||
m_logFileHandle.Write(tempString.c_str(), tempString.size());
|
||||
#if !defined(KEEP_LOG_FILE_OPEN)
|
||||
CloseLogFile();
|
||||
#endif
|
||||
@@ -1383,6 +1362,23 @@ bool CLog::SetFileName(const char* fileNameOrAbsolutePath, bool backupLogs)
|
||||
|
||||
CreateBackupFile();
|
||||
|
||||
AZ::IO::FileIOBase* fileSystem = AZ::IO::FileIOBase::GetDirectInstance();
|
||||
AZ::IO::FixedMaxPath newLogFilePath;
|
||||
if (fileSystem->ReplaceAlias(newLogFilePath, m_szFilename))
|
||||
{
|
||||
newLogFilePath = newLogFilePath.LexicallyNormal();
|
||||
}
|
||||
if (m_logFileHandle.IsOpen() && newLogFilePath != m_logFileHandle.Name())
|
||||
{
|
||||
constexpr auto openMode = AZ::IO::SystemFile::OpenMode::SF_OPEN_APPEND
|
||||
| AZ::IO::SystemFile::OpenMode::SF_OPEN_CREATE
|
||||
| AZ::IO::SystemFile::OpenMode::SF_OPEN_WRITE_ONLY;
|
||||
if(AZ::IO::SystemFile newLogFile; newLogFile.Open(m_szFilename, openMode))
|
||||
{
|
||||
m_logFileHandle = AZStd::move(newLogFile);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1537,9 +1533,9 @@ const char* CLog::GetModuleFilter()
|
||||
void CLog::FlushAndClose()
|
||||
{
|
||||
#if defined(KEEP_LOG_FILE_OPEN)
|
||||
if (m_logFileHandle)
|
||||
if (m_logFileHandle.IsOpen())
|
||||
{
|
||||
CloseLogFile(true);
|
||||
CloseLogFile();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -137,8 +137,8 @@ private: // -------------------------------------------------------------------
|
||||
void LogStringToConsole(const char* szString, ELogType logType, bool bAdd) {}
|
||||
#endif // !defined(EXCLUDE_NORMAL_LOG)
|
||||
|
||||
AZ::IO::HandleType OpenLogFile(const char* filename, const char* mode);
|
||||
void CloseLogFile(bool force = false);
|
||||
bool OpenLogFile(const char* filename, int mode);
|
||||
void CloseLogFile();
|
||||
|
||||
// will format the message into m_szTemp
|
||||
void FormatMessage(const char* szCommand, ...) PRINTF_PARAMS(2, 3);
|
||||
@@ -152,15 +152,11 @@ private: // -------------------------------------------------------------------
|
||||
virtual const char* GetAssetScopeString();
|
||||
#endif
|
||||
|
||||
ISystem* m_pSystem; //
|
||||
float m_fLastLoadingUpdateTime; // for non-frequent streamingEngine update
|
||||
//char m_szTemp[MAX_TEMP_LENGTH_SIZE]; //
|
||||
char m_szFilename[MAX_FILENAME_SIZE]; // can be with path
|
||||
mutable char m_sBackupFilename[MAX_FILENAME_SIZE]; // can be with path
|
||||
AZ::IO::HandleType m_logFileHandle;
|
||||
CryStackStringT<char, 32> m_LogMode; //mode m_pLogFile has been opened with
|
||||
AZ::IO::HandleType m_errFileHandle;
|
||||
int m_nErrCount;
|
||||
ISystem* m_pSystem; //
|
||||
float m_fLastLoadingUpdateTime; // for non-frequent streamingEngine update
|
||||
char m_szFilename[MAX_FILENAME_SIZE]; // can be with path
|
||||
mutable char m_sBackupFilename[MAX_FILENAME_SIZE]; // can be with path
|
||||
AZ::IO::SystemFile m_logFileHandle;
|
||||
|
||||
bool m_backupLogs;
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
|
||||
}
|
||||
if (pSystem && !pSystem->IsQuitting())
|
||||
{
|
||||
LRESULT result;
|
||||
LRESULT result = 0;
|
||||
bool bAny = false;
|
||||
for (std::vector<IWindowMessageHandler*>::const_iterator it = pSystem->m_windowMessageHandlers.begin(); it != pSystem->m_windowMessageHandlers.end(); ++it)
|
||||
{
|
||||
|
||||
@@ -634,7 +634,7 @@ ICVar* CSystem::attachVariable (const char* szVarName, int* pContainer, const ch
|
||||
IConsole* pConsole = GetIConsole();
|
||||
|
||||
ICVar* pOldVar = pConsole->GetCVar (szVarName);
|
||||
int nDefault;
|
||||
int nDefault = 0;
|
||||
if (pOldVar)
|
||||
{
|
||||
nDefault = pOldVar->GetIVal();
|
||||
@@ -1208,7 +1208,7 @@ bool CSystem::Init(const SSystemInitParams& startupParams)
|
||||
{
|
||||
assetPlatform = AzFramework::OSPlatformToDefaultAssetPlatform(AZ_TRAIT_OS_PLATFORM_CODENAME);
|
||||
AZ_Warning(AZ_TRACE_SYSTEM_WINDOW, false, R"(A valid asset platform is missing in "%s/assets" key in the SettingsRegistry.)""\n"
|
||||
R"(This typically done by setting he "assets" field in the bootstrap.cfg for within a .setreg file)""\n"
|
||||
R"(This typically done by setting the "assets" field within a .setreg file)""\n"
|
||||
R"(A fallback of %s will be used.)",
|
||||
AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey,
|
||||
assetPlatform.c_str());
|
||||
@@ -2017,8 +2017,8 @@ void CSystem::CreateSystemVars()
|
||||
REGISTER_CVAR2("sys_streaming_in_blocks", &g_cvars.sys_streaming_in_blocks, 1, VF_NULL,
|
||||
"Streaming of large files happens in blocks");
|
||||
|
||||
#if (defined(WIN32) || defined(WIN64)) && !defined(_RELEASE)
|
||||
REGISTER_CVAR2("sys_float_exceptions", &g_cvars.sys_float_exceptions, 3, 0, "Use or not use floating point exceptions.");
|
||||
#if (defined(WIN32) || defined(WIN64)) && defined(_DEBUG)
|
||||
REGISTER_CVAR2("sys_float_exceptions", &g_cvars.sys_float_exceptions, 2, 0, "Use or not use floating point exceptions.");
|
||||
#else // Float exceptions by default disabled for console builds.
|
||||
REGISTER_CVAR2("sys_float_exceptions", &g_cvars.sys_float_exceptions, 0, 0, "Use or not use floating point exceptions.");
|
||||
#endif
|
||||
|
||||
@@ -77,6 +77,27 @@
|
||||
#endif // defined(AZ_ENABLE_DEBUG_TOOLS)
|
||||
|
||||
#include <AzCore/Module/Environment.h>
|
||||
#include <AzCore/std/string/conversions.h>
|
||||
|
||||
static void PrintEntityName(const AZ::ConsoleCommandContainer& arguments)
|
||||
{
|
||||
if (arguments.empty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const auto entityIdStr = AZStd::string(arguments.front());
|
||||
const auto entityIdValue = AZStd::stoull(entityIdStr);
|
||||
|
||||
AZStd::string entityName;
|
||||
AZ::ComponentApplicationBus::BroadcastResult(
|
||||
entityName, &AZ::ComponentApplicationBus::Events::GetEntityName, AZ::EntityId(entityIdValue));
|
||||
|
||||
AZ_Printf("Entity Debug", "EntityId: %" PRIu64 ", Entity Name: %s", entityIdValue, entityName.c_str());
|
||||
}
|
||||
|
||||
AZ_CONSOLEFREEFUNC(
|
||||
PrintEntityName, AZ::ConsoleFunctorFlags::Null, "Parameter: EntityId value, Prints the name of the entity to the console");
|
||||
|
||||
namespace AZ
|
||||
{
|
||||
|
||||
@@ -30,7 +30,7 @@ namespace Platform
|
||||
|
||||
using FileHandleType = SystemFile::FileHandleType;
|
||||
|
||||
void Seek(FileHandleType handle, const SystemFile* systemFile, SizeType offset, SystemFile::SeekMode mode);
|
||||
void Seek(FileHandleType handle, const SystemFile* systemFile, SystemFile::SeekSizeType offset, SystemFile::SeekMode mode);
|
||||
SystemFile::SizeType Tell(FileHandleType handle, const SystemFile* systemFile);
|
||||
bool Eof(FileHandleType handle, const SystemFile* systemFile);
|
||||
AZ::u64 ModificationTime(FileHandleType handle, const SystemFile* systemFile);
|
||||
@@ -68,9 +68,8 @@ void SystemFile::CreatePath(const char* fileName)
|
||||
}
|
||||
|
||||
SystemFile::SystemFile()
|
||||
: m_handle{ AZ_TRAIT_SYSTEMFILE_INVALID_HANDLE }
|
||||
{
|
||||
m_fileName[0] = '\0';
|
||||
m_handle = AZ_TRAIT_SYSTEMFILE_INVALID_HANDLE;
|
||||
}
|
||||
|
||||
SystemFile::~SystemFile()
|
||||
@@ -81,6 +80,25 @@ SystemFile::~SystemFile()
|
||||
}
|
||||
}
|
||||
|
||||
SystemFile::SystemFile(SystemFile&& other)
|
||||
: SystemFile{}
|
||||
{
|
||||
AZStd::swap(m_fileName, other.m_fileName);
|
||||
AZStd::swap(m_handle, other.m_handle);
|
||||
}
|
||||
|
||||
SystemFile& SystemFile::operator=(SystemFile&& other)
|
||||
{
|
||||
// Close the current file and take over the SystemFile handle and filename
|
||||
Close();
|
||||
m_fileName = AZStd::move(other.m_fileName);
|
||||
m_handle = AZStd::move(other.m_handle);
|
||||
other.m_fileName = {};
|
||||
other.m_handle = AZ_TRAIT_SYSTEMFILE_INVALID_HANDLE;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool SystemFile::Open(const char* fileName, int mode, int platformFlags)
|
||||
{
|
||||
AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Open - %s", fileName);
|
||||
@@ -88,42 +106,42 @@ bool SystemFile::Open(const char* fileName, int mode, int platformFlags)
|
||||
|
||||
if (fileName) // If we reopen the file we are allowed to have NULL file name
|
||||
{
|
||||
if (strlen(fileName) > AZ_ARRAY_SIZE(m_fileName) - 1)
|
||||
if (strlen(fileName) > m_fileName.max_size())
|
||||
{
|
||||
EBUS_EVENT(FileIOEventBus, OnError, this, nullptr, 0);
|
||||
return false;
|
||||
}
|
||||
|
||||
// store the filename
|
||||
azsnprintf(m_fileName, AZ_ARRAY_SIZE(m_fileName), "%s", fileName);
|
||||
m_fileName = fileName;
|
||||
}
|
||||
|
||||
if (FileIOBus::HasHandlers())
|
||||
{
|
||||
bool isOpen = false;
|
||||
bool isHandled = false;
|
||||
EBUS_EVENT_RESULT(isHandled, FileIOBus, OnOpen, *this, m_fileName, mode, platformFlags, isOpen);
|
||||
EBUS_EVENT_RESULT(isHandled, FileIOBus, OnOpen, *this, m_fileName.c_str(), mode, platformFlags, isOpen);
|
||||
if (isHandled)
|
||||
{
|
||||
return isOpen;
|
||||
}
|
||||
}
|
||||
|
||||
AZ_Assert(!IsOpen(), "This file (%s) is already open!", m_fileName);
|
||||
AZ_Assert(!IsOpen(), "This file (%s) is already open!", m_fileName.c_str());
|
||||
|
||||
return PlatformOpen(mode, platformFlags);
|
||||
}
|
||||
|
||||
bool SystemFile::ReOpen(int mode, int platformFlags)
|
||||
{
|
||||
AZ_Assert(strlen(m_fileName) > 0, "Missing filename. You must call open first!");
|
||||
AZ_Assert(!m_fileName.empty(), "Missing filename. You must call open first!");
|
||||
return Open(0, mode, platformFlags);
|
||||
}
|
||||
|
||||
void SystemFile::Close()
|
||||
{
|
||||
AZ_PROFILE_INTERVAL_SCOPED(AZ::Debug::ProfileCategory::AzCore, this, "SystemFile::Close - %s", m_fileName);
|
||||
AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Close - %s", m_fileName);
|
||||
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())
|
||||
{
|
||||
@@ -138,9 +156,9 @@ void SystemFile::Close()
|
||||
PlatformClose();
|
||||
}
|
||||
|
||||
void SystemFile::Seek(SizeType offset, SeekMode mode)
|
||||
void SystemFile::Seek(SeekSizeType offset, SeekMode mode)
|
||||
{
|
||||
AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Seek - %s:%i", m_fileName, offset);
|
||||
AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Seek - %s:%i", m_fileName.c_str(), offset);
|
||||
|
||||
if (FileIOBus::HasHandlers())
|
||||
{
|
||||
@@ -167,15 +185,15 @@ bool SystemFile::Eof()
|
||||
|
||||
AZ::u64 SystemFile::ModificationTime()
|
||||
{
|
||||
AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::ModTime - %s", m_fileName);
|
||||
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, byteSize);
|
||||
AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Read - %s:%i", m_fileName, byteSize);
|
||||
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())
|
||||
{
|
||||
@@ -193,8 +211,8 @@ 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, byteSize);
|
||||
AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Write - %s:%i", m_fileName, 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())
|
||||
{
|
||||
@@ -212,14 +230,14 @@ 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);
|
||||
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);
|
||||
AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::Length - %s", m_fileName.c_str());
|
||||
|
||||
return Platform::Length(m_handle, this);
|
||||
}
|
||||
@@ -379,9 +397,9 @@ namespace
|
||||
HasPosixEnumOption(PermissionModeFlags::Write);
|
||||
|
||||
#undef HasPosixEnumOption
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
FileDescriptorRedirector::FileDescriptorRedirector(int sourceFileDescriptor)
|
||||
: m_sourceFileDescriptor(sourceFileDescriptor)
|
||||
{
|
||||
|
||||
@@ -12,10 +12,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <AzCore/base.h>
|
||||
#include <AzCore/std/function/function_fwd.h>
|
||||
#include <AzCore/std/string/string.h>
|
||||
|
||||
#include <AzCore/IO/Path/Path_fwd.h>
|
||||
#include <AzCore/IO/SystemFile_Platform.h>
|
||||
#include <AzCore/std/function/function_fwd.h>
|
||||
#include <AzCore/std/string/fixed_string.h>
|
||||
|
||||
// Establish a consistent size that works across platforms. It's actually larger than this
|
||||
// on platforms we support, but this is a good least common denominator
|
||||
@@ -51,11 +52,15 @@ namespace AZ
|
||||
};
|
||||
|
||||
using SizeType = AZ::IO::Internal::SizeType;
|
||||
using SeekSizeType = AZ::IO::Internal::SeekSizeType;
|
||||
using FileHandleType = AZ::IO::Internal::FileHandleType;
|
||||
|
||||
SystemFile();
|
||||
~SystemFile();
|
||||
|
||||
SystemFile(SystemFile&&);
|
||||
SystemFile& operator=(SystemFile&&);
|
||||
|
||||
/**
|
||||
* Opens a file.
|
||||
* \param fileName full file name including path
|
||||
@@ -69,7 +74,7 @@ namespace AZ
|
||||
/// Closes a file, if file already close it has no effect.
|
||||
void Close();
|
||||
/// Seek in current file.
|
||||
void Seek(SizeType offset, SeekMode mode);
|
||||
void Seek(SeekSizeType offset, SeekMode mode);
|
||||
/// Get the cursor position in the current file.
|
||||
SizeType Tell();
|
||||
/// Is the cursor at the end of the file?
|
||||
@@ -87,7 +92,7 @@ namespace AZ
|
||||
/// Return disc offset if possible, otherwise 0
|
||||
SizeType DiskOffset() const;
|
||||
/// Return file name or NULL if file is not open.
|
||||
AZ_FORCE_INLINE const char* Name() const { return m_fileName; }
|
||||
AZ_FORCE_INLINE const char* Name() const { return m_fileName.c_str(); }
|
||||
bool IsOpen() const;
|
||||
|
||||
/// Return native handle to the file.
|
||||
@@ -124,12 +129,12 @@ namespace AZ
|
||||
|
||||
private:
|
||||
static void CreatePath(const char * fileName);
|
||||
|
||||
|
||||
bool PlatformOpen(int mode, int platformFlags);
|
||||
void PlatformClose();
|
||||
|
||||
FileHandleType m_handle;
|
||||
char m_fileName[AZ_MAX_PATH_LEN];
|
||||
|
||||
FileHandleType m_handle;
|
||||
AZ::IO::FixedMaxPathString m_fileName;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -127,13 +127,14 @@ namespace AZ
|
||||
*/
|
||||
class EditContext
|
||||
{
|
||||
public:
|
||||
/// @cond EXCLUDE_DOCS
|
||||
class ClassBuilder;
|
||||
class EnumBuilder;
|
||||
using ClassInfo = ClassBuilder; ///< @deprecated Use EditContext::ClassBuilder
|
||||
using EnumInfo = EnumBuilder; ///< @deprecated Use EditContext::EnumBuilder
|
||||
/// @endcond
|
||||
public:
|
||||
|
||||
AZ_CLASS_ALLOCATOR(EditContext, SystemAllocator, 0);
|
||||
|
||||
/**
|
||||
@@ -186,6 +187,7 @@ namespace AZ
|
||||
* look at the unit tests and example to see use cases.
|
||||
*
|
||||
*/
|
||||
public:
|
||||
class ClassBuilder
|
||||
{
|
||||
friend EditContext;
|
||||
@@ -399,6 +401,7 @@ namespace AZ
|
||||
EnumBuilder* Value(const char* name, E value);
|
||||
};
|
||||
|
||||
private:
|
||||
typedef AZStd::list<Edit::ClassData> ClassDataListType;
|
||||
typedef AZStd::unordered_map<AZ::Uuid, Edit::ElementData> EnumDataMapType;
|
||||
|
||||
|
||||
@@ -28,7 +28,13 @@ namespace AZ
|
||||
{
|
||||
namespace IdUtils
|
||||
{
|
||||
template<typename IdType>
|
||||
/**
|
||||
* \param AllowDuplicates - If true allows the same id to be registered multiple times,
|
||||
with the newer value overwriting the stored value. If false, duplicates are not allowed and
|
||||
the first stored value is kept.The default is false.
|
||||
*/
|
||||
|
||||
template<typename IdType, bool AllowDuplicates = false>
|
||||
struct Remapper
|
||||
{
|
||||
/**
|
||||
@@ -138,14 +144,18 @@ namespace AZ
|
||||
* \param context - The serialize context for enumerating the @classPtr elements
|
||||
*/
|
||||
template<typename T, typename MapType>
|
||||
static void GenerateNewIdsAndFixRefs(T* object, MapType& newIdMap, AZ::SerializeContext* context = nullptr)
|
||||
static void GenerateNewIdsAndFixRefs(
|
||||
T* object, MapType& newIdMap, AZ::SerializeContext* context = nullptr)
|
||||
{
|
||||
if (!context)
|
||||
{
|
||||
AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationRequests::GetSerializeContext);
|
||||
if (!context)
|
||||
{
|
||||
AZ_Error("Serialization", false, "No serialize context provided! Failed to get component application default serialize context! ComponentApp is not started or input serialize context should not be null!");
|
||||
AZ_Error(
|
||||
"Serialization", false,
|
||||
"No serialize context provided! Failed to get component application default serialize context! ComponentApp is "
|
||||
"not started or input serialize context should not be null!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -156,8 +166,16 @@ namespace AZ
|
||||
{
|
||||
if (idGenerator)
|
||||
{
|
||||
auto it = newIdMap.emplace(originalId, idGenerator());
|
||||
return it.first->second;
|
||||
if constexpr(AllowDuplicates)
|
||||
{
|
||||
auto it = newIdMap.insert_or_assign(originalId, idGenerator());
|
||||
return it.first->second;
|
||||
}
|
||||
else
|
||||
{
|
||||
auto it = newIdMap.emplace(originalId, idGenerator());
|
||||
return it.first->second;
|
||||
}
|
||||
}
|
||||
return originalId;
|
||||
}
|
||||
|
||||
@@ -30,8 +30,10 @@ namespace AZ
|
||||
bool m_isModifiedContainer;
|
||||
};
|
||||
|
||||
template<typename IdType>
|
||||
unsigned int Remapper<IdType>::RemapIds(void* classPtr, const AZ::Uuid& classUuid, const typename Remapper<IdType>::IdMapper& mapper, AZ::SerializeContext* context, bool replaceId)
|
||||
template<typename IdType, bool AllowDuplicates>
|
||||
unsigned int Remapper<IdType, AllowDuplicates>::RemapIds(
|
||||
void* classPtr, const AZ::Uuid& classUuid, const typename Remapper<IdType, AllowDuplicates>::IdMapper& mapper,
|
||||
AZ::SerializeContext* context, bool replaceId)
|
||||
{
|
||||
if (!context)
|
||||
{
|
||||
@@ -152,16 +154,18 @@ namespace AZ
|
||||
return replaced;
|
||||
}
|
||||
|
||||
template<typename IdType>
|
||||
unsigned int Remapper<IdType>::ReplaceIdsAndIdRefs(void* classPtr, const AZ::Uuid& classUuid, const IdMapper& mapper, AZ::SerializeContext* context /*= nullptr*/)
|
||||
template<typename IdType, bool AllowDuplicates>
|
||||
unsigned int Remapper<IdType, AllowDuplicates>::ReplaceIdsAndIdRefs(void* classPtr, const AZ::Uuid& classUuid, const IdMapper& mapper, AZ::SerializeContext* context /*= nullptr*/)
|
||||
{
|
||||
unsigned int replaced = RemapIds(classPtr, classUuid, mapper, context, true);
|
||||
replaced += RemapIds(classPtr, classUuid, mapper, context, false);
|
||||
return replaced;
|
||||
}
|
||||
|
||||
template<typename IdType>
|
||||
unsigned int Remapper<IdType>::RemapIdsAndIdRefs(void* classPtr, const AZ::Uuid& classUuid, const typename Remapper<IdType>::IdReplacer& mapper, AZ::SerializeContext* context)
|
||||
template<typename IdType, bool AllowDuplicates>
|
||||
unsigned int Remapper<IdType, AllowDuplicates>::RemapIdsAndIdRefs(
|
||||
void* classPtr, const AZ::Uuid& classUuid, const typename Remapper<IdType, AllowDuplicates>::IdReplacer& mapper,
|
||||
AZ::SerializeContext* context)
|
||||
{
|
||||
if (!context)
|
||||
{
|
||||
|
||||
@@ -101,6 +101,9 @@ namespace AZ
|
||||
class SerializeContext
|
||||
: public ReflectContext
|
||||
{
|
||||
static const unsigned int VersionClassDeprecated = (unsigned int)-1;
|
||||
|
||||
public:
|
||||
/// @cond EXCLUDE_DOCS
|
||||
friend class EditContext;
|
||||
class ClassBuilder;
|
||||
@@ -108,9 +111,6 @@ namespace AZ
|
||||
/// @endcond
|
||||
class EnumBuilder;
|
||||
|
||||
static const unsigned int VersionClassDeprecated = (unsigned int)-1;
|
||||
|
||||
public:
|
||||
class ClassData;
|
||||
struct EnumerateInstanceCallContext;
|
||||
struct ClassElement;
|
||||
@@ -1131,6 +1131,7 @@ namespace AZ
|
||||
* ->Version(3,&MyVersionConverter)
|
||||
* ->Field("data",&MyStruct::m_data);
|
||||
*/
|
||||
public:
|
||||
class ClassBuilder
|
||||
{
|
||||
friend class SerializeContext;
|
||||
@@ -1330,7 +1331,8 @@ namespace AZ
|
||||
AZStd::vector<AttributeSharedPair, AZStdFunctorAllocator>* m_currentAttributes = nullptr;
|
||||
};
|
||||
|
||||
EditContext* m_editContext; ///< Pointer to optional edit context.
|
||||
private:
|
||||
EditContext* m_editContext; ///< Pointer to optional edit context.
|
||||
UuidToClassMap m_uuidMap; ///< Map for all class in this serialize context
|
||||
AZStd::unordered_multimap<AZ::Crc32, AZ::Uuid> m_classNameToUuid; /// Map all class names to their uuid
|
||||
AZStd::unordered_multimap<Uuid, GenericClassInfo*> m_uuidGenericMap; ///< Uuid to ClassData map of reflected classes with GenericTypeInfo
|
||||
|
||||
@@ -641,6 +641,8 @@ namespace AZ::SettingsRegistryMergeUtils
|
||||
}
|
||||
else
|
||||
{
|
||||
// Set the default ProjectUserPath to the <engine-root>/user directory
|
||||
registry.Set(FilePathKey_ProjectUserPath, (engineRoot / "user").LexicallyNormal().Native());
|
||||
AZ_TracePrintf("SettingsRegistryMergeUtils",
|
||||
R"(Project path isn't set in the Settings Registry at "%.*s". Project-related filepaths will not be set)" "\n",
|
||||
aznumeric_cast<int>(projectPathKey.size()), projectPathKey.data());
|
||||
|
||||
@@ -971,6 +971,10 @@ namespace AZ
|
||||
*/
|
||||
void RestoreCachedInstances();
|
||||
|
||||
/// Returns data flags for use when instantiating an instance of this slice.
|
||||
/// These data flags include those harvested from the entire slice ancestry.
|
||||
const DataFlagsPerEntity& GetDataFlagsForInstances() const;
|
||||
|
||||
protected:
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
@@ -1004,9 +1008,6 @@ namespace AZ
|
||||
DataFlagsPerEntity* GetCorrectBundleOfDataFlags(EntityId entityId);
|
||||
const DataFlagsPerEntity* GetCorrectBundleOfDataFlags(EntityId entityId) const;
|
||||
|
||||
/// Returns data flags for use when instantiating an instance of this slice.
|
||||
/// These data flags include those harvested from the entire slice ancestry.
|
||||
const DataFlagsPerEntity& GetDataFlagsForInstances() const;
|
||||
void BuildDataFlagsForInstances();
|
||||
|
||||
/**
|
||||
|
||||
@@ -101,7 +101,7 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags)
|
||||
createPath = (mode & SF_OPEN_CREATE_PATH) == SF_OPEN_CREATE_PATH;
|
||||
}
|
||||
|
||||
bool isApkFile = AZ::Android::Utils::IsApkPath(m_fileName);
|
||||
bool isApkFile = AZ::Android::Utils::IsApkPath(m_fileName.c_str());
|
||||
|
||||
if (createPath)
|
||||
{
|
||||
@@ -111,19 +111,19 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags)
|
||||
return false;
|
||||
}
|
||||
|
||||
CreatePath(m_fileName);
|
||||
CreatePath(m_fileName.c_str());
|
||||
}
|
||||
|
||||
int errorCode = 0;
|
||||
if (isApkFile)
|
||||
{
|
||||
AZ::u64 size = 0;
|
||||
m_handle = AZ::Android::APKFileHandler::Open(m_fileName, openMode, size);
|
||||
m_handle = AZ::Android::APKFileHandler::Open(m_fileName.c_str(), openMode, size);
|
||||
errorCode = EACCES; // general error when a file can't be opened from inside the APK
|
||||
}
|
||||
else
|
||||
{
|
||||
m_handle = fopen(m_fileName, openMode);
|
||||
m_handle = fopen(m_fileName.c_str(), openMode);
|
||||
errorCode = errno;
|
||||
}
|
||||
|
||||
@@ -233,7 +233,7 @@ namespace Platform
|
||||
}
|
||||
}
|
||||
|
||||
void Seek(FileHandleType handle, const SystemFile* systemFile, SizeType offset, SystemFile::SeekMode mode)
|
||||
void Seek(FileHandleType handle, const SystemFile* systemFile, SystemFile::SeekSizeType offset, SystemFile::SeekMode mode)
|
||||
{
|
||||
if (handle != PlatformSpecificInvalidHandle)
|
||||
{
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
#include <cstdio>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <AzCore/std/typetraits/underlying_type.h>
|
||||
|
||||
namespace AZ
|
||||
{
|
||||
@@ -23,6 +26,7 @@ namespace AZ
|
||||
namespace Internal
|
||||
{
|
||||
using SizeType = AZ::u64;
|
||||
using SeekSizeType = AZ::s64;
|
||||
using FileHandleType = FILE*;
|
||||
}
|
||||
|
||||
@@ -37,7 +41,7 @@ namespace AZ
|
||||
#else
|
||||
Temporary = 0, // (Not applicable for this platform) Applies only when used with CREAT. Creates a file as temporary; the file is deleted when the last file descriptor is closed. PermissionMode equired when CREAT is specified.
|
||||
#endif
|
||||
Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists.
|
||||
Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists.
|
||||
Truncate = O_TRUNC, // Opens a file and truncates it to zero length; the file must have write permission. Cannot be specified with RDONLY.
|
||||
// Note: The TRUNC flag destroys the contents of the specified file.
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@
|
||||
#include <sys/syslimits.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <AzCore/std/typetraits/underlying_type.h>
|
||||
|
||||
namespace AZ
|
||||
{
|
||||
@@ -22,9 +25,10 @@ namespace AZ
|
||||
namespace Internal
|
||||
{
|
||||
using SizeType = AZ::u64;
|
||||
using SeekSizeType = AZ::s64;
|
||||
using FileHandleType = int;
|
||||
}
|
||||
|
||||
|
||||
namespace PosixInternal
|
||||
{
|
||||
enum class OpenFlags : int
|
||||
@@ -36,7 +40,7 @@ namespace AZ
|
||||
#else
|
||||
Temporary = 0, // (Not applicable for this platform) Applies only when used with CREAT. Creates a file as temporary; the file is deleted when the last file descriptor is closed. PermissionMode equired when CREAT is specified.
|
||||
#endif
|
||||
Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists.
|
||||
Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists.
|
||||
Truncate = O_TRUNC, // Opens a file and truncates it to zero length; the file must have write permission. Cannot be specified with RDONLY.
|
||||
// Note: The TRUNC flag destroys the contents of the specified file.
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <AzCore/std/typetraits/underlying_type.h>
|
||||
|
||||
namespace AZ
|
||||
{
|
||||
@@ -21,6 +24,7 @@ namespace AZ
|
||||
namespace Internal
|
||||
{
|
||||
using SizeType = AZ::u64;
|
||||
using SeekSizeType = AZ::s64;
|
||||
using FileHandleType = int;
|
||||
}
|
||||
|
||||
@@ -35,7 +39,7 @@ namespace AZ
|
||||
#else
|
||||
Temporary = 0, // (Not applicable for this platform) Applies only when used with CREAT. Creates a file as temporary; the file is deleted when the last file descriptor is closed. PermissionMode equired when CREAT is specified.
|
||||
#endif
|
||||
Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists.
|
||||
Exclusive = O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists.
|
||||
Truncate = O_TRUNC, // Opens a file and truncates it to zero length; the file must have write permission. Cannot be specified with RDONLY.
|
||||
// Note: The TRUNC flag destroys the contents of the specified file.
|
||||
|
||||
|
||||
+16
-7
@@ -13,9 +13,10 @@
|
||||
#include <AzCore/Module/DynamicModuleHandle.h>
|
||||
#include <AzCore/IO/Path/Path.h>
|
||||
#include <AzCore/IO/SystemFile.h>
|
||||
|
||||
#include <AzCore/Memory/OSAllocator.h>
|
||||
#include <AzCore/Settings/SettingsRegistryMergeUtils.h>
|
||||
#include <AzCore/Utils/Utils.h>
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <libgen.h>
|
||||
|
||||
@@ -61,10 +62,11 @@ namespace AZ
|
||||
// If it doesn't attempt to append the path to the executable path
|
||||
if (!AZ::IO::SystemFile::Exists(fullFilePath.c_str()))
|
||||
{
|
||||
auto candidatePath = Platform::GetModulePath() / fullFilePath;
|
||||
AZ::IO::FixedMaxPath candidatePath = Platform::GetModulePath() / fullFilePath;
|
||||
if (AZ::IO::SystemFile::Exists(candidatePath.c_str()))
|
||||
{
|
||||
fullFilePath = candidatePath;
|
||||
m_fileName.assign(candidatePath.Native().c_str(), candidatePath.Native().size());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,19 +76,26 @@ namespace AZ
|
||||
{
|
||||
if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
|
||||
{
|
||||
if(AZ::IO::FixedMaxPath projectModulePath;
|
||||
if (AZ::IO::FixedMaxPath projectModulePath;
|
||||
settingsRegistry->Get(projectModulePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectConfigurationBinPath))
|
||||
{
|
||||
projectModulePath /= fullFilePath;
|
||||
if (AZ::IO::SystemFile::Exists(projectModulePath.c_str()))
|
||||
{
|
||||
fullFilePath = projectModulePath;
|
||||
m_fileName.assign(projectModulePath.c_str(), projectModulePath.Native().size());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m_fileName = AZStd::string_view{fullFilePath.Native()};
|
||||
else
|
||||
{
|
||||
// The module does exist (in 'cwd'), but still needs to be an absolute path for the module to be loaded.
|
||||
AZStd::optional<AZ::IO::FixedMaxPathString> absPathOptional = AZ::Utils::ConvertToAbsolutePath(m_fileName);
|
||||
if (absPathOptional.has_value())
|
||||
{
|
||||
m_fileName.assign(absPathOptional->c_str(), absPathOptional->size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
~DynamicModuleHandleUnixLike() override
|
||||
|
||||
+3
-3
@@ -86,9 +86,9 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags)
|
||||
|
||||
if (createPath)
|
||||
{
|
||||
CreatePath(m_fileName);
|
||||
CreatePath(m_fileName.c_str());
|
||||
}
|
||||
m_handle = open(m_fileName, desiredAccess, permissions);
|
||||
m_handle = open(m_fileName.c_str(), desiredAccess, permissions);
|
||||
|
||||
if (m_handle == PlatformSpecificInvalidHandle)
|
||||
{
|
||||
@@ -119,7 +119,7 @@ namespace Platform
|
||||
{
|
||||
using FileHandleType = AZ::IO::SystemFile::FileHandleType;
|
||||
|
||||
void Seek(FileHandleType handle, const SystemFile* systemFile, SizeType offset, SystemFile::SeekMode mode)
|
||||
void Seek(FileHandleType handle, const SystemFile* systemFile, SystemFile::SeekSizeType offset, SystemFile::SeekMode mode)
|
||||
{
|
||||
if (handle != PlatformSpecificInvalidHandle)
|
||||
{
|
||||
|
||||
@@ -209,19 +209,19 @@ bool SystemFile::PlatformOpen(int mode, int platformFlags)
|
||||
|
||||
if (createPath)
|
||||
{
|
||||
CreatePath(m_fileName);
|
||||
CreatePath(m_fileName.c_str());
|
||||
}
|
||||
|
||||
# ifdef _UNICODE
|
||||
wchar_t fileNameW[AZ_MAX_PATH_LEN];
|
||||
size_t numCharsConverted;
|
||||
m_handle = INVALID_HANDLE_VALUE;
|
||||
if (mbstowcs_s(&numCharsConverted, fileNameW, m_fileName, AZ_ARRAY_SIZE(fileNameW) - 1) == 0)
|
||||
if (mbstowcs_s(&numCharsConverted, fileNameW, m_fileName.c_str(), AZ_ARRAY_SIZE(fileNameW) - 1) == 0)
|
||||
{
|
||||
m_handle = CreateFileW(fileNameW, dwDesiredAccess, dwShareMode, 0, dwCreationDisposition, dwFlagsAndAttributes, 0);
|
||||
}
|
||||
# else //!_UNICODE
|
||||
m_handle = CreateFile(m_fileName, dwDesiredAccess, dwShareMode, 0, dwCreationDisposition, dwFlagsAndAttributes, 0);
|
||||
m_handle = CreateFile(m_fileName.c_str(), dwDesiredAccess, dwShareMode, 0, dwCreationDisposition, dwFlagsAndAttributes, 0);
|
||||
# endif // !_UNICODE
|
||||
|
||||
if (m_handle == INVALID_HANDLE_VALUE)
|
||||
@@ -261,7 +261,7 @@ namespace Platform
|
||||
{
|
||||
using FileHandleType = AZ::IO::SystemFile::FileHandleType;
|
||||
|
||||
void Seek(FileHandleType handle, const SystemFile* systemFile, SizeType offset, SystemFile::SeekMode mode)
|
||||
void Seek(FileHandleType handle, const SystemFile* systemFile, SystemFile::SeekSizeType offset, SystemFile::SeekMode mode)
|
||||
{
|
||||
if (handle != PlatformSpecificInvalidHandle)
|
||||
{
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <corecrt_io.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <AzCore/std/typetraits/underlying_type.h>
|
||||
|
||||
namespace AZ
|
||||
{
|
||||
@@ -21,6 +24,7 @@ namespace AZ
|
||||
namespace Internal
|
||||
{
|
||||
using SizeType = AZ::u64;
|
||||
using SeekSizeType = AZ::s64;
|
||||
using FileHandleType = void*;
|
||||
}
|
||||
|
||||
@@ -31,7 +35,7 @@ namespace AZ
|
||||
Append = _O_APPEND, // Moves the file pointer to the end of the file before every write operation.
|
||||
Create = _O_CREAT, // Creates a file and opens it for writing. Has no effect if the file specified by filename exists. PermissionMode is required.
|
||||
Temporary = _O_TEMPORARY, // Applies only when used with CREAT. Creates a file as temporary; the file is deleted when the last file descriptor is closed. PermissionMode equired when CREAT is specified.
|
||||
Exclusive = _O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists.
|
||||
Exclusive = _O_EXCL, // Applies only when used with CREAT. Returns an error value if a file specified by filename exists.
|
||||
Truncate = _O_TRUNC, // Opens a file and truncates it to zero length; the file must have write permission. Cannot be specified with RDONLY.
|
||||
// Note: The TRUNC flag destroys the contents of the specified file.
|
||||
|
||||
|
||||
+13
-3
@@ -24,9 +24,9 @@ namespace AZ
|
||||
: public DynamicModuleHandle
|
||||
{
|
||||
public:
|
||||
AZ_CLASS_ALLOCATOR(DynamicModuleHandleWindows, OSAllocator, 0)
|
||||
AZ_CLASS_ALLOCATOR(DynamicModuleHandleWindows, OSAllocator, 0);
|
||||
|
||||
DynamicModuleHandleWindows(const char* fullFileName)
|
||||
DynamicModuleHandleWindows(const char* fullFileName)
|
||||
: DynamicModuleHandle(fullFileName)
|
||||
, m_handle(nullptr)
|
||||
{
|
||||
@@ -52,6 +52,7 @@ namespace AZ
|
||||
if (AZ::IO::SystemFile::Exists(candidatePath.c_str()))
|
||||
{
|
||||
m_fileName.assign(candidatePath.Native().c_str(), candidatePath.Native().size());
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,7 +66,7 @@ namespace AZ
|
||||
// Therefore an existence check is needed
|
||||
if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
|
||||
{
|
||||
if(AZ::IO::FixedMaxPath projectModulePath;
|
||||
if (AZ::IO::FixedMaxPath projectModulePath;
|
||||
settingsRegistry->Get(projectModulePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectConfigurationBinPath))
|
||||
{
|
||||
projectModulePath /= AZStd::string_view(m_fileName);
|
||||
@@ -76,6 +77,15 @@ namespace AZ
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// The module does exist (in 'cwd'), but still needs to be an absolute path for the module to be loaded.
|
||||
AZStd::optional<AZ::IO::FixedMaxPathString> absPathOptional = AZ::Utils::ConvertToAbsolutePath(m_fileName);
|
||||
if (absPathOptional.has_value())
|
||||
{
|
||||
m_fileName.assign(absPathOptional->c_str(), absPathOptional->size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
~DynamicModuleHandleWindows() override
|
||||
|
||||
@@ -1914,7 +1914,7 @@ namespace UnitTest
|
||||
TEST_F(String, StringView_CompareIsConstexpr)
|
||||
{
|
||||
using TypeParam = char;
|
||||
auto MakeCompileTimeString1 = []() constexpr -> const TypeParam*
|
||||
auto ThisTestMakeCompileTimeString1 = []() constexpr -> const TypeParam*
|
||||
{
|
||||
return "HelloWorld";
|
||||
};
|
||||
@@ -1922,7 +1922,7 @@ namespace UnitTest
|
||||
{
|
||||
return "HelloPearl";
|
||||
};
|
||||
constexpr const TypeParam* compileTimeString1 = MakeCompileTimeString1();
|
||||
constexpr const TypeParam* compileTimeString1 = ThisTestMakeCompileTimeString1();
|
||||
constexpr const TypeParam* compileTimeString2 = MakeCompileTimeString2();
|
||||
constexpr basic_string_view<TypeParam> lhsView(compileTimeString1);
|
||||
constexpr basic_string_view<TypeParam> rhsView(compileTimeString2);
|
||||
@@ -1937,11 +1937,11 @@ namespace UnitTest
|
||||
TEST_F(String, StringView_CompareOperatorsAreConstexpr)
|
||||
{
|
||||
using TypeParam = char;
|
||||
auto MakeCompileTimeString1 = []() constexpr -> const TypeParam*
|
||||
auto TestMakeCompileTimeString1 = []() constexpr -> const TypeParam*
|
||||
{
|
||||
return "HelloWorld";
|
||||
};
|
||||
constexpr const TypeParam* compileTimeString1 = MakeCompileTimeString1();
|
||||
constexpr const TypeParam* compileTimeString1 = TestMakeCompileTimeString1();
|
||||
constexpr basic_string_view<TypeParam> compareView(compileTimeString1);
|
||||
static_assert(compareView == "HelloWorld", "string_view operator== comparison has failed");
|
||||
static_assert(compareView != "MadWorld", "string_view operator!= comparison has failed");
|
||||
@@ -1955,7 +1955,7 @@ namespace UnitTest
|
||||
{
|
||||
auto swap_test_func = []() constexpr -> basic_string_view<TypeParam>
|
||||
{
|
||||
constexpr auto MakeCompileTimeString1 = []() constexpr -> const TypeParam*
|
||||
constexpr auto ThisTestMakeCompileTimeString1 = []() constexpr -> const TypeParam*
|
||||
{
|
||||
if constexpr (AZStd::is_same_v<TypeParam, char>)
|
||||
{
|
||||
@@ -1977,7 +1977,7 @@ namespace UnitTest
|
||||
return L"InuWorld";
|
||||
}
|
||||
};
|
||||
constexpr const TypeParam* compileTimeString1 = MakeCompileTimeString1();
|
||||
constexpr const TypeParam* compileTimeString1 = ThisTestMakeCompileTimeString1();
|
||||
constexpr const TypeParam* compileTimeString2 = MakeCompileTimeString2();
|
||||
basic_string_view<TypeParam> lhsView(compileTimeString1);
|
||||
basic_string_view<TypeParam> rhsView(compileTimeString2);
|
||||
@@ -2001,7 +2001,7 @@ namespace UnitTest
|
||||
|
||||
TYPED_TEST(BasicStringViewConstexprFixture, HashString_FunctionIsConstexpr)
|
||||
{
|
||||
auto MakeCompileTimeString1 = []() constexpr -> const TypeParam*
|
||||
auto ThisTestMakeCompileTimeString1 = []() constexpr -> const TypeParam*
|
||||
{
|
||||
if constexpr (AZStd::is_same_v<TypeParam, char>)
|
||||
{
|
||||
@@ -2012,7 +2012,7 @@ namespace UnitTest
|
||||
return L"HelloWorld";
|
||||
}
|
||||
};
|
||||
constexpr const TypeParam* compileTimeString1 = MakeCompileTimeString1();
|
||||
constexpr const TypeParam* compileTimeString1 = ThisTestMakeCompileTimeString1();
|
||||
constexpr basic_string_view<TypeParam> hashView(compileTimeString1);
|
||||
constexpr size_t compileHash = AZStd::hash<basic_string_view<TypeParam>>{}(hashView);
|
||||
static_assert(compileHash != 0, "Hash of \"HelloWorld\" should not be 0");
|
||||
|
||||
@@ -395,7 +395,8 @@ namespace UnitTest
|
||||
}
|
||||
else
|
||||
{
|
||||
int result1, result2;
|
||||
int result1 = 0;
|
||||
int result2 = 0;
|
||||
Job* job1 = aznew FibonacciJob2(m_n - 1, &result1, m_context);
|
||||
Job* job2 = aznew FibonacciJob2(m_n - 2, &result2, m_context);
|
||||
StartAsChild(job1);
|
||||
|
||||
@@ -59,7 +59,7 @@ namespace UnitTest
|
||||
|
||||
TEST(MATH_Matrix4x4, TestCreateFrom)
|
||||
{
|
||||
float testFloats[] =
|
||||
float thisTestFloats[] =
|
||||
{
|
||||
1.0f, 2.0f, 3.0f, 4.0f,
|
||||
5.0f, 6.0f, 7.0f, 8.0f,
|
||||
@@ -67,20 +67,20 @@ namespace UnitTest
|
||||
13.0f, 14.0f, 15.0f, 16.0f
|
||||
};
|
||||
float testFloatMtx[16];
|
||||
Matrix4x4 m1 = Matrix4x4::CreateFromRowMajorFloat16(testFloats);
|
||||
Matrix4x4 m1 = Matrix4x4::CreateFromRowMajorFloat16(thisTestFloats);
|
||||
AZ_TEST_ASSERT(m1.GetRow(0) == Vector4(1.0f, 2.0f, 3.0f, 4.0f));
|
||||
AZ_TEST_ASSERT(m1.GetRow(1) == Vector4(5.0f, 6.0f, 7.0f, 8.0f));
|
||||
AZ_TEST_ASSERT(m1.GetRow(2) == Vector4(9.0f, 10.0f, 11.0f, 12.0f));
|
||||
AZ_TEST_ASSERT(m1.GetRow(3) == Vector4(13.0f, 14.0f, 15.0f, 16.0f));
|
||||
m1.StoreToRowMajorFloat16(testFloatMtx);
|
||||
AZ_TEST_ASSERT(memcmp(testFloatMtx, testFloats, sizeof(testFloatMtx)) == 0);
|
||||
m1 = Matrix4x4::CreateFromColumnMajorFloat16(testFloats);
|
||||
AZ_TEST_ASSERT(memcmp(testFloatMtx, thisTestFloats, sizeof(testFloatMtx)) == 0);
|
||||
m1 = Matrix4x4::CreateFromColumnMajorFloat16(thisTestFloats);
|
||||
AZ_TEST_ASSERT(m1.GetRow(0) == Vector4(1.0f, 5.0f, 9.0f, 13.0f));
|
||||
AZ_TEST_ASSERT(m1.GetRow(1) == Vector4(2.0f, 6.0f, 10.0f, 14.0f));
|
||||
AZ_TEST_ASSERT(m1.GetRow(2) == Vector4(3.0f, 7.0f, 11.0f, 15.0f));
|
||||
AZ_TEST_ASSERT(m1.GetRow(3) == Vector4(4.0f, 8.0f, 12.0f, 16.0f));
|
||||
m1.StoreToColumnMajorFloat16(testFloatMtx);
|
||||
AZ_TEST_ASSERT(memcmp(testFloatMtx, testFloats, sizeof(testFloatMtx)) == 0);
|
||||
AZ_TEST_ASSERT(memcmp(testFloatMtx, thisTestFloats, sizeof(testFloatMtx)) == 0);
|
||||
}
|
||||
|
||||
TEST(MATH_Matrix4x4, TestCreateFromMatrix3x4)
|
||||
|
||||
@@ -119,10 +119,10 @@ namespace UnitTest
|
||||
|
||||
TEST(MATH_Obb, Contains)
|
||||
{
|
||||
const Vector3 position(1.0f, 2.0f, 3.0f);
|
||||
const Quaternion rotation = Quaternion::CreateRotationZ(DegToRad(30.0f));
|
||||
const Vector3 halfLengths(2.0f, 1.0f, 2.5f);
|
||||
const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(position, rotation, halfLengths);
|
||||
const Vector3 testPosition(1.0f, 2.0f, 3.0f);
|
||||
const Quaternion testRotation = Quaternion::CreateRotationZ(DegToRad(30.0f));
|
||||
const Vector3 testHalfLengths(2.0f, 1.0f, 2.5f);
|
||||
const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(testPosition, testRotation, testHalfLengths);
|
||||
// test some pairs of points which should be just either side of the Obb boundary
|
||||
EXPECT_TRUE(obb.Contains(Vector3(1.35f, 3.35f, 3.5f)));
|
||||
EXPECT_FALSE(obb.Contains(Vector3(1.35f, 3.4f, 3.5f)));
|
||||
@@ -134,10 +134,10 @@ namespace UnitTest
|
||||
|
||||
TEST(MATH_Obb, GetDistance)
|
||||
{
|
||||
const Vector3 position(5.0f, 3.0f, 2.0f);
|
||||
const Quaternion rotation = Quaternion::CreateRotationX(DegToRad(60.0f));
|
||||
const Vector3 halfLengths(0.5f, 2.0f, 1.5f);
|
||||
const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(position, rotation, halfLengths);
|
||||
const Vector3 testPosition(5.0f, 3.0f, 2.0f);
|
||||
const Quaternion testRotation = Quaternion::CreateRotationX(DegToRad(60.0f));
|
||||
const Vector3 testHalfLengths(0.5f, 2.0f, 1.5f);
|
||||
const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(testPosition, testRotation, testHalfLengths);
|
||||
EXPECT_NEAR(obb.GetDistance(Vector3(5.3f, 3.2f, 1.8f)), 0.0f, 1e-3f);
|
||||
EXPECT_NEAR(obb.GetDistance(Vector3(5.1f, 1.1f, 3.7f)), 0.9955f, 1e-3f);
|
||||
EXPECT_NEAR(obb.GetDistance(Vector3(4.7f, 4.5f, 4.2f)), 0.6553f, 1e-3f);
|
||||
@@ -146,10 +146,10 @@ namespace UnitTest
|
||||
|
||||
TEST(MATH_Obb, GetDistanceSq)
|
||||
{
|
||||
const Vector3 position(1.0f, 4.0f, 3.0f);
|
||||
const Quaternion rotation = Quaternion::CreateRotationY(DegToRad(45.0f));
|
||||
const Vector3 halfLengths(1.5f, 3.0f, 1.0f);
|
||||
const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(position, rotation, halfLengths);
|
||||
const Vector3 testPosition(1.0f, 4.0f, 3.0f);
|
||||
const Quaternion testRotation = Quaternion::CreateRotationY(DegToRad(45.0f));
|
||||
const Vector3 testHalfLengths(1.5f, 3.0f, 1.0f);
|
||||
const Obb obb = Obb::CreateFromPositionRotationAndHalfLengths(testPosition, testRotation, testHalfLengths);
|
||||
EXPECT_NEAR(obb.GetDistanceSq(Vector3(1.1f, 4.3f, 2.7f)), 0.0f, 1e-3f);
|
||||
EXPECT_NEAR(obb.GetDistanceSq(Vector3(-0.7f, 3.5f, 2.0f)), 0.8266f, 1e-3f);
|
||||
EXPECT_NEAR(obb.GetDistanceSq(Vector3(2.4f, 0.5f, 1.5f)), 0.5532f, 1e-3f);
|
||||
|
||||
@@ -711,8 +711,8 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
|
||||
AZ::IO::FixedMaxPath projectUserPath;
|
||||
if (m_settingsRegistry->Get(projectUserPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectUserPath))
|
||||
if (AZ::IO::FixedMaxPath projectUserPath;
|
||||
m_settingsRegistry->Get(projectUserPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectUserPath))
|
||||
{
|
||||
fileIoBase->SetAlias("@user@", projectUserPath.c_str());
|
||||
AZ::IO::FixedMaxPath projectLogPath = projectUserPath / "log";
|
||||
@@ -721,6 +721,15 @@ namespace AzFramework
|
||||
|
||||
CreateUserCache(projectUserPath, *fileIoBase);
|
||||
}
|
||||
else
|
||||
{
|
||||
AZ::IO::FixedMaxPath fallbackLogPath = GetEngineRoot();
|
||||
fallbackLogPath /= "user";
|
||||
fileIoBase->SetAlias("@user@", fallbackLogPath.c_str());
|
||||
fallbackLogPath /= "log";
|
||||
fileIoBase->SetAlias("@log@", fallbackLogPath.c_str());
|
||||
fileIoBase->CreatePath(fallbackLogPath.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ namespace AzFramework
|
||||
AZ::Matrix3x4 m_transform = AZ::Matrix3x4::Identity(); //!< Transform to apply to text quads
|
||||
bool m_monospace = false; //!< disable character proportional spacing
|
||||
bool m_depthTest = false; //!< Test character against the depth buffer
|
||||
bool m_virtual800x600ScreenSize = true; //!< Text placement and size are scaled relative to a virtual 800x600 resolution
|
||||
bool m_virtual800x600ScreenSize = false; //!< Text placement and size are scaled relative to a virtual 800x600 resolution
|
||||
bool m_scaleWithWindow = false; //!< Font gets bigger as the window gets bigger
|
||||
bool m_multiline = true; //!< text respects ascii newline characters
|
||||
};
|
||||
|
||||
@@ -78,7 +78,7 @@ namespace AzFramework::ProjectManager
|
||||
projectJsonPath.c_str());
|
||||
}
|
||||
|
||||
if (LaunchProjectManager(engineRootPath))
|
||||
if (LaunchProjectManager())
|
||||
{
|
||||
AZ_TracePrintf("ProjectManager", "Project Manager launched successfully, requesting exit.");
|
||||
return ProjectPathCheckResult::ProjectManagerLaunched;
|
||||
@@ -87,7 +87,7 @@ namespace AzFramework::ProjectManager
|
||||
return ProjectPathCheckResult::ProjectManagerLaunchFailed;
|
||||
}
|
||||
|
||||
bool LaunchProjectManager([[maybe_unused]] const AZ::IO::FixedMaxPath& engineRootPath)
|
||||
bool LaunchProjectManager(const AZStd::string& commandLineArgs)
|
||||
{
|
||||
bool launchSuccess = false;
|
||||
#if (AZ_TRAIT_AZFRAMEWORK_USE_PROJECT_MANAGER)
|
||||
@@ -109,7 +109,7 @@ namespace AzFramework::ProjectManager
|
||||
}
|
||||
|
||||
AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo;
|
||||
processLaunchInfo.m_commandlineParameters = executablePath.String();
|
||||
processLaunchInfo.m_commandlineParameters = executablePath.String() + commandLineArgs;
|
||||
launchSuccess = AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo);
|
||||
}
|
||||
if (ownsSystemAllocator)
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <AzCore/IO/Path/Path_fwd.h>
|
||||
#include <AzCore/std/string/string.h>
|
||||
|
||||
namespace AzFramework::ProjectManager
|
||||
{
|
||||
@@ -21,8 +22,16 @@ namespace AzFramework::ProjectManager
|
||||
ProjectManagerLaunched = 0,
|
||||
ProjectPathFound = 1
|
||||
};
|
||||
// Check for a project name, if not found, attempts to launch project manager and returns false
|
||||
|
||||
//! Check for a project name, if not found, attempts to launch project manager and returns false
|
||||
//! @param argc the number of arguments in argv
|
||||
//! @param argv arguments provided to this executable
|
||||
//! @return a ProjectPathCheckResult
|
||||
ProjectPathCheckResult CheckProjectPathProvided(const int argc, char* argv[]);
|
||||
// Attempt to Launch the project manager. Requires locating the engine root, project manager script, and python.
|
||||
bool LaunchProjectManager(const AZ::IO::FixedMaxPath& engineRootPath);
|
||||
|
||||
//! Attempt to Launch the project manager, assuming the o3de executable exists in same folder as
|
||||
//! current executable. Requires the o3de cli and python.
|
||||
//! @param commandLineArgs additional command line arguments to provide to the project manager
|
||||
//! @return true on success, false if failed to find or launch the executable
|
||||
bool LaunchProjectManager(const AZStd::string& commandLineArgs = "");
|
||||
} // AzFramework::ProjectManager
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AzCore/RTTI/RTTI.h>
|
||||
#include <AzCore/std/string/string.h>
|
||||
|
||||
namespace AzFramework
|
||||
@@ -49,13 +50,17 @@ namespace AzFramework
|
||||
class ISessionHandlingClientRequests
|
||||
{
|
||||
public:
|
||||
// Handle the player join session process
|
||||
AZ_RTTI(ISessionHandlingClientRequests, "{41DE6BD3-72BC-4443-BFF9-5B1B9396657A}");
|
||||
ISessionHandlingClientRequests() = default;
|
||||
virtual ~ISessionHandlingClientRequests() = default;
|
||||
|
||||
// Request the player join session
|
||||
// @param sessionConnectionConfig The required properties to handle the player join session process
|
||||
// @return The result of player join session process
|
||||
virtual bool HandlePlayerJoinSession(const SessionConnectionConfig& sessionConnectionConfig) = 0;
|
||||
virtual bool RequestPlayerJoinSession(const SessionConnectionConfig& sessionConnectionConfig) = 0;
|
||||
|
||||
// Handle the player leave session process
|
||||
virtual void HandlePlayerLeaveSession() = 0;
|
||||
// Request the connected player leave session
|
||||
virtual void RequestPlayerLeaveSession() = 0;
|
||||
};
|
||||
|
||||
//! ISessionHandlingServerRequests
|
||||
@@ -63,6 +68,10 @@ namespace AzFramework
|
||||
class ISessionHandlingServerRequests
|
||||
{
|
||||
public:
|
||||
AZ_RTTI(ISessionHandlingServerRequests, "{4F0C17BA-F470-4242-A8CB-EC7EA805257C}");
|
||||
ISessionHandlingServerRequests() = default;
|
||||
virtual ~ISessionHandlingServerRequests() = default;
|
||||
|
||||
// Handle the destroy session process
|
||||
virtual void HandleDestroySession() = 0;
|
||||
|
||||
@@ -74,5 +83,10 @@ namespace AzFramework
|
||||
// Handle the player leave session process
|
||||
// @param playerConnectionConfig The required properties to handle the player leave session process
|
||||
virtual void HandlePlayerLeaveSession(const PlayerConnectionConfig& playerConnectionConfig) = 0;
|
||||
|
||||
// Retrieves the file location of a pem-encoded TLS certificate
|
||||
// @return If successful, returns the file location of TLS certificate file; if not successful, returns
|
||||
// empty string.
|
||||
virtual AZStd::string GetSessionCertificate() = 0;
|
||||
};
|
||||
} // namespace AzFramework
|
||||
|
||||
@@ -167,6 +167,9 @@ namespace AzFramework
|
||||
: public AZ::EBusTraits
|
||||
{
|
||||
public:
|
||||
// Safeguard handler for multi-threaded use case
|
||||
using MutexType = AZStd::recursive_mutex;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// EBusTraits overrides
|
||||
static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple;
|
||||
|
||||
@@ -24,6 +24,9 @@ namespace AzFramework
|
||||
: public AZ::EBusTraits
|
||||
{
|
||||
public:
|
||||
// Safeguard handler for multi-threaded use case
|
||||
using MutexType = AZStd::recursive_mutex;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// EBusTraits overrides
|
||||
static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple;
|
||||
|
||||
@@ -21,22 +21,6 @@ namespace AzFramework
|
||||
{
|
||||
}
|
||||
|
||||
Spawnable::Spawnable(Spawnable&& other)
|
||||
: m_entities(AZStd::move(other.m_entities))
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
Spawnable& Spawnable::operator=(Spawnable&& other)
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
m_entities = AZStd::move(other.m_entities);
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
const Spawnable::EntityList& Spawnable::GetEntities() const
|
||||
{
|
||||
return m_entities;
|
||||
|
||||
@@ -41,11 +41,11 @@ namespace AzFramework
|
||||
Spawnable() = default;
|
||||
explicit Spawnable(const AZ::Data::AssetId& id, AssetStatus status = AssetStatus::NotLoaded);
|
||||
Spawnable(const Spawnable& rhs) = delete;
|
||||
Spawnable(Spawnable&& other);
|
||||
Spawnable(Spawnable&& other) = delete;
|
||||
~Spawnable() override = default;
|
||||
|
||||
Spawnable& operator=(const Spawnable& rhs) = delete;
|
||||
Spawnable& operator=(Spawnable&& other);
|
||||
Spawnable& operator=(Spawnable&& other) = delete;
|
||||
|
||||
const EntityList& GetEntities() const;
|
||||
EntityList& GetEntities();
|
||||
|
||||
@@ -44,7 +44,8 @@ namespace AzFramework
|
||||
void SpawnableEntitiesContainer::SpawnEntities(AZStd::vector<size_t> entityIndices)
|
||||
{
|
||||
AZ_Assert(m_threadData, "Calling SpawnEntities on a Spawnable container that's not set.");
|
||||
SpawnableEntitiesInterface::Get()->SpawnEntities(m_threadData->m_spawnedEntitiesTicket, AZStd::move(entityIndices));
|
||||
SpawnableEntitiesInterface::Get()->SpawnEntities(
|
||||
m_threadData->m_spawnedEntitiesTicket, AZStd::move(entityIndices));
|
||||
}
|
||||
|
||||
void SpawnableEntitiesContainer::DespawnAllEntities()
|
||||
@@ -66,8 +67,9 @@ namespace AzFramework
|
||||
m_monitor.Disconnect();
|
||||
m_monitor.m_threadData.reset();
|
||||
|
||||
SpawnableEntitiesInterface::Get()->Barrier(m_threadData->m_spawnedEntitiesTicket,
|
||||
[threadData = m_threadData](EntitySpawnTicket&) mutable
|
||||
SpawnableEntitiesInterface::Get()->Barrier(
|
||||
m_threadData->m_spawnedEntitiesTicket,
|
||||
[threadData = m_threadData](EntitySpawnTicket::Id) mutable
|
||||
{
|
||||
threadData.reset();
|
||||
});
|
||||
@@ -83,8 +85,9 @@ namespace AzFramework
|
||||
void SpawnableEntitiesContainer::Alert(AlertCallback callback)
|
||||
{
|
||||
AZ_Assert(m_threadData, "Calling DespawnEntities on a Spawnable container that's not set.");
|
||||
SpawnableEntitiesInterface::Get()->Barrier(m_threadData->m_spawnedEntitiesTicket,
|
||||
[generation = m_threadData->m_generation, callback = AZStd::move(callback)](EntitySpawnTicket&)
|
||||
SpawnableEntitiesInterface::Get()->Barrier(
|
||||
m_threadData->m_spawnedEntitiesTicket,
|
||||
[generation = m_threadData->m_generation, callback = AZStd::move(callback)](EntitySpawnTicket::Id)
|
||||
{
|
||||
callback(generation);
|
||||
});
|
||||
|
||||
@@ -239,7 +239,9 @@ namespace AzFramework
|
||||
{
|
||||
auto manager = SpawnableEntitiesInterface::Get();
|
||||
AZ_Assert(manager, "Attempting to create an entity spawn ticket while the SpawnableEntitiesInterface has no implementation.");
|
||||
m_payload = manager->CreateTicket(AZStd::move(spawnable));
|
||||
AZStd::pair<EntitySpawnTicket::Id, void*> result = manager->CreateTicket(AZStd::move(spawnable));
|
||||
m_id = result.first;
|
||||
m_payload = result.second;
|
||||
}
|
||||
|
||||
EntitySpawnTicket::~EntitySpawnTicket()
|
||||
@@ -250,6 +252,7 @@ namespace AzFramework
|
||||
AZ_Assert(manager, "Attempting to destroy an entity spawn ticket while the SpawnableEntitiesInterface has no implementation.");
|
||||
manager->DestroyTicket(m_payload);
|
||||
m_payload = nullptr;
|
||||
m_id = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,12 +266,20 @@ namespace AzFramework
|
||||
AZ_Assert(manager, "Attempting to destroy an entity spawn ticket while the SpawnableEntitiesInterface has no implementation.");
|
||||
manager->DestroyTicket(m_payload);
|
||||
}
|
||||
m_id = rhs.m_id;
|
||||
rhs.m_id = 0;
|
||||
|
||||
m_payload = rhs.m_payload;
|
||||
rhs.m_payload = nullptr;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
auto EntitySpawnTicket::GetId() const -> Id
|
||||
{
|
||||
return m_id;
|
||||
}
|
||||
|
||||
bool EntitySpawnTicket::IsValid() const
|
||||
{
|
||||
return m_payload != nullptr;
|
||||
|
||||
@@ -14,16 +14,26 @@
|
||||
|
||||
#include <AzCore/Asset/AssetCommon.h>
|
||||
#include <AzCore/Interface/Interface.h>
|
||||
#include <AzCore/RTTI/TypeSafeIntegral.h>
|
||||
#include <AzCore/std/functional.h>
|
||||
#include <AzFramework/Spawnable/Spawnable.h>
|
||||
|
||||
namespace AZ
|
||||
{
|
||||
class Entity;
|
||||
class SerializeContext;
|
||||
}
|
||||
|
||||
namespace AzFramework
|
||||
{
|
||||
AZ_TYPE_SAFE_INTEGRAL(SpawnablePriority, uint8_t);
|
||||
|
||||
inline static constexpr SpawnablePriority SpawnablePriority_Highest { 0 };
|
||||
inline static constexpr SpawnablePriority SpawnablePriority_High { 32 };
|
||||
inline static constexpr SpawnablePriority SpawnablePriority_Default { 128 };
|
||||
inline static constexpr SpawnablePriority SpawnablePriority_Low { 192 };
|
||||
inline static constexpr SpawnablePriority SpawnablePriority_Lowest { 255 };
|
||||
|
||||
class SpawnableEntityContainerView
|
||||
{
|
||||
public:
|
||||
@@ -124,16 +134,18 @@ namespace AzFramework
|
||||
SpawnableIndexEntityIterator m_end;
|
||||
};
|
||||
|
||||
//! Requests to the SpawnableEntitiesInterface require a ticket with a valid spawnable that be used as a template. A ticket can
|
||||
//! be reused for multiple calls on the same spawnable and is safe to use by multiple threads at the same time. Entities created
|
||||
//! Requests to the SpawnableEntitiesInterface require a ticket with a valid spawnable that is used as a template. A ticket can
|
||||
//! be reused for multiple calls on the same spawnable and is safe to be used by multiple threads at the same time. Entities created
|
||||
//! from the spawnable may be tracked by the ticket and so using the same ticket is needed to despawn the exact entities created
|
||||
//! by a call so spawn entities. The life cycle of the spawned entities is tied to the ticket and all entities spawned using a
|
||||
//! by a call to spawn entities. The life cycle of the spawned entities is tied to the ticket and all entities spawned using a
|
||||
//! ticket will be despawned when it's deleted.
|
||||
class EntitySpawnTicket
|
||||
{
|
||||
public:
|
||||
friend class SpawnableEntitiesDefinition;
|
||||
|
||||
using Id = uint64_t;
|
||||
|
||||
EntitySpawnTicket() = default;
|
||||
EntitySpawnTicket(const EntitySpawnTicket&) = delete;
|
||||
EntitySpawnTicket(EntitySpawnTicket&& rhs);
|
||||
@@ -143,26 +155,108 @@ namespace AzFramework
|
||||
EntitySpawnTicket& operator=(const EntitySpawnTicket&) = delete;
|
||||
EntitySpawnTicket& operator=(EntitySpawnTicket&& rhs);
|
||||
|
||||
Id GetId() const;
|
||||
bool IsValid() const;
|
||||
|
||||
private:
|
||||
void* m_payload{ nullptr };
|
||||
Id m_id { 0 }; //!< An id that uniquely identifies a ticket.
|
||||
};
|
||||
|
||||
using EntitySpawnCallback = AZStd::function<void(EntitySpawnTicket&, SpawnableConstEntityContainerView)>;
|
||||
using EntityPreInsertionCallback = AZStd::function<void(EntitySpawnTicket&, SpawnableEntityContainerView)>;
|
||||
using EntityDespawnCallback = AZStd::function<void(EntitySpawnTicket&)>;
|
||||
using ReloadSpawnableCallback = AZStd::function<void(EntitySpawnTicket&, SpawnableConstEntityContainerView)>;
|
||||
using ListEntitiesCallback = AZStd::function<void(EntitySpawnTicket&, SpawnableConstEntityContainerView)>;
|
||||
using ListIndicesEntitiesCallback = AZStd::function<void(EntitySpawnTicket&, SpawnableConstIndexEntityContainerView)>;
|
||||
using ClaimEntitiesCallback = AZStd::function<void(EntitySpawnTicket&, SpawnableEntityContainerView)>;
|
||||
using BarrierCallback = AZStd::function<void(EntitySpawnTicket&)>;
|
||||
using EntitySpawnCallback = AZStd::function<void(EntitySpawnTicket::Id, SpawnableConstEntityContainerView)>;
|
||||
using EntityPreInsertionCallback = AZStd::function<void(EntitySpawnTicket::Id, SpawnableEntityContainerView)>;
|
||||
using EntityDespawnCallback = AZStd::function<void(EntitySpawnTicket::Id)>;
|
||||
using ReloadSpawnableCallback = AZStd::function<void(EntitySpawnTicket::Id, SpawnableConstEntityContainerView)>;
|
||||
using ListEntitiesCallback = AZStd::function<void(EntitySpawnTicket::Id, SpawnableConstEntityContainerView)>;
|
||||
using ListIndicesEntitiesCallback = AZStd::function<void(EntitySpawnTicket::Id, SpawnableConstIndexEntityContainerView)>;
|
||||
using ClaimEntitiesCallback = AZStd::function<void(EntitySpawnTicket::Id, SpawnableEntityContainerView)>;
|
||||
using BarrierCallback = AZStd::function<void(EntitySpawnTicket::Id)>;
|
||||
|
||||
struct SpawnAllEntitiesOptionalArgs final
|
||||
{
|
||||
//! Callback that's called after instances of entities have been created, but before they're spawned into the world. This
|
||||
//! gives the opportunity to modify the entities if needed such as injecting additional components or modifying components.
|
||||
EntityPreInsertionCallback m_preInsertionCallback;
|
||||
//! Callback that's called when spawning entities has completed. This can be triggered from a different thread than the one that
|
||||
//! made the function call to spawn. The returned list of entities contains all the newly created entities.
|
||||
EntitySpawnCallback m_completionCallback;
|
||||
//! The Serialize Context used to clone entities with. If this is not provided the global Serialize Contetx will be used.
|
||||
AZ::SerializeContext* m_serializeContext { nullptr };
|
||||
//! The priority at which this call will be executed.
|
||||
SpawnablePriority m_priority { SpawnablePriority_Default };
|
||||
};
|
||||
|
||||
struct SpawnEntitiesOptionalArgs final
|
||||
{
|
||||
//! Callback that's called after instances of entities have been created, but before they're spawned into the world. This
|
||||
//! gives the opportunity to modify the entities if needed such as injecting additional components or modifying components.
|
||||
EntityPreInsertionCallback m_preInsertionCallback;
|
||||
//! Callback that's called when spawning entities has completed. This can be triggered from a different thread than the one that
|
||||
//! made the function call to spawn. The returned list of entities contains all the newly created entities.
|
||||
EntitySpawnCallback m_completionCallback;
|
||||
//! The Serialize Context used to clone entities with. If this is not provided the global Serialize Contetx will be used.
|
||||
AZ::SerializeContext* m_serializeContext{ nullptr };
|
||||
//! The priority at which this call will be executed.
|
||||
SpawnablePriority m_priority{ SpawnablePriority_Default };
|
||||
//! Entity references are resolved by referring to the last entity spawned from a template entity in the spawnable. If this
|
||||
//! is set to false entities from previous spawn calls are not taken into account. If set to true entity references may be
|
||||
//! resolved to a previously spawned entity. A lookup table has to be constructed when true, which may negatively impact
|
||||
//! performance, especially if a large number of entities are present on a ticket.
|
||||
bool m_referencePreviouslySpawnedEntities{ false };
|
||||
};
|
||||
|
||||
struct DespawnAllEntitiesOptionalArgs final
|
||||
{
|
||||
//! Callback that's called when despawning entities has completed. This can be triggered from a different thread than the one that
|
||||
//! made the function call to despawn. The returned list of entities contains all the newly created entities.
|
||||
EntityDespawnCallback m_completionCallback;
|
||||
//! The priority at which this call will be executed.
|
||||
SpawnablePriority m_priority { SpawnablePriority_Default };
|
||||
};
|
||||
|
||||
struct ReloadSpawnableOptionalArgs final
|
||||
{
|
||||
//! Callback that's called when respawning entities has completed. This can be triggered from a different thread than the one that
|
||||
//! made the function call to respawn. The returned list of entities contains all the newly created entities.
|
||||
ReloadSpawnableCallback m_completionCallback;
|
||||
//! The Serialize Context used to clone entities with. If this is not provided the global Serialize Context will be used.
|
||||
AZ::SerializeContext* m_serializeContext { nullptr };
|
||||
//! The priority at which this call will be executed.
|
||||
SpawnablePriority m_priority { SpawnablePriority_Default };
|
||||
};
|
||||
|
||||
struct ListEntitiesOptionalArgs final
|
||||
{
|
||||
//! The priority at which this call will be executed.
|
||||
SpawnablePriority m_priority{ SpawnablePriority_Default };
|
||||
};
|
||||
|
||||
struct ClaimEntitiesOptionalArgs final
|
||||
{
|
||||
//! The priority at which this call will be executed.
|
||||
SpawnablePriority m_priority{ SpawnablePriority_Default };
|
||||
};
|
||||
|
||||
struct BarrierOptionalArgs final
|
||||
{
|
||||
//! The priority at which this call will be executed.
|
||||
SpawnablePriority m_priority{ SpawnablePriority_Default };
|
||||
};
|
||||
|
||||
//! Interface definition to (de)spawn entities from a spawnable into the game world.
|
||||
//!
|
||||
//! While the callbacks of the individual calls are being processed they will block processing any other request. Callbacks can be
|
||||
//! issued from threads other than the one that issued the call, including the main thread.
|
||||
//!
|
||||
//! Calls on the same ticket are guaranteed to be executed in the order they are issued. Note that when issuing requests from
|
||||
//! multiple threads on the same ticket the order in which the requests are assigned to the ticket is not guaranteed.
|
||||
//!
|
||||
//! Most calls have a priority with values that range from 0 (highest priority) to 255 (lowest priority). The implementation of this
|
||||
//! interface may choose to use priority lanes which doesn't guarantee that higher priority requests happen before lower priority
|
||||
//! requests if they don't pass the priority lane threshold. Priority lanes and their thresholds are implementation specific and may
|
||||
//! differ between platforms. Note that if a call happened on a ticket with lower priority followed by a one with a higher priority
|
||||
//! the first lower priority call will still need to complete before the second higher priority call can be executed and the priority
|
||||
//! of the first call will not be updated.
|
||||
class SpawnableEntitiesDefinition
|
||||
{
|
||||
public:
|
||||
@@ -173,40 +267,35 @@ namespace AzFramework
|
||||
virtual ~SpawnableEntitiesDefinition() = default;
|
||||
|
||||
//! Spawn instances of all entities in the spawnable.
|
||||
//! @param spawnable The Spawnable asset that will be used to create entity instances from.
|
||||
//! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them.
|
||||
//! @param completionCallback Optional callback that's called when spawning entities has completed. This can be called from
|
||||
//! a different thread than the one that made the function call. The returned list of entities contains all the newly
|
||||
//! created entities.
|
||||
virtual void SpawnAllEntities(EntitySpawnTicket& ticket, EntityPreInsertionCallback preInsertionCallback = {},
|
||||
EntitySpawnCallback completionCallback = {}) = 0;
|
||||
//! @param optionalArgs Optional additional arguments, see SpawnAllEntitiesOptionalArgs.
|
||||
virtual void SpawnAllEntities(EntitySpawnTicket& ticket, SpawnAllEntitiesOptionalArgs optionalArgs = {}) = 0;
|
||||
//! Spawn instances of some entities in the spawnable.
|
||||
//! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them.
|
||||
//! @param priority The priority at which this call will be executed.
|
||||
//! @param entityIndices The indices into the template entities stored in the spawnable that will be used to spawn entities from.
|
||||
//! @param completionCallback Optional callback that's called when spawning entities has completed. This can be called from
|
||||
//! a different thread than the one that made this function call. The returned list of entities contains all the newly
|
||||
//! created entities.
|
||||
virtual void SpawnEntities(EntitySpawnTicket& ticket, AZStd::vector<size_t> entityIndices,
|
||||
EntityPreInsertionCallback preInsertionCallback = {}, EntitySpawnCallback completionCallback = {}) = 0;
|
||||
//! @param optionalArgs Optional additional arguments, see SpawnEntitiesOptionalArgs.
|
||||
virtual void SpawnEntities(
|
||||
EntitySpawnTicket& ticket, AZStd::vector<size_t> entityIndices, SpawnEntitiesOptionalArgs optionalArgs = {}) = 0;
|
||||
//! Removes all entities in the provided list from the environment.
|
||||
//! @param ticket The ticket previously used to spawn entities with.
|
||||
//! @param completionCallback Optional callback that's called when despawning entities has completed. This can be called from
|
||||
//! a different thread than the one that made this function call.
|
||||
virtual void DespawnAllEntities(EntitySpawnTicket& ticket, EntityDespawnCallback completionCallback = {}) = 0;
|
||||
|
||||
//! @param priority The priority at which this call will be executed.
|
||||
//! @param optionalArgs Optional additional arguments, see DespawnAllEntitiesOptionalArgs.
|
||||
virtual void DespawnAllEntities(EntitySpawnTicket& ticket, DespawnAllEntitiesOptionalArgs optionalArgs = {}) = 0;
|
||||
//! Removes all entities in the provided list from the environment and reconstructs the entities from the provided spawnable.
|
||||
//! @param ticket Stores the results of the call. Use this ticket to spawn additional entities or to despawn them.
|
||||
//! @param ticket Holds the information on the entities to reload.
|
||||
//! @param priority The priority at which this call will be executed.
|
||||
//! @param spawnable The spawnable that will replace the existing spawnable. Both need to have the same asset id.
|
||||
//! @param completionCallback Optional callback that's called when the entities have been reloaded. This can be called from
|
||||
//! a different thread than the one that made this function call. The returned list of entities contains all the replacement
|
||||
//! entities.
|
||||
virtual void ReloadSpawnable(EntitySpawnTicket& ticket, AZ::Data::Asset<Spawnable> spawnable,
|
||||
ReloadSpawnableCallback completionCallback = {}) = 0;
|
||||
//! @param optionalArgs Optional additional arguments, see ReloadSpawnableOptionalArgs.
|
||||
virtual void ReloadSpawnable(
|
||||
EntitySpawnTicket& ticket, AZ::Data::Asset<Spawnable> spawnable, ReloadSpawnableOptionalArgs optionalArgs = {}) = 0;
|
||||
|
||||
//! List all entities that are spawned using this ticket.
|
||||
//! @param ticket Only the entities associated with this ticket will be listed.
|
||||
//! @param listCallback Required callback that will be called to list the entities on.
|
||||
virtual void ListEntities(EntitySpawnTicket& ticket, ListEntitiesCallback listCallback) = 0;
|
||||
//! @param optionalArgs Optional additional arguments, see ListEntitiesOptionalArgs.
|
||||
virtual void ListEntities(
|
||||
EntitySpawnTicket& ticket, ListEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs = {}) = 0;
|
||||
//! List all entities that are spawned using this ticket with their spawnable index.
|
||||
//! Spawnables contain a flat list of entities, which are used as templates to spawn entities from. For every spawned entity
|
||||
//! the index of the entity in the spawnable that was used as a template is stored. This version of ListEntities will return
|
||||
@@ -215,16 +304,23 @@ namespace AzFramework
|
||||
//! created.
|
||||
//! @param ticket Only the entities associated with this ticket will be listed.
|
||||
//! @param listCallback Required callback that will be called to list the entities and indices on.
|
||||
virtual void ListIndicesAndEntities(EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback) = 0;
|
||||
//! @param optionalArgs Optional additional arguments, see ListEntitiesOptionalArgs.
|
||||
virtual void ListIndicesAndEntities(
|
||||
EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs = {}) = 0;
|
||||
//! Claim all entities that are spawned using this ticket. Ownership of the entities is transferred from the ticket to the
|
||||
//! caller through the callback. After this call the ticket will have no entities associated with it. The caller of
|
||||
//! this function will need to manage the entities after this call.
|
||||
//! @param ticket Only the entities associated with this ticket will be released.
|
||||
//! @param listCallback Required callback that will be called to transfer the entities through.
|
||||
virtual void ClaimEntities(EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback) = 0;
|
||||
//! @param optionalArgs Optional additional arguments, see ClaimEntitiesOptionalArgs.
|
||||
virtual void ClaimEntities(
|
||||
EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback, ClaimEntitiesOptionalArgs optionalArgs = {}) = 0;
|
||||
|
||||
//! Blocks until all operations made on the provided ticket before the barrier call have completed.
|
||||
virtual void Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback) = 0;
|
||||
//! @param ticket The ticket to monitor.
|
||||
//! @param completionCallback Required callback that will be called as soon as the barrier has been reached.
|
||||
//! @param optionalArgs Optional additional arguments, see BarrierOptionalArgs.
|
||||
virtual void Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback, BarrierOptionalArgs optionalArgs = {}) = 0;
|
||||
|
||||
//! Register a handler for OnSpawned events.
|
||||
virtual void AddOnSpawnedHandler(AZ::Event<AZ::Data::Asset<Spawnable>>::Handler& handler) = 0;
|
||||
@@ -233,7 +329,7 @@ namespace AzFramework
|
||||
virtual void AddOnDespawnedHandler(AZ::Event<AZ::Data::Asset<Spawnable>>::Handler& handler) = 0;
|
||||
|
||||
protected:
|
||||
[[nodiscard]] virtual void* CreateTicket(AZ::Data::Asset<Spawnable>&& spawnable) = 0;
|
||||
[[nodiscard]] virtual AZStd::pair<EntitySpawnTicket::Id, void*> CreateTicket(AZ::Data::Asset<Spawnable>&& spawnable) = 0;
|
||||
virtual void DestroyTicket(void* ticket) = 0;
|
||||
|
||||
template<typename T>
|
||||
|
||||
@@ -10,9 +10,11 @@
|
||||
*
|
||||
*/
|
||||
|
||||
#include <AzCore/Casting/numeric_cast.h>
|
||||
#include <AzCore/Component/ComponentApplicationBus.h>
|
||||
#include <AzCore/Serialization/IdUtils.h>
|
||||
#include <AzCore/Serialization/SerializeContext.h>
|
||||
#include <AzCore/Settings/SettingsRegistry.h>
|
||||
#include <AzCore/std/parallel/scoped_lock.h>
|
||||
#include <AzCore/std/smart_ptr/make_shared.h>
|
||||
#include <AzFramework/Components/TransformComponent.h>
|
||||
@@ -22,128 +24,130 @@
|
||||
|
||||
namespace AzFramework
|
||||
{
|
||||
void SpawnableEntitiesManager::SpawnAllEntities(EntitySpawnTicket& ticket, EntityPreInsertionCallback preInsertionCallback,
|
||||
EntitySpawnCallback completionCallback)
|
||||
template<typename T>
|
||||
void SpawnableEntitiesManager::QueueRequest(EntitySpawnTicket& ticket, SpawnablePriority priority, T&& request)
|
||||
{
|
||||
request.m_ticket = &GetTicketPayload<Ticket>(ticket);
|
||||
Queue& queue = priority <= m_highPriorityThreshold ? m_highPriorityQueue : m_regularPriorityQueue;
|
||||
{
|
||||
AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex);
|
||||
request.m_requestId = GetTicketPayload<Ticket>(ticket).m_nextRequestId++;
|
||||
queue.m_pendingRequest.push(AZStd::move(request));
|
||||
}
|
||||
}
|
||||
|
||||
SpawnableEntitiesManager::SpawnableEntitiesManager()
|
||||
{
|
||||
AZ::ComponentApplicationBus::BroadcastResult(m_defaultSerializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
|
||||
AZ_Assert(
|
||||
m_defaultSerializeContext, "Failed to retrieve serialization context during construction of the Spawnable Entities Manager.");
|
||||
|
||||
if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
|
||||
{
|
||||
AZ::u64 value = aznumeric_caster(m_highPriorityThreshold);
|
||||
settingsRegistry->Get(value, "/O3DE/AzFramework/Spawnables/HighPriorityThreshold");
|
||||
m_highPriorityThreshold = aznumeric_cast<SpawnablePriority>(AZStd::clamp(value, 0llu, 255llu));
|
||||
}
|
||||
}
|
||||
|
||||
void SpawnableEntitiesManager::SpawnAllEntities(EntitySpawnTicket& ticket, SpawnAllEntitiesOptionalArgs optionalArgs)
|
||||
{
|
||||
AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnAllEntities hasn't been initialized.");
|
||||
|
||||
SpawnAllEntitiesCommand queueEntry;
|
||||
queueEntry.m_ticket = &ticket;
|
||||
queueEntry.m_completionCallback = AZStd::move(completionCallback);
|
||||
queueEntry.m_preInsertionCallback = AZStd::move(preInsertionCallback);
|
||||
{
|
||||
AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex);
|
||||
queueEntry.m_ticketId = GetTicketPayload<Ticket>(ticket).m_nextTicketId++;
|
||||
m_pendingRequestQueue.push(AZStd::move(queueEntry));
|
||||
}
|
||||
queueEntry.m_ticketId = ticket.GetId();
|
||||
queueEntry.m_serializeContext =
|
||||
optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext;
|
||||
queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback);
|
||||
queueEntry.m_preInsertionCallback = AZStd::move(optionalArgs.m_preInsertionCallback);
|
||||
QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry));
|
||||
}
|
||||
|
||||
void SpawnableEntitiesManager::SpawnEntities(
|
||||
EntitySpawnTicket& ticket, AZStd::vector<size_t> entityIndices,
|
||||
EntityPreInsertionCallback preInsertionCallback, EntitySpawnCallback completionCallback)
|
||||
EntitySpawnTicket& ticket, AZStd::vector<size_t> entityIndices, SpawnEntitiesOptionalArgs optionalArgs)
|
||||
{
|
||||
AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnEntities hasn't been initialized.");
|
||||
|
||||
SpawnEntitiesCommand queueEntry;
|
||||
queueEntry.m_ticket = &ticket;
|
||||
queueEntry.m_ticketId = ticket.GetId();
|
||||
queueEntry.m_entityIndices = AZStd::move(entityIndices);
|
||||
queueEntry.m_completionCallback = AZStd::move(completionCallback);
|
||||
queueEntry.m_preInsertionCallback = AZStd::move(preInsertionCallback);
|
||||
{
|
||||
AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex);
|
||||
queueEntry.m_ticketId = GetTicketPayload<Ticket>(ticket).m_nextTicketId++;
|
||||
m_pendingRequestQueue.push(AZStd::move(queueEntry));
|
||||
}
|
||||
queueEntry.m_serializeContext =
|
||||
optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext;
|
||||
queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback);
|
||||
queueEntry.m_preInsertionCallback = AZStd::move(optionalArgs.m_preInsertionCallback);
|
||||
queueEntry.m_referencePreviouslySpawnedEntities = optionalArgs.m_referencePreviouslySpawnedEntities;
|
||||
QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry));
|
||||
}
|
||||
|
||||
void SpawnableEntitiesManager::DespawnAllEntities(EntitySpawnTicket& ticket, EntityDespawnCallback completionCallback)
|
||||
void SpawnableEntitiesManager::DespawnAllEntities(EntitySpawnTicket& ticket, DespawnAllEntitiesOptionalArgs optionalArgs)
|
||||
{
|
||||
AZ_Assert(ticket.IsValid(), "Ticket provided to DespawnAllEntities hasn't been initialized.");
|
||||
|
||||
DespawnAllEntitiesCommand queueEntry;
|
||||
queueEntry.m_ticket = &ticket;
|
||||
queueEntry.m_completionCallback = AZStd::move(completionCallback);
|
||||
{
|
||||
AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex);
|
||||
queueEntry.m_ticketId = GetTicketPayload<Ticket>(ticket).m_nextTicketId++;
|
||||
m_pendingRequestQueue.push(AZStd::move(queueEntry));
|
||||
}
|
||||
queueEntry.m_ticketId = ticket.GetId();
|
||||
queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback);
|
||||
QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry));
|
||||
}
|
||||
|
||||
void SpawnableEntitiesManager::ReloadSpawnable(EntitySpawnTicket& ticket, AZ::Data::Asset<Spawnable> spawnable,
|
||||
ReloadSpawnableCallback completionCallback)
|
||||
void SpawnableEntitiesManager::ReloadSpawnable(
|
||||
EntitySpawnTicket& ticket, AZ::Data::Asset<Spawnable> spawnable, ReloadSpawnableOptionalArgs optionalArgs)
|
||||
{
|
||||
AZ_Assert(ticket.IsValid(), "Ticket provided to ReloadSpawnable hasn't been initialized.");
|
||||
|
||||
ReloadSpawnableCommand queueEntry;
|
||||
queueEntry.m_ticket = &ticket;
|
||||
queueEntry.m_ticketId = ticket.GetId();
|
||||
queueEntry.m_spawnable = AZStd::move(spawnable);
|
||||
queueEntry.m_completionCallback = AZStd::move(completionCallback);
|
||||
{
|
||||
AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex);
|
||||
queueEntry.m_ticketId = GetTicketPayload<Ticket>(ticket).m_nextTicketId++;
|
||||
m_pendingRequestQueue.push(AZStd::move(queueEntry));
|
||||
}
|
||||
queueEntry.m_serializeContext =
|
||||
optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext;
|
||||
queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback);
|
||||
QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry));
|
||||
}
|
||||
|
||||
void SpawnableEntitiesManager::ListEntities(EntitySpawnTicket& ticket, ListEntitiesCallback listCallback)
|
||||
void SpawnableEntitiesManager::ListEntities(
|
||||
EntitySpawnTicket& ticket, ListEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs)
|
||||
{
|
||||
AZ_Assert(listCallback, "ListEntities called on spawnable entities without a valid callback to use.");
|
||||
AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized.");
|
||||
|
||||
ListEntitiesCommand queueEntry;
|
||||
queueEntry.m_ticket = &ticket;
|
||||
queueEntry.m_ticketId = ticket.GetId();
|
||||
queueEntry.m_listCallback = AZStd::move(listCallback);
|
||||
{
|
||||
AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex);
|
||||
queueEntry.m_ticketId = GetTicketPayload<Ticket>(ticket).m_nextTicketId++;
|
||||
m_pendingRequestQueue.push(AZStd::move(queueEntry));
|
||||
}
|
||||
QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry));
|
||||
}
|
||||
|
||||
void SpawnableEntitiesManager::ListIndicesAndEntities(EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback)
|
||||
void SpawnableEntitiesManager::ListIndicesAndEntities(
|
||||
EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs)
|
||||
{
|
||||
AZ_Assert(listCallback, "ListEntities called on spawnable entities without a valid callback to use.");
|
||||
AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized.");
|
||||
|
||||
ListIndicesEntitiesCommand queueEntry;
|
||||
queueEntry.m_ticket = &ticket;
|
||||
queueEntry.m_ticketId = ticket.GetId();
|
||||
queueEntry.m_listCallback = AZStd::move(listCallback);
|
||||
{
|
||||
AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex);
|
||||
queueEntry.m_ticketId = GetTicketPayload<Ticket>(ticket).m_nextTicketId++;
|
||||
m_pendingRequestQueue.push(AZStd::move(queueEntry));
|
||||
}
|
||||
QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry));
|
||||
}
|
||||
|
||||
void SpawnableEntitiesManager::ClaimEntities(EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback)
|
||||
void SpawnableEntitiesManager::ClaimEntities(
|
||||
EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback, ClaimEntitiesOptionalArgs optionalArgs)
|
||||
{
|
||||
AZ_Assert(listCallback, "ClaimEntities called on spawnable entities without a valid callback to use.");
|
||||
AZ_Assert(ticket.IsValid(), "Ticket provided to ClaimEntities hasn't been initialized.");
|
||||
|
||||
ClaimEntitiesCommand queueEntry;
|
||||
queueEntry.m_ticket = &ticket;
|
||||
queueEntry.m_ticketId = ticket.GetId();
|
||||
queueEntry.m_listCallback = AZStd::move(listCallback);
|
||||
{
|
||||
AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex);
|
||||
queueEntry.m_ticketId = GetTicketPayload<Ticket>(ticket).m_nextTicketId++;
|
||||
m_pendingRequestQueue.push(AZStd::move(queueEntry));
|
||||
}
|
||||
QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry));
|
||||
}
|
||||
|
||||
void SpawnableEntitiesManager::Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback)
|
||||
void SpawnableEntitiesManager::Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback, BarrierOptionalArgs optionalArgs)
|
||||
{
|
||||
AZ_Assert(completionCallback, "Barrier on spawnable entities called without a valid callback to use.");
|
||||
AZ_Assert(ticket.IsValid(), "Ticket provided to Barrier hasn't been initialized.");
|
||||
|
||||
BarrierCommand queueEntry;
|
||||
queueEntry.m_ticket = &ticket;
|
||||
queueEntry.m_ticketId = ticket.GetId();
|
||||
queueEntry.m_completionCallback = AZStd::move(completionCallback);
|
||||
{
|
||||
AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex);
|
||||
queueEntry.m_ticketId = GetTicketPayload<Ticket>(ticket).m_nextTicketId++;
|
||||
m_pendingRequestQueue.push(AZStd::move(queueEntry));
|
||||
}
|
||||
QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry));
|
||||
}
|
||||
|
||||
void SpawnableEntitiesManager::AddOnSpawnedHandler(AZ::Event<AZ::Data::Asset<Spawnable>>::Handler& handler)
|
||||
@@ -156,69 +160,90 @@ namespace AzFramework
|
||||
handler.Connect(m_onDespawnedEvent);
|
||||
}
|
||||
|
||||
auto SpawnableEntitiesManager::ProcessQueue() -> CommandQueueStatus
|
||||
auto SpawnableEntitiesManager::ProcessQueue(CommandQueuePriority priority) -> CommandQueueStatus
|
||||
{
|
||||
AZStd::queue<Requests> pendingRequestQueue;
|
||||
CommandQueueStatus result = CommandQueueStatus::NoCommandsLeft;
|
||||
if ((priority & CommandQueuePriority::High) == CommandQueuePriority::High)
|
||||
{
|
||||
AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex);
|
||||
m_pendingRequestQueue.swap(pendingRequestQueue);
|
||||
if (ProcessQueue(m_highPriorityQueue) == CommandQueueStatus::HasCommandsLeft)
|
||||
{
|
||||
result = CommandQueueStatus::HasCommandsLeft;
|
||||
}
|
||||
}
|
||||
if ((priority & CommandQueuePriority::Regular) == CommandQueuePriority::Regular)
|
||||
{
|
||||
if (ProcessQueue(m_regularPriorityQueue) == CommandQueueStatus::HasCommandsLeft)
|
||||
{
|
||||
result = CommandQueueStatus::HasCommandsLeft;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
auto SpawnableEntitiesManager::ProcessQueue(Queue& queue) -> CommandQueueStatus
|
||||
{
|
||||
// Process delayed requests first.
|
||||
// Only process the requests that are currently in this queue, not the ones that could be re-added if they still can't complete.
|
||||
size_t delayedSize = queue.m_delayed.size();
|
||||
for (size_t i = 0; i < delayedSize; ++i)
|
||||
{
|
||||
Requests& request = queue.m_delayed.front();
|
||||
bool result = AZStd::visit(
|
||||
[this](auto&& args) -> bool
|
||||
{
|
||||
return ProcessRequest(args);
|
||||
},
|
||||
request);
|
||||
if (!result)
|
||||
{
|
||||
queue.m_delayed.emplace_back(AZStd::move(request));
|
||||
}
|
||||
queue.m_delayed.pop_front();
|
||||
}
|
||||
|
||||
if (!pendingRequestQueue.empty() || !m_delayedQueue.empty())
|
||||
// Process newly added requests.
|
||||
while (true)
|
||||
{
|
||||
AZ::SerializeContext* serializeContext = nullptr;
|
||||
AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
|
||||
AZ_Assert(serializeContext, "Failed to retrieve serialization context.");
|
||||
|
||||
// Only process the requests that are currently in this queue, not the ones that could be re-added if they still can't complete.
|
||||
size_t delayedSize = m_delayedQueue.size();
|
||||
for (size_t i = 0; i < delayedSize; ++i)
|
||||
AZStd::queue<Requests> pendingRequestQueue;
|
||||
{
|
||||
Requests& request = m_delayedQueue.front();
|
||||
bool result = AZStd::visit([this, serializeContext](auto&& args) -> bool
|
||||
{
|
||||
return ProcessRequest(args, *serializeContext);
|
||||
}, request);
|
||||
if (!result)
|
||||
{
|
||||
m_delayedQueue.emplace_back(AZStd::move(request));
|
||||
}
|
||||
m_delayedQueue.pop_front();
|
||||
AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex);
|
||||
queue.m_pendingRequest.swap(pendingRequestQueue);
|
||||
}
|
||||
|
||||
do
|
||||
if (!pendingRequestQueue.empty())
|
||||
{
|
||||
while (!pendingRequestQueue.empty())
|
||||
{
|
||||
Requests& request = pendingRequestQueue.front();
|
||||
bool result = AZStd::visit([this, serializeContext](auto&& args) -> bool
|
||||
bool result = AZStd::visit(
|
||||
[this](auto&& args) -> bool
|
||||
{
|
||||
return ProcessRequest(args, *serializeContext);
|
||||
}, request);
|
||||
return ProcessRequest(args);
|
||||
},
|
||||
request);
|
||||
if (!result)
|
||||
{
|
||||
m_delayedQueue.emplace_back(AZStd::move(request));
|
||||
queue.m_delayed.emplace_back(AZStd::move(request));
|
||||
}
|
||||
pendingRequestQueue.pop();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
// Spawning entities can result in more entities being queued to spawn. Repeat spawning until the queue is
|
||||
// empty to avoid a chain of entity spawning getting dragged out over multiple frames.
|
||||
{
|
||||
AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex);
|
||||
m_pendingRequestQueue.swap(pendingRequestQueue);
|
||||
}
|
||||
} while (!pendingRequestQueue.empty());
|
||||
}
|
||||
|
||||
return m_delayedQueue.empty() ? CommandQueueStatus::NoCommandLeft : CommandQueueStatus::HasCommandsLeft;
|
||||
return queue.m_delayed.empty() ? CommandQueueStatus::NoCommandsLeft : CommandQueueStatus::HasCommandsLeft;
|
||||
}
|
||||
|
||||
void* SpawnableEntitiesManager::CreateTicket(AZ::Data::Asset<Spawnable>&& spawnable)
|
||||
AZStd::pair<uint64_t, void*> SpawnableEntitiesManager::CreateTicket(AZ::Data::Asset<Spawnable>&& spawnable)
|
||||
{
|
||||
static AZStd::atomic_uint64_t idCounter { 1 };
|
||||
|
||||
auto result = aznew Ticket();
|
||||
result->m_spawnable = AZStd::move(spawnable);
|
||||
return result;
|
||||
return AZStd::make_pair<EntitySpawnTicket::Id, void*>(idCounter++, result);
|
||||
}
|
||||
|
||||
void SpawnableEntitiesManager::DestroyTicket(void* ticket)
|
||||
@@ -226,33 +251,23 @@ namespace AzFramework
|
||||
DestroyTicketCommand queueEntry;
|
||||
queueEntry.m_ticket = reinterpret_cast<Ticket*>(ticket);
|
||||
{
|
||||
AZStd::scoped_lock queueLock(m_pendingRequestQueueMutex);
|
||||
queueEntry.m_ticketId = reinterpret_cast<Ticket*>(ticket)->m_nextTicketId++;
|
||||
m_pendingRequestQueue.push(AZStd::move(queueEntry));
|
||||
AZStd::scoped_lock queueLock(m_regularPriorityQueue.m_pendingRequestMutex);
|
||||
queueEntry.m_requestId = reinterpret_cast<Ticket*>(ticket)->m_nextRequestId++;
|
||||
m_regularPriorityQueue.m_pendingRequest.push(AZStd::move(queueEntry));
|
||||
}
|
||||
}
|
||||
|
||||
AZ::Entity* SpawnableEntitiesManager::SpawnSingleEntity(const AZ::Entity& entityTemplate, AZ::SerializeContext& serializeContext)
|
||||
{
|
||||
AZ::Entity* clone = serializeContext.CloneObject(&entityTemplate);
|
||||
AZ_Assert(clone != nullptr, "Failed to clone spawnable entity.");
|
||||
clone->SetId(AZ::Entity::MakeId());
|
||||
|
||||
GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, clone);
|
||||
return clone;
|
||||
}
|
||||
|
||||
AZ::Entity* SpawnableEntitiesManager::CloneSingleEntity(const AZ::Entity& entityTemplate,
|
||||
EntityIdMap& templateToCloneEntityIdMap, AZ::SerializeContext& serializeContext)
|
||||
EntityIdMap& templateToCloneMap, AZ::SerializeContext& serializeContext)
|
||||
{
|
||||
return AZ::IdUtils::Remapper<AZ::EntityId>::CloneObjectAndGenerateNewIdsAndFixRefs(
|
||||
&entityTemplate, templateToCloneEntityIdMap, &serializeContext);
|
||||
return AZ::IdUtils::Remapper<AZ::EntityId, true>::CloneObjectAndGenerateNewIdsAndFixRefs(
|
||||
&entityTemplate, templateToCloneMap, &serializeContext);
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::ProcessRequest(SpawnAllEntitiesCommand& request, AZ::SerializeContext& serializeContext)
|
||||
bool SpawnableEntitiesManager::ProcessRequest(SpawnAllEntitiesCommand& request)
|
||||
{
|
||||
Ticket& ticket = GetTicketPayload<Ticket>(*request.m_ticket);
|
||||
if (ticket.m_spawnable.IsReady() && request.m_ticketId == ticket.m_currentTicketId)
|
||||
Ticket& ticket = *request.m_ticket;
|
||||
if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId)
|
||||
{
|
||||
AZStd::vector<AZ::Entity*>& spawnedEntities = ticket.m_spawnedEntities;
|
||||
AZStd::vector<size_t>& spawnedEntityIndices = ticket.m_spawnedEntityIndices;
|
||||
@@ -273,13 +288,9 @@ namespace AzFramework
|
||||
spawnedEntityIndices.reserve(spawnedEntityIndices.size() + entitiesToSpawnSize);
|
||||
templateToCloneEntityIdMap.reserve(entitiesToSpawnSize);
|
||||
|
||||
// Mark all indices as spawned
|
||||
for (size_t i = 0; i < entitiesToSpawnSize; ++i)
|
||||
{
|
||||
const AZ::Entity& entityTemplate = *entitiesToSpawn[i];
|
||||
|
||||
AZ::Entity* clone = CloneSingleEntity(entityTemplate, templateToCloneEntityIdMap, serializeContext);
|
||||
|
||||
AZ::Entity* clone = CloneSingleEntity(*entitiesToSpawn[i], templateToCloneEntityIdMap, *request.m_serializeContext);
|
||||
AZ_Assert(clone != nullptr, "Failed to clone spawnable entity.");
|
||||
|
||||
spawnedEntities.emplace_back(clone);
|
||||
@@ -287,40 +298,31 @@ namespace AzFramework
|
||||
}
|
||||
|
||||
// loadAll is true if every entity has been spawned only once
|
||||
if (spawnedEntities.size() == entitiesToSpawnSize)
|
||||
{
|
||||
ticket.m_loadAll = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Case where there were already spawns from a previous request
|
||||
ticket.m_loadAll = false;
|
||||
}
|
||||
|
||||
ticket.m_loadAll = (spawnedEntities.size() == entitiesToSpawnSize);
|
||||
|
||||
// Let other systems know about newly spawned entities for any pre-processing before adding to the scene/game context.
|
||||
if (request.m_preInsertionCallback)
|
||||
{
|
||||
request.m_preInsertionCallback(*request.m_ticket, SpawnableEntityContainerView(
|
||||
request.m_preInsertionCallback(request.m_ticketId, SpawnableEntityContainerView(
|
||||
ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end()));
|
||||
}
|
||||
|
||||
// Add to the game context, now the entities are active
|
||||
AZStd::for_each(ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end(),
|
||||
[](AZ::Entity* entity)
|
||||
for (auto it = ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount; it != ticket.m_spawnedEntities.end(); ++it)
|
||||
{
|
||||
GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, entity);
|
||||
});
|
||||
GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, *it);
|
||||
}
|
||||
|
||||
// Let other systems know about newly spawned entities for any post-processing after adding to the scene/game context.
|
||||
if (request.m_completionCallback)
|
||||
{
|
||||
request.m_completionCallback(*request.m_ticket, SpawnableConstEntityContainerView(
|
||||
request.m_completionCallback(request.m_ticketId, SpawnableConstEntityContainerView(
|
||||
ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end()));
|
||||
}
|
||||
|
||||
m_onSpawnedEvent.Signal(ticket.m_spawnable);
|
||||
|
||||
ticket.m_currentTicketId++;
|
||||
ticket.m_currentRequestId++;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
@@ -329,21 +331,41 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::ProcessRequest(SpawnEntitiesCommand& request, AZ::SerializeContext& serializeContext)
|
||||
bool SpawnableEntitiesManager::ProcessRequest(SpawnEntitiesCommand& request)
|
||||
{
|
||||
Ticket& ticket = GetTicketPayload<Ticket>(*request.m_ticket);
|
||||
if (ticket.m_spawnable.IsReady() && request.m_ticketId == ticket.m_currentTicketId)
|
||||
Ticket& ticket = *request.m_ticket;
|
||||
if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId)
|
||||
{
|
||||
AZStd::vector<AZ::Entity*>& spawnedEntities = ticket.m_spawnedEntities;
|
||||
AZStd::vector<size_t>& spawnedEntityIndices = ticket.m_spawnedEntityIndices;
|
||||
AZ_Assert(
|
||||
spawnedEntities.size() == spawnedEntityIndices.size(),
|
||||
"The indices for the spawned entities has gone out of sync with the entities.");
|
||||
|
||||
// Keep track how many entities there were in the array initially
|
||||
// Keep track of how many entities there were in the array initially
|
||||
size_t spawnedEntitiesInitialCount = spawnedEntities.size();
|
||||
|
||||
// These are 'template' entities we'll be cloning from
|
||||
const Spawnable::EntityList& entitiesToSpawn = ticket.m_spawnable->GetEntities();
|
||||
size_t entitiesToSpawnSize = request.m_entityIndices.size();
|
||||
|
||||
// Reconstruct the template to entity mapping.
|
||||
EntityIdMap templateToCloneEntityIdMap;
|
||||
if (!request.m_referencePreviouslySpawnedEntities)
|
||||
{
|
||||
templateToCloneEntityIdMap.reserve(entitiesToSpawnSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
templateToCloneEntityIdMap.reserve(spawnedEntitiesInitialCount + entitiesToSpawnSize);
|
||||
SpawnableConstIndexEntityContainerView indexEntityView(
|
||||
spawnedEntities.begin(), spawnedEntityIndices.begin(), spawnedEntities.size());
|
||||
for (auto& entry : indexEntityView)
|
||||
{
|
||||
templateToCloneEntityIdMap.insert_or_assign(entitiesToSpawn[entry.GetIndex()]->GetId(), entry.GetEntity()->GetId());
|
||||
}
|
||||
}
|
||||
|
||||
spawnedEntities.reserve(spawnedEntities.size() + entitiesToSpawnSize);
|
||||
spawnedEntityIndices.reserve(spawnedEntityIndices.size() + entitiesToSpawnSize);
|
||||
|
||||
@@ -351,15 +373,11 @@ namespace AzFramework
|
||||
{
|
||||
if (index < entitiesToSpawn.size())
|
||||
{
|
||||
const AZ::Entity& entityTemplate = *entitiesToSpawn[index];
|
||||
|
||||
AZ::Entity* clone = serializeContext.CloneObject(&entityTemplate);
|
||||
AZ::Entity* clone = CloneSingleEntity(*entitiesToSpawn[index], templateToCloneEntityIdMap, *request.m_serializeContext);
|
||||
AZ_Assert(clone != nullptr, "Failed to clone spawnable entity.");
|
||||
clone->SetId(AZ::Entity::MakeId());
|
||||
|
||||
spawnedEntities.push_back(clone);
|
||||
spawnedEntityIndices.push_back(index);
|
||||
|
||||
}
|
||||
}
|
||||
ticket.m_loadAll = false;
|
||||
@@ -367,28 +385,25 @@ namespace AzFramework
|
||||
// Let other systems know about newly spawned entities for any pre-processing before adding to the scene/game context.
|
||||
if (request.m_preInsertionCallback)
|
||||
{
|
||||
request.m_preInsertionCallback(
|
||||
*request.m_ticket,
|
||||
SpawnableEntityContainerView(
|
||||
request.m_preInsertionCallback(request.m_ticketId, SpawnableEntityContainerView(
|
||||
ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end()));
|
||||
}
|
||||
|
||||
// Add to the game context, now the entities are active
|
||||
AZStd::for_each(ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end(),
|
||||
[](AZ::Entity* entity)
|
||||
for (auto it = ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount; it != ticket.m_spawnedEntities.end(); ++it)
|
||||
{
|
||||
GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, entity);
|
||||
});
|
||||
GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, *it);
|
||||
}
|
||||
|
||||
if (request.m_completionCallback)
|
||||
{
|
||||
request.m_completionCallback(*request.m_ticket, SpawnableConstEntityContainerView(
|
||||
request.m_completionCallback(request.m_ticketId, SpawnableConstEntityContainerView(
|
||||
ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end()));
|
||||
}
|
||||
|
||||
m_onSpawnedEvent.Signal(ticket.m_spawnable);
|
||||
|
||||
ticket.m_currentTicketId++;
|
||||
ticket.m_currentRequestId++;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
@@ -397,11 +412,10 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::ProcessRequest(DespawnAllEntitiesCommand& request,
|
||||
[[maybe_unused]] AZ::SerializeContext& serializeContext)
|
||||
bool SpawnableEntitiesManager::ProcessRequest(DespawnAllEntitiesCommand& request)
|
||||
{
|
||||
Ticket& ticket = GetTicketPayload<Ticket>(*request.m_ticket);
|
||||
if (request.m_ticketId == ticket.m_currentTicketId)
|
||||
Ticket& ticket = *request.m_ticket;
|
||||
if (request.m_requestId == ticket.m_currentRequestId)
|
||||
{
|
||||
for (AZ::Entity* entity : ticket.m_spawnedEntities)
|
||||
{
|
||||
@@ -417,12 +431,12 @@ namespace AzFramework
|
||||
|
||||
if (request.m_completionCallback)
|
||||
{
|
||||
request.m_completionCallback(*request.m_ticket);
|
||||
request.m_completionCallback(request.m_ticketId);
|
||||
}
|
||||
|
||||
m_onDespawnedEvent.Signal(ticket.m_spawnable);
|
||||
|
||||
ticket.m_currentTicketId++;
|
||||
ticket.m_currentRequestId++;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
@@ -431,13 +445,13 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::ProcessRequest(ReloadSpawnableCommand& request, AZ::SerializeContext& serializeContext)
|
||||
bool SpawnableEntitiesManager::ProcessRequest(ReloadSpawnableCommand& request)
|
||||
{
|
||||
Ticket& ticket = GetTicketPayload<Ticket>(*request.m_ticket);
|
||||
Ticket& ticket = *request.m_ticket;
|
||||
AZ_Assert(ticket.m_spawnable.GetId() == request.m_spawnable.GetId(),
|
||||
"Spawnable is being reloaded, but the provided spawnable has a different asset id. "
|
||||
"This will likely result in unexpected entities being created.");
|
||||
if (ticket.m_spawnable.IsReady() && request.m_ticketId == ticket.m_currentTicketId)
|
||||
if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId)
|
||||
{
|
||||
// Delete the original entities.
|
||||
for (AZ::Entity* entity : ticket.m_spawnedEntities)
|
||||
@@ -454,50 +468,54 @@ namespace AzFramework
|
||||
// Rebuild the list of entities.
|
||||
ticket.m_spawnedEntities.clear();
|
||||
const Spawnable::EntityList& entities = request.m_spawnable->GetEntities();
|
||||
|
||||
// Map keeps track of ids from template (spawnable) to clone (instance)
|
||||
// Allowing patch ups of fields referring to entityIds outside of a given entity
|
||||
EntityIdMap templateToCloneEntityIdMap;
|
||||
|
||||
if (ticket.m_loadAll)
|
||||
{
|
||||
// The new spawnable may have a different number of entities and since the intent of the user was
|
||||
// to load every, simply start over.
|
||||
// to spawn every entity, simply start over.
|
||||
ticket.m_spawnedEntityIndices.clear();
|
||||
|
||||
size_t entitiesToSpawnSize = entities.size();
|
||||
|
||||
// Map keeps track of ids from template (spawnable) to clone (instance)
|
||||
// Allowing patch ups of fields referring to entityIds outside of a given entity
|
||||
EntityIdMap templateToCloneEntityIdMap;
|
||||
templateToCloneEntityIdMap.reserve(entitiesToSpawnSize);
|
||||
|
||||
// Mark all indices as spawned
|
||||
for (size_t i = 0; i < entitiesToSpawnSize; ++i)
|
||||
{
|
||||
const AZ::Entity& entityTemplate = *entities[i];
|
||||
|
||||
AZ::Entity* clone = CloneSingleEntity(entityTemplate, templateToCloneEntityIdMap, serializeContext);
|
||||
|
||||
AZ::Entity* clone = CloneSingleEntity(*entities[i], templateToCloneEntityIdMap, *request.m_serializeContext);
|
||||
AZ_Assert(clone != nullptr, "Failed to clone spawnable entity.");
|
||||
|
||||
ticket.m_spawnedEntities.emplace_back(clone);
|
||||
ticket.m_spawnedEntities.push_back(clone);
|
||||
ticket.m_spawnedEntityIndices.push_back(i);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
size_t entitiesSize = entities.size();
|
||||
templateToCloneEntityIdMap.reserve(entitiesSize);
|
||||
for (size_t index : ticket.m_spawnedEntityIndices)
|
||||
{
|
||||
ticket.m_spawnedEntities.push_back(
|
||||
index < entitiesSize ? SpawnSingleEntity(*entities[index], serializeContext) : nullptr);
|
||||
// It's possible for the new spawnable to have a different number of entities, so guard against this.
|
||||
// It's also possible that the entities have moved within the spawnable to a new index. This can't be
|
||||
// detected and will result in the incorrect entities being spawned.
|
||||
if (index < entitiesSize)
|
||||
{
|
||||
AZ::Entity* clone = CloneSingleEntity(*entities[index], templateToCloneEntityIdMap, *request.m_serializeContext);
|
||||
AZ_Assert(clone != nullptr, "Failed to clone spawnable entity.");
|
||||
ticket.m_spawnedEntities.push_back(clone);
|
||||
}
|
||||
}
|
||||
}
|
||||
ticket.m_spawnable = AZStd::move(request.m_spawnable);
|
||||
|
||||
if (request.m_completionCallback)
|
||||
{
|
||||
request.m_completionCallback(*request.m_ticket, SpawnableConstEntityContainerView(
|
||||
request.m_completionCallback(request.m_ticketId, SpawnableConstEntityContainerView(
|
||||
ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end()));
|
||||
}
|
||||
|
||||
ticket.m_currentTicketId++;
|
||||
ticket.m_currentRequestId++;
|
||||
|
||||
m_onSpawnedEvent.Signal(ticket.m_spawnable);
|
||||
|
||||
@@ -509,14 +527,14 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::ProcessRequest(ListEntitiesCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext)
|
||||
bool SpawnableEntitiesManager::ProcessRequest(ListEntitiesCommand& request)
|
||||
{
|
||||
Ticket& ticket = GetTicketPayload<Ticket>(*request.m_ticket);
|
||||
if (request.m_ticketId == ticket.m_currentTicketId)
|
||||
Ticket& ticket = *request.m_ticket;
|
||||
if (request.m_requestId == ticket.m_currentRequestId)
|
||||
{
|
||||
request.m_listCallback(*request.m_ticket, SpawnableConstEntityContainerView(
|
||||
request.m_listCallback(request.m_ticketId, SpawnableConstEntityContainerView(
|
||||
ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end()));
|
||||
ticket.m_currentTicketId++;
|
||||
ticket.m_currentRequestId++;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
@@ -525,19 +543,17 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::ProcessRequest(ListIndicesEntitiesCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext)
|
||||
bool SpawnableEntitiesManager::ProcessRequest(ListIndicesEntitiesCommand& request)
|
||||
{
|
||||
Ticket& ticket = GetTicketPayload<Ticket>(*request.m_ticket);
|
||||
if (request.m_ticketId == ticket.m_currentTicketId)
|
||||
Ticket& ticket = *request.m_ticket;
|
||||
if (request.m_requestId == ticket.m_currentRequestId)
|
||||
{
|
||||
AZ_Assert(
|
||||
ticket.m_spawnedEntities.size() == ticket.m_spawnedEntityIndices.size(),
|
||||
"Entities and indices on spawnable ticket have gone out of sync.");
|
||||
request.m_listCallback(
|
||||
*request.m_ticket,
|
||||
SpawnableConstIndexEntityContainerView(
|
||||
request.m_listCallback(request.m_ticketId, SpawnableConstIndexEntityContainerView(
|
||||
ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntityIndices.begin(), ticket.m_spawnedEntities.size()));
|
||||
ticket.m_currentTicketId++;
|
||||
ticket.m_currentRequestId++;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
@@ -546,18 +562,18 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::ProcessRequest(ClaimEntitiesCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext)
|
||||
bool SpawnableEntitiesManager::ProcessRequest(ClaimEntitiesCommand& request)
|
||||
{
|
||||
Ticket& ticket = GetTicketPayload<Ticket>(*request.m_ticket);
|
||||
if (request.m_ticketId == ticket.m_currentTicketId)
|
||||
Ticket& ticket = *request.m_ticket;
|
||||
if (request.m_requestId == ticket.m_currentRequestId)
|
||||
{
|
||||
request.m_listCallback(*request.m_ticket, SpawnableEntityContainerView(
|
||||
request.m_listCallback(request.m_ticketId, SpawnableEntityContainerView(
|
||||
ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end()));
|
||||
|
||||
ticket.m_spawnedEntities.clear();
|
||||
ticket.m_spawnedEntityIndices.clear();
|
||||
|
||||
ticket.m_currentTicketId++;
|
||||
ticket.m_currentRequestId++;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
@@ -566,17 +582,17 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::ProcessRequest(BarrierCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext)
|
||||
bool SpawnableEntitiesManager::ProcessRequest(BarrierCommand& request)
|
||||
{
|
||||
Ticket& ticket = GetTicketPayload<Ticket>(*request.m_ticket);
|
||||
if (request.m_ticketId == ticket.m_currentTicketId)
|
||||
Ticket& ticket = *request.m_ticket;
|
||||
if (request.m_requestId == ticket.m_currentRequestId)
|
||||
{
|
||||
if (request.m_completionCallback)
|
||||
{
|
||||
request.m_completionCallback(*request.m_ticket);
|
||||
request.m_completionCallback(request.m_ticketId);
|
||||
}
|
||||
|
||||
ticket.m_currentTicketId++;
|
||||
ticket.m_currentRequestId++;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
@@ -585,9 +601,9 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::ProcessRequest(DestroyTicketCommand& request, [[maybe_unused]] AZ::SerializeContext& serializeContext)
|
||||
bool SpawnableEntitiesManager::ProcessRequest(DestroyTicketCommand& request)
|
||||
{
|
||||
if (request.m_ticketId == request.m_ticket->m_currentTicketId)
|
||||
if (request.m_requestId == request.m_ticket->m_currentRequestId)
|
||||
{
|
||||
for (AZ::Entity* entity : request.m_ticket->m_spawnedEntities)
|
||||
{
|
||||
@@ -606,24 +622,4 @@ namespace AzFramework
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::IsEqualTicket(const EntitySpawnTicket* lhs, const EntitySpawnTicket* rhs)
|
||||
{
|
||||
return GetTicketPayload<Ticket>(lhs) == GetTicketPayload<Ticket>(rhs);
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::IsEqualTicket(const Ticket* lhs, const EntitySpawnTicket* rhs)
|
||||
{
|
||||
return lhs == GetTicketPayload<Ticket>(rhs);
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::IsEqualTicket(const EntitySpawnTicket* lhs, const Ticket* rhs)
|
||||
{
|
||||
return GetTicketPayload<Ticket>(lhs) == rhs;
|
||||
}
|
||||
|
||||
bool SpawnableEntitiesManager::IsEqualTicket(const Ticket* lhs, const Ticket* rhs)
|
||||
{
|
||||
return lhs = rhs;
|
||||
}
|
||||
} // namespace AzFramework
|
||||
|
||||
@@ -29,8 +29,6 @@ namespace AZ
|
||||
|
||||
namespace AzFramework
|
||||
{
|
||||
using EntityIdMap = AZStd::unordered_map<AZ::EntityId, AZ::EntityId>;
|
||||
|
||||
class SpawnableEntitiesManager
|
||||
: public SpawnableEntitiesInterface::Registrar
|
||||
{
|
||||
@@ -38,31 +36,42 @@ namespace AzFramework
|
||||
AZ_RTTI(AzFramework::SpawnableEntitiesManager, "{6E14333F-128C-464C-94CA-A63B05A5E51C}");
|
||||
AZ_CLASS_ALLOCATOR(SpawnableEntitiesManager, AZ::SystemAllocator, 0);
|
||||
|
||||
using EntityIdMap = AZStd::unordered_map<AZ::EntityId, AZ::EntityId>;
|
||||
|
||||
enum class CommandQueueStatus : bool
|
||||
{
|
||||
HasCommandsLeft,
|
||||
NoCommandLeft
|
||||
NoCommandsLeft
|
||||
};
|
||||
|
||||
enum class CommandQueuePriority
|
||||
{
|
||||
High = 1 << 0,
|
||||
Regular = 1 << 1
|
||||
};
|
||||
|
||||
SpawnableEntitiesManager();
|
||||
~SpawnableEntitiesManager() override = default;
|
||||
|
||||
//
|
||||
// The following functions are thread safe
|
||||
//
|
||||
|
||||
void SpawnAllEntities(EntitySpawnTicket& ticket, EntityPreInsertionCallback preInsertionCallback = {}, EntitySpawnCallback completionCallback = {}) override;
|
||||
void SpawnEntities(EntitySpawnTicket& ticket, AZStd::vector<size_t> entityIndices, EntityPreInsertionCallback preInsertionCallback = {},
|
||||
EntitySpawnCallback completionCallback = {}) override;
|
||||
void DespawnAllEntities(EntitySpawnTicket& ticket, EntityDespawnCallback completionCallback = {}) override;
|
||||
void SpawnAllEntities(EntitySpawnTicket& ticket, SpawnAllEntitiesOptionalArgs optionalArgs = {}) override;
|
||||
void SpawnEntities(
|
||||
EntitySpawnTicket& ticket, AZStd::vector<size_t> entityIndices, SpawnEntitiesOptionalArgs optionalArgs = {}) override;
|
||||
void DespawnAllEntities(EntitySpawnTicket& ticket, DespawnAllEntitiesOptionalArgs optionalArgs = {}) override;
|
||||
void ReloadSpawnable(
|
||||
EntitySpawnTicket& ticket, AZ::Data::Asset<Spawnable> spawnable, ReloadSpawnableOptionalArgs optionalArgs = {}) override;
|
||||
|
||||
void ReloadSpawnable(EntitySpawnTicket& ticket, AZ::Data::Asset<Spawnable> spawnable,
|
||||
ReloadSpawnableCallback completionCallback = {}) override;
|
||||
void ListEntities(
|
||||
EntitySpawnTicket& ticket, ListEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs = {}) override;
|
||||
void ListIndicesAndEntities(
|
||||
EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs = {}) override;
|
||||
void ClaimEntities(
|
||||
EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback, ClaimEntitiesOptionalArgs optionalArgs = {}) override;
|
||||
|
||||
void ListEntities(EntitySpawnTicket& ticket, ListEntitiesCallback listCallback) override;
|
||||
void ListIndicesAndEntities(EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback) override;
|
||||
void ClaimEntities(EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback) override;
|
||||
|
||||
void Barrier(EntitySpawnTicket& spawnInfo, BarrierCallback completionCallback) override;
|
||||
void Barrier(EntitySpawnTicket& spawnInfo, BarrierCallback completionCallback, BarrierOptionalArgs optionalArgs = {}) override;
|
||||
|
||||
void AddOnSpawnedHandler(AZ::Event<AZ::Data::Asset<Spawnable>>::Handler& handler) override;
|
||||
void AddOnDespawnedHandler(AZ::Event<AZ::Data::Asset<Spawnable>>::Handler& handler) override;
|
||||
@@ -71,13 +80,9 @@ namespace AzFramework
|
||||
// The following function is thread safe but intended to be run from the main thread.
|
||||
//
|
||||
|
||||
CommandQueueStatus ProcessQueue();
|
||||
CommandQueueStatus ProcessQueue(CommandQueuePriority priority);
|
||||
|
||||
protected:
|
||||
void* CreateTicket(AZ::Data::Asset<Spawnable>&& spawnable) override;
|
||||
void DestroyTicket(void* ticket) override;
|
||||
|
||||
private:
|
||||
struct Ticket
|
||||
{
|
||||
AZ_CLASS_ALLOCATOR(Ticket, AZ::ThreadPoolAllocator, 0);
|
||||
@@ -86,8 +91,8 @@ namespace AzFramework
|
||||
AZStd::vector<AZ::Entity*> m_spawnedEntities;
|
||||
AZStd::vector<size_t> m_spawnedEntityIndices;
|
||||
AZ::Data::Asset<Spawnable> m_spawnable;
|
||||
uint32_t m_nextTicketId{ 0 }; //!< Next id for this ticket.
|
||||
uint32_t m_currentTicketId{ 0 }; //!< The id for the command that should be executed.
|
||||
uint32_t m_nextRequestId{ 0 }; //!< Next id for this ticket.
|
||||
uint32_t m_currentRequestId { 0 }; //!< The id for the command that should be executed.
|
||||
bool m_loadAll{ true };
|
||||
};
|
||||
|
||||
@@ -95,90 +100,116 @@ namespace AzFramework
|
||||
{
|
||||
EntitySpawnCallback m_completionCallback;
|
||||
EntityPreInsertionCallback m_preInsertionCallback;
|
||||
EntitySpawnTicket* m_ticket;
|
||||
uint32_t m_ticketId;
|
||||
AZ::SerializeContext* m_serializeContext;
|
||||
Ticket* m_ticket;
|
||||
EntitySpawnTicket::Id m_ticketId;
|
||||
uint32_t m_requestId;
|
||||
};
|
||||
struct SpawnEntitiesCommand
|
||||
{
|
||||
AZStd::vector<size_t> m_entityIndices;
|
||||
EntitySpawnCallback m_completionCallback;
|
||||
EntityPreInsertionCallback m_preInsertionCallback;
|
||||
EntitySpawnTicket* m_ticket;
|
||||
uint32_t m_ticketId;
|
||||
AZ::SerializeContext* m_serializeContext;
|
||||
Ticket* m_ticket;
|
||||
EntitySpawnTicket::Id m_ticketId;
|
||||
uint32_t m_requestId;
|
||||
bool m_referencePreviouslySpawnedEntities;
|
||||
};
|
||||
struct DespawnAllEntitiesCommand
|
||||
{
|
||||
EntityDespawnCallback m_completionCallback;
|
||||
EntitySpawnTicket* m_ticket;
|
||||
uint32_t m_ticketId;
|
||||
Ticket* m_ticket;
|
||||
EntitySpawnTicket::Id m_ticketId;
|
||||
uint32_t m_requestId;
|
||||
};
|
||||
struct ReloadSpawnableCommand
|
||||
{
|
||||
AZ::Data::Asset<Spawnable> m_spawnable;
|
||||
ReloadSpawnableCallback m_completionCallback;
|
||||
EntitySpawnTicket* m_ticket;
|
||||
uint32_t m_ticketId;
|
||||
AZ::SerializeContext* m_serializeContext;
|
||||
Ticket* m_ticket;
|
||||
EntitySpawnTicket::Id m_ticketId;
|
||||
uint32_t m_requestId;
|
||||
};
|
||||
struct ListEntitiesCommand
|
||||
{
|
||||
ListEntitiesCallback m_listCallback;
|
||||
EntitySpawnTicket* m_ticket;
|
||||
uint32_t m_ticketId;
|
||||
Ticket* m_ticket;
|
||||
EntitySpawnTicket::Id m_ticketId;
|
||||
uint32_t m_requestId;
|
||||
};
|
||||
struct ListIndicesEntitiesCommand
|
||||
{
|
||||
ListIndicesEntitiesCallback m_listCallback;
|
||||
EntitySpawnTicket* m_ticket;
|
||||
uint32_t m_ticketId;
|
||||
Ticket* m_ticket;
|
||||
EntitySpawnTicket::Id m_ticketId;
|
||||
uint32_t m_requestId;
|
||||
};
|
||||
struct ClaimEntitiesCommand
|
||||
{
|
||||
ClaimEntitiesCallback m_listCallback;
|
||||
EntitySpawnTicket* m_ticket;
|
||||
uint32_t m_ticketId;
|
||||
Ticket* m_ticket;
|
||||
EntitySpawnTicket::Id m_ticketId;
|
||||
uint32_t m_requestId;
|
||||
};
|
||||
struct BarrierCommand
|
||||
{
|
||||
BarrierCallback m_completionCallback;
|
||||
EntitySpawnTicket* m_ticket;
|
||||
uint32_t m_ticketId;
|
||||
Ticket* m_ticket;
|
||||
EntitySpawnTicket::Id m_ticketId;
|
||||
uint32_t m_requestId;
|
||||
};
|
||||
struct DestroyTicketCommand
|
||||
{
|
||||
Ticket* m_ticket;
|
||||
uint32_t m_ticketId;
|
||||
uint32_t m_requestId;
|
||||
};
|
||||
|
||||
using Requests = AZStd::variant<
|
||||
SpawnAllEntitiesCommand, SpawnEntitiesCommand, DespawnAllEntitiesCommand, ReloadSpawnableCommand, ListEntitiesCommand,
|
||||
ListIndicesEntitiesCommand, ClaimEntitiesCommand, BarrierCommand, DestroyTicketCommand>;
|
||||
|
||||
AZ::Entity* SpawnSingleEntity(const AZ::Entity& entityTemplate,
|
||||
AZ::SerializeContext& serializeContext);
|
||||
struct Queue
|
||||
{
|
||||
AZStd::deque<Requests> m_delayed; //!< Requests that were processed before, but couldn't be completed.
|
||||
AZStd::queue<Requests> m_pendingRequest; //!< Requests waiting to be processed for the first time.
|
||||
AZStd::mutex m_pendingRequestMutex;
|
||||
};
|
||||
|
||||
AZ::Entity* CloneSingleEntity(const AZ::Entity& entityTemplate,
|
||||
EntityIdMap& templateToCloneEntityIdMap, AZ::SerializeContext& serializeContext);
|
||||
template<typename T>
|
||||
void QueueRequest(EntitySpawnTicket& ticket, SpawnablePriority priority, T&& request);
|
||||
AZStd::pair<EntitySpawnTicket::Id, void*> CreateTicket(AZ::Data::Asset<Spawnable>&& spawnable) override;
|
||||
void DestroyTicket(void* ticket) override;
|
||||
|
||||
bool ProcessRequest(SpawnAllEntitiesCommand& request, AZ::SerializeContext& serializeContext);
|
||||
bool ProcessRequest(SpawnEntitiesCommand& request, AZ::SerializeContext& serializeContext);
|
||||
bool ProcessRequest(DespawnAllEntitiesCommand& request, AZ::SerializeContext& serializeContext);
|
||||
bool ProcessRequest(ReloadSpawnableCommand& request, AZ::SerializeContext& serializeContext);
|
||||
bool ProcessRequest(ListEntitiesCommand& request, AZ::SerializeContext& serializeContext);
|
||||
bool ProcessRequest(ListIndicesEntitiesCommand& request, AZ::SerializeContext& serializeContext);
|
||||
bool ProcessRequest(ClaimEntitiesCommand& request, AZ::SerializeContext& serializeContext);
|
||||
bool ProcessRequest(BarrierCommand& request, AZ::SerializeContext& serializeContext);
|
||||
bool ProcessRequest(DestroyTicketCommand& request, AZ::SerializeContext& serializeContext);
|
||||
CommandQueueStatus ProcessQueue(Queue& queue);
|
||||
|
||||
[[nodiscard]] static bool IsEqualTicket(const EntitySpawnTicket* lhs, const EntitySpawnTicket* rhs);
|
||||
[[nodiscard]] static bool IsEqualTicket(const Ticket* lhs, const EntitySpawnTicket* rhs);
|
||||
[[nodiscard]] static bool IsEqualTicket(const EntitySpawnTicket* lhs, const Ticket* rhs);
|
||||
[[nodiscard]] static bool IsEqualTicket(const Ticket* lhs, const Ticket* rhs);
|
||||
AZ::Entity* CloneSingleEntity(
|
||||
const AZ::Entity& entityTemplate, EntityIdMap& templateToCloneMap, AZ::SerializeContext& serializeContext);
|
||||
|
||||
bool ProcessRequest(SpawnAllEntitiesCommand& request);
|
||||
bool ProcessRequest(SpawnEntitiesCommand& request);
|
||||
bool ProcessRequest(DespawnAllEntitiesCommand& request);
|
||||
bool ProcessRequest(ReloadSpawnableCommand& request);
|
||||
bool ProcessRequest(ListEntitiesCommand& request);
|
||||
bool ProcessRequest(ListIndicesEntitiesCommand& request);
|
||||
bool ProcessRequest(ClaimEntitiesCommand& request);
|
||||
bool ProcessRequest(BarrierCommand& request);
|
||||
bool ProcessRequest(DestroyTicketCommand& request);
|
||||
|
||||
AZStd::deque<Requests> m_delayedQueue; //!< Requests that were processed before, but couldn't be completed.
|
||||
AZStd::queue<Requests> m_pendingRequestQueue;
|
||||
AZStd::mutex m_pendingRequestQueueMutex;
|
||||
Queue m_highPriorityQueue;
|
||||
Queue m_regularPriorityQueue;
|
||||
|
||||
AZ::Event<AZ::Data::Asset<Spawnable>> m_onSpawnedEvent;
|
||||
AZ::Event<AZ::Data::Asset<Spawnable>> m_onDespawnedEvent;
|
||||
|
||||
AZ::SerializeContext* m_defaultSerializeContext { nullptr };
|
||||
//! The threshold used to determine if a request goes in the regular (if bigger than the value) or high priority queue (if smaller
|
||||
//! or equal to this value). The starting value of 64 is chosen as it's between default values SpawnablePriority_High and
|
||||
//! SpawnablePriority_Default which gives users a bit of room to fine tune the priorities as this value can be configured
|
||||
//! through the Settings Registry under the key "/O3DE/AzFramework/Spawnables/HighPriorityThreshold".
|
||||
SpawnablePriority m_highPriorityThreshold { 64 };
|
||||
};
|
||||
|
||||
AZ_DEFINE_ENUM_BITWISE_OPERATORS(AzFramework::SpawnableEntitiesManager::CommandQueuePriority);
|
||||
} // namespace AzFramework
|
||||
|
||||
@@ -48,10 +48,23 @@ namespace AzFramework
|
||||
|
||||
void SpawnableSystemComponent::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/)
|
||||
{
|
||||
m_entitiesManager.ProcessQueue();
|
||||
m_entitiesManager.ProcessQueue(
|
||||
SpawnableEntitiesManager::CommandQueuePriority::High | SpawnableEntitiesManager::CommandQueuePriority::Regular);
|
||||
RootSpawnableNotificationBus::ExecuteQueuedEvents();
|
||||
}
|
||||
|
||||
int SpawnableSystemComponent::GetTickOrder()
|
||||
{
|
||||
return AZ::ComponentTickBus::TICK_GAME;
|
||||
}
|
||||
|
||||
void SpawnableSystemComponent::OnSystemTick()
|
||||
{
|
||||
// Handle only high priority spawning events such as those created from network. These need to happen even if the client
|
||||
// doesn't have focus to avoid time-out issues for instance.
|
||||
m_entitiesManager.ProcessQueue(SpawnableEntitiesManager::CommandQueuePriority::High);
|
||||
}
|
||||
|
||||
void SpawnableSystemComponent::OnCatalogLoaded([[maybe_unused]] const char* catalogFile)
|
||||
{
|
||||
if (!m_catalogAvailable)
|
||||
@@ -168,7 +181,8 @@ namespace AzFramework
|
||||
SpawnableEntitiesManager::CommandQueueStatus queueStatus;
|
||||
do
|
||||
{
|
||||
queueStatus = m_entitiesManager.ProcessQueue();
|
||||
queueStatus = m_entitiesManager.ProcessQueue(
|
||||
SpawnableEntitiesManager::CommandQueuePriority::High | SpawnableEntitiesManager::CommandQueuePriority::Regular);
|
||||
} while (queueStatus == SpawnableEntitiesManager::CommandQueueStatus::HasCommandsLeft);
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ namespace AzFramework
|
||||
class SpawnableSystemComponent
|
||||
: public AZ::Component
|
||||
, public AZ::TickBus::Handler
|
||||
, public AZ::SystemTickBus::Handler
|
||||
, public AssetCatalogEventBus::Handler
|
||||
, public RootSpawnableInterface::Registrar
|
||||
, public RootSpawnableNotificationBus::Handler
|
||||
@@ -58,6 +59,13 @@ namespace AzFramework
|
||||
//
|
||||
|
||||
void OnTick(float deltaTime, AZ::ScriptTimePoint time) override;
|
||||
int GetTickOrder() override;
|
||||
|
||||
//
|
||||
// SystemTickBus
|
||||
//
|
||||
|
||||
void OnSystemTick() override;
|
||||
|
||||
//
|
||||
// AssetCatalogEventBus
|
||||
|
||||
@@ -29,7 +29,7 @@ namespace AzFramework
|
||||
AZ_CVAR(float, ed_cameraSystemOrbitDollyScrollSpeed, 0.02f, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
AZ_CVAR(float, ed_cameraSystemOrbitDollyCursorSpeed, 0.01f, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
AZ_CVAR(float, ed_cameraSystemScrollTranslateSpeed, 0.02f, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
AZ_CVAR(float, ed_cameraSystemMinOrbitDistance, 6.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
AZ_CVAR(float, ed_cameraSystemMinOrbitDistance, 10.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
AZ_CVAR(float, ed_cameraSystemMaxOrbitDistance, 50.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
AZ_CVAR(float, ed_cameraSystemLookSmoothness, 5.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
AZ_CVAR(float, ed_cameraSystemTranslateSmoothness, 5.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
@@ -37,7 +37,6 @@ namespace AzFramework
|
||||
AZ_CVAR(float, ed_cameraSystemPanSpeed, 0.01f, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
AZ_CVAR(bool, ed_cameraSystemPanInvertX, true, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
AZ_CVAR(bool, ed_cameraSystemPanInvertY, true, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
AZ_CVAR(float, ed_cameraSystemLookDeadzone, 2.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
|
||||
AZ_CVAR(
|
||||
AZ::CVarFixedString, ed_cameraSystemTranslateForwardKey, "keyboard_key_alphanumeric_W", nullptr, AZ::ConsoleFunctorFlags::Null, "");
|
||||
|
||||
@@ -128,12 +128,12 @@ namespace AzFramework
|
||||
worldPosition, CameraView(cameraState), CameraProjection(cameraState), cameraState.m_viewportSize);
|
||||
}
|
||||
|
||||
AZ::Vector3 ScreenToWorld(
|
||||
const ScreenPoint& screenPosition, const AZ::Matrix4x4& inverseCameraView,
|
||||
const AZ::Matrix4x4& inverseCameraProjection, const AZ::Vector2& viewportSize)
|
||||
AZ::Vector3 ScreenNDCToWorld(
|
||||
const AZ::Vector2& normalizedScreenPosition, const AZ::Matrix4x4& inverseCameraView,
|
||||
const AZ::Matrix4x4& inverseCameraProjection)
|
||||
{
|
||||
// convert screen space coordinates from <0, 1> to <-1,1> range
|
||||
const auto ndcPosition = NDCFromScreenPoint(screenPosition, viewportSize) * 2.0f - AZ::Vector2::CreateOne();
|
||||
const auto ndcPosition = normalizedScreenPosition * 2.0f - AZ::Vector2::CreateOne();
|
||||
|
||||
// transform ndc space position to clip space
|
||||
const auto clipSpacePosition = inverseCameraProjection * Vector2ToVector4(ndcPosition, -1.0f, 1.0f);
|
||||
@@ -145,6 +145,15 @@ namespace AzFramework
|
||||
return worldPosition;
|
||||
}
|
||||
|
||||
AZ::Vector3 ScreenToWorld(
|
||||
const ScreenPoint& screenPosition, const AZ::Matrix4x4& inverseCameraView,
|
||||
const AZ::Matrix4x4& inverseCameraProjection, const AZ::Vector2& viewportSize)
|
||||
{
|
||||
const auto normalizedScreenPosition = NDCFromScreenPoint(screenPosition, viewportSize);
|
||||
|
||||
return ScreenNDCToWorld(normalizedScreenPosition, inverseCameraView, inverseCameraProjection);
|
||||
}
|
||||
|
||||
AZ::Vector3 ScreenToWorld(const ScreenPoint& screenPosition, const CameraState& cameraState)
|
||||
{
|
||||
return ScreenToWorld(
|
||||
|
||||
@@ -42,7 +42,7 @@ namespace AzFramework
|
||||
const AZ::Vector3& worldPosition, const AZ::Matrix4x4& cameraView, const AZ::Matrix4x4& cameraProjection,
|
||||
const AZ::Vector2& viewportSize);
|
||||
|
||||
//! Unprojects a position in screen space to world space.
|
||||
//! Unprojects a position in screen space pixel coordinates to world space.
|
||||
//! Note: The position returned will be on the near clip plane of the camera in world space.
|
||||
AZ::Vector3 ScreenToWorld(const ScreenPoint& screenPosition, const CameraState& cameraState);
|
||||
|
||||
@@ -52,6 +52,12 @@ namespace AzFramework
|
||||
const ScreenPoint& screenPosition, const AZ::Matrix4x4& inverseCameraView,
|
||||
const AZ::Matrix4x4& inverseCameraProjection, const AZ::Vector2& viewportSize);
|
||||
|
||||
//! Unprojects a position in screen space normalized device coordinates to world space.
|
||||
//! Note: The position returned will be on the near clip plane of the camera in world space.
|
||||
AZ::Vector3 ScreenNDCToWorld(
|
||||
const AZ::Vector2& ndcPosition, const AZ::Matrix4x4& inverseCameraView,
|
||||
const AZ::Matrix4x4& inverseCameraProjection);
|
||||
|
||||
//! Returns the camera projection for the current camera state.
|
||||
AZ::Matrix4x4 CameraProjection(const CameraState& cameraState);
|
||||
|
||||
|
||||
+1
@@ -353,6 +353,7 @@ namespace AzFramework
|
||||
|
||||
// Get the dimensions of the display device on which the window is currently displayed.
|
||||
MONITORINFO monitorInfo;
|
||||
memset(&monitorInfo, 0, sizeof(MONITORINFO)); // C4701 potentially uninitialized local variable 'monitorInfo' used
|
||||
monitorInfo.cbSize = sizeof(MONITORINFO);
|
||||
const BOOL success = monitor ? GetMonitorInfo(monitor, &monitorInfo) : FALSE;
|
||||
if (!success)
|
||||
|
||||
+14
-11
@@ -12,17 +12,22 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AzToolsFramework/Manipulators/ManipulatorManager.h>
|
||||
#include <AzToolsFramework/Manipulators/ManipulatorBus.h>
|
||||
#include <AzToolsFramework/Manipulators/LinearManipulator.h>
|
||||
#include <AzToolsFramework/Manipulators/ManipulatorBus.h>
|
||||
#include <AzToolsFramework/Manipulators/ManipulatorManager.h>
|
||||
#include <AzToolsFramework/Manipulators/PlanarManipulator.h>
|
||||
|
||||
namespace AzManipulatorTestFramework
|
||||
{
|
||||
//! Create a linear manipulator with a unit sphere bounds.
|
||||
//! Create a linear manipulator with a unit sphere bound.
|
||||
AZStd::shared_ptr<AzToolsFramework::LinearManipulator> CreateLinearManipulator(
|
||||
const AzToolsFramework::ManipulatorManagerId manipulatorManagerId,
|
||||
const AZ::Vector3& position = AZ::Vector3::CreateZero(),
|
||||
const float radius = 1.0f);
|
||||
const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, const AZ::Vector3& position = AZ::Vector3::CreateZero(),
|
||||
float radius = 1.0f);
|
||||
|
||||
//! Create a planar manipulator with a unit sphere bound.
|
||||
AZStd::shared_ptr<AzToolsFramework::PlanarManipulator> CreatePlanarManipulator(
|
||||
const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, const AZ::Vector3& position = AZ::Vector3::CreateZero(),
|
||||
float radius = 1.0f);
|
||||
|
||||
//! Create a mouse pick from the specified ray and screen point.
|
||||
AzToolsFramework::ViewportInteraction::MousePick CreateMousePick(
|
||||
@@ -34,14 +39,12 @@ namespace AzManipulatorTestFramework
|
||||
|
||||
//! Create a mouse interaction from the specified pick, buttons, interaction id and keyboard modifiers.
|
||||
AzToolsFramework::ViewportInteraction::MouseInteraction CreateMouseInteraction(
|
||||
const AzToolsFramework::ViewportInteraction::MousePick& mousePick,
|
||||
AzToolsFramework::ViewportInteraction::MouseButtons buttons,
|
||||
const AzToolsFramework::ViewportInteraction::MousePick& mousePick, AzToolsFramework::ViewportInteraction::MouseButtons buttons,
|
||||
AzToolsFramework::ViewportInteraction::InteractionId interactionId,
|
||||
AzToolsFramework::ViewportInteraction::KeyboardModifiers modifiers);
|
||||
|
||||
//! Create a mouse buttons from the specified mouse button.
|
||||
AzToolsFramework::ViewportInteraction::MouseButtons CreateMouseButtons(
|
||||
AzToolsFramework::ViewportInteraction::MouseButton button);
|
||||
AzToolsFramework::ViewportInteraction::MouseButtons CreateMouseButtons(AzToolsFramework::ViewportInteraction::MouseButton button);
|
||||
|
||||
//! Create a mouse interaction event from the specified interaction and event.
|
||||
AzToolsFramework::ViewportInteraction::MouseInteractionEvent CreateMouseInteractionEvent(
|
||||
@@ -61,5 +64,5 @@ namespace AzManipulatorTestFramework
|
||||
AzFramework::ScreenPoint GetCameraStateViewportCenter(const AzFramework::CameraState& cameraState);
|
||||
|
||||
//! Default viewport size (1080p) in 16:9 aspect ratio.
|
||||
const auto DefaultViewportSize = AZ::Vector2(1920.0f, 1080.0f);
|
||||
inline const auto DefaultViewportSize = AZ::Vector2(1920.0f, 1080.0f);
|
||||
} // namespace AzManipulatorTestFramework
|
||||
|
||||
+36
-22
@@ -14,7 +14,6 @@
|
||||
#include <AzFramework/Viewport/ViewportScreen.h>
|
||||
#include <AzManipulatorTestFramework/AzManipulatorTestFrameworkUtils.h>
|
||||
#include <AzToolsFramework/ViewportSelection/EditorInteractionSystemViewportSelectionRequestBus.h>
|
||||
#include <AzToolsFramework/ViewportSelection/EditorInteractionSystemViewportSelectionRequestBus.h>
|
||||
#include <AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.h>
|
||||
|
||||
namespace AzManipulatorTestFramework
|
||||
@@ -28,22 +27,21 @@ namespace AzManipulatorTestFramework
|
||||
using MouseEvent = AzToolsFramework::ViewportInteraction::MouseEvent;
|
||||
using MousePick = AzToolsFramework::ViewportInteraction::MousePick;
|
||||
|
||||
AZStd::shared_ptr<AzToolsFramework::LinearManipulator> CreateLinearManipulator(
|
||||
const AzToolsFramework::ManipulatorManagerId manipulatorManagerId,
|
||||
const AZ::Vector3& position,
|
||||
const float radius)
|
||||
// create a default sphere view for a manipulator for simple intersection
|
||||
template<typename Manipulator>
|
||||
void SetupManipulatorView(
|
||||
AZStd::shared_ptr<Manipulator> manipulator, const AzToolsFramework::ManipulatorManagerId manipulatorManagerId,
|
||||
const AZ::Vector3& position, const float radius)
|
||||
{
|
||||
auto manipulator = AzToolsFramework::LinearManipulator::MakeShared(AZ::Transform::CreateIdentity());
|
||||
manipulator->SetLocalPosition(position);
|
||||
|
||||
// unit sphere view
|
||||
auto sphereView = AzToolsFramework::CreateManipulatorViewSphere(
|
||||
AZ::Colors::Red, radius,
|
||||
[](const MouseInteraction& /*mouseInteraction*/, const bool /*mouseOver*/,
|
||||
const AZ::Color& defaultColor)
|
||||
{
|
||||
return defaultColor;
|
||||
}, true);
|
||||
[]([[maybe_unused]] const MouseInteraction& mouseInteraction, [[maybe_unused]] const bool mouseOver,
|
||||
const AZ::Color& defaultColor)
|
||||
{
|
||||
return defaultColor;
|
||||
},
|
||||
true);
|
||||
|
||||
// unit sphere bound
|
||||
AzToolsFramework::Picking::BoundShapeSphere sphereBound;
|
||||
@@ -62,6 +60,26 @@ namespace AzManipulatorTestFramework
|
||||
// this would occur internally when the manipulator is drawn but we must do manually here to ensure that the
|
||||
// bounds will always be valid upon instantiation
|
||||
view->RefreshBound(manipulatorManagerId, manipulator->GetManipulatorId(), sphereBound);
|
||||
}
|
||||
|
||||
AZStd::shared_ptr<AzToolsFramework::LinearManipulator> CreateLinearManipulator(
|
||||
const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, const AZ::Vector3& position, const float radius)
|
||||
{
|
||||
auto manipulator = AzToolsFramework::LinearManipulator::MakeShared(AZ::Transform::CreateIdentity());
|
||||
manipulator->SetLocalPosition(position);
|
||||
|
||||
SetupManipulatorView(manipulator, manipulatorManagerId, position, radius);
|
||||
|
||||
return manipulator;
|
||||
}
|
||||
|
||||
AZStd::shared_ptr<AzToolsFramework::PlanarManipulator> CreatePlanarManipulator(
|
||||
const AzToolsFramework::ManipulatorManagerId manipulatorManagerId, const AZ::Vector3& position, const float radius)
|
||||
{
|
||||
auto manipulator = AzToolsFramework::PlanarManipulator::MakeShared(AZ::Transform::CreateIdentity());
|
||||
manipulator->SetLocalPosition(position);
|
||||
|
||||
SetupManipulatorView(manipulator, manipulatorManagerId, position, radius);
|
||||
|
||||
return manipulator;
|
||||
}
|
||||
@@ -104,8 +122,7 @@ namespace AzManipulatorTestFramework
|
||||
return buttons;
|
||||
}
|
||||
|
||||
MouseInteractionEvent CreateMouseInteractionEvent(
|
||||
const MouseInteraction& mouseInteraction, MouseEvent event)
|
||||
MouseInteractionEvent CreateMouseInteractionEvent(const MouseInteraction& mouseInteraction, MouseEvent event)
|
||||
{
|
||||
return MouseInteractionEvent(mouseInteraction, event);
|
||||
}
|
||||
@@ -114,8 +131,7 @@ namespace AzManipulatorTestFramework
|
||||
{
|
||||
AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Event(
|
||||
AzToolsFramework::GetEntityContextId(),
|
||||
&AzToolsFramework::ViewportInteraction::InternalMouseViewportRequests::InternalHandleAllMouseInteractions,
|
||||
event);
|
||||
&AzToolsFramework::ViewportInteraction::InternalMouseViewportRequests::InternalHandleAllMouseInteractions, event);
|
||||
}
|
||||
|
||||
AzFramework::CameraState SetCameraStatePosition(const AZ::Vector3& position, AzFramework::CameraState& cameraState)
|
||||
@@ -133,9 +149,7 @@ namespace AzManipulatorTestFramework
|
||||
|
||||
AzFramework::ScreenPoint GetCameraStateViewportCenter(const AzFramework::CameraState& cameraState)
|
||||
{
|
||||
return {
|
||||
aznumeric_cast<int>(cameraState.m_viewportSize.GetX() / 2.f),
|
||||
aznumeric_cast<int>(cameraState.m_viewportSize.GetY() / 2.f)
|
||||
};
|
||||
return { aznumeric_cast<int>(cameraState.m_viewportSize.GetX() / 2.f),
|
||||
aznumeric_cast<int>(cameraState.m_viewportSize.GetY() / 2.f) };
|
||||
}
|
||||
} // namespace UnitTest
|
||||
} // namespace AzManipulatorTestFramework
|
||||
|
||||
@@ -10,52 +10,55 @@
|
||||
*
|
||||
*/
|
||||
|
||||
#include "AzManipulatorTestFrameworkTestFixtures.h"
|
||||
|
||||
#include <AzCore/std/smart_ptr/unique_ptr.h>
|
||||
#include <AzFramework/Viewport/ViewportScreen.h>
|
||||
#include <AzManipulatorTestFramework/AzManipulatorTestFramework.h>
|
||||
#include "AzManipulatorTestFrameworkTestFixtures.h"
|
||||
#include <AzManipulatorTestFramework/DirectManipulatorViewportInteraction.h>
|
||||
#include <AzManipulatorTestFramework/IndirectManipulatorViewportInteraction.h>
|
||||
#include <AzManipulatorTestFramework/ImmediateModeActionDispatcher.h>
|
||||
#include <AzManipulatorTestFramework/AzManipulatorTestFrameworkUtils.h>
|
||||
#include <AzManipulatorTestFramework/DirectManipulatorViewportInteraction.h>
|
||||
#include <AzManipulatorTestFramework/ImmediateModeActionDispatcher.h>
|
||||
#include <AzManipulatorTestFramework/IndirectManipulatorViewportInteraction.h>
|
||||
#include <AzToolsFramework/Manipulators/LinearManipulator.h>
|
||||
#include <AzToolsFramework/Manipulators/PlanarManipulator.h>
|
||||
#include <AzToolsFramework/ViewportSelection/EditorSelectionUtil.h>
|
||||
#include <AZTestShared/Math/MathTestHelpers.h>
|
||||
|
||||
namespace UnitTest
|
||||
{
|
||||
class GridSnappingFixture
|
||||
: public ToolsApplicationFixture
|
||||
class GridSnappingFixture : public ToolsApplicationFixture
|
||||
{
|
||||
public:
|
||||
GridSnappingFixture()
|
||||
: m_viewportManipulatorInteraction(AZStd::make_unique<AzManipulatorTestFramework::DirectCallManipulatorViewportInteraction>())
|
||||
, m_actionDispatcher(AZStd::make_unique<AzManipulatorTestFramework::ImmediateModeActionDispatcher>(*m_viewportManipulatorInteraction))
|
||||
, m_linearManipulator(
|
||||
AzManipulatorTestFramework::CreateLinearManipulator(
|
||||
m_viewportManipulatorInteraction->GetManipulatorManager().GetId(),
|
||||
/*position=*/AZ::Vector3(0.0f, 50.0f, 0.0f),
|
||||
/*radius=*/m_boundsRadius))
|
||||
{}
|
||||
, m_actionDispatcher(
|
||||
AZStd::make_unique<AzManipulatorTestFramework::ImmediateModeActionDispatcher>(*m_viewportManipulatorInteraction))
|
||||
{
|
||||
}
|
||||
|
||||
protected:
|
||||
void SetUpEditorFixtureImpl() override
|
||||
{
|
||||
m_cameraState = AzFramework::CreateIdentityDefaultCamera(
|
||||
AZ::Vector3::CreateZero(), AzManipulatorTestFramework::DefaultViewportSize);
|
||||
m_cameraState =
|
||||
AzFramework::CreateIdentityDefaultCamera(AZ::Vector3::CreateZero(), AzManipulatorTestFramework::DefaultViewportSize);
|
||||
}
|
||||
|
||||
public:
|
||||
|
||||
const float m_boundsRadius = 1.0f;
|
||||
AZStd::unique_ptr<AzManipulatorTestFramework::ManipulatorViewportInteraction> m_viewportManipulatorInteraction;
|
||||
AZStd::unique_ptr<AzManipulatorTestFramework::ImmediateModeActionDispatcher> m_actionDispatcher;
|
||||
AZStd::shared_ptr<AzToolsFramework::LinearManipulator> m_linearManipulator;
|
||||
AzFramework::CameraState m_cameraState;
|
||||
};
|
||||
|
||||
TEST_F(GridSnappingFixture, MouseDownWithSnappingEnabledSnapsToClosestGridSize)
|
||||
{
|
||||
AZStd::shared_ptr<AzToolsFramework::LinearManipulator> linearManipulator(AzManipulatorTestFramework::CreateLinearManipulator(
|
||||
m_viewportManipulatorInteraction->GetManipulatorManager().GetId(),
|
||||
/*position=*/AZ::Vector3(0.0f, 50.0f, 0.0f),
|
||||
/*radius=*/m_boundsRadius));
|
||||
|
||||
// the initial starting position of the manipulator (in front of the camera)
|
||||
const auto initialPositionWorld = m_linearManipulator->GetLocalPosition();
|
||||
const auto initialPositionWorld = linearManipulator->GetLocalPosition();
|
||||
// where the manipulator should end up (in front and to the left of the camera)
|
||||
const auto finalPositionWorld = AZ::Vector3(-10.0f, 50.0f, 0.0f);
|
||||
// perspective scale factor for manipulator distance to camera
|
||||
@@ -66,21 +69,18 @@ namespace UnitTest
|
||||
// adjusted final world position taking into account the manipulator position relative to the camera
|
||||
const auto finalPositionWorldAdjusted = finalPositionWorld - (vectorToInitialPositionWorld * scaledRadiusBound);
|
||||
// calculate the position in screen space of the initial position of the manipulator
|
||||
const auto initialPositionScreen =
|
||||
AzFramework::WorldToScreen(initialPositionWorld, m_cameraState);
|
||||
const auto initialPositionScreen = AzFramework::WorldToScreen(initialPositionWorld, m_cameraState);
|
||||
// calculate the position in screen space of the final position of the manipulator
|
||||
const auto finalPositionScreen = AzFramework::WorldToScreen(finalPositionWorldAdjusted, m_cameraState);
|
||||
|
||||
// callback to update the manipulator's current position
|
||||
m_linearManipulator->InstallMouseMoveCallback(
|
||||
[this](const AzToolsFramework::LinearManipulator::Action& action)
|
||||
{
|
||||
auto pos = action.LocalPosition();
|
||||
m_linearManipulator->SetLocalPosition(pos);
|
||||
});
|
||||
linearManipulator->InstallMouseMoveCallback(
|
||||
[this, linearManipulator](const AzToolsFramework::LinearManipulator::Action& action)
|
||||
{
|
||||
linearManipulator->SetLocalPosition(action.LocalPosition());
|
||||
});
|
||||
|
||||
m_actionDispatcher
|
||||
->EnableSnapToGrid()
|
||||
m_actionDispatcher->EnableSnapToGrid()
|
||||
->GridSize(5.0f)
|
||||
->CameraState(m_cameraState)
|
||||
->MousePosition(initialPositionScreen)
|
||||
@@ -89,7 +89,67 @@ namespace UnitTest
|
||||
->MousePosition(finalPositionScreen)
|
||||
->MouseLButtonUp()
|
||||
->ExpectManipulatorNotBeingInteracted()
|
||||
->ExpectTrue(m_linearManipulator->GetLocalPosition().IsClose(finalPositionWorld, 0.01f))
|
||||
;
|
||||
->ExpectTrue(linearManipulator->GetLocalPosition().IsClose(finalPositionWorld, 0.01f));
|
||||
}
|
||||
|
||||
template<typename Manipulator>
|
||||
void ValidateManipulatorSnappingBehavior(
|
||||
AZStd::shared_ptr<Manipulator> manipulator, AzManipulatorTestFramework::ImmediateModeActionDispatcher* actionDispatcher,
|
||||
const AzFramework::CameraState& cameraState)
|
||||
{
|
||||
manipulator->SetLocalOrientation(AZ::Quaternion::CreateFromEulerAnglesDegrees(AZ::Vector3(180.0f, 0.0f, 135.0f)));
|
||||
|
||||
// the initial starting position of the manipulator (in front of the camera)
|
||||
const auto initialPositionWorld = manipulator->GetLocalPosition() + AZ::Vector3::CreateAxisX(0.15f);
|
||||
// where the manipulator should end up (unmoved)
|
||||
const auto finalPositionWorld = manipulator->GetLocalPosition();
|
||||
// where we should move the mouse to
|
||||
const auto attemptPositionWorld = manipulator->GetLocalPosition() + AZ::Vector3::CreateAxisX(0.35f);
|
||||
// calculate the position in screen space of the initial position of the manipulator
|
||||
const auto initialPositionScreen = AzFramework::WorldToScreen(initialPositionWorld, cameraState);
|
||||
// calculate the position in screen space of the final position of the manipulator
|
||||
const auto attemptPositionScreen = AzFramework::WorldToScreen(attemptPositionWorld, cameraState);
|
||||
|
||||
// callback to update the manipulator's current position
|
||||
manipulator->InstallMouseMoveCallback(
|
||||
[manipulator](const typename Manipulator::Action& action)
|
||||
{
|
||||
manipulator->SetLocalPosition(action.LocalPosition());
|
||||
});
|
||||
|
||||
actionDispatcher->EnableSnapToGrid()
|
||||
->GridSize(1.0f)
|
||||
->CameraState(cameraState)
|
||||
->MousePosition(initialPositionScreen)
|
||||
->MouseLButtonDown()
|
||||
->ExpectManipulatorBeingInteracted()
|
||||
->MousePosition(attemptPositionScreen)
|
||||
->MouseLButtonUp()
|
||||
->ExpectManipulatorNotBeingInteracted()
|
||||
->ExpectThat(manipulator->GetLocalPosition(), IsCloseTolerance(finalPositionWorld, 0.01f));
|
||||
}
|
||||
|
||||
TEST_F(GridSnappingFixture, MouseDownAndMoveLinearManipulatorDoesNotSnapWithMovementSmallerThanHalfGridSize)
|
||||
{
|
||||
AZStd::shared_ptr<AzToolsFramework::LinearManipulator> linearManipulator(AzManipulatorTestFramework::CreateLinearManipulator(
|
||||
m_viewportManipulatorInteraction->GetManipulatorManager().GetId(),
|
||||
/*position=*/AZ::Vector3(0.0f, 10.0f, 0.0f),
|
||||
/*radius=*/m_boundsRadius));
|
||||
|
||||
linearManipulator->SetAxis(AZ::Vector3::CreateAxisY());
|
||||
|
||||
ValidateManipulatorSnappingBehavior(linearManipulator, m_actionDispatcher.get(), m_cameraState);
|
||||
}
|
||||
|
||||
TEST_F(GridSnappingFixture, MouseDownAndMovePlanarManipulatorDoesNotSnapWithMovementSmallerThanHalfGridSize)
|
||||
{
|
||||
AZStd::shared_ptr<AzToolsFramework::PlanarManipulator> planarManipulator(AzManipulatorTestFramework::CreatePlanarManipulator(
|
||||
m_viewportManipulatorInteraction->GetManipulatorManager().GetId(),
|
||||
/*position=*/AZ::Vector3(0.0f, 10.0f, 0.0f),
|
||||
/*radius=*/m_boundsRadius));
|
||||
|
||||
planarManipulator->SetAxes(AZ::Vector3::CreateAxisY(), AZ::Vector3::CreateAxisZ());
|
||||
|
||||
ValidateManipulatorSnappingBehavior(planarManipulator, m_actionDispatcher.get(), m_cameraState);
|
||||
}
|
||||
} // namespace UnitTest
|
||||
|
||||
@@ -139,7 +139,7 @@ namespace AzNetworking
|
||||
|
||||
NetworkOutputSerializer networkSerializer(buffer.GetBuffer(), buffer.GetSize());
|
||||
{
|
||||
ISerializer& serializer = networkSerializer; // To get the default typeinfo parameters in ISerializer
|
||||
ISerializer& networkISerializer = networkSerializer; // To get the default typeinfo parameters in ISerializer
|
||||
|
||||
// First, serialize out the header
|
||||
if (!header.SerializePacketFlags(networkSerializer))
|
||||
@@ -148,7 +148,7 @@ namespace AzNetworking
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!serializer.Serialize(header, "Header"))
|
||||
if (!networkISerializer.Serialize(header, "Header"))
|
||||
{
|
||||
AZLOG(NET_FragmentQueue, "Reconstructed fragmented packet failed header serialization");
|
||||
return false;
|
||||
|
||||
@@ -46,7 +46,7 @@ namespace AzNetworking
|
||||
}
|
||||
else if (m_updateRate < updateTimeMs)
|
||||
{
|
||||
AZLOG_INFO("TimedThread bled %d ms", aznumeric_cast<int32_t>(updateTimeMs - m_updateRate));
|
||||
AZLOG(NET_TimedThread, "TimedThread bled %d ms", aznumeric_cast<int32_t>(updateTimeMs - m_updateRate));
|
||||
}
|
||||
}
|
||||
OnStop();
|
||||
|
||||
@@ -433,6 +433,11 @@ namespace AzToolsFramework
|
||||
return m_manipulatorSpaceWithLocalTransform.GetSpace();
|
||||
}
|
||||
|
||||
const AZ::Vector3& Manipulators::GetNonUniformScale() const
|
||||
{
|
||||
return m_manipulatorSpaceWithLocalTransform.GetNonUniformScale();
|
||||
}
|
||||
|
||||
void Manipulators::SetSpace(const AZ::Transform& worldFromLocal)
|
||||
{
|
||||
m_manipulatorSpaceWithLocalTransform.SetSpace(worldFromLocal);
|
||||
|
||||
+13
-14
@@ -192,8 +192,7 @@ namespace AzToolsFramework
|
||||
/// for each vertex associated with the translation manipulator to use with offset calculations when updating.
|
||||
template<typename Vertex>
|
||||
void InitializeVertexLookup(
|
||||
IndexedTranslationManipulator<Vertex>& translationManipulator,
|
||||
const AZ::EntityId entityId, const AZ::Vector3& snapOffset)
|
||||
IndexedTranslationManipulator<Vertex>& translationManipulator, const AZ::EntityId entityId)
|
||||
{
|
||||
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
|
||||
|
||||
@@ -202,7 +201,7 @@ namespace AzToolsFramework
|
||||
AZ::FixedVerticesRequestBus<Vertex>::Bind(fixedVertices, entityId);
|
||||
|
||||
translationManipulator.Process(
|
||||
[snapOffset, fixedVertices]
|
||||
[fixedVertices]
|
||||
(typename IndexedTranslationManipulator<Vertex>::VertexLookup& vertexLookup)
|
||||
{
|
||||
Vertex vertex;
|
||||
@@ -213,7 +212,7 @@ namespace AzToolsFramework
|
||||
|
||||
if (found)
|
||||
{
|
||||
vertexLookup.m_start = vertex + AZ::AdaptVertexIn<Vertex>(snapOffset);
|
||||
vertexLookup.m_start = vertex;
|
||||
vertexLookup.m_offset = Vertex::CreateZero();
|
||||
}
|
||||
});
|
||||
@@ -250,10 +249,10 @@ namespace AzToolsFramework
|
||||
|
||||
// linear manipulator callbacks
|
||||
m_translationManipulator->m_manipulator.InstallLinearManipulatorMouseDownCallback(
|
||||
[this](const LinearManipulator::Action& action)
|
||||
[this]([[maybe_unused]] const LinearManipulator::Action& action)
|
||||
{
|
||||
BeginBatchMovement();
|
||||
InitializeVertexLookup(*m_translationManipulator, GetEntityId(), action.m_start.m_positionSnapOffset);
|
||||
InitializeVertexLookup(*m_translationManipulator, GetEntityId());
|
||||
});
|
||||
|
||||
m_translationManipulator->m_manipulator.InstallLinearManipulatorMouseMoveCallback(
|
||||
@@ -264,17 +263,17 @@ namespace AzToolsFramework
|
||||
});
|
||||
|
||||
m_translationManipulator->m_manipulator.InstallLinearManipulatorMouseUpCallback(
|
||||
[this](const LinearManipulator::Action& /*action*/)
|
||||
[this]([[maybe_unused]] const LinearManipulator::Action& action)
|
||||
{
|
||||
EndBatchMovement();
|
||||
});
|
||||
|
||||
// planar manipulator callbacks
|
||||
m_translationManipulator->m_manipulator.InstallPlanarManipulatorMouseDownCallback(
|
||||
[this](const PlanarManipulator::Action& action)
|
||||
[this]([[maybe_unused]] const PlanarManipulator::Action& action)
|
||||
{
|
||||
BeginBatchMovement();
|
||||
InitializeVertexLookup(*m_translationManipulator, GetEntityId(), action.m_start.m_snapOffset);
|
||||
InitializeVertexLookup(*m_translationManipulator, GetEntityId());
|
||||
});
|
||||
|
||||
m_translationManipulator->m_manipulator.InstallPlanarManipulatorMouseMoveCallback(
|
||||
@@ -285,17 +284,17 @@ namespace AzToolsFramework
|
||||
});
|
||||
|
||||
m_translationManipulator->m_manipulator.InstallPlanarManipulatorMouseUpCallback(
|
||||
[this](const PlanarManipulator::Action& /*action*/)
|
||||
[this]([[maybe_unused]] const PlanarManipulator::Action& action)
|
||||
{
|
||||
EndBatchMovement();
|
||||
});
|
||||
|
||||
// surface manipulator callbacks
|
||||
m_translationManipulator->m_manipulator.InstallSurfaceManipulatorMouseDownCallback(
|
||||
[this](const SurfaceManipulator::Action& action)
|
||||
[this]([[maybe_unused]] const SurfaceManipulator::Action& action)
|
||||
{
|
||||
BeginBatchMovement();
|
||||
InitializeVertexLookup(*m_translationManipulator, GetEntityId(), action.m_start.m_snapOffset);
|
||||
InitializeVertexLookup(*m_translationManipulator, GetEntityId());
|
||||
});
|
||||
|
||||
m_translationManipulator->m_manipulator.InstallSurfaceManipulatorMouseMoveCallback(
|
||||
@@ -306,7 +305,7 @@ namespace AzToolsFramework
|
||||
});
|
||||
|
||||
m_translationManipulator->m_manipulator.InstallSurfaceManipulatorMouseUpCallback(
|
||||
[this](const SurfaceManipulator::Action& /*action*/)
|
||||
[this]([[maybe_unused]] const SurfaceManipulator::Action& action)
|
||||
{
|
||||
EndBatchMovement();
|
||||
});
|
||||
@@ -893,7 +892,7 @@ namespace AzToolsFramework
|
||||
{
|
||||
BeginBatchMovement();
|
||||
|
||||
InitializeVertexLookup(*m_translationManipulator, GetEntityId(), AZ::Vector3::CreateZero());
|
||||
InitializeVertexLookup(*m_translationManipulator, GetEntityId());
|
||||
// note: AdaptVertexIn/Out is to ensure we clamp the vertex local Z position to 0 if
|
||||
// dealing with Vector2s when setting the position of the manipulator.
|
||||
const AZ::Vector3 localOffset =
|
||||
|
||||
+26
-44
@@ -23,8 +23,8 @@ namespace AzToolsFramework
|
||||
{
|
||||
LinearManipulator::Starter CalculateLinearManipulationDataStart(
|
||||
const LinearManipulator::Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale,
|
||||
const AZ::Transform& localTransform, const GridSnapAction& gridSnapAction, const ViewportInteraction::MouseInteraction& interaction,
|
||||
const float intersectionDistance, const AzFramework::CameraState& cameraState)
|
||||
const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, const float intersectionDistance,
|
||||
const AzFramework::CameraState& cameraState)
|
||||
{
|
||||
const ManipulatorInteraction manipulatorInteraction =
|
||||
BuildManipulatorInteraction(
|
||||
@@ -50,28 +50,9 @@ namespace AzToolsFramework
|
||||
manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection,
|
||||
localIntersectionPoint, startTransition.m_localNormal, start.m_localHitPosition);
|
||||
|
||||
const float gridSize = gridSnapAction.m_gridSnapParams.m_gridSize;
|
||||
const bool snapping = gridSnapAction.m_gridSnapParams.m_gridSnap;
|
||||
const float scaleRecip = manipulatorInteraction.m_scaleReciprocal;
|
||||
|
||||
// calculate position amount to snap, to align with grid
|
||||
const AZ::Vector3 positionSnapOffset = snapping && !gridSnapAction.m_localSnapping
|
||||
? CalculateSnappedOffset(localTransform.GetTranslation(), axis, gridSize * scaleRecip)
|
||||
: AZ::Vector3::CreateZero();
|
||||
|
||||
const AZ::Vector3 localScale = AZ::Vector3(localTransform.GetUniformScale());
|
||||
const AZ::Quaternion localRotation = QuaternionFromTransformNoScaling(localTransform);
|
||||
// calculate scale amount to snap, to align to round scale value
|
||||
const AZ::Vector3 scaleSnapOffset = snapping && !gridSnapAction.m_localSnapping
|
||||
? localRotation.GetInverseFull().TransformVector(CalculateSnappedOffset(
|
||||
localRotation.TransformVector(localScale), axis, gridSize * scaleRecip))
|
||||
: AZ::Vector3::CreateZero();
|
||||
|
||||
start.m_screenPosition = interaction.m_mousePick.m_screenCoordinates;
|
||||
start.m_positionSnapOffset = positionSnapOffset;
|
||||
start.m_scaleSnapOffset = scaleSnapOffset;
|
||||
start.m_localPosition = localTransform.GetTranslation() + positionSnapOffset;
|
||||
start.m_localScale = localScale + scaleSnapOffset;
|
||||
start.m_localPosition = localTransform.GetTranslation();
|
||||
start.m_localScale = AZ::Vector3(localTransform.GetUniformScale());;
|
||||
start.m_localAxis = axis;
|
||||
// sign to determine which side of the linear axis we pressed
|
||||
// (useful to know when the visual axis flips to face the camera)
|
||||
@@ -87,7 +68,7 @@ namespace AzToolsFramework
|
||||
LinearManipulator::Action CalculateLinearManipulationDataAction(
|
||||
const LinearManipulator::Fixed& fixed, const LinearManipulator::Starter& starter,
|
||||
const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform,
|
||||
const GridSnapAction& gridSnapAction, const ViewportInteraction::MouseInteraction& interaction)
|
||||
const GridSnapParameters& gridSnapParams, const ViewportInteraction::MouseInteraction& interaction)
|
||||
{
|
||||
const ManipulatorInteraction manipulatorInteraction =
|
||||
BuildManipulatorInteraction(
|
||||
@@ -108,31 +89,34 @@ namespace AzToolsFramework
|
||||
GetCameraState(interaction.m_interactionId.m_viewportId));
|
||||
|
||||
const AZ::Vector3 axis = TransformDirectionNoScaling(localTransform, fixed.m_axis);
|
||||
// The local positions have been transformed to the reference frame of the object being manipulated. But they appear in the world
|
||||
// with non-uniform scale applied, and the object being manipulated will want to work with unscaled deltas, so we need to divide by
|
||||
// the non-uniform scale here.
|
||||
// the local positions have been transformed to the reference frame of the object being manipulated, but they appear in the world
|
||||
// with non-uniform scale applied, the object being manipulated will want to work with unscaled deltas, so we need to divide by
|
||||
// the non-uniform scale here
|
||||
const AZ::Vector3 hitDelta = (localHitPosition - start.m_localHitPosition) / nonUniformScale;
|
||||
const AZ::Vector3 unsnappedOffset = axis * axis.Dot(hitDelta);
|
||||
|
||||
const float scaleRecip = manipulatorInteraction.m_scaleReciprocal * axis.Dot(manipulatorInteraction.m_nonUniformScaleReciprocal);
|
||||
const float gridSize = gridSnapAction.m_gridSnapParams.m_gridSize;
|
||||
const bool snapping = gridSnapAction.m_gridSnapParams.m_gridSnap;
|
||||
const float scaleRecip =
|
||||
manipulatorInteraction.m_scaleReciprocal * fixed.m_axis.Dot(manipulatorInteraction.m_nonUniformScaleReciprocal);
|
||||
const float gridSize = gridSnapParams.m_gridSize;
|
||||
const bool snapping = gridSnapParams.m_gridSnap;
|
||||
|
||||
LinearManipulator::Action action;
|
||||
action.m_fixed = fixed;
|
||||
action.m_start = start;
|
||||
action.m_current.m_localPositionOffset = snapping
|
||||
? unsnappedOffset + CalculateSnappedOffset(unsnappedOffset, axis, gridSize * scaleRecip)
|
||||
? CalculateSnappedAmount(unsnappedOffset, axis, gridSize * scaleRecip)
|
||||
: unsnappedOffset;
|
||||
action.m_current.m_screenPosition = interaction.m_mousePick.m_screenCoordinates;
|
||||
action.m_viewportId = interaction.m_interactionId.m_viewportId;
|
||||
|
||||
const AZ::Quaternion localRotation = QuaternionFromTransformNoScaling(localTransform);
|
||||
const AZ::Vector3 scaledUnsnappedOffset = unsnappedOffset * startTransition.m_screenToWorldScale * NonUniformScaleReciprocal(nonUniformScale);
|
||||
const AZ::Vector3 scaledUnsnappedOffset =
|
||||
unsnappedOffset * startTransition.m_screenToWorldScale * NonUniformScaleReciprocal(nonUniformScale);
|
||||
|
||||
// how much to adjust the scale based on movement
|
||||
const AZ::Quaternion invLocalRotation = localRotation.GetInverseFull();
|
||||
action.m_current.m_localScaleOffset = snapping
|
||||
? invLocalRotation.TransformVector((scaledUnsnappedOffset + CalculateSnappedOffset(scaledUnsnappedOffset, axis, gridSize * scaleRecip)))
|
||||
? invLocalRotation.TransformVector(CalculateSnappedAmount(scaledUnsnappedOffset, axis, gridSize * scaleRecip))
|
||||
: invLocalRotation.TransformVector(scaledUnsnappedOffset);
|
||||
|
||||
// record what modifier keys are held during this action
|
||||
@@ -171,19 +155,18 @@ namespace AzToolsFramework
|
||||
const ViewportInteraction::MouseInteraction& interaction, const float rayIntersectionDistance)
|
||||
{
|
||||
const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace());
|
||||
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
|
||||
|
||||
// note: m_localTransform must not be made uniform as it may contain a local scale we want to snap
|
||||
m_starter = CalculateLinearManipulationDataStart(
|
||||
m_fixed, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(),
|
||||
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction, rayIntersectionDistance,
|
||||
m_fixed, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), interaction, rayIntersectionDistance,
|
||||
GetCameraState(interaction.m_interactionId.m_viewportId));
|
||||
|
||||
if (m_onLeftMouseDownCallback)
|
||||
{
|
||||
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
|
||||
|
||||
m_onLeftMouseDownCallback(CalculateLinearManipulationDataAction(
|
||||
m_fixed, m_starter, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(),
|
||||
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction));
|
||||
m_fixed, m_starter, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), gridSnapParams, interaction));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,8 +178,8 @@ namespace AzToolsFramework
|
||||
|
||||
// note: m_localTransform must not be made uniform as it may contain a local scale we want to snap
|
||||
m_onMouseMoveCallback(CalculateLinearManipulationDataAction(
|
||||
m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(),
|
||||
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction));
|
||||
m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), gridSnapParams,
|
||||
interaction));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,8 +191,7 @@ namespace AzToolsFramework
|
||||
|
||||
// note: m_localTransform must not be made uniform as it may contain a local scale we want to snap
|
||||
m_onLeftMouseUpCallback(CalculateLinearManipulationDataAction(
|
||||
m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(),
|
||||
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction));
|
||||
m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), gridSnapParams, interaction));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,8 +214,8 @@ namespace AzToolsFramework
|
||||
GridSnapSettings(mouseInteraction.m_interactionId.m_viewportId);
|
||||
|
||||
const auto action = CalculateLinearManipulationDataAction(
|
||||
m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(),
|
||||
GridSnapAction(gridSnapParams, mouseInteraction.m_keyboardModifiers.Alt()), mouseInteraction);
|
||||
m_fixed, m_starter, TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalTransform(), gridSnapParams,
|
||||
mouseInteraction);
|
||||
|
||||
// display the exact hit (ray intersection) of the mouse pick on the manipulator
|
||||
DrawTransformAxes(
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
struct GridSnapAction;
|
||||
struct GridSnapParameters;
|
||||
|
||||
/// LinearManipulator serves as a visual tool for users to modify values
|
||||
/// in one dimension on an axis defined in 3D space.
|
||||
@@ -68,8 +68,6 @@ namespace AzToolsFramework
|
||||
AZ::Vector3 m_localScale; ///< The current scale of the manipulator in local space.
|
||||
AZ::Vector3 m_localHitPosition; ///< The intersection point in local space between the ray and the manipulator when the mouse down event happens.
|
||||
AZ::Vector3 m_localAxis; ///< The axis in the local space of the manipulator itself.
|
||||
AZ::Vector3 m_positionSnapOffset; ///< The snap offset amount to ensure manipulator is aligned to the grid.
|
||||
AZ::Vector3 m_scaleSnapOffset; ///< The snap offset amount to ensure manipulator is aligned to round scale increments.
|
||||
float m_sign; ///< Used to determine which side of the axis we clicked on in case it's flipped to face the camera.
|
||||
AzFramework::ScreenPoint m_screenPosition; ///< The initial position in screen space of the manipulator.
|
||||
};
|
||||
@@ -91,7 +89,7 @@ namespace AzToolsFramework
|
||||
ViewportInteraction::KeyboardModifiers m_modifiers;
|
||||
int m_viewportId; ///< The id of the viewport this manipulator is being used in.
|
||||
AZ::Vector3 LocalScale() const { return m_start.m_localScale + m_current.m_localScaleOffset; }
|
||||
AZ::Vector3 LocalScaleOffset() const { return m_start.m_scaleSnapOffset + m_current.m_localScaleOffset; }
|
||||
AZ::Vector3 LocalScaleOffset() const { return m_current.m_localScaleOffset; }
|
||||
AZ::Vector3 LocalPosition() const { return m_start.m_localPosition + m_current.m_localPositionOffset; }
|
||||
AZ::Vector3 LocalPositionOffset() const { return m_current.m_localPositionOffset; }
|
||||
AZ::Vector2 ScreenOffset() const
|
||||
@@ -162,11 +160,11 @@ namespace AzToolsFramework
|
||||
|
||||
LinearManipulator::Starter CalculateLinearManipulationDataStart(
|
||||
const LinearManipulator::Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale,
|
||||
const AZ::Transform& localTransform, const GridSnapAction& gridSnapAction, const ViewportInteraction::MouseInteraction& interaction,
|
||||
float intersectionDistance, const AzFramework::CameraState& cameraState);
|
||||
const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, float intersectionDistance,
|
||||
const AzFramework::CameraState& cameraState);
|
||||
|
||||
LinearManipulator::Action CalculateLinearManipulationDataAction(
|
||||
const LinearManipulator::Fixed& fixed, const LinearManipulator::Starter& starter,
|
||||
const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform,
|
||||
const GridSnapAction& gridSnapAction, const ViewportInteraction::MouseInteraction& interaction);
|
||||
const GridSnapParameters& gridSnapParams, const ViewportInteraction::MouseInteraction& interaction);
|
||||
} // namespace AzToolsFramework
|
||||
|
||||
+25
-11
@@ -42,12 +42,6 @@ namespace AzToolsFramework
|
||||
{
|
||||
}
|
||||
|
||||
GridSnapAction::GridSnapAction(const GridSnapParameters& gridSnapParameters, const bool localSnapping)
|
||||
: m_gridSnapParams(gridSnapParameters)
|
||||
, m_localSnapping(localSnapping)
|
||||
{
|
||||
}
|
||||
|
||||
ManipulatorInteraction BuildManipulatorInteraction(
|
||||
const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale,
|
||||
const AZ::Vector3& worldRayOrigin, const AZ::Vector3& worldRayDirection)
|
||||
@@ -57,19 +51,39 @@ namespace AzToolsFramework
|
||||
|
||||
return {localFromWorldUniform.TransformPoint(worldRayOrigin),
|
||||
TransformDirectionNoScaling(localFromWorldUniform, worldRayDirection),
|
||||
ScaleReciprocal(worldFromLocalUniform),
|
||||
NonUniformScaleReciprocal(nonUniformScale)};
|
||||
NonUniformScaleReciprocal(nonUniformScale),
|
||||
ScaleReciprocal(worldFromLocalUniform)};
|
||||
}
|
||||
|
||||
AZ::Vector3 CalculateSnappedOffset(
|
||||
const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, const float size)
|
||||
struct SnapAdjustment
|
||||
{
|
||||
float m_existingSnapDistance; //!< How far to snap up or down to align to the grid.
|
||||
float m_nextSnapDistance; //!< The snap increment (will return full signed value (grid size) when distance
|
||||
//!< moved is greater than half of the grid size in either direction).
|
||||
};
|
||||
|
||||
static SnapAdjustment CalculateSnapDistance(const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, const float size)
|
||||
{
|
||||
// calculate total distance along axis
|
||||
const float axisDistance = axis.Dot(unsnappedPosition);
|
||||
// round to nearest step size
|
||||
const float snappedAxisDistance = floorf((axisDistance / size) + 0.5f) * size;
|
||||
|
||||
return { axisDistance, snappedAxisDistance };
|
||||
}
|
||||
|
||||
AZ::Vector3 CalculateSnappedOffset(const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, const float size)
|
||||
{
|
||||
const auto snapAdjustment = CalculateSnapDistance(unsnappedPosition, axis, size);
|
||||
// return offset along axis to snap to step size
|
||||
return axis * (snappedAxisDistance - axisDistance);
|
||||
return axis * (snapAdjustment.m_nextSnapDistance - snapAdjustment.m_existingSnapDistance);
|
||||
}
|
||||
|
||||
AZ::Vector3 CalculateSnappedAmount(const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, const float size)
|
||||
{
|
||||
const auto snapAdjustment = CalculateSnapDistance(unsnappedPosition, axis, size);
|
||||
// return offset along axis to snap to step size
|
||||
return axis * snapAdjustment.m_nextSnapDistance;
|
||||
}
|
||||
|
||||
AZ::Vector3 CalculateSnappedTerrainPosition(
|
||||
|
||||
+9
-13
@@ -31,24 +31,15 @@ namespace AzToolsFramework
|
||||
float m_gridSize;
|
||||
};
|
||||
|
||||
/// Structure to encapsulate the current grid snapping state.
|
||||
struct GridSnapAction
|
||||
{
|
||||
GridSnapAction(const GridSnapParameters& gridSnapParameters, bool localSnapping);
|
||||
|
||||
GridSnapParameters m_gridSnapParams;
|
||||
bool m_localSnapping;
|
||||
};
|
||||
|
||||
/// Structure to hold transformed incoming viewport interaction from world space to manipulator space.
|
||||
struct ManipulatorInteraction
|
||||
{
|
||||
AZ::Vector3 m_localRayOrigin; ///< The ray origin (start) in the reference from of the manipulator.
|
||||
AZ::Vector3 m_localRayDirection; ///< The ray direction in the reference from of the manipulator.
|
||||
float m_scaleReciprocal; ///< The scale reciprocal (1.0 / scale) of the transform used to move the
|
||||
///< ray from world space to local space.
|
||||
AZ::Vector3 m_nonUniformScaleReciprocal; ///< Handles inverting any non-uniform scale which was applied
|
||||
///< separately from the transform.
|
||||
float m_scaleReciprocal; ///< The scale reciprocal (1.0 / scale) of the transform used to move the
|
||||
///< ray from world space to local space.
|
||||
};
|
||||
|
||||
/// Build a ManipulatorInteraction structure from the incoming viewport interaction.
|
||||
@@ -56,11 +47,16 @@ namespace AzToolsFramework
|
||||
const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale,
|
||||
const AZ::Vector3& worldRayOrigin, const AZ::Vector3& worldRayDirection);
|
||||
|
||||
/// Calculate the offset along an axis to adjust a position
|
||||
/// to stay snapped to a given grid size.
|
||||
/// Calculate the offset along an axis to adjust a position to stay snapped to a given grid size.
|
||||
/// @note This is snap up or down to the nearest grid segment (e.g. 0.2 snaps to 0.0 -> delta 0.2,
|
||||
/// 0.7 snaps to 1.0 -> delta 0.3).
|
||||
AZ::Vector3 CalculateSnappedOffset(
|
||||
const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, float size);
|
||||
|
||||
/// Return the amount to snap from the starting position given the current grid size.
|
||||
/// @note A movement of more than half size (in either direction) will cause a snap by size.
|
||||
AZ::Vector3 CalculateSnappedAmount(const AZ::Vector3& unsnappedPosition, const AZ::Vector3& axis, float size);
|
||||
|
||||
/// For a given point on the terrain, calculate the closest xy position snapped to the grid
|
||||
/// (z position is aligned to terrain height, not snapped to z grid)
|
||||
AZ::Vector3 CalculateSnappedTerrainPosition(
|
||||
|
||||
+10
-18
@@ -59,17 +59,16 @@ namespace AzToolsFramework
|
||||
const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform,
|
||||
const ViewportInteraction::MouseInteraction& interaction,
|
||||
const AZStd::vector<LinearManipulator::Fixed>& fixedAxes,
|
||||
const AZStd::vector<LinearManipulator::Starter>& starterStates, const GridSnapAction& gridSnapAction)
|
||||
const AZStd::vector<LinearManipulator::Starter>& starterStates, const GridSnapParameters& gridSnapParams)
|
||||
{
|
||||
MultiLinearManipulator::Action action;
|
||||
action.m_viewportId = interaction.m_interactionId.m_viewportId;
|
||||
// build up action state for each axis
|
||||
for (size_t fixedIndex = 0; fixedIndex < fixedAxes.size(); ++fixedIndex)
|
||||
{
|
||||
action.m_actions.push_back(
|
||||
CalculateLinearManipulationDataAction(
|
||||
fixedAxes[fixedIndex], starterStates[fixedIndex], worldFromLocal, nonUniformScale, localTransform,
|
||||
gridSnapAction, interaction));
|
||||
action.m_actions.push_back(CalculateLinearManipulationDataAction(
|
||||
fixedAxes[fixedIndex], starterStates[fixedIndex], worldFromLocal, nonUniformScale, localTransform, gridSnapParams,
|
||||
interaction));
|
||||
}
|
||||
|
||||
return action;
|
||||
@@ -79,8 +78,6 @@ namespace AzToolsFramework
|
||||
const ViewportInteraction::MouseInteraction& interaction, const float rayIntersectionDistance)
|
||||
{
|
||||
const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace());
|
||||
|
||||
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
|
||||
const AzFramework::CameraState cameraState = GetCameraState(interaction.m_interactionId.m_viewportId);
|
||||
|
||||
// build up initial start state for each axis
|
||||
@@ -88,20 +85,19 @@ namespace AzToolsFramework
|
||||
{
|
||||
// note: m_localTransform must not be made uniform as it may contain a local scale we want to snap
|
||||
const auto linearStart = CalculateLinearManipulationDataStart(
|
||||
fixed, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(),
|
||||
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction,
|
||||
rayIntersectionDistance, cameraState);
|
||||
fixed, worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(), interaction, rayIntersectionDistance,
|
||||
cameraState);
|
||||
|
||||
m_starters.push_back(linearStart);
|
||||
}
|
||||
|
||||
if (m_onLeftMouseDownCallback)
|
||||
{
|
||||
const GridSnapAction gridSnapAction = GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt());
|
||||
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
|
||||
// pass action containing all linear actions for each axis to handler
|
||||
m_onLeftMouseDownCallback(BuildMultiLinearManipulatorAction(
|
||||
worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(),
|
||||
interaction, m_fixedAxes, m_starters, gridSnapAction));
|
||||
interaction, m_fixedAxes, m_starters, gridSnapParams));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,11 +107,9 @@ namespace AzToolsFramework
|
||||
{
|
||||
const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace());
|
||||
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
|
||||
const GridSnapAction gridSnapAction = GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt());
|
||||
|
||||
m_onMouseMoveCallback(BuildMultiLinearManipulatorAction(
|
||||
worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(),
|
||||
interaction, m_fixedAxes, m_starters, gridSnapAction));
|
||||
interaction, m_fixedAxes, m_starters, gridSnapParams));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,11 +119,9 @@ namespace AzToolsFramework
|
||||
{
|
||||
const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace());
|
||||
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
|
||||
const GridSnapAction gridSnapAction = GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt());
|
||||
|
||||
m_onLeftMouseUpCallback(BuildMultiLinearManipulatorAction(
|
||||
worldFromLocalUniformScale, GetNonUniformScale(), GetLocalTransform(),
|
||||
interaction, m_fixedAxes, m_starters, gridSnapAction));
|
||||
interaction, m_fixedAxes, m_starters, gridSnapParams));
|
||||
|
||||
m_starters.clear();
|
||||
}
|
||||
|
||||
@@ -20,8 +20,6 @@
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
struct GridSnapAction;
|
||||
|
||||
//! MultiLinearManipulator serves as a visual tool for users to modify values
|
||||
//! in one or more dimensions on axes defined in 3D space.
|
||||
class MultiLinearManipulator
|
||||
|
||||
+15
-35
@@ -22,8 +22,7 @@
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
PlanarManipulator::StartInternal PlanarManipulator::CalculateManipulationDataStart(
|
||||
const Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale,
|
||||
const AZ::Transform& localTransform, const GridSnapAction& gridSnapAction,
|
||||
const Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform,
|
||||
const ViewportInteraction::MouseInteraction& interaction, const float intersectionDistance)
|
||||
{
|
||||
const ManipulatorInteraction manipulatorInteraction =
|
||||
@@ -31,8 +30,6 @@ namespace AzToolsFramework
|
||||
worldFromLocal, nonUniformScale, interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection);
|
||||
|
||||
const AZ::Vector3 normal = TransformDirectionNoScaling(localTransform, fixed.m_normal);
|
||||
const AZ::Vector3 axis1 = TransformDirectionNoScaling(localTransform, fixed.m_axis1);
|
||||
const AZ::Vector3 axis2 = TransformDirectionNoScaling(localTransform, fixed.m_axis2);
|
||||
|
||||
// initial intersect point
|
||||
const AZ::Vector3 localIntersectionPoint =
|
||||
@@ -43,25 +40,14 @@ namespace AzToolsFramework
|
||||
manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection,
|
||||
localIntersectionPoint, normal, startInternal.m_localHitPosition);
|
||||
|
||||
const float scaleRecip = manipulatorInteraction.m_scaleReciprocal;
|
||||
const float gridSize = gridSnapAction.m_gridSnapParams.m_gridSize;
|
||||
const bool snapping = gridSnapAction.m_gridSnapParams.m_gridSnap;
|
||||
|
||||
// calculate amount to snap to align with grid
|
||||
const AZ::Vector3 snapOffset = snapping && !gridSnapAction.m_localSnapping
|
||||
? CalculateSnappedOffset(localTransform.GetTranslation(), axis1, gridSize * scaleRecip) +
|
||||
CalculateSnappedOffset(localTransform.GetTranslation(), axis2, gridSize * scaleRecip)
|
||||
: AZ::Vector3::CreateZero();
|
||||
|
||||
startInternal.m_snapOffset = snapOffset;
|
||||
startInternal.m_localPosition = localTransform.GetTranslation() + snapOffset;
|
||||
startInternal.m_localPosition = localTransform.GetTranslation();
|
||||
|
||||
return startInternal;
|
||||
}
|
||||
|
||||
PlanarManipulator::Action PlanarManipulator::CalculateManipulationDataAction(
|
||||
const Fixed& fixed, const StartInternal& startInternal, const AZ::Transform& worldFromLocal,
|
||||
const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform, const GridSnapAction& gridSnapAction,
|
||||
const Fixed& fixed, const StartInternal& startInternal, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale,
|
||||
const AZ::Transform& localTransform, const GridSnapParameters& gridSnapParams,
|
||||
const ViewportInteraction::MouseInteraction& interaction)
|
||||
{
|
||||
const ManipulatorInteraction manipulatorInteraction =
|
||||
@@ -88,20 +74,18 @@ namespace AzToolsFramework
|
||||
const AZ::Vector3 hitDelta = (localHitPosition - startInternal.m_localHitPosition) / nonUniformScale;
|
||||
const AZ::Vector3 unsnappedOffset = axis1.Dot(hitDelta) * axis1 + axis2.Dot(hitDelta) * axis2;
|
||||
|
||||
const float scaleRecip = manipulatorInteraction.m_scaleReciprocal;
|
||||
const AZ::Vector3 nonUniformScaleRecip = manipulatorInteraction.m_nonUniformScaleReciprocal;
|
||||
const float gridSize = gridSnapAction.m_gridSnapParams.m_gridSize;
|
||||
const bool snapping = gridSnapAction.m_gridSnapParams.m_gridSnap;
|
||||
const float scaleRecip = manipulatorInteraction.m_scaleReciprocal;
|
||||
const float gridSize = gridSnapParams.m_gridSize;
|
||||
const bool snapping = gridSnapParams.m_gridSnap;
|
||||
|
||||
Action action;
|
||||
action.m_fixed = fixed;
|
||||
action.m_start.m_localPosition = startInternal.m_localPosition;
|
||||
action.m_start.m_snapOffset = startInternal.m_snapOffset;
|
||||
action.m_start.m_localHitPosition = startInternal.m_localHitPosition;
|
||||
action.m_current.m_localOffset = snapping
|
||||
? unsnappedOffset +
|
||||
CalculateSnappedOffset(unsnappedOffset, axis1, gridSize * scaleRecip * nonUniformScaleRecip.Dot(axis1)) +
|
||||
CalculateSnappedOffset(unsnappedOffset, axis2, gridSize * scaleRecip * nonUniformScaleRecip.Dot(axis2))
|
||||
? CalculateSnappedAmount(unsnappedOffset, axis1, gridSize * scaleRecip * nonUniformScaleRecip.Dot(fixed.m_axis1)) +
|
||||
CalculateSnappedAmount(unsnappedOffset, axis2, gridSize * scaleRecip * nonUniformScaleRecip.Dot(fixed.m_axis2))
|
||||
: unsnappedOffset;
|
||||
|
||||
// record what modifier keys are held during this action
|
||||
@@ -141,18 +125,17 @@ namespace AzToolsFramework
|
||||
{
|
||||
const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(GetSpace());
|
||||
|
||||
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
|
||||
|
||||
m_startInternal = CalculateManipulationDataStart(
|
||||
m_fixed, worldFromLocalUniformScale, GetNonUniformScale(), TransformNormalizedScale(GetLocalTransform()),
|
||||
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()),
|
||||
interaction, rayIntersectionDistance);
|
||||
|
||||
if (m_onLeftMouseDownCallback)
|
||||
{
|
||||
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
|
||||
|
||||
m_onLeftMouseDownCallback(CalculateManipulationDataAction(
|
||||
m_fixed, m_startInternal, worldFromLocalUniformScale, GetNonUniformScale(), TransformNormalizedScale(GetLocalTransform()),
|
||||
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction));
|
||||
gridSnapParams, interaction));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,8 +147,7 @@ namespace AzToolsFramework
|
||||
|
||||
m_onMouseMoveCallback(CalculateManipulationDataAction(
|
||||
m_fixed, m_startInternal, TransformUniformScale(GetSpace()), GetNonUniformScale(),
|
||||
TransformNormalizedScale(GetLocalTransform()),
|
||||
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction));
|
||||
TransformNormalizedScale(GetLocalTransform()), gridSnapParams, interaction));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,8 +159,7 @@ namespace AzToolsFramework
|
||||
|
||||
m_onLeftMouseUpCallback(CalculateManipulationDataAction(
|
||||
m_fixed, m_startInternal, TransformUniformScale(GetSpace()), GetNonUniformScale(),
|
||||
TransformNormalizedScale(GetLocalTransform()),
|
||||
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()), interaction));
|
||||
TransformNormalizedScale(GetLocalTransform()), gridSnapParams, interaction));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,8 +176,7 @@ namespace AzToolsFramework
|
||||
const GridSnapParameters gridSnapParams = GridSnapSettings(mouseInteraction.m_interactionId.m_viewportId);
|
||||
const auto action = CalculateManipulationDataAction(
|
||||
m_fixed, m_startInternal, TransformUniformScale(GetSpace()), GetNonUniformScale(),
|
||||
TransformNormalizedScale(GetLocalTransform()),
|
||||
GridSnapAction(gridSnapParams, mouseInteraction.m_keyboardModifiers.Alt()), mouseInteraction);
|
||||
TransformNormalizedScale(GetLocalTransform()), gridSnapParams, mouseInteraction);
|
||||
|
||||
// display the exact hit (ray intersection) of the mouse pick on the manipulator
|
||||
DrawTransformAxes(
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
class ManipulatorView;
|
||||
struct GridSnapAction;
|
||||
struct GridSnapParameters;
|
||||
|
||||
/// PlanarManipulator serves as a visual tool for users to modify values
|
||||
/// in two dimension in a plane defined two non-collinear axes in 3D space.
|
||||
@@ -58,7 +58,6 @@ namespace AzToolsFramework
|
||||
{
|
||||
AZ::Vector3 m_localPosition; ///< The current position of the manipulator in local space.
|
||||
AZ::Vector3 m_localHitPosition; ///< The intersection point in local space between the ray and the manipulator when the mouse down event happens.
|
||||
AZ::Vector3 m_snapOffset; ///< The snap offset amount to ensure manipulator is aligned to the grid.
|
||||
};
|
||||
|
||||
/// The state of the manipulator during an interaction.
|
||||
@@ -120,7 +119,6 @@ namespace AzToolsFramework
|
||||
{
|
||||
AZ::Vector3 m_localPosition; ///< The starting position of the manipulator in local space.
|
||||
AZ::Vector3 m_localHitPosition; ///< The intersection point in world space between the ray and the manipulator when the mouse down event happens.
|
||||
AZ::Vector3 m_snapOffset; ///< The snap offset amount to ensure manipulator is aligned to the grid.
|
||||
};
|
||||
|
||||
Fixed m_fixed;
|
||||
@@ -134,12 +132,11 @@ namespace AzToolsFramework
|
||||
|
||||
static StartInternal CalculateManipulationDataStart(
|
||||
const Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale,
|
||||
const AZ::Transform& localTransform, const GridSnapAction& gridSnapAction,
|
||||
const ViewportInteraction::MouseInteraction& interaction, float intersectionDistance);
|
||||
const AZ::Transform& localTransform, const ViewportInteraction::MouseInteraction& interaction, float intersectionDistance);
|
||||
|
||||
static Action CalculateManipulationDataAction(
|
||||
const Fixed& fixed, const StartInternal& startInternal, const AZ::Transform& worldFromLocal,
|
||||
const AZ::Vector3& nonUniformScale, const AZ::Transform& localTransform,
|
||||
const GridSnapAction& gridSnapAction, const ViewportInteraction::MouseInteraction& interaction);
|
||||
const Fixed& fixed, const StartInternal& startInternal, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale,
|
||||
const AZ::Transform& localTransform, const GridSnapParameters& gridSnapParams,
|
||||
const ViewportInteraction::MouseInteraction& interaction);
|
||||
};
|
||||
} // namespace AzToolsFramework
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
|
||||
#include <AzToolsFramework/Entity/EditorEntityHelpers.h>
|
||||
#include <AzToolsFramework/Prefab/Instance/Instance.h>
|
||||
#include <AzToolsFramework/Prefab/PrefabDomUtils.h>
|
||||
#include <AzToolsFramework/Prefab/Instance/InstanceEntityMapperInterface.h>
|
||||
#include <AzToolsFramework/Prefab/Instance/TemplateInstanceMapperInterface.h>
|
||||
|
||||
@@ -49,8 +50,7 @@ namespace AzToolsFramework
|
||||
m_alias = GenerateInstanceAlias();
|
||||
m_containerEntity = containerEntity ? AZStd::move(containerEntity)
|
||||
: AZStd::make_unique<AZ::Entity>();
|
||||
EntityAlias containerEntityAlias = GenerateEntityAlias();
|
||||
RegisterEntity(m_containerEntity->GetId(), containerEntityAlias);
|
||||
RegisterEntity(m_containerEntity->GetId(), PrefabDomUtils::ContainerEntityName);
|
||||
}
|
||||
|
||||
Instance::~Instance()
|
||||
@@ -311,8 +311,15 @@ namespace AzToolsFramework
|
||||
Instance& Instance::AddInstance(AZStd::unique_ptr<Instance> instance)
|
||||
{
|
||||
InstanceAlias newInstanceAlias = GenerateInstanceAlias();
|
||||
return AddInstance(AZStd::move(instance), newInstanceAlias);
|
||||
}
|
||||
|
||||
Instance& Instance::AddInstance(AZStd::unique_ptr<Instance> instance, InstanceAlias newInstanceAlias)
|
||||
{
|
||||
AZ_Assert(instance.get(), "instance argument is nullptr");
|
||||
AZ_Assert(m_nestedInstances.find(newInstanceAlias) == m_nestedInstances.end(), "InstanceAlias' unique id collision, this should never happen.");
|
||||
AZ_Assert(
|
||||
m_nestedInstances.find(newInstanceAlias) == m_nestedInstances.end(),
|
||||
"InstanceAlias' unique id collision, this should never happen.");
|
||||
instance->m_parent = this;
|
||||
instance->m_alias = newInstanceAlias;
|
||||
return *(m_nestedInstances[newInstanceAlias] = std::move(instance));
|
||||
@@ -613,6 +620,7 @@ namespace AzToolsFramework
|
||||
|
||||
AZStd::unique_ptr<AZ::Entity> Instance::DetachContainerEntity()
|
||||
{
|
||||
m_instanceEntityMapper->UnregisterEntity(m_containerEntity->GetId());
|
||||
return AZStd::move(m_containerEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ namespace AzToolsFramework
|
||||
using EntityAliasOptionalReference = AZStd::optional<AZStd::reference_wrapper<EntityAlias>>;
|
||||
using InstanceOptionalReference = AZStd::optional<AZStd::reference_wrapper<Instance>>;
|
||||
using InstanceOptionalConstReference = AZStd::optional<AZStd::reference_wrapper<const Instance>>;
|
||||
|
||||
using InstanceSet = AZStd::unordered_set<Instance*>;
|
||||
using InstanceSetConstReference = AZStd::optional<AZStd::reference_wrapper<const InstanceSet>>;
|
||||
using EntityOptionalReference = AZStd::optional<AZStd::reference_wrapper<AZ::Entity>>;
|
||||
@@ -85,12 +86,14 @@ namespace AzToolsFramework
|
||||
bool AddEntity(AZ::Entity& entity);
|
||||
bool AddEntity(AZ::Entity& entity, EntityAlias entityAlias);
|
||||
AZStd::unique_ptr<AZ::Entity> DetachEntity(const AZ::EntityId& entityId);
|
||||
void DetachEntities(const AZStd::function<void(AZStd::unique_ptr<AZ::Entity>)>& callback);
|
||||
void DetachNestedEntities(const AZStd::function<void(AZStd::unique_ptr<AZ::Entity>)>& callback);
|
||||
void RemoveNestedEntities(const AZStd::function<bool(const AZStd::unique_ptr<AZ::Entity>&)>& filter);
|
||||
|
||||
void Reset();
|
||||
|
||||
Instance& AddInstance(AZStd::unique_ptr<Instance> instance);
|
||||
Instance& AddInstance(AZStd::unique_ptr<Instance> instance, InstanceAlias instanceAlias);
|
||||
AZStd::unique_ptr<Instance> DetachNestedInstance(const InstanceAlias& instanceAlias);
|
||||
|
||||
/**
|
||||
@@ -171,6 +174,8 @@ namespace AzToolsFramework
|
||||
static EntityAlias GenerateEntityAlias();
|
||||
AliasPath GetAbsoluteInstanceAliasPath() const;
|
||||
|
||||
static InstanceAlias GenerateInstanceAlias();
|
||||
|
||||
protected:
|
||||
/**
|
||||
* Gets the entities owned by this instance
|
||||
@@ -182,14 +187,11 @@ namespace AzToolsFramework
|
||||
|
||||
void ClearEntities();
|
||||
|
||||
void DetachEntities(const AZStd::function<void(AZStd::unique_ptr<AZ::Entity>)>& callback);
|
||||
void RemoveEntities(const AZStd::function<bool(const AZStd::unique_ptr<AZ::Entity>&)>& filter);
|
||||
|
||||
bool RegisterEntity(const AZ::EntityId& entityId, const EntityAlias& entityAlias);
|
||||
AZStd::unique_ptr<AZ::Entity> DetachEntity(const EntityAlias& entityAlias);
|
||||
|
||||
static InstanceAlias GenerateInstanceAlias();
|
||||
|
||||
// Provide access to private data members in the serializer
|
||||
friend class JsonInstanceSerializer;
|
||||
friend class InstanceEntityIdMapper;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user