Merge branch 'development' of https://github.com/o3de/o3de into jckand/PrefabTestOptimization

Signed-off-by: jckand-amzn <82226555+jckand-amzn@users.noreply.github.com>
This commit is contained in:
jckand-amzn
2021-12-02 11:55:45 -06:00
241 changed files with 5130 additions and 1115 deletions
+124
View File
@@ -0,0 +1,124 @@
#
# Copyright (c) Contributors to the Open 3D Engine Project.
# For complete copyright and license terms please see the LICENSE at the root of this distribution.
#
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
#
import os, traceback, binascii, sys, json, pathlib, logging
import azlmbr.math
import azlmbr.bus
from scene_helpers import *
#
# SceneAPI Processor
#
def update_manifest(scene):
import uuid
import azlmbr.scene as sceneApi
import azlmbr.scene.graph
from scene_api import scene_data as sceneData
graph = sceneData.SceneGraph(scene.graph)
# Get a list of all the mesh nodes, as well as all the nodes
mesh_name_list, all_node_paths = get_mesh_node_names(graph)
mesh_name_list.sort(key=lambda node: str.casefold(node.get_path()))
scene_manifest = sceneData.SceneManifest()
clean_filename = scene.sourceFilename.replace('.', '_')
# Compute the filename of the scene file
source_basepath = scene.watchFolder
source_relative_path = os.path.dirname(os.path.relpath(clean_filename, source_basepath))
source_filename_only = os.path.basename(clean_filename)
created_entities = []
previous_entity_id = azlmbr.entity.InvalidEntityId
first_mesh = True
# Make a list of mesh node paths
mesh_path_list = list(map(lambda node: node.get_path(), mesh_name_list))
# Assume the first mesh is the main mesh
main_mesh = mesh_name_list[0]
mesh_path = main_mesh.get_path()
# Create a unique mesh group name using the filename + node name
mesh_group_name = '{}_{}'.format(source_filename_only, main_mesh.get_name())
# Remove forbidden filename characters from the name since this will become a file on disk later
mesh_group_name = "".join(char for char in mesh_group_name if char not in "|<>:\"/?*\\")
# Add the MeshGroup to the manifest and give it a unique ID
mesh_group = scene_manifest.add_mesh_group(mesh_group_name)
mesh_group['id'] = '{' + str(uuid.uuid5(uuid.NAMESPACE_DNS, source_filename_only + mesh_path)) + '}'
# Set our current node as the only node that is included in this MeshGroup
scene_manifest.mesh_group_select_node(mesh_group, mesh_path)
# Explicitly remove all other nodes to prevent implicit inclusions
for node in mesh_path_list:
if node != mesh_path:
scene_manifest.mesh_group_unselect_node(mesh_group, node)
# Create a LOD rule
lod_rule = scene_manifest.mesh_group_add_lod_rule(mesh_group)
# Loop all the mesh nodes after the first
for x in mesh_path_list[1:]:
# Add a new LOD level
lod = scene_manifest.lod_rule_add_lod(lod_rule)
# Select the current mesh for this LOD level
scene_manifest.lod_select_node(lod, x)
# Unselect every other mesh for this LOD level
for y in mesh_path_list:
if y != x:
scene_manifest.lod_unselect_node(lod, y)
# Create an editor entity
entity_id = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "CreateEditorReadyEntity", mesh_group_name)
# Add an EditorMeshComponent to the entity
editor_mesh_component = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "GetOrAddComponentByTypeName", entity_id, "AZ::Render::EditorMeshComponent")
# Set the ModelAsset assetHint to the relative path of the input asset + the name of the MeshGroup we just created + the azmodel extension
# The MeshGroup we created will be output as a product in the asset's path named mesh_group_name.azmodel
# The assetHint will be converted to an AssetId later during prefab loading
json_update = json.dumps({
"Controller": { "Configuration": { "ModelAsset": {
"assetHint": os.path.join(source_relative_path, mesh_group_name) + ".azmodel" }}}
});
# Apply the JSON above to the component we created
result = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "UpdateComponentForEntity", entity_id, editor_mesh_component, json_update)
if not result:
raise RuntimeError("UpdateComponentForEntity failed for Mesh component")
create_prefab(scene_manifest, source_filename_only, [entity_id])
# Convert the manifest to a JSON string and return it
new_manifest = scene_manifest.export()
return new_manifest
sceneJobHandler = None
def on_update_manifest(args):
try:
scene = args[0]
return update_manifest(scene)
except RuntimeError as err:
print (f'ERROR - {err}')
log_exception_traceback()
except:
log_exception_traceback()
global sceneJobHandler
sceneJobHandler = None
# try to create SceneAPI handler for processing
try:
import azlmbr.scene as sceneApi
if (sceneJobHandler == None):
sceneJobHandler = sceneApi.ScriptBuildingNotificationBusHandler()
sceneJobHandler.connect()
sceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest)
except:
sceneJobHandler = None
@@ -0,0 +1,95 @@
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import traceback, logging, json
from typing import Tuple, List
import azlmbr.bus
from scene_api import scene_data as sceneData
from scene_api.scene_data import SceneGraphName
def log_exception_traceback():
"""
Outputs an exception stacktrace.
"""
data = traceback.format_exc()
logger = logging.getLogger('python')
logger.error(data)
def sanitize_name_for_disk(name: str):
"""
Removes illegal filename characters from a string.
:param name: String to clean.
:return: Name with illegal characters removed.
"""
return "".join(char for char in name if char not in "|<>:\"/?*\\")
def get_mesh_node_names(scene_graph: sceneData.SceneGraph) -> Tuple[List[SceneGraphName], List[str]]:
"""
Returns a tuple of all the mesh nodes as well as all the node paths
:param scene_graph: Scene graph to search
:return: Tuple of [Mesh Nodes, All Node Paths]
"""
import azlmbr.scene as sceneApi
import azlmbr.scene.graph
mesh_data_list = []
node = scene_graph.get_root()
children = []
paths = []
while node.IsValid():
# store children to process after siblings
if scene_graph.has_node_child(node):
children.append(scene_graph.get_node_child(node))
node_name = sceneData.SceneGraphName(scene_graph.get_node_name(node))
paths.append(node_name.get_path())
# store any node that has mesh data content
node_content = scene_graph.get_node_content(node)
if node_content.CastWithTypeName('MeshData'):
if scene_graph.is_node_end_point(node) is False:
if len(node_name.get_path()):
mesh_data_list.append(sceneData.SceneGraphName(scene_graph.get_node_name(node)))
# advance to next node
if scene_graph.has_node_sibling(node):
node = scene_graph.get_node_sibling(node)
elif children:
node = children.pop()
else:
node = azlmbr.scene.graph.NodeIndex()
return mesh_data_list, paths
def create_prefab(scene_manifest: sceneData.SceneManifest, prefab_name: str, entities: list) -> None:
prefab_filename = prefab_name + ".prefab"
created_template_id = azlmbr.prefab.PrefabSystemScriptingBus(azlmbr.bus.Broadcast, "CreatePrefab", entities,
prefab_filename)
if created_template_id is None or created_template_id == azlmbr.prefab.InvalidTemplateId:
raise RuntimeError("CreatePrefab {} failed".format(prefab_filename))
# Convert the prefab to a JSON string
output = azlmbr.prefab.PrefabLoaderScriptingBus(azlmbr.bus.Broadcast, "SaveTemplateToString", created_template_id)
if output is not None and output.IsSuccess():
json_string = output.GetValue()
uuid = azlmbr.math.Uuid_CreateRandom().ToString()
json_result = json.loads(json_string)
# Add a PrefabGroup to the manifest and store the JSON on it
scene_manifest.add_prefab_group(prefab_name, uuid, json_result)
else:
raise RuntimeError(
"SaveTemplateToString failed for template id {}, prefab {}".format(created_template_id, prefab_filename))
@@ -5,55 +5,16 @@
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
#
import os, traceback, binascii, sys, json, pathlib, logging
import azlmbr.math
import azlmbr.bus
import azlmbr.math
from scene_helpers import *
#
# SceneAPI Processor
#
def log_exception_traceback():
data = traceback.format_exc()
logger = logging.getLogger('python')
logger.error(data)
def get_mesh_node_names(sceneGraph):
import azlmbr.scene as sceneApi
import azlmbr.scene.graph
from scene_api import scene_data as sceneData
meshDataList = []
node = sceneGraph.get_root()
children = []
paths = []
while node.IsValid():
# store children to process after siblings
if sceneGraph.has_node_child(node):
children.append(sceneGraph.get_node_child(node))
nodeName = sceneData.SceneGraphName(sceneGraph.get_node_name(node))
paths.append(nodeName.get_path())
# store any node that has mesh data content
nodeContent = sceneGraph.get_node_content(node)
if nodeContent.CastWithTypeName('MeshData'):
if sceneGraph.is_node_end_point(node) is False:
if (len(nodeName.get_path())):
meshDataList.append(sceneData.SceneGraphName(sceneGraph.get_node_name(node)))
# advance to next node
if sceneGraph.has_node_sibling(node):
node = sceneGraph.get_node_sibling(node)
elif children:
node = children.pop()
else:
node = azlmbr.scene.graph.NodeIndex()
return meshDataList, paths
def add_material_component(entity_id):
# Create an override AZ::Render::EditorMaterialComponent
editor_material_component = azlmbr.entity.EntityUtilityBus(
@@ -64,24 +25,24 @@ def add_material_component(entity_id):
# this fills out the material asset to a known product AZMaterial asset relative path
json_update = json.dumps({
"Controller": { "Configuration": { "materials": [
{
"Key": {},
"Value": { "MaterialAsset":{
"assetHint": "materials/basic_grey.azmaterial"
}}
}]
}}
});
result = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "UpdateComponentForEntity", entity_id, editor_material_component, json_update)
"Controller": {"Configuration": {"materials": [
{
"Key": {},
"Value": {"MaterialAsset": {
"assetHint": "materials/basic_grey.azmaterial"
}}
}]
}}
})
result = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "UpdateComponentForEntity", entity_id,
editor_material_component, json_update)
if not result:
raise RuntimeError("UpdateComponentForEntity for editor_material_component failed")
def update_manifest(scene):
import json
import uuid, os
import azlmbr.scene as sceneApi
import azlmbr.scene.graph
from scene_api import scene_data as sceneData
@@ -89,9 +50,9 @@ def update_manifest(scene):
# Get a list of all the mesh nodes, as well as all the nodes
mesh_name_list, all_node_paths = get_mesh_node_names(graph)
scene_manifest = sceneData.SceneManifest()
clean_filename = scene.sourceFilename.replace('.', '_')
# Compute the filename of the scene file
source_basepath = scene.watchFolder
source_relative_path = os.path.dirname(os.path.relpath(clean_filename, source_basepath))
@@ -108,7 +69,7 @@ def update_manifest(scene):
# Create a unique mesh group name using the filename + node name
mesh_group_name = '{}_{}'.format(source_filename_only, mesh_name.get_name())
# Remove forbidden filename characters from the name since this will become a file on disk later
mesh_group_name = "".join(char for char in mesh_group_name if char not in "|<>:\"/?*\\")
mesh_group_name = sanitize_name_for_disk(mesh_group_name)
# Add the MeshGroup to the manifest and give it a unique ID
mesh_group = scene_manifest.add_mesh_group(mesh_group_name)
mesh_group['id'] = '{' + str(uuid.uuid5(uuid.NAMESPACE_DNS, source_filename_only + mesh_path)) + '}'
@@ -129,16 +90,18 @@ def update_manifest(scene):
# Create an editor entity
entity_id = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "CreateEditorReadyEntity", mesh_group_name)
# Add an EditorMeshComponent to the entity
editor_mesh_component = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "GetOrAddComponentByTypeName", entity_id, "AZ::Render::EditorMeshComponent")
# Set the ModelAsset assetHint to the relative path of the input asset + the name of the MeshGroup we just created + the azmodel extension
# The MeshGroup we created will be output as a product in the asset's path named mesh_group_name.azmodel
# The assetHint will be converted to an AssetId later during prefab loading
editor_mesh_component = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "GetOrAddComponentByTypeName",
entity_id, "AZ::Render::EditorMeshComponent")
# Set the ModelAsset assetHint to the relative path of the input asset + the name of the MeshGroup we just
# created + the azmodel extension The MeshGroup we created will be output as a product in the asset's path
# named mesh_group_name.azmodel The assetHint will be converted to an AssetId later during prefab loading
json_update = json.dumps({
"Controller": { "Configuration": { "ModelAsset": {
"assetHint": os.path.join(source_relative_path, mesh_group_name) + ".azmodel" }}}
});
"Controller": {"Configuration": {"ModelAsset": {
"assetHint": os.path.join(source_relative_path, mesh_group_name) + ".azmodel"}}}
})
# Apply the JSON above to the component we created
result = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "UpdateComponentForEntity", entity_id, editor_mesh_component, json_update)
result = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "UpdateComponentForEntity", entity_id,
editor_mesh_component, json_update)
if not result:
raise RuntimeError("UpdateComponentForEntity failed for Mesh component")
@@ -149,17 +112,19 @@ def update_manifest(scene):
add_material_component(entity_id)
# Get the transform component
transform_component = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "GetOrAddComponentByTypeName", entity_id, "27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0")
transform_component = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "GetOrAddComponentByTypeName",
entity_id, "27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0")
# Set this entity to be a child of the last entity we created
# This is just an example of how to do parenting and isn't necessarily useful to parent everything like this
if previous_entity_id is not None:
transform_json = json.dumps({
"Parent Entity" : previous_entity_id.to_json()
});
"Parent Entity": previous_entity_id.to_json()
})
# Apply the JSON update
result = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "UpdateComponentForEntity", entity_id, transform_component, transform_json)
result = azlmbr.entity.EntityUtilityBus(azlmbr.bus.Broadcast, "UpdateComponentForEntity", entity_id,
transform_component, transform_json)
if not result:
raise RuntimeError("UpdateComponentForEntity failed for Transform component")
@@ -171,37 +136,23 @@ def update_manifest(scene):
created_entities.append(entity_id)
# Create a prefab with all our entities
prefab_filename = source_filename_only + ".prefab"
created_template_id = azlmbr.prefab.PrefabSystemScriptingBus(azlmbr.bus.Broadcast, "CreatePrefab", created_entities, prefab_filename)
if created_template_id == azlmbr.prefab.InvalidTemplateId:
raise RuntimeError("CreatePrefab {} failed".format(prefab_filename))
# Convert the prefab to a JSON string
output = azlmbr.prefab.PrefabLoaderScriptingBus(azlmbr.bus.Broadcast, "SaveTemplateToString", created_template_id)
if output.IsSuccess():
jsonString = output.GetValue()
uuid = azlmbr.math.Uuid_CreateRandom().ToString()
jsonResult = json.loads(jsonString)
# Add a PrefabGroup to the manifest and store the JSON on it
scene_manifest.add_prefab_group(source_filename_only, uuid, jsonResult)
else:
raise RuntimeError("SaveTemplateToString failed for template id {}, prefab {}".format(created_template_id, prefab_filename))
create_prefab(scene_manifest, source_filename_only, created_entities)
# Convert the manifest to a JSON string and return it
new_manifest = scene_manifest.export()
return new_manifest
sceneJobHandler = None
def on_update_manifest(args):
try:
scene = args[0]
return update_manifest(scene)
except RuntimeError as err:
print (f'ERROR - {err}')
print(f'ERROR - {err}')
log_exception_traceback()
except:
log_exception_traceback()
@@ -209,10 +160,12 @@ def on_update_manifest(args):
global sceneJobHandler
sceneJobHandler = None
# try to create SceneAPI handler for processing
try:
import azlmbr.scene as sceneApi
if (sceneJobHandler == None):
if sceneJobHandler is None:
sceneJobHandler = sceneApi.ScriptBuildingNotificationBusHandler()
sceneJobHandler.connect()
sceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest)
@@ -393,7 +393,7 @@ class AtomComponentProperties:
'name': 'PostFX Shape Weight Modifier',
'requires': [AtomComponentProperties.postfx_layer()],
'shapes': ['Axis Aligned Box Shape', 'Box Shape', 'Capsule Shape', 'Compound Shape', 'Cylinder Shape',
'Disk Shape', 'Polygon Prism Shape', 'Quad Shape', 'Sphere Shape', 'Vegetation Reference Shape'],
'Disk Shape', 'Polygon Prism Shape', 'Quad Shape', 'Sphere Shape', 'Shape Reference'],
}
return properties[property]
@@ -72,7 +72,7 @@ def Terrain_SupportsPhysics():
# 2) Create 2 test entities, one parent at 512.0, 512.0, 50.0 and one child at the default position and add the required components
entity1_components_to_add = ["Axis Aligned Box Shape", "Terrain Layer Spawner", "Terrain Height Gradient List", "Terrain Physics Heightfield Collider", "PhysX Heightfield Collider"]
entity2_components_to_add = ["Vegetation Reference Shape", "Gradient Transform Modifier", "FastNoise Gradient"]
entity2_components_to_add = ["Shape Reference", "Gradient Transform Modifier", "FastNoise Gradient"]
ball_components_to_add = ["Sphere Shape", "PhysX Collider", "PhysX Rigid Body"]
terrain_spawner_entity = hydra.Entity("TestEntity1")
terrain_spawner_entity.create_entity(azmath.Vector3(512.0, 512.0, 50.0), entity1_components_to_add)
@@ -78,7 +78,7 @@ def LayerSpawner_InheritBehaviorFlag():
# Create Vegetation area and assign a valid asset
veg_1 = hydra.Entity("veg_1")
veg_1.create_entity(
position, ["Vegetation Layer Spawner", "Vegetation Reference Shape", "Vegetation Asset List"]
position, ["Vegetation Layer Spawner", "Shape Reference", "Vegetation Asset List"]
)
set_dynamic_slice_asset(veg_1, 2, os.path.join("Slices", "PinkFlower.dynamicslice"))
veg_1.get_set_test(1, "Configuration|Shape Entity Id", blender_entity.id)
@@ -86,7 +86,7 @@ def LayerSpawner_InheritBehaviorFlag():
# Create second vegetation area and assign a valid asset
veg_2 = hydra.Entity("veg_2")
veg_2.create_entity(
position, ["Vegetation Layer Spawner", "Vegetation Reference Shape", "Vegetation Asset List"]
position, ["Vegetation Layer Spawner", "Shape Reference", "Vegetation Asset List"]
)
set_dynamic_slice_asset(veg_2, 2, os.path.join("Slices", "PurpleFlower.dynamicslice"))
veg_2.get_set_test(1, "Configuration|Shape Entity Id", blender_entity.id)
@@ -9,7 +9,7 @@ SPDX-License-Identifier: Apache-2.0 OR MIT
def LayerSpawner_InstancesPlantInAllSupportedShapes():
"""
Summary:
The level is loaded and vegetation area is created. Then the Vegetation Reference Shape
The level is loaded and vegetation area is created. Then the Shape Reference
component of vegetation area is pinned with entities of different shape components to check
if the vegetation plants in different shaped areas.
@@ -67,7 +67,7 @@ def LayerSpawner_InstancesPlantInAllSupportedShapes():
10.0, 10.0, 10.0,
asset_path)
vegetation.remove_component("Box Shape")
vegetation.add_component("Vegetation Reference Shape")
vegetation.add_component("Shape Reference")
# Create surface for planting on
dynveg.create_surface_entity("Surface Entity", entity_position, 60.0, 60.0, 1.0)
@@ -96,7 +96,7 @@ def AreaNodes_DependentComponentsAdded():
'SpawnerAreaNode': [
'Vegetation Layer Spawner',
'Vegetation Asset List',
'Vegetation Reference Shape'
'Shape Reference'
],
'MeshBlockerAreaNode': [
'Vegetation Layer Blocker (Mesh)',
@@ -104,7 +104,7 @@ def AreaNodes_DependentComponentsAdded():
],
'BlockerAreaNode': [
'Vegetation Layer Blocker',
'Vegetation Reference Shape'
'Shape Reference'
]
}
@@ -82,7 +82,7 @@ def Edit_DisabledNodeDuplication():
nodes = {
'SpawnerAreaNode': 'Vegetation Asset List',
'MeshBlockerAreaNode': 'Mesh',
'BlockerAreaNode': 'Vegetation Reference Shape',
'BlockerAreaNode': 'Shape Reference',
'FastNoiseGradientNode': 'Gradient Transform Modifier',
'ImageGradientNode': 'Gradient Transform Modifier',
'PerlinNoiseGradientNode': 'Gradient Transform Modifier',
@@ -104,7 +104,7 @@ def GradientNodes_DependentComponentsAdded():
# we will be checking for
commonComponents = [
'Gradient Transform Modifier',
'Vegetation Reference Shape'
'Shape Reference'
]
componentNames = []
for name in gradients:
@@ -114,7 +114,7 @@ def GradientNodes_DependentComponentsAdded():
# Create nodes for the gradients that have additional required dependencies and check if
# the Entity created by adding the node has the appropriate Component and required
# Gradient Transform Modifier and Vegetation Reference Shape components added automatically to it
# Gradient Transform Modifier and Shape Reference components added automatically to it
newGraph = graph.GraphManagerRequestBus(bus.Broadcast, 'GetGraph', newGraphId)
x = 10.0
y = 10.0
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,12 @@
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7e169277bca473325281d5fe043cffc9196bd3ef46f6bffbea6e0b5e3b7194a1
size 62700
@@ -0,0 +1,8 @@
{
"values": [
{
"$type": "ScriptProcessorRule",
"scriptFilename": "Editor/Scripts/auto_lod.py"
}
]
}
+5 -6
View File
@@ -75,17 +75,16 @@ void CImageEx::ReverseUpDown()
}
uint32* pPixData = GetData();
uint32* pReversePix = new uint32[GetWidth() * GetHeight()];
for (int i = GetHeight() - 1, i2 = 0; i >= 0; i--, i2++)
const int height = GetHeight();
const int width = GetWidth();
for (int i = 0; i < height / 2; i++)
{
for (int k = 0; k < GetWidth(); k++)
for (int j = 0; j < width; j++)
{
pReversePix[i2 * GetWidth() + k] = pPixData[i * GetWidth() + k];
AZStd::swap(pPixData[i * width + j], pPixData[(height - 1 - i) * width + j]);
}
}
Attach(pReversePix, GetWidth(), GetHeight());
}
void CImageEx::FillAlpha(unsigned char value)
@@ -53,7 +53,6 @@ static void OptimizedSetParent(QWidget* widget, QWidget* parent)
namespace AzQtComponents
{
static const FancyDockingDropZoneConstants g_FancyDockingConstants;
// Constant for the threshold in pixels for snapping to edges while dragging for docking
static const int g_snapThresholdInPixels = 15;
@@ -155,7 +154,7 @@ namespace AzQtComponents
// Timer for updating our hovered drop zone opacity
QObject::connect(m_dropZoneHoverFadeInTimer, &QTimer::timeout, this, &FancyDocking::onDropZoneHoverFadeInUpdate);
m_dropZoneHoverFadeInTimer->setInterval(g_FancyDockingConstants.dropZoneHoverFadeUpdateIntervalMS);
m_dropZoneHoverFadeInTimer->setInterval(FancyDockingDropZoneConstants::dropZoneHoverFadeUpdateIntervalMS);
QIcon dragIcon = QIcon(QStringLiteral(":/Cursors/Grabbing.svg"));
m_dragCursor = QCursor(dragIcon.pixmap(16), 5, 2);
}
@@ -333,13 +332,13 @@ namespace AzQtComponents
*/
void FancyDocking::onDropZoneHoverFadeInUpdate()
{
const qreal dropZoneHoverOpacity = g_FancyDockingConstants.dropZoneHoverFadeIncrement + m_dropZoneState.dropZoneHoverOpacity();
const qreal dropZoneHoverOpacity = FancyDockingDropZoneConstants::dropZoneHoverFadeIncrement + m_dropZoneState.dropZoneHoverOpacity();
// Once we've reached the full drop zone opacity, cut it off in case we
// went over and stop the timer
if (dropZoneHoverOpacity >= g_FancyDockingConstants.dropZoneOpacity)
if (dropZoneHoverOpacity >= FancyDockingDropZoneConstants::dropZoneOpacity)
{
m_dropZoneState.setDropZoneHoverOpacity(g_FancyDockingConstants.dropZoneOpacity);
m_dropZoneState.setDropZoneHoverOpacity(FancyDockingDropZoneConstants::dropZoneOpacity);
m_dropZoneHoverFadeInTimer->stop();
}
else
@@ -792,12 +791,12 @@ namespace AzQtComponents
QPoint mainWindowTopLeft = multiscreenMapFromGlobal(mainWindow->mapToGlobal(mainWindowRect.topLeft()));
QPoint mainWindowTopRight = multiscreenMapFromGlobal(mainWindow->mapToGlobal(mainWindowRect.topRight()));
QPoint mainWindowBottomLeft = multiscreenMapFromGlobal(mainWindow->mapToGlobal(mainWindowRect.bottomLeft()));
QSize absoluteLeftRightSize(g_FancyDockingConstants.absoluteDropZoneSizeInPixels, mainWindowRect.height());
QSize absoluteLeftRightSize(FancyDockingDropZoneConstants::absoluteDropZoneSizeInPixels, mainWindowRect.height());
QRect absoluteLeftDropZone(mainWindowTopLeft, absoluteLeftRightSize);
QRect absoluteRightDropZone(mainWindowTopRight - QPoint(g_FancyDockingConstants.absoluteDropZoneSizeInPixels, 0), absoluteLeftRightSize);
QSize absoluteTopBottomSize(mainWindowRect.width(), g_FancyDockingConstants.absoluteDropZoneSizeInPixels);
QRect absoluteRightDropZone(mainWindowTopRight - QPoint(FancyDockingDropZoneConstants::absoluteDropZoneSizeInPixels, 0), absoluteLeftRightSize);
QSize absoluteTopBottomSize(mainWindowRect.width(), FancyDockingDropZoneConstants::absoluteDropZoneSizeInPixels);
QRect absoluteTopDropZone(mainWindowTopLeft, absoluteTopBottomSize);
QRect absoluteBottomDropZone(mainWindowBottomLeft - QPoint(0, g_FancyDockingConstants.absoluteDropZoneSizeInPixels), absoluteTopBottomSize);
QRect absoluteBottomDropZone(mainWindowBottomLeft - QPoint(0, FancyDockingDropZoneConstants::absoluteDropZoneSizeInPixels), absoluteTopBottomSize);
// If the drop target is a main window, then we will only show the absolute
// drop zone if the cursor is in that zone already
@@ -986,16 +985,16 @@ namespace AzQtComponents
switch (m_dropZoneState.absoluteDropZoneArea())
{
case Qt::LeftDockWidgetArea:
dockRect.setX(dockRect.x() + g_FancyDockingConstants.absoluteDropZoneSizeInPixels);
dockRect.setX(dockRect.x() + FancyDockingDropZoneConstants::absoluteDropZoneSizeInPixels);
break;
case Qt::RightDockWidgetArea:
dockRect.setWidth(dockRect.width() - g_FancyDockingConstants.absoluteDropZoneSizeInPixels);
dockRect.setWidth(dockRect.width() - FancyDockingDropZoneConstants::absoluteDropZoneSizeInPixels);
break;
case Qt::TopDockWidgetArea:
dockRect.setY(dockRect.y() + g_FancyDockingConstants.absoluteDropZoneSizeInPixels);
dockRect.setY(dockRect.y() + FancyDockingDropZoneConstants::absoluteDropZoneSizeInPixels);
break;
case Qt::BottomDockWidgetArea:
dockRect.setHeight(dockRect.height() - g_FancyDockingConstants.absoluteDropZoneSizeInPixels);
dockRect.setHeight(dockRect.height() - FancyDockingDropZoneConstants::absoluteDropZoneSizeInPixels);
break;
}
@@ -1034,15 +1033,15 @@ namespace AzQtComponents
// Set the drop zone width/height to the default, but if the dock widget
// width and/or height is below the threshold, then switch to scaling them
// down accordingly
int dropZoneWidth = g_FancyDockingConstants.dropZoneSizeInPixels;
if (dockWidth < g_FancyDockingConstants.minDockSizeBeforeDropZoneScalingInPixels)
int dropZoneWidth = FancyDockingDropZoneConstants::dropZoneSizeInPixels;
if (dockWidth < FancyDockingDropZoneConstants::minDockSizeBeforeDropZoneScalingInPixels)
{
dropZoneWidth = aznumeric_cast<int>(dockWidth * g_FancyDockingConstants.dropZoneScaleFactor);
dropZoneWidth = aznumeric_cast<int>(dockWidth * FancyDockingDropZoneConstants::dropZoneScaleFactor);
}
int dropZoneHeight = g_FancyDockingConstants.dropZoneSizeInPixels;
if (dockHeight < g_FancyDockingConstants.minDockSizeBeforeDropZoneScalingInPixels)
int dropZoneHeight = FancyDockingDropZoneConstants::dropZoneSizeInPixels;
if (dockHeight < FancyDockingDropZoneConstants::minDockSizeBeforeDropZoneScalingInPixels)
{
dropZoneHeight = aznumeric_cast<int>(dockHeight * g_FancyDockingConstants.dropZoneScaleFactor);
dropZoneHeight = aznumeric_cast<int>(dockHeight * FancyDockingDropZoneConstants::dropZoneScaleFactor);
}
// Calculate the inner corners to be used when constructing the drop zone polygons
@@ -1078,7 +1077,7 @@ namespace AzQtComponents
int innerDropZoneWidth = m_dropZoneState.innerDropZoneRect().width();
int innerDropZoneHeight = m_dropZoneState.innerDropZoneRect().height();
int centerDropZoneDiameter = (innerDropZoneWidth < innerDropZoneHeight) ? innerDropZoneWidth : innerDropZoneHeight;
centerDropZoneDiameter = aznumeric_cast<int>(centerDropZoneDiameter * g_FancyDockingConstants.centerTabDropZoneScale);
centerDropZoneDiameter = aznumeric_cast<int>(centerDropZoneDiameter * FancyDockingDropZoneConstants::centerTabDropZoneScale);
// Setup our center tab drop zone
const QSize centerDropZoneSize(centerDropZoneDiameter, centerDropZoneDiameter);
@@ -1986,7 +1985,7 @@ namespace AzQtComponents
// hasn't faded in all the way yet, then ignore the drop zone area
// which will make the widget floating
bool modifiedKeyPressed = FancyDockingDropZoneWidget::CheckModifierKey();
if (modifiedKeyPressed || m_dropZoneState.dropZoneHoverOpacity() != g_FancyDockingConstants.dropZoneOpacity)
if (modifiedKeyPressed || m_dropZoneState.dropZoneHoverOpacity() != FancyDockingDropZoneConstants::dropZoneOpacity)
{
area = Qt::NoDockWidgetArea;
}
@@ -3026,7 +3025,7 @@ namespace AzQtComponents
{
bool modifiedKeyPressed = FancyDockingDropZoneWidget::CheckModifierKey();
m_ghostWidget->setWindowOpacity(modifiedKeyPressed ? 1.0f : g_FancyDockingConstants.draggingDockWidgetOpacity);
m_ghostWidget->setWindowOpacity(modifiedKeyPressed ? 1.0f : FancyDockingDropZoneConstants::draggingDockWidgetOpacity);
m_ghostWidget->setPixmap(m_state.dockWidgetScreenGrab.screenGrab, m_state.placeholder(), m_state.placeholderScreen());
}
}
@@ -19,26 +19,6 @@
namespace AzQtComponents
{
static const FancyDockingDropZoneConstants g_Constants;
FancyDockingDropZoneConstants::FancyDockingDropZoneConstants()
{
draggingDockWidgetOpacity = 0.6;
dropZoneOpacity = 0.4;
dropZoneSizeInPixels = 40;
minDockSizeBeforeDropZoneScalingInPixels = dropZoneSizeInPixels * 3;
dropZoneScaleFactor = 0.25;
centerTabDropZoneScale = 0.5;
centerTabIconScale = 0.5;
dropZoneColor = QColor(155, 155, 155);
dropZoneBorderColor = Qt::black;
dropZoneBorderInPixels = 1;
absoluteDropZoneSizeInPixels = 25;
dockingTargetDelayMS = 110;
dropZoneHoverFadeUpdateIntervalMS = 20;
dropZoneHoverFadeIncrement = dropZoneOpacity / (dockingTargetDelayMS / dropZoneHoverFadeUpdateIntervalMS);
centerDropZoneIconPath = QString(":/stylesheet/img/UI20/docking/tabs_icon.svg");
}
FancyDockingDropZoneWidget::FancyDockingDropZoneWidget(QMainWindow* mainWindow, QWidget* coordinatesRelativeTo, QScreen* screen, FancyDockingDropZoneState* dropZoneState)
// NOTE: this will not work with multiple monitors if this widget has a parent. The floating drop zone
@@ -154,7 +134,7 @@ namespace AzQtComponents
// Draw all of the normal drop zones if they exist (if a dock widget is hovered over)
painter.setPen(Qt::NoPen);
painter.setOpacity(g_Constants.dropZoneOpacity);
painter.setOpacity(FancyDockingDropZoneConstants::dropZoneOpacity);
auto dropZones = m_dropZoneState->dropZones();
for (auto it = dropZones.cbegin(); it != dropZones.cend(); ++it)
{
@@ -189,7 +169,7 @@ namespace AzQtComponents
// Otherwise, set the normal color
else
{
painter.setBrush(g_Constants.dropZoneColor);
painter.setBrush(FancyDockingDropZoneConstants::dropZoneColor);
}
// negate the window position to offset everything by that much
@@ -214,8 +194,8 @@ namespace AzQtComponents
// Scale the tabs icon based on the drop zone size and our specified offset
// Doing this through QIcon to make sure that SVG is rendered already in desired resolution
const QSize& dropZoneSize = dropZoneRect.size();
const QSize requestedIconSize = dropZoneSize * g_Constants.centerTabIconScale;
const QIcon dropZoneIcon = QIcon(g_Constants.centerDropZoneIconPath);
const QSize requestedIconSize = dropZoneSize * FancyDockingDropZoneConstants::centerTabIconScale;
const QIcon dropZoneIcon = QIcon(FancyDockingDropZoneConstants::centerDropZoneIconPath);
const QPixmap dropZonePixmap = dropZoneIcon.pixmap(requestedIconSize);
const QSize receivedIconSize = dropZoneIcon.actualSize(requestedIconSize);
@@ -264,7 +244,7 @@ namespace AzQtComponents
}
else
{
painter.setBrush(g_Constants.dropZoneColor);
painter.setBrush(FancyDockingDropZoneConstants::dropZoneColor);
}
painter.drawRect(absoluteDropZoneRect);
@@ -313,8 +293,8 @@ namespace AzQtComponents
const QPoint innerBottomRight = innerDropZoneRect.bottomRight();
// Draw the lines using the appropriate pen
QPen dropZoneBorderPen(g_Constants.dropZoneBorderColor);
dropZoneBorderPen.setWidth(g_Constants.dropZoneBorderInPixels);
QPen dropZoneBorderPen(FancyDockingDropZoneConstants::dropZoneBorderColor);
dropZoneBorderPen.setWidth(FancyDockingDropZoneConstants::dropZoneBorderInPixels);
painter.setPen(dropZoneBorderPen);
painter.setOpacity(1);
painter.drawLine(topLeft, innerTopLeft);
@@ -28,63 +28,58 @@ class QPainter;
namespace AzQtComponents
{
struct AZ_QT_COMPONENTS_API FancyDockingDropZoneConstants
namespace FancyDockingDropZoneConstants
{
// Constant for the opacity of the screen grab for the dock widget being dragged
qreal draggingDockWidgetOpacity;
static constexpr qreal draggingDockWidgetOpacity = 0.6;
// Constant for the opacity of the normal drop zones
qreal dropZoneOpacity;
static constexpr qreal dropZoneOpacity = 0.4;
// Constant for the default drop zone size (in pixels)
int dropZoneSizeInPixels;
static constexpr int dropZoneSizeInPixels = 40;
// Constant for the dock width/height size (in pixels) before we need to start
// scaling down the drop zone sizes, or else they will overlap with the center
// tab icon or each other
int minDockSizeBeforeDropZoneScalingInPixels;
static constexpr int minDockSizeBeforeDropZoneScalingInPixels = dropZoneSizeInPixels * 3;
// Constant for the factor by which we must scale down the drop zone sizes once
// the dock width/height size is too small
qreal dropZoneScaleFactor;
static constexpr qreal dropZoneScaleFactor = 0.25;
// Constant for the percentage to scale down the inner drop zone rectangle for the center tab drop zone
qreal centerTabDropZoneScale;
static constexpr qreal centerTabDropZoneScale = 0.5;
// Constant for the percentage to scale down the center tab drop zone for the center tab icon
qreal centerTabIconScale;
static constexpr qreal centerTabIconScale = 0.5;
// Constant for the drop zone hotspot default color
QColor dropZoneColor;
static const QColor dropZoneColor = QColor(155, 155, 155);
// Constant for the drop zone border color
QColor dropZoneBorderColor;
static const QColor dropZoneBorderColor = Qt::black;
// Constant for the border width in pixels separating the drop zones
int dropZoneBorderInPixels;
static constexpr int dropZoneBorderInPixels = 1;
// Constant for the border width in pixels separating the drop zones
int absoluteDropZoneSizeInPixels;
static constexpr int absoluteDropZoneSizeInPixels = 25;
// Constant for the delay (in milliseconds) before a drop zone becomes active
// once it is hovered over
int dockingTargetDelayMS;
static constexpr int dockingTargetDelayMS = 110;
// Constant for the rate at which we will update (fade in) the drop zone opacity
// when hovered over (in milliseconds)
int dropZoneHoverFadeUpdateIntervalMS;
static constexpr int dropZoneHoverFadeUpdateIntervalMS = 20;
// Constant for the incremental opacity increase for the hovered drop zone
// that will fade in to the full drop zone opacity in the desired time
qreal dropZoneHoverFadeIncrement;
static constexpr qreal dropZoneHoverFadeIncrement = dropZoneOpacity / (dockingTargetDelayMS / dropZoneHoverFadeUpdateIntervalMS);
// Constant for the path to the center drop zone tabs icon
QString centerDropZoneIconPath;
FancyDockingDropZoneConstants();
FancyDockingDropZoneConstants(const FancyDockingDropZoneConstants&) = delete;
FancyDockingDropZoneConstants& operator=(const FancyDockingDropZoneConstants&) = delete;
static const QString centerDropZoneIconPath = QStringLiteral(":/stylesheet/img/UI20/docking/tabs_icon.svg");
};
class FancyDockingDropZoneState
@@ -323,7 +323,7 @@ namespace AzQtComponents
saturation *= 2.0 - lightness;
}
double value = (lightness + saturation) / 2.0;
saturation = (2.0 * saturation) / (lightness + saturation);
saturation = qFuzzyIsNull(lightness + saturation) ? 0 : (2.0 * saturation) / (lightness + saturation);
m_hsv.saturation = AZ::GetClamp(saturation, 0.0, 1.0);
m_hsv.value = AZ::GetClamp(value, 0.0, 12.5);
@@ -341,11 +341,12 @@ namespace AzQtComponents
double saturation = m_hsv.saturation * m_hsv.value;
if (lightness <= 1.0)
{
saturation /= lightness;
saturation = (qFuzzyIsNull(lightness)) ? 0.0 : saturation / lightness;
}
else
{
saturation /= 2.0 - lightness;
double two_minus_lightness = 2.0 - lightness;
saturation = (qFuzzyIsNull(two_minus_lightness)) ? 0.0 : saturation / two_minus_lightness;
}
lightness /= 2.0;
@@ -164,11 +164,7 @@ namespace
}
}
#if AZ_TRAIT_DISABLE_FAILED_ZERO_COLOR_CONVERSION_TEST
TEST(AzQtComponents, DISABLED_ColorConversionsTestAllZeros)
#else
TEST(AzQtComponents, ColorConversionsTestAllZeros)
#endif // AZ_TRAIT_DISABLE_FAILED_ZERO_COLOR_CONVERSION_TEST
{
TestConversions({ 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 });
}
@@ -18,7 +18,7 @@
#define AZ_TRAIT_DISABLE_FAILED_ATOM_RPI_TESTS true
#define AZ_TRAIT_DISABLE_FAILED_ARCHIVE_TESTS true
#define AZ_TRAIT_DISABLE_FAILED_ZERO_COLOR_CONVERSION_TEST true
#define AZ_TRAIT_DISABLE_FAILED_FRAMEPROFILER_TEST true
#define AZ_TRAIT_DISABLE_FAILED_FRAMEWORK_TESTS true
#define AZ_TRAIT_DISABLE_FAILED_GRADIENT_SIGNAL_TESTS true
@@ -521,21 +521,18 @@ namespace AzToolsFramework
nestedInstanceLink.has_value(),
"A valid link was not found for one of the instances provided as input for the CreatePrefab operation.");
PrefabDomReference nestedInstanceLinkDom = nestedInstanceLink->get().GetLinkDom();
AZ_Assert(
nestedInstanceLinkDom.has_value(),
"A valid DOM was not found for the link corresponding to one of the instances provided as input for the "
"CreatePrefab operation.");
PrefabDomValueReference nestedInstanceLinkPatches =
PrefabDomUtils::FindPrefabDomValue(nestedInstanceLinkDom->get(), PrefabDomUtils::PatchesName);
AZ_Assert(
nestedInstanceLinkPatches.has_value(),
"A valid DOM for patches was not found for the link corresponding to one of the instances provided as input for the "
"CreatePrefab operation.");
PrefabDom patchesCopyForUndoSupport;
patchesCopyForUndoSupport.CopyFrom(nestedInstanceLinkPatches->get(), patchesCopyForUndoSupport.GetAllocator());
PrefabDomReference nestedInstanceLinkDom = nestedInstanceLink->get().GetLinkDom();
if (nestedInstanceLinkDom.has_value())
{
PrefabDomValueReference nestedInstanceLinkPatches =
PrefabDomUtils::FindPrefabDomValue(nestedInstanceLinkDom->get(), PrefabDomUtils::PatchesName);
if (nestedInstanceLinkPatches.has_value())
{
patchesCopyForUndoSupport.CopyFrom(nestedInstanceLinkPatches->get(), patchesCopyForUndoSupport.GetAllocator());
}
}
PrefabUndoHelpers::RemoveLink(
sourceInstance->GetTemplateId(), targetTemplateId, sourceInstance->GetInstanceAlias(), sourceInstance->GetLinkId(),
AZStd::move(patchesCopyForUndoSupport), undoBatch);
@@ -0,0 +1,150 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/Settings/SettingsRegistryMergeUtils.h>
#include <AzToolsFramework/Entity/EditorEntityHelpers.h>
#include <AzToolsFramework/ToolsComponents/TransformComponent.h>
#include <Prefab/PrefabTestComponent.h>
#include <Prefab/PrefabTestDomUtils.h>
#include <Prefab/PrefabTestFixture.h>
namespace UnitTest
{
using PrefabDeleteTest = PrefabTestFixture;
TEST_F(PrefabDeleteTest, DeleteEntitiesInInstance_DeleteSingleEntitySucceeds)
{
PrefabEntityResult createEntityResult = m_prefabPublicInterface->CreateEntity(AZ::EntityId(), AZ::Vector3());
// Verify that a valid entity is created.
AZ::EntityId testEntityId = createEntityResult.GetValue();
ASSERT_TRUE(testEntityId.IsValid());
AZ::Entity* testEntity = AzToolsFramework::GetEntityById(testEntityId);
ASSERT_TRUE(testEntity != nullptr);
m_prefabPublicInterface->DeleteEntitiesInInstance(AzToolsFramework::EntityIdList{ testEntityId });
// Verify that entity can't be found after deletion.
testEntity = AzToolsFramework::GetEntityById(testEntityId);
EXPECT_TRUE(testEntity == nullptr);
}
TEST_F(PrefabDeleteTest, DeleteEntitiesInInstance_DeleteSinglePrefabSucceeds)
{
PrefabEntityResult createEntityResult = m_prefabPublicInterface->CreateEntity(AZ::EntityId(), AZ::Vector3());
// Verify that a valid entity is created.
AZ::EntityId createdEntityId = createEntityResult.GetValue();
ASSERT_TRUE(createdEntityId.IsValid());
AZ::Entity* createdEntity = AzToolsFramework::GetEntityById(createdEntityId);
ASSERT_TRUE(createdEntity != nullptr);
// Rather than hardcode a path, use a path from settings registry since that will work on all platforms.
AZ::SettingsRegistryInterface* registry = AZ::SettingsRegistry::Get();
AZ::IO::FixedMaxPath path;
registry->Get(path.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
CreatePrefabResult createPrefabResult =
m_prefabPublicInterface->CreatePrefabInMemory(AzToolsFramework::EntityIdList{ createdEntityId }, path);
AZ::EntityId createdPrefabContainerId = createPrefabResult.GetValue();
ASSERT_TRUE(createdPrefabContainerId.IsValid());
AZ::Entity* prefabContainerEntity = AzToolsFramework::GetEntityById(createdPrefabContainerId);
ASSERT_TRUE(prefabContainerEntity != nullptr);
// Verify that the prefab container entity and the entity within are deleted.
m_prefabPublicInterface->DeleteEntitiesInInstance(AzToolsFramework::EntityIdList{ createdPrefabContainerId });
prefabContainerEntity = AzToolsFramework::GetEntityById(createdPrefabContainerId);
EXPECT_TRUE(prefabContainerEntity == nullptr);
createdEntity = AzToolsFramework::GetEntityById(createdEntityId);
EXPECT_TRUE(createdEntity == nullptr);
}
TEST_F(PrefabDeleteTest, DeleteEntitiesAndAllDescendantsInInstance_DeletingEntityDeletesChildEntityToo)
{
PrefabEntityResult parentEntityCreationResult = m_prefabPublicInterface->CreateEntity(AZ::EntityId(), AZ::Vector3());
// Verify that valid parent entity is created.
AZ::EntityId parentEntityId = parentEntityCreationResult.GetValue();
ASSERT_TRUE(parentEntityId.IsValid());
AZ::Entity* parentEntity = AzToolsFramework::GetEntityById(parentEntityId);
ASSERT_TRUE(parentEntity != nullptr);
// Verify that valid child entity is created.
PrefabEntityResult childEntityCreationResult = m_prefabPublicInterface->CreateEntity(parentEntityId, AZ::Vector3());
AZ::EntityId childEntityId = childEntityCreationResult.GetValue();
ASSERT_TRUE(childEntityId.IsValid());
AZ::Entity* childEntity = AzToolsFramework::GetEntityById(childEntityId);
ASSERT_TRUE(childEntity != nullptr);
// PrefabTestFixture won't add required editor components by default. Hence we add them here.
AddRequiredEditorComponents(childEntity);
AddRequiredEditorComponents(parentEntity);
// Parent the child entity under the parent entity.
AZ::TransformBus::Event(childEntityId, &AZ::TransformBus::Events::SetParent, parentEntityId);
// Delete parent entity and its children.
m_prefabPublicInterface->DeleteEntitiesAndAllDescendantsInInstance(AzToolsFramework::EntityIdList{ parentEntityId });
// Verify that both the parent and child entities are deleted.
parentEntity = AzToolsFramework::GetEntityById(parentEntityId);
EXPECT_TRUE(parentEntity == nullptr);
childEntity = AzToolsFramework::GetEntityById(childEntityId);
EXPECT_TRUE(childEntity == nullptr);
}
TEST_F(PrefabDeleteTest, DeleteEntitiesAndAllDescendantsInInstance_DeletingEntityDeletesChildPrefabToo)
{
PrefabEntityResult entityToBePutUnderPrefabResult = m_prefabPublicInterface->CreateEntity(AZ::EntityId(), AZ::Vector3());
// Verify that a valid entity is created that will be put in a prefab later.
AZ::EntityId entityToBePutUnderPrefabId = entityToBePutUnderPrefabResult.GetValue();
ASSERT_TRUE(entityToBePutUnderPrefabId.IsValid());
AZ::Entity* entityToBePutUnderPrefab = AzToolsFramework::GetEntityById(entityToBePutUnderPrefabId);
ASSERT_TRUE(entityToBePutUnderPrefab != nullptr);
// Verify that a valid parent entity is created.
PrefabEntityResult parentEntityCreationResult = m_prefabPublicInterface->CreateEntity(AZ::EntityId(), AZ::Vector3());
AZ::EntityId parentEntityId = parentEntityCreationResult.GetValue();
ASSERT_TRUE(parentEntityId.IsValid());
AZ::Entity* parentEntity = AzToolsFramework::GetEntityById(parentEntityId);
ASSERT_TRUE(parentEntity != nullptr);
// Rather than hardcode a path, use a path from settings registry since that will work on all platforms.
AZ::SettingsRegistryInterface* registry = AZ::SettingsRegistry::Get();
AZ::IO::FixedMaxPath path;
registry->Get(path.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
CreatePrefabResult createPrefabResult =
m_prefabPublicInterface->CreatePrefabInMemory(AzToolsFramework::EntityIdList{ entityToBePutUnderPrefabId }, path);
// Verify that a valid prefab container entity is created.
AZ::EntityId createdPrefabContainerId = createPrefabResult.GetValue();
ASSERT_TRUE(createdPrefabContainerId.IsValid());
AZ::Entity* prefabContainerEntity = AzToolsFramework::GetEntityById(createdPrefabContainerId);
ASSERT_TRUE(prefabContainerEntity != nullptr);
// PrefabTestFixture won't add required editor components by default. Hence we add them here.
AddRequiredEditorComponents(parentEntity);
AddRequiredEditorComponents(prefabContainerEntity);
// Parent the prefab under the parent entity.
AZ::TransformBus::Event(createdPrefabContainerId, &AZ::TransformBus::Events::SetParent, parentEntityId);
// Delete the parent entity.
m_prefabPublicInterface->DeleteEntitiesAndAllDescendantsInInstance(AzToolsFramework::EntityIdList{ parentEntityId });
// Validate that the parent and the prefab under it and the entity inside the prefab are all deleted.
parentEntity = AzToolsFramework::GetEntityById(parentEntityId);
ASSERT_TRUE(parentEntity == nullptr);
entityToBePutUnderPrefab = AzToolsFramework::GetEntityById(entityToBePutUnderPrefabId);
ASSERT_TRUE(entityToBePutUnderPrefab == nullptr);
prefabContainerEntity = AzToolsFramework::GetEntityById(createdPrefabContainerId);
EXPECT_TRUE(prefabContainerEntity == nullptr);
}
} // namespace UnitTest
@@ -57,6 +57,11 @@ namespace UnitTest
return AZStd::make_unique<PrefabTestToolsApplication>("PrefabTestApplication");
}
void PrefabTestFixture::PropagateAllTemplateChanges()
{
m_prefabSystemComponent->OnSystemTick();
}
AZ::Entity* PrefabTestFixture::CreateEntity(const char* entityName, const bool shouldActivate)
{
// Circumvent the EntityContext system and generate a new entity with a transformcomponent
@@ -125,4 +130,13 @@ namespace UnitTest
EXPECT_EQ(entityInInstance->GetState(), AZ::Entity::State::Active);
}
}
void PrefabTestFixture::AddRequiredEditorComponents(AZ::Entity* entity)
{
ASSERT_TRUE(entity != nullptr);
entity->Deactivate();
AzToolsFramework::EditorEntityContextRequestBus::Broadcast(
&AzToolsFramework::EditorEntityContextRequests::AddRequiredComponents, *entity);
entity->Activate();
}
}
@@ -52,6 +52,8 @@ namespace UnitTest
AZStd::unique_ptr<ToolsTestApplication> CreateTestApplication() override;
void PropagateAllTemplateChanges();
AZ::Entity* CreateEntity(const char* entityName, const bool shouldActivate = true);
void CompareInstances(const Instance& instanceA, const Instance& instanceB, bool shouldCompareLinkIds = true,
@@ -62,6 +64,8 @@ namespace UnitTest
//! Validates that all entities within a prefab instance are in 'Active' state.
void ValidateInstanceEntitiesActive(Instance& instance);
void AddRequiredEditorComponents(AZ::Entity* entity);
PrefabSystemComponent* m_prefabSystemComponent = nullptr;
PrefabLoaderInterface* m_prefabLoaderInterface = nullptr;
PrefabPublicInterface* m_prefabPublicInterface = nullptr;
@@ -128,7 +128,7 @@ namespace UnitTest
void ProcessDeferredUpdates()
{
// Force a prefab propagation for updates that are deferred to the next tick.
m_prefabSystemComponent->OnSystemTick();
PropagateAllTemplateChanges();
// Ensure the model process its entity update queue
m_model->ProcessEntityUpdates();
@@ -69,6 +69,7 @@ set(FILES
Prefab/PrefabFocus/PrefabFocusTests.cpp
Prefab/MockPrefabFileIOActionValidator.cpp
Prefab/MockPrefabFileIOActionValidator.h
Prefab/PrefabDeleteTests.cpp
Prefab/PrefabDuplicateTests.cpp
Prefab/PrefabEntityAliasTests.cpp
Prefab/PrefabInstanceToTemplatePropagatorTests.cpp
+5 -5
View File
@@ -15,9 +15,9 @@ ly_add_target(
awsclientauth_files.cmake
INCLUDE_DIRECTORIES
PUBLIC
Include/Public
Include
PRIVATE
Include/Private
Source
BUILD_DEPENDENCIES
PRIVATE
AZ::AzCore
@@ -35,7 +35,7 @@ ly_add_target(
awsclientauth_shared_files.cmake
INCLUDE_DIRECTORIES
PRIVATE
Include/Private
Source
BUILD_DEPENDENCIES
PRIVATE
AZ::AzCore
@@ -97,8 +97,8 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED)
awsclientauth_test_files.cmake
INCLUDE_DIRECTORIES
PRIVATE
"Include/Private"
"Include/Public"
Source
Include
Tests
BUILD_DEPENDENCIES
PRIVATE
@@ -7,46 +7,43 @@
#
set(FILES
Include/Public/Authentication/AuthenticationProviderBus.h
Include/Public/Authentication/AuthenticationTokens.h
Include/Public/Authorization/AWSCognitoAuthorizationBus.h
Include/Public/Authorization/ClientAuthAWSCredentials.h
Include/Public/UserManagement/AWSCognitoUserManagementBus.h
Include/Authentication/AuthenticationProviderBus.h
Include/Authentication/AuthenticationTokens.h
Include/Authorization/AWSCognitoAuthorizationBus.h
Include/Authorization/ClientAuthAWSCredentials.h
Include/UserManagement/AWSCognitoUserManagementBus.h
Include/Private/AWSClientAuthSystemComponent.h
Include/Private/AWSClientAuthBus.h
Include/Private/AWSClientAuthResourceMappingConstants.h
Include/Private/Authentication/AuthenticationProviderTypes.h
Include/Private/Authentication/AuthenticationProviderScriptCanvasBus.h
Include/Private/Authentication/AuthenticationProviderManager.h
Include/Private/Authentication/AuthenticationNotificationBusBehaviorHandler.h
Include/Private/Authorization/AWSCognitoAuthorizationController.h
Include/Private/Authorization/AWSClientAuthPersistentCognitoIdentityProvider.h
Include/Private/Authorization/AWSCognitoAuthorizationNotificationBusBehaviorHandler.h
Include/Private/Authorization/AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider.h
Include/Private/UserManagement/AWSCognitoUserManagementController.h
Include/Private/UserManagement/UserManagementNotificationBusBehaviorHandler.h
Include/Private/Authentication/AuthenticationProviderInterface.h
Include/Private/Authentication/OAuthConstants.h
Include/Private/Authentication/AWSCognitoAuthenticationProvider.h
Include/Private/Authentication/LWAAuthenticationProvider.h
Include/Private/Authentication/GoogleAuthenticationProvider.h
Source/AWSClientAuthSystemComponent.cpp
Source/Authentication/AuthenticationTokens.cpp
Source/Authentication/AuthenticationProviderInterface.cpp
Source/Authentication/AuthenticationProviderManager.cpp
Source/Authentication/AWSCognitoAuthenticationProvider.cpp
Source/Authentication/LWAAuthenticationProvider.cpp
Source/Authentication/GoogleAuthenticationProvider.cpp
Source/AWSClientAuthSystemComponent.h
Source/AWSClientAuthBus.h
Source/AWSClientAuthResourceMappingConstants.h
Source/Authentication/AuthenticationNotificationBusBehaviorHandler.h
Source/Authentication/AuthenticationProviderInterface.cpp
Source/Authentication/AuthenticationProviderInterface.h
Source/Authentication/AuthenticationProviderManager.cpp
Source/Authentication/AuthenticationProviderManager.h
Source/Authentication/AuthenticationProviderScriptCanvasBus.h
Source/Authentication/AuthenticationProviderTypes.h
Source/Authentication/AuthenticationTokens.cpp
Source/Authentication/AWSCognitoAuthenticationProvider.cpp
Source/Authentication/AWSCognitoAuthenticationProvider.h
Source/Authentication/LWAAuthenticationProvider.cpp
Source/Authentication/LWAAuthenticationProvider.h
Source/Authentication/GoogleAuthenticationProvider.cpp
Source/Authentication/GoogleAuthenticationProvider.h
Source/Authentication/OAuthConstants.h
Source/Authorization/ClientAuthAWSCredentials.cpp
Source/Authorization/AWSCognitoAuthorizationController.cpp
Source/Authorization/AWSClientAuthPersistentCognitoIdentityProvider.cpp
Source/Authorization/AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider.cpp
Source/Authorization/AWSClientAuthCognitoCachingAuthenticatedCredentialsProvider.h
Source/Authorization/AWSClientAuthPersistentCognitoIdentityProvider.cpp
Source/Authorization/AWSClientAuthPersistentCognitoIdentityProvider.h
Source/Authorization/AWSCognitoAuthorizationController.cpp
Source/Authorization/AWSCognitoAuthorizationController.h
Source/Authorization/AWSCognitoAuthorizationNotificationBusBehaviorHandler.h
Source/Authorization/ClientAuthAWSCredentials.cpp
Source/UserManagement/AWSCognitoUserManagementController.cpp
Source/UserManagement/AWSCognitoUserManagementController.h
Source/UserManagement/UserManagementNotificationBusBehaviorHandler.h
)
@@ -7,6 +7,6 @@
#
set(FILES
Include/Private/AWSClientAuthModule.h
Source/AWSClientAuthModule.cpp
Source/AWSClientAuthModule.h
)
+11 -11
View File
@@ -16,10 +16,10 @@ ly_add_target(
${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake
INCLUDE_DIRECTORIES
PUBLIC
Include/Public
Include
${pal_dir}
PRIVATE
Include/Private
Source
BUILD_DEPENDENCIES
PRIVATE
AZ::AzCore
@@ -36,7 +36,7 @@ ly_add_target(
awscore_shared_files.cmake
INCLUDE_DIRECTORIES
PRIVATE
Include/Private
Source
BUILD_DEPENDENCIES
PRIVATE
AZ::AzCore
@@ -71,10 +71,10 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS)
${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_editor_files.cmake
INCLUDE_DIRECTORIES
PRIVATE
Include/Private
Source
${pal_dir}
PUBLIC
Include/Public
Include
BUILD_DEPENDENCIES
PRIVATE
AZ::AzQtComponents
@@ -93,7 +93,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS)
awscore_editor_shared_files.cmake
INCLUDE_DIRECTORIES
PRIVATE
Include/Private
Source
BUILD_DEPENDENCIES
PRIVATE
AZ::AzCore
@@ -112,7 +112,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS)
awscore_resourcemappingtool_files.cmake
INCLUDE_DIRECTORIES
PRIVATE
Include/Private
Source
BUILD_DEPENDENCIES
PRIVATE
Gem::AWSCore.Editor.Static
@@ -156,8 +156,8 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED)
awscore_tests_files.cmake
INCLUDE_DIRECTORIES
PRIVATE
Include/Private
Include/Public
Source
Include
Tests
BUILD_DEPENDENCIES
PRIVATE
@@ -190,9 +190,9 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED)
${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_editor_tests_files.cmake
INCLUDE_DIRECTORIES
PRIVATE
Include/Private
Source
${pal_dir}
Include/Public
Include
Tests
COMPILE_DEFINITIONS
PRIVATE

Some files were not shown because too many files have changed in this diff Show More