Merge branch 'main' into cgalvan/RemoveLensFlareEditor

This commit is contained in:
Chris Galvan
2021-04-30 15:06:01 -05:00
76 changed files with 581 additions and 10745 deletions
@@ -161,20 +161,6 @@ def run():
# Deletion/Undo/Redo test
verify_deletion_undo_redo(self.component_name, entity_obj)
# Area Light Component
area_light = "Area Light"
ComponentTests(
area_light, lambda entity_obj: verify_required_component_addition(
entity_obj, ["Capsule Shape"], area_light))
# Decal Component
material_asset_path = os.path.join("AutomatedTesting", "Materials", "basic_grey.material")
material_asset = asset.AssetCatalogRequestBus(
bus.Broadcast, "GetAssetIdByPath", material_asset_path, math.Uuid(), False)
ComponentTests(
"Decal (Atom)", lambda entity_obj: verify_set_property(
entity_obj, "Controller|Configuration|Material", material_asset))
# DepthOfField Component
camera_entity = hydra.Entity("camera_entity")
camera_entity.create_entity(math.Vector3(512.0, 512.0, 34.0), ["Camera"])
@@ -185,6 +171,14 @@ def run():
lambda entity_obj: verify_set_property(
entity_obj, "Controller|Configuration|Camera Entity", camera_entity.id))
# Decal Component
material_asset_path = os.path.join("AutomatedTesting", "Materials", "basic_grey.material")
material_asset = asset.AssetCatalogRequestBus(
bus.Broadcast, "GetAssetIdByPath", material_asset_path, math.Uuid(), False)
ComponentTests(
"Decal (Atom)", lambda entity_obj: verify_set_property(
entity_obj, "Controller|Configuration|Material", material_asset))
# Directional Light Component
ComponentTests(
"Directional Light",
@@ -213,9 +207,6 @@ def run():
# Physical Sky Component
ComponentTests("Physical Sky")
# Point Light Component
ComponentTests("Point Light")
# PostFX Layer Component
ComponentTests("PostFX Layer")
@@ -27,194 +27,6 @@ TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "atom_hydra_scripts")
@pytest.mark.parametrize("level", ["auto_test"])
class TestAtomEditorComponentsMain(object):
@pytest.mark.test_case_id(
"C32078117", # Area Light
"C32078130", # Display Mapper
"C32078129", # Light
"C32078131", # Radius Weight Modifier
"C32078127", # PostFX Layer
"C32078126", # Point Light
"C32078125", # Physical Sky
"C32078115", # Global Skylight (IBL)
"C32078121", # Exposure Control
"C32078120", # Directional Light
"C32078119", # DepthOfField
"C32078118") # Decal
def test_AtomEditorComponents_AddedToEntity(self, request, editor, level, workspace, project, launcher_platform):
cfg_args = [level]
expected_lines = [
# Area Light Component
"Area Light Entity successfully created",
"Area Light_test: Component added to the entity: True",
"Area Light_test: Component removed after UNDO: True",
"Area Light_test: Component added after REDO: True",
"Area Light_test: Entered game mode: True",
"Area Light_test: Entity enabled after adding required components: True",
"Area Light_test: Entity is hidden: True",
"Area Light_test: Entity is shown: True",
"Area Light_test: Entity deleted: True",
"Area Light_test: UNDO entity deletion works: True",
"Area Light_test: REDO entity deletion works: True",
# Decal Component
"Decal (Atom) Entity successfully created",
"Decal (Atom)_test: Component added to the entity: True",
"Decal (Atom)_test: Component removed after UNDO: True",
"Decal (Atom)_test: Component added after REDO: True",
"Decal (Atom)_test: Entered game mode: True",
"Decal (Atom)_test: Exit game mode: True",
"Decal (Atom) Controller|Configuration|Material: SUCCESS",
"Decal (Atom)_test: Entity is hidden: True",
"Decal (Atom)_test: Entity is shown: True",
"Decal (Atom)_test: Entity deleted: True",
"Decal (Atom)_test: UNDO entity deletion works: True",
"Decal (Atom)_test: REDO entity deletion works: True",
# DepthOfField Component
"DepthOfField Entity successfully created",
"DepthOfField_test: Component added to the entity: True",
"DepthOfField_test: Component removed after UNDO: True",
"DepthOfField_test: Component added after REDO: True",
"DepthOfField_test: Entered game mode: True",
"DepthOfField_test: Exit game mode: True",
"DepthOfField_test: Entity disabled initially: True",
"DepthOfField_test: Entity enabled after adding required components: True",
"DepthOfField Controller|Configuration|Camera Entity: SUCCESS",
"DepthOfField_test: Entity is hidden: True",
"DepthOfField_test: Entity is shown: True",
"DepthOfField_test: Entity deleted: True",
"DepthOfField_test: UNDO entity deletion works: True",
"DepthOfField_test: REDO entity deletion works: True",
# Directional Light Component
"Directional Light Entity successfully created",
"Directional Light_test: Component added to the entity: True",
"Directional Light_test: Component removed after UNDO: True",
"Directional Light_test: Component added after REDO: True",
"Directional Light_test: Entered game mode: True",
"Directional Light_test: Exit game mode: True",
"Directional Light Controller|Configuration|Shadow|Camera: SUCCESS",
"Directional Light_test: Entity is hidden: True",
"Directional Light_test: Entity is shown: True",
"Directional Light_test: Entity deleted: True",
"Directional Light_test: UNDO entity deletion works: True",
"Directional Light_test: REDO entity deletion works: True",
# Exposure Control Component
"Exposure Control Entity successfully created",
"Exposure Control_test: Component added to the entity: True",
"Exposure Control_test: Component removed after UNDO: True",
"Exposure Control_test: Component added after REDO: True",
"Exposure Control_test: Entered game mode: True",
"Exposure Control_test: Exit game mode: True",
"Exposure Control_test: Entity disabled initially: True",
"Exposure Control_test: Entity enabled after adding required components: True",
"Exposure Control_test: Entity is hidden: True",
"Exposure Control_test: Entity is shown: True",
"Exposure Control_test: Entity deleted: True",
"Exposure Control_test: UNDO entity deletion works: True",
"Exposure Control_test: REDO entity deletion works: True",
# Global Skylight (IBL) Component
"Global Skylight (IBL) Entity successfully created",
"Global Skylight (IBL)_test: Component added to the entity: True",
"Global Skylight (IBL)_test: Component removed after UNDO: True",
"Global Skylight (IBL)_test: Component added after REDO: True",
"Global Skylight (IBL)_test: Entered game mode: True",
"Global Skylight (IBL)_test: Exit game mode: True",
"Global Skylight (IBL) Controller|Configuration|Diffuse Image: SUCCESS",
"Global Skylight (IBL) Controller|Configuration|Specular Image: SUCCESS",
"Global Skylight (IBL)_test: Entity is hidden: True",
"Global Skylight (IBL)_test: Entity is shown: True",
"Global Skylight (IBL)_test: Entity deleted: True",
"Global Skylight (IBL)_test: UNDO entity deletion works: True",
"Global Skylight (IBL)_test: REDO entity deletion works: True",
# Physical Sky Component
"Physical Sky Entity successfully created",
"Physical Sky component was added to entity",
"Entity has a Physical Sky component",
"Physical Sky_test: Component added to the entity: True",
"Physical Sky_test: Component removed after UNDO: True",
"Physical Sky_test: Component added after REDO: True",
"Physical Sky_test: Entered game mode: True",
"Physical Sky_test: Exit game mode: True",
"Physical Sky_test: Entity is hidden: True",
"Physical Sky_test: Entity is shown: True",
"Physical Sky_test: Entity deleted: True",
"Physical Sky_test: UNDO entity deletion works: True",
"Physical Sky_test: REDO entity deletion works: True",
# Point Light Component
"Point Light Entity successfully created",
"Point Light_test: Component added to the entity: True",
"Point Light_test: Component removed after UNDO: True",
"Point Light_test: Component added after REDO: True",
"Point Light_test: Entered game mode: True",
"Point Light_test: Exit game mode: True",
"Point Light_test: Entity is hidden: True",
"Point Light_test: Entity is shown: True",
"Point Light_test: Entity deleted: True",
"Point Light_test: UNDO entity deletion works: True",
"Point Light_test: REDO entity deletion works: True",
# PostFX Layer Component
"PostFX Layer Entity successfully created",
"PostFX Layer_test: Component added to the entity: True",
"PostFX Layer_test: Component removed after UNDO: True",
"PostFX Layer_test: Component added after REDO: True",
"PostFX Layer_test: Entered game mode: True",
"PostFX Layer_test: Exit game mode: True",
"PostFX Layer_test: Entity is hidden: True",
"PostFX Layer_test: Entity is shown: True",
"PostFX Layer_test: Entity deleted: True",
"PostFX Layer_test: UNDO entity deletion works: True",
"PostFX Layer_test: REDO entity deletion works: True",
# Radius Weight Modifier Component
"Radius Weight Modifier Entity successfully created",
"Radius Weight Modifier_test: Component added to the entity: True",
"Radius Weight Modifier_test: Component removed after UNDO: True",
"Radius Weight Modifier_test: Component added after REDO: True",
"Radius Weight Modifier_test: Entered game mode: True",
"Radius Weight Modifier_test: Exit game mode: True",
"Radius Weight Modifier_test: Entity is hidden: True",
"Radius Weight Modifier_test: Entity is shown: True",
"Radius Weight Modifier_test: Entity deleted: True",
"Radius Weight Modifier_test: UNDO entity deletion works: True",
"Radius Weight Modifier_test: REDO entity deletion works: True",
# Light Component
"Light Entity successfully created",
"Light_test: Component added to the entity: True",
"Light_test: Component removed after UNDO: True",
"Light_test: Component added after REDO: True",
"Light_test: Entered game mode: True",
"Light_test: Exit game mode: True",
"Light_test: Entity is hidden: True",
"Light_test: Entity is shown: True",
"Light_test: Entity deleted: True",
"Light_test: UNDO entity deletion works: True",
"Light_test: REDO entity deletion works: True",
# Display Mapper Component
"Display Mapper Entity successfully created",
"Display Mapper_test: Component added to the entity: True",
"Display Mapper_test: Component removed after UNDO: True",
"Display Mapper_test: Component added after REDO: True",
"Display Mapper_test: Entered game mode: True",
"Display Mapper_test: Exit game mode: True",
"Display Mapper_test: Entity is hidden: True",
"Display Mapper_test: Entity is shown: True",
"Display Mapper_test: Entity deleted: True",
"Display Mapper_test: UNDO entity deletion works: True",
"Display Mapper_test: REDO entity deletion works: True",
]
unexpected_lines = [
"failed to open",
"Traceback (most recent call last):",
]
hydra.launch_and_validate_results(
request,
TEST_DIRECTORY,
editor,
"hydra_AtomEditorComponents_AddedToEntity.py",
timeout=EDITOR_TIMEOUT,
expected_lines=expected_lines,
unexpected_lines=unexpected_lines,
halt_on_unexpected=True,
null_renderer=True,
cfg_args=cfg_args,
)
# It requires at least one test
def test_Dummy(self, request, editor, level, workspace, project, launcher_platform):
pass
@@ -19,6 +19,170 @@ import pytest
@pytest.mark.parametrize("level", ["auto_test"])
class TestAtomEditorComponentsSandbox(object):
# It requires at least one test
def test_Dummy(self, request, editor, level, workspace, project, launcher_platform):
pass
@pytest.mark.test_case_id(
"C32078117", # Area Light
"C32078130", # Display Mapper
"C32078129", # Light
"C32078131", # Radius Weight Modifier
"C32078127", # PostFX Layer
"C32078126", # Point Light
"C32078125", # Physical Sky
"C32078115", # Global Skylight (IBL)
"C32078121", # Exposure Control
"C32078120", # Directional Light
"C32078119", # DepthOfField
"C32078118") # Decal
def test_AtomEditorComponents_AddedToEntity(self, request, editor, level, workspace, project, launcher_platform):
cfg_args = [level]
expected_lines = [
# Decal Component
"Decal (Atom) Entity successfully created",
"Decal (Atom)_test: Component added to the entity: True",
"Decal (Atom)_test: Component removed after UNDO: True",
"Decal (Atom)_test: Component added after REDO: True",
"Decal (Atom)_test: Entered game mode: True",
"Decal (Atom)_test: Exit game mode: True",
"Decal (Atom) Controller|Configuration|Material: SUCCESS",
"Decal (Atom)_test: Entity is hidden: True",
"Decal (Atom)_test: Entity is shown: True",
"Decal (Atom)_test: Entity deleted: True",
"Decal (Atom)_test: UNDO entity deletion works: True",
"Decal (Atom)_test: REDO entity deletion works: True",
# DepthOfField Component
"DepthOfField Entity successfully created",
"DepthOfField_test: Component added to the entity: True",
"DepthOfField_test: Component removed after UNDO: True",
"DepthOfField_test: Component added after REDO: True",
"DepthOfField_test: Entered game mode: True",
"DepthOfField_test: Exit game mode: True",
"DepthOfField_test: Entity disabled initially: True",
"DepthOfField_test: Entity enabled after adding required components: True",
"DepthOfField Controller|Configuration|Camera Entity: SUCCESS",
"DepthOfField_test: Entity is hidden: True",
"DepthOfField_test: Entity is shown: True",
"DepthOfField_test: Entity deleted: True",
"DepthOfField_test: UNDO entity deletion works: True",
"DepthOfField_test: REDO entity deletion works: True",
# Directional Light Component
"Directional Light Entity successfully created",
"Directional Light_test: Component added to the entity: True",
"Directional Light_test: Component removed after UNDO: True",
"Directional Light_test: Component added after REDO: True",
"Directional Light_test: Entered game mode: True",
"Directional Light_test: Exit game mode: True",
"Directional Light Controller|Configuration|Shadow|Camera: SUCCESS",
"Directional Light_test: Entity is hidden: True",
"Directional Light_test: Entity is shown: True",
"Directional Light_test: Entity deleted: True",
"Directional Light_test: UNDO entity deletion works: True",
"Directional Light_test: REDO entity deletion works: True",
# Exposure Control Component
"Exposure Control Entity successfully created",
"Exposure Control_test: Component added to the entity: True",
"Exposure Control_test: Component removed after UNDO: True",
"Exposure Control_test: Component added after REDO: True",
"Exposure Control_test: Entered game mode: True",
"Exposure Control_test: Exit game mode: True",
"Exposure Control_test: Entity disabled initially: True",
"Exposure Control_test: Entity enabled after adding required components: True",
"Exposure Control_test: Entity is hidden: True",
"Exposure Control_test: Entity is shown: True",
"Exposure Control_test: Entity deleted: True",
"Exposure Control_test: UNDO entity deletion works: True",
"Exposure Control_test: REDO entity deletion works: True",
# Global Skylight (IBL) Component
"Global Skylight (IBL) Entity successfully created",
"Global Skylight (IBL)_test: Component added to the entity: True",
"Global Skylight (IBL)_test: Component removed after UNDO: True",
"Global Skylight (IBL)_test: Component added after REDO: True",
"Global Skylight (IBL)_test: Entered game mode: True",
"Global Skylight (IBL)_test: Exit game mode: True",
"Global Skylight (IBL) Controller|Configuration|Diffuse Image: SUCCESS",
"Global Skylight (IBL) Controller|Configuration|Specular Image: SUCCESS",
"Global Skylight (IBL)_test: Entity is hidden: True",
"Global Skylight (IBL)_test: Entity is shown: True",
"Global Skylight (IBL)_test: Entity deleted: True",
"Global Skylight (IBL)_test: UNDO entity deletion works: True",
"Global Skylight (IBL)_test: REDO entity deletion works: True",
# Physical Sky Component
"Physical Sky Entity successfully created",
"Physical Sky component was added to entity",
"Entity has a Physical Sky component",
"Physical Sky_test: Component added to the entity: True",
"Physical Sky_test: Component removed after UNDO: True",
"Physical Sky_test: Component added after REDO: True",
"Physical Sky_test: Entered game mode: True",
"Physical Sky_test: Exit game mode: True",
"Physical Sky_test: Entity is hidden: True",
"Physical Sky_test: Entity is shown: True",
"Physical Sky_test: Entity deleted: True",
"Physical Sky_test: UNDO entity deletion works: True",
"Physical Sky_test: REDO entity deletion works: True",
# PostFX Layer Component
"PostFX Layer Entity successfully created",
"PostFX Layer_test: Component added to the entity: True",
"PostFX Layer_test: Component removed after UNDO: True",
"PostFX Layer_test: Component added after REDO: True",
"PostFX Layer_test: Entered game mode: True",
"PostFX Layer_test: Exit game mode: True",
"PostFX Layer_test: Entity is hidden: True",
"PostFX Layer_test: Entity is shown: True",
"PostFX Layer_test: Entity deleted: True",
"PostFX Layer_test: UNDO entity deletion works: True",
"PostFX Layer_test: REDO entity deletion works: True",
# Radius Weight Modifier Component
"Radius Weight Modifier Entity successfully created",
"Radius Weight Modifier_test: Component added to the entity: True",
"Radius Weight Modifier_test: Component removed after UNDO: True",
"Radius Weight Modifier_test: Component added after REDO: True",
"Radius Weight Modifier_test: Entered game mode: True",
"Radius Weight Modifier_test: Exit game mode: True",
"Radius Weight Modifier_test: Entity is hidden: True",
"Radius Weight Modifier_test: Entity is shown: True",
"Radius Weight Modifier_test: Entity deleted: True",
"Radius Weight Modifier_test: UNDO entity deletion works: True",
"Radius Weight Modifier_test: REDO entity deletion works: True",
# Light Component
"Light Entity successfully created",
"Light_test: Component added to the entity: True",
"Light_test: Component removed after UNDO: True",
"Light_test: Component added after REDO: True",
"Light_test: Entered game mode: True",
"Light_test: Exit game mode: True",
"Light_test: Entity is hidden: True",
"Light_test: Entity is shown: True",
"Light_test: Entity deleted: True",
"Light_test: UNDO entity deletion works: True",
"Light_test: REDO entity deletion works: True",
# Display Mapper Component
"Display Mapper Entity successfully created",
"Display Mapper_test: Component added to the entity: True",
"Display Mapper_test: Component removed after UNDO: True",
"Display Mapper_test: Component added after REDO: True",
"Display Mapper_test: Entered game mode: True",
"Display Mapper_test: Exit game mode: True",
"Display Mapper_test: Entity is hidden: True",
"Display Mapper_test: Entity is shown: True",
"Display Mapper_test: Entity deleted: True",
"Display Mapper_test: UNDO entity deletion works: True",
"Display Mapper_test: REDO entity deletion works: True",
]
unexpected_lines = [
"failed to open",
"Traceback (most recent call last):",
]
hydra.launch_and_validate_results(
request,
TEST_DIRECTORY,
editor,
"hydra_AtomEditorComponents_AddedToEntity.py",
timeout=EDITOR_TIMEOUT,
expected_lines=expected_lines,
unexpected_lines=unexpected_lines,
halt_on_unexpected=True,
null_renderer=True,
cfg_args=cfg_args,
)
-26
View File
@@ -27,11 +27,6 @@
// ComponentEntityEditorPlugin
#include "Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h"
// LmbrCentral
#include <LmbrCentral/Rendering/MeshComponentBus.h>
#include <LmbrCentral/Rendering/GeomCacheComponentBus.h>
static const float kEnoughFarDistance(5000.0f);
CSurfaceInfoPicker::CSurfaceInfoPicker()
@@ -185,19 +180,6 @@ void CSurfaceInfoPicker::FindNearestInfoFromEntities(
AZ::EntityId id;
AzToolsFramework::ComponentEntityObjectRequestBus::EventResult(id, entityObject, &AzToolsFramework::ComponentEntityObjectRequestBus::Events::GetAssociatedEntityId);
AZ::EBusAggregateResults<IStatObj*> statObjs;
LmbrCentral::LegacyMeshComponentRequestBus::EventResult(statObjs, id, &LmbrCentral::LegacyMeshComponentRequestBus::Events::GetStatObj);
// If the entity has a MeshComponent, it will hit here
for (IStatObj* statObj : statObjs.values)
{
hit = RayIntersection(vWorldRaySrc, vWorldRayDir, nullptr, statObj, object->GetWorldTM(), outHitInfo, &statObjDefaultMaterial);
if (hit)
{
break;
}
}
// If the entity has an ActorComponent or another component that overrides RenderNodeRequestBus, it will hit here
if (!hit)
{
@@ -237,14 +219,6 @@ void CSurfaceInfoPicker::FindNearestInfoFromEntities(
}
}
}
// If the entity has a GeometryCacheComponent it will hit here
if (!hit)
{
IGeomCacheRenderNode* geomCacheRenderNode = nullptr;
LmbrCentral::GeometryCacheComponentRequestBus::EventResult(geomCacheRenderNode, id, &LmbrCentral::GeometryCacheComponentRequestBus::Events::GetGeomCacheRenderNode);
hit = RayIntersection_IGeomCacheRenderNode(vWorldRaySrc, vWorldRayDir, geomCacheRenderNode, &pickedMaterial, object->GetWorldTM(), outHitInfo);
}
}
if (hit)
@@ -43,7 +43,6 @@
#include <AzToolsFramework/ToolsComponents/EditorEntityIconComponentBus.h>
#include <AzToolsFramework/Undo/UndoCacheInterface.h>
#include <LmbrCentral/Rendering/RenderNodeBus.h>
#include <LmbrCentral/Rendering/MeshComponentBus.h>
#include <LmbrCentral/Rendering/MaterialOwnerBus.h>
#include <IDisplayViewport.h>
@@ -112,7 +111,6 @@ void CComponentEntityObject::AssignEntity(AZ::Entity* entity, bool destroyOld)
{
AZ::TransformNotificationBus::Handler::BusDisconnect();
LmbrCentral::RenderBoundsNotificationBus::Handler::BusDisconnect();
LmbrCentral::MeshComponentNotificationBus::Handler::BusDisconnect();
AzToolsFramework::ComponentEntityEditorRequestBus::Handler::BusDisconnect();
AZ::EntityBus::Handler::BusDisconnect();
AzToolsFramework::ComponentEntityObjectRequestBus::Handler::BusDisconnect();
@@ -158,7 +156,6 @@ void CComponentEntityObject::AssignEntity(AZ::Entity* entity, bool destroyOld)
AZ::TransformNotificationBus::Handler::BusConnect(m_entityId);
LmbrCentral::RenderBoundsNotificationBus::Handler::BusConnect(m_entityId);
LmbrCentral::MeshComponentNotificationBus::Handler::BusConnect(m_entityId);
AzToolsFramework::ComponentEntityEditorRequestBus::Handler::BusConnect(m_entityId);
AZ::EntityBus::Handler::BusConnect(m_entityId);
AzToolsFramework::ComponentEntityObjectRequestBus::Handler::BusConnect(this);
@@ -399,15 +396,6 @@ void CComponentEntityObject::OnParentChanged([[maybe_unused]] AZ::EntityId oldPa
{
}
void CComponentEntityObject::OnMeshCreated(const AZ::Data::Asset<AZ::Data::AssetData>& asset)
{
(void)asset;
// Need to recalculate bounds when the mesh changes.
OnRenderBoundsReset();
ValidateMeshStatObject();
}
void CComponentEntityObject::OnRenderBoundsReset()
{
CEntityObject::InvalidateTM(0);
@@ -950,9 +938,7 @@ void CComponentEntityObject::DrawDefault(DisplayContext& dc, const QColor& label
IStatObj* CComponentEntityObject::GetIStatObj()
{
IStatObj* statObj = nullptr;
LmbrCentral::LegacyMeshComponentRequestBus::EventResult(statObj, m_entityId, &LmbrCentral::LegacyMeshComponentRequests::GetStatObj);
return statObj;
return nullptr;
}
bool CComponentEntityObject::IsIsolated() const
@@ -27,7 +27,6 @@
#include <QtViewPane.h>
#include "../Editor/Objects/EntityObject.h"
#include <LmbrCentral/Rendering/MeshComponentBus.h>
#include <LmbrCentral/Rendering/RenderBoundsBus.h>
#endif
@@ -43,7 +42,6 @@ class CComponentEntityObject
, private AzToolsFramework::EditorEntityIconComponentNotificationBus::Handler
, private AZ::TransformNotificationBus::Handler
, private LmbrCentral::RenderBoundsNotificationBus::Handler
, private LmbrCentral::MeshComponentNotificationBus::Handler
, private AzToolsFramework::ComponentEntityEditorRequestBus::Handler
, private AzToolsFramework::ComponentEntityObjectRequestBus::Handler
, private AZ::EntityBus::Handler
@@ -131,11 +129,6 @@ public:
void OnParentChanged(AZ::EntityId oldParent, AZ::EntityId newParent) override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//! MeshComponentNotificationBus
void OnMeshCreated(const AZ::Data::Asset<AZ::Data::AssetData>& asset) override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//! RenderBoundsNotificationBus
void OnRenderBoundsReset() override;
@@ -146,15 +146,6 @@ namespace AZ
{
static const AZ::Uuid legacyRenderComponentUuids[] = {
AZ::Uuid("{FC315B86-3280-4D03-B4F0-5553D7D08432}"), // EditorMeshComponent
AZ::Uuid("{4B85E77D-91F9-40C5-8FCB-B494000A9E69}"), // EditorLensFlareComponent
AZ::Uuid("{7C18B273-5BA3-4E0F-857D-1F30BD6B0733}"), // EditorLightComponent
AZ::Uuid("{00818135-138D-42AD-8657-FF3FD38D9E7A}"), // EditorPointLightComponent
AZ::Uuid("{1DE624B1-876F-4E0A-96A6-7B248FA2076F}"), // EditorAreaLightComponent
AZ::Uuid("{41928E34-B558-4559-82CF-8B5795A38CB4}"), // EditorProjectorLightComponent
AZ::Uuid("{BA3890BD-D2E7-4DB6-95CD-7E7D5525567A}"), // EditorDecalComponent
AZ::Uuid("{8DBD6035-583E-409F-AFD9-F36829A0655D}"), // EditorEnvProbeComponent
AZ::Uuid("{9C86E09D-0727-476E-A4A1-25989CDBF9C6}"), // EditorHighQualityShadowComponent
AZ::Uuid("{045C0C58-C13E-49B0-A471-D4AC5D3FC6BD}"), // EditorGeometryCacheComponent
};
const AZStd::string deprecatedString = " (DEPRECATED By Atom)";
@@ -29,7 +29,10 @@ import collections
from collections import abc
# import subprocess
import logging as _logging
import pathlib
try:
import pathlib
except:
import pathlib2 as pathlib
from pathlib import *
import shelve
# import socket
@@ -17,8 +17,14 @@
import logging as _logging
try:
import pathlib
except:
import pathlib2 as pathlib
from pathlib import Path
import pathlib
from box import Box
import os
@@ -62,15 +62,15 @@ _LOGGER.debug('Invoking:: {0}.'.format({_MODULENAME}))
# To Do: move the callback key like 'NewSceneOpened' here (instead of None)
# ^ this would provide ability to loop through and replace key with CB object
_G_callbacks = Box(box_dots=True) # global scope container
_G_masterkey = 'DCCsi_callbacks'
_G_callbacks[_G_masterkey] = True # required master key
_G_CALLBACKS = Box(box_dots=True) # global scope container
_G_PRIMEKEY = 'DCCsi_callbacks'
_G_CALLBACKS[_G_PRIMEKEY] = True # required prime key
# -------------------------------------------------------------------------
def init_callbacks(_callbacks=_G_callbacks):
def init_callbacks(_callbacks=_G_CALLBACKS):
# store as a dict (Box is a fancy dict)
_callbacks[_G_masterkey] = True # required master key
_callbacks[_G_PRIMEKEY] = True # required prime key
# signature dict['callback key'] = ('CallBack'(type), func, callbackObj)
_callbacks['on_new_file'] = ['NewSceneOpened', set_defaults, None]
@@ -96,24 +96,24 @@ def uninstall_callbacks():
"""Bulk uninstalls hte globally defined set of callbacks:
_G_callbacks"""
global _G_callbacks
global _G_CALLBACKS
_LOGGER.debug('uninstall_callbacks() fired')
for key, value in _G_callbacks:
for key, value in _G_CALLBACKS:
if value[2] is not None: # have a cb
value[2].uninstall() # so uninstall it
else:
_LOGGER.warning('No callback in: key {0}, value:{1}'
''.format(key, value))
_G_callbacks = None
_G_CALLBACKS = None
_LOGGER.info('DCCSI CALLBACKS UNINSTALLED ... EXITING')
return _G_callbacks
return _G_CALLBACKS
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
def install_callbacks(_callbacks=_G_callbacks):
def install_callbacks(_callbacks=_G_CALLBACKS):
"""Bulk installs the globally defined set of callbacks:
_G_callbacks"""
@@ -126,15 +126,15 @@ def install_callbacks(_callbacks=_G_callbacks):
_callbacks.pop('box_dots')
# don't pass anything but carefully considered dict
if _G_masterkey in _callbacks:
_masterkey = _callbacks.pop(_G_masterkey)
if _G_PRIMEKEY in _callbacks:
_primekey = _callbacks.pop(_G_PRIMEKEY)
else:
_LOGGER.error('No master key, use a correct dictionary')
_LOGGER.error('No prime key, use a correct dictionary')
#To Do: implement error handling and return codes
return _callbacks[None]
for key, value in _G_callbacks.items():
# we popped the master key should the rest should be safe
for key, value in _G_CALLBACKS.items():
# we popped the prime key should the rest should be safe
if value[0] != 'nodeMessageType':
# set callback up
_cb = azEvCbH.EventCallbackHandler(value[0],
@@ -195,10 +195,10 @@ def update_workspace(foo=None):
# -------------------------------------------------------------------------
# install and init callbacks on an import obj
_G_callbacks = install_callbacks(_G_callbacks)
_G_CALLBACKS = install_callbacks(_G_CALLBACKS)
# ==========================================================================
# Module Tests
#==========================================================================
if __name__ == '__main__':
_G_callbacks = install_callbacks(_G_callbacks)
_G_CALLBACKS = install_callbacks(_G_CALLBACKS)
@@ -262,9 +262,9 @@ def post_startup():
# callbacks, To Do: these should also be moved to the bootstrapping config
# Defered startup after the Ui is running.
_G_callbacks = Box(box_dots=True) # this just ensures a global scope container
_G_CALLBACKS = Box(box_dots=True) # this just ensures a global scope container
if _G_LOAD_CALLBACKS:
from set_callbacks import _G_callbacks
from set_callbacks import _G_CALLBACKS
# ^ need to hold on to this as the install repopulate set
# this ensures the fixPaths callback is loaded
@@ -74,7 +74,9 @@ Now your local maya install is all set up with pip so you can install additional
Now you will want to run the following file to finish setup...
We have a requirements.txt file with the extension packages we use in the DCCsi.
You'll need the repo/branch path of your Lumberyard(O3DE) install.
And you'll need to know where the DCCsi, we will install package dependancies there.
You'll need the repo/branch path of your O3DE (aka Lumberyard) install.
And you'll need to know where the DCCsi is located, we will install package dependancies there.
C:\Program Files\Autodesk\Maya2020\bin>mayapy -m pip install -r C:\Depot\Lumberyard\Gems\AtomLyIntegration\TechnicalArt\DccScriptingInterface\SDK\Maya\requirements.txt -t C:\Depot\Lumberyard\Gems\AtomLyIntegration\TechnicalArt\DccScriptingInterface\3rdParty\Python\Lib\2.x\2.7.x\site-packages
Note: you may need to update the paths below to match your local o3de engine install!
C:\Program Files\Autodesk\Maya2020\bin>mayapy -m pip install -r C:\Depot\o3de\Gems\AtomLyIntegration\TechnicalArt\DccScriptingInterface\SDK\Maya\requirements.txt -t C:\Depot\o3de\Gems\AtomLyIntegration\TechnicalArt\DccScriptingInterface\3rdParty\Python\Lib\2.x\2.7.x\site-packages
@@ -4,12 +4,14 @@
#
# pip-compile --generate-hashes requirements.txt
#
typing==3.7.4.3 \
--hash=sha256:1187fb9c82fd670d10aa07bbb6cfcfe4bdda42d6fab8d5134f04e8c4d0b71cc9 \
--hash=sha256:283d868f5071ab9ad873e5e52268d611e851c870a2ba354193026f2dfb29d8b5
# via
# -r requirements.txt
# dynaconf
cachetools==3.1.1 \
--hash=sha256:428266a1c0d36dc5aca63a2d7c5942e88c2c898d72139fca0e97fdd2380517ae \
--hash=sha256:8ea2d3ce97850f31e4a08b0e2b5e6c34997d7216a9d2c98e0f3978630d4da69a
# via -r requirements.txt
certifi==2020.6.20 \
--hash=sha256:5930595817496dd21bb8dc35dad090f1c2cd0adfaf21204bf6732ca5d8ee34d3 \
--hash=sha256:8fc0819f1f30ba15bdb34cceffb9ef04d99f420f68eb75d901e9560b8749fc41
# via -r requirements.txt
click==7.1.2 \
--hash=sha256:d2b5255c7c6349bc1bd1e59e08cd12acbbd63ce649f2588755783aa94dfb6b1a \
--hash=sha256:dacca89f4bfadd5de3d7489b7c8a566eee0d3676333fbb50030263894c38c0dc
@@ -20,6 +22,14 @@ dynaconf==3.1.4 \
--hash=sha256:b2f472d83052f809c5925565b8a2ba76a103d5dc1dbb9748b693ed67212781b9 \
--hash=sha256:e6f383b84150b70fc439c8b2757581a38a58d07962aa14517292dcce1a77e160
# via -r requirements.txt
hashids==1.3.1 \
--hash=sha256:6c3dc775e65efc2ce2c157a65acb776d634cb814598f406469abef00ae3f635c \
--hash=sha256:8bddd1acba501bfc9306e7e5a99a1667f4f2cacdc20cbd70bcc5ddfa5147c94c
# via -r requirements.txt
pathlib2==2.3.5 \
--hash=sha256:0ec8205a157c80d7acc301c0b18fbd5d44fe655968f5d947b6ecef5290fc35db \
--hash=sha256:6cd9a47b597b37cc57de1c05e56fb1a1c9cc9fab04fe78c29acd090418529868
# via -r requirements.txt
pathlib==1.0.1 \
--hash=sha256:6940718dfc3eff4258203ad5021090933e5c04707d5ca8cc9e73c94a7894ea9f
# via -r requirements.txt
@@ -27,7 +37,38 @@ python-box==3.4.6 \
--hash=sha256:694a7555e3ff9fbbce734bbaef3aad92b8e4ed0659d3ed04d56b6a0a0eff26a9 \
--hash=sha256:a71d3dc9dbaa34c8597d3517c89a8041bd62fa875f23c0f3dad55e1958e3ce10
# via -r requirements.txt
scandir==1.10.0 \
--hash=sha256:2586c94e907d99617887daed6c1d102b5ca28f1085f90446554abf1faf73123e \
--hash=sha256:2ae41f43797ca0c11591c0c35f2f5875fa99f8797cb1a1fd440497ec0ae4b022 \
--hash=sha256:2b8e3888b11abb2217a32af0766bc06b65cc4a928d8727828ee68af5a967fa6f \
--hash=sha256:2c712840c2e2ee8dfaf36034080108d30060d759c7b73a01a52251cc8989f11f \
--hash=sha256:4d4631f6062e658e9007ab3149a9b914f3548cb38bfb021c64f39a025ce578ae \
--hash=sha256:67f15b6f83e6507fdc6fca22fedf6ef8b334b399ca27c6b568cbfaa82a364173 \
--hash=sha256:7d2d7a06a252764061a020407b997dd036f7bd6a175a5ba2b345f0a357f0b3f4 \
--hash=sha256:8c5922863e44ffc00c5c693190648daa6d15e7c1207ed02d6f46a8dcc2869d32 \
--hash=sha256:92c85ac42f41ffdc35b6da57ed991575bdbe69db895507af88b9f499b701c188 \
--hash=sha256:b24086f2375c4a094a6b51e78b4cf7ca16c721dcee2eddd7aa6494b42d6d519d \
--hash=sha256:cb925555f43060a1745d0a321cca94bcea927c50114b623d73179189a4e100ac
# via
# -r requirements.txt
# pathlib2
six==1.15.0 \
--hash=sha256:30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259 \
--hash=sha256:8b74bedcbbbaca38ff6d7491d76f2b06b3592611af620f8426e82dddb04a5ced
# via
# -r requirements.txt
# pathlib2
typing==3.7.4.3 \
--hash=sha256:1187fb9c82fd670d10aa07bbb6cfcfe4bdda42d6fab8d5134f04e8c4d0b71cc9 \
--hash=sha256:283d868f5071ab9ad873e5e52268d611e851c870a2ba354193026f2dfb29d8b5
# via
# -r requirements.txt
# dynaconf
unipath==1.1 \
--hash=sha256:09839adcc72e8a24d4f76d63656f30b5a1f721fc40c9bcd79d8c67bdd8b47dae \
--hash=sha256:e6257e508d8abbfb6ddd8ec357e33589f1f48b1599127f23b017124d90b0fff7
# via -r requirements.txt
wincertstore==0.2 \
--hash=sha256:22d5eebb52df88a8d4014d5cf6d1b6c3a5d469e6c3b2e2854f3a003e48872356 \
--hash=sha256:780bd1557c9185c15d9f4221ea7f905cb20b93f7151ca8ccaed9714dce4b327a
# via -r requirements.txt
@@ -36,11 +36,10 @@ _TYPE_TAG = 'module'
_PACKAGENAME = _TOOL_TAG
__all__ = ['initialize_logger',
'config_utils', 'render',
__all__ = ['config_utils', 'render',
'constants', 'return_stub', 'synthetic_env',
'env_base', 'env_bool', 'test', 'dev',
'lumberyard', 'marmoset'] #'blender', 'maya', 'substance', 'houdini']
'lumberyard', 'marmoset'] # 'blender', 'maya', 'substance', 'houdini']
# -------------------------------------------------------------------------
@@ -68,7 +67,10 @@ _DCCSI_DEV_MODE = env_bool.env_bool(constants.ENVAR_DCCSI_DEV_MODE, False)
# for py2.7 (Maya) we provide this, so we must assume some bootstrapping
# has occured, see DccScriptingInterface\\config.py (_DCCSI_PYTHON_LIB_PATH)
import pathlib
try:
import pathlib
except:
import pathlib2 as pathlib
from pathlib import Path
if _G_DEBUG:
print('DCCsi debug breadcrumb, pathlib is: {}'.format(pathlib))
@@ -80,9 +80,9 @@ def return_stub_dir(stub_file='dccsi_stub'):
# -------------------------------------------------------------------------
def get_stub_check_path(in_path=os.getcwd(), check_stub='engineroot.txt'):
def get_stub_check_path(in_path=os.getcwd(), check_stub='engine.json'):
'''
Returns the branch root directory of the dev\\'engineroot.txt'
Returns the branch root directory of the dev\\'engine.json'
(... or you can pass it another known stub)
so we can safely build relative filepaths within that branch.
@@ -158,7 +158,6 @@ def bootstrap_dccsi_py_libs(dccsi_dirpath=return_stub_dir()):
"""Builds and adds local site dir libs based on py version"""
from azpy.constants import STR_DCCSI_PYTHON_LIB_PATH # a path string constructor
#_DCCSI_PYTHON_LIB_PATH = "E:\\P4\\jromnoa_spectra_atom_2\\dev\\Tools\\Python\\3.7.5\\windows\\Lib\\site-packages"
_DCCSI_PYTHON_LIB_PATH = STR_DCCSI_PYTHON_LIB_PATH.format(dccsi_dirpath,
sys.version_info[0],
sys.version_info[1])
@@ -193,9 +192,9 @@ if __name__ == '__main__':
_config = get_dccsi_config()
_LOGGER.info('DCCSI_CONFIG_PATH: {}'.format(_config))
_LOGGER.info('LY_DEV: {}'.format(get_stub_check_path('engineroot.txt')))
_LOGGER.info('LY_DEV: {}'.format(get_stub_check_path('engine.json')))
_LOGGER.info('LY_PROJECT: {}'.format(get_current_project(get_stub_check_path('engineroot.txt'))))
_LOGGER.info('LY_PROJECT: {}'.format(get_current_project(get_stub_check_path('bootstrap.cfg'))))
_LOGGER.info('DCCSI_PYTHON_LIB_PATH: {}'.format(bootstrap_dccsi_py_libs(return_stub_dir('dccsi_stub'))))
@@ -92,7 +92,7 @@ TAG_DIR_LY_BUILD = str('build')
TAG_QT_PLUGIN_PATH = str('QT_PLUGIN_PATH')
# filesystem markers, stub file names.
STUB_LY_DEV = str('engineroot.txt')
STUB_LY_DEV = str('engine.json')
STUB_LY_ROOT_PROJECT = str('ly_project_stub')
STUB_LY_ROOT_DCCSI = str('dccsi_stub')
STUB_LY_DCCSI_AZPY = str('dccsi_azpy_stub')
@@ -36,7 +36,7 @@ _LOGGER.info('local_host: {}'.format(_LOCAL_HOST))
# -------------------------------------------------------------------------
def start_wing_to_maya(local_host=_LOCAL_HOST,
comman_port=6000,
command_port=6000,
logger=_LOGGER,
*args, **kwargs):
"""
@@ -58,7 +58,7 @@ def start_wing_to_maya(local_host=_LOCAL_HOST,
except NameError:
port = None
port_name = str('{0}:{1}'.format(local_host, comman_port))
port_name = str('{0}:{1}'.format(local_host, command_port))
# should only be getting the port passed in
_LOGGER.info('Attempting to open port:: {0}'.format(port_name))
@@ -145,10 +145,10 @@ def start_wing_to_maya_menu():
port = object() # init a dummy object
# default name ... name is first arg, or a kwarg
portName, kwargs = setSynthArgKwarg(port, argPosIndex=0, argTag='portName',
inArgs=args, inKwargs=kwargs,
defaultValue="127.0.0.1:6000")
portName, kwargs = set_synth_arg_kwarg(port, arg_pos_index=0, arg_tag='portName',
in_args=args, in_kwargs=kwargs,
default_value="127.0.0.1:6000")
port = start_wing_to_maya(local_host=_LOCAL_HOST, comman_port=6000)
port = start_wing_to_maya(local_host=_LOCAL_HOST, command_port=6000)
return
# -------------------------------------------------------------------------
@@ -15,30 +15,118 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
"""azpy.shared.ui.__init__"""
import os
import logging
import logging.config
from pathlib import Path
import logging as _logging
# global space debug flag
_G_DEBUG = os.getenv('DCCSI_GDEBUG', False)
from azpy.env_bool import env_bool
from azpy.constants import ENVAR_DCCSI_GDEBUG
from azpy.constants import ENVAR_DCCSI_DEV_MODE
# global space debug flag
_DCCSI_DEV_MODE = os.getenv('DCCSI_DEV_MODE', False)
# global space
_G_DEBUG = env_bool(ENVAR_DCCSI_GDEBUG, False)
_DCCSI_DEV_MODE = env_bool(ENVAR_DCCSI_DEV_MODE, False)
_PACKAGENAME = __name__
if _PACKAGENAME is '__main__':
_PACKAGENAME = 'azpy.shared.noodely'
import azpy
_LOGGER = azpy.initialize_logger(_PACKAGENAME)
_LOGGER.debug('Invoking __init__.py for {0}.'.format({_PACKAGENAME}))
# -------------------------------------------------------------------------
#
__all__ = ['find_arg',
'helpers',
'node',
'synth',
'synth_arg_kwarg',
'test_foo']
#
# -------------------------------------------------------------------------
# -- Project Globals ------------------------------------------------------
while 1:
# But if we want to change the prject root, we can set a new one here.
def set_G_DEFAULT_PROJECT_DIR(value):
global _G_DEFAULT_PROJECT_DIR
"""Sets and returns the _G_DEFAULT_PROJECT_DIR"""
_G_DEFAULT_PROJECT_DIR = Path(value).resolve()
return Path(_G_DEFAULT_PROJECT_DIR)
def get_G_DEFAULT_PROJECT_DIR():
global _G_DEFAULT_PROJECT_DIR
"""Returns the _G_DEFAULT_PROJECT_DIR"""
return Path(_G_DEFAULT_PROJECT_DIR)
# if we are initializing everythin properly, we can assume the project
# variables are properly set
global _G_DEFAULT_PROJECT_DIR
_G_DEFAULT_PROJECT_DIR = Path(os.getcwd()).resolve()
break
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
while 1:
global _G_PRIME_ROOT_NODE
_G_PRIME_ROOT_NODE = None # <-- needs to be set up!
# But if we want to change the prject root, we can set a new one here.
def set_G_PRIME_ROOT_NODE(node):
"""Sets and returns the _G_PRIME_ROOT_NODE"""
global _G_PRIME_ROOT_NODE
if not isinstance(node, ProjectRootNode):
message = '_G_PRIME_ROOT_NODE: {}\r'.format(type(node))
message += 'A project root node needs to be properly set\r'
raise TypeError(message)
_G_PRIME_ROOT_NODE = node
return _G_PRIME_ROOT_NODE
def get_G_PRIME_ROOT_NODE():
"""Returns the _G_PRIME_ROOT_NODE"""
global _G_PRIME_ROOT_NODE
return _G_PRIME_ROOT_NODE
break
# -------------------------------------------------------------------------
###########################################################################
# tests(), code block for testing module
# -------------------------------------------------------------------------
def tests():
_G_DEFAULT_PROJECT_DIR = set_G_DEFAULT_PROJECT_DIR(os.getcwd())
_LOGGER.info(_G_DEFAULT_PROJECT_DIR)
_LOGGER.info(_G_DEFAULT_PROJECT_DIR.parent)
_LOGGER.info(_G_DEFAULT_PROJECT_DIR.parts)
# NOT implemented yet
# _G_PRIME_ROOT_NODE
return
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
if _DCCSI_DEV_MODE:
_PACKAGENAME = __name__
if _PACKAGENAME is '__main__':
_PACKAGENAME = 'noodely'
_PKG_PARENT_PATH = str('azpy.shared')
_PKG_PATH = str('{0}.{1}'.format(_PKG_PARENT_PATH, _PACKAGENAME))
_LOGGER = logging.getLogger(_PACKAGENAME)
_LOGGER.debug('Invoking __init__.py for {0}.'.format({_PKG_PATH}))
# -------------------------------------------------------------------------
#
__all__ = ['config', 'find_arg', 'master', 'node', 'synth',
'synth_arg_kwarg', 'test_foo']
#
# If in dev mode this will test imports of __all__
from azpy import test_imports
_LOGGER.debug('Testing Imports from {0}'.format(_PACKAGENAME))
test_imports(__all__,
_pkg=_PACKAGENAME,
_logger=_LOGGER)
# -------------------------------------------------------------------------
del _LOGGER
###########################################################################
# --call block-------------------------------------------------------------
if __name__ == "__main__":
_LOGGER.info("# {0} #".format('-' * 72))
_LOGGER.info('~ noodely.prime ... Running script as __main__')
_LOGGER.info("# {0} #".format('-' * 72))
# run simple tests
tests()
del _LOGGER
@@ -23,8 +23,8 @@ __author__ = 'HogJonny'
# -------------------------------------------------------------------------
def find_arg(argPosIndex=None, argTag=None, removeKwarg=None,
inArgs=None, inKwargs=None, defaultValue=None):
def find_arg(arg_pos_index=None, arg_tag=None, remove_kwarg=None,
in_args=None, in_kwargs=None, default_value=None):
"""
# finds and returns an arg...
# if a positional index is given argPosIndex=0, it checks args first
@@ -41,31 +41,33 @@ def find_arg(argPosIndex=None, argTag=None, removeKwarg=None,
#
# foundArg, args, kwargs = find_arg(0, 'name',)
"""
if argPosIndex != None:
if not isinstance(argPosIndex, int):
found_arg = None
if arg_pos_index != None:
if not isinstance(arg_pos_index, int):
raise TypeError('argPosIndex: accepts a index integer!\r'
'got: {0}'.format(argPosIndex))
'got: {0}'.format(arg_pos_index))
# positional args ... check the position
if len(inArgs) > 0:
if len(in_args) > 0:
try:
foundArg = inArgs[argPosIndex]
found_arg = in_args[arg_pos_index]
except:
pass
# check kwargs ... a set kwarg will ALWAYS take precident over
# positional arg!!!
try:
foundArg
except:
foundArg = inKwargs.get(argTag, defaultValue) # defaults to None
if in_kwargs:
found_arg = in_kwargs.get(arg_tag, default_value) # defaults to None
if removeKwarg:
if argTag in inKwargs:
del inKwargs[argTag]
if remove_kwarg:
if in_kwargs:
if arg_tag in in_kwargs:
del in_kwargs[arg_tag]
# if we didn't find the arg/kwarg, the defualt return will be None
return foundArg, inKwargs
return found_arg, in_kwargs
# -------------------------------------------------------------------------
@@ -86,14 +88,14 @@ if __name__ == "__main__":
class TestNode(Foo):
def __init__(self, *args, **kwargs):
super().__init__()
self._name, kwargs = find_arg(argTag='foo', removeKwarg=True,
inArgs=args, inKwargs=kwargs)
self._name, kwargs = find_arg(argPosIndex=0, argTag='name',
removeKwarg=True,
inArgs=args, inKwargs=kwargs) # <-- first positional OR kwarg
self._parent, kwargs = find_arg(argPosIndex=1, argTag='parent',
removeKwarg=True,
inArgs=args, inKwargs=kwargs) # <-- second positional OR kwarg
self._name, kwargs = find_arg(arg_tag='foo', remove_kwarg=True,
in_args=args, in_kwargs=kwargs)
self._name, kwargs = find_arg(arg_pos_index=0, arg_tag='name',
remove_kwarg=True,
in_args=args, in_kwargs=kwargs) # <-- first positional OR kwarg
self._parent, kwargs = find_arg(arg_pos_index=1, arg_tag='parent',
remove_kwarg=True,
in_args=args, in_kwargs=kwargs) # <-- second positional OR kwarg
self._kwargsDict = {}
@@ -117,7 +119,7 @@ if __name__ == "__main__":
testNode2 = TestNode(name='fooey', parent=testNode)
testNode3 = TestNode('kablooey', testNode2, goober='dufus')
testNode3 = TestNode('kablooey', testNode2, gomer='pile')
print ('testNode2, name: {0}, parent: {1}'.format(testNode2._name, testNode2._parent))
print (testNode3)
@@ -1,90 +0,0 @@
"""
All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
its licensors.
For complete copyright and license terms please see the LICENSE at the root of this
distribution (the "License"). All use of this software is governed by the License,
or, if provided, by the license below or the license accompanying this file. Do not
remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
"""
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# master.py
# Allows for project based setup to be used with noodly
# version: 0.1
# author: Gallowj
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
import os
from unipath import Path
_G_DEFAULT_PROJECT_DIR = os.getcwd()
_G_MASTER_ROOT_NODE = None
@property
def _G_DEFAULT_PROJECT_DIR(value):
_G_DEFAULT_PROJECT_DIR = value
return _G_DEFAULT_PROJECT_DIR
def set_PROJECT_DIR(value):
"""Sets and returns _G_DEFAULT_PROJECT_DIR"""
global _G_DEFAULT_PROJECT_DIR
_G_DEFAULT_PROJECT_DIR = Path(value).expand()
return Path(_G_DEFAULT_PROJECT_DIR)
@property
def _G_MASTER_ROOT_NODE(value):
_G_MASTER_ROOT_NODE = value
return _G_MASTER_ROOT_NODE
def set_MASTER_ROOT_NODE(value):
"""Sets and returns _G_MASTER_ROOT_NODE"""
global _G_MASTER_ROOT_NODE
if not isinstance(inNode, ProjectRootNode):
raise TypeError('self._projectRootNode is: {0}\r'
'A _projectRootNode, needs to be properly set\r'
'So that we can acces:\r'
'\tself._projectRootNode._sourceRoot\r'
'\tself._projectRootNode._overrideRoot\r'
'Use self.assignProjectRootNode(<projectRootNode>)\r'
''.format(type(inNode)))
_G_MASTER_ROOT_NODE = inNode
return _G_MASTER_ROOT_NODE
###########################################################################
# tests(), code block for testing module
# -------------------------------------------------------------------------
def tests():
set_PROJECT_DIR(os.getcwd())
print(_G_DEFAULT_PROJECT_DIR)
print(_G_DEFAULT_PROJECT_DIR.parent)
print(_G_DEFAULT_PROJECT_DIR.components())
# NOT implemented yet
# set_PROJECT_DIR
return
###########################################################################
# --call block-------------------------------------------------------------
if __name__ == "__main__":
print ("# ----------------------------------------------------------------------- #")
print ('~ noodly.master ... Running script as __main__')
print ("# ----------------------------------------------------------------------- #\r")
# run simple tests
tests()
#_G_DEFAULT_PROJECT_DIR = Path(os.getcwd())
print(_G_DEFAULT_PROJECT_DIR.components())
@@ -16,7 +16,7 @@ from __future__ import division
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# node.py
# simple base Node Class, for tool creation.
# simple base Node Class, useful in tool creation.
# version: 0.1
# author: Gallowj
# -------------------------------------------------------------------------
@@ -25,16 +25,8 @@ from __future__ import division
Module docstring:
A Simple Node Base Class Module, for creating basic nodes within a hierarchy.
"""
__author__ = 'HogJonny'
_G_DEBUG = True # global state for debugging
_G_SETTINGS = None # global Settings storage
_G_LOG = None # global LOGger storage
_G_MASTER_NODE = None # We intend to init a master node, unless provided
# -------------------------------------------------------------------------
# built-ins
import os
import copy
@@ -48,11 +40,32 @@ import cachetools
from sched import scheduler
# local imports
from LyPy.si_shared.noodly.helpers import display_cached_value
from LyPy.si_shared.noodly.find_arg import find_arg
from LyPy.si_shared.noodly.synth import synthesize
from azpy.shared.noodely.helpers import display_cached_value
from azpy.shared.noodely.find_arg import find_arg
from azpy.shared.noodely.synth import synthesize
import azpy
from azpy.env_bool import env_bool
from azpy.constants import ENVAR_DCCSI_GDEBUG
from azpy.constants import ENVAR_DCCSI_DEV_MODE
# global space
# To Do: update to dynaconf dynamic env and settings?
_G_DEBUG = env_bool(ENVAR_DCCSI_GDEBUG, False)
_DCCSI_DEV_MODE = env_bool(ENVAR_DCCSI_DEV_MODE, False)
_MODULENAME = 'azpy.shared.noodely.node'
_log_level = int(20)
if _G_DEBUG:
_log_level = int(10)
_LOGGER = azpy.initialize_logger(_MODULENAME,
log_to_file=False,
default_log_level=_log_level)
_LOGGER.debug('Starting:: {}.'.format({_MODULENAME}))
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# quick test code (remove later)
from hashids import Hashids
@@ -79,8 +92,6 @@ if os.path.supports_unicode_filenames:
###########################################################################
# HELPER method functions
# -------------------------------------------------------------------------
def return_node_from_hashid(hashid):
if not isinstance(hashid, str):
raise TypeError("{0},{1}: Accepts hashids as str types!\r"
@@ -95,6 +106,7 @@ def return_node_from_hashid(hashid):
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
class Node(object):
"""Class constructor: makes a node."""
@@ -131,9 +143,9 @@ class Node(object):
# -- secret keyword -----------------------------------------------
self._temp_node = False
temp_node, kwargs = find_arg(argPosIndex=None, argTag='temp_node',
removeKwarg=True, inArgs=args,
inKwargs=kwargs) # <-- kwarg only
temp_node, kwargs = find_arg(arg_pos_index=None, arg_tag='temp_node',
remove_kwarg=True, in_args=args,
in_kwargs=kwargs) # <-- kwarg only
self._temp_node = temp_node
if self._temp_node:
self._kwargs_dict['temp_node'] = self._temp_node
@@ -141,9 +153,9 @@ class Node(object):
# -- store message header -----------------------------------------
# setup the .message_header <-- kwarg only
message_header, kwargs = find_arg(argPosIndex=None, argTag='message_header',
removeKwarg=True, inArgs=args, inKwargs=kwargs,
defaultValue=('{0}(), Message'
message_header, kwargs = find_arg(arg_pos_index=None, arg_tag='message_header',
remove_kwarg=True, in_args=args, in_kwargs=kwargs,
default_value=('{0}(), Message'
.format(self._node_type)))
self._message_header = message_header
# -----------------------------------------------------------------
@@ -165,7 +177,7 @@ class Node(object):
# -- store the node name ------------------------------------------
self._node_name = node_name
if (self._node_class_index == 0 and self._node_name == None):
self._node_name = 'MASTER'
self._node_name = 'PRIME'
elif (self._node_class_index > 0 and self._node_name == None):
# set a default node_name if none, based on the unihashid
if not self._name_is_uni_hashid:
@@ -325,7 +337,7 @@ class Node(object):
@property
def cls_node_dict(self):
return Node._cls_node_dict
# ----------------------------------------------------------------------
# ---------------------------------------------------------------------
# --method-set---------------------------------------------------------
def cls_node_count_up(self):
@@ -584,10 +596,10 @@ def tests():
print(default_node.hierarchy())
# retreive a node from it's known hashid
master_node = return_node_from_hashid('kxYLm0XQeXJ7jWaP')
print(master_node.uni_hashid) # verify hasid
prime_node = return_node_from_hashid('kxYLm0XQeXJ7jWaP')
print(prime_node.uni_hashid) # verify hasid
# should return the same node as default_node
print(master_node.node_name) # should be 'MASTER'
print(prime_node.node_name) # should be 'PRIME'
return
# -------------------------------------------------------------------------
@@ -27,12 +27,6 @@ A simple path objecy based Node Class, for creating path hierarchies.
"""
__author__ = 'HogJonny'
_G_DEBUG = True # global state for debugging
_G_SETTINGS = None # global Settings storage
_G_LOG = None # global LOGger storage
_G_MASTER_NODE = None # We intend to init a master node
# -------------------------------------------------------------------------
# built-ins
import os
@@ -44,10 +38,31 @@ import logging
from unipath import Path, AbstractPath
# local ly imports
from LyPy.si_shared.noodly.helpers import istext
from LyPy.si_shared.noodly.find_arg import find_arg
from LyPy.si_shared.noodly.synth import synthesize
from LyPy.si_shared.noodly.node import Node
from azpy.shared.noodely.helpers import istext
from azpy.shared.noodely.find_arg import find_arg
from azpy.shared.noodely.synth import synthesize
from azpy.shared.noodely.node import Node
import azpy
from azpy.env_bool import env_bool
from azpy.constants import ENVAR_DCCSI_GDEBUG
from azpy.constants import ENVAR_DCCSI_DEV_MODE
# -------------------------------------------------------------------------
# global space
# To Do: update to dynaconf dynamic env and settings?
_G_DEBUG = env_bool(ENVAR_DCCSI_GDEBUG, False)
_DCCSI_DEV_MODE = env_bool(ENVAR_DCCSI_DEV_MODE, False)
_MODULENAME = 'azpy.shared.noodely.pathnode'
_log_level = int(20)
if _G_DEBUG:
_log_level = int(10)
_LOGGER = azpy.initialize_logger(_MODULENAME,
log_to_file=False,
default_log_level=_log_level)
_LOGGER.debug('Starting:: {}.'.format({_MODULENAME}))
# -------------------------------------------------------------------------
@@ -63,20 +78,12 @@ if os.path.supports_unicode_filenames:
# -------------------------------------------------------------------------
# set up logger
_G_LOGGER = logging.getLogger(__name__)
# -------------------------------------------------------------------------
class PathNode(Node):
"""doc string"""
# share the debug state
_DEBUG = _G_DEBUG
# logger
_LOGGER = _G_LOGGER
# class header
_message_header = 'noodly, PathNode(): Message'
@@ -117,22 +124,22 @@ class PathNode(Node):
# -- secret keyword -----------------------------------------------
self._temp_node = False
temp_node, kwargs = find_arg(argPosIndex=None, argTag='temp_node',
removeKwarg=True, inArgs=args,
inKwargs=kwargs) # <-- kwarg only
temp_node, kwargs = find_arg(arg_pos_index=None, arg_tag='temp_node',
remove_kwarg=True, in_args=args,
in_kwargs=kwargs) # <-- kwarg only
self._temp_node = temp_node
if self._temp_node:
self.k_wargs_dict['temp_node'] = self._temp_node
# -- Node class args/kwargs ---------------------------------------
node_name, kwargs = find_arg(argPosIndex=2, argTag='node_name',
removeKwarg=True, inArgs=args,
inKwargs=kwargs) # <-- third arg, kwarg
node_name, kwargs = find_arg(arg_pos_index=2, arg_tag='node_name',
remove_kwarg=True, in_args=args,
in_kwargs=kwargs) # <-- third arg, kwarg
parent_node, kwargs = find_arg(argPosIndex=3, argTag='parent_node',
removeKwarg=True, inArgs=args,
inKwargs=kwargs) # <-- fourth arg, kwarg
parent_node, kwargs = find_arg(arg_pos_index=3, arg_tag='parent_node',
remove_kwarg=True, in_args=args,
in_kwargs=kwargs) # <-- fourth arg, kwarg
self._root_path = root_path
@@ -344,12 +351,12 @@ class PathNode(Node):
# -------------------------------------------------------------------------
def tests():
from node import Node
default_node = Node() # result: Node(node_name='MASTER')
default_node = Node() # result: Node(node_name='PRIME')
print(default_node)
first_child = PathNode(path=None, node_name='first_child', parent_node=default_node)
print(first_child)
# result: PathNode(temp_node=True, parent_node=Node(node_name='MASTER')).siblingNodeFromHashid('WNPZoKBVpXV16QLz')
# result: PathNode(temp_node=True, parent_node=Node(node_name='PRIME')).siblingNodeFromHashid('WNPZoKBVpXV16QLz')
# first_child.nodeType
# first_child.parent_node
# first_child.node_name
@@ -22,9 +22,9 @@ from synth import synthesize
# -------------------------------------------------------------------------
def setSynthArgKwarg(inst, argPosIndex=None, argTag=None, defaultValue=None,
inArgs=None, inKwargs=None, removeKwarg=True,
setAnyway=True):
def set_synth_arg_kwarg(inst, arg_pos_index=None, arg_tag=None, default_value=None,
in_args=None, in_kwargs=None, remove_kwarg=True,
set_anyway=True):
"""
Uses find_arg and sets a property on a object.
@@ -34,44 +34,44 @@ def setSynthArgKwarg(inst, argPosIndex=None, argTag=None, defaultValue=None,
If the arg/property doesn't exist we synthesize it
"""
foundArg = None
argValueDict = {}
found_arg = None
arg_value_dict = {}
# find the argument, or set to default value
foundArg, inKwargs = find_arg(argPosIndex, argTag, removeKwarg,
inArgs, inKwargs,
defaultValue)
found_arg, in_kwargs = find_arg(arg_pos_index, arg_tag, remove_kwarg,
in_args, in_kwargs,
default_value)
if foundArg:
argTag = foundArg
if found_arg:
arg_tag = found_arg
# single arg first
# make sure the object doesn't arealdy have this property
try:
hasattr(inst, argTag) # check if property exists
if setAnyway:
hasattr(inst, arg_tag) # check if property exists
if set_anyway:
try:
setattr(inst, argTag, defaultValue) # try to set
setattr(inst, arg_tag, default_value) # try to set
except Exception as e:
raise e
except:
pass
# make it a synthetic property
if argTag:
if arg_tag:
try:
argValue = synthesize(inst, argTag, defaultValue)
argValueDict[argTag] = argValue
arg_value = synthesize(inst, arg_tag, default_value)
arg_value_dict[arg_tag] = arg_value
except Exception as e:
raise e
# multiple and/or remaining kwards next
if inKwargs:
if len(inKwargs) > 0:
for k, v in inKwargs.items():
if in_kwargs:
if len(in_kwargs) > 0:
for k, v in in_kwargs.items():
try:
hasattr(inst, k) # check if property exists
if setAnyway:
if set_anyway:
try:
setattr(inst, k, v) # try to set
except Exception as e:
@@ -81,12 +81,12 @@ def setSynthArgKwarg(inst, argPosIndex=None, argTag=None, defaultValue=None,
if k:
try:
argValue = synthesize(inst, k, v)
argValueDict[k] = argValue
arg_value = synthesize(inst, k, v)
arg_value_dict[k] = arg_value
except Exception as e:
raise e
return argValueDict
return arg_value_dict
# --------------------------------------------------------------------------
@@ -98,28 +98,28 @@ if __name__ == '__main__':
from test_foo import Foo
# define a arg/property tag we know doesn't exist
synthArgTag = 'syntheticArg'
synth_arg_tag = 'synthetic_arg'
# create a test object
print('~ creating the test foo object...')
myFoo = Foo()
my_foo = Foo()
print('~ Starting - single synthetic arg test...')
# find and set existing, or create and set
argValueDict = setSynthArgKwarg(myFoo,
argTag=synthArgTag,
defaultValue='kablooey')
arg_value_dict = set_synth_arg_kwarg(my_foo,
arg_tag=synth_arg_tag,
default_value='kablooey')
# what was returned
print('~ single value returned...')
for k, v in argValueDict.items():
for k, v in arg_value_dict.items():
print("Arg '{0}':'{1}'".format(k, v))
# attempt to access the new synthetic property directly
print('~ direct property access test...')
try:
myFoo.syntheticArg
print('myFoo.{0}: {1}'.format(synthArgTag, myFoo.syntheticArg))
my_foo.synthetic_arg
print('myFoo.{0}: {1}'.format(synth_arg_tag, my_foo.synthetic_arg))
except Exception as e:
raise e
@@ -128,31 +128,31 @@ if __name__ == '__main__':
newKwargs = {'fooey': 'chop suey', 'success': True}
# find and set existing, or create and set
argValueDict = setSynthArgKwarg(myFoo,
inKwargs=newKwargs,
defaultValue='kablooey')
arg_value_dict = set_synth_arg_kwarg(my_foo,
in_kwargs=newKwargs,
default_value='kablooey')
# what was returned
print('~ multiple values returned...')
for k, v in argValueDict.items():
for k, v in arg_value_dict.items():
print("Arg '{0}':'{1}'".format(k, v))
print('~ multiple direct property access test...')
try:
myFoo.fooey
print('myFoo.{0}: {1}'.format('fooey', myFoo.fooey))
my_foo.fooey
print('myFoo.{0}: {1}'.format('fooey', my_foo.fooey))
except Exception as e:
raise e
try:
myFoo.success
print('myFoo.{0}: {1}'.format('success', myFoo.success))
my_foo.success
print('myFoo.{0}: {1}'.format('success', my_foo.success))
except Exception as e:
raise e
print('~ Starting - known failure test...')
try:
myFoo.knownBad
my_foo.knownBad
except Exception as e:
print(e)
print('Test failed as expected!!!')
@@ -25,13 +25,13 @@ class Foo(object):
This is a Class, it creates a Foo object... which does nothing really
"""
__propertyTag = 'fooProperty'
__property_tag = 'fooProperty'
# ------------------------------------------------------------------
def __init__(self, name='Foo', value='defaultValue', *args, **kwargs):
'''Class __init__'''
synthesize(self, 'name', name)
synthesize(self, Foo.__propertyTag, value)
synthesize(self, Foo.__property_tag, value)
synthesize(self, 'test', 'testValue')
@@ -20,7 +20,10 @@ import os
# from io import StringIO # for handling unicode strings
# azpy
from azpy import initialize_logger
import azpy
from azpy.env_bool import env_bool
from azpy.constants import ENVAR_DCCSI_GDEBUG
from azpy.constants import ENVAR_DCCSI_DEV_MODE
# 3rd Party
from unipath import Path
@@ -28,22 +31,22 @@ import PySide2.QtCore as QtCore
import PySide2.QtWidgets as QtWidgets
import PySide2.QtGui as QtGui
# -------------------------------------------------------------------------
# global space debug flag
_G_DEBUG = os.getenv('DCCSI_GDEBUG', False)
# global space debug flag
_DCCSI_DEV_MODE = os.getenv('DCCSI_DEV_MODE', False)
# global space
# To Do: update to dynaconf dynamic env and settings?
_G_DEBUG = env_bool(ENVAR_DCCSI_GDEBUG, False)
_DCCSI_DEV_MODE = env_bool(ENVAR_DCCSI_DEV_MODE, False)
_MODULE_PATH = Path(__file__)
_ORG_TAG = 'Amazon_Lumberyard'
_APP_TAG = 'DCCsi'
_TOOL_TAG = 'azpy.shared.ui.custom_treemodel'
_TYPE_TAG = 'test'
_MODULENAME = 'azpy.shared.ui.custom_treemodel'
_MODULENAME = __name__
if _MODULENAME is '__main__':
_MODULENAME = _TOOL_TAG
_log_level = int(20)
if _G_DEBUG:
_log_level = int(10)
_LOGGER = azpy.initialize_logger(_MODULENAME,
log_to_file=False,
default_log_level=_log_level)
_LOGGER.debug('Starting:: {}.'.format({_MODULENAME}))
_UI_FILE = Path(_MODULE_PATH.parent, 'resources', 'example.ui')
# -------------------------------------------------------------------------
@@ -75,15 +78,15 @@ class CustomFileTreeModel(QtCore.QAbstractItemModel):
# TODO: need to make sure we are getting path objects
# build the root node
self._root_node = self.buildRootNode('root', None, self._rootFilePath)
self._root_node = self.build_rootnode('root', None, self._root_filepath)
# master selection
self._masterSelection = masterSelection
# prime selection
self._prime_selection = prime_selection
# build the master selection node
self._masterNode = self.buildMasterNode('master', None, self._masterSelection, self._rootNode.path())
# build the prime selection node
self._primenode = self.build_primenode('prime', None, self._prime_selection, self._rootnode.path())
# want to store off a couple lists in the model, for retreival later
self._nodeList = None
self._depNodesList = None
self._nodelist = None
self._dep_nodelist = None
@@ -68,7 +68,7 @@ class HelpMenu():
INPUTS:
main_window = the class instance of the QMainWindow
tool_label = the menu label for the tool's help item
tool_help_page = the http:// path to the specific bpTool help page
tool_help_page = the http:// path to the tool specific help page
Here's an example
# self.help_menu = azpy.shared.ui.help_menu.setup(self, 'Help...', 'https://some.site.com/azpy')
@@ -667,7 +667,7 @@ if __name__ == '__main__':
try:
import azpy.test.entry_test
print('SUCCESS: import azpy.test.entry_test')
azpy.test.entry_test.main(verbose=True, connectDebugger=True)
azpy.test.entry_test.main(verbose=True, connect_debugger=True)
except ImportError as e:
print('ERROR: {0}'.format(e))
raise e
@@ -25,6 +25,7 @@ from pathlib import Path
# -------------------------------------------------------------------------
_BOOT_CHECK = False # set true to test breakpoint in this module directly
import azpy
from azpy.env_bool import env_bool
from azpy.constants import ENVAR_DCCSI_GDEBUG
@@ -48,13 +49,13 @@ _LOGGER.debug('Starting:: {}.'.format({_MODULENAME}))
# -------------------------------------------------------------------------
def main(verbose=_G_DEBUG, connectDebugger=True):
def main(verbose=_G_DEBUG, connect_debugger=True):
_LOGGER.info('{}'.format('-' * 74))
_LOGGER.info('entry_test.main()')
_LOGGER.info('Root test import successful:')
_LOGGER.info('~ {}'.format(__file__))
if connectDebugger:
if connect_debugger:
status = connect_wing()
_LOGGER.info(status)
# -------------------------------------------------------------------------
@@ -137,4 +138,4 @@ def connect_wing():
# -------------------------------------------------------------------------
if __name__ == '__main__':
_G_DEBUG = True
main(verbose=_G_DEBUG, connectDebugger=_G_DEBUG)
main(verbose=_G_DEBUG, connect_debugger=_G_DEBUG)
@@ -26,7 +26,6 @@ import re
# our framework for dcc tools need to run in apps like Maya that may still be
# on py27 so we need to import and use after some boostrapping
# -------------------------------------------------------------------+------
#os.environ['PYTHONINSPECT'] = 'True'
_MODULE_PATH = os.path.abspath(__file__)
@@ -78,6 +77,10 @@ _DCCSI_PYTHON_LIB_PATH = azpy.config_utils.bootstrap_dccsi_py_libs(_DCCSIG_PATH)
# Now we should be able to just carry on with pth lib and dynaconf
from dynaconf import Dynaconf
try:
import pathlib
except:
import pathlib2 as pathlib
from pathlib import Path
_DCCSIG_PATH = Path(_DCCSIG_PATH).resolve()
@@ -218,7 +221,7 @@ os.environ["DYNACONF_DCCSI_DEV_MODE"] = str(_DCCSI_DEV_MODE)
# search up to get \dev
_LY_DEV = azpy.config_utils.get_stub_check_path(in_path=_DCCSIG_PATH,
check_stub='engineroot.txt')
check_stub='engine.json')
os.environ["DYNACONF_LY_DEV"] = str(_LY_DEV.resolve())
_LY_PROJECT = azpy.config_utils.get_current_project(_LY_DEV)
os.environ["DYNACONF_LY_PROJECT"] = _LY_PROJECT
@@ -4,34 +4,39 @@
#
# pip-compile --generate-hashes requirements.txt
#
typing==3.7.4.3 \
--hash=sha256:1187fb9c82fd670d10aa07bbb6cfcfe4bdda42d6fab8d5134f04e8c4d0b71cc9 \
--hash=sha256:283d868f5071ab9ad873e5e52268d611e851c870a2ba354193026f2dfb29d8b5
# via
# -r requirements.txt
# dynaconf
cachetools==4.2.1 \
--hash=sha256:1d9d5f567be80f7c07d765e21b814326d78c61eb0c3a637dffc0e5d1796cb2e2 \
--hash=sha256:f469e29e7aa4cff64d8de4aad95ce76de8ea1125a16c68e0d93f65c3c3dc92e9
# via -r requirements.txt
certifi==2020.12.5 \
--hash=sha256:1a4995114262bffbc2413b159f2a1a480c969de6e6eb13ee966d470af86af59c \
--hash=sha256:719a74fb9e33b9bd44cc7f3a8d94bc35e4049deebe19ba7d8e108280cfd59830
# via -r requirements.txt
click==7.1.2 \
--hash=sha256:d2b5255c7c6349bc1bd1e59e08cd12acbbd63ce649f2588755783aa94dfb6b1a \
--hash=sha256:dacca89f4bfadd5de3d7489b7c8a566eee0d3676333fbb50030263894c38c0dc
# via
# -r requirements.txt
# pip-tools
dynaconf==3.1.4 \
--hash=sha256:b2f472d83052f809c5925565b8a2ba76a103d5dc1dbb9748b693ed67212781b9 \
--hash=sha256:e6f383b84150b70fc439c8b2757581a38a58d07962aa14517292dcce1a77e160
# via -r requirements.txt
hashids==1.3.1 \
--hash=sha256:6c3dc775e65efc2ce2c157a65acb776d634cb814598f406469abef00ae3f635c \
--hash=sha256:8bddd1acba501bfc9306e7e5a99a1667f4f2cacdc20cbd70bcc5ddfa5147c94c
# via -r requirements.txt
pathlib==1.0.1 \
--hash=sha256:6940718dfc3eff4258203ad5021090933e5c04707d5ca8cc9e73c94a7894ea9f
# via -r requirements.txt
python-box==3.4.6 \
--hash=sha256:694a7555e3ff9fbbce734bbaef3aad92b8e4ed0659d3ed04d56b6a0a0eff26a9 \
--hash=sha256:a71d3dc9dbaa34c8597d3517c89a8041bd62fa875f23c0f3dad55e1958e3ce10
python-box==5.3.0 \
--hash=sha256:4ed4ef5d34de505a65c01e3f1911de8cdb29484fcae0c035141dce535c6c194a \
--hash=sha256:f2a531f9f5bbef078c175fad6abb31e9b59d40d121ea79993197e6bb221c6be6
# via -r requirements.txt
unipath==1.1 \
--hash=sha256:09839adcc72e8a24d4f76d63656f30b5a1f721fc40c9bcd79d8c67bdd8b47dae \
--hash=sha256:e6257e508d8abbfb6ddd8ec357e33589f1f48b1599127f23b017124d90b0fff7
# via -r requirements.txt
# WARNING: The following packages were not pinned, but pip requires them to be
# pinned when the requirements file includes hashes. Consider using the --allow-unsafe flag.
# pip
wincertstore==0.2 \
--hash=sha256:22d5eebb52df88a8d4014d5cf6d1b6c3a5d469e6c3b2e2854f3a003e48872356 \
--hash=sha256:780bd1557c9185c15d9f4221ea7f905cb20b93f7151ca8ccaed9714dce4b327a
# via -r requirements.txt
@@ -15,11 +15,6 @@
#include <AzCore/std/containers/vector.h>
#include <Azcore/Math/Vector3.h>
namespace LmbrCentral
{
class MeshComponentRequests;
}
namespace Blast
{
class BlastMeshData;
@@ -33,13 +33,7 @@
#include "Audio/AudioSystemComponent.h"
#include "Audio/AudioTriggerComponent.h"
#include "Bundling/BundlingSystemComponent.h"
#include "Rendering/DecalComponent.h"
#include "Rendering/StereoRendererComponent.h"
#include "Rendering/LensFlareComponent.h"
#include "Rendering/LightComponent.h"
#include "Rendering/HighQualityShadowComponent.h"
#include "Rendering/MeshComponent.h"
#include "Rendering/GeomCacheComponent.h"
#include "Ai/NavigationComponent.h"
#include "Scripting/TagComponent.h"
#include "Scripting/SimpleStateComponent.h"
@@ -77,12 +71,10 @@
#include <AzCore/Slice/SliceAsset.h>
#include <AzCore/Script/ScriptAsset.h>
#include <LmbrCentral/Rendering/MaterialAsset.h>
#include <LmbrCentral/Rendering/LensFlareAsset.h>
#include <LmbrCentral/Rendering/MeshAsset.h>
#include <LmbrCentral/Rendering/MaterialHandle.h>
// Asset handlers
#include <Rendering/LensFlareAssetHandler.h>
#include <Rendering/MeshAssetHandler.h>
// Scriptable Ebus Registration
@@ -214,13 +206,9 @@ namespace LmbrCentral
AudioSystemComponent::CreateDescriptor(),
AudioTriggerComponent::CreateDescriptor(),
BundlingSystemComponent::CreateDescriptor(),
DecalComponent::CreateDescriptor(),
LensFlareComponent::CreateDescriptor(),
LightComponent::CreateDescriptor(),
LmbrCentralAllocatorComponent::CreateDescriptor(),
LmbrCentralAssetBuilderAllocatorComponent::CreateDescriptor(),
LmbrCentralSystemComponent::CreateDescriptor(),
HighQualityShadowComponent::CreateDescriptor(),
MeshComponent::CreateDescriptor(),
NavigationComponent::CreateDescriptor(),
SimpleStateComponent::CreateDescriptor(),
@@ -237,11 +225,9 @@ namespace LmbrCentral
CompoundShapeComponent::CreateDescriptor(),
SplineComponent::CreateDescriptor(),
PolygonPrismShapeComponent::CreateDescriptor(),
StereoRendererComponent::CreateDescriptor(),
NavigationSystemComponent::CreateDescriptor(),
GeometrySystemComponent::CreateDescriptor(),
RandomTimedSpawnerComponent::CreateDescriptor(),
GeometryCacheComponent::CreateDescriptor(),
SphereShapeDebugDisplayComponent::CreateDescriptor(),
DiskShapeDebugDisplayComponent::CreateDescriptor(),
BoxShapeDebugDisplayComponent::CreateDescriptor(),
@@ -275,7 +261,6 @@ namespace LmbrCentral
azrtti_typeid<LmbrCentralAllocatorComponent>(),
azrtti_typeid<LmbrCentralAssetBuilderAllocatorComponent>(),
azrtti_typeid<LmbrCentralSystemComponent>(),
azrtti_typeid<StereoRendererComponent>(),
azrtti_typeid<NavigationSystemComponent>(),
azrtti_typeid<GeometrySystemComponent>(),
azrtti_typeid<AudioSystemComponent>(),
@@ -394,24 +379,15 @@ namespace LmbrCentral
// Register asset handlers. Requires "AssetDatabaseService"
AZ_Assert(AZ::Data::AssetManager::IsReady(), "Asset manager isn't ready!");
auto lensFlareAssetHandler = aznew LensFlareAssetHandler;
lensFlareAssetHandler->Register(); // registers self with AssetManager
m_assetHandlers.emplace_back(lensFlareAssetHandler);
auto meshAssetHandler = aznew MeshAssetHandler();
meshAssetHandler->Register(); // registers self with AssetManager
m_assetHandlers.emplace_back(meshAssetHandler);
auto geomCacheAssetHandler = aznew GeomCacheAssetHandler();
geomCacheAssetHandler->Register(); // registers self with AssetManager
m_assetHandlers.emplace_back(geomCacheAssetHandler);
// Add asset types and extensions to AssetCatalog. Uses "AssetCatalogService".
auto assetCatalog = AZ::Data::AssetCatalogRequestBus::FindFirstHandler();
if (assetCatalog)
{
assetCatalog->EnableCatalogForAsset(AZ::AzTypeInfo<AZ::ScriptAsset>::Uuid());
assetCatalog->EnableCatalogForAsset(AZ::AzTypeInfo<LensFlareAsset>::Uuid());
assetCatalog->EnableCatalogForAsset(AZ::AzTypeInfo<MaterialAsset>::Uuid());
assetCatalog->EnableCatalogForAsset(AZ::AzTypeInfo<DccMaterialAsset>::Uuid());
assetCatalog->EnableCatalogForAsset(AZ::AzTypeInfo<MeshAsset>::Uuid());
@@ -25,16 +25,7 @@
#include "Audio/EditorAudioRtpcComponent.h"
#include "Audio/EditorAudioSwitchComponent.h"
#include "Audio/EditorAudioTriggerComponent.h"
#include "Rendering/EditorDecalComponent.h"
#include "Rendering/EditorLensFlareComponent.h"
#include "Rendering/EditorLightComponent.h"
#include "Rendering/EditorPointLightComponent.h"
#include "Rendering/EditorAreaLightComponent.h"
#include "Rendering/EditorProjectorLightComponent.h"
#include "Rendering/EditorEnvProbeComponent.h"
#include "Rendering/EditorHighQualityShadowComponent.h"
#include "Rendering/EditorMeshComponent.h"
#include "Rendering/EditorGeomCacheComponent.h"
#include "Scripting/EditorLookAtComponent.h"
#include "Scripting/EditorRandomTimedSpawnerComponent.h"
#include "Scripting/EditorSpawnerComponent.h"
@@ -79,14 +70,6 @@ namespace LmbrCentral
EditorAudioRtpcComponent::CreateDescriptor(),
EditorAudioSwitchComponent::CreateDescriptor(),
EditorAudioTriggerComponent::CreateDescriptor(),
EditorDecalComponent::CreateDescriptor(),
EditorLensFlareComponent::CreateDescriptor(),
EditorLightComponent::CreateDescriptor(),
EditorPointLightComponent::CreateDescriptor(),
EditorAreaLightComponent::CreateDescriptor(),
EditorProjectorLightComponent::CreateDescriptor(),
EditorEnvProbeComponent::CreateDescriptor(),
EditorHighQualityShadowComponent::CreateDescriptor(),
EditorMeshComponent::CreateDescriptor(),
EditorTagComponent::CreateDescriptor(),
EditorSphereShapeComponent::CreateDescriptor(),
@@ -104,7 +87,6 @@ namespace LmbrCentral
EditorNavigationAreaComponent::CreateDescriptor(),
EditorNavigationSeedComponent::CreateDescriptor(),
EditorRandomTimedSpawnerComponent::CreateDescriptor(),
EditorGeometryCacheComponent::CreateDescriptor(),
EditorSpawnerComponent::CreateDescriptor(),
CopyDependencyBuilder::CopyDependencyBuilderComponent::CreateDescriptor(),
DependencyBuilder::DependencyBuilderComponent::CreateDescriptor(),
@@ -1,229 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include "DecalComponent.h"
#include <LmbrCentral/Rendering/Utils/MaterialOwnerRequestBusHandlerImpl.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <MathConversion.h>
#include <I3DEngine.h>
#include <AzCore/RTTI/BehaviorContext.h>
namespace LmbrCentral
{
void DecalConfiguration::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<DecalConfiguration>()->
Version(2, &VersionConverter)->
Field("Visible", &DecalConfiguration::m_visible)->
Field("ProjectionType", &DecalConfiguration::m_projectionType)->
Field("Material", &DecalConfiguration::m_material)->
Field("SortPriority", &DecalConfiguration::m_sortPriority)->
Field("Depth", &DecalConfiguration::m_depth)->
Field("Offset", &DecalConfiguration::m_position)->
Field("Opacity", &DecalConfiguration::m_opacity)->
Field("Angle Attenuation", &DecalConfiguration::m_angleAttenuation)->
Field("Deferred", &DecalConfiguration::m_deferred)->
Field("DeferredString", &DecalConfiguration::m_deferredString)->
Field("Max View Distance", &DecalConfiguration::m_maxViewDist)->
Field("View Distance Multiplier", &DecalConfiguration::m_viewDistanceMultiplier)->
Field("Min Spec", &DecalConfiguration::m_minSpec)
;
}
AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
if (behaviorContext)
{
behaviorContext->EBus<DecalComponentRequestBus>("DecalComponentRequestBus")
->Event("SetVisibility", &DecalComponentRequestBus::Events::SetVisibility)
->Event("Show", &DecalComponentRequestBus::Events::Show)
->Event("Hide", &DecalComponentRequestBus::Events::Hide)
;
}
}
// Private Static
bool DecalConfiguration::VersionConverter([[maybe_unused]] AZ::SerializeContext& context,
AZ::SerializeContext::DataElementNode& classElement)
{
// conversion from version 1:
// - Remove Normal
if (classElement.GetVersion() <= 1)
{
classElement.RemoveElementByName(AZ_CRC_CE("Normal"));
}
return true;
}
//////////////////////////////////////////////////////////////////////////
void DecalComponent::Reflect(AZ::ReflectContext* context)
{
DecalConfiguration::Reflect(context);
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<DecalComponent, AZ::Component>()->
Version(1)->
Field("DecalConfiguration", &DecalComponent::m_configuration);
;
}
}
//////////////////////////////////////////////////////////////////////////
DecalComponent::DecalComponent()
: m_decalRenderNode(nullptr)
{
m_materialBusHandler = aznew MaterialOwnerRequestBusHandlerImpl;
}
DecalComponent::~DecalComponent()
{
delete m_materialBusHandler;
}
void DecalComponent::Activate()
{
}
void DecalComponent::Deactivate()
{
}
void DecalComponent::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world)
{
SDecalProperties decalProperties = m_configuration.GetDecalProperties(world);
if (m_decalRenderNode)
{
m_decalRenderNode->SetDecalProperties(decalProperties);
m_decalRenderNode->SetMatrix(AZTransformToLYTransform(world));
}
}
void DecalComponent::Show()
{
if (!m_decalRenderNode)
{
return;
}
m_decalRenderNode->Hide(false);
}
void DecalComponent::Hide()
{
if (!m_decalRenderNode)
{
return;
}
m_decalRenderNode->Hide(true);
}
void DecalComponent::SetVisibility(bool show)
{
if (show)
{
Show();
}
else
{
Hide();
}
}
IRenderNode* DecalComponent::GetRenderNode()
{
return m_decalRenderNode;
}
float DecalComponent::GetRenderNodeRequestBusOrder() const
{
return s_renderNodeRequestBusOrder;
}
bool DecalComponent::IsMaterialOwnerReady()
{
return m_materialBusHandler->IsMaterialOwnerReady();
}
void DecalComponent::SetMaterial(_smart_ptr<IMaterial> material)
{
m_materialBusHandler->SetMaterial(material);
}
_smart_ptr<IMaterial> DecalComponent::GetMaterial()
{
return m_materialBusHandler->GetMaterial();
}
void DecalComponent::SetMaterialHandle(const MaterialHandle& materialHandle)
{
m_materialBusHandler->SetMaterialHandle(materialHandle);
}
MaterialHandle DecalComponent::GetMaterialHandle()
{
return m_materialBusHandler->GetMaterialHandle();
}
void DecalComponent::SetMaterialParamVector4(const AZStd::string& name, const AZ::Vector4& value, int materialId)
{
m_materialBusHandler->SetMaterialParamVector4(name, value, materialId);
}
void DecalComponent::SetMaterialParamVector3(const AZStd::string& name, const AZ::Vector3& value, int materialId)
{
m_materialBusHandler->SetMaterialParamVector3(name, value, materialId);
}
void DecalComponent::SetMaterialParamColor(const AZStd::string& name, const AZ::Color& value, int materialId)
{
m_materialBusHandler->SetMaterialParamColor(name, value, materialId);
}
void DecalComponent::SetMaterialParamFloat(const AZStd::string& name, float value, int materialId)
{
m_materialBusHandler->SetMaterialParamFloat(name, value, materialId);
}
AZ::Vector4 DecalComponent::GetMaterialParamVector4(const AZStd::string& name, int materialId)
{
return m_materialBusHandler->GetMaterialParamVector4(name, materialId);
}
AZ::Vector3 DecalComponent::GetMaterialParamVector3(const AZStd::string& name, int materialId)
{
return m_materialBusHandler->GetMaterialParamVector3(name, materialId);
}
AZ::Color DecalComponent::GetMaterialParamColor(const AZStd::string& name, int materialId)
{
return m_materialBusHandler->GetMaterialParamColor(name, materialId);
}
float DecalComponent::GetMaterialParamFloat(const AZStd::string& name, int materialId)
{
return m_materialBusHandler->GetMaterialParamFloat(name, materialId);
}
const float DecalComponent::s_renderNodeRequestBusOrder = 900.f;
} // namespace LmbrCentral
@@ -1,187 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/Component.h>
#include <AzCore/Math/Vector3.h>
#include <AzCore/Math/Transform.h>
#include <AzCore/Component/TransformBus.h>
#include <MathConversion.h>
#include <IEntityRenderState.h>
#include <LmbrCentral/Rendering/DecalComponentBus.h>
#include <LmbrCentral/Rendering/RenderNodeBus.h>
#include <LmbrCentral/Rendering/MaterialAsset.h>
#include <LmbrCentral/Rendering/MaterialOwnerBus.h>
namespace LmbrCentral
{
class MaterialOwnerRequestBusHandlerImpl;
/*!
* Contains properties used to create decals, these properties are later propagated to the
* 3D engine decal system.
*/
class DecalConfiguration
{
public:
AZ_TYPE_INFO(DecalConfiguration, "{47082F75-428F-4353-AC82-FAE8AB017F3B}");
virtual ~DecalConfiguration() {}
virtual AZ::u32 MajorPropertyChanged() { return AZ_CRC("RefreshNone", 0x98a5045b); }
virtual AZ::u32 MinorPropertyChanged() { return AZ_CRC("RefreshNone", 0x98a5045b); }
SDecalProperties::EProjectionType m_projectionType = SDecalProperties::EProjectionType::ePlanar;
AZ::Vector3 m_position = AZ::Vector3::CreateZero();
AZ::Transform m_explicitRightUpFront = AZ::Transform::CreateIdentity();
AZ::u32 m_sortPriority = 16;
float m_depth = 1.f;
float m_viewDistanceMultiplier = 1.f;
bool m_visible = true;
bool m_deferred = false;
AZStd::string m_deferredString = "";
float m_opacity = 1.0f;
float m_angleAttenuation = 1.0f;
float m_maxViewDist = 8000.0f;
EngineSpec m_minSpec = EngineSpec::Low;
//! User-specified material override.
AzFramework::SimpleAssetReference<MaterialAsset> m_material;
AZ::EntityId m_editorEntityId; // Editor-only, not reflected.
static void Reflect(AZ::ReflectContext* context);
SDecalProperties GetDecalProperties(const AZ::Transform& transform)
{
SDecalProperties decalProperties;
decalProperties.m_projectionType = m_projectionType;
decalProperties.m_radius = 1.f;
if (m_projectionType != SDecalProperties::ePlanar)
{
decalProperties.m_radius = decalProperties.m_normal.GetLength();
}
Matrix34 wtm = AZTransformToLYTransform(transform);
Matrix33 rotation(wtm);
decalProperties.m_explicitRightUpFront = rotation;
decalProperties.m_pos = wtm.TransformPoint(AZVec3ToLYVec3(m_position));
decalProperties.m_normal = Vec3(0, 0, 1);
decalProperties.m_pMaterialName = m_material.GetAssetPath().c_str();
decalProperties.m_sortPrio = m_sortPriority;
decalProperties.m_deferred = m_deferred;
decalProperties.m_opacity = m_opacity;
decalProperties.m_angleAttenuation = m_angleAttenuation;
decalProperties.m_depth = m_depth;
decalProperties.m_maxViewDist = m_maxViewDist;
decalProperties.m_minSpec = m_minSpec;
return decalProperties;
}
private:
static bool VersionConverter(AZ::SerializeContext& context,
AZ::SerializeContext::DataElementNode& classElement);
};
/*!
* Spawns decals as setup during edit time.
*/
class DecalComponent
: public AZ::Component
, public DecalComponentRequestBus::Handler
, public RenderNodeRequestBus::Handler
, public AZ::TransformNotificationBus::Handler
, public MaterialOwnerRequestBus::Handler
{
public:
AZ_COMPONENT(DecalComponent, "{1C2CEAA8-786F-4684-8202-CA7D940D627B}");
DecalComponent();
~DecalComponent() override;
//////////////////////////////////////////////////////////////////////////
// AZ::Component implementation.
void Activate() override;
void Deactivate() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// DecalComponentRequests implementation.
void Show() override;
void Hide() override;
void SetVisibility(bool visible) override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// RenderNodeRequests implementation
IRenderNode* GetRenderNode() override;
float GetRenderNodeRequestBusOrder() const override;
static const float s_renderNodeRequestBusOrder;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// AZ::TransformNotificationBus implementation.
void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// MaterialOwnerRequestBus interface implementation
bool IsMaterialOwnerReady() override;
void SetMaterial(_smart_ptr<IMaterial>) override;
_smart_ptr<IMaterial> GetMaterial() override;
void SetMaterialHandle(const MaterialHandle& materialHandle) override;
MaterialHandle GetMaterialHandle() override;
void SetMaterialParamVector4( const AZStd::string& /*name*/, const AZ::Vector4& /*value*/, int /*materialId = 1*/) override;
void SetMaterialParamVector3( const AZStd::string& /*name*/, const AZ::Vector3& /*value*/, int /*materialId = 1*/) override;
void SetMaterialParamColor( const AZStd::string& /*name*/, const AZ::Color& /*value*/, int /*materialId = 1*/) override;
void SetMaterialParamFloat( const AZStd::string& /*name*/, float /*value*/, int /*materialId = 1*/) override;
AZ::Vector4 GetMaterialParamVector4( const AZStd::string& /*name*/, int /*materialId = 1*/) override;
AZ::Vector3 GetMaterialParamVector3( const AZStd::string& /*name*/, int /*materialId = 1*/) override;
AZ::Color GetMaterialParamColor( const AZStd::string& /*name*/, int /*materialId = 1*/) override;
float GetMaterialParamFloat( const AZStd::string& /*name*/, int /*materialId = 1*/) override;
///////////////////////////////////
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("DecalService", 0xfb7f71ae));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
required.push_back(AZ_CRC("TransformService", 0x8ee22c50));
}
static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& /*dependent*/)
{
}
static void Reflect(AZ::ReflectContext* context);
void SetConfiguration(const DecalConfiguration& configuration)
{
m_configuration = configuration;
}
protected:
IDecalRenderNode* m_decalRenderNode;
DecalConfiguration m_configuration;
MaterialOwnerRequestBusHandlerImpl* m_materialBusHandler;
};
} // namespace LmbrCentral
@@ -1,63 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include "EditorAreaLightComponent.h"
namespace LmbrCentral
{
void EditorAreaLightComponent::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<EditorAreaLightComponent, EditorLightComponent>()->
Version(1);
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<EditorAreaLightComponent>(
"Area Light", "The Area Light component allows an entity to light a defined area")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "Rendering")
->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/AreaLight.svg")
->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/AreaLight.png")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c))
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-area-light.html")
->Attribute(AZ::Edit::Attributes::ExportIfAllPlatformTags, AZStd::vector<AZ::Crc32>{AZ_CRC("renderer", 0xf199a19c)}) // Only export on platforms that render
->Attribute(AZ::Edit::Attributes::RuntimeExportCallback, &EditorLightComponent::ExportLightComponent)
;
}
}
AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
if (behaviorContext)
{
behaviorContext->Class<EditorAreaLightComponent>()->RequestBus("EditorAreaLightComponentBus");
}
}
void EditorAreaLightComponent::Init()
{
SetLightType(EditorLightConfiguration::LightType::Area);
EditorLightComponent::Init();
}
} // namespace LmbrCentral
@@ -1,39 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include "EditorLightComponent.h"
namespace LmbrCentral
{
/*!
* In-editor point light component.
* Handles previewing and activating lights in the editor.
*/
class EditorAreaLightComponent
: public EditorLightComponent
{
public:
AZ_COMPONENT(EditorAreaLightComponent, "{1DE624B1-876F-4E0A-96A6-7B248FA2076F}", EditorLightComponent);
static void Reflect(AZ::ReflectContext* context);
void Init() override;
protected:
const char* GetLightTypeText() const override
{
return "Area Light";
}
};
} // namespace LmbrCentral
@@ -1,401 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include "EditorDecalComponent.h"
#include <IEditor.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/Math/Quaternion.h>
#include <AzCore/Math/IntersectSegment.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Component/TransformBus.h>
#include <AzCore/Asset/AssetManagerBus.h>
#include <AzToolsFramework/Entity/EditorEntityInfoBus.h>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <IEditor.h>
#include <I3DEngine.h>
namespace LmbrCentral
{
void EditorDecalComponent::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
EditorDecalConfiguration::Reflect(context);
if (serializeContext)
{
serializeContext->Class<EditorDecalComponent, EditorComponentBase>()->
Version(1)->
Field("EditorDecalConfiguration", &EditorDecalComponent::m_configuration)
;
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<EditorDecalComponent>(
"Decal", "The Decal component allows an entity to project a texture or material onto a mesh")->
ClassElement(AZ::Edit::ClassElements::EditorData, "")->
Attribute(AZ::Edit::Attributes::Category, "Rendering")->
Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Decal.svg")->
Attribute(AZ::Edit::Attributes::PrimaryAssetType, AZ::AzTypeInfo<LmbrCentral::MaterialAsset>::Uuid())->
Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Decal.png")->
Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c))->
Attribute(AZ::Edit::Attributes::AutoExpand, true)->
Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-decal.html")->
DataElement(0, &EditorDecalComponent::m_configuration, "Settings", "Decal configuration")->
Attribute(AZ::Edit::Attributes::Visibility, AZ_CRC("PropertyVisibility_ShowChildrenOnly", 0xef428f20))
;
}
}
}
//////////////////////////////////////////////////////////////////////////
void EditorDecalConfiguration::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<EditorDecalConfiguration, DecalConfiguration>()->
Version(1);
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<DecalConfiguration>(
"Render Settings", "Rendering options for the decal.")->
ClassElement(AZ::Edit::ClassElements::EditorData, "")->
Attribute(AZ::Edit::Attributes::AutoExpand, true)->
Attribute(AZ::Edit::Attributes::Visibility, AZ_CRC("PropertyVisibility_ShowChildrenOnly", 0xef428f20))->
ClassElement(AZ::Edit::ClassElements::Group, "Decal Settings")->
Attribute(AZ::Edit::Attributes::AutoExpand, true)->
DataElement(0, &DecalConfiguration::m_position, "Offset", "")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MinorPropertyChanged)->
DataElement(0, &DecalConfiguration::m_visible, "Visible", "")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MinorPropertyChanged)->
DataElement(AZ::Edit::UIHandlers::ComboBox, &DecalConfiguration::m_projectionType, "Projection type", "")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MajorPropertyChanged)->
EnumAttribute(SDecalProperties::EProjectionType::ePlanar, "Planar")->
EnumAttribute(SDecalProperties::EProjectionType::eProjectOnTerrain, "On Terrain")->
EnumAttribute(SDecalProperties::EProjectionType::eProjectOnTerrainAndStaticObjects, "On Terrain and Static Objects")->
DataElement(AZ::Edit::UIHandlers::Default, &DecalConfiguration::m_deferredString, "Deferred", "")->
Attribute(AZ::Edit::Attributes::ReadOnly, true)->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MajorPropertyChanged)->
DataElement(AZ::Edit::UIHandlers::SpinBox, &DecalConfiguration::m_sortPriority, "Sort priority", "Higher priority renders decals on top.")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MinorPropertyChanged)->
Attribute(AZ::Edit::Attributes::Min, 0)->
Attribute(AZ::Edit::Attributes::Max, 255)->
Attribute(AZ::Edit::Attributes::Step, 1)->
DataElement(AZ::Edit::UIHandlers::SpinBox, &DecalConfiguration::m_depth, "Depth", "")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MinorPropertyChanged)->
Attribute(AZ::Edit::Attributes::Min, 0.0001f)->
Attribute(AZ::Edit::Attributes::Max, 10.f)->
Attribute(AZ::Edit::Attributes::Step, 1.f / 255.f)->
DataElement(0, &DecalConfiguration::m_material, "Material", "")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MajorPropertyChanged)->
DataElement(AZ::Edit::UIHandlers::Slider, &DecalConfiguration::m_opacity, "Opacity", "Additional opacity setting on top of the distance from the decal to the surface")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MinorPropertyChanged)->
Attribute(AZ::Edit::Attributes::Min, 0.f)->
Attribute(AZ::Edit::Attributes::Max, 1.f)->
Attribute(AZ::Edit::Attributes::Visibility, &DecalConfiguration::m_deferred)->
DataElement(AZ::Edit::UIHandlers::Slider, &DecalConfiguration::m_angleAttenuation, "Angle Attenuation", "amount of angle attenuation computation taken into account")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MinorPropertyChanged)->
Attribute(AZ::Edit::Attributes::Min, 0.f)->
Attribute(AZ::Edit::Attributes::Max, 1.f)->
Attribute(AZ::Edit::Attributes::Visibility, &DecalConfiguration::m_deferred)->
ClassElement(AZ::Edit::ClassElements::Group, "Options")->
DataElement(AZ::Edit::UIHandlers::Default, &DecalConfiguration::m_maxViewDist, "Max view distance", "The furthest distance this decal can be seen from")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MinorPropertyChanged)->
Attribute(AZ::Edit::Attributes::Suffix, " m")->
Attribute(AZ::Edit::Attributes::Min, 0.f)->
Attribute(AZ::Edit::Attributes::Max, 8000.0f)->
Attribute(AZ::Edit::Attributes::Step, 0.1f)->
DataElement(AZ::Edit::UIHandlers::SpinBox, &DecalConfiguration::m_viewDistanceMultiplier, "View distance multiplier", "")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MinorPropertyChanged)->
Attribute(AZ::Edit::Attributes::Min, 0.f)->
Attribute(AZ::Edit::Attributes::Max, IRenderNode::VIEW_DISTANCE_MULTIPLIER_MAX)->
DataElement(AZ::Edit::UIHandlers::ComboBox, &DecalConfiguration::m_minSpec, "Minimum spec", "Min spec for light to be active.")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &DecalConfiguration::MinorPropertyChanged)->
EnumAttribute(EngineSpec::Never, "Never")->
EnumAttribute(EngineSpec::VeryHigh, "Very high")->
EnumAttribute(EngineSpec::High, "High")->
EnumAttribute(EngineSpec::Medium, "Medium")->
EnumAttribute(EngineSpec::Low, "Low")
;
}
}
}
//////////////////////////////////////////////////////////////////////////
AZ::u32 EditorDecalConfiguration::MajorPropertyChanged()
{
if (m_editorEntityId.IsValid())
{
EBUS_EVENT_ID(m_editorEntityId, DecalComponentEditorRequests::Bus, RefreshDecal);
}
return AZ::Edit::PropertyRefreshLevels::EntireTree;
}
AZ::u32 EditorDecalConfiguration::MinorPropertyChanged()
{
if (m_editorEntityId.IsValid())
{
EBUS_EVENT_ID(m_editorEntityId, DecalComponentEditorRequests::Bus, RefreshDecal);
}
return AZ::Edit::PropertyRefreshLevels::None;
}
//////////////////////////////////////////////////////////////////////////
EditorDecalComponent::EditorDecalComponent()
: m_materialLayersMask(0)
{
}
EditorDecalComponent::~EditorDecalComponent()
{
}
void EditorDecalComponent::Activate()
{
Base::Activate();
}
void EditorDecalComponent::Deactivate()
{
Base::Deactivate();
}
void EditorDecalComponent::BuildGameEntity(AZ::Entity* gameEntity)
{
DecalComponent* decalComponent = gameEntity->CreateComponent<DecalComponent>();
if (decalComponent)
{
decalComponent->SetConfiguration(m_configuration);
}
}
void EditorDecalComponent::OnEditorSpecChange()
{
RefreshDecal();
}
void EditorDecalComponent::RefreshDecal()
{
if (!m_decalRenderNode)
{
return;
}
if (m_configuration.m_projectionType == SDecalProperties::EProjectionType::eProjectOnTerrainAndStaticObjects)
{
m_configuration.m_deferred = true;
m_configuration.m_deferredString = "Yes";
}
else
{
m_configuration.m_deferred = false;
m_configuration.m_deferredString = "No";
}
m_renderFlags = 0;
if (IsSelected())
{
m_renderFlags |= ERF_SELECTED;
}
// take the entity's visibility into account
bool visible = false;
AzToolsFramework::EditorEntityInfoRequestBus::EventResult(
visible, GetEntityId(), &AzToolsFramework::EditorEntityInfoRequestBus::Events::IsVisible);
const int configSpec = gEnv->pSystem->GetConfigSpec(true);
if (!visible || !m_configuration.m_visible || static_cast<AZ::u32>(configSpec) < static_cast<AZ::u32>(m_configuration.m_minSpec))
{
m_renderFlags |= ERF_HIDDEN;
}
//Set default material
if (m_configuration.m_material.GetAssetPath().empty())
{
m_configuration.m_material.SetAssetPath("engineassets/materials/decals/default.mtl");
}
AZ::Transform transform = AZ::Transform::CreateIdentity();
EBUS_EVENT_ID_RESULT(transform, GetEntityId(), AZ::TransformBus, GetWorldTM);
SDecalProperties decalProperties = m_configuration.GetDecalProperties(transform);
m_decalRenderNode->SetDecalProperties(decalProperties);
m_renderFlags |= ERF_COMPONENT_ENTITY;
m_decalRenderNode->SetRndFlags(m_renderFlags);
m_decalRenderNode->SetMatrix(AZTransformToLYTransform(transform));
m_decalRenderNode->SetMinSpec(static_cast<int>(decalProperties.m_minSpec));
m_decalRenderNode->SetMaterialLayers(m_materialLayersMask);
m_decalRenderNode->SetViewDistanceMultiplier(m_configuration.m_viewDistanceMultiplier);
}
void EditorDecalComponent::SetPrimaryAsset(const AZ::Data::AssetId& id)
{
AZStd::string assetPath;
EBUS_EVENT_RESULT(assetPath, AZ::Data::AssetCatalogRequestBus, GetAssetPathById, id);
m_configuration.m_material.SetAssetPath(assetPath.c_str());
RefreshDecal();
EBUS_EVENT(AzToolsFramework::ToolsApplicationRequests::Bus, AddDirtyEntity, GetEntityId());
}
void EditorDecalComponent::DisplayEntityViewport(
[[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo,
AzFramework::DebugDisplayRequests& debugDisplay)
{
// Displays a small grid over the area where the decal will be applied.
if (!IsSelected())
{
return;
}
AZ::Transform transform = AZ::Transform::CreateIdentity();
EBUS_EVENT_ID_RESULT(transform, GetEntityId(), AZ::TransformBus, GetWorldTM);
AZ::Vector3 x1 = transform.TransformPoint(AZ::Vector3(-1, 0, 0));
AZ::Vector3 x2 = transform.TransformPoint(AZ::Vector3(1, 0, 0));
AZ::Vector3 y1 = transform.TransformPoint(AZ::Vector3(0, -1, 0));
AZ::Vector3 y2 = transform.TransformPoint(AZ::Vector3(0, 1, 0));
AZ::Vector3 p = transform.TransformPoint(AZ::Vector3(0, 0, 0));
AZ::Vector3 n = transform.TransformPoint(AZ::Vector3(0, 0, 1));
debugDisplay.SetColor(AZ::Vector4(1, 0, 0, 1));
debugDisplay.DrawLine(p, n);
debugDisplay.DrawLine(x1, x2);
debugDisplay.DrawLine(y1, y2);
AZ::Vector3 p0 = transform.TransformPoint(AZ::Vector3(-1, -1, 0));
AZ::Vector3 p1 = transform.TransformPoint(AZ::Vector3(-1, 1, 0));
AZ::Vector3 p2 = transform.TransformPoint(AZ::Vector3(1, 1, 0));
AZ::Vector3 p3 = transform.TransformPoint(AZ::Vector3(1, -1, 0));
debugDisplay.DrawLine(p0, p1);
debugDisplay.DrawLine(p1, p2);
debugDisplay.DrawLine(p2, p3);
debugDisplay.DrawLine(p3, p0);
debugDisplay.DrawLine(p0, p2);
debugDisplay.DrawLine(p1, p3);
}
void EditorDecalComponent::OnEntityVisibilityChanged(bool /*visibility*/)
{
RefreshDecal();
}
IRenderNode* EditorDecalComponent::GetRenderNode()
{
return m_decalRenderNode;
}
float EditorDecalComponent::GetRenderNodeRequestBusOrder() const
{
return DecalComponent::s_renderNodeRequestBusOrder;
}
void EditorDecalComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& /*world*/)
{
RefreshDecal();
}
void EditorDecalComponent::SetMaterial(_smart_ptr<IMaterial> material)
{
if (material)
{
m_configuration.m_material.SetAssetPath(material->GetName());
}
else
{
m_configuration.m_material.SetAssetPath("");
}
RefreshDecal();
EBUS_EVENT(AzToolsFramework::ToolsApplicationEvents::Bus, InvalidatePropertyDisplay, AzToolsFramework::Refresh_AttributesAndValues);
}
_smart_ptr<IMaterial> EditorDecalComponent::GetMaterial()
{
return m_decalRenderNode->GetMaterial();
}
AZ::Aabb EditorDecalComponent::GetEditorSelectionBoundsViewport(const AzFramework::ViewportInfo& /*viewportInfo*/)
{
return GetWorldBounds();
}
AZ::Aabb EditorDecalComponent::GetWorldBounds()
{
AZ::Transform transform = AZ::Transform::CreateIdentity();
AZ::TransformBus::EventResult(transform, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM);
return GetLocalBounds().GetTransformedAabb(transform);
}
AZ::Aabb EditorDecalComponent::GetLocalBounds()
{
AZ::Aabb bbox = AZ::Aabb::CreateNull();
bbox.AddPoint(AZ::Vector3(-1, -1, 0));
bbox.AddPoint(AZ::Vector3(-1, 1, 0));
bbox.AddPoint(AZ::Vector3(1, 1, 0));
bbox.AddPoint(AZ::Vector3(1, -1, 0));
return bbox;
}
bool EditorDecalComponent::EditorSelectionIntersectRayViewport(const AzFramework::ViewportInfo& /*viewportInfo*/, const AZ::Vector3& src, const AZ::Vector3& dir, float& distance)
{
AZ::Transform transform = AZ::Transform::CreateIdentity();
AZ::TransformBus::EventResult(transform, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM);
AZ::Vector3 p0 = transform.TransformPoint(AZ::Vector3(-1, -1, 0));
AZ::Vector3 p1 = transform.TransformPoint(AZ::Vector3(-1, 1, 0));
AZ::Vector3 p2 = transform.TransformPoint(AZ::Vector3(1, 1, 0));
AZ::Vector3 p3 = transform.TransformPoint(AZ::Vector3(1, -1, 0));
float t{ 0.0f };
bool hitResult = AZ::Intersect::IntersectRayQuad(src, dir, p0, p1, p2, p3, t) != 0;
distance = t;
return hitResult;
}
} // namespace LmbrCentral
@@ -1,145 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/Component.h>
#include <AzCore/Component/TransformBus.h>
#include <AzFramework/Visibility/BoundsBus.h>
#include <AzToolsFramework/ToolsComponents/EditorComponentBase.h>
#include <AzToolsFramework/ToolsComponents/EditorVisibilityBus.h>
#include <AzToolsFramework/API/ComponentEntitySelectionBus.h>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <AzFramework/Entity/EntityDebugDisplayBus.h>
#include <LmbrCentral/Rendering/MeshComponentBus.h>
#include "DecalComponent.h"
namespace LmbrCentral
{
/*!
* Extends DecalConfiguration structure to add editor functionality
* such as property handlers and visibility filters, as well as
* reflection for editing.
*/
class EditorDecalConfiguration
: public DecalConfiguration
{
public:
AZ_TYPE_INFO(EditorDecalConfiguration, "{559556BE-F41E-43C0-9EE6-7048D84D7952}");
~EditorDecalConfiguration() override {}
static void Reflect(AZ::ReflectContext* context);
AZ::u32 MajorPropertyChanged() override;
AZ::u32 MinorPropertyChanged() override;
};
/*!
* In-editor decal component.
* Handles placement of decals in editor.
*/
class EditorDecalComponent
: public AzToolsFramework::Components::EditorComponentBase
, private DecalComponentEditorRequests::Bus::Handler
, private MaterialOwnerRequestBus::Handler
, private RenderNodeRequestBus::Handler
, private AZ::TransformNotificationBus::Handler
, private AzFramework::EntityDebugDisplayEventBus::Handler
, private AzToolsFramework::EditorVisibilityNotificationBus::Handler
, private AzToolsFramework::EditorEvents::Bus::Handler
, private AzToolsFramework::EditorComponentSelectionRequestsBus::Handler
, public AzFramework::BoundsRequestBus::Handler
{
private:
using Base = AzToolsFramework::Components::EditorComponentBase;
public:
AZ_COMPONENT(EditorDecalComponent, "{BA3890BD-D2E7-4DB6-95CD-7E7D5525567A}", AzToolsFramework::Components::EditorComponentBase);
EditorDecalComponent();
~EditorDecalComponent() override;
// AZ::Component interface implementation
void Activate() override;
void Deactivate() override;
// AzFramework::EntityDebugDisplayEventBus
void DisplayEntityViewport(
const AzFramework::ViewportInfo& viewportInfo,
AzFramework::DebugDisplayRequests& debugDisplay) override;
// AzToolsFramework::EditorVisibilityNotificationBus interface implementation
void OnEntityVisibilityChanged(bool visibility) override;
// DecalComponentEditorRequests::Bus::Handler interface implementation
void RefreshDecal() override;
// MaterialOwnerRequestBus interface implementation
void SetMaterial(_smart_ptr<IMaterial>) override;
_smart_ptr<IMaterial> GetMaterial() override;
// RenderNodeRequestBus::Handler interface implementation
IRenderNode* GetRenderNode() override;
float GetRenderNodeRequestBusOrder() const override;
// TransformNotificationBus::Handler interface implementation
void OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& /*world*/) override;
// EditorComponentSelectionRequestsBus::Handler interface implementation
AZ::Aabb GetEditorSelectionBoundsViewport(const AzFramework::ViewportInfo&) override;
bool SupportsEditorRayIntersect() override { return true; };
bool EditorSelectionIntersectRayViewport(
const AzFramework::ViewportInfo& viewportInfo, const AZ::Vector3& src, const AZ::Vector3& dir,
float& distance) override;
// BoundsRequestBus overrides ...
AZ::Aabb GetWorldBounds() override;
AZ::Aabb GetLocalBounds() override;
void BuildGameEntity(AZ::Entity* gameEntity) override;
//! Called when you want to change the game asset through code (like when creating components based on assets).
void SetPrimaryAsset(const AZ::Data::AssetId& assetId) override;
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
DecalComponent::GetProvidedServices(provided);
}
static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent)
{
DecalComponent::GetDependentServices(dependent);
dependent.push_back(AZ_CRC_CE("EditorVisibilityService"));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
DecalComponent::GetRequiredServices(required);
}
static void Reflect(AZ::ReflectContext* context);
protected:
EditorDecalConfiguration m_configuration;
IDecalRenderNode* m_decalRenderNode;
uint32 m_renderFlags;
uint8 m_materialLayersMask;
private:
// AzToolsFramework::EditorEvents interface implementation
void OnEditorSpecChange() override;
};
} // namespace LmbrCentral
@@ -1,63 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include "EditorEnvProbeComponent.h"
namespace LmbrCentral
{
void EditorEnvProbeComponent::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<EditorEnvProbeComponent, EditorLightComponent>()->
Version(1);
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<EditorEnvProbeComponent>(
"Environment Probe", "The Environment Probe component is used to achieve the right visual quality for a space and help determine proper reflections, ambient diffuse values, particle diffuse values, and shadow colors")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "Rendering")
->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/EnvironmentProbe.svg")
->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/EnvironmentProbe.png")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c))
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-environment-probe.html")
->Attribute(AZ::Edit::Attributes::RuntimeExportCallback, &EditorLightComponent::ExportLightComponent)
;
}
}
AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
if (behaviorContext)
{
behaviorContext->Class<EditorEnvProbeComponent>()->RequestBus("EditorProbeLightComponentBus");
}
}
void EditorEnvProbeComponent::Init()
{
SetLightType(EditorLightConfiguration::LightType::Probe);
EditorLightComponent::Init();
}
} // namespace LmbrCentral
@@ -1,39 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include "EditorLightComponent.h"
namespace LmbrCentral
{
/*!
* In-editor point light component.
* Handles previewing and activating lights in the editor.
*/
class EditorEnvProbeComponent
: public EditorLightComponent
{
public:
AZ_COMPONENT(EditorEnvProbeComponent, "{8DBD6035-583E-409F-AFD9-F36829A0655D}", EditorLightComponent);
static void Reflect(AZ::ReflectContext* context);
void Init() override;
protected:
const char* GetLightTypeText() const override
{
return "Environment Probe";
}
};
} // namespace LmbrCentral
@@ -1,347 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include "EditorGeomCacheComponent.h"
#include <AzCore/RTTI/BehaviorContext.h>
#include <LmbrCentral/Rendering/MeshComponentBus.h>
namespace LmbrCentral
{
void EditorGeometryCacheCommon::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<EditorGeometryCacheCommon, GeometryCacheCommon>()
->Version(1)
;
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<EditorGeometryCacheCommon>("Editor Geom Cache Common Configuration", "")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
;
editContext->Class<GeometryCacheCommon>("Geom Cache Common Configuration", "")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_visible, "Visible", "Should the GeomCache be rendered.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnRenderOptionsChanged)
->DataElement(AZ::Edit::UIHandlers::ComboBox, &GeometryCacheCommon::m_minSpec, "Min Spec", "The minimum graphics spec where this GeomCache will be rendered.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnRenderOptionsChanged)
->EnumAttribute(EngineSpec::Never, "Never")
->EnumAttribute(EngineSpec::VeryHigh, "Very high")
->EnumAttribute(EngineSpec::High, "High")
->EnumAttribute(EngineSpec::Medium, "Medium")
->EnumAttribute(EngineSpec::Low, "Low")
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_geomCacheAsset, "Geom Cache", "The Alembic Geometry Cache asset.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnGeomCacheAssetChanged)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_materialOverrideAsset, "Material Override", "Optional material override asset.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnMaterialOverrideChanged)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_loop, "Loop", "Should the animation loop.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnLoopChanged)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_playOnStart, "Play on Start", "Should the alembic animation play when the component activates.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnPlayOnStartChanged)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_startTime, "Start Time", "The time point that the animation should start at.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnStartTimeChanged)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_streamInDistance, "Stream In Distance", "How close does the viewer need to be for the GeomCache to begin streaming into memory.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnStreamInDistanceChanged)
->ClassElement(AZ::Edit::ClassElements::Group, "Stand-in Settings")
->Attribute(AZ::Edit::Attributes::AutoExpand, false)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_firstFrameStandin, "First Frame Stand-in", "The entity that should stand in for this GeomCache before playback begins.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnFirstFrameStandinChanged)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_lastFrameStandin, "Last Frame Stand-in", "The entity that should stand in for this GeomCache after playback has ended.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnLastFrameStandinChanged)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_standin, "Stand-in", "The entity that should stand in for this GeomCache when the viewer is past the Stand-in Distance.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnStandinChanged)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_standinDistance, "Stand-in Distance", "How close does the viewer need to be before the GeomCache replaces the Stand-in.")
->ClassElement(AZ::Edit::ClassElements::Group, "Options")
->Attribute(AZ::Edit::Attributes::AutoExpand, false)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_maxViewDistance, "Max View Distance", "That maximum distance that this GeomCache can be viewed from.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnMaxViewDistanceChanged)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_viewDistanceMultiplier, "View Distance Multiplier", "Multiplied to the Max View Distance to get the final max view distance.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnViewDistanceMultiplierChanged)
->DataElement(AZ::Edit::UIHandlers::Slider, &GeometryCacheCommon::m_lodDistanceRatio, "LOD Distance Ratio", "Controls LOD ratio over distance.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnLODDistanceRatioChanged)
->Attribute(AZ::Edit::Attributes::Min, 0)
->Attribute(AZ::Edit::Attributes::Max, 255)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_castShadows, "Cast Shadows", "Should the GeomCache cast shadows.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnRenderOptionsChanged)
->DataElement(AZ::Edit::UIHandlers::Default, &GeometryCacheCommon::m_useVisAreas, "Use Vis Areas", "Should the GeomCache be affected by VisAreas.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &GeometryCacheCommon::OnRenderOptionsChanged)
;
}
}
}
void EditorGeometryCacheCommon::Activate()
{
GeometryCacheCommon::Activate();
EditorGeometryCacheComponentRequestBus::Handler::BusConnect(m_entityId);
//Store the serialized results here so that we can properly react to stand-in changes after level load
m_prevFirstFrameStandin = m_firstFrameStandin;
m_prevLastFrameStandin = m_lastFrameStandin;
m_prevStandin = m_standin;
}
void EditorGeometryCacheCommon::Deactivate()
{
EditorGeometryCacheComponentRequestBus::Handler::BusDisconnect(m_entityId);
GeometryCacheCommon::Deactivate();
}
void EditorGeometryCacheCommon::SetMinSpec(EngineSpec minSpec)
{
m_minSpec = minSpec;
OnRenderOptionsChanged();
}
void EditorGeometryCacheCommon::SetPlayOnStart(bool playOnStart)
{
m_playOnStart = playOnStart;
OnPlayOnStartChanged();
}
void EditorGeometryCacheCommon::SetMaxViewDistance(float maxViewDistance)
{
m_maxViewDistance = maxViewDistance;
OnMaxViewDistanceChanged();
}
void EditorGeometryCacheCommon::SetViewDistanceMultiplier(float viewDistanceMultiplier)
{
m_viewDistanceMultiplier = viewDistanceMultiplier;
OnViewDistanceMultiplierChanged();
}
void EditorGeometryCacheCommon::SetLODDistanceRatio(AZ::u32 lodDistanceRatio)
{
m_lodDistanceRatio = lodDistanceRatio;
OnLODDistanceRatioChanged();
}
void EditorGeometryCacheCommon::SetCastShadows(bool castShadows)
{
m_castShadows = castShadows;
OnRenderOptionsChanged();
}
void EditorGeometryCacheCommon::SetUseVisAreas(bool useVisAreas)
{
m_useVisAreas = useVisAreas;
OnRenderOptionsChanged();
}
void EditorGeometryCacheCommon::OnFirstFrameStandinChanged()
{
//We only need to remove the prev stand-in from the geom cache's hierarchy if it's not used anywhere else
bool removePrevFirstFrameStandinTransform = false;
if (m_prevFirstFrameStandin != m_prevStandin && m_prevFirstFrameStandin != m_prevLastFrameStandin)
{
removePrevFirstFrameStandinTransform = true;
}
HandleStandinChanged(m_prevFirstFrameStandin, m_firstFrameStandin, removePrevFirstFrameStandinTransform);
m_prevFirstFrameStandin = m_firstFrameStandin;
}
void EditorGeometryCacheCommon::OnLastFrameStandinChanged()
{
//We only need to remove the prev stand-in from the geom cache's hierarchy if it's not used anywhere else
bool removePrevLastFrameStandinTransform = false;
if (m_prevLastFrameStandin != m_prevStandin && m_prevLastFrameStandin != m_prevFirstFrameStandin)
{
removePrevLastFrameStandinTransform = true;
}
HandleStandinChanged(m_prevLastFrameStandin, m_lastFrameStandin, removePrevLastFrameStandinTransform);
m_prevLastFrameStandin = m_lastFrameStandin;
}
void EditorGeometryCacheCommon::OnStandinChanged()
{
//We only need to remove the prev stand-in from the geom cache's hierarchy if it's not used anywhere else
bool removePrevStandinTransform = false;
if (m_prevStandin != m_prevLastFrameStandin && m_prevStandin != m_prevFirstFrameStandin)
{
removePrevStandinTransform = true;
}
HandleStandinChanged(m_prevStandin, m_standin, removePrevStandinTransform);
m_prevStandin = m_standin;
}
void EditorGeometryCacheCommon::HandleStandinChanged(const AZ::EntityId& prevStandinId, const AZ::EntityId& newStandinId, bool evictPrevStandinTransform)
{
//Undo modifications we've made to the stand-in entity
if (prevStandinId.IsValid() && evictPrevStandinTransform)
{
//If this stand-in isn't currently active it may be set to invisible. If it's not going to be a stand-in anymore we want it to be visible
MeshComponentRequestBus::Event(prevStandinId, &MeshComponentRequestBus::Events::SetVisibility, true);
//If it's not going to be a stand-in anymore it also doesn't need to be parented. User can re-parent if needed
AZ::TransformBus::Event(prevStandinId, &AZ::TransformBus::Events::SetParent, AZ::EntityId());
}
//Parent new stand-in to geometry cache transform
AZ::TransformBus::Event(newStandinId, &AZ::TransformBus::Events::SetParent, m_entityId);
//Standin will be made visible if necessary in GeomCacheCommon::OnTick
MeshComponentRequestBus::Event(m_standin, &MeshComponentRequestBus::Events::SetVisibility, false);
MeshComponentRequestBus::Event(m_firstFrameStandin, &MeshComponentRequestBus::Events::SetVisibility, false);
MeshComponentRequestBus::Event(m_lastFrameStandin, &MeshComponentRequestBus::Events::SetVisibility, false);
//Force stand-in logic to refresh
m_currentStandinType = StandinType::None;
}
void EditorGeometryCacheCommon::SetMaterial(_smart_ptr<IMaterial> material)
{
GeometryCacheCommon::SetMaterial(material);
AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast(
&AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay,
AzToolsFramework::Refresh_AttributesAndValues);
}
void EditorGeometryCacheComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides)
{
provides.push_back(AZ_CRC("GeomCacheService", 0x3d2bc48c));
}
void EditorGeometryCacheComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires)
{
requires.push_back(AZ_CRC("TransformService", 0x8ee22c50));
}
void EditorGeometryCacheComponent::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<EditorGeometryCacheComponent, AzToolsFramework::Components::EditorComponentBase>()
->Version(1)
->Field("Common", &EditorGeometryCacheComponent::m_common)
;
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<EditorGeometryCacheComponent>("Geometry Cache", "Controls playback of baked vertex animations.")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "Rendering")
->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/GeometryCache.svg")
->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/GeometryCache.png")
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c))
->Attribute(AZ::Edit::Attributes::HelpPageURL, "http://docs.aws.amazon.com/console/lumberyard/userguide/geom-cache-component")
->DataElement(AZ::Edit::UIHandlers::Default, &EditorGeometryCacheComponent::m_common, "Common", "No Description")
;
}
}
if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
{
behaviorContext->Class<EditorGeometryCacheComponent>()
->RequestBus("GeometryCacheComponentRequestBus")
->RequestBus("GeometryCacheComponentNotificationBus")
;
}
EditorGeometryCacheCommon::Reflect(context);
}
void EditorGeometryCacheComponent::Init()
{
m_common.Init(GetEntityId());
}
void EditorGeometryCacheComponent::Activate()
{
m_common.Activate();
AzToolsFramework::Components::EditorComponentBase::Activate();
AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(GetEntityId());
AZ::TransformNotificationBus::Handler::BusConnect(GetEntityId());
//Get initial world transform for debug rendering
m_currentWorldTransform = AZ::Transform::CreateIdentity();
AZ::TransformBus::EventResult(m_currentWorldTransform, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM);
}
void EditorGeometryCacheComponent::Deactivate()
{
AzToolsFramework::Components::EditorComponentBase::Deactivate();
AZ::TransformNotificationBus::Handler::BusDisconnect(GetEntityId());
AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(GetEntityId());
m_common.Deactivate();
}
void EditorGeometryCacheComponent::SetPrimaryAsset(const AZ::Data::AssetId& assetId)
{
m_common.SetGeomCacheAsset(assetId);
}
void EditorGeometryCacheComponent::BuildGameEntity(AZ::Entity* gameEntity)
{
gameEntity->CreateComponent<GeometryCacheComponent>(&m_common);
}
void EditorGeometryCacheComponent::DisplayEntityViewport(
[[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo,
AzFramework::DebugDisplayRequests& debugDisplay)
{
// Don't draw extra visualization unless selected.
if (!IsSelected())
{
return;
}
debugDisplay.PushMatrix(m_currentWorldTransform);
debugDisplay.SetColor(AZ::Vector4(1.0f, 1.0f, 1.0f, 1.0f));
debugDisplay.DrawWireSphere(AZ::Vector3::CreateZero(), m_common.GetStandInDistance());
debugDisplay.DrawWireSphere(AZ::Vector3::CreateZero(), m_common.GetStreamInDistance());
debugDisplay.PopMatrix();
}
void EditorGeometryCacheComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world)
{
m_currentWorldTransform = world;
}
} //namespace LmbrCentral
@@ -1,133 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzFramework/Entity/EntityDebugDisplayBus.h>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <AzToolsFramework/ToolsComponents/EditorComponentBase.h>
#include "GeomCacheComponent.h"
namespace LmbrCentral
{
/**
* Editor extensions for the GeometryCacheCommon
*
* Some parameters of the GeometryCache we only care
* about being able to edit on a bus at edit time. Mostly
* for legacy conversion. Also this class handles the
* PlayOnStart parameter differently.
*/
class EditorGeometryCacheCommon
: public GeometryCacheCommon
, public EditorGeometryCacheComponentRequestBus::Handler
{
public:
AZ_TYPE_INFO_LEGACY(EditorGeometryCacheCommon, "{ACE31D8E-F7BC-48B9-950E-AE191E50A80F}", GeometryCacheCommon);
AZ_CLASS_ALLOCATOR(EditorGeometryCacheCommon, AZ::SystemAllocator, 0);
static void Reflect(AZ::ReflectContext* context);
void Activate() override;
void Deactivate() override;
void SetMinSpec(EngineSpec minSpec) override;
EngineSpec GetMinSpec() override { return m_minSpec; }
void SetPlayOnStart(bool playOnStart) override;
bool GetPlayOnStart() override { return m_playOnStart; }
void SetMaxViewDistance(float maxViewDistance) override;
float GetMaxViewDistance() override { return m_maxViewDistance; }
void SetViewDistanceMultiplier(float viewDistanceMultiplier) override;
float GetViewDistanceMultiplier() override { return m_viewDistanceMultiplier; }
void SetLODDistanceRatio(AZ::u32 lodDistanceRatio) override;
AZ::u32 GetLODDistanceRatio() override { return m_lodDistanceRatio; }
void SetCastShadows(bool castShadows) override;
bool GetCastShadows() override { return m_castShadows; }
void SetUseVisAreas(bool useVisAreas) override;
bool GetUseVisAreas() override { return m_useVisAreas; }
void SetMaterial(_smart_ptr<IMaterial> material) override;
private:
//We want the playOnStart param to reflect playing immediately in the editor
void OnPlayOnStartChanged() override
{
m_playing = m_playOnStart;
m_currentTime = m_startTime;
//As in GeomCacheCommon::Activate we reset m_currentTime to m_startTime so
//that animations begin at the requested time.
}
void OnFirstFrameStandinChanged() override;
void OnLastFrameStandinChanged() override;
void OnStandinChanged() override;
void HandleStandinChanged(const AZ::EntityId& prevStandinId, const AZ::EntityId& newStandinId, bool evictPrevStandinTransform); //Handles the common logic for OnStandinXChanged events
AZ::EntityId m_prevFirstFrameStandin;
AZ::EntityId m_prevLastFrameStandin;
AZ::EntityId m_prevStandin;
};
/**
* The Edit-time implementation of the GeometryCache component
*/
class EditorGeometryCacheComponent
: public AzToolsFramework::Components::EditorComponentBase
, public AzFramework::EntityDebugDisplayEventBus::Handler
, public AZ::TransformNotificationBus::Handler
{
public:
friend class GeomCacheConverter;
AZ_COMPONENT(EditorGeometryCacheComponent, "{045C0C58-C13E-49B0-A471-D4AC5D3FC6BD}", AzToolsFramework::Components::EditorComponentBase);
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides);
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires);
static void Reflect(AZ::ReflectContext* context);
~EditorGeometryCacheComponent() = default;
// EditorComponentBase
void Init() override;
void Activate() override;
void Deactivate() override;
void SetPrimaryAsset(const AZ::Data::AssetId& assetId) override;
void BuildGameEntity(AZ::Entity* gameEntity) override;
private:
// AzFramework::EntityDebugDisplayEventBus
void DisplayEntityViewport(
const AzFramework::ViewportInfo& viewportInfo,
AzFramework::DebugDisplayRequests& debugDisplay) override;
// AZ::TransformNotificationBus
void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override;
//Reflected members
EditorGeometryCacheCommon m_common;
//Unreflected members
AZ::Transform m_currentWorldTransform;
};
} //namespace LmbrCentral
@@ -1,156 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include "EditorHighQualityShadowComponent.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
namespace LmbrCentral
{
void EditorHighQualityShadowConfig::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<EditorHighQualityShadowConfig, HighQualityShadowConfig>()->
Version(1);
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<HighQualityShadowConfig>(
"Shadow Map Settings", "Settings for the entity's shadow map")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->DataElement(AZ::Edit::UIHandlers::Default, &HighQualityShadowConfig::m_enabled, "Enabled", "Enable the shadow map")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &HighQualityShadowConfig::EditorRefresh)
->DataElement(AZ::Edit::UIHandlers::SpinBox, &HighQualityShadowConfig::m_constBias, "Const Bias", "Constant bias")
->Attribute(AZ::Edit::Attributes::Min, 0.f)
->Attribute(AZ::Edit::Attributes::Max, 1.f)
->Attribute(AZ::Edit::Attributes::Step, 0.001f)
->Attribute(AZ::Edit::Attributes::ChangeNotify, &HighQualityShadowConfig::EditorRefresh)
->DataElement(AZ::Edit::UIHandlers::SpinBox, &HighQualityShadowConfig::m_slopeBias, "Slope Bias", "Slope bias")
->Attribute(AZ::Edit::Attributes::Min, 0.f)
->Attribute(AZ::Edit::Attributes::Max, 1.f)
->Attribute(AZ::Edit::Attributes::Step, 0.01f)
->Attribute(AZ::Edit::Attributes::ChangeNotify, &HighQualityShadowConfig::EditorRefresh)
->DataElement(AZ::Edit::UIHandlers::SpinBox, &HighQualityShadowConfig::m_jitter, "Jitter", "Jitter")
->Attribute(AZ::Edit::Attributes::Min, 0.f)
->Attribute(AZ::Edit::Attributes::Max, 1.f)
->Attribute(AZ::Edit::Attributes::Step, 0.01f)
->Attribute(AZ::Edit::Attributes::ChangeNotify, &HighQualityShadowConfig::EditorRefresh)
->DataElement(AZ::Edit::UIHandlers::Vector3, &HighQualityShadowConfig::m_bboxScale, "Bounding Box Scale", "Scale applied to the shadow frustum")
->Attribute(AZ::Edit::Attributes::Min, 0.f)
->Attribute(AZ::Edit::Attributes::ChangeNotify, &HighQualityShadowConfig::EditorRefresh)
->DataElement(AZ::Edit::UIHandlers::ComboBox, &HighQualityShadowConfig::m_shadowMapSize, "Shadow Map Size", "Shadow map size")
->Attribute(AZ::Edit::Attributes::EnumValues, AZStd::vector<AZ::Edit::EnumConstant<int> > {
AZ::Edit::EnumConstant<int>(256, "256"),
AZ::Edit::EnumConstant<int>(512, "512"),
AZ::Edit::EnumConstant<int>(1024, "1024"),
AZ::Edit::EnumConstant<int>(2048, "2048"),
AZ::Edit::EnumConstant<int>(8192, "8192")
})
->Attribute(AZ::Edit::Attributes::ChangeNotify, &HighQualityShadowConfig::EditorRefresh)
;
}
}
}
void EditorHighQualityShadowConfig::EditorRefresh()
{
if (m_entityId.IsValid())
{
EditorHighQualityShadowComponentRequestBus::Event(m_entityId, &EditorHighQualityShadowComponentRequests::RefreshProperties);
}
}
void EditorHighQualityShadowComponent::Reflect(AZ::ReflectContext* context)
{
EditorHighQualityShadowConfig::Reflect(context);
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<EditorHighQualityShadowComponent, EditorComponentBase>()
->Version(1)
->Field("EditorHighQualityShadowConfig", &EditorHighQualityShadowComponent::m_config);
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<EditorHighQualityShadowComponent>("High Quality Shadow", "Assigns a unique shadow map to the entity to provide higher quality shadows. Has performance and memory impact so use sparingly.")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "Rendering")
->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Shadow.svg")
->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Shadow.png")
->Attribute(AZ::Edit::Attributes::PreferNoViewportIcon, true)
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c))
->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-high-quality-shadow.html")
->DataElement(AZ::Edit::UIHandlers::Default, &EditorHighQualityShadowComponent::m_config, "Shadow Map Settings", "Settings for the entity's unique shadow map")
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
;
}
}
}
void EditorHighQualityShadowComponent::Activate()
{
m_config.m_entityId = GetEntityId();
EditorHighQualityShadowComponentRequestBus::Handler::BusConnect(GetEntityId());
MeshComponentNotificationBus::Handler::BusConnect(GetEntityId());
}
void EditorHighQualityShadowComponent::Deactivate()
{
HighQualityShadowComponentUtils::RemoveShadow(GetEntityId());
EditorHighQualityShadowComponentRequestBus::Handler::BusDisconnect();
MeshComponentNotificationBus::Handler::BusDisconnect(GetEntityId());
}
void EditorHighQualityShadowComponent::RefreshProperties()
{
HighQualityShadowComponentUtils::ApplyShadowSettings(GetEntityId(), m_config);
}
void EditorHighQualityShadowComponent::BuildGameEntity(AZ::Entity* gameEntity)
{
if (HighQualityShadowComponent* runtimeComponent = gameEntity->CreateComponent<HighQualityShadowComponent>())
{
runtimeComponent->m_config = m_config;
}
}
void EditorHighQualityShadowComponent::OnMeshCreated([[maybe_unused]] const AZ::Data::Asset<AZ::Data::AssetData>& asset)
{
HighQualityShadowComponentUtils::ApplyShadowSettings(GetEntityId(), m_config);
}
void EditorHighQualityShadowComponent::OnMeshDestroyed()
{
HighQualityShadowComponentUtils::RemoveShadow(GetEntityId());
}
} // namespace LmbrCentral
@@ -1,88 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzToolsFramework/ToolsComponents/EditorComponentBase.h>
#include "HighQualityShadowComponent.h"
namespace LmbrCentral
{
/**
* Extends HighQualityShadowConfig structure for editor functionality.
*/
class EditorHighQualityShadowConfig
: public HighQualityShadowConfig
{
public:
AZ_TYPE_INFO(EditorHighQualityShadowConfig, "{4A7D67C6-E689-427A-B126-A71A4BF8A2C7}");
static void Reflect(AZ::ReflectContext* context);
AZ::EntityId m_entityId; // Editor-only, not reflected.
void EditorRefresh() override;
};
/*!
* In-editor high quality shadow component.
*/
class EditorHighQualityShadowComponent
: public AzToolsFramework::Components::EditorComponentBase
, public EditorHighQualityShadowComponentRequestBus::Handler
, public MeshComponentNotificationBus::Handler
{
public:
AZ_COMPONENT(EditorHighQualityShadowComponent, "{9C86E09D-0727-476E-A4A1-25989CDBF9C6}", AzToolsFramework::Components::EditorComponentBase);
void BuildGameEntity(AZ::Entity* gameEntity) override;
//////////////////////////////////////////////////////////////////////////
// AZ::Component interface implementation
void Activate() override;
void Deactivate() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// MeshComponentNotificationBus interface implementation
void OnMeshCreated(const AZ::Data::Asset<AZ::Data::AssetData>& asset) override;
void OnMeshDestroyed() override;
///////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// EditorHighQualityShadowComponentRequestBus interface implementation
void RefreshProperties() override;
///////////////////////////////////
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("HighQualityShadowService", 0x43dea981));
}
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("HighQualityShadowService", 0x43dea981));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
// HighQualityShadowComponent is only applicable to Entities that cast and/or receive shadows.
required.push_back(AZ_CRC("MeshService", 0x71d8a455));
}
static void Reflect(AZ::ReflectContext* context);
protected:
EditorHighQualityShadowConfig m_config;
};
} // namespace LmbrCentral
@@ -1,564 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/Math/Quaternion.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Asset/AssetManagerBus.h>
#include <AzToolsFramework/Entity/EditorEntityInfoBus.h>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <CryCommon/IFlares.h>
#include <LmbrCentral/Rendering/EditorLightComponentBus.h>
#include "EditorLensFlareComponent.h"
#include "LightComponent.h"
namespace LmbrCentral
{
void EditorLensFlareComponent::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
EditorLensFlareConfiguration::Reflect(context);
if (serializeContext)
{
serializeContext->Class<EditorLensFlareComponent, EditorComponentBase>()->
Version(1)->
Field("Visible", &EditorLensFlareComponent::m_visible)->
Field("LensFlareLibrary", &EditorLensFlareComponent::m_asset)->
Field("SelectedLensFlare", &EditorLensFlareComponent::m_selectedLensFlareName)->
Field("EditorLensFlareConfiguration", &EditorLensFlareComponent::m_configuration)
;
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<EditorLensFlareComponent>(
"Lens Flare", "The Lens Flare component allows the placement of a lens flare on an entity")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "Rendering")
->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/LensFlare.svg")
->Attribute(AZ::Edit::Attributes::PrimaryAssetType, AZ::AzTypeInfo<LmbrCentral::LensFlareAsset>::Uuid())
->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/LensFlare.png")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c))
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-lens-flare.html")
->DataElement(0, &EditorLensFlareComponent::m_configuration, "Settings", "Lens flare configuration")
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->DataElement(AZ::Edit::UIHandlers::CheckBox, &EditorLensFlareComponent::m_visible, "Visible", "The current visibility status of this lens flare")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorLensFlareComponent::OnVisibleChanged)
->DataElement(0, &EditorLensFlareComponent::m_asset, "Library", "The selected library of lens flares.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorLensFlareComponent::OnAssetChanged)
->DataElement(AZ::Edit::UIHandlers::ComboBox, &EditorLensFlareComponent::m_selectedLensFlareName, "Lens flare", "The selected lens flare in this library.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorLensFlareComponent::OnLensFlareSelected)
->Attribute(AZ::Edit::Attributes::StringList, &EditorLensFlareComponent::GetLensFlarePaths)
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
;
}
}
}
void EditorLensFlareConfiguration::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<EditorLensFlareConfiguration, LensFlareConfiguration>()->
Version(1);
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<LensFlareConfiguration>(
"Configuration", "Lens Flare configuration")->
ClassElement(AZ::Edit::ClassElements::EditorData, "")->
Attribute(AZ::Edit::Attributes::AutoExpand, true)->
Attribute(AZ::Edit::Attributes::Visibility, AZ_CRC("PropertyVisibility_ShowChildrenOnly", 0xef428f20))->
ClassElement(AZ::Edit::ClassElements::Group, "Flare Settings")->
DataElement(AZ::Edit::UIHandlers::ComboBox, &LensFlareConfiguration::m_minSpec, "Minimum spec", "Min spec for light to be active.")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
EnumAttribute(EngineSpec::Never, "Never")->
EnumAttribute(EngineSpec::VeryHigh, "Very high")->
EnumAttribute(EngineSpec::High, "High")->
EnumAttribute(EngineSpec::Medium, "Medium")->
EnumAttribute(EngineSpec::Low, "Low")->
DataElement(0, &LensFlareConfiguration::m_lensFlareFrustumAngle, "FOV", "The lens flare FOV angle")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
Attribute(AZ::Edit::Attributes::Min, 0.f)->
Attribute(AZ::Edit::Attributes::Step, 1.f)->
Attribute(AZ::Edit::Attributes::Max, 360.f)->
Attribute(AZ::Edit::Attributes::Suffix, " degrees")->
DataElement(AZ::Edit::UIHandlers::Default, &LensFlareConfiguration::m_size, "Size", "The size of the lens flare")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
Attribute(AZ::Edit::Attributes::Min, 0.f)->
DataElement(0, &LensFlareConfiguration::m_attachToSun, "Attach to sun", "Attach this flare to the sun")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::AttachToSunChanged)->
DataElement(0, &LensFlareConfiguration::m_useVisAreas, "Use VisAreas", "Lens Flares is affected by VisAreas")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
DataElement(0, &LensFlareConfiguration::m_indoorOnly, "Indoor only", "Indoor only")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
DataElement(0, &LensFlareConfiguration::m_onInitially, "On initially", "The lens flare is initially turned on.")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
DataElement(0, &LensFlareConfiguration::m_viewDistMultiplier, "View distance multiplier", "Adjusts max view distance. If 1.0 then default is used. 1.1 would be 10% further than default.")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
// Will be visible if attach to sun is false.
Attribute(AZ::Edit::Attributes::Visibility, &LensFlareConfiguration::ShouldViewDistanceMultiplier)->
Attribute(AZ::Edit::Attributes::Suffix, "x")->
Attribute(AZ::Edit::Attributes::Min, 0.f)->
ClassElement(AZ::Edit::ClassElements::Group, "Color Settings")->
DataElement(AZ::Edit::UIHandlers::Color, &LensFlareConfiguration::m_tint, "Tint", "Lens flare color tint")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
DataElement(AZ::Edit::UIHandlers::Color, &LensFlareConfiguration::m_tintAlpha, "Tint [alpha]", "Lens flare alpha tint")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
Attribute(AZ::Edit::Attributes::Min, 0)->
Attribute(AZ::Edit::Attributes::Max, 255)->
Attribute(AZ::Edit::Attributes::Step, 1)->
DataElement(0, &LensFlareConfiguration::m_brightness, "Brightness", "Lens flare brightness")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
Attribute(AZ::Edit::Attributes::Min, 0.f)->
Attribute(AZ::Edit::Attributes::Step, 0.1f)->
Attribute(AZ::Edit::Attributes::Suffix, "x")->
ClassElement(AZ::Edit::ClassElements::Group, "Animation")->
DataElement(0, &LensFlareConfiguration::m_syncAnimWithLight, "Sync with light", "When checked uses the animation settings of a provided light")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::SyncAnimationChanged)->
DataElement(0, &LensFlareConfiguration::m_lightEntity, "Light", "Entity that has a light component to sync with")->
Attribute(AZ::Edit::Attributes::Visibility, &LensFlareConfiguration::m_syncAnimWithLight)->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
DataElement(0, &LensFlareConfiguration::m_animIndex, "Style", "Light animation curve ID (\"style\") as it corresponds to values in Light.cfx")->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
Attribute(AZ::Edit::Attributes::Max, 255)->
Attribute(AZ::Edit::Attributes::Visibility, &LensFlareConfiguration::ShouldShowAnimationSettings)->
DataElement(0, &LensFlareConfiguration::m_animSpeed, "Speed", "Multiple of the base animation rate")->
Attribute(AZ::Edit::Attributes::Visibility, &LensFlareConfiguration::ShouldShowAnimationSettings)->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
Attribute(AZ::Edit::Attributes::Min, 0.f)->
Attribute(AZ::Edit::Attributes::Step, 0.1f)->
Attribute(AZ::Edit::Attributes::Max, 4.f)->
Attribute(AZ::Edit::Attributes::Suffix, "x")->
DataElement(0, &LensFlareConfiguration::m_animPhase, "Phase", "Animation start offset from 0 to 1. 0.1 would be 10% into the animation")->
Attribute(AZ::Edit::Attributes::Visibility, &LensFlareConfiguration::ShouldShowAnimationSettings)->
Attribute(AZ::Edit::Attributes::ChangeNotify, &LensFlareConfiguration::PropertyChanged)->
Attribute(AZ::Edit::Attributes::Min, 0.f)->
Attribute(AZ::Edit::Attributes::Step, 0.1f)->
Attribute(AZ::Edit::Attributes::Max, 1.f)
;
}
}
}
AZ::u32 EditorLensFlareConfiguration::PropertyChanged()
{
if (m_editorEntityId.IsValid())
{
if (m_syncAnimWithLight && m_lightEntity.IsValid())
{
//Get the config of the light we want to sync with
LmbrCentral::LightConfiguration lightConfig;
EBUS_EVENT_ID_RESULT(lightConfig, m_lightEntity, EditorLightComponentRequestBus, GetConfiguration);
m_syncAnimIndex = lightConfig.m_animIndex;
m_syncAnimSpeed = lightConfig.m_animSpeed;
m_syncAnimPhase = lightConfig.m_animPhase;
}
EBUS_EVENT_ID(m_editorEntityId, EditorLensFlareComponentRequestBus, RefreshLensFlare);
}
return AZ::Edit::PropertyRefreshLevels::None;
}
AZ::u32 EditorLensFlareConfiguration::SyncAnimationChanged()
{
if (m_syncAnimWithLight)
{
LightSettingsNotificationsBus::Handler::BusConnect(m_editorEntityId);
}
else
{
LightSettingsNotificationsBus::Handler::BusDisconnect();
}
PropertyChanged();
return AZ_CRC("RefreshEntireTree", 0xefbc823c);
}
AZ::u32 EditorLensFlareConfiguration::AttachToSunChanged()
{
// if attached to the sun , then use VIEW_DISTANCE_MULTIPLIER_MAX value
// else use the value set by user.
if (m_attachToSun)
{
m_viewDistMultiplierUser = m_viewDistMultiplier;
m_viewDistMultiplier = static_cast<float>(IRenderNode::VIEW_DISTANCE_MULTIPLIER_MAX);
}
else
{
// We restore the cache user set value when it is not attached to the sun.
m_viewDistMultiplier = m_viewDistMultiplierUser;
}
PropertyChanged();
return AZ_CRC("RefreshEntireTree", 0xefbc823c);
}
void EditorLensFlareConfiguration::AnimationSettingsChanged()
{
PropertyChanged();
}
void EditorLensFlareComponent::Init()
{
Base::Init();
//Set this in Init because it will never change and doesn't need to be reset if the component re-activates
m_configuration.m_material.SetAssetPath("EngineAssets/Materials/lens_optics");
}
void EditorLensFlareComponent::Activate()
{
Base::Activate();
//Trigger asset loading so the the editor could show right content for the dropdown.
//Don't call OnAssetChanged because we don't need to clear any serialized data
//nor do we need to check for bus connection.
if (m_asset.GetId().IsValid())
{
//load LensFlare asset
AZ::Data::AssetBus::Handler::BusConnect(m_asset.GetId());
m_asset.QueueLoad();
}
m_selectedLensFlareLibrary = GetLibraryNameFromAsset();
m_selectedLensFlareName = GetFlareNameFromPath(m_configuration.m_lensFlare);
const AZ::EntityId entityId = GetEntityId();
m_configuration.m_editorEntityId = entityId;
m_light.SetEntity(entityId);
RefreshLensFlare();
//Check to see if we need to start connected to the LightSettingsNotificationBus
m_configuration.SyncAnimationChanged();
// We call this one in order to cache the user set value.
m_configuration.m_viewDistMultiplierUser = m_configuration.m_viewDistMultiplier;
m_configuration.AttachToSunChanged();
EditorLensFlareComponentRequestBus::Handler::BusConnect(entityId);
RenderNodeRequestBus::Handler::BusConnect(entityId);
AzToolsFramework::EditorVisibilityNotificationBus::Handler::BusConnect(entityId);
AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(entityId);
AzToolsFramework::EditorEvents::Bus::Handler::BusConnect();
}
void EditorLensFlareComponent::Deactivate()
{
//Check to see if we need to disconnect from the LightSettingsNotificationBus
m_configuration.SyncAnimationChanged();
AZ::Data::AssetBus::Handler::BusDisconnect();
EditorLensFlareComponentRequestBus::Handler::BusDisconnect();
RenderNodeRequestBus::Handler::BusDisconnect();
AzToolsFramework::EditorVisibilityNotificationBus::Handler::BusDisconnect();
AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect();
AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect();
m_light.DestroyRenderLight();
m_light.SetEntity(AZ::EntityId());
m_configuration.m_editorEntityId.SetInvalid();
m_selectedLensFlareLibrary.clear();
Base::Deactivate();
}
void EditorLensFlareComponent::OnEntityVisibilityChanged(bool /*visibility*/)
{
RefreshLensFlare();
}
void EditorLensFlareComponent::OnEditorSpecChange()
{
RefreshLensFlare();
}
void EditorLensFlareComponent::RefreshLensFlare()
{
m_light.UpdateRenderLight(GetEditorLensFlareConfiguration());
}
EditorLensFlareConfiguration EditorLensFlareComponent::GetEditorLensFlareConfiguration() const
{
EditorLensFlareConfiguration configuration = m_configuration;
// take the entity's visibility into account
bool visible = false;
AzToolsFramework::EditorEntityInfoRequestBus::EventResult(
visible, GetEntityId(), &AzToolsFramework::EditorEntityInfoRequestBus::Events::IsVisible);
configuration.m_visible = visible && configuration.m_visible;
configuration.m_asset = m_asset;
return configuration;
}
void EditorLensFlareComponent::BuildGameEntity(AZ::Entity* gameEntity)
{
LensFlareComponent* lensFlareComponent = gameEntity->CreateComponent<LensFlareComponent>();
if (lensFlareComponent)
{
lensFlareComponent->m_configuration = m_configuration;
lensFlareComponent->m_configuration.m_asset = m_asset;
}
}
void EditorLensFlareComponent::DisplayEntityViewport(
[[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo,
AzFramework::DebugDisplayRequests& debugDisplay)
{
// Don't draw extra visualization unless selected.
if (!IsSelected())
{
return;
}
AZ::Transform transform = AZ::Transform::CreateIdentity();
EBUS_EVENT_ID_RESULT(transform, GetEntityId(), AZ::TransformBus, GetWorldTM);
debugDisplay.PushMatrix(transform);
{
const AZ::Vector3& color = m_configuration.m_tint;
debugDisplay.SetColor(AZ::Vector4(color.GetX(), color.GetY(), color.GetZ(), 1.f));
debugDisplay.DrawWireSphere(AZ::Vector3::CreateZero(), 1.0f);
}
debugDisplay.PopMatrix();
}
AZ::u32 EditorLensFlareComponent::OnLensFlareSelected()
{
m_configuration.m_lensFlare = GetSelectedLensFlareFullName();
//If the flare we've selected is valid we need to parse a couple of parameters from it to make sure
//that we display the flare as it's seen in the lens flare editor
if (!m_configuration.m_lensFlare.empty())
{
int lensOpticsID = 0;
if (gEnv->pOpticsManager->Load(m_configuration.m_lensFlare.c_str(), lensOpticsID))
{
IOpticsElementBase* flare = gEnv->pOpticsManager->GetOptics(lensOpticsID);
AZStd::vector<FuncVariableGroup> varGroups = flare->GetEditorParamGroups();
for (size_t i = 0; i < varGroups.size(); ++i)
{
if (strcmp(varGroups[i].GetName(), "Common") == 0)
{
IFuncVariable* var = varGroups[i].FindVariable("Size");
if (var)
{
m_configuration.m_size = var->GetFloat();
}
var = varGroups[i].FindVariable("Tint");
if (var)
{
ColorF color = var->GetColorF();
m_configuration.m_tint = AZ::Vector3(color.r, color.g, color.b);
m_configuration.m_tintAlpha = static_cast<AZ::u32>(color.a * 255.0f);
}
var = varGroups[i].FindVariable("Brightness");
if (var)
{
m_configuration.m_brightness = var->GetFloat();
}
}
}
}
}
m_configuration.PropertyChanged(); // Update the render light
return AZ::Edit::PropertyRefreshLevels::AttributesAndValues;
}
void EditorLensFlareComponent::OnVisibleChanged()
{
m_configuration.m_visible = m_visible;
m_configuration.PropertyChanged();
}
void EditorLensFlareComponent::OnAssetReady(AZ::Data::Asset<AZ::Data::AssetData> asset)
{
if (asset.GetId() == m_asset.GetId())
{
// Grab the lens flare list list from the Asset and refresh
const AZStd::vector<AZStd::string>& paths = static_cast<LensFlareAsset*>(asset.Get())->GetPaths();
if (!paths.empty())
{
//Store the name of the library retrieved from the filepath
m_selectedLensFlareLibrary = GetLibraryNameFromAsset();
// No selected lens flare, so automatically select the first one to ensure we see something right away.
if (m_selectedLensFlareName.empty())
{
m_selectedLensFlareName = GetFlareNameFromPath(paths[0]);
OnLensFlareSelected();
}
}
EBUS_EVENT(AzToolsFramework::ToolsApplicationEvents::Bus, InvalidatePropertyDisplay, AzToolsFramework::Refresh_AttributesAndValues);
}
}
AZStd::vector<AZStd::string> EditorLensFlareComponent::GetLensFlarePaths() const
{
if (m_asset.IsReady())
{
AZStd::vector<AZStd::string> paths = m_asset.Get()->GetPaths();
//Remove the library name from the path as it's redundant to display it
for (size_t i = 0; i < paths.size(); i++)
{
paths[i] = GetFlareNameFromPath(paths[i]);
}
return paths;
}
else
{
return AZStd::vector<AZStd::string>();
}
}
IRenderNode* EditorLensFlareComponent::GetRenderNode()
{
return m_light.GetRenderNode();
}
float EditorLensFlareComponent::GetRenderNodeRequestBusOrder() const
{
return LensFlareComponent::s_renderNodeRequestBusOrder;
}
void EditorLensFlareComponent::OnAssetReloaded(AZ::Data::Asset<AZ::Data::AssetData> asset)
{
m_asset = asset;
// Force the optics manager to reload the library. Otherwise, it will keep returning the old version of the lens flare
// each time Load() is called.
int unusedOutIndex = 0;
const bool forceReload = true;
gEnv->pOpticsManager->Load(GetSelectedLensFlareFullName().c_str(), unusedOutIndex, forceReload);
RefreshLensFlare();
}
void EditorLensFlareComponent::OnAssetChanged()
{
m_selectedLensFlareLibrary.clear();
m_selectedLensFlareName.clear(); //Clear this so that when the asset is ready we will always pull a new flare from the new library
if (AZ::Data::AssetBus::Handler::BusIsConnected())
{
AZ::Data::AssetBus::Handler::BusDisconnect();
}
if (m_asset.GetId().IsValid())
{
//load LensFlare asset
AZ::Data::AssetBus::Handler::BusConnect(m_asset.GetId());
m_asset.QueueLoad();
m_asset.BlockUntilLoadComplete();
}
EBUS_EVENT(AzToolsFramework::ToolsApplicationEvents::Bus, InvalidatePropertyDisplay, AzToolsFramework::Refresh_AttributesAndValues);
}
void EditorLensFlareComponent::SetPrimaryAsset(const AZ::Data::AssetId& id)
{
m_asset.Create(id, true);
EBUS_EVENT(AzToolsFramework::ToolsApplicationRequests::Bus, AddDirtyEntity, GetEntityId());
OnAssetChanged();
}
AZStd::string EditorLensFlareComponent::GetFlareNameFromPath(const AZStd::string& path) const
{
//Trim the library name from the beginning of the path to get the flare's name
if (!m_selectedLensFlareLibrary.empty() && m_selectedLensFlareLibrary.size() < path.size())
{
return path.substr(m_selectedLensFlareLibrary.size() + 1);
}
return AZStd::string();
}
AZStd::string EditorLensFlareComponent::GetLibraryNameFromAsset() const
{
AZStd::string filePath;
EBUS_EVENT_RESULT(filePath, AZ::Data::AssetCatalogRequestBus, GetAssetPathById, m_asset.GetId());
if (!filePath.empty())
{
filePath = filePath.substr(filePath.find_last_of('/') + 1);
return filePath.substr(0, filePath.find_last_of('.'));
}
return AZStd::string();
}
AZStd::string EditorLensFlareComponent::GetSelectedLensFlareFullName() const
{
return m_selectedLensFlareLibrary + "." + m_selectedLensFlareName;
}
} // namespace LmbrCentral
@@ -1,167 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzToolsFramework/ToolsComponents/EditorComponentBase.h>
#include <AzToolsFramework/ToolsComponents/EditorVisibilityBus.h>
#include <AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <AzFramework/Entity/EntityDebugDisplayBus.h>
#include <LmbrCentral/Rendering/LensFlareAsset.h>
#include <LmbrCentral/Rendering/LightComponentBus.h>
#include "LensFlareComponent.h"
namespace LmbrCentral
{
/**
* Extends LightConfiguration structure to add editor functionality
* such as property handlers and visibility filters, as well as
* reflection for editing.
*/
class EditorLensFlareConfiguration
: public LensFlareConfiguration
, private LightSettingsNotificationsBus::Handler
{
public:
AZ_TYPE_INFO(EditorLightConfiguration, "{B7E8C0BF-A7B6-4414-90FF-6E21B32E5E16}");
~EditorLensFlareConfiguration() override {}
static void Reflect(AZ::ReflectContext* context);
// Overrides from LensFlareConfiguration
AZ::u32 PropertyChanged() override;
AZ::u32 SyncAnimationChanged() override;
AZ::u32 AttachToSunChanged() override;
// Overrides from LightSettingsNotificationBus
void AnimationSettingsChanged() override;
AZ::EntityId m_editorEntityId; // Not reflected.
};
/*!
* In-editor light component.
* Handles previewing and activating lights in the editor.
*/
class EditorLensFlareComponent
: public AzToolsFramework::Components::EditorComponentBase
, private AzToolsFramework::EditorVisibilityNotificationBus::Handler
, private AzToolsFramework::EditorEvents::Bus::Handler
, private AzFramework::EntityDebugDisplayEventBus::Handler
, private EditorLensFlareComponentRequestBus::Handler
, private RenderNodeRequestBus::Handler
, private AZ::Data::AssetBus::Handler
{
private:
using Base = AzToolsFramework::Components::EditorComponentBase;
public:
AZ_COMPONENT(EditorLensFlareComponent, "{4B85E77D-91F9-40C5-8FCB-B494000A9E69}", AzToolsFramework::Components::EditorComponentBase);
EditorLensFlareComponent() {}
~EditorLensFlareComponent() override {}
//////////////////////////////////////////////////////////////////////////
// AZ::Component interface implementation
void Init() override;
void Activate() override;
void Deactivate() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// AzToolsFramework::EditorVisibilityNotificationBus interface implementation
void OnEntityVisibilityChanged(bool visibility) override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// LensFlareComponentEditorRequestBus::Handler interface implementation
virtual void RefreshLensFlare() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// RenderNodeRequestBus::Handler interface implementation
IRenderNode* GetRenderNode() override;
float GetRenderNodeRequestBusOrder() const override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// AssetEventHandler
void OnAssetReady(AZ::Data::Asset<AZ::Data::AssetData> asset) override;
void OnAssetReloaded(AZ::Data::Asset<AZ::Data::AssetData> asset) override;
//////////////////////////////////////////////////////////////////////////
//! Called when you want to change the game asset through code (like when creating components based on assets).
void BuildGameEntity(AZ::Entity* gameEntity) override;
//! Called when you want to change the game asset through code (like when creating components based on assets).
void SetPrimaryAsset(const AZ::Data::AssetId& assetId) override;
//! Invoked in the editor when the user assigns a new lens flare.
void OnAssetChanged();
//! Invoked in the editor when the user selects a lens flare from the combo box.
AZ::u32 OnLensFlareSelected();
//! Invoked in the editor when the user changes the visibility setting from the check box
void OnVisibleChanged();
//! Used to populate the lens flare combo box.
AZStd::vector<AZStd::string> GetLensFlarePaths() const;
//! Get a copy of configuration appropriate for use with the lens flare
EditorLensFlareConfiguration GetEditorLensFlareConfiguration() const;
//////////////////////////////////////////////////////////////////////////
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
LensFlareComponent::GetProvidedServices(provided);
}
static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent)
{
LensFlareComponent::GetDependentServices(dependent);
dependent.push_back(AZ_CRC("EditorVisibilityService", 0x90888caf));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
LensFlareComponent::GetRequiredServices(required);
}
static void Reflect(AZ::ReflectContext* context);
//////////////////////////////////////////////////////////////////////////
private:
//////////////////////////////////////////////////////////////////////////
// AzToolsFramework::EditorEvents::Bus::Handler interface implementation
void OnEditorSpecChange() override;
//////////////////////////////////////////////////////////////////////////
// AzFramework::EntityDebugDisplayEventBus
void DisplayEntityViewport(
const AzFramework::ViewportInfo& viewportInfo,
AzFramework::DebugDisplayRequests& debugDisplay) override;
AZStd::string GetSelectedLensFlareFullName() const;
AZStd::string GetFlareNameFromPath(const AZStd::string& path) const;
AZStd::string GetLibraryNameFromAsset() const;
EditorLensFlareConfiguration m_configuration;
LightInstance m_light;
AZStd::string m_selectedLensFlareName;
AZStd::string m_selectedLensFlareLibrary;
AZ::Data::Asset<LensFlareAsset> m_asset;
bool m_visible = true;
};
} // namespace LmbrCentral
File diff suppressed because it is too large Load Diff
@@ -1,408 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/Component.h>
#include <AzCore/Component/ComponentBus.h>
#include <AzCore/Component/ComponentExport.h>
#include <AzToolsFramework/ToolsComponents/EditorComponentBase.h>
#include <AzToolsFramework/ToolsComponents/EditorVisibilityBus.h>
#include <AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <AzFramework/Entity/EntityDebugDisplayBus.h>
#include <AzFramework/Asset/AssetCatalogBus.h>
#include <LmbrCentral/Rendering/EditorLightComponentBus.h>
#include <LmbrCentral/Rendering/EditorCameraCorrectionBus.h>
#include "LightComponent.h"
#include <IStatObj.h>
namespace LmbrCentral
{
class EditorLightComponent;
/**
* Extends LightConfiguration structure to add editor functionality
* such as property handlers and visibility filters, as well as
* reflection for editing.
*/
class EditorLightConfiguration
: public LightConfiguration
{
public:
AZ_TYPE_INFO(EditorLightConfiguration, "{1D3B114F-8FB2-47BD-9C21-E089F4F37861}");
~EditorLightConfiguration() override {}
static void Reflect(AZ::ReflectContext* context);
AZ::Crc32 GetAmbientLightVisibility() const override;
AZ::Crc32 GetPointLightVisibility() const override;
AZ::Crc32 GetProjectorLightVisibility() const override;
AZ::Crc32 GetProbeLightVisibility() const override;
AZ::Crc32 GetShadowSpecVisibility() const override;
AZ::Crc32 GetShadowSettingsVisibility() const override;
AZ::Crc32 GetAreaSettingVisibility() const override;
AZ::Crc32 MinorPropertyChanged() override;
AZ::Crc32 MajorPropertyChanged() override;
AZ::Crc32 OnAnimationSettingChanged() override;
AZ::Crc32 OnCubemapAssetChanged() override;
bool CanGenerateCubemap() const override;
void SetComponent(EditorLightComponent* component);
EditorLightComponent* m_component;
};
/*!
* In-editor light component.
* Handles previewing and activating lights in the editor.
*/
class EditorLightComponent
: public AzToolsFramework::Components::EditorComponentBase
, private AzToolsFramework::EditorVisibilityNotificationBus::Handler
, private AzToolsFramework::EditorEvents::Bus::Handler
, private AzFramework::EntityDebugDisplayEventBus::Handler
, private EditorLightComponentRequestBus::Handler
, private RenderNodeRequestBus::Handler
, private AzFramework::AssetCatalogEventBus::Handler
, private AZ::TransformNotificationBus::Handler
, private EditorCameraCorrectionRequestBus::Handler
{
private:
using Base = AzToolsFramework::Components::EditorComponentBase;
public:
friend EditorLightConfiguration;
//old guid "{33BB1CD4-6A33-46AA-87ED-8BBB40D94B0D}" before splitting editor light component
AZ_COMPONENT(EditorLightComponent, "{7C18B273-5BA3-4E0F-857D-1F30BD6B0733}", AzToolsFramework::Components::EditorComponentBase);
EditorLightComponent();
~EditorLightComponent() override;
//////////////////////////////////////////////////////////////////////////
// AZ::Component interface implementation
void Init() override;
void Activate() override;
void Deactivate() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// AzToolsFramework::EditorVisibilityNotificationBus interface implementation
void OnEntityVisibilityChanged(bool visibility) override;
//////////////////////////////////////////////////////////////////////////
// AzFramework::EntityDebugDisplayEventBus
void DisplayEntityViewport(
const AzFramework::ViewportInfo& viewportInfo,
AzFramework::DebugDisplayRequests& debugDisplay) override;
//////////////////////////////////////////////////////////////////////////
// EditorLightComponentRequestBus::Handler interface implementation
void SetCubemap(const AZStd::string& cubemap) override;
void SetProjectorTexture(const AZStd::string& projectorTexture) override;
AZ::u32 GetCubemapResolution() override;
void SetCubemapResolution(AZ::u32 resolution) override;
bool UseCustomizedCubemap() const override;
void RefreshLight() override;
const LightConfiguration& GetConfiguration() const override;
AZ::Crc32 OnCubemapAssetChanged();
AZ::Crc32 OnCustomizedCubemapChanged();
// EditorCameraCorrectionRequestBus interface implementation
// Light is aligned along the the x-axis so add a transform correction to align along the y-axis.
AZ::Matrix3x3 GetTransformCorrection() override { return AZ::Matrix3x3::CreateRotationZ(-AZ::Constants::HalfPi); }
///////////////////////////////////////////
// EditorLightComponentRequestBus Modifiers
void SetVisible(bool isVisible) override;
bool GetVisible() override;
void SetOnInitially(bool onInitially) override;
bool GetOnInitially() override;
void SetColor(const AZ::Color& newColor) override;
const AZ::Color GetColor() override;
void SetDiffuseMultiplier(float newMultiplier) override;
float GetDiffuseMultiplier() override;
void SetSpecularMultiplier(float newMultiplier) override;
float GetSpecularMultiplier() override;
void SetAmbient(bool isAmbient) override;
bool GetAmbient() override;
void SetPointMaxDistance(float newMaxDistance) override;
float GetPointMaxDistance() override;
void SetPointAttenuationBulbSize(float newAttenuationBulbSize) override;
float GetPointAttenuationBulbSize() override;
void SetAreaMaxDistance(float newMaxDistance) override;
float GetAreaMaxDistance() override;
void SetAreaWidth(float newWidth) override;
float GetAreaWidth() override;
void SetAreaHeight(float newHeight) override;
float GetAreaHeight() override;
void SetAreaFOV(float newFOV) override;
float GetAreaFOV() override;
void SetProjectorMaxDistance(float newMaxDistance) override;
float GetProjectorMaxDistance() override;
void SetProjectorAttenuationBulbSize(float newAttenuationBulbSize) override;
float GetProjectorAttenuationBulbSize() override;
void SetProjectorFOV(float newFOV) override;
float GetProjectorFOV() override;
void SetProjectorNearPlane(float newNearPlane) override;
float GetProjectorNearPlane() override;
// Environment Probe Settings
void SetProbeAreaDimensions(const AZ::Vector3& newDimensions) override;
const AZ::Vector3 GetProbeAreaDimensions() override;
void SetProbeSortPriority(AZ::u32 newPriority) override;
AZ::u32 GetProbeSortPriority() override;
void SetProbeBoxProjected(bool isProbeBoxProjected) override;
bool GetProbeBoxProjected() override;
void SetProbeBoxHeight(float newHeight) override;
float GetProbeBoxHeight() override;
void SetProbeBoxLength(float newLength) override;
float GetProbeBoxLength() override;
void SetProbeBoxWidth(float newWidth) override;
float GetProbeBoxWidth() override;
void SetProbeAttenuationFalloff(float newAttenuationFalloff) override;
float GetProbeAttenuationFalloff() override;
void SetProbeFade(float fade) override;
float GetProbeFade() override;
void SetIndoorOnly(bool indoorOnly) override;
bool GetIndoorOnly() override;
void SetCastShadowSpec(AZ::u32 castShadowSpec) override;
AZ::u32 GetCastShadowSpec() override;
void SetViewDistanceMultiplier(float viewDistanceMultiplier) override;
float GetViewDistanceMultiplier() override;
void SetProbeArea(const AZ::Vector3& probeArea) override;
AZ::Vector3 GetProbeArea() override;
void SetVolumetricFogOnly(bool volumetricFogOnly) override;
bool GetVolumetricFogOnly() override;
void SetVolumetricFog(bool volumetricFog) override;
bool GetVolumetricFog() override;
void SetAttenuationFalloffMax(float attenFalloffMax);
float GetAttenuationFalloffMax();
void SetUseVisAreas(bool useVisAreas) override;
bool GetUseVisAreas() override;
void SetAffectsThisAreaOnly(bool affectsThisAreaOnly) override;
bool GetAffectsThisAreaOnly() override;
void SetBoxHeight(float boxHeight) override;
float GetBoxHeight() override;
void SetBoxWidth(float boxWidth) override;
float GetBoxWidth() override;
void SetBoxLength(float boxLength) override;
float GetBoxLength() override;
void SetBoxProjected(bool boxProjected) override;
bool GetBoxProjected() override;
void SetShadowBias(float shadowBias) override;
float GetShadowBias() override;
void SetShadowSlopeBias(float shadowSlopeBias) override;
float GetShadowSlopeBias() override;
void SetShadowResScale(float shadowResScale) override;
float GetShadowResScale() override;
void SetShadowUpdateMinRadius(float shadowUpdateMinRadius) override;
float GetShadowUpdateMinRadius() override;
void SetShadowUpdateRatio(float shadowUpdateRatio) override;
float GetShadowUpdateRatio() override;
//////////////////////////////////////////////////////////////////////////
// Animation parameters
void SetAnimIndex(AZ::u32 animIndex) override;
AZ::u32 GetAnimIndex() override;
void SetAnimSpeed(float animSpeed) override;
float GetAnimSpeed() override;
void SetAnimPhase(float animPhase) override;
float GetAnimPhase() override;
//////////////////////////////////////////////////////////////////////////
// RenderNodeRequestBus::Handler interface implementation
IRenderNode* GetRenderNode() override;
float GetRenderNodeRequestBusOrder() const override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// TransformNotificationBus::Handler interface implementation
void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override;
//////////////////////////////////////////////////////////////////////////
void BuildGameEntity(AZ::Entity* gameEntity) override;
//////////////////////////////////////////////////////////////////////////
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
LightComponent::GetProvidedServices(provided);
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
LightComponent::GetRequiredServices(required);
}
static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent)
{
LightComponent::GetDependentServices(dependent);
dependent.push_back(AZ_CRC("EditorVisibilityService", 0x90888caf));
}
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
LightComponent::GetIncompatibleServices(incompatible);
}
static AZ::ExportedComponent ExportLightComponent(AZ::Component* thisComponent, const AZ::PlatformTagSet& /*platformTags*/);
static void Reflect(AZ::ReflectContext* context);
//////////////////////////////////////////////////////////////////////////
protected:
void SetLightType(EditorLightConfiguration::LightType lightType)
{
m_configuration.m_lightType = lightType;
}
AZ::Uuid GetCubemapId()
{
return m_configuration.m_cubemapId;
}
virtual const char* GetLightTypeText() const;
private:
static bool VersionConverter(AZ::SerializeContext& context,
AZ::SerializeContext::DataElementNode& classElement);
//! Handles rendering of the preview cubemap by creating a simple cubemapped sphere.
class CubemapPreview : public IRenderNode
{
public:
CubemapPreview();
void Setup(const char* textureName);
void UpdateTexture(const char* textureName);
void SetTransform(const Matrix34& transform);
private:
//////////////////////////////////////////////////////////////////////////
// IRenderNode interface implementation
void Render(const struct SRendParams& inRenderParams, const struct SRenderingPassInfo& passInfo) override;
EERType GetRenderNodeType() override;
const char* GetName() const override;
const char* GetEntityClassName() const override;
Vec3 GetPos(bool bWorldOnly = true) const override;
const AABB GetBBox() const override;
void SetBBox([[maybe_unused]] const AABB& WSBBox) override {}
void OffsetPosition([[maybe_unused]] const Vec3& delta) override {}
void SetMaterial(_smart_ptr<IMaterial> pMat) override {}
_smart_ptr<IMaterial> GetMaterial(Vec3* pHitPos = nullptr) override;
_smart_ptr<IMaterial> GetMaterialOverride() override;
IStatObj* GetEntityStatObj(unsigned int nPartId = 0, unsigned int nSubPartId = 0, Matrix34A* pMatrix = nullptr, bool bReturnOnlyVisible = false);
float GetMaxViewDist() override;
void GetMemoryUsage(class ICrySizer* pSizer) const override;
//////////////////////////////////////////////////////////////////////////
private:
Matrix34 m_renderTransform;
_smart_ptr<IStatObj> m_statObj;
};
//if an cubemap asset is added or changed
void OnCatalogAssetAdded(const AZ::Data::AssetId& assetId) override;
void OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) override;
void OnEditorSpecChange() override;
//! Returns whether the light is an environment probe
bool IsProbe() const;
//! Returns whether the light has a cubemap assigned
bool HasCubemap() const;
//! Triggers regeneration of the environment probe's cubemap (the current cubemap output will be baked into the new cubemap as well).
void GenerateCubemap();
//! Removes the associated cubemap, returning the environment probe to its default state
void ClearCubemap();
void OnViewCubemapChanged();
//! Returns true if it's an environment probe and not using customized cubemap
bool CanGenerateCubemap() const;
//! Returns the name to use for the Generate Cubemap button.
const char* GetGenerateCubemapButtonName() const;
const char* GetCubemapAssetName() const;
void DrawProjectionGizmo(AzFramework::DebugDisplayRequests& dc, const float radius) const;
void DrawPlaneGizmo(AzFramework::DebugDisplayRequests& dc, const float depth) const;
EditorLightConfiguration m_configuration;
bool m_viewCubemap;
bool m_useCustomizedCubemap;
bool m_cubemapRegen;
bool m_cubemapClear;
CubemapPreview m_cubemapPreview;
LightInstance m_light;
//Statics that can be used by every light
static IEditor* m_editor;
static IMaterialManager* m_materialManager;
static const char* BUTTON_GENERATE;
static const char* BUTTON_ADDBOUNCE;
};
} // namespace LmbrCentral
@@ -1,62 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include "EditorPointLightComponent.h"
namespace LmbrCentral
{
void EditorPointLightComponent::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<EditorPointLightComponent, EditorLightComponent>()->
Version(1);
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<EditorPointLightComponent>(
"Point Light", "The Point Light component allows an entity to create a point of light")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "Rendering")
->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/PointLight.svg")
->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/PointLight.png")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c))
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-point-light.html")
->Attribute(AZ::Edit::Attributes::ExportIfAllPlatformTags, AZStd::vector<AZ::Crc32>{AZ_CRC("renderer", 0xf199a19c)}) // Only export on platforms that render
->Attribute(AZ::Edit::Attributes::RuntimeExportCallback, &EditorLightComponent::ExportLightComponent)
;
}
}
AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
if (behaviorContext)
{
behaviorContext->Class<EditorPointLightComponent>()->RequestBus("EditorPointLightComponentBus");
}
}
void EditorPointLightComponent::Init()
{
SetLightType(EditorLightConfiguration::LightType::Point);
EditorLightComponent::Init();
}
} // namespace LmbrCentral
@@ -1,39 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include "EditorLightComponent.h"
namespace LmbrCentral
{
/*!
* In-editor point light component.
* Handles previewing and activating lights in the editor.
*/
class EditorPointLightComponent
: public EditorLightComponent
{
public:
AZ_COMPONENT(EditorPointLightComponent, "{00818135-138D-42AD-8657-FF3FD38D9E7A}", AzToolsFramework::Components::EditorComponentBase);
static void Reflect(AZ::ReflectContext* context);
void Init() override;
protected:
const char* GetLightTypeText() const override
{
return "Point Light";
}
};
} // namespace LmbrCentral
@@ -1,64 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include "EditorProjectorLightComponent.h"
namespace LmbrCentral
{
void EditorProjectorLightComponent::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<EditorProjectorLightComponent, EditorLightComponent>()->
Version(1);
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<EditorProjectorLightComponent>(
"Projector Light", "The Projector Light component allows an entity to project a light")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "Rendering")
->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/ProjectorLight.svg")
->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/ProjectorLight.png")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c))
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-projector-light.html")
->Attribute(AZ::Edit::Attributes::ExportIfAllPlatformTags, AZStd::vector<AZ::Crc32>{AZ_CRC("renderer", 0xf199a19c)}) // Only export on platforms that render
->Attribute(AZ::Edit::Attributes::RuntimeExportCallback, &EditorLightComponent::ExportLightComponent)
;
}
}
AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
if (behaviorContext)
{
behaviorContext->Class<EditorProjectorLightComponent>()->RequestBus("EditorProjectorLightComponentBus");
}
}
void EditorProjectorLightComponent::Init()
{
SetLightType(EditorLightConfiguration::LightType::Projector);
EditorLightComponent::Init();
}
} // namespace LmbrCentral
@@ -1,39 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include "EditorLightComponent.h"
namespace LmbrCentral
{
/*!
* In-editor point light component.
* Handles previewing and activating lights in the editor.
*/
class EditorProjectorLightComponent
: public EditorLightComponent
{
public:
AZ_COMPONENT(EditorProjectorLightComponent, "{41928E34-B558-4559-82CF-8B5795A38CB4}", EditorLightComponent);
static void Reflect(AZ::ReflectContext* context);
void Init() override;
protected:
const char* GetLightTypeText() const override
{
return "Projector Light";
}
};
} // namespace LmbrCentral
@@ -1,817 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include "GeomCacheComponent.h"
#include <AzCore/RTTI/BehaviorContext.h>
#include <AzCore/Asset/AssetManagerBus.h>
#include "MathConversion.h"
#include <LmbrCentral/Rendering/MeshComponentBus.h>
namespace LmbrCentral
{
//BehaviorContext GeometryCacheComponentNotificationBus Forwarder
class BehaviorGeometryCacheComponentNotificationBusHandler
: public GeometryCacheComponentNotificationBus::Handler
, public AZ::BehaviorEBusHandler
{
public:
AZ_EBUS_BEHAVIOR_BINDER(BehaviorGeometryCacheComponentNotificationBusHandler, "{8E0B4617-DD82-47D8-AA2F-3DF3E6677B4B}", AZ::SystemAllocator,
OnPlaybackStart,
OnPlaybackPause,
OnPlaybackStop,
OnStandinChanged);
void OnPlaybackStart() override
{
Call(FN_OnPlaybackStart);
}
void OnPlaybackPause() override
{
Call(FN_OnPlaybackPause);
}
void OnPlaybackStop() override
{
Call(FN_OnPlaybackStop);
}
void OnStandinChanged(StandinType standinType) override
{
Call(FN_OnStandinChanged, standinType);
}
};
void GeometryCacheCommon::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<GeometryCacheCommon>()
->Version(1)
->Field("Visible", &GeometryCacheCommon::m_visible)
->Field("MinSpec", &GeometryCacheCommon::m_minSpec)
->Field("GeomCacheAsset", &GeometryCacheCommon::m_geomCacheAsset)
->Field("MaterialOverrideAsset", &GeometryCacheCommon::m_materialOverrideAsset)
->Field("Loop", &GeometryCacheCommon::m_loop)
->Field("PlayOnStart", &GeometryCacheCommon::m_playOnStart)
->Field("StartTime", &GeometryCacheCommon::m_startTime)
->Field("StreamInDistance", &GeometryCacheCommon::m_streamInDistance)
->Field("FirstFrameStandin", &GeometryCacheCommon::m_firstFrameStandin)
->Field("LastFrameStandin", &GeometryCacheCommon::m_lastFrameStandin)
->Field("Standin", &GeometryCacheCommon::m_standin)
->Field("StandinDistance", &GeometryCacheCommon::m_standinDistance)
->Field("MaxViewDistance", &GeometryCacheCommon::m_maxViewDistance)
->Field("ViewDistanceMultiplier", &GeometryCacheCommon::m_viewDistanceMultiplier)
->Field("LODDistanceRatio", &GeometryCacheCommon::m_lodDistanceRatio)
->Field("CastShadows", &GeometryCacheCommon::m_castShadows)
->Field("UseVisArea", &GeometryCacheCommon::m_useVisAreas)
;
}
if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
{
behaviorContext->EBus<GeometryCacheComponentRequestBus>("GeometryCacheComponentRequestBus")
->Event("Play", &GeometryCacheComponentRequestBus::Events::Play)
->Event("Pause", &GeometryCacheComponentRequestBus::Events::Pause)
->Event("Stop", &GeometryCacheComponentRequestBus::Events::Stop)
->Event("GetTimeRemaining", &GeometryCacheComponentRequestBus::Events::GetTimeRemaining)
->Event("SetVisible", &GeometryCacheComponentRequestBus::Events::SetVisible)
->Event("GetVisible", &GeometryCacheComponentRequestBus::Events::GetVisible)
->VirtualProperty("Visible", "GetVisible", "SetVisible")
->Event("SetLoop", &GeometryCacheComponentRequestBus::Events::SetLoop)
->Event("GetLoop", &GeometryCacheComponentRequestBus::Events::GetLoop)
->VirtualProperty("Loop", "GetLoop", "SetLoop")
->Event("SetStartTime", &GeometryCacheComponentRequestBus::Events::SetStartTime)
->Event("GetStartTime", &GeometryCacheComponentRequestBus::Events::GetStartTime)
->VirtualProperty("StartTime", "GetStartTime", "SetStartTime")
->Event("SetFirstFrameStandIn", &GeometryCacheComponentRequestBus::Events::SetFirstFrameStandIn)
->Event("GetFirstFrameStandIn", &GeometryCacheComponentRequestBus::Events::GetFirstFrameStandIn)
->VirtualProperty("FirstFrameStandIn", "GetFirstFrameStandIn", "SetFirstFrameStandIn")
->Event("SetLastFrameStandIn", &GeometryCacheComponentRequestBus::Events::SetLastFrameStandIn)
->Event("GetLastFrameStandIn", &GeometryCacheComponentRequestBus::Events::GetLastFrameStandIn)
->VirtualProperty("LastFrameStandIn", "GetLastFrameStandIn", "SetLastFrameStandIn")
->Event("SetStandIn", &GeometryCacheComponentRequestBus::Events::SetStandIn)
->Event("GetStandIn", &GeometryCacheComponentRequestBus::Events::GetStandIn)
->VirtualProperty("StandIn", "GetStandIn", "SetStandIn")
->Event("SetStandInDistance", &GeometryCacheComponentRequestBus::Events::SetStandInDistance)
->Event("GetStandInDistance", &GeometryCacheComponentRequestBus::Events::GetStandInDistance)
->VirtualProperty("StandInDistance", "GetStandInDistance", "SetStandInDistance")
->Event("SetStreamInDistance", &GeometryCacheComponentRequestBus::Events::SetStreamInDistance)
->Event("GetStreamInDistance", &GeometryCacheComponentRequestBus::Events::GetStreamInDistance)
->VirtualProperty("StreamInDistance", "GetStreamInDistance", "SetStreamInDistance")
;
behaviorContext->EBus<GeometryCacheComponentNotificationBus>("GeometryCacheComponentNotificationBus")
->Handler<BehaviorGeometryCacheComponentNotificationBusHandler>()
;
behaviorContext->Class<GeometryCacheComponent>()
->RequestBus("GeometryCacheComponentRequestBus")
->NotificationBus("GeometryCacheComponentNotificationBus")
;
}
}
GeometryCacheCommon::~GeometryCacheCommon()
{
if (m_geomCacheRenderNode)
{
delete m_geomCacheRenderNode;
m_geomCacheRenderNode = nullptr;
}
}
void GeometryCacheCommon::Init(const AZ::EntityId& entityId)
{
m_entityId = entityId;
if (gEnv && gEnv->p3DEngine && !m_geomCacheRenderNode)
{
m_geomCacheRenderNode = static_cast<IGeomCacheRenderNode*>(gEnv->p3DEngine->CreateRenderNode(eERType_GeomCache));
}
}
void GeometryCacheCommon::Activate()
{
m_isRegisteredWithRenderer = false;
m_currentTime = m_startTime; //We default to m_startTime here instead of 0.0 so that animations actually start at m_startTime
//If there is no set asset use the defaultgeomcache asset that is expected to exist in EngineAssets
if (!m_geomCacheAsset.GetId().IsValid())
{
AZ::Data::AssetId defaultGeomCacheAssetId;
const char* defaultGeomCacheAssetName = "engineassets/geomcaches/defaultgeomcache.cax";
AZ::Data::AssetCatalogRequestBus::BroadcastResult(defaultGeomCacheAssetId, &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, defaultGeomCacheAssetName, AZ::Data::s_invalidAssetType, false);
if (defaultGeomCacheAssetId.IsValid())
{
m_geomCacheAsset.Create(defaultGeomCacheAssetId);
}
else
{
AZ_Warning("GeometryCache", false, "Default Geometry Cache was not found");
}
}
CreateGeomCache();
//Hide all referenced entities by default
//If a standin *should* be shown that will be determined on the first tick
HideAllStandins();
m_currentStandinType = StandinType::None;
ShowCurrentStandin();
GeometryCacheComponentRequestBus::Handler::BusConnect(m_entityId);
AZ::TransformNotificationBus::Handler::BusConnect(m_entityId);
AZ::TickBus::Handler::BusConnect();
MaterialOwnerRequestBus::Handler::BusConnect(m_entityId);
//Get initial transform and update the render node with it
AZ::Transform world = AZ::Transform::CreateIdentity();
AZ::TransformBus::EventResult(world, m_entityId, &AZ::TransformBus::Events::GetWorldTM);
OnTransformChanged(AZ::Transform::CreateIdentity(), world);
m_playing = false;
if (m_playOnStart)
{
Play();
}
}
void GeometryCacheCommon::Deactivate()
{
HideAllStandins();
GeometryCacheComponentRequestBus::Handler::BusDisconnect(m_entityId);
AZ::TransformNotificationBus::Handler::BusDisconnect(m_entityId);
AZ::TickBus::Handler::BusDisconnect();
MaterialOwnerRequestBus::Handler::BusDisconnect(m_entityId);
DestroyGeomCache();
}
void GeometryCacheCommon::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world)
{
m_currentWorldPos = world.GetTranslation();
if (m_geomCacheRenderNode)
{
Matrix34 cryMat = AZTransformToLYTransform(world);
m_geomCacheRenderNode->SetMatrix(cryMat);
//Re-register to update position
RegisterRenderNode();
}
}
void GeometryCacheCommon::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
{
if (m_geomCacheRenderNode && m_playing)
{
float playbackTime = m_currentTime;
m_currentTime += deltaTime;
playbackTime = m_currentTime;
m_geomCacheRenderNode->SetPlaybackTime(playbackTime);
}
//Don't care about handling stand-in visibility if the whole
//GeomCache shouldn't be visible
if (m_hidden)
{
return;
}
bool standinInUse = false;
//Distance based stand-in
//This has the highest priority
const Vec3 cameraPos = gEnv->p3DEngine->GetRenderingCamera().GetPosition();
float distance = (LYVec3ToAZVec3(cameraPos) - m_currentWorldPos).GetLength();
if (distance > m_standinDistance)
{
standinInUse = true;
if (m_standin.IsValid() && m_currentStandinType != StandinType::Distance)
{
HideCurrentStandin();
m_currentStandinType = StandinType::Distance;
ShowCurrentStandin();
}
}
else
{
//Stand-in for first frame
if (m_currentTime == m_startTime)
{
standinInUse = true;
if (m_firstFrameStandin.IsValid() && m_currentStandinType != StandinType::FirstFrame)
{
HideCurrentStandin();
m_currentStandinType = StandinType::FirstFrame;
ShowCurrentStandin();
}
}
//Stand-in for last frame
else if (!m_loop && m_geomCache && m_currentTime >= m_geomCache->GetDuration())
{
standinInUse = true;
if (m_lastFrameStandin.IsValid() && m_currentStandinType != StandinType::LastFrame)
{
HideCurrentStandin();
m_currentStandinType = StandinType::LastFrame;
ShowCurrentStandin();
}
}
}
//If none of the other stand-ins are being rendered, remove any existing ones
//and go back to just rendering the geom cache
if (!standinInUse && m_currentStandinType != StandinType::None)
{
HideCurrentStandin();
m_currentStandinType = StandinType::None;
ShowCurrentStandin();
}
}
void GeometryCacheCommon::OnAssetReady(AZ::Data::Asset<AZ::Data::AssetData> asset)
{
if (asset == m_geomCacheAsset)
{
m_geomCacheAsset = asset;
m_geomCache = m_geomCacheAsset.Get()->m_geomCache;
if (m_geomCache != nullptr)
{
m_geomCacheRenderNode->SetGeomCache(m_geomCache);
//Allow this geom cache to clean up after we've properly set it on the render node
m_geomCache->SetProcessedByRenderNode(true);
if (m_materialOverride)
{
m_geomCacheRenderNode->SetMaterial(m_materialOverride);
}
if (gEnv && gEnv->p3DEngine)
{
gEnv->p3DEngine->RegisterEntity(m_geomCacheRenderNode);
m_isRegisteredWithRenderer = true;
}
//Apply latest transform to the render node
AZ::Transform world = AZ::Transform::CreateIdentity();
AZ::TransformBus::EventResult(world, m_entityId, &AZ::TransformBus::Events::GetWorldTM);
OnTransformChanged(AZ::Transform::CreateIdentity(), world);
}
}
}
void GeometryCacheCommon::OnAssetReloaded(AZ::Data::Asset<AZ::Data::AssetData> asset)
{
if (asset == m_geomCacheAsset)
{
// We need to make sure m_geomCacheAsset is assigned with the new asset.
// Since the new asset passed in has zero refCount. The assigning will clear the refCount of the old m_geomCacheAsset
// and set the refCount of the new asset to 1, otherwise it will be unloaded.
m_geomCacheAsset = asset;
m_geomCache = m_geomCacheAsset.Get()->m_geomCache;
}
}
void GeometryCacheCommon::SetMaterial(_smart_ptr<IMaterial> material)
{
m_materialOverride = material;
if (material)
{
m_materialOverrideAsset.SetAssetPath(material->GetName());
}
else
{
m_materialOverrideAsset.SetAssetPath("");
}
DestroyGeomCache();
CreateGeomCache();
}
_smart_ptr<IMaterial> GeometryCacheCommon::GetMaterial()
{
if (m_materialOverride)
{
return m_materialOverride;
}
if (m_geomCache == nullptr)
{
return nullptr;
}
return m_geomCache->GetMaterial();
}
void GeometryCacheCommon::Play()
{
if (!m_playing)
{
m_playing = true;
GeometryCacheComponentNotificationBus::Broadcast(&GeometryCacheComponentNotificationBus::Events::OnPlaybackStart);
}
}
void GeometryCacheCommon::Pause()
{
if (m_playing)
{
m_playing = false;
GeometryCacheComponentNotificationBus::Broadcast(&GeometryCacheComponentNotificationBus::Events::OnPlaybackPause);
}
}
void GeometryCacheCommon::Stop()
{
if (m_playing)
{
m_playing = false;
m_currentTime = 0;
if (m_geomCacheRenderNode)
{
m_geomCacheRenderNode->StopStreaming();
}
GeometryCacheComponentNotificationBus::Broadcast(&GeometryCacheComponentNotificationBus::Events::OnPlaybackStop);
}
}
float GeometryCacheCommon::GetTimeRemaining()
{
if (m_playing)
{
return m_geomCache->GetDuration() - m_currentTime;
}
else
{
return -1.0f;
}
}
void GeometryCacheCommon::SetGeomCacheAsset(const AZ::Data::AssetId& id)
{
DestroyGeomCache();
m_geomCacheAsset.Create(id);
CreateGeomCache();
}
void GeometryCacheCommon::SetVisible(bool visible)
{
m_visible = visible;
OnRenderOptionsChanged();
}
void GeometryCacheCommon::SetLoop(bool loop)
{
m_loop = loop;
OnLoopChanged();
}
void GeometryCacheCommon::SetStartTime(float startTime)
{
m_startTime = startTime;
OnStartTimeChanged();
}
void GeometryCacheCommon::SetFirstFrameStandIn(AZ::EntityId entityId)
{
if (!entityId.IsValid())
{
return;
}
if (m_currentStandinType == StandinType::FirstFrame)
{
HideCurrentStandin();
}
m_firstFrameStandin = entityId;
if (m_currentStandinType == StandinType::FirstFrame)
{
ShowCurrentStandin();
}
}
void GeometryCacheCommon::SetLastFrameStandIn(AZ::EntityId entityId)
{
if (!entityId.IsValid())
{
return;
}
if (m_currentStandinType == StandinType::LastFrame)
{
HideCurrentStandin();
}
m_lastFrameStandin = entityId;
if (m_currentStandinType == StandinType::LastFrame)
{
ShowCurrentStandin();
}
}
void GeometryCacheCommon::SetStandIn(AZ::EntityId entityId)
{
if (!entityId.IsValid())
{
return;
}
if (m_currentStandinType == StandinType::Distance)
{
HideCurrentStandin();
}
m_standin = entityId;
if (m_currentStandinType == StandinType::Distance)
{
ShowCurrentStandin();
}
}
void GeometryCacheCommon::SetStandInDistance(float standInDistance)
{
m_standinDistance = standInDistance;
}
void GeometryCacheCommon::SetStreamInDistance(float streamInDistance)
{
m_streamInDistance = streamInDistance;
OnStreamInDistanceChanged();
}
void GeometryCacheCommon::OnRenderOptionsChanged()
{
AZ::u32 rendFlags = 0;
//We want to hide the GeomCache if we're rendering a stand-in
if (m_renderingStandin)
{
rendFlags |= ERF_HIDDEN;
}
//But if the GeomCache is marked as invisible (or the min spec is too high), neither
//the GeomCache or any stand-ins should render
const int configSpec = gEnv->pSystem->GetConfigSpec(true);
m_hidden = !m_visible || (static_cast<AZ::u32>(configSpec) < static_cast<AZ::u32>(m_minSpec));
if (m_hidden)
{
rendFlags |= ERF_HIDDEN;
HideAllStandins();
}
if (!m_useVisAreas)
{
rendFlags |= ERF_OUTDOORONLY;
}
if (m_castShadows)
{
rendFlags |= ERF_HAS_CASTSHADOWMAPS;
rendFlags |= ERF_CASTSHADOWMAPS;
}
rendFlags |= ERF_COMPONENT_ENTITY;
m_geomCacheRenderNode->SetRndFlags(rendFlags);
//Re-register to update flags
RegisterRenderNode();
}
void GeometryCacheCommon::OnGeomCacheAssetChanged()
{
DestroyGeomCache();
CreateGeomCache();
}
void GeometryCacheCommon::OnMaterialOverrideChanged()
{
LoadMaterialOverride();
if (m_materialOverride)
{
m_geomCacheRenderNode->SetMaterial(m_materialOverride);
}
//On Activate this will be false and that's expected.
//However when the asset actually loads, the material should be applied.
//This is just for whenever the material override *changes*
//but not necessarily for material application on startup.
RegisterRenderNode();
}
void GeometryCacheCommon::OnStartTimeChanged()
{
if (m_geomCache)
{
if (m_startTime > m_geomCache->GetDuration())
{
m_startTime = m_geomCache->GetDuration();
}
}
//If the start time has changed, restart the animation
m_currentTime = m_startTime;
}
void GeometryCacheCommon::OnLoopChanged()
{
m_geomCacheRenderNode->SetLooping(m_loop);
}
void GeometryCacheCommon::OnMaxViewDistanceChanged()
{
m_geomCacheRenderNode->SetBaseMaxViewDistance(m_maxViewDistance);
RegisterRenderNode();
}
void GeometryCacheCommon::OnViewDistanceMultiplierChanged()
{
m_geomCacheRenderNode->SetViewDistanceMultiplier(m_viewDistanceMultiplier);
RegisterRenderNode();
}
void GeometryCacheCommon::OnLODDistanceRatioChanged()
{
m_geomCacheRenderNode->SetLodRatio(m_lodDistanceRatio);
RegisterRenderNode();
}
void GeometryCacheCommon::OnStreamInDistanceChanged()
{
m_geomCacheRenderNode->SetStreamInDistance(m_streamInDistance);
}
void GeometryCacheCommon::LoadMaterialOverride()
{
const AZStd::string& materialOverridePath = m_materialOverrideAsset.GetAssetPath();
if (!materialOverridePath.empty())
{
m_materialOverride = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(materialOverridePath.c_str());
AZ_Warning("GeomCacheComponent", m_materialOverride != gEnv->p3DEngine->GetMaterialManager()->GetDefaultMaterial(),
"Failed to load override material \"%s\".",
materialOverridePath.c_str());
}
else
{
m_materialOverride = nullptr;
}
}
void GeometryCacheCommon::RegisterRenderNode()
{
if(m_isRegisteredWithRenderer && gEnv && gEnv->p3DEngine)
{
gEnv->p3DEngine->RegisterEntity(m_geomCacheRenderNode);
}
}
void GeometryCacheCommon::CreateGeomCache()
{
if (gEnv && gEnv->p3DEngine && !m_geomCacheRenderNode)
{
m_geomCacheRenderNode = static_cast<IGeomCacheRenderNode*>(gEnv->p3DEngine->CreateRenderNode(eERType_GeomCache));
}
if (m_geomCacheAsset.GetId().IsValid())
{
if (!AZ::Data::AssetBus::Handler::BusIsConnected())
{
AZ::Data::AssetBus::Handler::BusConnect(m_geomCacheAsset.GetId());
}
m_geomCacheAsset.QueueLoad();
}
//Apply starting params to the render node
ApplyAllRenderNodeParams();
}
void GeometryCacheCommon::DestroyGeomCache()
{
if (m_isRegisteredWithRenderer && m_geomCacheRenderNode)
{
m_geomCacheRenderNode->StopStreaming();
m_isRegisteredWithRenderer = false;
gEnv->p3DEngine->FreeRenderNodeState(m_geomCacheRenderNode);
}
m_geomCache = nullptr;
m_materialOverride = nullptr;
m_geomCacheAsset.Release();
AZ::Data::AssetBus::Handler::BusDisconnect();
}
void GeometryCacheCommon::ApplyAllRenderNodeParams()
{
OnRenderOptionsChanged();
OnMaterialOverrideChanged();
OnLoopChanged();
OnMaxViewDistanceChanged();
OnViewDistanceMultiplierChanged();
OnLODDistanceRatioChanged();
OnStreamInDistanceChanged();
}
void GeometryCacheCommon::ShowCurrentStandin()
{
switch (m_currentStandinType)
{
case StandinType::FirstFrame:
{
MeshComponentRequestBus::Event(m_firstFrameStandin, &MeshComponentRequestBus::Events::SetVisibility, true);
break;
}
case StandinType::LastFrame:
{
MeshComponentRequestBus::Event(m_lastFrameStandin, &MeshComponentRequestBus::Events::SetVisibility, true);
break;
}
case StandinType::Distance:
{
MeshComponentRequestBus::Event(m_standin, &MeshComponentRequestBus::Events::SetVisibility, true);
break;
}
case StandinType::None:
{
//Show the geom cache by removing the ERF_HIDDEN flag
m_renderingStandin = false;
OnRenderOptionsChanged();
break;
}
}
GeometryCacheComponentNotificationBus::Broadcast(&GeometryCacheComponentNotificationBus::Events::OnStandinChanged, m_currentStandinType);
}
void GeometryCacheCommon::HideCurrentStandin()
{
switch (m_currentStandinType)
{
case StandinType::FirstFrame:
{
MeshComponentRequestBus::Event(m_firstFrameStandin, &MeshComponentRequestBus::Events::SetVisibility, false);
break;
}
case StandinType::LastFrame:
{
MeshComponentRequestBus::Event(m_lastFrameStandin, &MeshComponentRequestBus::Events::SetVisibility, false);
break;
}
case StandinType::Distance:
{
MeshComponentRequestBus::Event(m_standin, &MeshComponentRequestBus::Events::SetVisibility, false);
break;
}
case StandinType::None:
{
//Hide the geom cache by adding the ERF_HIDDEN flag
m_renderingStandin = true;
OnRenderOptionsChanged();
break;
}
}
}
void GeometryCacheCommon::HideAllStandins()
{
if (m_firstFrameStandin.IsValid())
{
MeshComponentRequestBus::Event(m_firstFrameStandin, &MeshComponentRequestBus::Events::SetVisibility, false);
}
if (m_lastFrameStandin.IsValid())
{
MeshComponentRequestBus::Event(m_lastFrameStandin, &MeshComponentRequestBus::Events::SetVisibility, false);
}
if (m_standin.IsValid())
{
MeshComponentRequestBus::Event(m_standin, &MeshComponentRequestBus::Events::SetVisibility, false);
}
}
void GeometryCacheComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides)
{
provides.push_back(AZ_CRC("GeomCacheService", 0x3d2bc48c));
}
void GeometryCacheComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires)
{
requires.push_back(AZ_CRC("TransformService", 0x8ee22c50));
}
void GeometryCacheComponent::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<GeometryCacheComponent, AZ::Component>()
->Version(1)
->Field("Common", &GeometryCacheComponent::m_common)
;
}
GeometryCacheCommon::Reflect(context);
}
void GeometryCacheComponent::Init()
{
m_common.Init(GetEntityId());
}
void GeometryCacheComponent::Activate()
{
m_common.Activate();
}
void GeometryCacheComponent::Deactivate()
{
m_common.Deactivate();
}
} //namespace LmbrCentral
@@ -1,225 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Component/Component.h>
#include <AzCore/Component/TransformBus.h>
#include <AzCore/Component/TickBus.h>
#include <AzCore/Slice/SliceAsset.h>
#include <AzCore/Math/Transform.h>
#include <AzCore/Math/Vector3.h>
#include <LmbrCentral/Rendering/MeshAsset.h>
#include <LmbrCentral/Rendering/MaterialAsset.h>
#include <LmbrCentral/Rendering/MaterialOwnerBus.h>
#include <LmbrCentral/Rendering/GeomCacheComponentBus.h>
#include <LmbrCentral/Scripting/SpawnerComponentBus.h>
#include <IEntityRenderState.h>
namespace LmbrCentral
{
enum class StandinType : AZ::u32
{
None,
FirstFrame,
LastFrame,
Distance
};
/**
* A Common structure for the GeometryCache and EditorGeometryCache.
*
* This is where most of the GeometryCache logic lives and it's made
* available to the GeometryCacheComponent and the EditorGeometryCacheComponent.
*/
class GeometryCacheCommon
: public AZ::TransformNotificationBus::Handler
, public AZ::Data::AssetBus::Handler
, public AZ::TickBus::Handler
, public MaterialOwnerRequestBus::Handler
, public GeometryCacheComponentRequestBus::Handler
{
friend class EditorGeometryCacheCommon; //So that we can reflect private members
public:
AZ_TYPE_INFO(GeometryCacheCommon, "{4534C4C4-50CC-4256-83F0-85B0274A5E26}");
AZ_CLASS_ALLOCATOR(GeometryCacheCommon, AZ::SystemAllocator, 0);
static void Reflect(AZ::ReflectContext* context);
virtual ~GeometryCacheCommon();
//Startup helpers
void Init(const AZ::EntityId& entityId);
virtual void Activate();
virtual void Deactivate();
// AZ::TransformNotificationBus interface implementation
void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override;
// AZ::TickBus
void OnTick(float deltaTime, AZ::ScriptTimePoint time) override;
// AZ::Data::AssetBus
void OnAssetReady(AZ::Data::Asset<AZ::Data::AssetData> asset) override;
void OnAssetReloaded(AZ::Data::Asset<AZ::Data::AssetData> asset) override;
// MaterialOwnerRequestBus
void SetMaterial(_smart_ptr<IMaterial> material) override;
_smart_ptr<IMaterial> GetMaterial() override;
// GeometryCacheComponentRequestBus
void Play() override;
void Pause() override;
void Stop() override;
float GetTimeRemaining() override;
StandinType GetCurrentStandinType() override { return m_currentStandinType; }
void SetGeomCacheAsset(const AZ::Data::AssetId& id);
AZ::Data::Asset<AZ::Data::AssetData> GetGeomCacheAsset() { return m_geomCacheAsset; }
void SetVisible(bool visible) override;
bool GetVisible() override { return m_visible; }
void SetLoop(bool loop) override;
bool GetLoop() override { return m_loop; }
void SetStartTime(float startTime) override;
float GetStartTime() override { return m_startTime; }
void SetFirstFrameStandIn(AZ::EntityId entityId) override;
AZ::EntityId GetFirstFrameStandIn() override { return m_firstFrameStandin; }
void SetLastFrameStandIn(AZ::EntityId entityId) override;
AZ::EntityId GetLastFrameStandIn() override { return m_lastFrameStandin; }
void SetStandIn(AZ::EntityId entityId) override;
AZ::EntityId GetStandIn() override { return m_standin; }
void SetStandInDistance(float standInDistance) override;
float GetStandInDistance() override { return m_standinDistance; }
void SetStreamInDistance(float streamInDistance) override;
float GetStreamInDistance() override { return m_streamInDistance; }
IGeomCacheRenderNode* GetGeomCacheRenderNode() override { return m_geomCacheRenderNode; }
void ClearGeomCacheRenderNode() { m_geomCacheRenderNode = nullptr; }
protected:
//Reflected Members
bool m_visible = true;
bool m_loop = false;
bool m_playOnStart = false;
bool m_castShadows = true;
bool m_useVisAreas = true;
float m_startTime = 0.0f;
EngineSpec m_minSpec = EngineSpec::Low;
float m_standinDistance = 100.0f;
float m_streamInDistance = 150.0f;
float m_maxViewDistance = 8000.0f;
float m_viewDistanceMultiplier = 1.0f;
AZ::u32 m_lodDistanceRatio = 100;
AZ::EntityId m_firstFrameStandin;
AZ::EntityId m_lastFrameStandin;
AZ::EntityId m_standin;
AZ::Data::Asset<GeomCacheAsset> m_geomCacheAsset;
AzFramework::SimpleAssetReference<MaterialAsset> m_materialOverrideAsset;
//Unreflected members
bool m_hidden; //< This is different from visible because this can also be controlled by the min spec being too high.
bool m_isRegisteredWithRenderer = false; //< We keep track of this because if some params are change we want to re-register but only if already registered.
bool m_renderingStandin = false;
bool m_playing;
float m_currentTime;
StandinType m_currentStandinType;
_smart_ptr<IMaterial> m_materialOverride;
IGeomCacheRenderNode* m_geomCacheRenderNode = nullptr;
_smart_ptr<IGeomCache> m_geomCache;
AZ::EntityId m_entityId;
AZ::Vector3 m_currentWorldPos;
AZStd::vector<AZ::EntityId> m_currentStandinEntities;
//Helper methods
void OnRenderOptionsChanged();
void OnGeomCacheAssetChanged();
void OnMaterialOverrideChanged();
void OnStartTimeChanged();
virtual void OnPlayOnStartChanged() {} //Only matters at edit time
void OnLoopChanged();
void OnMaxViewDistanceChanged();
void OnViewDistanceMultiplierChanged();
void OnLODDistanceRatioChanged();
void OnStreamInDistanceChanged();
virtual void OnFirstFrameStandinChanged() {}
virtual void OnLastFrameStandinChanged() {}
virtual void OnStandinChanged() {}
void LoadMaterialOverride();
void RegisterRenderNode();
void CreateGeomCache();
void DestroyGeomCache();
void ApplyAllRenderNodeParams();
void ShowCurrentStandin();
void HideCurrentStandin();
void HideAllStandins();
AZ::EntityId m_prevFirstFrameStandin;
AZ::EntityId m_prevLastFrameStandin;
AZ::EntityId m_prevStandin;
};
/**
* A Component for handling Alembic geometry cache animations.
*
* Most of the logic lives in GeometryCacheCommon.
*/
class GeometryCacheComponent
: public AZ::Component
{
public:
AZ_COMPONENT(GeometryCacheComponent, "{B2974790-5A3B-4641-868F-6148C67830EE}", AZ::Component);
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides);
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires);
static void Reflect(AZ::ReflectContext* context);
GeometryCacheComponent() {};
explicit GeometryCacheComponent(GeometryCacheCommon* common)
{
m_common = *common;
m_common.ClearGeomCacheRenderNode(); //We don't want to copy the render node from the given common structure
}
~GeometryCacheComponent() = default;
void Init() override;
void Activate() override;
void Deactivate() override;
private:
//Reflected members
GeometryCacheCommon m_common;
};
} //namespace LmbrCentral
@@ -1,171 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include "HighQualityShadowComponent.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include <LmbrCentral/Rendering/RenderNodeBus.h>
#include <I3DEngine.h>
namespace LmbrCentral
{
//////////////////////////////////////////////////////////////////////////
HighQualityShadowConfig::HighQualityShadowConfig()
: m_enabled(true)
, m_constBias(0.001f)
, m_slopeBias(0.01f)
, m_jitter(0.01f)
, m_bboxScale(1,1,1)
, m_shadowMapSize(1024)
{
}
void HighQualityShadowConfig::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<HighQualityShadowConfig>()
->Version(1)
->Field("Enabled", &HighQualityShadowConfig::m_enabled)
->Field("ConstBias", &HighQualityShadowConfig::m_constBias)
->Field("SlopeBias", &HighQualityShadowConfig::m_slopeBias)
->Field("Jitter", &HighQualityShadowConfig::m_jitter)
->Field("BBoxScale", &HighQualityShadowConfig::m_bboxScale)
->Field("ShadowMapSize", &HighQualityShadowConfig::m_shadowMapSize)
;
}
}
//////////////////////////////////////////////////////////////////////////
void HighQualityShadowComponent::Reflect(AZ::ReflectContext* context)
{
HighQualityShadowConfig::Reflect(context);
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<HighQualityShadowComponent, AZ::Component>()
->Version(1)
->Field("HighQualityShadowConfig", &HighQualityShadowComponent::m_config);
}
if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
{
behaviorContext->EBus<HighQualityShadowComponentRequestBus>("HighQualityShadowComponentRequestBus")
->Event("SetEnabled", &HighQualityShadowComponentRequestBus::Events::SetEnabled, { { {"Enabled", ""} } })
->Attribute(AZ::Script::Attributes::ToolTip, "Enables or disables the High Quality Shadow")
->Event("GetEnabled", &HighQualityShadowComponentRequestBus::Events::GetEnabled)
->Attribute(AZ::Script::Attributes::ToolTip, "Returns whether the High Quality Shadow is enabled")
->VirtualProperty("Enabled", "GetEnabled", "SetEnabled");
}
}
void HighQualityShadowComponent::Activate()
{
HighQualityShadowComponentRequestBus::Handler::BusConnect(GetEntityId());
MeshComponentNotificationBus::Handler::BusConnect(GetEntityId());
}
void HighQualityShadowComponent::Deactivate()
{
HighQualityShadowComponentUtils::RemoveShadow(GetEntityId());
HighQualityShadowComponentRequestBus::Handler::BusDisconnect();
MeshComponentNotificationBus::Handler::BusDisconnect(GetEntityId());
}
bool HighQualityShadowComponent::GetEnabled()
{
return m_config.m_enabled;
}
void HighQualityShadowComponent::SetEnabled(bool enabled)
{
m_config.m_enabled = enabled;
HighQualityShadowComponentUtils::ApplyShadowSettings(GetEntityId(), m_config);
}
void HighQualityShadowComponentUtils::ApplyShadowSettings(AZ::EntityId entityId, const HighQualityShadowConfig& config)
{
int numRenderNodesApplied = 0;
AZ::EBusAggregateResults<IRenderNode*> renderNodes;
LmbrCentral::RenderNodeRequestBus::EventResult(renderNodes, entityId, &LmbrCentral::RenderNodeRequests::GetRenderNode);
for(IRenderNode* renderNode : renderNodes.values)
{
if (renderNode)
{
const EERType type = renderNode->GetRenderNodeType();
const bool typeIsSupported =
type == eERType_StaticMeshRenderComponent || // Mesh Component uses this
type == eERType_DynamicMeshRenderComponent || // Mesh Component uses this
type == eERType_SkinnedMeshRenderComponent || // Skinned Mesh Component uses this; probably isn't necessary since this is deprecated, but is included for completion's sake
type == eERType_RenderComponent; // Actor Component uses this
if (typeIsSupported)
{
++numRenderNodesApplied;
if (config.m_enabled && renderNode->IsReady()) // Note that if the mesh isn't ready yet, OnMeshCreated will be called when it is ready, which will call ApplyShadowSettings again
{
const Vec3 bboxScaleVec3(config.m_bboxScale.GetX(), config.m_bboxScale.GetY(), config.m_bboxScale.GetZ());
gEnv->p3DEngine->AddPerObjectShadow(renderNode, config.m_constBias, config.m_slopeBias, config.m_jitter, bboxScaleVec3, config.m_shadowMapSize);
}
else
{
gEnv->p3DEngine->RemovePerObjectShadow(renderNode);
}
}
}
}
// This should never fail because "MeshService" components are mutually exclusive. It is possible that numRenderNodesApplied be 0,
// because some mesh-based components, like ActorComponent, may return a null IRenderNode when they aren't initialized yet.
AZ_Assert(numRenderNodesApplied <= 1, "Expected exactly one mesh-based component. Found %d", numRenderNodesApplied);
}
void HighQualityShadowComponentUtils::RemoveShadow(AZ::EntityId entityId)
{
AZ::EBusAggregateResults<IRenderNode*> renderNodes;
LmbrCentral::RenderNodeRequestBus::EventResult(renderNodes, entityId, &LmbrCentral::RenderNodeRequests::GetRenderNode);
for (IRenderNode* renderNode : renderNodes.values)
{
if (renderNode)
{
gEnv->p3DEngine->RemovePerObjectShadow(renderNode);
}
}
}
void HighQualityShadowComponent::OnMeshCreated([[maybe_unused]] const AZ::Data::Asset<AZ::Data::AssetData>& asset)
{
HighQualityShadowComponentUtils::ApplyShadowSettings(GetEntityId(), m_config);
}
void HighQualityShadowComponent::OnMeshDestroyed()
{
HighQualityShadowComponentUtils::RemoveShadow(GetEntityId());
}
} // namespace LmbrCentral
@@ -1,109 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/Component.h>
#include <AzCore/Component/ComponentBus.h>
#include <AzCore/Component/Entity.h>
#include <AzCore/Math/Vector3.h>
#include <LmbrCentral/Rendering/MeshComponentBus.h>
#include <LmbrCentral/Rendering/HighQualityShadowComponentBus.h>
namespace LmbrCentral
{
/*!
* Stores configuration settings for per-entity shadows
*/
class HighQualityShadowConfig
{
public:
AZ_TYPE_INFO(HighQualityShadowConfig, "{3B3CD21A-E61B-401A-8F54-B76FB6278B11}");
HighQualityShadowConfig();
virtual ~HighQualityShadowConfig() {}
static void Reflect(AZ::ReflectContext* context);
bool m_enabled;
float m_constBias;
float m_slopeBias;
float m_jitter;
AZ::Vector3 m_bboxScale;
int m_shadowMapSize;
// Property event-handlers implemented in editor component.
virtual void EditorRefresh() { }
};
/*!
* Provides a entity-specific shadow map to achieving higher quality shadows on a specific entity.
* Has performance and memory impact so use sparingly.
* Corresponds to legacy PerEntityShadows feature.
*/
class HighQualityShadowComponent
: public AZ::Component
, public HighQualityShadowComponentRequestBus::Handler
, public MeshComponentNotificationBus::Handler
{
public:
friend class EditorHighQualityShadowComponent;
AZ_COMPONENT(HighQualityShadowComponent, "{B692F9D9-4850-4D6E-9A32-760901455E40}");
//////////////////////////////////////////////////////////////////////////
// AZ::Component interface implementation
void Activate() override;
void Deactivate() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// HighQualityShadowComponentRequestBus interface implementation
void SetEnabled(bool enabled) override;
bool GetEnabled() override;
///////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// MeshComponentNotificationBus interface implementation
void OnMeshCreated(const AZ::Data::Asset<AZ::Data::AssetData>& asset) override;
void OnMeshDestroyed() override;
///////////////////////////////////
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("HighQualityShadowService", 0x43dea981));
}
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("HighQualityShadowService", 0x43dea981));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
// HighQualityShadowComponent is only applicable to Entities that cast and/or receive shadows.
required.push_back(AZ_CRC("MeshService", 0x71d8a455));
}
static void Reflect(AZ::ReflectContext* context);
protected:
HighQualityShadowConfig m_config;
};
namespace HighQualityShadowComponentUtils
{
void ApplyShadowSettings(AZ::EntityId entityId, const HighQualityShadowConfig& config);
void RemoveShadow(AZ::EntityId entityId);
}
} // namespace LmbrCentral
@@ -1,205 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include <AzCore/IO/GenericStreams.h>
#include <AzFramework/Asset/SimpleAsset.h>
#include <AzFramework/Asset/AssetCatalogBus.h>
#include <AzCore/XML/rapidxml.h>
#include <AzFramework/Archive/IArchive.h>
#include <LmbrCentral/Rendering/LensFlareAsset.h>
#include "LensFlareAssetHandler.h"
#include <ISystem.h>
#define LENS_FLARE_EXT "xml"
namespace LmbrCentral
{
LensFlareAssetHandler::~LensFlareAssetHandler()
{
Unregister();
}
AZ::Data::AssetPtr LensFlareAssetHandler::CreateAsset(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type)
{
(void)type;
AZ_Assert(type == AZ::AzTypeInfo<LensFlareAsset>::Uuid(), "Invalid asset type! We handle only 'LensFlareAsset'");
if (!CanHandleAsset(id))
{
return nullptr;
}
return aznew LensFlareAsset;
}
AZ::Data::AssetHandler::LoadResult LensFlareAssetHandler::LoadAssetData(
const AZ::Data::Asset<AZ::Data::AssetData>& asset,
AZStd::shared_ptr<AZ::Data::AssetDataStream> stream,
const AZ::Data::AssetFilterCB& assetLoadFilterCB)
{
(void)assetLoadFilterCB;
// Load from preloaded stream.
AZ_Assert(asset.GetType() == AZ::AzTypeInfo<LensFlareAsset>::Uuid(), "Invalid asset type! We handle only 'LensFlareAsset'");
if (stream)
{
LensFlareAsset* data = asset.GetAs<LensFlareAsset>();
const size_t sizeBytes = static_cast<size_t>(stream->GetLength());
char* buffer = new char[sizeBytes];
stream->Read(sizeBytes, buffer);
bool loaded = LoadFromBuffer(data, buffer, sizeBytes);
delete[] buffer;
return loaded ? AZ::Data::AssetHandler::LoadResult::LoadComplete : AZ::Data::AssetHandler::LoadResult::Error;
}
return AZ::Data::AssetHandler::LoadResult::Error;
}
void LensFlareAssetHandler::DestroyAsset(AZ::Data::AssetPtr ptr)
{
delete ptr;
}
void LensFlareAssetHandler::GetHandledAssetTypes(AZStd::vector<AZ::Data::AssetType>& assetTypes)
{
assetTypes.push_back(AZ::AzTypeInfo<LensFlareAsset>::Uuid());
}
void LensFlareAssetHandler::Register()
{
AZ_Assert(AZ::Data::AssetManager::IsReady(), "Asset manager isn't ready!");
AZ::Data::AssetManager::Instance().RegisterHandler(this, AZ::AzTypeInfo<LensFlareAsset>::Uuid());
AZ::AssetTypeInfoBus::Handler::BusConnect(AZ::AzTypeInfo<LensFlareAsset>::Uuid());
}
void LensFlareAssetHandler::Unregister()
{
AZ::AssetTypeInfoBus::Handler::BusDisconnect();
if (AZ::Data::AssetManager::IsReady())
{
AZ::Data::AssetManager::Instance().UnregisterHandler(this);
}
}
AZ::Data::AssetType LensFlareAssetHandler::GetAssetType() const
{
return AZ::AzTypeInfo<LensFlareAsset>::Uuid();
}
const char* LensFlareAssetHandler::GetAssetTypeDisplayName() const
{
return "Lens Flare";
}
const char* LensFlareAssetHandler::GetBrowserIcon() const
{
return "Icons/Components/LensFlare.svg";
}
AZ::Uuid LensFlareAssetHandler::GetComponentTypeId() const
{
return AZ::Uuid("{4B85E77D-91F9-40C5-8FCB-B494000A9E69}");
}
void LensFlareAssetHandler::GetAssetTypeExtensions(AZStd::vector<AZStd::string>& extensions)
{
extensions.push_back(LENS_FLARE_EXT);
}
bool LensFlareAssetHandler::CanHandleAsset(const AZ::Data::AssetId& id) const
{
// Look up the asset path to ensure it's actually a lens flare library.
AZStd::string assetPath;
EBUS_EVENT_RESULT(assetPath, AZ::Data::AssetCatalogRequestBus, GetAssetPathById, id);
bool isLensFlareLibrary = false;
if (!assetPath.empty() && strstr(assetPath.c_str(), "." LENS_FLARE_EXT))
{
//check whether the file includes "LensFlareLibrary" string
AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance();
AZ_Assert(fileIO, "FileIO is not initialized.");
AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle;
const AZ::IO::Result result = fileIO->Open(assetPath.c_str(), AZ::IO::OpenMode::ModeRead, fileHandle);
if (result)
{
AZ::u64 fileSize = 0;
if (fileIO->Size(fileHandle, fileSize) && fileSize)
{
AZStd::vector<char> memoryBuffer;
memoryBuffer.resize_no_construct(fileSize);
if (fileIO->Read(fileHandle, memoryBuffer.begin(), fileSize, true))
{
//compare string instead of parse the entire xml because it's faster.
isLensFlareLibrary = (nullptr != strstr(memoryBuffer.begin(), "LensFlareLibrary"));
}
}
fileIO->Close(fileHandle);
}
}
return isLensFlareLibrary;
}
bool LensFlareAssetHandler::LoadFromBuffer(LensFlareAsset* data, char* buffer, [[maybe_unused]] size_t bufferSize)
{
using namespace AZ::rapidxml;
xml_document<char> xmlDoc;
xmlDoc.parse<parse_no_data_nodes>(buffer);
xml_node<char>* root = xmlDoc.first_node();
if (root)
{
//get the name of this lens flare library
xml_attribute<char>* nameAttribute = root->first_attribute("Name");
if (nameAttribute)
{
const char* libName = nameAttribute->value();
if (libName && libName[0])
{
xml_node<char>* flareNode = root->first_node("FlareItem");
while (flareNode)
{
//for each of FlareItem add their path, combined with lib name, to LensFlareAsset data.
xml_attribute<char>* flareNameAttribute = flareNode->first_attribute("Name");
if (flareNameAttribute)
{
const char* effectName = flareNameAttribute->value();
if (effectName && effectName[0])
{
AZStd::string flarePath = AZStd::string::format("%s.%s", libName, effectName);
data->AddPath(std::move(flarePath));
}
}
flareNode = flareNode->next_sibling("FlareItem");
}
return true;
}
}
}
return false;
}
} // namespace LmbrCentral
@@ -1,56 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Asset/AssetManager.h>
#include <AzCore/Asset/AssetTypeInfoBus.h>
namespace LmbrCentral
{
class LensFlareAssetHandler
: public AZ::Data::AssetHandler
, public AZ::AssetTypeInfoBus::Handler
{
public:
AZ_CLASS_ALLOCATOR(LensFlareAssetHandler, AZ::SystemAllocator, 0);
~LensFlareAssetHandler() override;
//////////////////////////////////////////////////////////////////////////////////////////////
// AZ::Data::AssetHandler
AZ::Data::AssetPtr CreateAsset(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override;
AZ::Data::AssetHandler::LoadResult LoadAssetData(
const AZ::Data::Asset<AZ::Data::AssetData>& asset,
AZStd::shared_ptr<AZ::Data::AssetDataStream> stream,
const AZ::Data::AssetFilterCB& assetLoadFilterCB) override;
void DestroyAsset(AZ::Data::AssetPtr ptr) override;
void GetHandledAssetTypes(AZStd::vector<AZ::Data::AssetType>& assetTypes) override;
bool CanHandleAsset(const AZ::Data::AssetId& id) const override;
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
// AZ::AssetTypeInfoBus::Handler
AZ::Data::AssetType GetAssetType() const override;
const char* GetAssetTypeDisplayName() const override;
const char* GetBrowserIcon() const override;
AZ::Uuid GetComponentTypeId() const override;
void GetAssetTypeExtensions(AZStd::vector<AZStd::string>& extensions) override;
//////////////////////////////////////////////////////////////////////////////////////////////
void Register();
void Unregister();
private:
static bool LoadFromBuffer(LensFlareAsset* data, char* buffer, size_t bufferSize);
};
} // namespace LmbrCentral
@@ -1,275 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include <AzCore/Math/Vector3.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Component/Entity.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include "LensFlareComponent.h"
namespace LmbrCentral
{
//////////////////////////////////////////////////////////////////////////
// BehaviorContext LensFlareComponentNotificationBus forwarder
class BehaviorLensFlareComponentNotificationBusHandler : public LensFlareComponentNotificationBus::Handler, public AZ::BehaviorEBusHandler
{
public:
AZ_EBUS_BEHAVIOR_BINDER(BehaviorLensFlareComponentNotificationBusHandler, "{285A6AB7-82CF-472F-8C3B-1659A59213FF}", AZ::SystemAllocator,
LensFlareTurnedOn, LensFlareTurnedOff);
void LensFlareTurnedOn()
{
Call(FN_LensFlareTurnedOn);
}
void LensFlareTurnedOff()
{
Call(FN_LensFlareTurnedOff);
}
};
// Class to encapsulate LensFlareComponentRequests::State values.
class BehaviorLensFlareComponentState
{
public:
AZ_TYPE_INFO(BehaviorLensFlareComponentState, "{1A63ED6B-C2D2-4D3C-AC27-5FDBF22B5B38}");
AZ_CLASS_ALLOCATOR(BehaviorLensFlareComponentState, AZ::SystemAllocator, 0);
};
void LensFlareComponent::Reflect(AZ::ReflectContext* context)
{
LensFlareConfiguration::Reflect(context);
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<LensFlareComponent, AZ::Component>()->
Version(1)->
Field("LensFlareConfiguration", &LensFlareComponent::m_configuration);
}
AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
if (behaviorContext)
{
behaviorContext->Class<BehaviorLensFlareComponentState>("LensFlareComponentState")
->Attribute(AZ::Script::Attributes::Storage, AZ::Script::Attributes::StorageType::Value)
->Constant("Off", BehaviorConstant(LensFlareComponentRequests::State::Off))
->Constant("On", BehaviorConstant(LensFlareComponentRequests::State::On))
;
behaviorContext->EBus<LensFlareComponentRequestBus>("LensFlareComponentRequestBus")
->Event("SetLensFlareState", &LensFlareComponentRequestBus::Events::SetLensFlareState)
->Event("TurnOnLensFlare", &LensFlareComponentRequestBus::Events::TurnOnLensFlare)
->Event("TurnOffLensFlare", &LensFlareComponentRequestBus::Events::TurnOffLensFlare)
->Event("ToggleLensFlare", &LensFlareComponentRequestBus::Events::ToggleLensFlare)
;
behaviorContext->EBus<LensFlareComponentNotificationBus>("LensFlareComponentNotificationBus")
->Handler<BehaviorLensFlareComponentNotificationBusHandler>();
}
}
void LensFlareConfiguration::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<LensFlareConfiguration>()->
Version(4, &VersionConverter)->
Field("Visible", &LensFlareConfiguration::m_visible)->
Field("LensFlare", &LensFlareConfiguration::m_lensFlare)->
Field("Asset", &LensFlareConfiguration::m_asset)->
Field("MinimumSpec", &LensFlareConfiguration::m_minSpec)->
Field("LensFlareFrustumAngle", &LensFlareConfiguration::m_lensFlareFrustumAngle)->
Field("Size", &LensFlareConfiguration::m_size)->
Field("AttachToSun", &LensFlareConfiguration::m_attachToSun)->
Field("AffectsThisAreaOnly", &LensFlareConfiguration::m_affectsThisAreaOnly)->
Field("UseVisAreas", &LensFlareConfiguration::m_useVisAreas)->
Field("IndoorOnly", &LensFlareConfiguration::m_indoorOnly)->
Field("OnInitially", &LensFlareConfiguration::m_onInitially)->
Field("ViewDistanceMultiplier", &LensFlareConfiguration::m_viewDistMultiplier)->
Field("Tint", &LensFlareConfiguration::m_tint)->
Field("TintAlpha", &LensFlareConfiguration::m_tintAlpha)->
Field("Brightness", &LensFlareConfiguration::m_brightness)->
Field("SyncAnimWithLight", &LensFlareConfiguration::m_syncAnimWithLight)->
Field("LightEntity", &LensFlareConfiguration::m_lightEntity)->
Field("AnimIndex", &LensFlareConfiguration::m_animIndex)->
Field("AnimSpeed", &LensFlareConfiguration::m_animSpeed)->
Field("AnimPhase", &LensFlareConfiguration::m_animPhase)->
Field("SyncedAnimIndex", &LensFlareConfiguration::m_syncAnimIndex)->
Field("SyncedAnimSpeed", &LensFlareConfiguration::m_syncAnimSpeed)->
Field("SyncedAnimPhase", &LensFlareConfiguration::m_syncAnimPhase)
;
}
}
bool LensFlareConfiguration::VersionConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement)
{
// conversion from version 2 to version 3:
// - Need to rename IgnoreVisAreas to UseVisAreas
// UseVisAreas is the Inverse of IgnoreVisAreas
if (classElement.GetVersion() <= 2)
{
int ignoreVisAreasIndex = classElement.FindElement(AZ_CRC("IgnoreVisAreas", 0x01823201));
if (ignoreVisAreasIndex < 0)
{
return false;
}
AZ::SerializeContext::DataElementNode& useVisAreasNode = classElement.GetSubElement(ignoreVisAreasIndex);
useVisAreasNode.SetName("UseVisAreas");
bool ignoreVisAreas = true;
if (!useVisAreasNode.GetData<bool>(ignoreVisAreas))
{
return false;
}
if (!useVisAreasNode.SetData<bool>(context, !ignoreVisAreas))
{
return false;
}
}
return true;
}
void LensFlareComponent::TurnOnLensFlare()
{
bool success = m_light.TurnOn();
if (success)
{
LensFlareComponentNotificationBus::Event(GetEntityId(), &LensFlareComponentNotificationBus::Events::LensFlareTurnedOn);
}
}
void LensFlareComponent::TurnOffLensFlare()
{
bool success = m_light.TurnOff();
if (success)
{
LensFlareComponentNotificationBus::Event(GetEntityId(), &LensFlareComponentNotificationBus::Events::LensFlareTurnedOff);
}
}
void LensFlareComponent::ToggleLensFlare()
{
if (m_light.IsOn())
{
TurnOffLensFlare();
}
else
{
TurnOnLensFlare();
}
}
LensFlareConfiguration LensFlareComponent::GetLensFlareConfiguration()
{
return m_configuration;
}
void LensFlareComponent::SetLensFlareState(State state)
{
switch (state)
{
case LensFlareComponentRequests::State::On:
{
TurnOnLensFlare();
}
break;
case LensFlareComponentRequests::State::Off:
{
TurnOffLensFlare();
}
break;
}
}
IRenderNode* LensFlareComponent::GetRenderNode()
{
return m_light.GetRenderNode();
}
float LensFlareComponent::GetRenderNodeRequestBusOrder() const
{
return s_renderNodeRequestBusOrder;
}
const float LensFlareComponent::s_renderNodeRequestBusOrder = 600.f;
void LensFlareComponent::Init()
{
//Set this in Init because it will never change and doesn't need to be reset if the component re-activates
m_configuration.m_material.SetAssetPath("EngineAssets/Materials/lens_optics");
}
void LensFlareComponent::Activate()
{
const AZ::EntityId entityId = GetEntityId();
m_light.SetEntity(entityId);
m_light.CreateRenderLight(m_configuration);
LensFlareComponentRequestBus::Handler::BusConnect(entityId);
RenderNodeRequestBus::Handler::BusConnect(entityId);
if (m_configuration.m_onInitially)
{
TurnOnLensFlare();
}
else
{
TurnOffLensFlare();
}
}
void LensFlareComponent::Deactivate()
{
LensFlareComponentRequestBus::Handler::BusDisconnect();
RenderNodeRequestBus::Handler::BusDisconnect();
m_light.DestroyRenderLight();
m_light.SetEntity(AZ::EntityId());
}
LensFlareConfiguration::LensFlareConfiguration()
: m_minSpec(EngineSpec::Low)
, m_visible(true)
, m_onInitially(true)
, m_tint(1.f)
, m_brightness(1.f)
, m_viewDistMultiplier(1.f)
, m_affectsThisAreaOnly(1.f)
, m_useVisAreas(true)
, m_indoorOnly(false)
, m_animSpeed(1.f)
, m_animPhase(0.f)
, m_animIndex(0)
, m_lensFlareFrustumAngle(360.f)
, m_size(1.0f)
, m_attachToSun(false)
, m_syncAnimWithLight(false)
{
}
} // namespace LmbrCentral
@@ -1,163 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/Component.h>
#include <AzCore/Component/ComponentBus.h>
#include <AzFramework/Asset/SimpleAsset.h>
#include "LightInstance.h"
#include <LmbrCentral/Rendering/LensFlareAsset.h>
#include <LmbrCentral/Rendering/LensFlareComponentBus.h>
#include <LmbrCentral/Rendering/RenderNodeBus.h>
#include <LmbrCentral/Rendering/MaterialAsset.h>
#include <IEntityRenderState.h>
namespace LmbrCentral
{
/*!
* Stores configuration settings for engine lens flares.
*/
class LensFlareConfiguration
{
public:
AZ_TYPE_INFO(LensFlareConfiguration, "{1E28DADD-0BD4-4AD5-A94B-2665813BF346}");
LensFlareConfiguration();
virtual ~LensFlareConfiguration() {};
static void Reflect(AZ::ReflectContext* context);
static bool VersionConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement);
AZ::Data::Asset<LensFlareAsset> m_asset { AZ::Data::AssetLoadBehavior::PreLoad }; //! Used at asset compile time to track the dependency. Not used at edit or runtime.
//! Settings common to all LY engine lights
EngineSpec m_minSpec;
//! Turned on by default?
bool m_onInitially;
//! Currently visible?
bool m_visible;
//! Lens flare size
float m_size;
AZ::Vector3 m_tint;
AZ::u32 m_tintAlpha;
float m_brightness;
float m_viewDistMultiplier;
float m_viewDistMultiplierUser; // Value set by user from UI.
bool m_affectsThisAreaOnly;
bool m_useVisAreas;
bool m_indoorOnly;
bool m_attachToSun;
bool m_syncAnimWithLight;
AZ::EntityId m_lightEntity;
float m_animSpeed;
float m_animPhase;
AZ::u32 m_animIndex;
AZStd::string m_lensFlare;
float m_lensFlareFrustumAngle;
// Animation settings from the light
float m_syncAnimSpeed;
float m_syncAnimPhase;
AZ::u32 m_syncAnimIndex;
// Settings not reflected in the editor
AzFramework::SimpleAssetReference<MaterialAsset> m_material; //Same name as the material in the LightSettings
AZ_INLINE bool ShouldShowAnimationSettings() {
return !m_syncAnimWithLight;
}
AZ_INLINE bool ShouldViewDistanceMultiplier() {
return !m_attachToSun;
}
// Property event-handlers implemented in editor component.
virtual AZ::u32 PropertyChanged() { return 0; }
virtual AZ::u32 SyncAnimationChanged() { return AZ_CRC("RefreshNone", 0x98a5045b); }
virtual AZ::u32 AttachToSunChanged() {return AZ_CRC("RefreshNone", 0x98a5045b); }
};
/*!
* In-game light component.
*/
class LensFlareComponent
: public AZ::Component
, public LensFlareComponentRequestBus::Handler
, public RenderNodeRequestBus::Handler
{
public:
friend class EditorLensFlareComponent;
AZ_COMPONENT(LensFlareComponent, "{07593109-4A57-473F-B868-C2DCF9270186}");
LensFlareComponent() {}
~LensFlareComponent() override {}
//////////////////////////////////////////////////////////////////////////
// AZ::Component interface implementation
void Init() override;
void Activate() override;
void Deactivate() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// LensFlareComponentRequestBus::Handler interface implementation
void TurnOnLensFlare() override;
void TurnOffLensFlare() override;
void SetLensFlareState(State state) override;
void ToggleLensFlare() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// RenderNodeRequestBus::Handler interface implementation
IRenderNode* GetRenderNode() override;
float GetRenderNodeRequestBusOrder() const override;
static const float s_renderNodeRequestBusOrder;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("LensFlareService", 0xda3286e8));
}
static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent)
{
dependent.push_back(AZ_CRC("TransformService", 0x8ee22c50));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
required.push_back(AZ_CRC("TransformService", 0x8ee22c50));
}
static void Reflect(AZ::ReflectContext* context);
//////////////////////////////////////////////////////////////////////////
LensFlareConfiguration GetLensFlareConfiguration();
protected:
LensFlareConfiguration m_configuration;
LightInstance m_light;
};
} // namespace LmbrCentral
@@ -1,875 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include <AzCore/Math/Vector3.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Component/Entity.h>
#include "LightInstance.h"
#include "LightComponent.h"
namespace LmbrCentral
{
//////////////////////////////////////////////////////////////////////////
class BehaviorLightComponentNotificationBusHandler : public LightComponentNotificationBus::Handler, public AZ::BehaviorEBusHandler
{
public:
AZ_EBUS_BEHAVIOR_BINDER(BehaviorLightComponentNotificationBusHandler, "{969C5B17-10D1-41DB-8123-6664FA64B4E9}", AZ::SystemAllocator,
LightTurnedOn, LightTurnedOff);
// Sent when the light is turned on.
void LightTurnedOn() override
{
Call(FN_LightTurnedOn);
}
// Sent when the light is turned off.
void LightTurnedOff() override
{
Call(FN_LightTurnedOff);
}
};
void LightComponent::Reflect(AZ::ReflectContext* context)
{
LightConfiguration::Reflect(context);
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<LightComponent, AZ::Component>()
->Version(1)
->Field("LightConfiguration", &LightComponent::m_configuration);
}
AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
if (behaviorContext)
{
behaviorContext->Class<LightComponent>()->RequestBus("LightComponentRequestBus");
;
auto probeFadeDefaultValue(behaviorContext->MakeDefaultValue(1.0f));
behaviorContext->EBus<LightComponentRequestBus>("Light", "LightComponentRequestBus")
->Attribute(AZ::Script::Attributes::Category, "Rendering")
->Event("SetState", &LightComponentRequestBus::Events::SetLightState, "SetLightState", { { { "State", "1=On, 0=Off" } } })
->Attribute(AZ::Script::Attributes::ToolTip, "Set the light state")
->Event("TurnOn", &LightComponentRequestBus::Events::TurnOnLight, "TurnOnLight")
->Event("TurnOff", &LightComponentRequestBus::Events::TurnOffLight, "TurnOffLight")
->Event("Toggle", &LightComponentRequestBus::Events::ToggleLight, "ToggleLight")
// General Settings Modifiers
->Event("GetVisible", &LightComponentRequestBus::Events::GetVisible)
->Event("SetVisible", &LightComponentRequestBus::Events::SetVisible, { { { "IsVisible", "" } } })
->VirtualProperty("Visible", "GetVisible", "SetVisible")
->Event("GetColor", &LightComponentRequestBus::Events::GetColor)
->Event("SetColor", &LightComponentRequestBus::Events::SetColor, { { { "Color", "The color to set" } } })
->VirtualProperty("Color", "GetColor", "SetColor")
->Event("GetDiffuseMultiplier", &LightComponentRequestBus::Events::GetDiffuseMultiplier)
->Event("SetDiffuseMultiplier", &LightComponentRequestBus::Events::SetDiffuseMultiplier, { { { "Multiplier", "The multiplier" } } })
->VirtualProperty("DiffuseMultiplier", "GetDiffuseMultiplier", "SetDiffuseMultiplier")
->Event("GetSpecularMultiplier", &LightComponentRequestBus::Events::GetSpecularMultiplier)
->Event("SetSpecularMultiplier", &LightComponentRequestBus::Events::SetSpecularMultiplier, { { { "Multiplier", "The multiplier" } } })
->VirtualProperty("SpecularMultiplier", "GetSpecularMultiplier", "SetSpecularMultiplier")
->Event("GetAmbient", &LightComponentRequestBus::Events::GetAmbient)
->Event("SetAmbient", &LightComponentRequestBus::Events::SetAmbient, { { { "IsAmbient", "" } } })
->VirtualProperty("Ambient", "GetAmbient", "SetAmbient")
// Point Light Modifiers
->Event("GetPointMaxDistance", &LightComponentRequestBus::Events::GetPointMaxDistance)
->Event("SetPointMaxDistance", &LightComponentRequestBus::Events::SetPointMaxDistance, { { { "Distance", "The max point distance" } } })
->VirtualProperty("PointMaxDistance", "GetPointMaxDistance", "SetPointMaxDistance")
->Event("GetPointAttenuationBulbSize", &LightComponentRequestBus::Events::GetPointAttenuationBulbSize)
->Event("SetPointAttenuationBulbSize", &LightComponentRequestBus::Events::SetPointAttenuationBulbSize, { { { "BulbSize", "The size of the bulb" } } })
->VirtualProperty("PointAttenuationBulbSize", "GetPointAttenuationBulbSize", "SetPointAttenuationBulbSize")
// Area Light Modifiers
->Event("GetAreaMaxDistance", &LightComponentRequestBus::Events::GetAreaMaxDistance)
->Event("SetAreaMaxDistance", &LightComponentRequestBus::Events::SetAreaMaxDistance, { { { "Distance", "The max point distance" } } })
->VirtualProperty("AreaMaxDistance", "GetAreaMaxDistance", "SetAreaMaxDistance")
->Event("GetAreaWidth", &LightComponentRequestBus::Events::GetAreaWidth)
->Event("SetAreaWidth", &LightComponentRequestBus::Events::SetAreaWidth, { { { "Width", "Area Width" } } })
->VirtualProperty("AreaWidth", "GetAreaWidth", "SetAreaWidth")
->Event("GetAreaHeight", &LightComponentRequestBus::Events::GetAreaHeight)
->Event("SetAreaHeight", &LightComponentRequestBus::Events::SetAreaHeight, { { { "Height", "Area Height" } } })
->VirtualProperty("AreaHeight", "GetAreaHeight", "SetAreaHeight")
->Event("GetAreaFOV", &LightComponentRequestBus::Events::GetAreaFOV)
->Event("SetAreaFOV", &LightComponentRequestBus::Events::SetAreaFOV, { { { "FOV", "Field of View" } } })
->VirtualProperty("AreaFOV", "GetAreaFOV", "SetAreaFOV")
// Projector Light Modifiers
->Event("GetProjectorMaxDistance", &LightComponentRequestBus::Events::GetProjectorMaxDistance)
->Event("SetProjectorMaxDistance", &LightComponentRequestBus::Events::SetProjectorMaxDistance, { { { "Distance", "Projector distance" } } })
->VirtualProperty("ProjectorMaxDistance", "GetProjectorMaxDistance", "SetProjectorMaxDistance")
->Event("GetProjectorAttenuationBulbSize", &LightComponentRequestBus::Events::GetProjectorAttenuationBulbSize)
->Event("SetProjectorAttenuationBulbSize", &LightComponentRequestBus::Events::SetProjectorAttenuationBulbSize, { { { "BulbSize", "The size of the bulb" } } })
->VirtualProperty("ProjectorAttenuationBulbSize", "GetProjectorAttenuationBulbSize", "SetProjectorAttenuationBulbSize")
->Event("GetProjectorFOV", &LightComponentRequestBus::Events::GetProjectorFOV)
->Event("SetProjectorFOV", &LightComponentRequestBus::Events::SetProjectorFOV, { { { "FOV", "Field of View" } } })
->VirtualProperty("ProjectorFOV", "GetProjectorFOV", "SetProjectorFOV")
->Event("GetProjectorNearPlane", &LightComponentRequestBus::Events::GetProjectorNearPlane)
->Event("SetProjectorNearPlane", &LightComponentRequestBus::Events::SetProjectorNearPlane, { { { "Plane", "Plane distance" } } })
->VirtualProperty("ProjectorNearPlane", "GetProjectorNearPlane", "SetProjectorNearPlane")
// Environment Probe Light Modifiers
->Event("GetProbeAreaDimensions", &LightComponentRequestBus::Events::GetProbeAreaDimensions)
->Event("SetProbeAreaDimensions", &LightComponentRequestBus::Events::SetProbeAreaDimensions, { { { "Dimension", "The X,Y and Z extents" } } })
->VirtualProperty("ProbeAreaDimensions", "GetProbeAreaDimensions", "SetProbeAreaDimensions")
->Event("GetProbeSortPriority", &LightComponentRequestBus::Events::GetProbeSortPriority)
->Event("SetProbeSortPriority", &LightComponentRequestBus::Events::SetProbeSortPriority, { { { "Priority", "" } } })
->VirtualProperty("ProbeSortPriority", "GetProbeSortPriority", "SetProbeSortPriority")
->Event("GetProbeBoxProjected", &LightComponentRequestBus::Events::GetProbeBoxProjected)
->Event("SetProbeBoxProjected", &LightComponentRequestBus::Events::SetProbeBoxProjected, { { { "IsProjected", "TRUE will project the box, False otherwise." } } })
->VirtualProperty("ProbeBoxProjected", "GetProbeBoxProjected", "SetProbeBoxProjected")
->Event("GetProbeBoxHeight", &LightComponentRequestBus::Events::GetProbeBoxHeight)
->Event("SetProbeBoxHeight", &LightComponentRequestBus::Events::SetProbeBoxHeight, { { { "Height", "Box Height" } } })
->VirtualProperty("ProbeBoxHeight", "GetProbeBoxHeight", "SetProbeBoxHeight")
->Event("GetProbeBoxLength", &LightComponentRequestBus::Events::GetProbeBoxLength)
->Event("SetProbeBoxLength", &LightComponentRequestBus::Events::SetProbeBoxLength, { { { "Length", "Box Length" } } })
->VirtualProperty("ProbeBoxLength", "GetProbeBoxLength", "SetProbeBoxLength")
->Event("GetProbeBoxWidth", &LightComponentRequestBus::Events::GetProbeBoxWidth)
->Event("SetProbeBoxWidth", &LightComponentRequestBus::Events::SetProbeBoxWidth, { { { "Width", "Box Width" } } })
->VirtualProperty("ProbeBoxWidth", "GetProbeBoxWidth", "SetProbeBoxWidth")
->Event("GetProbeAttenuationFalloff", &LightComponentRequestBus::Events::GetProbeAttenuationFalloff)
->Event("SetProbeAttenuationFalloff", &LightComponentRequestBus::Events::SetProbeAttenuationFalloff, { { { "Falloff", "Smoothness of the falloff around the probe's bounds" } } })
->VirtualProperty("ProbeAttenuationFalloff", "GetProbeAttenuationFalloff", "SetProbeAttenuationFalloff")
->Event("GetProbeFade", &LightComponentRequestBus::Events::GetProbeFade)
->Event("SetProbeFade", &LightComponentRequestBus::Events::SetProbeFade, { { { "Fade", "Multiplier for fading out a probe [0-1]", probeFadeDefaultValue } } })
->VirtualProperty("ProbeFade", "GetProbeFade", "SetProbeFade")
;
behaviorContext->EBus<LightComponentNotificationBus>("LightNotification", "LightComponentNotificationBus", "Notifications for the Light Components")
->Attribute(AZ::Script::Attributes::Category, "Rendering")
->Handler<BehaviorLightComponentNotificationBusHandler>();
}
}
void LightConfiguration::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<LightConfiguration>()
->Version(8, &VersionConverter)
->Field("LightType", &LightConfiguration::m_lightType)
->Field("Visible", &LightConfiguration::m_visible)
->Field("OnInitially", &LightConfiguration::m_onInitially)
->Field("Color", &LightConfiguration::m_color)
->Field("DiffuseMultiplier", &LightConfiguration::m_diffuseMultiplier)
->Field("SpecMultiplier", &LightConfiguration::m_specMultiplier)
->Field("Ambient", &LightConfiguration::m_ambient)
->Field("PointMaxDistance", &LightConfiguration::m_pointMaxDistance)
->Field("PointAttenuationBulbSize", &LightConfiguration::m_pointAttenuationBulbSize)
->Field("AreaWidth", &LightConfiguration::m_areaWidth)
->Field("AreaHeight", &LightConfiguration::m_areaHeight)
->Field("AreaMaxDistance", &LightConfiguration::m_areaMaxDistance)
->Field("AreaFOV", &LightConfiguration::m_areaFOV)
->Field("ProjectorDistance", &LightConfiguration::m_projectorRange)
->Field("ProjectorAttenuationBulbSize", &LightConfiguration::m_projectorAttenuationBulbSize)
->Field("ProjectorFOV", &LightConfiguration::m_projectorFOV)
->Field("ProjectorNearPlane", &LightConfiguration::m_projectorNearPlane)
->Field("ProjectorTexture", &LightConfiguration::m_projectorTexture)
->Field("ProjectorMaterial", &LightConfiguration::m_material)
->Field("Area X,Y,Z", &LightConfiguration::m_probeArea)
->Field("SortPriority", &LightConfiguration::m_probeSortPriority)
->Field("CubemapResolution", &LightConfiguration::m_probeCubemapResolution)
->Field("CubemapTexture", &LightConfiguration::m_probeCubemap)
->Field("BoxProject", &LightConfiguration::m_isBoxProjected)
->Field("BoxHeight", &LightConfiguration::m_boxHeight)
->Field("BoxLength", &LightConfiguration::m_boxLength)
->Field("BoxWidth", &LightConfiguration::m_boxWidth)
->Field("AttenuationFalloffMax", &LightConfiguration::m_attenFalloffMax)
->Field("ViewDistanceMultiplier", &LightConfiguration::m_viewDistMultiplier)
->Field("MinimumSpec", &LightConfiguration::m_minSpec)
->Field("CastShadowsSpec", &LightConfiguration::m_castShadowsSpec)
->Field("VoxelGIMode", &LightConfiguration::m_voxelGIMode)
->Field("UseVisAreas", &LightConfiguration::m_useVisAreas)
->Field("IndoorOnly", &LightConfiguration::m_indoorOnly)
->Field("AffectsThisAreaOnly", &LightConfiguration::m_affectsThisAreaOnly)
->Field("VolumetricFogOnly", &LightConfiguration::m_volumetricFogOnly)
->Field("VolumetricFog", &LightConfiguration::m_volumetricFog)
->Field("Deferred", &LightConfiguration::m_deferred)
->Field("TerrainShadows", &LightConfiguration::m_castTerrainShadows)
->Field("ShadowBias", &LightConfiguration::m_shadowBias)
->Field("ShadowResScale", &LightConfiguration::m_shadowResScale)
->Field("ShadowSlopeBias", &LightConfiguration::m_shadowSlopeBias)
->Field("ShadowUpdateMinRadius", &LightConfiguration::m_shadowUpdateMinRadius)
->Field("ShadowUpdateRatio", &LightConfiguration::m_shadowUpdateRatio)
->Field("AnimIndex", &LightConfiguration::m_animIndex)
->Field("AnimSpeed", &LightConfiguration::m_animSpeed)
->Field("AnimPhase", &LightConfiguration::m_animPhase)
->Field("CubemapId", &LightConfiguration::m_cubemapId);
}
}
// Private Static
bool LightConfiguration::VersionConverter(AZ::SerializeContext& context,
AZ::SerializeContext::DataElementNode& classElement)
{
// conversion from version 1:
// - Need to rename OmniRadius to MaxDistance
// - remove ShadowBlurStrength
if (classElement.GetVersion() <= 1)
{
int radiusIndex = classElement.FindElement(AZ_CRC("OmniRadius", 0x3fbb253e));
if (radiusIndex < 0)
{
return false;
}
AZ::SerializeContext::DataElementNode& radius = classElement.GetSubElement(radiusIndex);
radius.SetName("MaxDistance");
classElement.RemoveElementByName(AZ_CRC("ShadowBlurStrength", 0x70ac8e34));
}
// conversion from version 2:
// - Replace AreaSize with AreaWidth and AreaHeights
if (classElement.GetVersion() <= 2)
{
int areaIndex = classElement.FindElement(AZ_CRC("AreaSize", 0x287b852c));
if (areaIndex < 0)
{
return false;
}
//Get the size
AZ::SerializeContext::DataElementNode& area = classElement.GetSubElement(areaIndex);
AZ::Vector3 size;
area.GetData<AZ::Vector3>(size);
//Create width and height
int areaWidthIndex = classElement.AddElement<float>(context, "AreaWidth");
int areaHeightIndex = classElement.AddElement<float>(context, "AreaHeight");
AZ::SerializeContext::DataElementNode& areaWidth = classElement.GetSubElement(areaWidthIndex);
AZ::SerializeContext::DataElementNode& areaHeight = classElement.GetSubElement(areaHeightIndex);
//Set width and height data to x and y from the old size
areaWidth.SetData<float>(context, size.GetX());
areaHeight.SetData<float>(context, size.GetY());
classElement.RemoveElement(areaIndex);
}
// conversion from version 3:
// - MaxDistance turned into PointMaxDistance and AreaMaxDistance
// - AttenuationBulbSize turned into PointAttenuationBulbSize and ProjectorAttenuationBulbSize
// - Apply old area size to new probe area
if (classElement.GetVersion() <= 3)
{
int maxDistanceIndex = classElement.FindElement(AZ_CRC("MaxDistance", 0xfc2921b8));
int attenBulbIndex = classElement.FindElement(AZ_CRC("AttenuationBulbSize", 0x3ca0f5c0));
int areaWidthIndex = classElement.FindElement(AZ_CRC("AreaWidth", 0x137a1a2b));
int areaHeightIndex = classElement.FindElement(AZ_CRC("AreaHeight", 0xf2bf4149));
if (maxDistanceIndex < 0 || attenBulbIndex < 0 || areaWidthIndex < 0 || areaHeightIndex < 0)
{
return false;
}
//Get some values
AZ::SerializeContext::DataElementNode& maxDistance = classElement.GetSubElement(maxDistanceIndex);
AZ::SerializeContext::DataElementNode& attenBulbSize = classElement.GetSubElement(attenBulbIndex);
AZ::SerializeContext::DataElementNode& areaWidth = classElement.GetSubElement(areaWidthIndex);
AZ::SerializeContext::DataElementNode& areaHeight = classElement.GetSubElement(attenBulbIndex);
float maxDistVal, attenBulbVal, areaWidthVal, areaHeightVal;
maxDistance.GetData<float>(maxDistVal);
attenBulbSize.GetData<float>(attenBulbVal);
areaWidth.GetData<float>(areaWidthVal);
areaHeight.GetData<float>(areaHeightVal);
//Create AreaMaxDistance, PointMaxDistance, PointAttenuationBulbSize and ProjectorAttenuationBulbSize
int areaMaxDistIndex = classElement.AddElement<float>(context, "AreaMaxDistance");
int pointMaxDistIndex = classElement.AddElement<float>(context, "PointMaxDistance");
int pointAttenBulbIndex = classElement.AddElement<float>(context, "PointAttenuationBulbSize");
int projectorAttenBulbIndex = classElement.AddElement<float>(context, "ProjectorAttenuationBulbSize");
int areaXYZIndex = classElement.AddElement<AZ::Vector3>(context, "Area X,Y,Z");
AZ::SerializeContext::DataElementNode& areaMaxDist = classElement.GetSubElement(areaMaxDistIndex);
AZ::SerializeContext::DataElementNode& pointMaxDist = classElement.GetSubElement(pointMaxDistIndex);
AZ::SerializeContext::DataElementNode& pointAttenBulb = classElement.GetSubElement(pointAttenBulbIndex);
AZ::SerializeContext::DataElementNode& projectorAttenBulb = classElement.GetSubElement(projectorAttenBulbIndex);
AZ::SerializeContext::DataElementNode& areaXYZ = classElement.GetSubElement(areaXYZIndex);
//Set width and height data to x and y from the old size
areaMaxDist.SetData<float>(context, maxDistVal);
pointMaxDist.SetData<float>(context, maxDistVal);
pointAttenBulb.SetData<float>(context, attenBulbVal);
projectorAttenBulb.SetData<float>(context, attenBulbVal);
//Set new area XYZ values based on existing area values
areaXYZ.SetData<AZ::Vector3>(context, AZ::Vector3(maxDistVal, areaWidthVal, areaHeightVal));
//Remove old MaxDistance and AttenuationBulbSize
classElement.RemoveElement(maxDistanceIndex);
classElement.RemoveElement(attenBulbIndex);
}
// conversion from version 4:
// m_color: AZ::Vector4 -> AZ::Color
if (classElement.GetVersion() <= 4)
{
int colorIndex = classElement.FindElement(AZ_CRC("Color", 0x665648e9));
if (colorIndex == -1)
{
return false;
}
AZ::SerializeContext::DataElementNode& color = classElement.GetSubElement(colorIndex);
AZ::Vector4 colorVec;
color.GetData<AZ::Vector4>(colorVec);
AZ::Color colorVal(colorVec.GetX(), colorVec.GetY(), colorVec.GetZ(), colorVec.GetW());
color.Convert<AZ::Color>(context);
color.SetData(context, colorVal);
}
// conversion from version 6 to version 7:
// - Need to rename IgnoreVisAreas to UseVisAreas
// UseVisAreas is the Inverse of IgnoreVisAreas
if (classElement.GetVersion() <= 6)
{
int ignoreVisAreasIndex = classElement.FindElement(AZ_CRC("IgnoreVisAreas", 0x01823201));
if (ignoreVisAreasIndex < 0)
{
return false;
}
AZ::SerializeContext::DataElementNode& useVisAreasNode = classElement.GetSubElement(ignoreVisAreasIndex);
useVisAreasNode.SetName("UseVisAreas");
bool ignoreVisAreas = true;
if (!useVisAreasNode.GetData<bool>(ignoreVisAreas))
{
return false;
}
if (!useVisAreasNode.SetData<bool>(context, !ignoreVisAreas))
{
return false;
}
}
if (classElement.GetVersion() <= 7)
{
AZ::SerializeContext::DataElementNode* cubemapTexture = classElement.FindSubElement(AZ_CRC("CubemapTexture", 0xbf6d8df4));
if (!cubemapTexture)
{
return false;
}
AZStd::string cubemapPath;
if (!cubemapTexture->GetData<AZStd::string>(cubemapPath))
{
return false;
}
AzFramework::SimpleAssetReference<TextureAsset> cubemapSimpleAsset;
cubemapSimpleAsset.SetAssetPath(cubemapPath.c_str());
if (!classElement.RemoveElementByName(AZ_CRC("CubemapTexture", 0xbf6d8df4)))
{
return false;
}
if (!classElement.AddElementWithData<AzFramework::SimpleAssetReference<TextureAsset>>(context, "CubemapTexture", cubemapSimpleAsset))
{
return false;
}
}
return true;
}
bool LightComponent::TurnOnLight()
{
bool success = m_light.TurnOn();
if (success)
{
EBUS_EVENT_ID(GetEntityId(), LightComponentNotificationBus, LightTurnedOn);
}
return success;
}
bool LightComponent::TurnOffLight()
{
bool success = m_light.TurnOff();
if (success)
{
EBUS_EVENT_ID(GetEntityId(), LightComponentNotificationBus, LightTurnedOff);
}
return success;
}
///////////////////////////////////////////////////////////////////////
// Modifiers
void LightComponent::SetVisible(bool isVisible)
{
if (isVisible != m_configuration.m_visible)
{
m_configuration.m_visible = isVisible;
if (m_configuration.m_visible)
{
if (!TurnOnLight())
{
// unable to turn on light. This happens when trying to turn on a light was was previously not visible. Use UpdateRenderLight to
// update the light's visibility (by recreating it) to turn it on.
m_light.UpdateRenderLight(m_configuration);
}
}
else
{
TurnOffLight();
}
}
}
bool LightComponent::GetVisible()
{
return m_light.IsOn();
}
void LightComponent::SetColor(const AZ::Color& newColor)
{
if (m_configuration.m_color != newColor)
{
m_configuration.m_color = newColor;
m_light.UpdateRenderLight(m_configuration);
}
}
const AZ::Color LightComponent::GetColor()
{
return m_configuration.m_color;
}
void LightComponent::SetDiffuseMultiplier(float newMultiplier)
{
if (m_configuration.m_diffuseMultiplier != newMultiplier)
{
m_configuration.m_diffuseMultiplier = newMultiplier;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetDiffuseMultiplier()
{
return m_configuration.m_diffuseMultiplier;
}
void LightComponent::SetSpecularMultiplier(float newMultiplier)
{
if (m_configuration.m_specMultiplier != newMultiplier)
{
m_configuration.m_specMultiplier = newMultiplier;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetSpecularMultiplier()
{
return m_configuration.m_specMultiplier;
}
void LightComponent::SetAmbient(bool isAmbient)
{
if (isAmbient != m_configuration.m_ambient)
{
m_configuration.m_ambient = isAmbient;
m_light.UpdateRenderLight(m_configuration);
}
}
bool LightComponent::GetAmbient()
{
return m_configuration.m_ambient;
}
void LightComponent::SetPointMaxDistance(float newMaxDistance)
{
if (newMaxDistance != m_configuration.m_pointMaxDistance)
{
m_configuration.m_pointMaxDistance = newMaxDistance;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetPointMaxDistance()
{
return m_configuration.m_pointMaxDistance;
}
void LightComponent::SetPointAttenuationBulbSize(float newAttenuationBulbSize)
{
if (newAttenuationBulbSize != m_configuration.m_pointAttenuationBulbSize)
{
m_configuration.m_pointAttenuationBulbSize = newAttenuationBulbSize;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetPointAttenuationBulbSize()
{
return m_configuration.m_pointAttenuationBulbSize;
}
void LightComponent::SetAreaMaxDistance(float newMaxDistance)
{
if (newMaxDistance != m_configuration.m_areaMaxDistance)
{
m_configuration.m_areaMaxDistance = newMaxDistance;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetAreaMaxDistance()
{
return m_configuration.m_areaMaxDistance;
}
void LightComponent::SetAreaWidth(float newWidth)
{
if (newWidth != m_configuration.m_areaWidth)
{
m_configuration.m_areaWidth = newWidth;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetAreaWidth()
{
return m_configuration.m_areaWidth;
}
void LightComponent::SetAreaHeight(float newHeight)
{
if (newHeight != m_configuration.m_areaHeight)
{
m_configuration.m_areaHeight = newHeight;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetAreaHeight()
{
return m_configuration.m_areaHeight;
}
void LightComponent::SetAreaFOV(float newFOV)
{
if (newFOV != m_configuration.m_areaFOV)
{
m_configuration.m_areaFOV = newFOV;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetAreaFOV()
{
return m_configuration.m_areaFOV;
}
void LightComponent::SetProjectorMaxDistance(float newMaxDistance)
{
if (newMaxDistance != m_configuration.m_projectorRange)
{
m_configuration.m_projectorRange = newMaxDistance;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetProjectorMaxDistance()
{
return m_configuration.m_projectorRange;
}
void LightComponent::SetProjectorAttenuationBulbSize(float newAttenuationBulbSize)
{
if (newAttenuationBulbSize != m_configuration.m_projectorAttenuationBulbSize)
{
m_configuration.m_projectorAttenuationBulbSize = newAttenuationBulbSize;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetProjectorAttenuationBulbSize()
{
return m_configuration.m_projectorAttenuationBulbSize;
}
void LightComponent::SetProjectorFOV(float newFOV)
{
if (newFOV != m_configuration.m_projectorFOV)
{
m_configuration.m_projectorFOV = newFOV;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetProjectorFOV()
{
return m_configuration.m_projectorFOV;
}
void LightComponent::SetProjectorNearPlane(float newNearPlane)
{
if (newNearPlane != m_configuration.m_projectorNearPlane)
{
m_configuration.m_projectorNearPlane = newNearPlane;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetProjectorNearPlane()
{
return m_configuration.m_projectorNearPlane;
}
void LightComponent::SetProbeAreaDimensions(const AZ::Vector3& newDimensions)
{
if (newDimensions != m_configuration.m_probeArea)
{
m_configuration.m_probeArea = newDimensions;
m_light.UpdateRenderLight(m_configuration);
}
}
const AZ::Vector3 LightComponent::GetProbeAreaDimensions()
{
return m_configuration.m_probeArea;
}
void LightComponent::SetProbeSortPriority(AZ::u32 newPriority)
{
if (newPriority != m_configuration.m_probeSortPriority)
{
m_configuration.m_probeSortPriority = newPriority;
m_light.UpdateRenderLight(m_configuration);
}
}
AZ::u32 LightComponent::GetProbeSortPriority()
{
return m_configuration.m_probeSortPriority;
}
void LightComponent::SetProbeBoxProjected(bool isProbeBoxProjected)
{
if (isProbeBoxProjected != m_configuration.m_isBoxProjected)
{
m_configuration.m_isBoxProjected = isProbeBoxProjected;
m_light.UpdateRenderLight(m_configuration);
}
}
bool LightComponent::GetProbeBoxProjected()
{
return m_configuration.m_isBoxProjected;
}
void LightComponent::SetProbeBoxHeight(float newHeight)
{
if (newHeight != m_configuration.m_boxHeight)
{
m_configuration.m_boxHeight = newHeight;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetProbeBoxHeight()
{
return m_configuration.m_boxHeight;
}
void LightComponent::SetProbeBoxLength(float newLength)
{
if (newLength != m_configuration.m_boxLength)
{
m_configuration.m_boxLength = newLength;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetProbeBoxLength()
{
return m_configuration.m_boxLength;
}
void LightComponent::SetProbeBoxWidth(float newWidth)
{
if (newWidth != m_configuration.m_boxWidth)
{
m_configuration.m_boxWidth = newWidth;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetProbeBoxWidth()
{
return m_configuration.m_boxWidth;
}
void LightComponent::SetProbeAttenuationFalloff(float newAttenuationFalloff)
{
if (newAttenuationFalloff != m_configuration.m_attenFalloffMax)
{
m_configuration.m_attenFalloffMax = newAttenuationFalloff;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetProbeAttenuationFalloff()
{
return m_configuration.m_attenFalloffMax;
}
void LightComponent::SetProbeFade(float fade)
{
AZ_Warning("Lighting", 0.0f <= fade && fade <= 1.0f, "SetProbeFade value %f out of range. Clamping to [0,1]", fade);
fade = AZ::GetClamp(fade, 0.0f, 1.0f);
if (fade != m_configuration.m_probeFade)
{
m_configuration.m_probeFade = fade;
m_light.UpdateRenderLight(m_configuration);
}
}
float LightComponent::GetProbeFade()
{
return m_configuration.m_probeFade;
}
///////////////////////////////////////////////////////////
void LightComponent::ToggleLight()
{
if (m_light.IsOn())
{
TurnOffLight();
}
else
{
TurnOnLight();
}
}
void LightComponent::SetLightState(State state)
{
switch (state)
{
case LightComponentRequests::State::On:
{
TurnOnLight();
}
break;
case LightComponentRequests::State::Off:
{
TurnOffLight();
}
break;
}
}
IRenderNode* LightComponent::GetRenderNode()
{
return m_light.GetRenderNode();
}
float LightComponent::GetRenderNodeRequestBusOrder() const
{
return s_renderNodeRequestBusOrder;
}
const float LightComponent::s_renderNodeRequestBusOrder = 500.f;
LightComponent::LightComponent()
{
}
LightComponent::~LightComponent()
{
}
void LightComponent::Init()
{
}
void LightComponent::Activate()
{
const AZ::EntityId entityId = GetEntityId();
m_light.SetEntity(entityId);
m_light.CreateRenderLight(m_configuration);
LightComponentRequestBus::Handler::BusConnect(entityId);
RenderNodeRequestBus::Handler::BusConnect(entityId);
if (m_configuration.m_onInitially)
{
m_light.TurnOn();
}
else
{
m_light.TurnOff();
}
}
void LightComponent::Deactivate()
{
LightComponentRequestBus::Handler::BusDisconnect();
RenderNodeRequestBus::Handler::BusDisconnect();
m_light.DestroyRenderLight();
m_light.SetEntity(AZ::EntityId());
}
LightConfiguration::LightConfiguration()
: m_lightType(LightType::Point)
, m_visible(true)
, m_onInitially(true)
, m_pointMaxDistance(2.f)
, m_pointAttenuationBulbSize(0.05f)
, m_areaMaxDistance(2.f)
, m_areaWidth(5.f)
, m_areaHeight(5.f)
, m_areaFOV(45.0f)
, m_projectorAttenuationBulbSize(0.05f)
, m_projectorRange(5.f)
, m_projectorFOV(90.f)
, m_projectorNearPlane(0)
, m_probeSortPriority(0)
, m_probeArea(20.0f, 20.0f, 20.0f)
, m_probeCubemapResolution(ResolutionSetting::ResDefault)
, m_isBoxProjected(false)
, m_boxWidth(20.0f)
, m_boxHeight(20.0f)
, m_boxLength(20.0f)
, m_attenFalloffMax(0.3f)
, m_probeFade(1.0f)
, m_minSpec(EngineSpec::Low)
, m_viewDistMultiplier(1.f)
, m_castShadowsSpec(EngineSpec::Never)
, m_voxelGIMode(IRenderNode::VM_None)
, m_color(1.f, 1.f, 1.f, 1.f)
, m_diffuseMultiplier(1.f)
, m_specMultiplier(1.f)
, m_affectsThisAreaOnly(true)
, m_useVisAreas(true)
, m_volumetricFog(true)
, m_volumetricFogOnly(false)
, m_indoorOnly(false)
, m_ambient(false)
, m_deferred(true)
, m_animIndex(0)
, m_animSpeed(1.f)
, m_animPhase(0.f)
, m_castTerrainShadows(false)
, m_shadowBias(1.f)
, m_shadowSlopeBias(1.f)
, m_shadowResScale(1.f)
, m_shadowUpdateMinRadius(10.f)
, m_shadowUpdateRatio(1.f)
, m_cubemapId(AZ::Uuid::Create())
{
}
} // namespace LmbrCentral
@@ -1,303 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/base.h>
#include <AzCore/Component/Component.h>
#include <AzCore/Component/ComponentBus.h>
#include <AzCore/Math/Color.h>
#include <AzCore/Math/Uuid.h>
#include <AzFramework/Asset/SimpleAsset.h>
#include <LmbrCentral/Rendering/LightComponentBus.h>
#include <LmbrCentral/Rendering/RenderNodeBus.h>
#include <LmbrCentral/Rendering/MaterialAsset.h>
#include "LightInstance.h"
#include <IEntityRenderState.h>
namespace LmbrCentral
{
/*!
* Stores configuration settings for engine lights.
* - Common color and shader settings
* - Common shadow-casting settings
* - Settings unique to different light types
*/
class LightConfiguration
{
public:
AZ_TYPE_INFO(LightConfiguration, "{F4CC7BB4-C541-480C-88FC-C5A8F37CC67F}");
// LY renderer supported light types.
enum class LightType : AZ::u32
{
Point = 0, ///> Omni-directional point light
Area, ///> Area/box light
Projector, ///> Texture projector light
Probe, ///> Environment probe
};
// Texture resolution settings.
enum class ResolutionSetting : AZ::u32
{
ResDefault = 256,
Res32 = 32,
Res64 = 64,
Res128 = 128,
Res256 = 256,
Res512 = 512,
};
LightConfiguration();
virtual ~LightConfiguration() {};
static void Reflect(AZ::ReflectContext* context);
//! The type of render light (point/omni, projector, area, or environment probe).
LightType m_lightType;
//! Turned on by default?
bool m_onInitially;
//! Currently visible?
bool m_visible;
//! Point light settings
float m_pointMaxDistance;
float m_pointAttenuationBulbSize;
//! Settings for area lights
float m_areaWidth;
float m_areaHeight;
float m_areaMaxDistance;
float m_areaFOV;
//! Settings for projector lights
float m_projectorRange;
float m_projectorAttenuationBulbSize;
float m_projectorFOV;
float m_projectorNearPlane;
AzFramework::SimpleAssetReference<TextureAsset> m_projectorTexture;
AzFramework::SimpleAssetReference<MaterialAsset> m_material;
//! Settings for environment lights (probes)
AZ::Vector3 m_probeArea;
AZ::u32 m_probeSortPriority;
ResolutionSetting m_probeCubemapResolution;
AzFramework::SimpleAssetReference<TextureAsset> m_probeCubemap;
//parameter to enable box projection
bool m_isBoxProjected;
float m_boxWidth;
float m_boxHeight;
float m_boxLength;
float m_attenFalloffMax;
float m_probeFade;
//! Settings common to all LY engine lights
EngineSpec m_minSpec;
float m_viewDistMultiplier;
EngineSpec m_castShadowsSpec;
IRenderNode::EVoxelGIMode m_voxelGIMode;
AZ::Color m_color;
float m_diffuseMultiplier;
float m_specMultiplier;
bool m_affectsThisAreaOnly;
bool m_useVisAreas;
bool m_indoorOnly;
bool m_ambient;
bool m_deferred;
AZ::u32 m_animIndex;
float m_animSpeed;
float m_animPhase;
bool m_volumetricFog;
bool m_volumetricFogOnly;
bool m_castTerrainShadows;
//! Shadow settings
float m_shadowBias;
float m_shadowSlopeBias;
float m_shadowResScale;
float m_shadowUpdateMinRadius;
float m_shadowUpdateRatio;
// Need to keep a unique Id to use as cubemap name
AZ::Uuid m_cubemapId;
// \todo clip bounds - artists aren't using it. Includes fade dimensions.
AZ::EntityId m_editorEntityId; // Editor-only, not reflected.
// Property event-handlers implemented in editor component.
virtual AZ::Crc32 GetAmbientLightVisibility() const { return 0; }
virtual AZ::Crc32 GetPointLightVisibility() const { return 0; }
virtual AZ::Crc32 GetProjectorLightVisibility() const { return 0; }
virtual AZ::Crc32 GetProbeLightVisibility() const { return 0; }
virtual AZ::Crc32 GetShadowSpecVisibility() const { return 0; }
virtual AZ::Crc32 GetShadowSettingsVisibility() const { return 0; }
virtual AZ::Crc32 GetAreaSettingVisibility() const { return 0; }
virtual AZ::Crc32 MinorPropertyChanged() { return 0; }
virtual AZ::Crc32 MajorPropertyChanged() { return 0; }
virtual AZ::Crc32 OnAnimationSettingChanged() { return 0; }
virtual AZ::Crc32 OnCubemapAssetChanged() { return 0; }
virtual bool CanGenerateCubemap() const { return false; }
private:
static bool VersionConverter(AZ::SerializeContext& context,
AZ::SerializeContext::DataElementNode& classElement);
};
/*!
* In-game light component.
*/
class LightComponent
: public AZ::Component
, public LightComponentRequestBus::Handler
, public RenderNodeRequestBus::Handler
{
public:
friend class EditorLightComponent;
AZ_COMPONENT(LightComponent, "{6B9AB512-CA8A-4D2B-B570-DF128EA7CE6A}");
LightComponent();
~LightComponent() override;
//////////////////////////////////////////////////////////////////////////
// AZ::Component interface implementation
void Init() override;
void Activate() override;
void Deactivate() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// LightComponentRequests::Bus::Handler interface implementation
void SetLightState(State state) override;
bool TurnOnLight() override;
bool TurnOffLight() override;
void ToggleLight() override;
////////////////////////////////////
// Modifiers
void SetVisible(bool isVisible) override;
bool GetVisible() override;
void SetColor(const AZ::Color& newColor) override;
const AZ::Color GetColor() override;
void SetDiffuseMultiplier(float newMultiplier) override;
float GetDiffuseMultiplier() override;
void SetSpecularMultiplier(float newMultiplier) override;
float GetSpecularMultiplier() override;
void SetAmbient(bool isAmbient) override;
bool GetAmbient() override;
void SetPointMaxDistance(float newMaxDistance) override;
float GetPointMaxDistance() override;
void SetPointAttenuationBulbSize(float newAttenuationBulbSize) override;
float GetPointAttenuationBulbSize() override;
void SetAreaMaxDistance(float newMaxDistance) override;
float GetAreaMaxDistance() override;
void SetAreaWidth(float newWidth) override;
float GetAreaWidth() override;
void SetAreaHeight(float newHeight) override;
float GetAreaHeight() override;
void SetAreaFOV(float newFOV) override;
float GetAreaFOV() override;
void SetProjectorMaxDistance(float newMaxDistance) override;
float GetProjectorMaxDistance() override;
void SetProjectorAttenuationBulbSize(float newAttenuationBulbSize) override;
float GetProjectorAttenuationBulbSize() override;
void SetProjectorFOV(float newFOV) override;
float GetProjectorFOV() override;
void SetProjectorNearPlane(float newNearPlane) override;
float GetProjectorNearPlane() override;
// Environment Probe Settings
void SetProbeAreaDimensions(const AZ::Vector3& newDimensions) override;
const AZ::Vector3 GetProbeAreaDimensions() override;
void SetProbeSortPriority(AZ::u32 newPriority) override;
AZ::u32 GetProbeSortPriority() override;
void SetProbeBoxProjected(bool isProbeBoxProjected) override;
bool GetProbeBoxProjected() override;
void SetProbeBoxHeight(float newHeight) override;
float GetProbeBoxHeight() override;
void SetProbeBoxLength(float newLength) override;
float GetProbeBoxLength() override;
void SetProbeBoxWidth(float newWidth) override;
float GetProbeBoxWidth() override;
void SetProbeAttenuationFalloff(float newAttenuationFalloff) override;
float GetProbeAttenuationFalloff() override;
void SetProbeFade(float fade) override;
float GetProbeFade() override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// RenderNodeRequestBus::Handler interface implementation
IRenderNode* GetRenderNode() override;
float GetRenderNodeRequestBusOrder() const override;
static const float s_renderNodeRequestBusOrder;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("LightService", 0xfd7fa928));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
required.push_back(AZ_CRC("TransformService", 0x8ee22c50));
}
static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& /*dependent*/)
{
}
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("LightService", 0xfd7fa928));
}
static void Reflect(AZ::ReflectContext* context);
//////////////////////////////////////////////////////////////////////////
protected:
LightConfiguration m_configuration;
LightInstance m_light;
};
} // namespace LmbrCentral
@@ -1,442 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include <AzCore/Math/Quaternion.h>
#include <MathConversion.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Component/Entity.h>
#include <I3DEngine.h>
#include "LightInstance.h"
#include "LightComponent.h"
#include "LensFlareComponent.h"
namespace
{
const float kDefaultLightFrustumAngle = 45.f;
const uint8 kDefaultLensOpticsFrustumAngle = 255;
void UpdateLightFlag(bool enable, int mask, unsigned int& flags)
{
if (enable)
{
flags |= mask;
}
else
{
flags &= ~mask;
}
}
AZ::u32 CreateLightId(AZ::EntityId entityId)
{
// Renderer requires a non-zero value, but doesn't care what it actually means.
// This is used only for debug coloring and tie-breaking sorts.
// Use the timestamp half of our entity Id.
const AZ::u32 lowerEntityId = static_cast<AZ::u32>(static_cast<AZ::u64>(entityId) >> 32);
return lowerEntityId;
}
const char* GetEntityName(AZ::EntityId entityId)
{
AZ::Entity* entity = nullptr;
EBUS_EVENT_RESULT(entity, AZ::ComponentApplicationBus, FindEntity, entityId);
return (entity ? entity->GetName().c_str() : "<unknown>");
}
void LightConfigToLightParams(const LmbrCentral::LightConfiguration& configuration, AZ::EntityId entityId, int configSpec, CDLight& lightParams)
{
// The light cannot be ambient if it is an environment probe
bool ambient = configuration.m_ambient;
if (configuration.m_lightType == LmbrCentral::LightConfiguration::LightType::Probe)
{
ambient = false;
}
lightParams.SetPosition(Vec3_Zero);
lightParams.m_fLightFrustumAngle = kDefaultLightFrustumAngle;
lightParams.m_Flags = 0;
lightParams.m_LensOpticsFrustumAngle = kDefaultLensOpticsFrustumAngle;
Vec3 color = AZColorToLYVec3(configuration.m_color);
color *= configuration.m_diffuseMultiplier;
lightParams.SetLightColor(ColorF(color.x, color.y, color.z, 1.f));
lightParams.SetSpecularMult(configuration.m_specMultiplier);
lightParams.m_nLightStyle = configuration.m_animIndex; // "light style" is really a light animation curve index
lightParams.SetAnimSpeed(configuration.m_animSpeed); // maps [0, 4] to [0, 255]
lightParams.m_nLightPhase = static_cast<AZ::u8>(configuration.m_animPhase * 255.f); // maps [0, 1] to [0, 255]
lightParams.m_nEntityId = CreateLightId(entityId);
UpdateLightFlag(!configuration.m_useVisAreas, DLF_IGNORES_VISAREAS, lightParams.m_Flags);
UpdateLightFlag(configuration.m_indoorOnly, DLF_INDOOR_ONLY, lightParams.m_Flags);
UpdateLightFlag(configuration.m_affectsThisAreaOnly, DLF_THIS_AREA_ONLY, lightParams.m_Flags);
UpdateLightFlag(ambient, DLF_AMBIENT, lightParams.m_Flags);
UpdateLightFlag(configuration.m_deferred, DLF_DEFERRED_LIGHT, lightParams.m_Flags);
UpdateLightFlag(configuration.m_volumetricFog, DLF_VOLUMETRIC_FOG, lightParams.m_Flags);
UpdateLightFlag(configuration.m_volumetricFogOnly, DLF_VOLUMETRIC_FOG_ONLY, lightParams.m_Flags);
UpdateLightFlag(configuration.m_castTerrainShadows, DLF_CAST_TERRAIN_SHADOWS, lightParams.m_Flags);
if (static_cast<AZ::u32>(configSpec) >= static_cast<AZ::u32>(configuration.m_castShadowsSpec))
{
lightParams.m_Flags |= DLF_CASTSHADOW_MAPS;
}
//Probe won't cast shadow. Enable this flag wrongly for probe could lead to wrong bbox.
if (configuration.m_lightType == LmbrCentral::LightConfiguration::LightType::Probe)
{
lightParams.m_Flags &= ~DLF_CASTSHADOW_MAPS;
}
lightParams.m_fShadowBias = configuration.m_shadowBias;
lightParams.m_fShadowSlopeBias = configuration.m_shadowSlopeBias;
lightParams.m_fShadowResolutionScale = configuration.m_shadowResScale;
lightParams.m_fShadowUpdateMinRadius = configuration.m_shadowUpdateMinRadius;
lightParams.m_nShadowUpdateRatio = max((uint16)1, (uint16)(configuration.m_shadowUpdateRatio * (1 << DL_SHADOW_UPDATE_SHIFT)));
switch (configuration.m_lightType)
{
case LmbrCentral::LightConfiguration::LightType::Point:
{
lightParams.m_fRadius = configuration.m_pointMaxDistance;
lightParams.m_fAttenuationBulbSize = configuration.m_pointAttenuationBulbSize;
lightParams.m_Flags |= DLF_POINT;
}
break;
case LmbrCentral::LightConfiguration::LightType::Area:
{
lightParams.m_fRadius = configuration.m_areaMaxDistance;
lightParams.m_fAreaWidth = configuration.m_areaWidth;
lightParams.m_fAreaHeight = configuration.m_areaHeight;
lightParams.m_fLightFrustumAngle = configuration.m_areaFOV;
lightParams.m_Flags |= DLF_AREA_LIGHT;
}
break;
case LmbrCentral::LightConfiguration::LightType::Projector:
{
lightParams.m_fRadius = configuration.m_projectorRange;
lightParams.m_fLightFrustumAngle = configuration.m_projectorFOV * 0.5f;
lightParams.m_fProjectorNearPlane = configuration.m_projectorNearPlane;
lightParams.m_fAttenuationBulbSize = configuration.m_projectorAttenuationBulbSize;
lightParams.m_Flags |= DLF_PROJECT;
const char* texturePath = configuration.m_projectorTexture.GetAssetPath().c_str();
const int flags = FT_DONT_STREAM;
if (gEnv->pRenderer)
{
lightParams.m_pLightImage = gEnv->pRenderer->EF_LoadTexture(texturePath, flags);
if (!lightParams.m_pLightImage || !lightParams.m_pLightImage->IsTextureLoaded())
{
GetISystem()->Warning(VALIDATOR_MODULE_RENDERER, VALIDATOR_WARNING, 0, texturePath,
"Light projector texture not found: %s", texturePath);
lightParams.m_pLightImage = gEnv->pRenderer->EF_LoadTexture("Textures/defaults/red.dds", flags);
}
}
}
break;
case LmbrCentral::LightConfiguration::LightType::Probe:
{
lightParams.m_ProbeExtents.x = configuration.m_probeArea.GetX() / 2.0f;
lightParams.m_ProbeExtents.y = configuration.m_probeArea.GetY() / 2.0f;
lightParams.m_ProbeExtents.z = configuration.m_probeArea.GetZ() / 2.0f;
lightParams.m_fRadius = lightParams.m_ProbeExtents.len();
lightParams.m_nSortPriority = configuration.m_probeSortPriority;
lightParams.m_fProbeAttenuation = configuration.m_probeFade;
//projection
if (configuration.m_isBoxProjected)
{
//enable box projection
lightParams.m_Flags |= DLF_BOX_PROJECTED_CM;
}
lightParams.m_fBoxHeight = configuration.m_boxHeight;
lightParams.m_fBoxLength = configuration.m_boxLength;
lightParams.m_fBoxWidth = configuration.m_boxWidth;
lightParams.SetFalloffMax(configuration.m_attenFalloffMax);
lightParams.ReleaseCubemaps();
const AZStd::string& specularMap = configuration.m_probeCubemap.GetAssetPath();
if (!specularMap.empty())
{
AZStd::string diffuseMap = specularMap;
AZStd::string::size_type dotPos = specularMap.find_last_of('.');
if (dotPos != AZStd::string::npos)
{
diffuseMap.insert(dotPos, "_diff");
}
if (gEnv->pRenderer)
{
lightParams.SetSpecularCubemap(gEnv->pRenderer->EF_LoadCubemapTexture(specularMap.c_str(), FT_DONT_STREAM));
lightParams.SetDiffuseCubemap(gEnv->pRenderer->EF_LoadCubemapTexture(diffuseMap.c_str(), FT_DONT_STREAM));
}
if (lightParams.GetDiffuseCubemap() && lightParams.GetSpecularCubemap())
{
lightParams.m_Flags |= DLF_DEFERRED_CUBEMAPS;
}
else
{
if (!lightParams.GetSpecularCubemap())
{
AZ_Warning("Light", false,
"Failed to load specular cubemap \"%s\" for light \"%s\".",
specularMap.c_str(),
GetEntityName(entityId));
}
if (!lightParams.GetDiffuseCubemap())
{
AZ_Warning("Light", false,
"Failed to load diffuse cubemap \"%s\" for light \"%s\".",
diffuseMap.c_str(),
GetEntityName(entityId));
}
lightParams.m_Flags &= ~DLF_DEFERRED_CUBEMAPS;
lightParams.m_Flags |= DLF_POINT;
lightParams.ReleaseCubemaps();
}
}
else
{
// Disable the light
lightParams.m_Flags = DLF_FAKE;
}
}
break;
}
}
void LensFlareConfigToLightParams(const LmbrCentral::LensFlareConfiguration& configuration, [[maybe_unused]] AZ::EntityId entityId, int, CDLight& lightParams)
{
lightParams.m_Flags |= DLF_FAKE; // As long as deferred lights are separate components disable the actual deferred light
ColorF color = AZVec3ToLYVec3(configuration.m_tint);
color.a = configuration.m_tintAlpha / 255.0f;
lightParams.SetLightColor(ColorF(1.f, 1.f, 1.f, 1.f)); //Set the light color to white. We can tint the lens flare directly
if (configuration.m_syncAnimWithLight)
{
lightParams.m_nLightStyle = static_cast<AZ::u8>(configuration.m_syncAnimIndex); // This is really a light animation curve ID
lightParams.SetAnimSpeed(configuration.m_syncAnimSpeed); // maps [0, 4] to [0, 255]
lightParams.m_nLightPhase = static_cast<AZ::u8>(configuration.m_syncAnimPhase * 255.f); // maps [0, 1] to [0, 255]
}
else if (configuration.m_attachToSun)
{
gEnv->p3DEngine->SetSunAnimIndex(static_cast<AZ::u8>(configuration.m_animIndex)); // This is really a light animation curve ID
gEnv->p3DEngine->SetSunAnimSpeed(configuration.m_animSpeed); // maps [0, 4] to [0, 255]
gEnv->p3DEngine->SetSunAnimPhase(static_cast<AZ::u8>(configuration.m_animPhase * 255.f)); // maps [0, 1] to [0, 255]
}
else
{
lightParams.m_nLightStyle = static_cast<AZ::u8>(configuration.m_animIndex); // This is really a light animation curve ID
lightParams.SetAnimSpeed(configuration.m_animSpeed); // maps [0, 4] to [0, 255]
lightParams.m_nLightPhase = static_cast<AZ::u8>(configuration.m_animPhase * 255.f); // maps [0, 1] to [0, 255]
}
lightParams.m_LensOpticsFrustumAngle = static_cast<AZ::u8>(configuration.m_lensFlareFrustumAngle / 360.f * 255.f);
UpdateLightFlag(configuration.m_affectsThisAreaOnly, DLF_THIS_AREA_ONLY, lightParams.m_Flags);
UpdateLightFlag(!configuration.m_useVisAreas, DLF_IGNORES_VISAREAS, lightParams.m_Flags);
UpdateLightFlag(configuration.m_indoorOnly, DLF_INDOOR_ONLY, lightParams.m_Flags);
UpdateLightFlag(configuration.m_attachToSun, DLF_ATTACH_TO_SUN, lightParams.m_Flags);
if (!configuration.m_lensFlare.empty())
{
int lensOpticsID = 0;
if (gEnv->pOpticsManager->Load(configuration.m_lensFlare.c_str(), lensOpticsID))
{
IOpticsElementBase* flare = gEnv->pOpticsManager->GetOptics(lensOpticsID);
lightParams.SetLensOpticsElement(flare);
lightParams.SetOpticsParams({ configuration.m_brightness, configuration.m_size, { color.r, color.g, color.b, color.a }, true });
}
else
{
AZ_Warning("LensFlare", false, "Failed to load lens flare \"%s\" for entity \"%s\".", configuration.m_lensFlare.c_str(), GetEntityName(entityId));
}
}
}
}
namespace LmbrCentral
{
LightInstance::LightInstance()
: m_renderLight(nullptr)
{
}
LightInstance::~LightInstance()
{
DestroyRenderLight();
}
void LightInstance::SetEntity(AZ::EntityId entityId)
{
if (m_entityId.IsValid())
{
AZ::TransformNotificationBus::Handler::BusDisconnect();
}
m_entityId = entityId;
if (m_entityId.IsValid())
{
AZ::TransformNotificationBus::Handler::BusConnect(m_entityId);
}
}
void LightInstance::OnTransformChanged(const AZ::Transform&, const AZ::Transform& world)
{
if (m_renderLight)
{
CDLight* lightProperties = &m_renderLight->GetLightProperties();
Matrix34 worldMatrix = AZTransformToLYTransform(world);
worldMatrix.OrthonormalizeFast(); // Lights do not support scale.
lightProperties->SetPosition(worldMatrix.GetTranslation());
lightProperties->SetMatrix(worldMatrix);
m_renderLight->SetMatrix(worldMatrix);
}
}
bool LightInstance::TurnOn()
{
if (!m_renderLight)
{
return false;
}
m_renderLight->SetRndFlags(ERF_HIDDEN, false);
return true;
}
bool LightInstance::TurnOff()
{
if (!m_renderLight)
{
return false;
}
m_renderLight->SetRndFlags(ERF_HIDDEN, true);
return true;
}
bool LightInstance::IsOn() const
{
if (!m_renderLight)
{
return false;
}
return 0 == (m_renderLight->GetRndFlags() & ERF_HIDDEN);
}
void LightInstance::CreateRenderLight(const LightConfiguration& configuration)
{
CreateRenderLightInternal(configuration, LightConfigToLightParams);
#if defined(FEATURE_SVO_GI)
if (m_renderLight)
{
m_renderLight->SetDesiredVoxelGIMode(configuration.m_voxelGIMode);
}
#endif
}
void LightInstance::CreateRenderLight(const LensFlareConfiguration& configuration)
{
CreateRenderLightInternal(configuration, LensFlareConfigToLightParams);
}
void LightInstance::UpdateRenderLight(const LightConfiguration& configuration)
{
// ERF_HIDDEN is used to turn on/off the light, so cache it here and set it back later
bool isHidden = m_renderLight ? (m_renderLight->GetRndFlags() & ERF_HIDDEN) == ERF_HIDDEN : false;
DestroyRenderLight();
CreateRenderLight(configuration);
if (m_renderLight)
{
m_renderLight->SetRndFlags(ERF_HIDDEN, isHidden);
}
}
void LightInstance::UpdateRenderLight(const LensFlareConfiguration& configuration)
{
// ERF_HIDDEN is used to turn on/off the light, so cache it here and set it back later
bool isHidden = m_renderLight ? (m_renderLight->GetRndFlags() & ERF_HIDDEN) == ERF_HIDDEN : false;
DestroyRenderLight();
CreateRenderLight(configuration);
if (m_renderLight)
{
m_renderLight->SetRndFlags(ERF_HIDDEN, isHidden);
}
}
void LightInstance::DestroyRenderLight()
{
if (m_renderLight)
{
m_renderLight->ReleaseNode();
m_renderLight = nullptr;
}
}
IRenderNode* LightInstance::GetRenderNode()
{
return m_renderLight;
}
template <typename ConfigurationType, typename ConfigToLightParamsFunc>
void LightInstance::CreateRenderLightInternal(const ConfigurationType& configuration, ConfigToLightParamsFunc configToLightParams)
{
if (m_renderLight || !configuration.m_visible || !gEnv->p3DEngine)
{
return;
}
ICVar* cvarSysSpecLight = gEnv->pConsole->GetCVar("e_LightQuality");
const int configSpec = cvarSysSpecLight ? cvarSysSpecLight->GetIVal() : gEnv->pSystem->GetConfigSpec(true);
if (static_cast<AZ::u32>(configSpec) < static_cast<AZ::u32>(configuration.m_minSpec))
{
// Light is disabled in the active system spec.
return;
}
CDLight lightParams;
configToLightParams(configuration, m_entityId, configSpec, lightParams);
m_renderLight = gEnv->p3DEngine->CreateLightSource();
if (!configuration.m_material.GetAssetPath().empty())
{
m_renderLight->SetMaterial(gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(configuration.m_material.GetAssetPath().c_str()));
}
m_renderLight->SetLightProperties(lightParams);
m_renderLight->SetMinSpec(static_cast<int>(configuration.m_minSpec));
m_renderLight->SetViewDistanceMultiplier(configuration.m_viewDistMultiplier);
AZ::Transform parentTransform = AZ::Transform::CreateIdentity();
EBUS_EVENT_ID_RESULT(parentTransform, m_entityId, AZ::TransformBus, GetWorldTM);
OnTransformChanged(AZ::Transform::CreateIdentity(), parentTransform);
}
} // namespace LmbrCentral
@@ -1,68 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/TransformBus.h>
#include <AzCore/Component/EntityId.h>
struct ILightSource;
struct IRenderNode;
class CDLight;
namespace LmbrCentral
{
class LightConfiguration;
class LensFlareConfiguration;
/*!
* Renderer specific implementation of a Renderer light
*/
class LightInstance final
: private AZ::TransformNotificationBus::Handler
{
public:
AZ_TYPE_INFO(LightInstance, "{844D6585-6613-4E0D-BBA7-C37073B84F5F}");
LightInstance();
~LightInstance();
void SetEntity(AZ::EntityId id);
void CreateRenderLight(const LightConfiguration& configuration);
void UpdateRenderLight(const LightConfiguration& configuration);
void CreateRenderLight(const LensFlareConfiguration& configuration);
void UpdateRenderLight(const LensFlareConfiguration& configuration);
void DestroyRenderLight();
IRenderNode* GetRenderNode();
bool IsOn() const;
bool TurnOn();
bool TurnOff();
//////////////////////////////////////////////////////////////////////////
// AZ::TransformNotificationBus::Handler interface implementation
void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override;
//////////////////////////////////////////////////////////////////////////
private:
template <typename ConfigurationType, typename ConfigToLightParamsFunc>
void CreateRenderLightInternal(const ConfigurationType& configuration, ConfigToLightParamsFunc configToLightParams);
AZ::EntityId m_entityId;
ILightSource* m_renderLight;
};
} // namespace LmbrCentral
@@ -262,119 +262,4 @@ namespace LmbrCentral
extensions.push_back(CRY_GEOMETRY_FILE_EXT);
}
GeomCacheAssetHandler::~GeomCacheAssetHandler()
{
Unregister();
}
AZ::Data::AssetPtr GeomCacheAssetHandler::CreateAsset([[maybe_unused]] const AZ::Data::AssetId& id, const AZ::Data::AssetType& type)
{
(void)type;
AZ_Assert(type == AZ::AzTypeInfo<GeomCacheAsset>::Uuid(), "Invalid asset type! We handle only 'GeomCacheAsset'");
return aznew GeomCacheAsset();
}
void GeomCacheAssetHandler::GetCustomAssetStreamInfoForLoad(AZ::Data::AssetStreamInfo& streamInfo)
{
// The GeomCache system only takes in a file name for loading, not a memory buffer.
// If we set our stream data length to 0, the asset system will skip any file I/O for reading the data, and will instead
// go directly into the AssetHandler for processing.
streamInfo.m_dataLen = 0;
}
AZ::Data::AssetHandler::LoadResult GeomCacheAssetHandler::LoadAssetData(
const AZ::Data::Asset<AZ::Data::AssetData>& asset,
AZStd::shared_ptr<AZ::Data::AssetDataStream> stream,
const AZ::Data::AssetFilterCB& /*assetLoadFilterCB*/)
{
const char* assetPath = stream->GetFilename();
AZ_Assert(asset.GetType() == AZ::AzTypeInfo<GeomCacheAsset>::Uuid(), "Invalid asset type! We only load 'GeomCacheAsset'");
if (GeomCacheAsset* geomCacheAsset = asset.GetAs<GeomCacheAsset>())
{
AZ_Assert(!geomCacheAsset->m_geomCache.get(), "Attempting to create geom cache without cleaning up the old one.");
// Strip the alias. GeomCache instances are stored in a dictionary by their path,
// so to share instances with legacy cry entities, we need to use the same un-aliased format.
StripAssetAlias(assetPath);
//Load GeomCaches synchronously, there is no Async support currently in the 3DEngine.
//Assets can stream asynchronously but this load step must be synchronous.
_smart_ptr<IGeomCache> geomCache = gEnv->p3DEngine->LoadGeomCache(assetPath);
if (geomCache)
{
geomCache->SetProcessedByRenderNode(false);
geomCacheAsset->m_geomCache = geomCache;
}
else
{
#if defined(AZ_ENABLE_TRACING)
AZStd::string assetDescription = asset.ToString<AZStd::string>();
AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetDescription, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetPathById, asset.GetId());
AZ_Error("GeomCacheAssetHandler", false, "Failed to load geom cache asset %s", assetDescription.c_str());
#endif // AZ_ENABLE_TRACING
}
return AZ::Data::AssetHandler::LoadResult::LoadComplete;
}
return AZ::Data::AssetHandler::LoadResult::Error;
}
void GeomCacheAssetHandler::DestroyAsset(AZ::Data::AssetPtr ptr)
{
delete ptr;
}
void GeomCacheAssetHandler::GetHandledAssetTypes(AZStd::vector<AZ::Data::AssetType>& assetTypes)
{
assetTypes.push_back(AZ::AzTypeInfo<GeomCacheAsset>::Uuid());
}
void GeomCacheAssetHandler::Register()
{
AZ_Assert(AZ::Data::AssetManager::IsReady(), "Asset manager isn't ready!");
AZ::Data::AssetManager::Instance().RegisterHandler(this, AZ::AzTypeInfo<GeomCacheAsset>::Uuid());
AZ::AssetTypeInfoBus::Handler::BusConnect(AZ::AzTypeInfo<GeomCacheAsset>::Uuid());
}
void GeomCacheAssetHandler::Unregister()
{
AZ::AssetTypeInfoBus::Handler::BusDisconnect(AZ::AzTypeInfo<GeomCacheAsset>::Uuid());
if (AZ::Data::AssetManager::IsReady())
{
AZ::Data::AssetManager::Instance().UnregisterHandler(this);
}
}
AZ::Data::AssetType GeomCacheAssetHandler::GetAssetType() const
{
return AZ::AzTypeInfo<GeomCacheAsset>::Uuid();
}
const char* GeomCacheAssetHandler::GetAssetTypeDisplayName() const
{
return "Geom Cache";
}
const char* GeomCacheAssetHandler::GetGroup() const
{
return "Geometry";
}
AZ::Uuid GeomCacheAssetHandler::GetComponentTypeId() const
{
return AZ::Uuid("{045C0C58-C13E-49B0-A471-D4AC5D3FC6BD}");
}
void GeomCacheAssetHandler::GetAssetTypeExtensions(AZStd::vector<AZStd::string>& extensions)
{
extensions.push_back(CRY_GEOM_CACHE_FILE_EXT);
}
} // namespace LmbrCentral
@@ -94,40 +94,4 @@ namespace LmbrCentral
AZ::Data::AssetId m_missingMeshAssetId;
};
/**
* Handler for Alembic Geometry Caches (cax)
*/
class GeomCacheAssetHandler
: public AZ::Data::AssetHandler
, public AZ::AssetTypeInfoBus::Handler
, private MeshAssetHandlerHelper
{
public:
AZ_CLASS_ALLOCATOR(GeomCacheAssetHandler, AZ::SystemAllocator, 0);
~GeomCacheAssetHandler() override;
// AZ::Data::AssetHandler
AZ::Data::AssetPtr CreateAsset(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override;
void GetCustomAssetStreamInfoForLoad(AZ::Data::AssetStreamInfo& streamInfo) override;
AZ::Data::AssetHandler::LoadResult LoadAssetData(
const AZ::Data::Asset<AZ::Data::AssetData>& asset,
AZStd::shared_ptr<AZ::Data::AssetDataStream> stream,
const AZ::Data::AssetFilterCB& assetLoadFilterCB) override;
void DestroyAsset(AZ::Data::AssetPtr ptr) override;
void GetHandledAssetTypes(AZStd::vector<AZ::Data::AssetType>& assetTypes) override;
// AZ::AssetTypeInfoBus::Handler
AZ::Data::AssetType GetAssetType() const override;
const char* GetAssetTypeDisplayName() const override;
const char* GetGroup() const override;
AZ::Uuid GetComponentTypeId() const override;
void GetAssetTypeExtensions(AZStd::vector<AZStd::string>& extensions) override;
void Register();
void Unregister();
};
} // namespace LmbrCentral
@@ -1,39 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include <StereoRendererBus.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include <AzCore/Serialization/SerializeContext.h>
#include "StereoRendererComponent.h"
namespace LmbrCentral
{
void StereoRendererComponent::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<StereoRendererComponent, AZ::Component>()
->Version(1);
}
AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
if (behaviorContext)
{
behaviorContext->EBus<AZ::StereoRendererRequestBus>("StereoRendererRequestBus")
->Event("IsRenderingToHMD", &AZ::StereoRendererRequestBus::Events::IsRenderingToHMD);
}
}
}
@@ -1,37 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/Component.h>
/*
This class exposes functionality from the renderer to lua
*/
namespace LmbrCentral
{
class StereoRendererComponent :
public AZ::Component
{
public:
AZ_COMPONENT(StereoRendererComponent, "{BBFE0965-5564-4739-8219-AFE8209A5E57}");
StereoRendererComponent() {};
~StereoRendererComponent() override {};
void Activate() override {};
void Deactivate() override {};
static void Reflect(AZ::ReflectContext* context);
};
}
@@ -1,308 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include "Source/Rendering/EditorLensFlareComponent.h"
#include <AzCore/Asset/AssetManager.h>
#include <AzCore/Component/TickBus.h>
#include <AzCore/std/parallel/binary_semaphore.h>
#include <AzCore/UnitTest/Mocks/MockFileIOBase.h>
#include <AzCore/UnitTest/TestTypes.h>
#include <AzCore/UserSettings/UserSettingsComponent.h>
#include <AzFramework/Components/TransformComponent.h>
#include <AzTest/AzTest.h>
#include <AzToolsFramework/Application/ToolsApplication.h>
#include <Mocks/ISystemMock.h>
#include <Mocks/IConsoleMock.h>
using ::testing::NiceMock;
namespace UnitTest
{
// Provides public access to protected/private members to allow for testing.
class Test_EditorLensFlareComponent :
public LmbrCentral::EditorLensFlareComponent
{
public:
AZ_COMPONENT(Test_EditorLensFlareComponent, "{2FB6C076-BB92-47A3-93C1-6ED7E622D7E0}", LmbrCentral::EditorLensFlareComponent);
Test_EditorLensFlareComponent() : EditorLensFlareComponent()
{
}
~Test_EditorLensFlareComponent() override
{
}
static void Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<Test_EditorLensFlareComponent, EditorLensFlareComponent>()->
Version(1);
}
}
LmbrCentral::EditorLensFlareConfiguration Public_GetEditorLensFlareConfiguration() const
{
return GetEditorLensFlareConfiguration();
}
};
class MockLensFlareHandlerAndCatalog
: public AZ::Data::AssetHandler
, public AZ::Data::AssetCatalog
{
public:
AZ_CLASS_ALLOCATOR(MockLensFlareHandlerAndCatalog, AZ::SystemAllocator, 0);
AZ::Data::AssetPtr CreateAsset([[maybe_unused]] const AZ::Data::AssetId& id, const AZ::Data::AssetType& /*type*/) override
{
return aznew LmbrCentral::LensFlareAsset();
}
AZ::Data::AssetHandler::LoadResult LoadAssetData(
const AZ::Data::Asset<AZ::Data::AssetData>& /*asset*/,
AZStd::shared_ptr<AZ::Data::AssetDataStream> /*stream*/,
const AZ::Data::AssetFilterCB& /*assetLoadFilterCB*/) override
{
return AZ::Data::AssetHandler::LoadResult::LoadComplete;
}
void DestroyAsset(AZ::Data::AssetPtr ptr) override
{
delete ptr;
}
void GetHandledAssetTypes(AZStd::vector<AZ::Data::AssetType>& assetTypes) override
{
assetTypes.push_back(AZ::AzTypeInfo<LmbrCentral::LensFlareAsset>::Uuid());
}
AZ::Data::AssetStreamInfo GetStreamInfoForLoad(const AZ::Data::AssetId& assetId, const AZ::Data::AssetType& /*type*/) override
{
AZ::Data::AssetStreamInfo info;
// Set valid stream info. This ensures the asset load doesn't result in an
// error on another thread that can occur during shutdown.
info.m_streamName = AZStd::string::format("MockLensFlareHandlerAndCatalog%s", assetId.ToString<AZStd::string>().c_str());
info.m_dataOffset = 0;
info.m_streamFlags = AZ::IO::OpenMode::ModeRead;
return info;
}
};
class EditorLensFlareComponentTests
: public ::testing::Test
, public UnitTest::TraceBusRedirector
, public AZ::Data::AssetBus::MultiHandler
{
protected:
//////////////////////////////////////////////////////////////////////////
// AZ::Data::AssetBus::MultiHandler
void OnAssetReady(AZ::Data::Asset<AZ::Data::AssetData> asset) override
{
EXPECT_EQ(asset.GetId(), m_waitForAssetIdLoad);
m_waitForAssetIdLoad.SetInvalid();
AZ::Data::AssetBus::MultiHandler::BusDisconnect();
}
void OnAssetCanceled(AZ::Data::AssetId assetId) override
{
// With the right timing, it's possible for the asset to get canceled if the test ends
// before the load actually starts. Make sure that if this case happens, we still clear out
// the pending asset Id and disconnect from the bus.
EXPECT_EQ(assetId, m_waitForAssetIdLoad);
m_waitForAssetIdLoad.SetInvalid();
AZ::Data::AssetBus::MultiHandler::BusDisconnect();
}
void OnAssetError([[maybe_unused]] AZ::Data::Asset<AZ::Data::AssetData> asset) override
{
// No asset errors should happen during this test.
EXPECT_TRUE(false);
}
//////////////////////////////////////////////////////////////////////////
void SetUp() override
{
m_app.Start(m_descriptor);
// Mock up the File I/O system
m_priorFileIO = AZ::IO::FileIOBase::GetInstance();
// for FileIO, you must set the instance to null before changing it.
// this is a way to tell the singleton system that you mean to replace a singleton and its
// not a mistake.
AZ::IO::FileIOBase::SetInstance(nullptr);
AZ::IO::FileIOBase::SetInstance(&m_fileIOMock);
AZ::IO::MockFileIOBase::InstallDefaultReturns(m_fileIOMock);
AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize);
m_EditorLensFlareComponentDescriptor = LmbrCentral::EditorLensFlareComponent::CreateDescriptor();
m_testEditorLensFlareComponentDescriptor = Test_EditorLensFlareComponent::CreateDescriptor();
m_lensFlareComponentDescriptor = LmbrCentral::LensFlareComponent::CreateDescriptor();
m_testEditorLensFlareComponentDescriptor->Reflect(m_app.GetSerializeContext());
m_lensFlareComponentDescriptor->Reflect(m_app.GetSerializeContext());
AZ::Debug::TraceMessageBus::Handler::BusConnect();
AZ::Data::AssetManager::Instance().RegisterHandler(&m_lensFlareHandlerAndCatalog, AZ::AzTypeInfo<LmbrCentral::LensFlareAsset>::Uuid());
AZ::Data::AssetManager::Instance().RegisterCatalog(&m_lensFlareHandlerAndCatalog, AZ::AzTypeInfo<LmbrCentral::LensFlareAsset>::Uuid());
EXPECT_CALL(m_system, GetConfigSpec(::testing::_))
.WillRepeatedly(::testing::Return(CONFIG_AUTO_SPEC));
// Setup Mocks on a stub environment
m_stubEnv.pConsole = &m_console;
m_stubEnv.pSystem = &m_system;
m_priorEnv = gEnv;
gEnv = &m_stubEnv;
}
void TearDown() override
{
gEnv = m_priorEnv;
if (m_waitForAssetIdLoad.IsValid())
{
const int assetLoadSleepMS = 20;
int totalWaitTimeMS = 5000;
while (m_waitForAssetIdLoad.IsValid() && totalWaitTimeMS > 0)
{
AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(assetLoadSleepMS));
AZ::SystemTickBus::Broadcast(&AZ::SystemTickBus::Events::OnSystemTick);
if (m_waitForAssetIdLoad.IsValid())
{
totalWaitTimeMS -= assetLoadSleepMS;
}
}
EXPECT_GT(totalWaitTimeMS, 0);
EXPECT_FALSE(m_waitForAssetIdLoad.IsValid());
AZ::Data::AssetBus::MultiHandler::BusDisconnect();
}
AZ::Data::AssetManager::Instance().UnregisterHandler(&m_lensFlareHandlerAndCatalog);
AZ::Data::AssetManager::Instance().UnregisterCatalog(&m_lensFlareHandlerAndCatalog);
m_EditorLensFlareComponentDescriptor->ReleaseDescriptor();
m_testEditorLensFlareComponentDescriptor->ReleaseDescriptor();
m_lensFlareComponentDescriptor->ReleaseDescriptor();
AZ::IO::FileIOBase::SetInstance(nullptr);
AZ::IO::FileIOBase::SetInstance(m_priorFileIO);
m_app.Stop();
// Disconnect last, ToolsApplication::Stop() can result in messages that we are using
// TraceMessageBus to handle.
AZ::Debug::TraceMessageBus::Handler::BusDisconnect();
}
void SetupLensFlareEntity(AZ::Entity& entity)
{
entity.CreateComponent<AzFramework::TransformComponent>();
entity.CreateComponent<Test_EditorLensFlareComponent>();
entity.Init();
entity.Activate();
}
AzToolsFramework::ToolsApplication m_app;
AZ::ComponentApplication::Descriptor m_descriptor;
MockLensFlareHandlerAndCatalog m_lensFlareHandlerAndCatalog;
AZ::ComponentDescriptor* m_EditorLensFlareComponentDescriptor = nullptr;
AZ::ComponentDescriptor* m_testEditorLensFlareComponentDescriptor = nullptr;
AZ::ComponentDescriptor* m_lensFlareComponentDescriptor = nullptr;
// If this is set to a valid asset ID, teardown won't finish until
// this asset has been loaded. If this takes too long, teardown will error out.
AZ::Data::AssetId m_waitForAssetIdLoad;
SSystemGlobalEnvironment m_stubEnv;
NiceMock<SystemMock> m_system;
NiceMock<ConsoleMock> m_console;
SSystemGlobalEnvironment* m_priorEnv = nullptr;
AZ::IO::FileIOBase* m_priorFileIO = nullptr;
::testing::NiceMock<AZ::IO::MockFileIOBase> m_fileIOMock;
};
TEST_F(EditorLensFlareComponentTests, EditorLensFlareComponent_AddEditorLensFlareComponent_ComponentExists)
{
AZ::Entity entity;
SetupLensFlareEntity(entity);
Test_EditorLensFlareComponent* lensFlareComponent =
entity.FindComponent<Test_EditorLensFlareComponent>();
EXPECT_TRUE(lensFlareComponent != nullptr);
}
TEST_F(EditorLensFlareComponentTests, EditorLensFlareComponent_SetAssetId_GetAssetIdMatchesSet)
{
AZ::Entity entity;
SetupLensFlareEntity(entity);
// Use an arbitrary, non-default asset ID to verify the set & get work.
AZ::Data::AssetId assetIdToSet(AZ::Uuid("{377939BD-57BB-4476-B7B5-35A162B1335E}"), 5);
AZ::Data::AssetInfo assetInfo;
assetInfo.m_assetType = azrtti_typeid<LmbrCentral::LensFlareAsset>();
assetInfo.m_assetId = assetIdToSet;
AZ::Data::AssetCatalogRequestBus::Broadcast(&AZ::Data::AssetCatalogRequestBus::Events::RegisterAsset, assetIdToSet, assetInfo);
// m_waitForAssetIdLoad is cleared when the asset load finishes, so keep a local copy of the asset ID.
m_waitForAssetIdLoad = assetIdToSet;
AZ::Data::AssetBus::MultiHandler::BusConnect(m_waitForAssetIdLoad);
Test_EditorLensFlareComponent* lensFlareComponent =
entity.FindComponent<Test_EditorLensFlareComponent>();
lensFlareComponent->SetPrimaryAsset(assetIdToSet);
LmbrCentral::EditorLensFlareConfiguration lensFlareConfiguration =
lensFlareComponent->Public_GetEditorLensFlareConfiguration();
EXPECT_EQ(lensFlareConfiguration.m_asset.GetId(), assetIdToSet);
}
TEST_F(EditorLensFlareComponentTests, EditorLensFlareComponent_SetAssetIdBuildGameEntity_GameEntityHasAssetId)
{
AZ::Entity entity;
SetupLensFlareEntity(entity);
// Use an arbitrary, non-default asset ID to verify the set & get work.
AZ::Data::AssetId assetIdToSet(AZ::Uuid("{BC7C7A76-C5F2-44E2-8E32-3CE03C3C5ADE}"), 6);
AZ::Data::AssetInfo assetInfo;
assetInfo.m_assetType = azrtti_typeid<LmbrCentral::LensFlareAsset>();
assetInfo.m_assetId = assetIdToSet;
AZ::Data::AssetCatalogRequestBus::Broadcast(&AZ::Data::AssetCatalogRequestBus::Events::RegisterAsset, assetIdToSet, assetInfo);
// m_waitForAssetIdLoad is cleared when the asset load finishes, so keep a local copy of the asset ID.
m_waitForAssetIdLoad = assetIdToSet;
AZ::Data::AssetBus::MultiHandler::BusConnect(m_waitForAssetIdLoad);
Test_EditorLensFlareComponent* lensFlareComponent =
entity.FindComponent<Test_EditorLensFlareComponent>();
lensFlareComponent->SetPrimaryAsset(assetIdToSet);
AZ::Entity gameEntity;
lensFlareComponent->BuildGameEntity(&gameEntity);
LmbrCentral::LensFlareComponent* gameComponent =
gameEntity.FindComponent<LmbrCentral::LensFlareComponent>();
EXPECT_TRUE(gameComponent != nullptr);
EXPECT_EQ(gameComponent->GetLensFlareConfiguration().m_asset.GetId(), assetIdToSet);
}
} // namespace UnitTest
@@ -1,366 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/EBus/EBus.h>
#include <I3DEngine.h>
namespace LmbrCentral
{
//Forward decl
enum class StandinType : AZ::u32;
class EditorGeometryCacheComponentRequests
: public AZ::ComponentBus
{
public:
// EBus Traits overrides (Configuring this EBus)
// Using Defaults
virtual ~EditorGeometryCacheComponentRequests() {}
/**
* Sets the minimum spec for the Geometry Cache
*
* The geom cache will not render when the current graphics spec is
* below this minimum spec.
*/
virtual void SetMinSpec(EngineSpec minSpec) = 0;
//! Gets the minimum spec for the Geom Cache
virtual EngineSpec GetMinSpec() = 0;
/**
* Sets whether or not the Geom Cache's animation will play on start
*
* When set to true the Geometry Cache will play in the editor. In game
* mode the Geom Cache will begin playing immediately.
*/
virtual void SetPlayOnStart(bool playOnStart) = 0;
//! Gets whether or not the Geom Cache's animation will play on start
virtual bool GetPlayOnStart() = 0;
/**
* Sets the max view distance that this Geom Cache will be visible from
*
* The actual max view distance is calculated from
* maxViewDistance * viewDistanceMultiplier.
*/
virtual void SetMaxViewDistance(float maxViewDistance) = 0;
/**
* Gets the max view distance that the Geom Cache will be visible from
*
* This is the max view distance without the view distance multiplier
*/
virtual float GetMaxViewDistance() = 0;
/**
* Sets the view distance multiplier
*
* The view distance multiplier is multiplied into the max view distance
* to determine how far you can be from the Geom Cache before it stops
* being rendered.
*
* A value of 1.0 will leave the max view distance as the actual max view distance.
*/
virtual void SetViewDistanceMultiplier(float viewDistanceMultiplier) = 0;
//! Gets the view distance multiplier
virtual float GetViewDistanceMultiplier() = 0;
/**
* Sets the LOD Distance Ratio
*
* The LOD Distance ratio affects how LODs are chosen. A lower value means
* less detailed LODs are used at shorter view distances.
*/
virtual void SetLODDistanceRatio(AZ::u32 lodDistanceRatio) = 0;
//! Gets the LOD Distance Ratio
virtual AZ::u32 GetLODDistanceRatio() = 0;
//! Sets whether or not the Geometry Cache will cast shadows
virtual void SetCastShadows(bool castShadows) = 0;
//! Gets whether or not the Geometry Cache casts shadows
virtual bool GetCastShadows() = 0;
//! Sets whether or not the Geometry Cache will be affected by VisAreas and Portals
virtual void SetUseVisAreas(bool useVisAreas) = 0;
//! Gets whether or not the Geometry Cache is affected by VisAreas and Portals
virtual bool GetUseVisAreas() = 0;
};
using EditorGeometryCacheComponentRequestBus = AZ::EBus<EditorGeometryCacheComponentRequests>;
class GeometryCacheComponentRequests
: public AZ::ComponentBus
{
public:
// EBus Traits overrides (Configuring this EBus)
// Using Defaults
virtual ~GeometryCacheComponentRequests() {}
/**
* Begins Geometry Cache animation playback
*
* If the animation is already playing, this does nothing.
* This may be the case if PlayOnStart was set during edit mode.
*/
virtual void Play() = 0;
//! Pauses Geometry Cache animation playback
virtual void Pause() = 0;
/**
* Stops Geometry Cache animation playback
*
* This will reset the playback time to 0. This means
* that when Play is called again that the animation
* will start from StartTime.
*/
virtual void Stop() = 0;
/**
* Gets how much time remains in the animation
*
* Returns -1.0 if the animation is paused or stopped.
*
* @return How much time in seconds is left in the animation
*/
virtual float GetTimeRemaining() = 0;
/**
* Gets the type of the stand-in that's currently in use
*
* If no stand-in is in use this will return
* StandinType::None.
*
* @return The type of stand-in currently in use
*/
virtual StandinType GetCurrentStandinType() = 0;
/**
* Sets the geom cache asset to be rendered
*/
virtual void SetGeomCacheAsset(const AZ::Data::AssetId& id) = 0;
/**
* Gets the geom cache asset in use by this component
*/
virtual AZ::Data::Asset<AZ::Data::AssetData> GetGeomCacheAsset() = 0;
/**
* Sets whether or not the Geometry Cache will be processed for rendering
*
* If Visibility is turned off, all Stand-ins for this
* Geometry Cache will also be turned off.
*
* This does not mean that the Geometry Cache is visible in the current
* frame or the next frame. This just means that it will be
* submitted to the visibility system for rendering. It can still
* be culled.
*
* @param visible Pass True for the Geometry Cache to render
*/
virtual void SetVisible(bool visible) = 0;
/**
* Gets whether or not the Geometry Cache will be processed for rendering
*
* If this returns false then all related Stand-ins should also
* not be visible.
*
* @return True if the Geometry Cache should be rendered.
*/
virtual bool GetVisible() = 0;
/**
* Sets whether or not the Geometry Cache animation should loop
*
* The Last Frame Stand-in will never be visible as long as this remains
* true.
*
* @param loop Pass true if you want the Geometry Cache animation to loop
*/
virtual void SetLoop(bool loop) = 0;
/**
* Gets whether or not the Geometry Cache animation is set to loop
*
* @return True if the Geometry Cache animation will loop
*/
virtual bool GetLoop() = 0;
/**
* Sets the time point that the Geometry Cache animation should start at
*
* Changing the start time of the animation will restart the animation.
*
* @param startTime The starting time point in seconds.
*/
virtual void SetStartTime(float startTime) = 0;
/**
* Gets the current start time point for the Geometry Cache animation
*
* @return The Geometry Cache's animation start time in seconds.
*/
virtual float GetStartTime() = 0;
/**
* Sets the distance threshold that controls Geometry Cache streaming
*
* When the distance between the center of the Geometry Cache and the
* current camera is greater than this value the Geometry Cache's animation
* will begin to stream into memory.
*
* @param streamInDistance The distance threshold for Geometry Cache streaming
*/
virtual void SetStreamInDistance(float streamInDistance) = 0;
/**
* Gets the distance threshold that controls when the Geometry Cache will stream to memory
*
* @return The distance threshold for Geometry Cache streaming
*/
virtual float GetStreamInDistance() = 0;
/**
* Sets the entity to be used for the First Frame Stand-in
*
* It's assumed that the entityId points to an entity that has
* a MeshComponent attached. The stand-in is controlled by the
* visibility parameter of the MeshComponent.
*
* The given entity will not be transformed or moved at all. The
* only change that will be made to it will be when it's made
* visible/invisible as a stand-in.
*
* Invalid entity ids will be ignored.
*
* This stand-in will be used until the Geometry Cache animation
* starts playing.
*
* @param entityId The ID of the Entity to use as the First Frame Stand-in
*/
virtual void SetFirstFrameStandIn(AZ::EntityId entityId) = 0;
/**
* Gets the entity that is used as the First Frame Stand-in
*
* @return The entity with a mesh component that's used as the First Frame Stand-in
*/
virtual AZ::EntityId GetFirstFrameStandIn() = 0;
/**
* Sets the entity to be used for the Last Frame Stand-in
*
* It's assumed that the entityId points to an entity that has
* a MeshComponent attached. The stand-in is controlled by the
* visibility parameter of the MeshComponent.
*
* The given entity will not be transformed or moved at all. The
* only change that will be made to it will be when it's made
* visible/invisible as a stand-in.
*
* Invalid entity ids will be ignored.
*
* This stand-in will never be used if the Loop parameter is set to true.
*
* @param entityId The ID of the Entity to use as the Last Frame Stand-in
*/
virtual void SetLastFrameStandIn(AZ::EntityId entityId) = 0;
/**
* Gets the entity that is used as the Last Frame Stand-in
*
* @return The entity with a mesh component that's used as the Last Frame Stand-in
*/
virtual AZ::EntityId GetLastFrameStandIn() = 0;
/**
* Sets the entity to be used for the distance-based Stand-in
*
* It's assumed that the entityId points to an entity that has
* a MeshComponent attached. The stand-in is controlled by the
* visibility parameter of the MeshComponent.
*
* The given entity will not be transformed or moved at all. The
* only change that will be made to it will be when it's made
* visible/invisible as a stand-in.
*
* Invalid entity ids will be ignored.
*
* This Stand-in will be used as long as the distance between the
* Geometry Cache's center and the current camera's position is larger
* than the Stand-in Distance parameter.
*
* @param entityId The ID of the Entity to use as the distance-based Stand-in
*/
virtual void SetStandIn(AZ::EntityId entityId) = 0;
/**
* Gets the entity that is used as the distance-based Stand-in
*
* @return The entity with a mesh component that's used as the distance-based Stand-in
*/
virtual AZ::EntityId GetStandIn() = 0;
/**
* Sets the distance threshold that controls the visibility of the stand-in
*
* The stand-in will be used when the distance between the center of the
* Geometry Cache and the current camera is greater than this value.
*
* @param standInDistance The distance threshold for the stand-in
*/
virtual void SetStandInDistance(float standInDistance) = 0;
/**
* Gets the distance threshold that controls the visibility of the stand-in
*
* @return The distance threshold for the stand-in
*/
virtual float GetStandInDistance() = 0;
/**
* Gets the Geometry Cache's render node
*
* This method is only exposed to C++.
*
* @return A pointer to the geometry cache's internal render node
*/
virtual IGeomCacheRenderNode* GetGeomCacheRenderNode() = 0;
};
using GeometryCacheComponentRequestBus = AZ::EBus<GeometryCacheComponentRequests>;
class GeometryCacheComponentNotifications
: public AZ::EBusTraits
{
public:
// EBus Traits overrides (Configuring this EBus)
// Using Defaults
virtual ~GeometryCacheComponentNotifications() {}
//! Event that triggers when Geometry Cache playback starts
virtual void OnPlaybackStart() = 0;
//! Event that triggers when Geometry Cache playback pauses
virtual void OnPlaybackPause() = 0;
//! Event that triggers when Geometry Cache playback stops
virtual void OnPlaybackStop() = 0;
/**
* Event that triggers when the Geometry Cache changes which stand-in is in use
*
* This does fire if a stand-in is turned off and the Geometry Cache becomes
* active instead.
*
* @param standinType The new stand-in type that will be used
*/
virtual void OnStandinChanged(StandinType standinType) = 0;
};
using GeometryCacheComponentNotificationBus = AZ::EBus<GeometryCacheComponentNotifications>;
} //namespace LmbrCentral
@@ -1,44 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/ComponentBus.h>
namespace LmbrCentral
{
/*!
* Messages serviced by the unique shadow component.
*/
class HighQualityShadowComponentRequests
: public AZ::ComponentBus
{
public:
virtual void SetEnabled(bool enabled) = 0;
virtual bool GetEnabled() = 0;
};
using HighQualityShadowComponentRequestBus = AZ::EBus<HighQualityShadowComponentRequests>;
/*!
* Messages serviced by the unique shadow editor component.
*/
class EditorHighQualityShadowComponentRequests
: public AZ::ComponentBus
{
public:
virtual void RefreshProperties() = 0;
};
using EditorHighQualityShadowComponentRequestBus = AZ::EBus<EditorHighQualityShadowComponentRequests>;
} // namespace LmbrCentral
@@ -1,84 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/ComponentBus.h>
namespace LmbrCentral
{
/*!
* LensFlareComponentRequestsBus
* Messages serviced by the Lens Flare component.
*/
class LensFlareComponentRequests
: public AZ::ComponentBus
{
public:
enum class State
{
Off,
On,
};
virtual ~LensFlareComponentRequests() {}
//! Control lens flare state.
virtual void SetLensFlareState(State state) { (void)state; }
//! Turns lens flare on
virtual void TurnOnLensFlare() {}
//! Turns lens flare off
virtual void TurnOffLensFlare() {}
//! Toggles lens flare state.
virtual void ToggleLensFlare() {}
};
using LensFlareComponentRequestBus = AZ::EBus<LensFlareComponentRequests>;
/*!
* LensFlareEditorRequestBus
* Editor/UI messages serviced by the Lens Flare component.
*/
class EditorLensFlareComponentRequests
: public AZ::ComponentBus
{
public:
virtual ~EditorLensFlareComponentRequests() {}
//! Recreates the lens flare.
virtual void RefreshLensFlare() = 0;
};
using EditorLensFlareComponentRequestBus = AZ::EBus<EditorLensFlareComponentRequests>;
/*!
* LensFlareComponentEventBus
* Events dispatched by the Lens Flare component.
*/
class LensFlareComponentNotifications
: public AZ::ComponentBus
{
public:
virtual ~LensFlareComponentNotifications() {}
//! Lens flare has been turned on
virtual void LensFlareTurnedOn() {}
//! Lens flare has been turned off
virtual void LensFlareTurnedOff() {}
};
using LensFlareComponentNotificationBus = AZ::EBus<LensFlareComponentNotifications>;
} // namespace LmbrCentral
@@ -40,26 +40,8 @@ set(FILES
Source/Builders/BenchmarkAssetBuilder/BenchmarkAssetBuilderComponent.cpp
Source/Builders/BenchmarkAssetBuilder/BenchmarkAssetBuilderWorker.h
Source/Builders/BenchmarkAssetBuilder/BenchmarkAssetBuilderWorker.cpp
Source/Rendering/EditorDecalComponent.h
Source/Rendering/EditorDecalComponent.cpp
Source/Rendering/EditorLensFlareComponent.h
Source/Rendering/EditorLensFlareComponent.cpp
Source/Rendering/EditorLightComponent.h
Source/Rendering/EditorLightComponent.cpp
Source/Rendering/EditorPointLightComponent.h
Source/Rendering/EditorPointLightComponent.cpp
Source/Rendering/EditorAreaLightComponent.h
Source/Rendering/EditorAreaLightComponent.cpp
Source/Rendering/EditorProjectorLightComponent.h
Source/Rendering/EditorProjectorLightComponent.cpp
Source/Rendering/EditorEnvProbeComponent.h
Source/Rendering/EditorEnvProbeComponent.cpp
Source/Rendering/EditorMeshComponent.h
Source/Rendering/EditorMeshComponent.cpp
Source/Rendering/EditorHighQualityShadowComponent.h
Source/Rendering/EditorHighQualityShadowComponent.cpp
Source/Rendering/EditorGeomCacheComponent.h
Source/Rendering/EditorGeomCacheComponent.cpp
Source/Scripting/EditorLookAtComponent.h
Source/Scripting/EditorLookAtComponent.cpp
Source/Scripting/EditorRandomTimedSpawnerComponent.cpp
@@ -14,7 +14,6 @@ set(FILES
Tests/LmbrCentralReflectionTest.h
Tests/LmbrCentralReflectionTest.cpp
Tests/EditorBoxShapeComponentTests.cpp
Tests/EditorLensFlareComponentTests.cpp
Tests/EditorSphereShapeComponentTests.cpp
Tests/EditorCapsuleShapeComponentTests.cpp
Tests/EditorCompoundShapeComponentTests.cpp
@@ -35,8 +35,6 @@ set(FILES
include/LmbrCentral/Physics/ForceVolumeRequestBus.h
include/LmbrCentral/Physics/WaterNotificationBus.h
include/LmbrCentral/Rendering/DecalComponentBus.h
include/LmbrCentral/Rendering/LensFlareAsset.h
include/LmbrCentral/Rendering/LensFlareComponentBus.h
include/LmbrCentral/Rendering/LightComponentBus.h
include/LmbrCentral/Rendering/MaterialAsset.h
include/LmbrCentral/Rendering/MaterialHandle.h
@@ -45,8 +43,6 @@ set(FILES
include/LmbrCentral/Rendering/MeshComponentBus.h
include/LmbrCentral/Rendering/MeshModificationBus.h
include/LmbrCentral/Rendering/RenderNodeBus.h
include/LmbrCentral/Rendering/HighQualityShadowComponentBus.h
include/LmbrCentral/Rendering/GeomCacheComponentBus.h
include/LmbrCentral/Rendering/GiRegistrationBus.h
include/LmbrCentral/Rendering/RenderBoundsBus.h
include/LmbrCentral/Rendering/Utils/MaterialOwnerRequestBusHandlerImpl.h
@@ -103,27 +99,11 @@ set(FILES
Source/Events/ReflectScriptableEvents.cpp
Source/Geometry/GeometrySystemComponent.h
Source/Geometry/GeometrySystemComponent.cpp
Source/Rendering/DecalComponent.h
Source/Rendering/DecalComponent.cpp
Source/Rendering/LensFlareAssetHandler.h
Source/Rendering/LensFlareAssetHandler.cpp
Source/Rendering/LensFlareComponent.h
Source/Rendering/LensFlareComponent.cpp
Source/Rendering/LightComponent.h
Source/Rendering/LightComponent.cpp
Source/Rendering/LightInstance.h
Source/Rendering/LightInstance.cpp
Source/Rendering/MaterialHandle.cpp
Source/Rendering/MeshAssetHandler.h
Source/Rendering/MeshAssetHandler.cpp
Source/Rendering/MeshComponent.h
Source/Rendering/MeshComponent.cpp
Source/Rendering/StereoRendererComponent.h
Source/Rendering/StereoRendererComponent.cpp
Source/Rendering/HighQualityShadowComponent.h
Source/Rendering/HighQualityShadowComponent.cpp
Source/Rendering/GeomCacheComponent.h
Source/Rendering/GeomCacheComponent.cpp
Source/Rendering/EntityDebugDisplayComponent.h
Source/Rendering/EntityDebugDisplayComponent.cpp
Source/Scripting/LookAtComponent.h