Merge branch 'main' into LYN-2461
This commit is contained in:
@@ -133,7 +133,15 @@ namespace AZ
|
||||
if (!id.m_guid.IsNull())
|
||||
{
|
||||
*instance = AssetManager::Instance().FindOrCreateAsset(id, instance->GetType(), instance->GetAutoLoadBehavior());
|
||||
|
||||
if (!instance->GetId().IsValid())
|
||||
{
|
||||
// If the asset failed to be created, FindOrCreateAsset returns an asset instance with a null
|
||||
// id. To preserve the asset id in the source json, reset the asset to an empty one, but with
|
||||
// the right id.
|
||||
const auto loadBehavior = instance->GetAutoLoadBehavior();
|
||||
*instance = Asset<AssetData>(id, instance->GetType());
|
||||
instance->SetAutoLoadBehavior(loadBehavior);
|
||||
}
|
||||
|
||||
result.Combine(context.Report(result, "Successfully created Asset<T> with id."));
|
||||
}
|
||||
|
||||
@@ -86,4 +86,94 @@ namespace AZ
|
||||
Normal,
|
||||
UniformReal
|
||||
};
|
||||
|
||||
//! Halton sequences are deterministic, quasi-random sequences with low discrepancy. They
|
||||
//! are useful for generating evenly distributed points.
|
||||
//! See https://en.wikipedia.org/wiki/Halton_sequence for more information.
|
||||
|
||||
//! Returns a single halton number.
|
||||
//! @param index The index of the number. Indices start at 1. Using index 0 will return 0.
|
||||
//! @param base The numerical base of the halton number.
|
||||
inline float GetHaltonNumber(uint32_t index, uint32_t base)
|
||||
{
|
||||
float fraction = 1.0f;
|
||||
float result = 0.0f;
|
||||
|
||||
while (index > 0)
|
||||
{
|
||||
fraction = fraction / base;
|
||||
result += fraction * (index % base);
|
||||
index = aznumeric_cast<uint32_t>(index / base);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
//! A helper class for generating arrays of Halton sequences in n dimensions.
|
||||
//! The class holds the state of which bases to use, the starting offset
|
||||
//! of each dimension and how much to increment between each index for each
|
||||
//! dimension.
|
||||
template <uint8_t Dimensions>
|
||||
class HaltonSequence
|
||||
{
|
||||
public:
|
||||
|
||||
//! Initializes a Halton sequence with some bases. By default there is no
|
||||
//! offset and the index increments by 1 between each number.
|
||||
HaltonSequence(AZStd::array<uint32_t, Dimensions> bases)
|
||||
: m_bases(bases)
|
||||
{
|
||||
m_offsets.fill(1); // Halton sequences start at index 1.
|
||||
m_increments.fill(1); // By default increment by 1 between each number.
|
||||
}
|
||||
|
||||
//! Returns a Halton sequence in an array of N length
|
||||
template<uint32_t N>
|
||||
AZStd::array<AZStd::array<float, Dimensions>, N> GetHaltonSequence()
|
||||
{
|
||||
AZStd::array<AZStd::array<float, Dimensions>, N> result;
|
||||
|
||||
AZStd::array<uint32_t, Dimensions> indices = m_offsets;
|
||||
|
||||
// Generator that returns the Halton number for all bases for a single entry.
|
||||
auto f = [&] ()
|
||||
{
|
||||
AZStd::array<float, Dimensions> item;
|
||||
for (auto d = 0; d < Dimensions; ++d)
|
||||
{
|
||||
item[d] = GetHaltonNumber(indices[d], m_bases[d]);
|
||||
indices[d] += m_increments[d];
|
||||
}
|
||||
return item;
|
||||
};
|
||||
|
||||
AZStd::generate(result.begin(), result.end(), f);
|
||||
return result;
|
||||
}
|
||||
|
||||
//! Sets the offsets per dimension to start generating a sequence from.
|
||||
//! By default, there is no offset (offset of 0 corresponds to starting at index 1)
|
||||
void SetOffsets(AZStd::array<uint32_t, Dimensions> offsets)
|
||||
{
|
||||
m_offsets = offsets;
|
||||
|
||||
// Halton sequences start at index 1, so increment all the indices.
|
||||
AZStd::for_each(m_offsets.begin(), m_offsets.end(), [](uint32_t &n){ n++; });
|
||||
}
|
||||
|
||||
//! Sets the increment between numbers in the halton sequence per dimension
|
||||
//! By default this is 1, meaning that no numbers are skipped. Can be negative
|
||||
//! to generate numbers in reverse order.
|
||||
void SetIncrements(AZStd::array<int32_t, Dimensions> increments)
|
||||
{
|
||||
m_increments = increments;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
AZStd::array<uint32_t, Dimensions> m_bases;
|
||||
AZStd::array<uint32_t, Dimensions> m_offsets;
|
||||
AZStd::array<int32_t, Dimensions> m_increments;
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <cerrno>
|
||||
#include <AzCore/Casting/numeric_cast.h>
|
||||
#include <AzCore/JSON/error/en.h>
|
||||
#include <AzCore/NativeUI//NativeUIRequests.h>
|
||||
#include <AzCore/Serialization/Json/JsonSerialization.h>
|
||||
#include <AzCore/Serialization/Json/StackedString.h>
|
||||
#include <AzCore/Settings/SettingsRegistryImpl.h>
|
||||
@@ -880,6 +881,13 @@ namespace AZ
|
||||
const Specializations& specializations, const rapidjson::Pointer& historyPointer, AZStd::string_view folderPath)
|
||||
{
|
||||
using namespace rapidjson;
|
||||
|
||||
if (&lhs == &rhs)
|
||||
{
|
||||
// Early return to avoid setting the collisionFound reference to true
|
||||
// std::sort is allowed to pass in the same memory address for the left and right elements
|
||||
return false;
|
||||
}
|
||||
|
||||
AZ_Assert(!lhs.m_tags.empty(), "Comparing a settings file without at least a name tag.");
|
||||
AZ_Assert(!rhs.m_tags.empty(), "Comparing a settings file without at least a name tag.");
|
||||
@@ -1054,15 +1062,23 @@ namespace AZ
|
||||
jsonPatch.ParseInsitu<flags>(scratchBuffer.data());
|
||||
if (jsonPatch.HasParseError())
|
||||
{
|
||||
auto nativeUI = AZ::Interface<NativeUI::NativeUIRequests>::Get();
|
||||
if (jsonPatch.GetParseError() == rapidjson::kParseErrorDocumentEmpty)
|
||||
{
|
||||
AZ_Warning("Settings Registry", false, R"(Unable to parse registry file "%s" due to json error "%s" at offset %llu.)",
|
||||
AZ_Warning("Settings Registry", false, R"(Unable to parse registry file "%s" due to json error "%s" at offset %zu.)",
|
||||
path, GetParseError_En(jsonPatch.GetParseError()), jsonPatch.GetErrorOffset());
|
||||
}
|
||||
else
|
||||
{
|
||||
AZ_Error("Settings Registry", false, R"(Unable to parse registry file "%s" due to json error "%s" at offset %llu.)", path,
|
||||
using ErrorString = AZStd::fixed_string<4096>;
|
||||
auto jsonError = ErrorString::format(R"(Unable to parse registry file "%s" due to json error "%s" at offset %zu.)", path,
|
||||
GetParseError_En(jsonPatch.GetParseError()), jsonPatch.GetErrorOffset());
|
||||
AZ_Error("Settings Registry", false, "%s", jsonError.c_str());
|
||||
|
||||
if (nativeUI)
|
||||
{
|
||||
nativeUI->DisplayOkDialog("Setreg(Patch) Merge Issue", AZStd::string_view(jsonError), false);
|
||||
}
|
||||
}
|
||||
|
||||
pointer.Create(m_settings, m_settings.GetAllocator()).SetObject()
|
||||
|
||||
@@ -41,10 +41,6 @@ namespace AZ
|
||||
if (const char* homePath = std::getenv("HOME"); homePath != nullptr)
|
||||
{
|
||||
AZ::IO::FixedMaxPath path{homePath};
|
||||
if (!path.empty())
|
||||
{
|
||||
path /= ".o3de";
|
||||
}
|
||||
return path.Native();
|
||||
}
|
||||
return {};
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* 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 <AzCore/Math/Random.h>
|
||||
#include <AzCore/UnitTest/TestTypes.h>
|
||||
|
||||
using namespace AZ;
|
||||
|
||||
namespace UnitTest
|
||||
{
|
||||
TEST(MATH_Random, GetHaltonNumber)
|
||||
{
|
||||
EXPECT_FLOAT_EQ(0.5, GetHaltonNumber(1, 2));
|
||||
EXPECT_FLOAT_EQ(898.0f / 2187.0f, GetHaltonNumber(1234, 3));
|
||||
EXPECT_FLOAT_EQ(5981.0f / 15625.0f, GetHaltonNumber(4321, 5));
|
||||
}
|
||||
|
||||
TEST(MATH_Random, HaltonSequence)
|
||||
{
|
||||
HaltonSequence<3> sequence({ 2, 3, 5 });
|
||||
auto regularSequence = sequence.GetHaltonSequence<5>();
|
||||
|
||||
EXPECT_FLOAT_EQ(1.0f / 2.0f, regularSequence[0][0]);
|
||||
EXPECT_FLOAT_EQ(1.0f / 3.0f, regularSequence[0][1]);
|
||||
EXPECT_FLOAT_EQ(1.0f / 5.0f, regularSequence[0][2]);
|
||||
|
||||
EXPECT_FLOAT_EQ(1.0f / 4.0f, regularSequence[1][0]);
|
||||
EXPECT_FLOAT_EQ(2.0f / 3.0f, regularSequence[1][1]);
|
||||
EXPECT_FLOAT_EQ(2.0f / 5.0f, regularSequence[1][2]);
|
||||
|
||||
EXPECT_FLOAT_EQ(3.0f / 4.0f, regularSequence[2][0]);
|
||||
EXPECT_FLOAT_EQ(1.0f / 9.0f, regularSequence[2][1]);
|
||||
EXPECT_FLOAT_EQ(3.0f / 5.0f, regularSequence[2][2]);
|
||||
|
||||
EXPECT_FLOAT_EQ(1.0f / 8.0f, regularSequence[3][0]);
|
||||
EXPECT_FLOAT_EQ(4.0f / 9.0f, regularSequence[3][1]);
|
||||
EXPECT_FLOAT_EQ(4.0f / 5.0f, regularSequence[3][2]);
|
||||
|
||||
EXPECT_FLOAT_EQ(5.0f / 8.0f, regularSequence[4][0]);
|
||||
EXPECT_FLOAT_EQ(7.0f / 9.0f, regularSequence[4][1]);
|
||||
EXPECT_FLOAT_EQ(1.0f / 25.0f, regularSequence[4][2]);
|
||||
|
||||
sequence.SetOffsets({ 1, 2, 3 });
|
||||
auto offsetSequence = sequence.GetHaltonSequence<2>();
|
||||
|
||||
EXPECT_FLOAT_EQ(1.0f / 4.0f, offsetSequence[0][0]);
|
||||
EXPECT_FLOAT_EQ(1.0f / 9.0f, offsetSequence[0][1]);
|
||||
EXPECT_FLOAT_EQ(4.0f / 5.0f, offsetSequence[0][2]);
|
||||
|
||||
EXPECT_FLOAT_EQ(3.0f / 4.0f, offsetSequence[1][0]);
|
||||
EXPECT_FLOAT_EQ(4.0f / 9.0f, offsetSequence[1][1]);
|
||||
EXPECT_FLOAT_EQ(1.0f / 25.0f, offsetSequence[1][2]);
|
||||
|
||||
sequence.SetIncrements({ 1, 2, 3 });
|
||||
auto incrementedSequence = sequence.GetHaltonSequence<2>();
|
||||
|
||||
EXPECT_FLOAT_EQ(1.0f / 4.0f, incrementedSequence[0][0]);
|
||||
EXPECT_FLOAT_EQ(1.0f / 9.0f, incrementedSequence[0][1]);
|
||||
EXPECT_FLOAT_EQ(4.0f / 5.0f, incrementedSequence[0][2]);
|
||||
|
||||
EXPECT_FLOAT_EQ(3.0f / 4.0f, incrementedSequence[1][0]);
|
||||
EXPECT_FLOAT_EQ(7.0f / 9.0f, incrementedSequence[1][1]);
|
||||
EXPECT_FLOAT_EQ(11.0f / 25.0f, incrementedSequence[1][2]);
|
||||
}
|
||||
}
|
||||
@@ -152,6 +152,7 @@ set(FILES
|
||||
Math/PlaneTests.cpp
|
||||
Math/QuaternionPerformanceTests.cpp
|
||||
Math/QuaternionTests.cpp
|
||||
Math/RandomTests.cpp
|
||||
Math/ShapeIntersectionPerformanceTests.cpp
|
||||
Math/ShapeIntersectionTests.cpp
|
||||
Math/SfmtTests.cpp
|
||||
|
||||
+11
-2
@@ -30,6 +30,16 @@ namespace AzPhysics
|
||||
classElement.AddElementWithData(context, "name", name);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SimulatedBodyVersionConverter([[maybe_unused]] AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement)
|
||||
{
|
||||
if (classElement.GetVersion() <= 1)
|
||||
{
|
||||
classElement.RemoveElementByName(AZ_CRC_CE("scale"));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
AZ_CLASS_ALLOCATOR_IMPL(SimulatedBodyConfiguration, AZ::SystemAllocator, 0);
|
||||
@@ -40,11 +50,10 @@ namespace AzPhysics
|
||||
{
|
||||
serializeContext->ClassDeprecate("WorldBodyConfiguration", "{6EEB377C-DC60-4E10-AF12-9626C0763B2D}", &Internal::DeprecateWorldBodyConfiguration);
|
||||
serializeContext->Class<SimulatedBodyConfiguration>()
|
||||
->Version(1)
|
||||
->Version(2, &Internal::SimulatedBodyVersionConverter)
|
||||
->Field("name", &SimulatedBodyConfiguration::m_debugName)
|
||||
->Field("position", &SimulatedBodyConfiguration::m_position)
|
||||
->Field("orientation", &SimulatedBodyConfiguration::m_orientation)
|
||||
->Field("scale", &SimulatedBodyConfiguration::m_scale)
|
||||
->Field("entityId", &SimulatedBodyConfiguration::m_entityId)
|
||||
->Field("startSimulationEnabled", &SimulatedBodyConfiguration::m_startSimulationEnabled)
|
||||
;
|
||||
|
||||
-1
@@ -38,7 +38,6 @@ namespace AzPhysics
|
||||
// Basic initial settings.
|
||||
AZ::Vector3 m_position = AZ::Vector3::CreateZero();
|
||||
AZ::Quaternion m_orientation = AZ::Quaternion::CreateIdentity();
|
||||
AZ::Vector3 m_scale = AZ::Vector3::CreateOne();
|
||||
bool m_startSimulationEnabled = true;
|
||||
|
||||
// Entity/object association.
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
#include <AzCore/std/numeric.h>
|
||||
#include <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
|
||||
#include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
|
||||
#include <AzFramework/Windowing/WindowBus.h>
|
||||
|
||||
namespace AzFramework
|
||||
{
|
||||
@@ -160,24 +159,27 @@ namespace AzFramework
|
||||
|
||||
bool CameraSystem::HandleEvents(const InputEvent& event)
|
||||
{
|
||||
if (const auto& cursor = AZStd::get_if<CursorEvent>(&event))
|
||||
if (const auto& horizonalMotion = AZStd::get_if<HorizontalMotionEvent>(&event))
|
||||
{
|
||||
m_cursorState.SetCurrentPosition(cursor->m_position);
|
||||
m_motionDelta.m_x = horizonalMotion->m_delta;
|
||||
}
|
||||
else if (const auto& verticalMotion = AZStd::get_if<VerticalMotionEvent>(&event))
|
||||
{
|
||||
m_motionDelta.m_y = verticalMotion->m_delta;
|
||||
}
|
||||
else if (const auto& scroll = AZStd::get_if<ScrollEvent>(&event))
|
||||
{
|
||||
m_scrollDelta = scroll->m_delta;
|
||||
}
|
||||
|
||||
return m_cameras.HandleEvents(event, m_cursorState.CursorDelta(), m_scrollDelta);
|
||||
return m_cameras.HandleEvents(event, m_motionDelta, m_scrollDelta);
|
||||
}
|
||||
|
||||
Camera CameraSystem::StepCamera(const Camera& targetCamera, const float deltaTime)
|
||||
{
|
||||
const auto nextCamera = m_cameras.StepCamera(targetCamera, m_cursorState.CursorDelta(), m_scrollDelta, deltaTime);
|
||||
|
||||
m_cursorState.Update();
|
||||
const auto nextCamera = m_cameras.StepCamera(targetCamera, m_motionDelta, m_scrollDelta, deltaTime);
|
||||
|
||||
m_motionDelta = ScreenVector{0, 0};
|
||||
m_scrollDelta = 0.0f;
|
||||
|
||||
return nextCamera;
|
||||
@@ -193,13 +195,12 @@ namespace AzFramework
|
||||
bool handling = false;
|
||||
for (auto& cameraInput : m_activeCameraInputs)
|
||||
{
|
||||
cameraInput->HandleEvents(event, cursorDelta, scrollDelta);
|
||||
handling = !cameraInput->Idle() || handling;
|
||||
handling = cameraInput->HandleEvents(event, cursorDelta, scrollDelta) || handling;
|
||||
}
|
||||
|
||||
for (auto& cameraInput : m_idleCameraInputs)
|
||||
{
|
||||
cameraInput->HandleEvents(event, cursorDelta, scrollDelta);
|
||||
handling = cameraInput->HandleEvents(event, cursorDelta, scrollDelta) || handling;
|
||||
}
|
||||
|
||||
return handling;
|
||||
@@ -262,17 +263,26 @@ namespace AzFramework
|
||||
{
|
||||
m_activeCameraInputs[i]->Reset();
|
||||
m_idleCameraInputs.push_back(m_activeCameraInputs[i]);
|
||||
m_activeCameraInputs[i] = m_activeCameraInputs[m_activeCameraInputs.size() - 1];
|
||||
using AZStd::swap;
|
||||
swap(m_activeCameraInputs[i], m_activeCameraInputs[m_activeCameraInputs.size() - 1]);
|
||||
m_activeCameraInputs.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
void Cameras::Clear()
|
||||
{
|
||||
Reset();
|
||||
AZ_Assert(m_activeCameraInputs.empty(), "Active Camera Inputs is not empty");
|
||||
|
||||
m_idleCameraInputs.clear();
|
||||
}
|
||||
|
||||
RotateCameraInput::RotateCameraInput(const InputChannelId rotateChannelId)
|
||||
: m_rotateChannelId(rotateChannelId)
|
||||
{
|
||||
}
|
||||
|
||||
void RotateCameraInput::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta)
|
||||
bool RotateCameraInput::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta)
|
||||
{
|
||||
const ClickDetector::ClickEvent clickEvent = [&event, this] {
|
||||
if (const auto& input = AZStd::get_if<DiscreteInputEvent>(&event))
|
||||
@@ -304,6 +314,11 @@ namespace AzFramework
|
||||
// noop
|
||||
break;
|
||||
}
|
||||
|
||||
// note - must also check !ending to ensure the mouse up (release) event
|
||||
// is not consumed and can be propagated to other systems.
|
||||
// (don't swallow mouse up events)
|
||||
return !Idle() && !Ending();
|
||||
}
|
||||
|
||||
Camera RotateCameraInput::StepCamera(
|
||||
@@ -330,7 +345,7 @@ namespace AzFramework
|
||||
{
|
||||
}
|
||||
|
||||
void PanCameraInput::HandleEvents(
|
||||
bool PanCameraInput::HandleEvents(
|
||||
const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta)
|
||||
{
|
||||
if (const auto& input = AZStd::get_if<DiscreteInputEvent>(&event))
|
||||
@@ -347,6 +362,8 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return !Idle();
|
||||
}
|
||||
|
||||
Camera PanCameraInput::StepCamera(
|
||||
@@ -411,7 +428,7 @@ namespace AzFramework
|
||||
{
|
||||
}
|
||||
|
||||
void TranslateCameraInput::HandleEvents(
|
||||
bool TranslateCameraInput::HandleEvents(
|
||||
const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta)
|
||||
{
|
||||
if (const auto& input = AZStd::get_if<DiscreteInputEvent>(&event))
|
||||
@@ -429,7 +446,8 @@ namespace AzFramework
|
||||
m_boost = true;
|
||||
}
|
||||
}
|
||||
else if (input->m_state == InputChannel::State::Ended)
|
||||
// ensure we don't process end events in the idle state
|
||||
else if (input->m_state == InputChannel::State::Ended && !Idle())
|
||||
{
|
||||
m_translation &= ~(translationFromKey(input->m_channelId));
|
||||
if (m_translation == TranslationType::Nil)
|
||||
@@ -442,6 +460,8 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return !Idle();
|
||||
}
|
||||
|
||||
Camera TranslateCameraInput::StepCamera(
|
||||
@@ -503,7 +523,7 @@ namespace AzFramework
|
||||
m_boost = false;
|
||||
}
|
||||
|
||||
void OrbitCameraInput::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta)
|
||||
bool OrbitCameraInput::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta)
|
||||
{
|
||||
if (const auto* input = AZStd::get_if<DiscreteInputEvent>(&event))
|
||||
{
|
||||
@@ -522,8 +542,10 @@ namespace AzFramework
|
||||
|
||||
if (Active())
|
||||
{
|
||||
m_orbitCameras.HandleEvents(event, cursorDelta, scrollDelta);
|
||||
return m_orbitCameras.HandleEvents(event, cursorDelta, scrollDelta);
|
||||
}
|
||||
|
||||
return !Idle();
|
||||
}
|
||||
|
||||
Camera OrbitCameraInput::StepCamera(
|
||||
@@ -533,7 +555,7 @@ namespace AzFramework
|
||||
|
||||
if (Beginning())
|
||||
{
|
||||
const auto hasLookAt = [&nextCamera, &targetCamera, lookAtFn = m_lookAtFn] {
|
||||
const auto hasLookAt = [&nextCamera, &targetCamera, &lookAtFn = m_lookAtFn] {
|
||||
if (lookAtFn)
|
||||
{
|
||||
if (const auto lookAt = lookAtFn())
|
||||
@@ -585,13 +607,15 @@ namespace AzFramework
|
||||
return nextCamera;
|
||||
}
|
||||
|
||||
void OrbitDollyScrollCameraInput::HandleEvents(
|
||||
bool OrbitDollyScrollCameraInput::HandleEvents(
|
||||
const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta)
|
||||
{
|
||||
if (const auto* scroll = AZStd::get_if<ScrollEvent>(&event))
|
||||
{
|
||||
BeginActivation();
|
||||
}
|
||||
|
||||
return !Idle();
|
||||
}
|
||||
|
||||
Camera OrbitDollyScrollCameraInput::StepCamera(
|
||||
@@ -609,7 +633,7 @@ namespace AzFramework
|
||||
{
|
||||
}
|
||||
|
||||
void OrbitDollyCursorMoveCameraInput::HandleEvents(
|
||||
bool OrbitDollyCursorMoveCameraInput::HandleEvents(
|
||||
const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta)
|
||||
{
|
||||
if (const auto& input = AZStd::get_if<DiscreteInputEvent>(&event))
|
||||
@@ -626,6 +650,8 @@ namespace AzFramework
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return !Idle();
|
||||
}
|
||||
|
||||
Camera OrbitDollyCursorMoveCameraInput::StepCamera(
|
||||
@@ -637,13 +663,15 @@ namespace AzFramework
|
||||
return nextCamera;
|
||||
}
|
||||
|
||||
void ScrollTranslationCameraInput::HandleEvents(
|
||||
bool ScrollTranslationCameraInput::HandleEvents(
|
||||
const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta)
|
||||
{
|
||||
if (const auto* scroll = AZStd::get_if<ScrollEvent>(&event))
|
||||
{
|
||||
BeginActivation();
|
||||
}
|
||||
|
||||
return !Idle();
|
||||
}
|
||||
|
||||
Camera ScrollTranslationCameraInput::StepCamera(
|
||||
@@ -694,7 +722,7 @@ namespace AzFramework
|
||||
return camera;
|
||||
}
|
||||
|
||||
InputEvent BuildInputEvent(const InputChannel& inputChannel, const WindowSize& windowSize)
|
||||
InputEvent BuildInputEvent(const InputChannel& inputChannel)
|
||||
{
|
||||
const auto& inputChannelId = inputChannel.GetInputChannelId();
|
||||
const auto& inputDeviceId = inputChannel.GetInputDevice().GetInputDeviceId();
|
||||
@@ -704,13 +732,13 @@ namespace AzFramework
|
||||
return button == inputChannelId;
|
||||
});
|
||||
|
||||
if (inputChannelId == InputDeviceMouse::Movement::X || inputChannelId == InputDeviceMouse::Movement::Y)
|
||||
if (inputChannelId == InputDeviceMouse::Movement::X)
|
||||
{
|
||||
const auto* position = inputChannel.GetCustomData<AzFramework::InputChannel::PositionData2D>();
|
||||
AZ_Assert(position, "Expected PositionData2D but found nullptr");
|
||||
|
||||
return CursorEvent{ScreenPoint(
|
||||
position->m_normalizedPosition.GetX() * windowSize.m_width, position->m_normalizedPosition.GetY() * windowSize.m_height)};
|
||||
return HorizontalMotionEvent{(int)inputChannel.GetValue()};
|
||||
}
|
||||
else if (inputChannelId == InputDeviceMouse::Movement::Y)
|
||||
{
|
||||
return VerticalMotionEvent{(int)inputChannel.GetValue()};
|
||||
}
|
||||
else if (inputChannelId == InputDeviceMouse::Movement::Z)
|
||||
{
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
#include <AzCore/std/optional.h>
|
||||
#include <AzFramework/Input/Channels/InputChannel.h>
|
||||
#include <AzFramework/Viewport/ClickDetector.h>
|
||||
#include <AzFramework/Viewport/CursorState.h>
|
||||
#include <AzFramework/Viewport/ScreenGeometry.h>
|
||||
#include <AzFramework/Viewport/ViewportId.h>
|
||||
|
||||
@@ -72,11 +71,16 @@ namespace AzFramework
|
||||
|
||||
void UpdateCameraFromTransform(Camera& camera, const AZ::Transform& transform);
|
||||
|
||||
struct CursorEvent
|
||||
//! Generic motion type
|
||||
template<typename MotionTag>
|
||||
struct MotionEvent
|
||||
{
|
||||
ScreenPoint m_position;
|
||||
int m_delta;
|
||||
};
|
||||
|
||||
using HorizontalMotionEvent = MotionEvent<struct HorizontalMotionTag>;
|
||||
using VerticalMotionEvent = MotionEvent<struct VerticalMotionTag>;
|
||||
|
||||
struct ScrollEvent
|
||||
{
|
||||
float m_delta;
|
||||
@@ -88,7 +92,7 @@ namespace AzFramework
|
||||
InputChannel::State m_state; //!< Channel state. (e.g. Begin/update/end event).
|
||||
};
|
||||
|
||||
using InputEvent = AZStd::variant<AZStd::monostate, CursorEvent, ScrollEvent, DiscreteInputEvent>;
|
||||
using InputEvent = AZStd::variant<AZStd::monostate, HorizontalMotionEvent, VerticalMotionEvent, ScrollEvent, DiscreteInputEvent>;
|
||||
|
||||
class CameraInput
|
||||
{
|
||||
@@ -149,7 +153,7 @@ namespace AzFramework
|
||||
ResetImpl();
|
||||
}
|
||||
|
||||
virtual void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) = 0;
|
||||
virtual bool HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) = 0;
|
||||
virtual Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) = 0;
|
||||
|
||||
virtual bool Exclusive() const
|
||||
@@ -171,16 +175,30 @@ namespace AzFramework
|
||||
class Cameras
|
||||
{
|
||||
public:
|
||||
void AddCamera(AZStd::shared_ptr<CameraInput> cameraInput);
|
||||
bool HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta);
|
||||
Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime);
|
||||
|
||||
void AddCamera(AZStd::shared_ptr<CameraInput> cameraInput);
|
||||
//! Reset the state of all cameras.
|
||||
void Reset();
|
||||
//! Remove all cameras that were added.
|
||||
void Clear();
|
||||
//! Is one of the cameras in the active camera inputs marked as 'exclusive'.
|
||||
//! @note This implies no other sibling cameras can begin while the exclusive camera is running.
|
||||
bool Exclusive() const;
|
||||
|
||||
private:
|
||||
AZStd::vector<AZStd::shared_ptr<CameraInput>> m_activeCameraInputs;
|
||||
AZStd::vector<AZStd::shared_ptr<CameraInput>> m_idleCameraInputs;
|
||||
};
|
||||
|
||||
inline bool Cameras::Exclusive() const
|
||||
{
|
||||
return AZStd::any_of(
|
||||
m_activeCameraInputs.begin(), m_activeCameraInputs.end(), [](const auto& cameraInput) { return cameraInput->Exclusive(); });
|
||||
}
|
||||
|
||||
//! Responsible for updating a series of cameras given various inputs.
|
||||
class CameraSystem
|
||||
{
|
||||
public:
|
||||
@@ -190,8 +208,8 @@ namespace AzFramework
|
||||
Cameras m_cameras;
|
||||
|
||||
private:
|
||||
CursorState m_cursorState;
|
||||
float m_scrollDelta = 0.0f;
|
||||
ScreenVector m_motionDelta; //!< The delta used for look/orbit/pan (rotation + translation) - two dimensional.
|
||||
float m_scrollDelta = 0.0f; //!< The delta used for dolly/movement (translation) - one dimensional.
|
||||
};
|
||||
|
||||
class RotateCameraInput : public CameraInput
|
||||
@@ -200,7 +218,7 @@ namespace AzFramework
|
||||
explicit RotateCameraInput(InputChannelId rotateChannelId);
|
||||
|
||||
// CameraInput overrides ...
|
||||
void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
bool HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override;
|
||||
|
||||
private:
|
||||
@@ -241,7 +259,7 @@ namespace AzFramework
|
||||
PanCameraInput(InputChannelId panChannelId, PanAxesFn panAxesFn);
|
||||
|
||||
// CameraInput overrides ...
|
||||
void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
bool HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override;
|
||||
|
||||
private:
|
||||
@@ -282,7 +300,7 @@ namespace AzFramework
|
||||
explicit TranslateCameraInput(TranslationAxesFn translationAxesFn);
|
||||
|
||||
// CameraInput overrides ...
|
||||
void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
bool HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override;
|
||||
void ResetImpl() override;
|
||||
|
||||
@@ -352,7 +370,7 @@ namespace AzFramework
|
||||
{
|
||||
public:
|
||||
// CameraInput overrides ...
|
||||
void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
bool HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override;
|
||||
};
|
||||
|
||||
@@ -362,7 +380,7 @@ namespace AzFramework
|
||||
explicit OrbitDollyCursorMoveCameraInput(InputChannelId dollyChannelId);
|
||||
|
||||
// CameraInput overrides ...
|
||||
void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
bool HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override;
|
||||
|
||||
private:
|
||||
@@ -373,7 +391,7 @@ namespace AzFramework
|
||||
{
|
||||
public:
|
||||
// CameraInput overrides ...
|
||||
void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
bool HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override;
|
||||
};
|
||||
|
||||
@@ -383,7 +401,7 @@ namespace AzFramework
|
||||
using LookAtFn = AZStd::function<AZStd::optional<AZ::Vector3>()>;
|
||||
|
||||
// CameraInput overrides ...
|
||||
void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
bool HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override;
|
||||
Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override;
|
||||
bool Exclusive() const override;
|
||||
|
||||
@@ -406,8 +424,6 @@ namespace AzFramework
|
||||
return true;
|
||||
}
|
||||
|
||||
struct WindowSize;
|
||||
|
||||
//! Map from a generic InputChannel event to a camera specific InputEvent.
|
||||
InputEvent BuildInputEvent(const InputChannel& inputChannel, const WindowSize& windowSize);
|
||||
InputEvent BuildInputEvent(const InputChannel& inputChannel);
|
||||
} // namespace AzFramework
|
||||
|
||||
@@ -17,6 +17,17 @@ namespace AzFramework
|
||||
{
|
||||
ClickDetector::ClickOutcome ClickDetector::DetectClick(const ClickEvent clickEvent, const ScreenVector& cursorDelta)
|
||||
{
|
||||
const auto previousDetectionState = m_detectionState;
|
||||
if (previousDetectionState == DetectionState::WaitingForMove)
|
||||
{
|
||||
// only allow the action to begin if the mouse has been moved a small amount
|
||||
m_moveAccumulator += ScreenVectorLength(cursorDelta);
|
||||
if (m_moveAccumulator > m_deadZone)
|
||||
{
|
||||
m_detectionState = DetectionState::Moved;
|
||||
}
|
||||
}
|
||||
|
||||
if (clickEvent == ClickEvent::Down)
|
||||
{
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
@@ -52,15 +63,9 @@ namespace AzFramework
|
||||
return clickOutcome;
|
||||
}
|
||||
|
||||
if (m_detectionState == DetectionState::WaitingForMove)
|
||||
if (previousDetectionState == DetectionState::WaitingForMove && m_detectionState == DetectionState::Moved)
|
||||
{
|
||||
// only allow the action to begin if the mouse has been moved a small amount
|
||||
m_moveAccumulator += ScreenVectorLength(cursorDelta);
|
||||
if (m_moveAccumulator > m_deadZone)
|
||||
{
|
||||
m_detectionState = DetectionState::Moved;
|
||||
return ClickOutcome::Move;
|
||||
}
|
||||
return ClickOutcome::Move;
|
||||
}
|
||||
|
||||
return ClickOutcome::Nil;
|
||||
|
||||
@@ -50,7 +50,11 @@ namespace AzFramework
|
||||
//! Called from any type of 'handle event' function.
|
||||
ClickOutcome DetectClick(ClickEvent clickEvent, const ScreenVector& cursorDelta);
|
||||
|
||||
//! Override the default double click interval.
|
||||
//! @note Default is 400ms - system default.
|
||||
void SetDoubleClickInterval(float doubleClickInterval);
|
||||
//! Override the dead zone before a 'move' outcome will be triggered.
|
||||
void SetDeadZone(float deadZone);
|
||||
|
||||
private:
|
||||
//! Internal state of ClickDetector based on incoming events.
|
||||
@@ -72,4 +76,9 @@ namespace AzFramework
|
||||
{
|
||||
m_doubleClickInterval = doubleClickInterval;
|
||||
}
|
||||
|
||||
inline void ClickDetector::SetDeadZone(const float deadZone)
|
||||
{
|
||||
m_deadZone = deadZone;
|
||||
}
|
||||
} // namespace AzFramework
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
namespace AzNetworking
|
||||
{
|
||||
using NetworkInterfaces = AZStd::unordered_map<AZ::Name, AZStd::unique_ptr<INetworkInterface>>;
|
||||
|
||||
//! @class INetworking
|
||||
//! @brief The interface for creating and working with network interfaces.
|
||||
class INetworking
|
||||
@@ -60,5 +62,25 @@ namespace AzNetworking
|
||||
//! @param name The name of the Compressor factory to unregister, must match result of factory->GetFactoryName()
|
||||
//! @return Whether the factory was found and unregistered
|
||||
virtual bool UnregisterCompressorFactory(AZ::Name name) = 0;
|
||||
|
||||
//! Returns the raw network interfaces owned by the networking instance.
|
||||
//! @return the raw network interfaces owned by the networking instance
|
||||
virtual const NetworkInterfaces& GetNetworkInterfaces() const = 0;
|
||||
|
||||
//! Returns the number of sockets monitored by our TcpListenThread.
|
||||
//! @return the number of sockets monitored by our TcpListenThread
|
||||
virtual uint32_t GetTcpListenThreadSocketCount() const = 0;
|
||||
|
||||
//! Returns the total time spent updating our TcpListenThread.
|
||||
//! @return the total time spent updating our TcpListenThread
|
||||
virtual AZ::TimeMs GetTcpListenThreadUpdateTime() const = 0;
|
||||
|
||||
//! Returns the number of sockets monitored by our UdpReaderThread.
|
||||
//! @return the number of sockets monitored by our UdpReaderThread
|
||||
virtual uint32_t GetUdpReaderThreadSocketCount() const = 0;
|
||||
|
||||
//! Returns the total time spent updating our UdpReaderThread.
|
||||
//! @return the total time spent updating our UdpReaderThread
|
||||
virtual AZ::TimeMs GetUdpReaderThreadUpdateTime() const = 0;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -149,12 +149,37 @@ namespace AzNetworking
|
||||
return m_compressorFactories.erase(name) > 0;
|
||||
}
|
||||
|
||||
const NetworkInterfaces& NetworkingSystemComponent::GetNetworkInterfaces() const
|
||||
{
|
||||
return m_networkInterfaces;
|
||||
}
|
||||
|
||||
uint32_t NetworkingSystemComponent::GetTcpListenThreadSocketCount() const
|
||||
{
|
||||
return m_listenThread->GetSocketCount();
|
||||
}
|
||||
|
||||
AZ::TimeMs NetworkingSystemComponent::GetTcpListenThreadUpdateTime() const
|
||||
{
|
||||
return m_listenThread->GetUpdateTimeMs();
|
||||
}
|
||||
|
||||
uint32_t NetworkingSystemComponent::GetUdpReaderThreadSocketCount() const
|
||||
{
|
||||
return m_readerThread->GetSocketCount();
|
||||
}
|
||||
|
||||
AZ::TimeMs NetworkingSystemComponent::GetUdpReaderThreadUpdateTime() const
|
||||
{
|
||||
return m_readerThread->GetUpdateTimeMs();
|
||||
}
|
||||
|
||||
void NetworkingSystemComponent::DumpStats([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments)
|
||||
{
|
||||
AZLOG_INFO("Total sockets monitored by TcpListenThread: %u", m_listenThread->GetSocketCount());
|
||||
AZLOG_INFO("Total time spent updating TcpListenThread: %lld", aznumeric_cast<AZ::s64>(m_listenThread->GetUpdateTimeMs()));
|
||||
AZLOG_INFO("Total sockets monitored by UdpReaderThread: %u", m_readerThread->GetSocketCount());
|
||||
AZLOG_INFO("Total time spent updating UdpReaderThread: %lld", aznumeric_cast<AZ::s64>(m_readerThread->GetUpdateTimeMs()));
|
||||
AZLOG_INFO("Total sockets monitored by TcpListenThread: %u", GetTcpListenThreadSocketCount());
|
||||
AZLOG_INFO("Total time spent updating TcpListenThread: %lld", aznumeric_cast<AZ::s64>(GetTcpListenThreadUpdateTime()));
|
||||
AZLOG_INFO("Total sockets monitored by UdpReaderThread: %u", GetUdpReaderThreadSocketCount());
|
||||
AZLOG_INFO("Total time spent updating UdpReaderThread: %lld", aznumeric_cast<AZ::s64>(GetUdpReaderThreadUpdateTime()));
|
||||
|
||||
for (auto& networkInterface : m_networkInterfaces)
|
||||
{
|
||||
|
||||
@@ -63,6 +63,11 @@ namespace AzNetworking
|
||||
void RegisterCompressorFactory(ICompressorFactory* factory) override;
|
||||
AZStd::unique_ptr<ICompressor> CreateCompressor(AZ::Name name) override;
|
||||
bool UnregisterCompressorFactory(AZ::Name name) override;
|
||||
const NetworkInterfaces& GetNetworkInterfaces() const override;
|
||||
uint32_t GetTcpListenThreadSocketCount() const override;
|
||||
AZ::TimeMs GetTcpListenThreadUpdateTime() const override;
|
||||
uint32_t GetUdpReaderThreadSocketCount() const override;
|
||||
AZ::TimeMs GetUdpReaderThreadUpdateTime() const override;
|
||||
//! @}
|
||||
|
||||
//! Console commands.
|
||||
@@ -74,7 +79,6 @@ namespace AzNetworking
|
||||
|
||||
AZ_CONSOLEFUNC(NetworkingSystemComponent, DumpStats, AZ::ConsoleFunctorFlags::Null, "Dumps stats for all instantiated network interfaces");
|
||||
|
||||
using NetworkInterfaces = AZStd::unordered_map<AZ::Name, AZStd::unique_ptr<INetworkInterface>>;
|
||||
NetworkInterfaces m_networkInterfaces;
|
||||
AZStd::unique_ptr<TcpListenThread> m_listenThread;
|
||||
AZStd::unique_ptr<UdpReaderThread> m_readerThread;
|
||||
|
||||
@@ -46,6 +46,12 @@ namespace AzNetworking
|
||||
|
||||
void TcpSocketManager::ProcessEvents(AZ::TimeMs maxBlockMs, const SocketEventCallback& readCallback, const SocketEventCallback& writeCallback)
|
||||
{
|
||||
if(static_cast<int32_t>(m_maxFd) <= 0 && m_socketFds.empty())
|
||||
{
|
||||
// There are no available sockets to process
|
||||
return;
|
||||
}
|
||||
|
||||
m_readerFdSet = m_sourceFdSet;
|
||||
m_writerFdSet = m_sourceFdSet;
|
||||
|
||||
|
||||
@@ -52,6 +52,21 @@ namespace AzToolsFramework
|
||||
* Deletes all entities in the provided list, as well as their transform descendants.
|
||||
*/
|
||||
virtual void DeleteEntitiesAndAllDescendants(const EntityIdList& entities) = 0;
|
||||
|
||||
/**
|
||||
* Duplicate all currently-selected entities.
|
||||
*/
|
||||
virtual void DuplicateSelected() = 0;
|
||||
|
||||
/**
|
||||
* Duplicates the specified entity.
|
||||
*/
|
||||
virtual void DuplicateEntityById(AZ::EntityId entityId) = 0;
|
||||
|
||||
/**
|
||||
* Duplicates all specified entities.
|
||||
*/
|
||||
virtual void DuplicateEntities(const EntityIdList& entities) = 0;
|
||||
};
|
||||
|
||||
} // namespace AzToolsFramework
|
||||
|
||||
+20
-2
@@ -43,7 +43,7 @@ namespace AzToolsFramework
|
||||
|
||||
void EditorEntityManager::DeleteEntityById(AZ::EntityId entityId)
|
||||
{
|
||||
DeleteEntities({entityId});
|
||||
DeleteEntities(EntityIdList{ entityId });
|
||||
}
|
||||
|
||||
void EditorEntityManager::DeleteEntities(const EntityIdList& entities)
|
||||
@@ -53,12 +53,30 @@ namespace AzToolsFramework
|
||||
|
||||
void EditorEntityManager::DeleteEntityAndAllDescendants(AZ::EntityId entityId)
|
||||
{
|
||||
DeleteEntitiesAndAllDescendants({entityId});
|
||||
DeleteEntitiesAndAllDescendants(EntityIdList{ entityId });
|
||||
}
|
||||
|
||||
void EditorEntityManager::DeleteEntitiesAndAllDescendants(const EntityIdList& entities)
|
||||
{
|
||||
m_prefabPublicInterface->DeleteEntitiesAndAllDescendantsInInstance(entities);
|
||||
}
|
||||
|
||||
void EditorEntityManager::DuplicateSelected()
|
||||
{
|
||||
EntityIdList selectedEntities;
|
||||
ToolsApplicationRequestBus::BroadcastResult(selectedEntities, &ToolsApplicationRequests::GetSelectedEntities);
|
||||
|
||||
m_prefabPublicInterface->DuplicateEntitiesInInstance(selectedEntities);
|
||||
}
|
||||
|
||||
void EditorEntityManager::DuplicateEntityById(AZ::EntityId entityId)
|
||||
{
|
||||
DuplicateEntities(EntityIdList{ entityId });
|
||||
}
|
||||
|
||||
void EditorEntityManager::DuplicateEntities(const EntityIdList& entities)
|
||||
{
|
||||
m_prefabPublicInterface->DuplicateEntitiesInInstance(entities);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,9 @@ namespace AzToolsFramework
|
||||
void DeleteEntities(const EntityIdList& entities) override;
|
||||
void DeleteEntityAndAllDescendants(AZ::EntityId entityId) override;
|
||||
void DeleteEntitiesAndAllDescendants(const EntityIdList& entities) override;
|
||||
void DuplicateSelected() override;
|
||||
void DuplicateEntityById(AZ::EntityId entityId) override;
|
||||
void DuplicateEntities(const EntityIdList& entities) override;
|
||||
|
||||
private:
|
||||
Prefab::PrefabPublicInterface* m_prefabPublicInterface = nullptr;
|
||||
|
||||
@@ -28,6 +28,7 @@ namespace AzToolsFramework
|
||||
inline static const char* PatchesName = "Patches";
|
||||
inline static const char* SourceName = "Source";
|
||||
inline static const char* LinkIdName = "LinkId";
|
||||
inline static const char* EntityIdName = "Id";
|
||||
inline static const char* EntitiesName = "Entities";
|
||||
inline static const char* ContainerEntityName = "ContainerEntity";
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
#include <AzToolsFramework/Prefab/PrefabPublicHandler.h>
|
||||
|
||||
#include <AzCore/Component/TransformBus.h>
|
||||
#include <AzCore/JSON/stringbuffer.h>
|
||||
#include <AzCore/JSON/writer.h>
|
||||
#include <AzCore/Utils/TypeHash.h>
|
||||
|
||||
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
|
||||
@@ -31,6 +33,8 @@
|
||||
#include <AzToolsFramework/Prefab/PrefabUndoHelpers.h>
|
||||
#include <AzToolsFramework/ToolsComponents/TransformComponent.h>
|
||||
|
||||
#include <QString>
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
namespace Prefab
|
||||
@@ -83,7 +87,9 @@ namespace AzToolsFramework
|
||||
commonRootInstanceDomBeforeCreate, commonRootEntityOwningInstance->get());
|
||||
|
||||
AZStd::vector<AZ::Entity*> entities;
|
||||
AZStd::vector<AZStd::unique_ptr<Instance>> instances;
|
||||
AZStd::vector<AZStd::unique_ptr<Instance>> instancePtrs;
|
||||
AZStd::vector<Instance*> instances;
|
||||
AZStd::unordered_map<Instance*, PrefabDom> nestedInstanceLinkPatchesMap;
|
||||
|
||||
// Retrieve all entities affected and identify Instances
|
||||
if (!RetrieveAndSortPrefabEntitiesAndInstances(inputEntityList, commonRootEntityOwningInstance->get(), entities, instances))
|
||||
@@ -92,11 +98,31 @@ namespace AzToolsFramework
|
||||
AZStd::string("Could not create a new prefab out of the entities provided - invalid selection."));
|
||||
}
|
||||
|
||||
// Detach the retrieved entities
|
||||
for (AZ::Entity* entity : entities)
|
||||
{
|
||||
commonRootEntityOwningInstance->get().DetachEntity(entity->GetId()).release();
|
||||
}
|
||||
|
||||
// When we create a prefab with other prefab instances, we have to remove the existing links between the source and
|
||||
// target templates of the other instances.
|
||||
for (auto& nestedInstance : instances)
|
||||
{
|
||||
RemoveLink(nestedInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch());
|
||||
AZStd::unique_ptr<Instance> outInstance = commonRootEntityOwningInstance->get().DetachNestedInstance(nestedInstance->GetInstanceAlias());
|
||||
|
||||
auto linkRef = m_prefabSystemComponentInterface->FindLink(nestedInstance->GetLinkId());
|
||||
|
||||
if (linkRef.has_value())
|
||||
{
|
||||
PrefabDom oldLinkPatches;
|
||||
oldLinkPatches.CopyFrom(linkRef->get().GetLinkDom(), oldLinkPatches.GetAllocator());
|
||||
|
||||
nestedInstanceLinkPatchesMap.emplace(nestedInstance, AZStd::move(oldLinkPatches));
|
||||
}
|
||||
|
||||
RemoveLink(outInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch());
|
||||
|
||||
instancePtrs.emplace_back(AZStd::move(outInstance));
|
||||
}
|
||||
|
||||
PrefabUndoHelpers::UpdatePrefabInstance(
|
||||
@@ -112,7 +138,7 @@ namespace AzToolsFramework
|
||||
|
||||
// Create the Prefab
|
||||
instanceToCreate = prefabEditorEntityOwnershipInterface->CreatePrefab(
|
||||
entities, AZStd::move(instances), filePath, commonRootEntityOwningInstance);
|
||||
entities, AZStd::move(instancePtrs), filePath, commonRootEntityOwningInstance);
|
||||
|
||||
if (!instanceToCreate)
|
||||
{
|
||||
@@ -122,6 +148,9 @@ namespace AzToolsFramework
|
||||
|
||||
AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId();
|
||||
|
||||
// Apply the correct transform to the container for the new instance, and store the patch for use when creating the link.
|
||||
PrefabDom patch = ApplyContainerTransformAndGeneratePatch(containerEntityId, commonRootEntityId, topLevelEntities);
|
||||
|
||||
// Parent the non-container top level entities to the container entity.
|
||||
// Parenting the top level container entities will be done during the creation of links.
|
||||
for (AZ::Entity* topLevelEntity : topLevelEntities)
|
||||
@@ -141,35 +170,55 @@ namespace AzToolsFramework
|
||||
|
||||
instanceToCreate->get().GetNestedInstances([&](AZStd::unique_ptr<Instance>& nestedInstance) {
|
||||
AZ_Assert(nestedInstance, "Invalid nested instance found in the new prefab created.");
|
||||
|
||||
EntityOptionalReference nestedInstanceContainerEntity = nestedInstance->GetContainerEntity();
|
||||
AZ_Assert(
|
||||
nestedInstanceContainerEntity, "Invalid container entity found for the nested instance used in prefab creation.");
|
||||
|
||||
AZ::EntityId parentId;
|
||||
AZ::TransformBus::EventResult(
|
||||
parentId, nestedInstanceContainerEntity->get().GetId(), &AZ::TransformBus::Events::GetParentId);
|
||||
AZ::EntityId nestedInstanceContainerEntityId = nestedInstanceContainerEntity->get().GetId();
|
||||
PrefabDom previousPatch;
|
||||
|
||||
auto entityIterator = AZStd::find_if(
|
||||
entities.begin(), entities.end(), [parentId](AZ::Entity* entity) { return entity->GetId() == parentId; });
|
||||
|
||||
// If the previous parent entity of the nested instance is not part of the entities of the newly created prefab,
|
||||
// then set the parent of the nested prefab as the container entity of the newly created prefab.
|
||||
if (entityIterator == entities.end())
|
||||
// Retrieve the previous patch if it exists
|
||||
if (nestedInstanceLinkPatchesMap.contains(nestedInstance.get()))
|
||||
{
|
||||
parentId = containerEntityId;
|
||||
previousPatch = AZStd::move(nestedInstanceLinkPatchesMap[nestedInstance.get()]);
|
||||
}
|
||||
|
||||
// These link creations shouldn't be undone because that would put the template in a non-usable state if a user
|
||||
// chooses to instantiate the template after undoing the creation.
|
||||
CreateLink(
|
||||
{&nestedInstanceContainerEntity->get()}, *nestedInstance, instanceToCreate->get().GetTemplateId(),
|
||||
undoBatch.GetUndoBatch(), parentId, false);
|
||||
CreateLink(*nestedInstance, instanceToCreate->get().GetTemplateId(), undoBatch.GetUndoBatch(), AZStd::move(previousPatch), false);
|
||||
|
||||
// If this nested instance's container is a top level entity in the new prefab, re-parent it and apply the change.
|
||||
if (AZStd::find(topLevelEntities.begin(), topLevelEntities.end(), &nestedInstanceContainerEntity->get()) != topLevelEntities.end())
|
||||
{
|
||||
Prefab::PrefabDom containerEntityDomBefore;
|
||||
m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomBefore, *nestedInstanceContainerEntity);
|
||||
|
||||
AZ::TransformBus::Event(nestedInstanceContainerEntityId, &AZ::TransformBus::Events::SetParent, containerEntityId);
|
||||
|
||||
PrefabDom containerEntityDomAfter;
|
||||
m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomAfter, *nestedInstanceContainerEntity);
|
||||
|
||||
PrefabDom reparentPatch;
|
||||
m_instanceToTemplateInterface->GeneratePatch(reparentPatch, containerEntityDomBefore, containerEntityDomAfter);
|
||||
m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(reparentPatch, nestedInstanceContainerEntityId);
|
||||
|
||||
// Update the cache - this prevents these changes from being stored in the regular undo/redo nodes as a separate step
|
||||
m_prefabUndoCache.Store(nestedInstanceContainerEntityId, AZStd::move(containerEntityDomAfter));
|
||||
|
||||
// Save these changes as patches to the link
|
||||
PrefabUndoLinkUpdate* linkUpdate = aznew PrefabUndoLinkUpdate(AZStd::to_string(static_cast<AZ::u64>(nestedInstanceContainerEntityId)));
|
||||
linkUpdate->SetParent(undoBatch.GetUndoBatch());
|
||||
linkUpdate->Capture(reparentPatch, nestedInstance->GetLinkId());
|
||||
|
||||
linkUpdate->Redo();
|
||||
}
|
||||
});
|
||||
|
||||
// Create a link between the templates of the newly created instance and the instance it's being parented under.
|
||||
CreateLink(
|
||||
topLevelEntities, instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(),
|
||||
undoBatch.GetUndoBatch(), commonRootEntityId);
|
||||
instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(),
|
||||
AZStd::move(patch));
|
||||
|
||||
for (AZ::Entity* topLevelEntity : topLevelEntities)
|
||||
{
|
||||
@@ -199,6 +248,40 @@ namespace AzToolsFramework
|
||||
return AZ::Success();
|
||||
}
|
||||
|
||||
PrefabDom PrefabPublicHandler::ApplyContainerTransformAndGeneratePatch(AZ::EntityId containerEntityId, AZ::EntityId parentEntityId, const EntityList& childEntities)
|
||||
{
|
||||
AZ::Entity* containerEntity = GetEntityById(containerEntityId);
|
||||
AZ_Assert(containerEntity, "Invalid container entity passed to ApplyContainerTransformAndGeneratePatch.");
|
||||
|
||||
// Generate the transform for the container entity out of the top level entities, and set it
|
||||
// This step needs to be done before anything is parented to the container, else children position will be wrong
|
||||
Prefab::PrefabDom containerEntityDomBefore;
|
||||
m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomBefore, *containerEntity);
|
||||
|
||||
AZ::Vector3 containerEntityTranslation(AZ::Vector3::CreateZero());
|
||||
AZ::Quaternion containerEntityRotation(AZ::Quaternion::CreateZero());
|
||||
|
||||
// Set container entity to be child of common root
|
||||
AZ::TransformBus::Event(containerEntityId, &AZ::TransformBus::Events::SetParent, parentEntityId);
|
||||
|
||||
// Set the transform (translation, rotation) of the container entity
|
||||
GenerateContainerEntityTransform(childEntities, containerEntityTranslation, containerEntityRotation);
|
||||
AZ::TransformBus::Event(containerEntityId, &AZ::TransformBus::Events::SetLocalTranslation, containerEntityTranslation);
|
||||
AZ::TransformBus::Event(containerEntityId, &AZ::TransformBus::Events::SetLocalRotationQuaternion, containerEntityRotation);
|
||||
|
||||
PrefabDom containerEntityDomAfter;
|
||||
m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomAfter, *containerEntity);
|
||||
|
||||
PrefabDom patch;
|
||||
m_instanceToTemplateInterface->GeneratePatch(patch, containerEntityDomBefore, containerEntityDomAfter);
|
||||
m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, containerEntityId);
|
||||
|
||||
// Update the cache - this prevents these changes from being stored in the regular undo/redo nodes
|
||||
m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter));
|
||||
|
||||
return AZStd::move(patch);
|
||||
}
|
||||
|
||||
PrefabOperationResult PrefabPublicHandler::InstantiatePrefab(
|
||||
AZStd::string_view filePath, AZ::EntityId parent, const AZ::Vector3& position)
|
||||
{
|
||||
@@ -249,10 +332,10 @@ namespace AzToolsFramework
|
||||
// Initialize Undo Batch object
|
||||
ScopedUndoBatch undoBatch("Instantiate Prefab");
|
||||
|
||||
// Instantiate the Prefab
|
||||
PrefabDom instanceToParentUnderDomBeforeCreate;
|
||||
m_instanceToTemplateInterface->GenerateDomForInstance(instanceToParentUnderDomBeforeCreate, instanceToParentUnder->get());
|
||||
|
||||
// Instantiate the Prefab
|
||||
auto instanceToCreate = prefabEditorEntityOwnershipInterface->InstantiatePrefab(relativePath, instanceToParentUnder);
|
||||
|
||||
if (!instanceToCreate)
|
||||
@@ -264,11 +347,32 @@ namespace AzToolsFramework
|
||||
PrefabUndoHelpers::UpdatePrefabInstance(
|
||||
instanceToParentUnder->get(), "Update prefab instance", instanceToParentUnderDomBeforeCreate, undoBatch.GetUndoBatch());
|
||||
|
||||
CreateLink({}, instanceToCreate->get(), instanceToParentUnder->get().GetTemplateId(), undoBatch.GetUndoBatch(), parent);
|
||||
// Create Link with correct container patches
|
||||
AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId();
|
||||
AZ::Entity* containerEntity = GetEntityById(containerEntityId);
|
||||
AZ_Assert(containerEntity, "Invalid container entity detected in InstantiatePrefab.");
|
||||
|
||||
// Apply position
|
||||
Prefab::PrefabDom containerEntityDomBefore;
|
||||
m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomBefore, *containerEntity);
|
||||
|
||||
// Set container entity's parent
|
||||
AZ::TransformBus::Event(containerEntityId, &AZ::TransformBus::Events::SetParent, parent);
|
||||
|
||||
// Set the position of the container entity
|
||||
AZ::TransformBus::Event(containerEntityId, &AZ::TransformBus::Events::SetWorldTranslation, position);
|
||||
|
||||
PrefabDom containerEntityDomAfter;
|
||||
m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomAfter, *containerEntity);
|
||||
|
||||
// Generate patch to be stored in the link
|
||||
PrefabDom patch;
|
||||
m_instanceToTemplateInterface->GeneratePatch(patch, containerEntityDomBefore, containerEntityDomAfter);
|
||||
m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, containerEntityId);
|
||||
|
||||
CreateLink(instanceToCreate->get(), instanceToParentUnder->get().GetTemplateId(), undoBatch.GetUndoBatch(), AZStd::move(patch));
|
||||
|
||||
// Update the cache - this prevents these changes from being stored in the regular undo/redo nodes
|
||||
m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter));
|
||||
}
|
||||
|
||||
return AZ::Success();
|
||||
@@ -299,7 +403,7 @@ namespace AzToolsFramework
|
||||
// Find common root and top level entities
|
||||
bool entitiesHaveCommonRoot = false;
|
||||
|
||||
AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(
|
||||
AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(
|
||||
entitiesHaveCommonRoot, &AzToolsFramework::ToolsApplicationRequests::FindCommonRootInactive, inputEntityList,
|
||||
commonRootEntityId, &topLevelEntities);
|
||||
|
||||
@@ -335,33 +439,9 @@ namespace AzToolsFramework
|
||||
}
|
||||
|
||||
void PrefabPublicHandler::CreateLink(
|
||||
const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId,
|
||||
UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool isUndoRedoSupportNeeded)
|
||||
Instance& sourceInstance, TemplateId targetTemplateId,
|
||||
UndoSystem::URSequencePoint* undoBatch, PrefabDom patch, const bool isUndoRedoSupportNeeded)
|
||||
{
|
||||
AZ::EntityId containerEntityId = sourceInstance.GetContainerEntityId();
|
||||
AZ::Entity* containerEntity = GetEntityById(containerEntityId);
|
||||
Prefab::PrefabDom containerEntityDomBefore;
|
||||
m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomBefore, *containerEntity);
|
||||
|
||||
AZ::Vector3 containerEntityTranslation(AZ::Vector3::CreateZero());
|
||||
AZ::Quaternion containerEntityRotation(AZ::Quaternion::CreateZero());
|
||||
|
||||
// Set the transform (translation, rotation) of the container entity
|
||||
GenerateContainerEntityTransform(topLevelEntities, containerEntityTranslation, containerEntityRotation);
|
||||
|
||||
// Set container entity to be child of common root
|
||||
AZ::TransformBus::Event(containerEntityId, &AZ::TransformBus::Events::SetParent, commonRootEntityId);
|
||||
|
||||
AZ::TransformBus::Event(containerEntityId, &AZ::TransformBus::Events::SetLocalTranslation, containerEntityTranslation);
|
||||
AZ::TransformBus::Event(containerEntityId, &AZ::TransformBus::Events::SetLocalRotationQuaternion, containerEntityRotation);
|
||||
|
||||
PrefabDom containerEntityDomAfter;
|
||||
m_instanceToTemplateInterface->GenerateDomForEntity(containerEntityDomAfter, *containerEntity);
|
||||
|
||||
PrefabDom patch;
|
||||
m_instanceToTemplateInterface->GeneratePatch(patch, containerEntityDomBefore, containerEntityDomAfter);
|
||||
m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, containerEntityId);
|
||||
|
||||
LinkId linkId;
|
||||
if (isUndoRedoSupportNeeded)
|
||||
{
|
||||
@@ -377,9 +457,6 @@ namespace AzToolsFramework
|
||||
}
|
||||
|
||||
sourceInstance.SetLinkId(linkId);
|
||||
|
||||
// Update the cache - this prevents these changes from being stored in the regular undo/redo nodes
|
||||
m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter));
|
||||
}
|
||||
|
||||
void PrefabPublicHandler::RemoveLink(
|
||||
@@ -648,6 +725,151 @@ namespace AzToolsFramework
|
||||
return DeleteFromInstance(entityIds, true);
|
||||
}
|
||||
|
||||
PrefabOperationResult PrefabPublicHandler::DuplicateEntitiesInInstance(const EntityIdList& entityIds)
|
||||
{
|
||||
if (entityIds.empty())
|
||||
{
|
||||
return AZ::Failure(AZStd::string("No entities to duplicate."));
|
||||
}
|
||||
|
||||
if (!EntitiesBelongToSameInstance(entityIds))
|
||||
{
|
||||
return AZ::Failure(AZStd::string("Cannot duplicate multiple "
|
||||
"entities belonging to different instances with one operation."));
|
||||
}
|
||||
|
||||
// We've already verified the entities are all owned by the same instance,
|
||||
// so we can just retrieve our instance from the first entity in the list.
|
||||
InstanceOptionalReference commonEntityOwningInstance = GetOwnerInstanceByEntityId(entityIds[0]);
|
||||
AZ_Assert(
|
||||
commonEntityOwningInstance.has_value(),
|
||||
"Failed to duplicate : Couldn't get a valid owning instance for the common root entity of the entities provided");
|
||||
|
||||
// This will cull out any entities that have ancestors in the list, since we will end up duplicating
|
||||
// the full nested hierarchy with what is returned from RetrieveAndSortPrefabEntitiesAndInstances
|
||||
AzToolsFramework::EntityIdSet duplicationSet = AzToolsFramework::GetCulledEntityHierarchy(entityIds);
|
||||
|
||||
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
|
||||
|
||||
ScopedUndoBatch undoBatch("Duplicate Entities");
|
||||
|
||||
{
|
||||
AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "DuplicateEntitiesInInstance::UndoCaptureAndDuplicateEntities");
|
||||
|
||||
// Take a snapshot of the instance DOM before we manipulate it
|
||||
Prefab::PrefabDom instanceDomBefore;
|
||||
m_instanceToTemplateInterface->GenerateDomForInstance(instanceDomBefore, commonEntityOwningInstance->get());
|
||||
|
||||
AZStd::vector<AZ::Entity*> entities;
|
||||
AZStd::vector<Instance*> instances;
|
||||
|
||||
// Gather all entities/instances in the hierarchy, but don't detach them because we are duplicating not deleting.
|
||||
EntityList inputEntityList = EntityIdSetToEntityList(duplicationSet);
|
||||
bool success = RetrieveAndSortPrefabEntitiesAndInstances(inputEntityList, commonEntityOwningInstance->get(), entities, instances);
|
||||
|
||||
if (!success)
|
||||
{
|
||||
return AZ::Failure(AZStd::string("Failed to retrieve entities and instances from the given list of entity ids for duplication"));
|
||||
}
|
||||
|
||||
// Make a copy of our before instance DOM where we will add our duplicated entities
|
||||
Prefab::PrefabDom instanceDomAfter;
|
||||
instanceDomAfter.CopyFrom(instanceDomBefore, instanceDomAfter.GetAllocator());
|
||||
|
||||
AZStd::unordered_map<EntityAlias, EntityAlias> oldAliasToNewAliasMap;
|
||||
AZStd::unordered_map<EntityAlias, QString> aliasToEntityDomMap;
|
||||
|
||||
for (AZ::Entity* entity : entities)
|
||||
{
|
||||
EntityAliasOptionalReference oldAliasRef = commonEntityOwningInstance->get().GetEntityAlias(entity->GetId());
|
||||
AZ_Assert(oldAliasRef.has_value(), "No alias found for Entity in the DOM");
|
||||
EntityAlias oldAlias = oldAliasRef.value();
|
||||
|
||||
// Give this the outer allocator so that the memory reference will be valid when
|
||||
// it gets used for AddMember
|
||||
Prefab::PrefabDom entityDomBefore(&instanceDomAfter.GetAllocator());
|
||||
m_instanceToTemplateInterface->GenerateDomForEntity(entityDomBefore, *entity);
|
||||
|
||||
// Keep track of the old alias <-> new alias mapping for this duplicated entity
|
||||
// so we can fixup references later
|
||||
EntityAlias newEntityAlias = Instance::GenerateEntityAlias();
|
||||
oldAliasToNewAliasMap.insert(AZStd::make_pair(oldAlias, newEntityAlias));
|
||||
|
||||
rapidjson::StringBuffer buffer;
|
||||
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
|
||||
entityDomBefore.Accept(writer);
|
||||
|
||||
// Store our duplicated Entity DOM with its new alias as a string
|
||||
// so that we can fixup entity alias references before adding it
|
||||
// to the Entities member of our instance DOM
|
||||
QString entityDomString(buffer.GetString());
|
||||
aliasToEntityDomMap.insert(AZStd::make_pair(newEntityAlias, entityDomString));
|
||||
}
|
||||
|
||||
auto entitiesIter = instanceDomAfter.FindMember(PrefabDomUtils::EntitiesName);
|
||||
AZ_Assert(entitiesIter != instanceDomAfter.MemberEnd(), "Instance DOM missing the Entities member.");
|
||||
|
||||
// Now that all the duplicated Entity DOMs have been created, we need to iterate
|
||||
// through them and replace any previous EntityAlias references with the new ones.
|
||||
// These are more than just parent entity references for nested entities, this will
|
||||
// also cover any EntityId references that were made in the components between them.
|
||||
for (auto aliasEntityPair : aliasToEntityDomMap)
|
||||
{
|
||||
EntityAlias newEntityAlias = aliasEntityPair.first;
|
||||
QString newEntityDomString = aliasEntityPair.second;
|
||||
|
||||
// Replace all of the old alias references with the new ones
|
||||
// We bookend the aliases with \" and also with a / as an extra precaution to prevent
|
||||
// inadvertently replacing a matching string vs. where an actual EntityId is expected
|
||||
// This will cover both cases where an alias could be used in a normal entity vs. an instance
|
||||
for (auto aliasMapIter : oldAliasToNewAliasMap)
|
||||
{
|
||||
QString oldAliasQuotes = QString("\"%1\"").arg(aliasMapIter.first.c_str());
|
||||
QString newAliasQuotes = QString("\"%1\"").arg(aliasMapIter.second.c_str());
|
||||
|
||||
newEntityDomString.replace(oldAliasQuotes, newAliasQuotes);
|
||||
|
||||
QString oldAliasPathRef = QString("/%1").arg(aliasMapIter.first.c_str());
|
||||
QString newAliasPathRef = QString("/%1").arg(aliasMapIter.second.c_str());
|
||||
|
||||
newEntityDomString.replace(oldAliasPathRef, newAliasPathRef);
|
||||
}
|
||||
|
||||
// Create the new Entity DOM from parsing the JSON string
|
||||
Prefab::PrefabDom entityDomAfter(&instanceDomAfter.GetAllocator());
|
||||
entityDomAfter.Parse(newEntityDomString.toUtf8().constData());
|
||||
|
||||
// Add the new Entity DOM to the Entities member of the instance
|
||||
rapidjson::Value aliasName(newEntityAlias.c_str(), newEntityAlias.length(), instanceDomAfter.GetAllocator());
|
||||
entitiesIter->value.AddMember(AZStd::move(aliasName), entityDomAfter, instanceDomAfter.GetAllocator());
|
||||
}
|
||||
|
||||
PrefabUndoInstance* command = aznew PrefabUndoInstance("Entity duplication");
|
||||
command->SetParent(undoBatch.GetUndoBatch());
|
||||
command->Capture(instanceDomBefore, instanceDomAfter, commonEntityOwningInstance->get().GetTemplateId());
|
||||
command->RunRedo();
|
||||
|
||||
EntityIdList duplicatedEntityIds;
|
||||
for (auto aliasMapIter : oldAliasToNewAliasMap)
|
||||
{
|
||||
EntityAlias newEntityAlias = aliasMapIter.second;
|
||||
|
||||
AliasPath absoluteEntityPath = commonEntityOwningInstance->get().GetAbsoluteInstanceAliasPath();
|
||||
absoluteEntityPath.Append(newEntityAlias);
|
||||
|
||||
AZ::EntityId newEntityId = InstanceEntityIdMapper::GenerateEntityIdForAliasPath(absoluteEntityPath);
|
||||
duplicatedEntityIds.push_back(newEntityId);
|
||||
}
|
||||
|
||||
// Select the duplicated entities
|
||||
auto selectionUndo = aznew SelectionCommand(duplicatedEntityIds, "Select Duplicated Entities");
|
||||
selectionUndo->SetParent(undoBatch.GetUndoBatch());
|
||||
ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequestBus::Events::RunRedoSeparately, selectionUndo);
|
||||
}
|
||||
|
||||
return AZ::Success();
|
||||
}
|
||||
|
||||
PrefabOperationResult PrefabPublicHandler::DeleteFromInstance(const EntityIdList& entityIds, bool deleteDescendants)
|
||||
{
|
||||
if (entityIds.empty())
|
||||
@@ -675,17 +897,7 @@ namespace AzToolsFramework
|
||||
|
||||
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
|
||||
|
||||
UndoSystem::URSequencePoint* currentUndoBatch = nullptr;
|
||||
ToolsApplicationRequests::Bus::BroadcastResult(currentUndoBatch, &ToolsApplicationRequests::Bus::Events::GetCurrentUndoBatch);
|
||||
|
||||
bool createdUndo = false;
|
||||
if (!currentUndoBatch)
|
||||
{
|
||||
createdUndo = true;
|
||||
ToolsApplicationRequests::Bus::BroadcastResult(
|
||||
currentUndoBatch, &ToolsApplicationRequests::Bus::Events::BeginUndoBatch, "Delete Selected");
|
||||
AZ_Assert(currentUndoBatch, "Failed to create new undo batch.");
|
||||
}
|
||||
ScopedUndoBatch undoBatch("Delete Selected");
|
||||
|
||||
// In order to undo DeleteSelected, we have to create a selection command which selects the current selection
|
||||
// and then add the deletion as children.
|
||||
@@ -713,7 +925,7 @@ namespace AzToolsFramework
|
||||
if (deleteDescendants)
|
||||
{
|
||||
AZStd::vector<AZ::Entity*> entities;
|
||||
AZStd::vector<AZStd::unique_ptr<Instance>> instances;
|
||||
AZStd::vector<Instance*> instances;
|
||||
|
||||
bool success = RetrieveAndSortPrefabEntitiesAndInstances(inputEntityList, commonOwningInstance->get(), entities, instances);
|
||||
|
||||
@@ -724,13 +936,15 @@ namespace AzToolsFramework
|
||||
|
||||
for (AZ::Entity* entity : entities)
|
||||
{
|
||||
commonOwningInstance->get().DetachEntity(entity->GetId()).release();
|
||||
AZ::ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationRequests::DeleteEntity, entity->GetId());
|
||||
}
|
||||
|
||||
for (auto& nestedInstance : instances)
|
||||
{
|
||||
RemoveLink(nestedInstance, commonOwningInstance->get().GetTemplateId(), currentUndoBatch);
|
||||
nestedInstance.reset();
|
||||
AZStd::unique_ptr<Instance> outInstance = commonOwningInstance->get().DetachNestedInstance(nestedInstance->GetInstanceAlias());
|
||||
RemoveLink(outInstance, commonOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch());
|
||||
outInstance.reset();
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -742,7 +956,7 @@ namespace AzToolsFramework
|
||||
if (owningInstance->get().GetContainerEntityId() == entityId)
|
||||
{
|
||||
auto instancePtr = commonOwningInstance->get().DetachNestedInstance(owningInstance->get().GetInstanceAlias());
|
||||
RemoveLink(instancePtr, commonOwningInstance->get().GetTemplateId(), currentUndoBatch);
|
||||
RemoveLink(instancePtr, commonOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch());
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -760,17 +974,12 @@ namespace AzToolsFramework
|
||||
command->SetParent(selCommand);
|
||||
}
|
||||
|
||||
selCommand->SetParent(currentUndoBatch);
|
||||
selCommand->SetParent(undoBatch.GetUndoBatch());
|
||||
{
|
||||
AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzToolsFramework, "Internal::DeleteEntities:RunRedo");
|
||||
selCommand->RunRedo();
|
||||
}
|
||||
|
||||
if (createdUndo)
|
||||
{
|
||||
ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::EndUndoBatch);
|
||||
}
|
||||
|
||||
return AZ::Success();
|
||||
}
|
||||
|
||||
@@ -882,7 +1091,7 @@ namespace AzToolsFramework
|
||||
|
||||
bool PrefabPublicHandler::RetrieveAndSortPrefabEntitiesAndInstances(
|
||||
const EntityList& inputEntities, Instance& commonRootEntityOwningInstance,
|
||||
EntityList& outEntities, AZStd::vector<AZStd::unique_ptr<Instance>>& outInstances) const
|
||||
EntityList& outEntities, AZStd::vector<Instance*>& outInstances) const
|
||||
{
|
||||
if (inputEntities.size() == 0)
|
||||
{
|
||||
@@ -966,14 +1175,14 @@ namespace AzToolsFramework
|
||||
|
||||
for (AZ::Entity* entity : entities)
|
||||
{
|
||||
outEntities.emplace_back(commonRootEntityOwningInstance.DetachEntity(entity->GetId()).release());
|
||||
outEntities.emplace_back(entity);
|
||||
}
|
||||
|
||||
outInstances.clear();
|
||||
outInstances.reserve(instances.size());
|
||||
for (Instance* instancePtr : instances)
|
||||
{
|
||||
outInstances.push_back(AZStd::move(commonRootEntityOwningInstance.DetachNestedInstance(instancePtr->GetInstanceAlias())));
|
||||
outInstances.push_back(instancePtr);
|
||||
}
|
||||
|
||||
return (outEntities.size() + outInstances.size()) > 0;
|
||||
|
||||
@@ -60,28 +60,41 @@ namespace AzToolsFramework
|
||||
|
||||
PrefabOperationResult DeleteEntitiesInInstance(const EntityIdList& entityIds) override;
|
||||
PrefabOperationResult DeleteEntitiesAndAllDescendantsInInstance(const EntityIdList& entityIds) override;
|
||||
PrefabOperationResult DuplicateEntitiesInInstance(const EntityIdList& entityIds) override;
|
||||
|
||||
private:
|
||||
PrefabOperationResult DeleteFromInstance(const EntityIdList& entityIds, bool deleteDescendants);
|
||||
bool RetrieveAndSortPrefabEntitiesAndInstances(const EntityList& inputEntities, Instance& commonRootEntityOwningInstance,
|
||||
EntityList& outEntities, AZStd::vector<AZStd::unique_ptr<Instance>>& outInstances) const;
|
||||
EntityList& outEntities, AZStd::vector<Instance*>& outInstances) const;
|
||||
|
||||
InstanceOptionalReference GetOwnerInstanceByEntityId(AZ::EntityId entityId) const;
|
||||
bool EntitiesBelongToSameInstance(const EntityIdList& entityIds) const;
|
||||
|
||||
/**
|
||||
* Applies the correct transform changes to the container entity based on the parent and child entities provided, and returns an appropriate patch.
|
||||
* The container will be parented to parentId, moved to the average transform of the future direct children and its cache will be updated.
|
||||
* This helper function won't support undo/redo, update the templates or create any links. All that needs to be done by the caller.
|
||||
*
|
||||
* \param containerEntityId The container to apply the changes to.
|
||||
* \param parentEntityId The id of the entity the container should be parented to.
|
||||
* \param childEntities A list of entities that will subsequently be parented to this container.
|
||||
* \return The PrefabDom containing the patches that should be stored in the parent link.
|
||||
*/
|
||||
PrefabDom ApplyContainerTransformAndGeneratePatch(
|
||||
AZ::EntityId containerEntityId, AZ::EntityId parentEntityId, const EntityList& childEntities);
|
||||
|
||||
/**
|
||||
* Creates a link between the templates of an instance and its parent.
|
||||
*
|
||||
* \param topLevelEntities The list of entities that are immediate children to the container entity of the instance.
|
||||
* \param sourceInstance The instance that corresponds to the source template of the link.
|
||||
* \param targetInstance The id of the target template.
|
||||
* \param undoBatch The undo batch to set as parent for this create link action.
|
||||
* \param commonRootEntityId The id of the entity that the source instance should be parented under.
|
||||
* \param patch The patch to store in the newly created link dom.
|
||||
* \param isUndoRedoSupportNeeded The flag indicating whether the link should be created with undo/redo support or not.
|
||||
*/
|
||||
void CreateLink(
|
||||
const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId,
|
||||
UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool isUndoRedoSupportNeeded = true);
|
||||
Instance& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch,
|
||||
PrefabDom patch, const bool isUndoRedoSupportNeeded = true);
|
||||
|
||||
/**
|
||||
* Removes the link between template of the sourceInstance and the template corresponding to targetTemplateId.
|
||||
|
||||
@@ -143,6 +143,13 @@ namespace AzToolsFramework
|
||||
* @return An outcome object; on failure, it comes with an error message detailing the cause of the error.
|
||||
*/
|
||||
virtual PrefabOperationResult DeleteEntitiesAndAllDescendantsInInstance(const EntityIdList& entityIds) = 0;
|
||||
|
||||
/**
|
||||
* Duplicates all entities in the owning instance. Bails if the entities don't all belong to the same instance.
|
||||
* @param entities The entities to duplicate.
|
||||
* @return An outcome object; on failure, it comes with an error message detailing the cause of the error.
|
||||
*/
|
||||
virtual PrefabOperationResult DuplicateEntitiesInInstance(const EntityIdList& entityIds) = 0;
|
||||
};
|
||||
|
||||
} // namespace Prefab
|
||||
|
||||
+11
@@ -63,6 +63,7 @@
|
||||
#include <AzToolsFramework/UI/Outliner/EntityOutlinerDisplayOptionsMenu.h>
|
||||
#include <AzToolsFramework/UI/Outliner/EntityOutlinerSortFilterProxyModel.hxx>
|
||||
#include <AzToolsFramework/UI/Outliner/EntityOutlinerTreeView.hxx>
|
||||
#include <AzToolsFramework/UI/Outliner/EntityOutlinerCacheBus.h>
|
||||
#include <AzToolsFramework/UI/UICore/WidgetHelpers.h>
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
@@ -1409,6 +1410,16 @@ namespace AzToolsFramework
|
||||
{
|
||||
(void)name;
|
||||
QueueEntityUpdate(entityId);
|
||||
|
||||
bool isSelected = false;
|
||||
AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(
|
||||
isSelected, &AzToolsFramework::ToolsApplicationRequests::IsSelected, entityId);
|
||||
|
||||
if (isSelected)
|
||||
{
|
||||
// Ask the system to scroll to the entity in case it is off screen after the rename
|
||||
EntityOutlinerModelNotificationBus::Broadcast(&EntityOutlinerModelNotifications::QueueScrollToNewContent, entityId);
|
||||
}
|
||||
}
|
||||
|
||||
void EntityOutlinerListModel::OnEntityInfoUpdatedUnsavedChanges(AZ::EntityId entityId)
|
||||
|
||||
+42
-61
@@ -93,28 +93,12 @@ namespace AzToolsFramework
|
||||
EditorContextMenuBus::Handler::BusConnect();
|
||||
PrefabInstanceContainerNotificationBus::Handler::BusConnect();
|
||||
AZ::Interface<PrefabIntegrationInterface>::Register(this);
|
||||
|
||||
bool prefabWipFeaturesEnabled = false;
|
||||
AzFramework::ApplicationRequests::Bus::BroadcastResult(
|
||||
prefabWipFeaturesEnabled, &AzFramework::ApplicationRequests::ArePrefabWipFeaturesEnabled);
|
||||
|
||||
if (prefabWipFeaturesEnabled)
|
||||
{
|
||||
AssetBrowser::AssetBrowserSourceDropBus::Handler::BusConnect(s_prefabFileExtension);
|
||||
}
|
||||
AssetBrowser::AssetBrowserSourceDropBus::Handler::BusConnect(s_prefabFileExtension);
|
||||
}
|
||||
|
||||
PrefabIntegrationManager::~PrefabIntegrationManager()
|
||||
{
|
||||
bool prefabWipFeaturesEnabled = false;
|
||||
AzFramework::ApplicationRequests::Bus::BroadcastResult(
|
||||
prefabWipFeaturesEnabled, &AzFramework::ApplicationRequests::ArePrefabWipFeaturesEnabled);
|
||||
|
||||
if (prefabWipFeaturesEnabled)
|
||||
{
|
||||
AssetBrowser::AssetBrowserSourceDropBus::Handler::BusDisconnect();
|
||||
}
|
||||
|
||||
AssetBrowser::AssetBrowserSourceDropBus::Handler::BusDisconnect();
|
||||
AZ::Interface<PrefabIntegrationInterface>::Unregister(this);
|
||||
PrefabInstanceContainerNotificationBus::Handler::BusDisconnect();
|
||||
EditorContextMenuBus::Handler::BusDisconnect();
|
||||
@@ -137,66 +121,63 @@ namespace AzToolsFramework
|
||||
|
||||
void PrefabIntegrationManager::PopulateEditorGlobalContextMenu(QMenu* menu) const
|
||||
{
|
||||
bool prefabWipFeaturesEnabled = false;
|
||||
AzFramework::ApplicationRequests::Bus::BroadcastResult(
|
||||
prefabWipFeaturesEnabled, &AzFramework::ApplicationRequests::ArePrefabWipFeaturesEnabled);
|
||||
|
||||
AzToolsFramework::EntityIdList selectedEntities;
|
||||
AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(
|
||||
selectedEntities, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities);
|
||||
|
||||
if (prefabWipFeaturesEnabled)
|
||||
bool prefabWipFeaturesEnabled = false;
|
||||
AzFramework::ApplicationRequests::Bus::BroadcastResult(
|
||||
prefabWipFeaturesEnabled, &AzFramework::ApplicationRequests::ArePrefabWipFeaturesEnabled);
|
||||
|
||||
// Create Prefab
|
||||
{
|
||||
// Create Prefab
|
||||
if (!selectedEntities.empty())
|
||||
{
|
||||
if (!selectedEntities.empty())
|
||||
// Hide if the only selected entity is the Level Container
|
||||
if (selectedEntities.size() > 1 || !s_prefabPublicInterface->IsLevelInstanceContainerEntity(selectedEntities[0]))
|
||||
{
|
||||
// Hide if the only selected entity is the Level Container
|
||||
if (selectedEntities.size() > 1 || !s_prefabPublicInterface->IsLevelInstanceContainerEntity(selectedEntities[0]))
|
||||
bool layerInSelection = false;
|
||||
|
||||
for (AZ::EntityId entityId : selectedEntities)
|
||||
{
|
||||
bool layerInSelection = false;
|
||||
|
||||
for (AZ::EntityId entityId : selectedEntities)
|
||||
{
|
||||
if (!layerInSelection)
|
||||
{
|
||||
AzToolsFramework::Layers::EditorLayerComponentRequestBus::EventResult(
|
||||
layerInSelection, entityId,
|
||||
&AzToolsFramework::Layers::EditorLayerComponentRequestBus::Events::HasLayer);
|
||||
|
||||
if (layerInSelection)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Layers can't be in prefabs.
|
||||
if (!layerInSelection)
|
||||
{
|
||||
QAction* createAction = menu->addAction(QObject::tr("Create Prefab..."));
|
||||
createAction->setToolTip(QObject::tr("Creates a prefab out of the currently selected entities."));
|
||||
AzToolsFramework::Layers::EditorLayerComponentRequestBus::EventResult(
|
||||
layerInSelection, entityId,
|
||||
&AzToolsFramework::Layers::EditorLayerComponentRequestBus::Events::HasLayer);
|
||||
|
||||
QObject::connect(createAction, &QAction::triggered, createAction, [this, selectedEntities] {
|
||||
ContextMenu_CreatePrefab(selectedEntities);
|
||||
});
|
||||
if (layerInSelection)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Layers can't be in prefabs.
|
||||
if (!layerInSelection)
|
||||
{
|
||||
QAction* createAction = menu->addAction(QObject::tr("Create Prefab..."));
|
||||
createAction->setToolTip(QObject::tr("Creates a prefab out of the currently selected entities."));
|
||||
|
||||
QObject::connect(createAction, &QAction::triggered, createAction, [this, selectedEntities] {
|
||||
ContextMenu_CreatePrefab(selectedEntities);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Instantiate Prefab
|
||||
{
|
||||
QAction* instantiateAction = menu->addAction(QObject::tr("Instantiate Prefab..."));
|
||||
instantiateAction->setToolTip(QObject::tr("Instantiates a prefab file in the scene."));
|
||||
|
||||
QObject::connect(
|
||||
instantiateAction, &QAction::triggered, instantiateAction, [this] { ContextMenu_InstantiatePrefab(); });
|
||||
}
|
||||
|
||||
menu->addSeparator();
|
||||
}
|
||||
|
||||
// Instantiate Prefab
|
||||
{
|
||||
QAction* instantiateAction = menu->addAction(QObject::tr("Instantiate Prefab..."));
|
||||
instantiateAction->setToolTip(QObject::tr("Instantiates a prefab file in the scene."));
|
||||
|
||||
QObject::connect(
|
||||
instantiateAction, &QAction::triggered, instantiateAction, [this] { ContextMenu_InstantiatePrefab(); });
|
||||
}
|
||||
|
||||
menu->addSeparator();
|
||||
|
||||
bool itemWasShown = false;
|
||||
|
||||
// Edit/Save Prefab
|
||||
|
||||
+7
-1
@@ -138,7 +138,7 @@ namespace UnitTest
|
||||
if (!GetApplication())
|
||||
{
|
||||
// Create & Start a new ToolsApplication if there's no existing one
|
||||
m_app = AZStd::make_unique<ToolsTestApplication>("ToolsApplication");
|
||||
m_app = CreateTestApplication();
|
||||
m_app->Start(AzFramework::Application::Descriptor());
|
||||
}
|
||||
|
||||
@@ -216,6 +216,12 @@ namespace UnitTest
|
||||
TestEditorActions m_editorActions;
|
||||
ToolsApplicationMessageHandler m_messageHandler; // used to suppress trace messages in test output
|
||||
|
||||
// Override this if your test fixture needs to use a custom TestApplication
|
||||
virtual AZStd::unique_ptr<ToolsTestApplication> CreateTestApplication()
|
||||
{
|
||||
return AZStd::make_unique<ToolsTestApplication>("ToolsApplication");
|
||||
}
|
||||
|
||||
private:
|
||||
AZStd::unique_ptr<ToolsTestApplication> m_app;
|
||||
};
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <AzFramework/Entity/EntityDebugDisplayBus.h>
|
||||
#include <AzFramework/Viewport/CameraState.h>
|
||||
#include <AzFramework/Viewport/ViewportId.h>
|
||||
#include <AzFramework/Viewport/ClickDetector.h>
|
||||
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
|
||||
#include <AzToolsFramework/Viewport/ViewportTypes.h>
|
||||
|
||||
@@ -304,4 +305,24 @@ namespace AzToolsFramework
|
||||
|
||||
return entityContextId;
|
||||
}
|
||||
|
||||
//! Maps a mouse interaction event to a ClickDetector event.
|
||||
//! @note Function only cares about up or down events, all other events are mapped to Nil (ignored).
|
||||
inline AzFramework::ClickDetector::ClickEvent ClickDetectorEventFromViewportInteraction(
|
||||
const ViewportInteraction::MouseInteractionEvent& mouseInteraction)
|
||||
{
|
||||
if (mouseInteraction.m_mouseInteraction.m_mouseButtons.Left())
|
||||
{
|
||||
if (mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::Down)
|
||||
{
|
||||
return AzFramework::ClickDetector::ClickEvent::Down;
|
||||
}
|
||||
|
||||
if (mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::Up)
|
||||
{
|
||||
return AzFramework::ClickDetector::ClickEvent::Up;
|
||||
}
|
||||
}
|
||||
return AzFramework::ClickDetector::ClickEvent::Nil;
|
||||
}
|
||||
} // namespace AzToolsFramework
|
||||
|
||||
+9
-4
@@ -14,6 +14,7 @@
|
||||
|
||||
#include <AzFramework/Entity/EntityDebugDisplayBus.h>
|
||||
#include <AzToolsFramework/ViewportSelection/EditorSelectionUtil.h>
|
||||
#include <AzToolsFramework/Viewport/ViewportMessages.h>
|
||||
|
||||
#include <QApplication>
|
||||
|
||||
@@ -27,8 +28,11 @@ namespace AzToolsFramework
|
||||
{
|
||||
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
|
||||
|
||||
if (mouseInteraction.m_mouseInteraction.m_mouseButtons.Left() &&
|
||||
mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::Down)
|
||||
m_cursorState.SetCurrentPosition(mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates);
|
||||
|
||||
const auto selectClickEvent = ClickDetectorEventFromViewportInteraction(mouseInteraction);
|
||||
const auto clickOutcome = m_clickDetector.DetectClick(selectClickEvent, m_cursorState.CursorDelta());
|
||||
if (clickOutcome == AzFramework::ClickDetector::ClickOutcome::Move)
|
||||
{
|
||||
if (m_leftMouseDown)
|
||||
{
|
||||
@@ -58,8 +62,7 @@ namespace AzToolsFramework
|
||||
}
|
||||
}
|
||||
|
||||
if (mouseInteraction.m_mouseInteraction.m_mouseButtons.Left() &&
|
||||
mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::Up)
|
||||
if (clickOutcome == AzFramework::ClickDetector::ClickOutcome::Release)
|
||||
{
|
||||
if (m_leftMouseUp)
|
||||
{
|
||||
@@ -77,6 +80,8 @@ namespace AzToolsFramework
|
||||
{
|
||||
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
|
||||
|
||||
m_cursorState.Update();
|
||||
|
||||
if (m_boxSelectRegion)
|
||||
{
|
||||
debugDisplay.DepthTestOff();
|
||||
|
||||
+21
-17
@@ -14,6 +14,8 @@
|
||||
|
||||
#include <AzCore/std/functional.h>
|
||||
#include <AzCore/std/optional.h>
|
||||
#include <AzFramework/Viewport/ClickDetector.h>
|
||||
#include <AzFramework/Viewport/CursorState.h>
|
||||
#include <AzToolsFramework/Viewport/ViewportTypes.h>
|
||||
|
||||
#include <QRect>
|
||||
@@ -26,49 +28,49 @@ namespace AzFramework
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
/// Utility to provide box select (click and drag) support for viewport types.
|
||||
/// Users can override the mouse event callbacks and display scene function to customize behavior.
|
||||
//! Utility to provide box select (click and drag) support for viewport types.
|
||||
//! Users can override the mouse event callbacks and display scene function to customize behavior.
|
||||
class EditorBoxSelect
|
||||
{
|
||||
public:
|
||||
EditorBoxSelect() = default;
|
||||
|
||||
/// Return if a box select action is currently taking place.
|
||||
//! Return if a box select action is currently taking place.
|
||||
bool Active() const { return m_boxSelectRegion.has_value(); }
|
||||
|
||||
/// Update the box select for various mouse events.
|
||||
/// Call HandleMouseInteraction from type/system implementing MouseViewportRequests interface.
|
||||
//! Update the box select for various mouse events.
|
||||
//! Call HandleMouseInteraction from type/system implementing MouseViewportRequests interface.
|
||||
void HandleMouseInteraction(
|
||||
const ViewportInteraction::MouseInteractionEvent& mouseInteraction);
|
||||
|
||||
/// Responsible for drawing the 2d box representing the selection in screen space.
|
||||
//! Responsible for drawing the 2d box representing the selection in screen space.
|
||||
void Display2d(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay);
|
||||
|
||||
/// Custom drawing behavior to happen during a box select.
|
||||
//! Custom drawing behavior to happen during a box select.
|
||||
void DisplayScene(
|
||||
const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay);
|
||||
|
||||
/// Set the left mouse down callback.
|
||||
//! Set the left mouse down callback.
|
||||
void InstallLeftMouseDown(
|
||||
const AZStd::function<void(const ViewportInteraction::MouseInteractionEvent& mouseInteraction)>& leftMouseDown);
|
||||
/// Set the mouse move callback.
|
||||
//! Set the mouse move callback.
|
||||
void InstallMouseMove(
|
||||
const AZStd::function<void(const ViewportInteraction::MouseInteractionEvent& mouseInteraction)>& mouseMove);
|
||||
/// Set the left mouse up callback.
|
||||
//! Set the left mouse up callback.
|
||||
void InstallLeftMouseUp(
|
||||
const AZStd::function<void()>& leftMouseUp);
|
||||
/// Set the display scene callback.
|
||||
//! Set the display scene callback.
|
||||
void InstallDisplayScene(
|
||||
const AZStd::function<void(
|
||||
const AzFramework::ViewportInfo& viewportInfo,
|
||||
AzFramework::DebugDisplayRequests& debugDisplay)>& displayScene);
|
||||
|
||||
/// Return the box select region.
|
||||
/// If a box selection is being made, return the current rectangle representing the area.
|
||||
/// If there is currently no active box select, then the Maybe type will be empty (there will be no region/area).
|
||||
//! Return the box select region.
|
||||
//! If a box selection is being made, return the current rectangle representing the area.
|
||||
//! If there is currently no active box select, then the Maybe type will be empty (there will be no region/area).
|
||||
const AZStd::optional<QRect>& BoxRegion() const { return m_boxSelectRegion; }
|
||||
|
||||
/// Return the active modifiers from the previous frame.
|
||||
//! Return the active modifiers from the previous frame.
|
||||
ViewportInteraction::KeyboardModifiers PreviousModifiers() const { return m_previousModifiers; }
|
||||
|
||||
private:
|
||||
@@ -79,7 +81,9 @@ namespace AzToolsFramework
|
||||
AZStd::function<void(
|
||||
const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay)> m_displayScene;
|
||||
|
||||
AZStd::optional<QRect> m_boxSelectRegion; ///< Maybe/optional value to store box select region while active.
|
||||
ViewportInteraction::KeyboardModifiers m_previousModifiers; ///< Modifier keys active on the previous frame.
|
||||
AZStd::optional<QRect> m_boxSelectRegion; //!< Maybe/optional value to store box select region while active.
|
||||
ViewportInteraction::KeyboardModifiers m_previousModifiers; //!< Modifier keys active on the previous frame.
|
||||
AzFramework::ClickDetector m_clickDetector; //!< Utility type to detect if a mouse click or move has occurred.
|
||||
AzFramework::CursorState m_cursorState; //!< Utility type to track the current cursor position (and movement/delta).
|
||||
};
|
||||
} // namespace AzToolsFramework
|
||||
|
||||
+1
-16
@@ -1782,22 +1782,7 @@ namespace AzToolsFramework
|
||||
|
||||
m_cachedEntityIdUnderCursor = m_editorHelpers->HandleMouseInteraction(cameraState, mouseInteraction);
|
||||
|
||||
const AzFramework::ClickDetector::ClickEvent selectClickEvent = [&mouseInteraction] {
|
||||
if (mouseInteraction.m_mouseInteraction.m_mouseButtons.Left())
|
||||
{
|
||||
if (mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::Down)
|
||||
{
|
||||
return AzFramework::ClickDetector::ClickEvent::Down;
|
||||
}
|
||||
|
||||
if (mouseInteraction.m_mouseEvent == ViewportInteraction::MouseEvent::Up)
|
||||
{
|
||||
return AzFramework::ClickDetector::ClickEvent::Up;
|
||||
}
|
||||
}
|
||||
return AzFramework::ClickDetector::ClickEvent::Nil;
|
||||
}();
|
||||
|
||||
const auto selectClickEvent = ClickDetectorEventFromViewportInteraction(mouseInteraction);
|
||||
m_cursorState.SetCurrentPosition(mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates);
|
||||
const auto clickOutcome = m_clickDetector.DetectClick(selectClickEvent, m_cursorState.CursorDelta());
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* 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 <AzToolsFramework/ToolsComponents/TransformComponent.h>
|
||||
|
||||
#include <Prefab/PrefabTestComponent.h>
|
||||
#include <Prefab/PrefabTestDomUtils.h>
|
||||
#include <Prefab/PrefabTestFixture.h>
|
||||
|
||||
namespace UnitTest
|
||||
{
|
||||
using PrefabDuplicateTest = PrefabTestFixture;
|
||||
|
||||
TEST_F(PrefabDuplicateTest, PrefabDuplicate_DuplicateSingleEntitySucceeds)
|
||||
{
|
||||
AZStd::string entityName("Same Name");
|
||||
AZ::Entity* entity1 = CreateEntity(entityName.c_str());
|
||||
entity1->Deactivate();
|
||||
entity1->CreateComponent<PrefabTestComponent>();
|
||||
entity1->Activate();
|
||||
|
||||
AzToolsFramework::EditorEntityContextRequestBus::Broadcast(
|
||||
&AzToolsFramework::EditorEntityContextRequests::HandleEntitiesAdded, AzToolsFramework::EntityList{ entity1 });
|
||||
AZStd::unique_ptr<Instance> newInstance = m_prefabSystemComponent->CreatePrefab(
|
||||
{ entity1 },
|
||||
{},
|
||||
PrefabMockFilePath);
|
||||
|
||||
// We've created a prefab with a single Entity, so there should only be one EntityAlias in our instance
|
||||
EXPECT_EQ(newInstance->GetEntityAliases().size(), 1);
|
||||
|
||||
// Duplicate the Entity and trigger the UpdateTemplateInstancesInQueue so the changes get propagated
|
||||
m_prefabPublicInterface->DuplicateEntitiesInInstance(AzToolsFramework::EntityIdList{ entity1->GetId() });
|
||||
m_instanceUpdateExecutorInterface->UpdateTemplateInstancesInQueue();
|
||||
|
||||
// We duplicated a single Entity, so there should now be two EntityAliases
|
||||
EXPECT_EQ(newInstance->GetEntityAliases().size(), 2);
|
||||
|
||||
newInstance->GetConstEntities([&](const AZ::Entity& entity)
|
||||
{
|
||||
// Both of the entities should have the same name
|
||||
EXPECT_EQ(entity.GetName(), entityName);
|
||||
|
||||
// Both of the entities should have the PrefabTestComponent we added
|
||||
auto testComponent = entity.FindComponent<PrefabTestComponent>();
|
||||
EXPECT_NE(nullptr, testComponent);
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
TEST_F(PrefabDuplicateTest, PrefabDuplicate_DuplicateMultipleEntitiesAndFixesReferences)
|
||||
{
|
||||
AZ::Entity* parentEntity = CreateEntity("Parent Entity");
|
||||
|
||||
AZ::Entity* childEntity = CreateEntity("Child Entity");
|
||||
childEntity->Deactivate();
|
||||
auto newComponent = childEntity->CreateComponent<PrefabTestComponent>();
|
||||
childEntity->Activate();
|
||||
|
||||
// Set the EntityId reference property on our PrefabTestComponent so we can
|
||||
// verify that arbitrary EntityId's are fixed up properly
|
||||
newComponent->m_entityIdProperty = parentEntity->GetId();
|
||||
|
||||
AzToolsFramework::EditorEntityContextRequestBus::Broadcast(
|
||||
&AzToolsFramework::EditorEntityContextRequests::HandleEntitiesAdded, AzToolsFramework::EntityList{ parentEntity, childEntity });
|
||||
|
||||
AZStd::unique_ptr<Instance> newInstance = m_prefabSystemComponent->CreatePrefab(
|
||||
{ parentEntity, childEntity },
|
||||
{},
|
||||
PrefabMockFilePath);
|
||||
|
||||
// We've created a prefab with two entities, so there should be two EntityAliases in our instance
|
||||
EXPECT_EQ(newInstance->GetEntityAliases().size(), 2);
|
||||
|
||||
// Duplicate the entities and trigger the UpdateTemplateInstancesInQueue so the changes get propagated
|
||||
m_prefabPublicInterface->DuplicateEntitiesInInstance(AzToolsFramework::EntityIdList{ parentEntity->GetId(), childEntity->GetId() });
|
||||
m_instanceUpdateExecutorInterface->UpdateTemplateInstancesInQueue();
|
||||
|
||||
// We duplicated two entities, so there should now be four EntityAliases
|
||||
EXPECT_EQ(newInstance->GetEntityAliases().size(), 4);
|
||||
|
||||
AzToolsFramework::EntityIdList parentEntityIds;
|
||||
newInstance->GetConstEntities([&](const AZ::Entity& entity)
|
||||
{
|
||||
// Gather the parent EntityIds by tracking which entities don't have a PrefabTestComponent
|
||||
auto testComponent = entity.FindComponent<PrefabTestComponent>();
|
||||
if (!testComponent)
|
||||
{
|
||||
parentEntityIds.push_back(entity.GetId());
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
// There should only be two parents
|
||||
EXPECT_EQ(parentEntityIds.size(), 2);
|
||||
|
||||
// Verify that the EntityId reference on the PrefabTestComponent on the children correspond
|
||||
// to unique entities, which will verify that the EntityIds are fixed up on duplicate
|
||||
newInstance->GetConstEntities([&](const AZ::Entity& entity)
|
||||
{
|
||||
// Only the child entities have a PrefabTestComponent
|
||||
auto testComponent = entity.FindComponent<PrefabTestComponent>();
|
||||
if (testComponent)
|
||||
{
|
||||
auto it = AZStd::find(parentEntityIds.begin(), parentEntityIds.end(), testComponent->m_entityIdProperty);
|
||||
EXPECT_NE(it, parentEntityIds.end());
|
||||
|
||||
// Erase when we find it so that the matches will be unique
|
||||
parentEntityIds.erase(it);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
// Verify we matched each of the parent EntityIds
|
||||
EXPECT_EQ(parentEntityIds.size(), 0);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,17 @@
|
||||
|
||||
namespace UnitTest
|
||||
{
|
||||
PrefabTestToolsApplication::PrefabTestToolsApplication(AZStd::string appName)
|
||||
: ToolsTestApplication(AZStd::move(appName))
|
||||
{
|
||||
}
|
||||
|
||||
bool PrefabTestToolsApplication::IsPrefabSystemEnabled() const
|
||||
{
|
||||
// Make sure our prefab tests always run with prefabs enabled
|
||||
return true;
|
||||
}
|
||||
|
||||
void PrefabTestFixture::SetUpEditorFixtureImpl()
|
||||
{
|
||||
// Acquire the system entity
|
||||
@@ -32,6 +43,9 @@ namespace UnitTest
|
||||
m_prefabLoaderInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabLoaderInterface>::Get();
|
||||
EXPECT_TRUE(m_prefabLoaderInterface);
|
||||
|
||||
m_prefabPublicInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabPublicInterface>::Get();
|
||||
EXPECT_TRUE(m_prefabPublicInterface);
|
||||
|
||||
m_instanceUpdateExecutorInterface = AZ::Interface<AzToolsFramework::Prefab::InstanceUpdateExecutorInterface>::Get();
|
||||
EXPECT_TRUE(m_instanceUpdateExecutorInterface);
|
||||
|
||||
@@ -41,6 +55,11 @@ namespace UnitTest
|
||||
GetApplication()->RegisterComponentDescriptor(PrefabTestComponent::CreateDescriptor());
|
||||
}
|
||||
|
||||
AZStd::unique_ptr<ToolsTestApplication> PrefabTestFixture::CreateTestApplication()
|
||||
{
|
||||
return AZStd::make_unique<PrefabTestToolsApplication>("PrefabTestApplication");
|
||||
}
|
||||
|
||||
AZ::Entity* PrefabTestFixture::CreateEntity(const char* entityName, const bool shouldActivate)
|
||||
{
|
||||
// Circumvent the EntityContext system and generate a new entity with a transformcomponent
|
||||
|
||||
@@ -31,6 +31,16 @@ namespace UnitTest
|
||||
using namespace AzToolsFramework::Prefab;
|
||||
using namespace PrefabTestUtils;
|
||||
|
||||
class PrefabTestToolsApplication
|
||||
: public ToolsTestApplication
|
||||
{
|
||||
public:
|
||||
PrefabTestToolsApplication(AZStd::string appName);
|
||||
|
||||
// Make sure our prefab tests always run with prefabs enabled
|
||||
bool IsPrefabSystemEnabled() const override;
|
||||
};
|
||||
|
||||
class PrefabTestFixture
|
||||
: public ToolsApplicationFixture,
|
||||
public UnitTest::TraceBusRedirector
|
||||
@@ -45,6 +55,8 @@ namespace UnitTest
|
||||
|
||||
void SetUpEditorFixtureImpl() override;
|
||||
|
||||
AZStd::unique_ptr<ToolsTestApplication> CreateTestApplication() override;
|
||||
|
||||
AZ::Entity* CreateEntity(const char* entityName, const bool shouldActivate = true);
|
||||
|
||||
void CompareInstances(const Instance& instanceA, const Instance& instanceB, bool shouldCompareLinkIds = true,
|
||||
@@ -57,6 +69,7 @@ namespace UnitTest
|
||||
|
||||
PrefabSystemComponent* m_prefabSystemComponent = nullptr;
|
||||
PrefabLoaderInterface* m_prefabLoaderInterface = nullptr;
|
||||
PrefabPublicInterface* m_prefabPublicInterface = nullptr;
|
||||
InstanceUpdateExecutorInterface* m_instanceUpdateExecutorInterface = nullptr;
|
||||
InstanceToTemplateInterface* m_instanceToTemplateInterface = nullptr;
|
||||
};
|
||||
|
||||
@@ -54,6 +54,7 @@ set(FILES
|
||||
Prefab/Spawnable/SpawnableMetaDataTests.cpp
|
||||
Prefab/MockPrefabFileIOActionValidator.cpp
|
||||
Prefab/MockPrefabFileIOActionValidator.h
|
||||
Prefab/PrefabDuplicateTests.cpp
|
||||
Prefab/PrefabEntityAliasTests.cpp
|
||||
Prefab/PrefabInstanceToTemplatePropagatorTests.cpp
|
||||
Prefab/PrefabInstantiateTests.cpp
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* 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 <AzCore/UnitTest/TestTypes.h>
|
||||
#include <AzCore/std/smart_ptr/make_shared.h>
|
||||
#include <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
|
||||
#include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
|
||||
#include <AzFramework/Viewport/CameraInput.h>
|
||||
|
||||
namespace UnitTest
|
||||
{
|
||||
class CameraInputFixture : public AllocatorsTestFixture
|
||||
{
|
||||
public:
|
||||
AzFramework::Camera m_camera;
|
||||
AzFramework::Camera m_targetCamera;
|
||||
AZStd::shared_ptr<AzFramework::CameraSystem> m_cameraSystem;
|
||||
|
||||
bool HandleEventAndUpdate(const AzFramework::InputEvent& event)
|
||||
{
|
||||
constexpr float deltaTime = 0.01666f; // 60fps
|
||||
const bool consumed = m_cameraSystem->HandleEvents(event);
|
||||
m_camera = m_cameraSystem->StepCamera(m_targetCamera, deltaTime);
|
||||
return consumed;
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
AllocatorsTestFixture::SetUp();
|
||||
|
||||
AzFramework::ReloadCameraKeyBindings();
|
||||
|
||||
m_cameraSystem = AZStd::make_shared<AzFramework::CameraSystem>();
|
||||
|
||||
auto firstPersonRotateCamera = AZStd::make_shared<AzFramework::RotateCameraInput>(AzFramework::InputDeviceMouse::Button::Right);
|
||||
auto firstPersonTranslateCamera = AZStd::make_shared<AzFramework::TranslateCameraInput>(AzFramework::LookTranslation);
|
||||
|
||||
auto orbitCamera = AZStd::make_shared<AzFramework::OrbitCameraInput>();
|
||||
auto orbitRotateCamera = AZStd::make_shared<AzFramework::RotateCameraInput>(AzFramework::InputDeviceMouse::Button::Left);
|
||||
auto orbitTranslateCamera = AZStd::make_shared<AzFramework::TranslateCameraInput>(AzFramework::OrbitTranslation);
|
||||
|
||||
orbitCamera->m_orbitCameras.AddCamera(orbitRotateCamera);
|
||||
orbitCamera->m_orbitCameras.AddCamera(orbitTranslateCamera);
|
||||
|
||||
m_cameraSystem->m_cameras.AddCamera(firstPersonRotateCamera);
|
||||
m_cameraSystem->m_cameras.AddCamera(firstPersonTranslateCamera);
|
||||
m_cameraSystem->m_cameras.AddCamera(orbitCamera);
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
m_cameraSystem->m_cameras.Clear();
|
||||
m_cameraSystem.reset();
|
||||
|
||||
AllocatorsTestFixture::TearDown();
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CameraInputFixture, BeginEndOrbitCameraConsumesCorrectEvents)
|
||||
{
|
||||
// begin orbit camera
|
||||
const bool consumed1 = HandleEventAndUpdate(
|
||||
AzFramework::DiscreteInputEvent{AzFramework::InputDeviceKeyboard::Key::ModifierAltL, AzFramework::InputChannel::State::Began});
|
||||
// begin listening for orbit rotate (click detector) - event is not consumed
|
||||
const bool consumed2 = HandleEventAndUpdate(
|
||||
AzFramework::DiscreteInputEvent{AzFramework::InputDeviceMouse::Button::Left, AzFramework::InputChannel::State::Began});
|
||||
// begin orbit rotate (mouse has moved sufficient distance to initiate)
|
||||
const bool consumed3 = HandleEventAndUpdate(AzFramework::HorizontalMotionEvent{5});
|
||||
// end orbit (mouse up) - event is not consumed
|
||||
const bool consumed4 = HandleEventAndUpdate(
|
||||
AzFramework::DiscreteInputEvent{AzFramework::InputDeviceMouse::Button::Left, AzFramework::InputChannel::State::Ended});
|
||||
|
||||
const auto allConsumed = AZStd::vector<bool>{consumed1, consumed2, consumed3, consumed4};
|
||||
|
||||
using ::testing::ElementsAre;
|
||||
EXPECT_THAT(allConsumed, ElementsAre(true, false, true, false));
|
||||
}
|
||||
} // namespace UnitTest
|
||||
@@ -139,4 +139,21 @@ namespace UnitTest
|
||||
EXPECT_THAT(secondaryDownOutcome, Eq(ClickDetector::ClickOutcome::Nil)); // ignored double click
|
||||
EXPECT_THAT(secondaryUpOutcome, Eq(ClickDetector::ClickOutcome::Nil)); // click not registered
|
||||
}
|
||||
|
||||
// if the click detector registers a mouse down event, but then all intermediate calls are ignored
|
||||
// (another system may start intercepting events and swallowing them) then when we do receive a mouse
|
||||
// up event we should ensure we take into account the current delta - if the delta is large, then the
|
||||
// outcome will be release
|
||||
TEST_F(ClickDetectorFixture, ClickIsNotRegisteredAfterIgnoringMouseMovesBeforeMouseUpWithLargeDelta)
|
||||
{
|
||||
using ::testing::Eq;
|
||||
|
||||
const ClickDetector::ClickOutcome downOutcome =
|
||||
m_clickDetector.DetectClick(ClickDetector::ClickEvent::Down, ScreenVector(0, 0));
|
||||
const ClickDetector::ClickOutcome upOutcome =
|
||||
m_clickDetector.DetectClick(ClickDetector::ClickEvent::Up, ScreenVector(50, 50));
|
||||
|
||||
EXPECT_THAT(downOutcome, Eq(ClickDetector::ClickOutcome::Nil));
|
||||
EXPECT_THAT(upOutcome, Eq(ClickDetector::ClickOutcome::Release));
|
||||
}
|
||||
} // namespace UnitTest
|
||||
|
||||
@@ -17,6 +17,7 @@ set(FILES
|
||||
BinToTextEncode.cpp
|
||||
ComponentAddRemove.cpp
|
||||
ComponentAdapterTests.cpp
|
||||
CameraInputTests.cpp
|
||||
ClickDetectorTests.cpp
|
||||
CursorStateTests.cpp
|
||||
EntityContext.cpp
|
||||
|
||||
@@ -457,15 +457,6 @@ void EditorViewportWidget::Update()
|
||||
return;
|
||||
}
|
||||
|
||||
static bool sentOnWindowCreated = false;
|
||||
if (!sentOnWindowCreated && windowHandle()->isActive())
|
||||
{
|
||||
sentOnWindowCreated = true;
|
||||
AzFramework::WindowSystemNotificationBus::Broadcast(
|
||||
&AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated,
|
||||
reinterpret_cast<AzFramework::NativeWindowHandle>(winId()));
|
||||
}
|
||||
|
||||
m_updatingCameraPosition = true;
|
||||
if (!ed_useNewCameraSystem)
|
||||
{
|
||||
|
||||
@@ -97,17 +97,34 @@ namespace SandboxEditor
|
||||
AzFramework::ViewportDebugDisplayEventBus::Handler::BusDisconnect();
|
||||
}
|
||||
|
||||
// should the camera system respond to this particular event
|
||||
static bool ShouldHandle(const AzFramework::ViewportControllerPriority priority, const bool exclusive)
|
||||
{
|
||||
// ModernViewportCameraControllerInstance receives events at all priorities, it should only respond
|
||||
// to normal priority events if it is not in 'exclusive' mode and when in 'exclusive' mode it should
|
||||
// only respond to the highest priority events
|
||||
return !exclusive && priority == AzFramework::ViewportControllerPriority::Normal ||
|
||||
exclusive && priority == AzFramework::ViewportControllerPriority::Highest;
|
||||
}
|
||||
|
||||
bool ModernViewportCameraControllerInstance::HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event)
|
||||
{
|
||||
AzFramework::WindowSize windowSize;
|
||||
AzFramework::WindowRequestBus::EventResult(
|
||||
windowSize, event.m_windowHandle, &AzFramework::WindowRequestBus::Events::GetClientAreaSize);
|
||||
if (ShouldHandle(event.m_priority, m_cameraSystem.m_cameras.Exclusive()))
|
||||
{
|
||||
return m_cameraSystem.HandleEvents(AzFramework::BuildInputEvent(event.m_inputChannel));
|
||||
}
|
||||
|
||||
return m_cameraSystem.HandleEvents(AzFramework::BuildInputEvent(event.m_inputChannel, windowSize));
|
||||
return false;
|
||||
}
|
||||
|
||||
void ModernViewportCameraControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event)
|
||||
{
|
||||
// only update for a single priority (normal is the default)
|
||||
if (event.m_priority != AzFramework::ViewportControllerPriority::Normal)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (auto viewportContext = RetrieveViewportContext(GetViewportId()))
|
||||
{
|
||||
m_updatingTransform = true;
|
||||
|
||||
@@ -22,7 +22,9 @@
|
||||
namespace SandboxEditor
|
||||
{
|
||||
class ModernViewportCameraControllerInstance;
|
||||
class ModernViewportCameraController : public AzFramework::MultiViewportController<ModernViewportCameraControllerInstance>
|
||||
class ModernViewportCameraController
|
||||
: public AzFramework::MultiViewportController<
|
||||
ModernViewportCameraControllerInstance, AzFramework::ViewportControllerPriority::DispatchToAllPriorities>
|
||||
{
|
||||
public:
|
||||
using CameraListBuilder = AZStd::function<void(AzFramework::Cameras&)>;
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
#include <AzFramework/StringFunc/StringFunc.h>
|
||||
#include <AzFramework/Visibility/BoundsBus.h>
|
||||
#include <AzToolsFramework/API/EditorAssetSystemAPI.h>
|
||||
#include <AzToolsFramework/API/EditorEntityAPI.h>
|
||||
#include <AzToolsFramework/API/EntityCompositionRequestBus.h>
|
||||
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
|
||||
#include <AzToolsFramework/AssetBrowser/AssetBrowserBus.h>
|
||||
@@ -192,6 +193,9 @@ void SandboxIntegrationManager::Setup()
|
||||
(m_prefabIntegrationInterface != nullptr),
|
||||
"SandboxIntegrationManager requires a PrefabIntegrationInterface instance to be present on Setup().");
|
||||
|
||||
m_editorEntityAPI = AZ::Interface<AzToolsFramework::EditorEntityAPI>::Get();
|
||||
AZ_Assert(m_editorEntityAPI, "SandboxIntegrationManager requires an EditorEntityAPI instance to be present on Setup().");
|
||||
|
||||
AzToolsFramework::Layers::EditorLayerComponentNotificationBus::Handler::BusConnect();
|
||||
}
|
||||
|
||||
@@ -1215,9 +1219,20 @@ void SandboxIntegrationManager::CloneSelection(bool& handled)
|
||||
|
||||
if (!duplicationSet.empty())
|
||||
{
|
||||
AZStd::unordered_set<AZ::EntityId> clonedEntities;
|
||||
handled = AzToolsFramework::CloneInstantiatedEntities(duplicationSet, clonedEntities);
|
||||
m_unsavedEntities.insert(clonedEntities.begin(), clonedEntities.end());
|
||||
bool prefabSystemEnabled = false;
|
||||
AzFramework::ApplicationRequests::Bus::BroadcastResult(prefabSystemEnabled, &AzFramework::ApplicationRequests::IsPrefabSystemEnabled);
|
||||
|
||||
if (prefabSystemEnabled)
|
||||
{
|
||||
m_editorEntityAPI->DuplicateSelected();
|
||||
handled = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
AZStd::unordered_set<AZ::EntityId> clonedEntities;
|
||||
handled = AzToolsFramework::CloneInstantiatedEntities(duplicationSet, clonedEntities);
|
||||
m_unsavedEntities.insert(clonedEntities.begin(), clonedEntities.end());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -77,6 +77,7 @@ class CHyperGraph;
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
class EditorEntityAPI;
|
||||
class EditorEntityUiInterface;
|
||||
|
||||
namespace AssetBrowser
|
||||
@@ -371,6 +372,7 @@ private:
|
||||
|
||||
AzToolsFramework::EditorEntityUiInterface* m_editorEntityUiInterface = nullptr;
|
||||
AzToolsFramework::Prefab::PrefabIntegrationInterface* m_prefabIntegrationInterface = nullptr;
|
||||
AzToolsFramework::EditorEntityAPI* m_editorEntityAPI = nullptr;
|
||||
|
||||
// Overrides UI styling and behavior for Layer Entities
|
||||
AzToolsFramework::LayerUiHandler m_layerUiOverrideHandler;
|
||||
|
||||
@@ -65,6 +65,7 @@
|
||||
#include "OutlinerTreeView.hxx"
|
||||
#include "Include/ICommandManager.h"
|
||||
#include "Include/IObjectManager.h"
|
||||
#include "OutlinerCacheBus.h"
|
||||
|
||||
#include <Editor/CryEditDoc.h>
|
||||
#include <AzCore/Outcome/Outcome.h>
|
||||
@@ -1538,6 +1539,16 @@ void OutlinerListModel::OnEntityInfoUpdatedName(AZ::EntityId entityId, const AZS
|
||||
{
|
||||
(void)name;
|
||||
QueueEntityUpdate(entityId);
|
||||
|
||||
bool isSelected = false;
|
||||
AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(
|
||||
isSelected, &AzToolsFramework::ToolsApplicationRequests::IsSelected, entityId);
|
||||
|
||||
if (isSelected)
|
||||
{
|
||||
// Ask the system to scroll to the entity in case it is off screen after the rename
|
||||
OutlinerModelNotificationBus::Broadcast(&OutlinerModelNotifications::QueueScrollToNewContent, entityId);
|
||||
}
|
||||
}
|
||||
|
||||
void OutlinerListModel::OnEntityInfoUpdatedUnsavedChanges(AZ::EntityId entityId)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.1359 15.3956L19.6728 7.8125L21.087 9.22671L12 18.5245L12 18.5245L2.86273 9.27696L4.27695 7.86275L12.1359 15.3956Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 286 B |
@@ -0,0 +1,3 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.2732 10.1288L19.8101 17.7119L21.2243 16.2977L12.1373 6.99994L12.1373 6.99995L3 16.2475L4.41421 17.6617L12.2732 10.1288Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 292 B |
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:7088e902885d98953f6a1715efab319c063a4ab8918fd0e810251c8ed82b8514
|
||||
size 542983
|
||||
@@ -0,0 +1,4 @@
|
||||
SPDX-FileCopyrightText: Unsplash grants you an irrevocable, nonexclusive, worldwide copyright license to download, copy,
|
||||
SPDX-FileCopyrightText: modify, distribute, perform, and use photos from Unsplash for free, including for commercial
|
||||
SPDX-FileCopyrightText: purposes, without permission from or attributing the photographer or Unsplash. This license does
|
||||
SPDX-FileCopyrightText: not include the right to compile photos from Unsplash to replicate a similar or competing service.
|
||||
@@ -12,18 +12,64 @@
|
||||
|
||||
#include <FirstTimeUseScreen.h>
|
||||
|
||||
#include <Source/ui_FirstTimeUseScreen.h>
|
||||
#include <QVBoxLayout>
|
||||
#include <QHBoxLayout>
|
||||
#include <QLabel>
|
||||
#include <QPushButton>
|
||||
#include <QIcon>
|
||||
#include <QSpacerItem>
|
||||
|
||||
namespace O3DE::ProjectManager
|
||||
{
|
||||
inline constexpr static int s_contentMargins = 80;
|
||||
inline constexpr static int s_buttonSpacing = 30;
|
||||
inline constexpr static int s_iconSize = 24;
|
||||
inline constexpr static int s_spacerSize = 20;
|
||||
inline constexpr static int s_boxButtonWidth = 210;
|
||||
inline constexpr static int s_boxButtonHeight = 280;
|
||||
|
||||
FirstTimeUseScreen::FirstTimeUseScreen(QWidget* parent)
|
||||
: ScreenWidget(parent)
|
||||
, m_ui(new Ui::FirstTimeUseClass())
|
||||
{
|
||||
m_ui->setupUi(this);
|
||||
QVBoxLayout* vLayout = new QVBoxLayout();
|
||||
setLayout(vLayout);
|
||||
vLayout->setContentsMargins(s_contentMargins, s_contentMargins, s_contentMargins, s_contentMargins);
|
||||
|
||||
connect(m_ui->createProjectButton, &QPushButton::pressed, this, &FirstTimeUseScreen::HandleNewProjectButton);
|
||||
connect(m_ui->openProjectButton, &QPushButton::pressed, this, &FirstTimeUseScreen::HandleOpenProjectButton);
|
||||
QLabel* titleLabel = new QLabel(this);
|
||||
titleLabel->setText(tr("Ready. Set. Create!"));
|
||||
titleLabel->setStyleSheet("font-size: 60px");
|
||||
vLayout->addWidget(titleLabel);
|
||||
|
||||
QLabel* introLabel = new QLabel(this);
|
||||
introLabel->setTextFormat(Qt::AutoText);
|
||||
introLabel->setText(tr("<html><head/><body><p>Welcome to O3DE! Start something new by creating a project. Not sure what to create? </p><p>Explore what\342\200\231s available by downloading our sample project.</p></body></html>"));
|
||||
introLabel->setStyleSheet("font-size: 14px");
|
||||
vLayout->addWidget(introLabel);
|
||||
|
||||
QHBoxLayout* buttonLayout = new QHBoxLayout();
|
||||
buttonLayout->setSpacing(s_buttonSpacing);
|
||||
|
||||
m_createProjectButton = CreateLargeBoxButton(QIcon(":/Resources/Add.svg"), tr("Create Project"), this);
|
||||
m_createProjectButton->setIconSize(QSize(s_iconSize, s_iconSize));
|
||||
buttonLayout->addWidget(m_createProjectButton);
|
||||
|
||||
m_addProjectButton = CreateLargeBoxButton(QIcon(":/Resources/Select_Folder.svg"), tr("Add a Project"), this);
|
||||
m_addProjectButton->setIconSize(QSize(s_iconSize, s_iconSize));
|
||||
buttonLayout->addWidget(m_addProjectButton);
|
||||
|
||||
QSpacerItem* buttonSpacer = new QSpacerItem(s_spacerSize, s_spacerSize, QSizePolicy::Expanding, QSizePolicy::Minimum);
|
||||
buttonLayout->addItem(buttonSpacer);
|
||||
|
||||
vLayout->addItem(buttonLayout);
|
||||
|
||||
QSpacerItem* verticalSpacer = new QSpacerItem(s_spacerSize, s_spacerSize, QSizePolicy::Minimum, QSizePolicy::Expanding);
|
||||
vLayout->addItem(verticalSpacer);
|
||||
|
||||
// Using border-image allows for scaling options background-image does not support
|
||||
setStyleSheet("O3DE--ProjectManager--ScreenWidget { border-image: url(:/Resources/Backgrounds/FirstTimeBackgroundImage.jpg) repeat repeat; }");
|
||||
|
||||
connect(m_createProjectButton, &QPushButton::pressed, this, &FirstTimeUseScreen::HandleNewProjectButton);
|
||||
connect(m_addProjectButton, &QPushButton::pressed, this, &FirstTimeUseScreen::HandleAddProjectButton);
|
||||
}
|
||||
|
||||
ProjectManagerScreen FirstTimeUseScreen::GetScreenEnum()
|
||||
@@ -36,9 +82,21 @@ namespace O3DE::ProjectManager
|
||||
emit ResetScreenRequest(ProjectManagerScreen::NewProjectSettingsCore);
|
||||
emit ChangeScreenRequest(ProjectManagerScreen::NewProjectSettingsCore);
|
||||
}
|
||||
void FirstTimeUseScreen::HandleOpenProjectButton()
|
||||
void FirstTimeUseScreen::HandleAddProjectButton()
|
||||
{
|
||||
emit ChangeScreenRequest(ProjectManagerScreen::ProjectsHome);
|
||||
}
|
||||
|
||||
QPushButton* FirstTimeUseScreen::CreateLargeBoxButton(const QIcon& icon, const QString& text, QWidget* parent)
|
||||
{
|
||||
QPushButton* largeBoxButton = new QPushButton(icon, text, parent);
|
||||
|
||||
largeBoxButton->setFixedSize(s_boxButtonWidth, s_boxButtonHeight);
|
||||
largeBoxButton->setFlat(true);
|
||||
largeBoxButton->setFocusPolicy(Qt::FocusPolicy::NoFocus);
|
||||
largeBoxButton->setStyleSheet("QPushButton { font-size: 14px; background-color: rgba(0, 0, 0, 191); }");
|
||||
|
||||
return largeBoxButton;
|
||||
}
|
||||
|
||||
} // namespace O3DE::ProjectManager
|
||||
|
||||
@@ -15,10 +15,8 @@
|
||||
#include <ScreenWidget.h>
|
||||
#endif
|
||||
|
||||
namespace Ui
|
||||
{
|
||||
class FirstTimeUseClass;
|
||||
}
|
||||
QT_FORWARD_DECLARE_CLASS(QIcon)
|
||||
QT_FORWARD_DECLARE_CLASS(QPushButton)
|
||||
|
||||
namespace O3DE::ProjectManager
|
||||
{
|
||||
@@ -32,10 +30,13 @@ namespace O3DE::ProjectManager
|
||||
|
||||
protected slots:
|
||||
void HandleNewProjectButton();
|
||||
void HandleOpenProjectButton();
|
||||
void HandleAddProjectButton();
|
||||
|
||||
private:
|
||||
QScopedPointer<Ui::FirstTimeUseClass> m_ui;
|
||||
QPushButton* CreateLargeBoxButton(const QIcon& icon, const QString& text, QWidget* parent = nullptr);
|
||||
|
||||
QPushButton* m_createProjectButton;
|
||||
QPushButton* m_addProjectButton;
|
||||
};
|
||||
|
||||
} // namespace O3DE::ProjectManager
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>FirstTimeUseClass</class>
|
||||
<widget class="QWidget" name="FirstTimeUseClass">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>881</width>
|
||||
<height>555</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>Form</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout_2">
|
||||
<item>
|
||||
<layout class="QVBoxLayout" name="verticalLayout_5">
|
||||
<item>
|
||||
<widget class="QLabel" name="label">
|
||||
<property name="font">
|
||||
<font>
|
||||
<pointsize>30</pointsize>
|
||||
</font>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>READY. SET. CREATE!</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="label_2">
|
||||
<property name="text">
|
||||
<string><html><head/><body><p>Welcome to O3DE! Start something new by creating a project. Not sure what to create? </p><p>Explore what’s available by downloading our sample project.</p></body></html></string>
|
||||
</property>
|
||||
<property name="textFormat">
|
||||
<enum>Qt::AutoText</enum>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="horizontalLayout_7">
|
||||
<item>
|
||||
<widget class="QPushButton" name="createProjectButton">
|
||||
<property name="sizePolicy">
|
||||
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
|
||||
<horstretch>0</horstretch>
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Create Project</string>
|
||||
</property>
|
||||
<property name="icon">
|
||||
<iconset resource="../project_manager.qrc">
|
||||
<normaloff>:/Resources/Add.svg</normaloff>:/Resources/Add.svg</iconset>
|
||||
</property>
|
||||
<property name="iconSize">
|
||||
<size>
|
||||
<width>16</width>
|
||||
<height>16</height>
|
||||
</size>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="openProjectButton">
|
||||
<property name="sizePolicy">
|
||||
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
|
||||
<horstretch>0</horstretch>
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Open a Project</string>
|
||||
</property>
|
||||
<property name="icon">
|
||||
<iconset resource="../project_manager.qrc">
|
||||
<normaloff>:/Resources/Select_Folder.svg</normaloff>:/Resources/Select_Folder.svg</iconset>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<resources>
|
||||
<include location="../project_manager.qrc"/>
|
||||
</resources>
|
||||
<connections/>
|
||||
</ui>
|
||||
@@ -58,13 +58,6 @@ namespace O3DE::ProjectManager
|
||||
|
||||
hLayout->addWidget(m_gemListView);
|
||||
hLayout->addWidget(m_gemInspector);
|
||||
|
||||
|
||||
// Select the first entry after everything got correctly sized
|
||||
QTimer::singleShot(100, [=]{
|
||||
QModelIndex firstModelIndex = m_gemListView->model()->index(0,0);
|
||||
m_gemListView->selectionModel()->select(firstModelIndex, QItemSelectionModel::ClearAndSelect);
|
||||
});
|
||||
}
|
||||
|
||||
QVector<GemInfo> GemCatalogScreen::GenerateTestData()
|
||||
|
||||
@@ -32,21 +32,36 @@ namespace O3DE::ProjectManager
|
||||
{
|
||||
switch (platform)
|
||||
{
|
||||
case O3DE::ProjectManager::GemInfo::Android:
|
||||
case Android:
|
||||
return "Android";
|
||||
case O3DE::ProjectManager::GemInfo::iOS:
|
||||
case iOS:
|
||||
return "iOS";
|
||||
case O3DE::ProjectManager::GemInfo::Linux:
|
||||
case Linux:
|
||||
return "Linux";
|
||||
case O3DE::ProjectManager::GemInfo::macOS:
|
||||
case macOS:
|
||||
return "macOS";
|
||||
case O3DE::ProjectManager::GemInfo::Windows:
|
||||
case Windows:
|
||||
return "Windows";
|
||||
default:
|
||||
return "<Unknown Platform>";
|
||||
}
|
||||
}
|
||||
|
||||
QString GemInfo::GetTypeString(Type type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case Asset:
|
||||
return "Asset";
|
||||
case Code:
|
||||
return "Code";
|
||||
case Tool:
|
||||
return "Tool";
|
||||
default:
|
||||
return "<Unknown Type>";
|
||||
}
|
||||
}
|
||||
|
||||
bool GemInfo::IsPlatformSupported(Platform platform) const
|
||||
{
|
||||
return (m_platforms & platform);
|
||||
|
||||
@@ -36,6 +36,16 @@ namespace O3DE::ProjectManager
|
||||
Q_DECLARE_FLAGS(Platforms, Platform)
|
||||
static QString GetPlatformString(Platform platform);
|
||||
|
||||
enum Type
|
||||
{
|
||||
Asset = 1 << 0,
|
||||
Code = 1 << 1,
|
||||
Tool = 1 << 2,
|
||||
NumTypes = 3
|
||||
};
|
||||
Q_DECLARE_FLAGS(Types, Type)
|
||||
static QString GetTypeString(Type type);
|
||||
|
||||
GemInfo() = default;
|
||||
GemInfo(const QString& name, const QString& creator, const QString& summary, Platforms platforms, bool isAdded);
|
||||
bool IsPlatformSupported(Platform platform) const;
|
||||
@@ -50,6 +60,7 @@ namespace O3DE::ProjectManager
|
||||
bool m_isAdded = false; //! Is the gem currently added and enabled in the project?
|
||||
QString m_summary;
|
||||
Platforms m_platforms;
|
||||
Types m_types; //! Asset and/or Code and/or Tool
|
||||
QStringList m_features;
|
||||
QString m_directoryLink;
|
||||
QString m_documentationLink;
|
||||
@@ -62,3 +73,4 @@ namespace O3DE::ProjectManager
|
||||
} // namespace O3DE::ProjectManager
|
||||
|
||||
Q_DECLARE_OPERATORS_FOR_FLAGS(O3DE::ProjectManager::GemInfo::Platforms)
|
||||
Q_DECLARE_OPERATORS_FOR_FLAGS(O3DE::ProjectManager::GemInfo::Types)
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
*
|
||||
*/
|
||||
|
||||
#include "GemModel.h"
|
||||
#include <AzCore/std/string/string.h>
|
||||
#include <GemCatalog/GemModel.h>
|
||||
|
||||
namespace O3DE::ProjectManager
|
||||
{
|
||||
@@ -32,8 +33,11 @@ namespace O3DE::ProjectManager
|
||||
item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
|
||||
|
||||
item->setData(gemInfo.m_name, RoleName);
|
||||
const QString uuidString = gemInfo.m_uuid.ToString<AZStd::string>().c_str();
|
||||
item->setData(uuidString, RoleUuid);
|
||||
item->setData(gemInfo.m_creator, RoleCreator);
|
||||
item->setData(static_cast<int>(gemInfo.m_platforms), RolePlatforms);
|
||||
item->setData(aznumeric_cast<int>(gemInfo.m_platforms), RolePlatforms);
|
||||
item->setData(aznumeric_cast<int>(gemInfo.m_types), RoleTypes);
|
||||
item->setData(gemInfo.m_summary, RoleSummary);
|
||||
item->setData(gemInfo.m_isAdded, RoleIsAdded);
|
||||
|
||||
@@ -48,6 +52,8 @@ namespace O3DE::ProjectManager
|
||||
item->setData(gemInfo.m_features, RoleFeatures);
|
||||
|
||||
appendRow(item);
|
||||
|
||||
m_uuidToNameMap[uuidString] = gemInfo.m_displayName;
|
||||
}
|
||||
|
||||
void GemModel::Clear()
|
||||
@@ -65,11 +71,21 @@ namespace O3DE::ProjectManager
|
||||
return modelIndex.data(RoleCreator).toString();
|
||||
}
|
||||
|
||||
QString GemModel::GetUuidString(const QModelIndex& modelIndex)
|
||||
{
|
||||
return modelIndex.data(RoleUuid).toString();
|
||||
}
|
||||
|
||||
GemInfo::Platforms GemModel::GetPlatforms(const QModelIndex& modelIndex)
|
||||
{
|
||||
return static_cast<GemInfo::Platforms>(modelIndex.data(RolePlatforms).toInt());
|
||||
}
|
||||
|
||||
GemInfo::Types GemModel::GetTypes(const QModelIndex& modelIndex)
|
||||
{
|
||||
return static_cast<GemInfo::Types>(modelIndex.data(RoleTypes).toInt());
|
||||
}
|
||||
|
||||
QString GemModel::GetSummary(const QModelIndex& modelIndex)
|
||||
{
|
||||
return modelIndex.data(RoleSummary).toString();
|
||||
@@ -90,9 +106,35 @@ namespace O3DE::ProjectManager
|
||||
return modelIndex.data(RoleDocLink).toString();
|
||||
}
|
||||
|
||||
AZ::Outcome<QString> GemModel::FindGemNameByUuidString(const QString& uuidString) const
|
||||
{
|
||||
const auto iterator = m_uuidToNameMap.find(uuidString);
|
||||
if (iterator != m_uuidToNameMap.end())
|
||||
{
|
||||
return AZ::Success(iterator.value());
|
||||
}
|
||||
|
||||
return AZ::Failure();
|
||||
}
|
||||
|
||||
QStringList GemModel::GetDependingGems(const QModelIndex& modelIndex)
|
||||
{
|
||||
return modelIndex.data(RoleDependingGems).toStringList();
|
||||
QStringList result = modelIndex.data(RoleDependingGems).toStringList();
|
||||
if (result.isEmpty())
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
for (QString& dependingGemString : result)
|
||||
{
|
||||
AZ::Outcome<QString> gemNameOutcome = FindGemNameByUuidString(dependingGemString);
|
||||
if (gemNameOutcome.IsSuccess())
|
||||
{
|
||||
dependingGemString = gemNameOutcome.GetValue();
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
QStringList GemModel::GetConflictingGems(const QModelIndex& modelIndex)
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
#pragma once
|
||||
|
||||
#if !defined(Q_MOC_RUN)
|
||||
#include "GemInfo.h"
|
||||
#include <AzCore/Outcome/Outcome.h>
|
||||
#include <GemCatalog/GemInfo.h>
|
||||
#include <QAbstractItemModel>
|
||||
#include <QStandardItemModel>
|
||||
#include <QItemSelectionModel>
|
||||
@@ -33,14 +34,18 @@ namespace O3DE::ProjectManager
|
||||
void AddGem(const GemInfo& gemInfo);
|
||||
void Clear();
|
||||
|
||||
AZ::Outcome<QString> FindGemNameByUuidString(const QString& uuidString) const;
|
||||
QStringList GetDependingGems(const QModelIndex& modelIndex);
|
||||
|
||||
static QString GetName(const QModelIndex& modelIndex);
|
||||
static QString GetCreator(const QModelIndex& modelIndex);
|
||||
static QString GetUuidString(const QModelIndex& modelIndex);
|
||||
static GemInfo::Platforms GetPlatforms(const QModelIndex& modelIndex);
|
||||
static GemInfo::Types GetTypes(const QModelIndex& modelIndex);
|
||||
static QString GetSummary(const QModelIndex& modelIndex);
|
||||
static bool IsAdded(const QModelIndex& modelIndex);
|
||||
static QString GetDirectoryLink(const QModelIndex& modelIndex);
|
||||
static QString GetDocLink(const QModelIndex& modelIndex);
|
||||
static QStringList GetDependingGems(const QModelIndex& modelIndex);
|
||||
static QStringList GetConflictingGems(const QModelIndex& modelIndex);
|
||||
static QString GetVersion(const QModelIndex& modelIndex);
|
||||
static QString GetLastUpdated(const QModelIndex& modelIndex);
|
||||
@@ -51,6 +56,7 @@ namespace O3DE::ProjectManager
|
||||
enum UserRole
|
||||
{
|
||||
RoleName = Qt::UserRole,
|
||||
RoleUuid,
|
||||
RoleCreator,
|
||||
RolePlatforms,
|
||||
RoleSummary,
|
||||
@@ -63,8 +69,10 @@ namespace O3DE::ProjectManager
|
||||
RoleLastUpdated,
|
||||
RoleBinarySize,
|
||||
RoleFeatures,
|
||||
RoleTypes
|
||||
};
|
||||
|
||||
QHash<QString, QString> m_uuidToNameMap;
|
||||
QItemSelectionModel* m_selectionModel = nullptr;
|
||||
};
|
||||
} // namespace O3DE::ProjectManager
|
||||
|
||||
@@ -27,7 +27,12 @@ namespace O3DE::ProjectManager
|
||||
|
||||
void LinkLabel::mousePressEvent([[maybe_unused]] QMouseEvent* event)
|
||||
{
|
||||
QDesktopServices::openUrl(m_url);
|
||||
if (m_url.isValid())
|
||||
{
|
||||
QDesktopServices::openUrl(m_url);
|
||||
}
|
||||
|
||||
emit clicked();
|
||||
}
|
||||
|
||||
void LinkLabel::enterEvent([[maybe_unused]] QEvent* event)
|
||||
|
||||
@@ -26,10 +26,16 @@ namespace O3DE::ProjectManager
|
||||
class LinkLabel
|
||||
: public QLabel
|
||||
{
|
||||
Q_OBJECT // AUTOMOC
|
||||
|
||||
public:
|
||||
LinkLabel(const QString& text, const QUrl& url = {}, QWidget* parent = nullptr);
|
||||
LinkLabel(const QString& text = {}, const QUrl& url = {}, QWidget* parent = nullptr);
|
||||
|
||||
void SetUrl(const QUrl& url);
|
||||
|
||||
signals:
|
||||
void clicked();
|
||||
|
||||
private:
|
||||
void mousePressEvent(QMouseEvent* event) override;
|
||||
void enterEvent(QEvent* event) override;
|
||||
|
||||
@@ -27,6 +27,12 @@ namespace O3DE::ProjectManager
|
||||
, m_ui(new Ui::ProjectManagerWindowClass())
|
||||
{
|
||||
m_ui->setupUi(this);
|
||||
QLayout* layout = m_ui->centralWidget->layout();
|
||||
layout->setMargin(0);
|
||||
layout->setSpacing(0);
|
||||
layout->setContentsMargins(0, 0, 0, 0);
|
||||
|
||||
setFixedSize(this->geometry().width(), this->geometry().height());
|
||||
|
||||
m_pythonBindings = AZStd::make_unique<PythonBindings>(engineRootPath);
|
||||
|
||||
|
||||
@@ -6,10 +6,16 @@
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>800</width>
|
||||
<height>600</height>
|
||||
<width>1200</width>
|
||||
<height>800</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="sizePolicy">
|
||||
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
|
||||
<horstretch>0</horstretch>
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>O3DE Project Manager</string>
|
||||
</property>
|
||||
@@ -21,7 +27,7 @@
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>800</width>
|
||||
<width>1200</width>
|
||||
<height>36</height>
|
||||
</rect>
|
||||
</property>
|
||||
|
||||
@@ -426,7 +426,7 @@ namespace O3DE::ProjectManager
|
||||
{
|
||||
// required
|
||||
gemInfo.m_name = Py_To_String(data["Name"]);
|
||||
gemInfo.m_uuid = AZ::Uuid(Py_To_String(data["Uuid"]));
|
||||
gemInfo.m_uuid = AZ::Uuid(Py_To_String(data["Uuid"]));
|
||||
|
||||
// optional
|
||||
gemInfo.m_displayName = Py_To_String_Optional(data, "DisplayName", gemInfo.m_name);
|
||||
@@ -437,7 +437,8 @@ namespace O3DE::ProjectManager
|
||||
{
|
||||
for (auto dependency : data["Dependencies"])
|
||||
{
|
||||
gemInfo.m_dependingGemUuids.push_back(Py_To_String(dependency["Uuid"]));
|
||||
const AZ::Uuid uuid = Py_To_String(dependency["Uuid"]);
|
||||
gemInfo.m_dependingGemUuids.push_back(uuid.ToString<AZStd::string>().c_str());
|
||||
}
|
||||
}
|
||||
if (data.contains("Tags"))
|
||||
@@ -507,6 +508,42 @@ namespace O3DE::ProjectManager
|
||||
}
|
||||
}
|
||||
|
||||
bool PythonBindings::AddGemToProject(const QString& gemPath, const QString& projectPath)
|
||||
{
|
||||
bool result = ExecuteWithLock([&] {
|
||||
pybind11::str pyGemPath = gemPath.toStdString();
|
||||
pybind11::str pyProjectPath = projectPath.toStdString();
|
||||
|
||||
m_registration.attr("add_gem_to_project")(
|
||||
pybind11::none(), // gem_name
|
||||
pyGemPath,
|
||||
pybind11::none(), // gem_target
|
||||
pybind11::none(), // project_name
|
||||
pyProjectPath
|
||||
);
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
bool PythonBindings::RemoveGemFromProject(const QString& gemPath, const QString& projectPath)
|
||||
{
|
||||
bool result = ExecuteWithLock([&] {
|
||||
pybind11::str pyGemPath = gemPath.toStdString();
|
||||
pybind11::str pyProjectPath = projectPath.toStdString();
|
||||
|
||||
m_registration.attr("remove_gem_to_project")(
|
||||
pybind11::none(), // gem_name
|
||||
pyGemPath,
|
||||
pybind11::none(), // gem_target
|
||||
pybind11::none(), // project_name
|
||||
pyProjectPath
|
||||
);
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
bool PythonBindings::UpdateProject([[maybe_unused]] const ProjectInfo& projectInfo)
|
||||
{
|
||||
return false;
|
||||
|
||||
@@ -47,6 +47,8 @@ namespace O3DE::ProjectManager
|
||||
AZ::Outcome<ProjectInfo> GetProject(const QString& path) override;
|
||||
AZ::Outcome<QVector<ProjectInfo>> GetProjects() override;
|
||||
bool UpdateProject(const ProjectInfo& projectInfo) override;
|
||||
bool AddGemToProject(const QString& gemPath, const QString& projectPath) override;
|
||||
bool RemoveGemFromProject(const QString& gemPath, const QString& projectPath) override;
|
||||
|
||||
// ProjectTemplate
|
||||
AZ::Outcome<QVector<ProjectTemplateInfo>> GetProjectTemplates() override;
|
||||
|
||||
@@ -96,6 +96,22 @@ namespace O3DE::ProjectManager
|
||||
*/
|
||||
virtual bool UpdateProject(const ProjectInfo& projectInfo) = 0;
|
||||
|
||||
/**
|
||||
* Add a gem to a project
|
||||
* @param gemPath the absolute path to the gem
|
||||
* @param projectPath the absolute path to the project
|
||||
* @return true on success, false on failure
|
||||
*/
|
||||
virtual bool AddGemToProject(const QString& gemPath, const QString& projectPath) = 0;
|
||||
|
||||
/**
|
||||
* Remove gem to a project
|
||||
* @param gemPath the absolute path to the gem
|
||||
* @param projectPath the absolute path to the project
|
||||
* @return true on success, false on failure
|
||||
*/
|
||||
virtual bool RemoveGemFromProject(const QString& gemPath, const QString& projectPath) = 0;
|
||||
|
||||
|
||||
// Project Templates
|
||||
|
||||
|
||||
@@ -15,18 +15,20 @@
|
||||
#include <ScreenDefs.h>
|
||||
|
||||
#include <QWidget>
|
||||
#include <QStyleOption>
|
||||
#include <QPainter>
|
||||
#endif
|
||||
|
||||
namespace O3DE::ProjectManager
|
||||
{
|
||||
class ScreenWidget
|
||||
: public QWidget
|
||||
: public QFrame
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit ScreenWidget(QWidget* parent = nullptr)
|
||||
: QWidget(parent)
|
||||
: QFrame(parent)
|
||||
{
|
||||
}
|
||||
~ScreenWidget() = default;
|
||||
|
||||
@@ -22,6 +22,9 @@ namespace O3DE::ProjectManager
|
||||
: QWidget(parent)
|
||||
{
|
||||
QVBoxLayout* vLayout = new QVBoxLayout();
|
||||
vLayout->setMargin(0);
|
||||
vLayout->setSpacing(0);
|
||||
vLayout->setContentsMargins(0, 0, 0, 0);
|
||||
setLayout(vLayout);
|
||||
|
||||
m_screenStack = new QStackedWidget();
|
||||
|
||||
@@ -9,5 +9,8 @@
|
||||
<file>Resources/iOS.svg</file>
|
||||
<file>Resources/Linux.svg</file>
|
||||
<file>Resources/macOS.svg</file>
|
||||
<file>Resources/ArrowDownLine.svg</file>
|
||||
<file>Resources/ArrowUpLine.svg</file>
|
||||
<file>Resources/Backgrounds/FirstTimeBackgroundImage.jpg</file>
|
||||
</qresource>
|
||||
</RCC>
|
||||
|
||||
@@ -22,7 +22,6 @@ set(FILES
|
||||
Source/EngineInfo.cpp
|
||||
Source/FirstTimeUseScreen.h
|
||||
Source/FirstTimeUseScreen.cpp
|
||||
Source/FirstTimeUseScreen.ui
|
||||
Source/ProjectManagerWindow.h
|
||||
Source/ProjectManagerWindow.cpp
|
||||
Source/ProjectTemplateInfo.h
|
||||
|
||||
@@ -41,18 +41,6 @@ namespace AZ
|
||||
static AZ::SceneAPI::FbxSceneImporter::FbxImportRequestHandler* g_fbxImporter = nullptr;
|
||||
static AZStd::vector<AZ::ComponentDescriptor*> g_componentDescriptors;
|
||||
|
||||
void Initialize()
|
||||
{
|
||||
// Currently it's still needed to explicitly create an instance of this instead of letting
|
||||
// it be a normal component. This is because ResourceCompilerScene needs to return
|
||||
// the list of available extensions before it can start the application.
|
||||
if (!g_fbxImporter)
|
||||
{
|
||||
g_fbxImporter = aznew AZ::SceneAPI::FbxSceneImporter::FbxImportRequestHandler();
|
||||
g_fbxImporter->Activate();
|
||||
}
|
||||
}
|
||||
|
||||
void Reflect(AZ::SerializeContext* /*context*/)
|
||||
{
|
||||
// Descriptor registration is done in Reflect instead of Initialize because the ResourceCompilerScene initializes the libraries before
|
||||
@@ -64,6 +52,7 @@ namespace AZ
|
||||
{
|
||||
// Global importer and behavior
|
||||
g_componentDescriptors.push_back(FbxSceneBuilder::FbxImporter::CreateDescriptor());
|
||||
g_componentDescriptors.push_back(FbxSceneImporter::FbxImportRequestHandler::CreateDescriptor());
|
||||
|
||||
// Node and attribute importers
|
||||
g_componentDescriptors.push_back(AssImpBitangentStreamImporter::CreateDescriptor());
|
||||
@@ -125,7 +114,6 @@ namespace AZ
|
||||
extern "C" AZ_DLL_EXPORT void InitializeDynamicModule(void* env)
|
||||
{
|
||||
AZ::Environment::Attach(static_cast<AZ::EnvironmentInstance>(env));
|
||||
AZ::SceneAPI::FbxSceneBuilder::Initialize();
|
||||
}
|
||||
extern "C" AZ_DLL_EXPORT void Reflect(AZ::SerializeContext* context)
|
||||
{
|
||||
|
||||
@@ -10,12 +10,16 @@
|
||||
*
|
||||
*/
|
||||
|
||||
#include <AssetProcessor/AssetBuilderSDK/AssetBuilderSDK/AssetBuilderSDK.h>
|
||||
#include <AzCore/Serialization/EditContextConstants.inl>
|
||||
#include <AzCore/Serialization/SerializeContext.h>
|
||||
#include <AzFramework/StringFunc/StringFunc.h>
|
||||
#include <AzCore/Serialization/Json/JsonSerialization.h>
|
||||
#include <AzCore/Settings/SettingsRegistry.h>
|
||||
#include <AzCore/StringFunc/StringFunc.h>
|
||||
#include <SceneAPI/FbxSceneBuilder/FbxImportRequestHandler.h>
|
||||
#include <SceneAPI/SceneCore/Containers/Scene.h>
|
||||
#include <SceneAPI/SceneCore/Events/CallProcessorBus.h>
|
||||
#include <SceneAPI/SceneCore/Events/ImportEventContext.h>
|
||||
#include <SceneAPI/FbxSceneBuilder/FbxImportRequestHandler.h>
|
||||
|
||||
namespace AZ
|
||||
{
|
||||
@@ -23,10 +27,25 @@ namespace AZ
|
||||
{
|
||||
namespace FbxSceneImporter
|
||||
{
|
||||
const char* FbxImportRequestHandler::s_extension = ".fbx";
|
||||
void SceneImporterSettings::Reflect(AZ::ReflectContext* context)
|
||||
{
|
||||
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context); serializeContext)
|
||||
{
|
||||
serializeContext->Class<SceneImporterSettings>()
|
||||
->Version(1)
|
||||
->Field("SupportedFileTypeExtensions", &SceneImporterSettings::m_supportedFileTypeExtensions);
|
||||
}
|
||||
}
|
||||
|
||||
void FbxImportRequestHandler::Activate()
|
||||
{
|
||||
auto settingsRegistry = AZ::SettingsRegistry::Get();
|
||||
|
||||
if (settingsRegistry)
|
||||
{
|
||||
settingsRegistry->GetObject(m_settings, "/O3DE/SceneAPI/AssetImporter");
|
||||
}
|
||||
|
||||
BusConnect();
|
||||
}
|
||||
|
||||
@@ -37,21 +56,29 @@ namespace AZ
|
||||
|
||||
void FbxImportRequestHandler::Reflect(ReflectContext* context)
|
||||
{
|
||||
SceneImporterSettings::Reflect(context);
|
||||
|
||||
SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context);
|
||||
if (serializeContext)
|
||||
{
|
||||
serializeContext->Class<FbxImportRequestHandler, SceneCore::BehaviorComponent>()->Version(1);
|
||||
serializeContext->Class<FbxImportRequestHandler, AZ::Component>()->Version(1)->Attribute(
|
||||
AZ::Edit::Attributes::SystemComponentTags,
|
||||
AZStd::vector<AZ::Crc32>({AssetBuilderSDK::ComponentTags::AssetBuilder}));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
void FbxImportRequestHandler::GetSupportedFileExtensions(AZStd::unordered_set<AZStd::string>& extensions)
|
||||
{
|
||||
extensions.insert(s_extension);
|
||||
extensions.insert(m_settings.m_supportedFileTypeExtensions.begin(), m_settings.m_supportedFileTypeExtensions.end());
|
||||
}
|
||||
|
||||
Events::LoadingResult FbxImportRequestHandler::LoadAsset(Containers::Scene& scene, const AZStd::string& path, const Uuid& guid, [[maybe_unused]] RequestingApplication requester)
|
||||
{
|
||||
if (!AzFramework::StringFunc::Path::IsExtension(path.c_str(), s_extension))
|
||||
AZStd::string extension;
|
||||
StringFunc::Path::GetExtension(path.c_str(), extension);
|
||||
|
||||
if (!m_settings.m_supportedFileTypeExtensions.contains(extension))
|
||||
{
|
||||
return Events::LoadingResult::Ignored;
|
||||
}
|
||||
@@ -73,6 +100,11 @@ namespace AZ
|
||||
return Events::LoadingResult::AssetFailure;
|
||||
}
|
||||
}
|
||||
|
||||
void FbxImportRequestHandler::GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided)
|
||||
{
|
||||
provided.emplace_back(AZ_CRC_CE("AssetImportRequestHandler"));
|
||||
}
|
||||
} // namespace Import
|
||||
} // namespace SceneAPI
|
||||
} // namespace AZ
|
||||
|
||||
@@ -21,12 +21,21 @@ namespace AZ
|
||||
{
|
||||
namespace FbxSceneImporter
|
||||
{
|
||||
struct SceneImporterSettings
|
||||
{
|
||||
AZ_TYPE_INFO(SceneImporterSettings, "{8BB6C7AD-BF99-44DC-9DA1-E7AD3F03DC10}");
|
||||
|
||||
static void Reflect(AZ::ReflectContext* context);
|
||||
|
||||
AZStd::unordered_set<AZStd::string> m_supportedFileTypeExtensions;
|
||||
};
|
||||
|
||||
class FbxImportRequestHandler
|
||||
: public SceneCore::BehaviorComponent
|
||||
: public AZ::Component
|
||||
, public Events::AssetImportRequestBus::Handler
|
||||
{
|
||||
public:
|
||||
AZ_COMPONENT(FbxImportRequestHandler, "{9F4B189C-0A96-4F44-A5F0-E087FF1561F8}", SceneCore::BehaviorComponent);
|
||||
AZ_COMPONENT(FbxImportRequestHandler, "{9F4B189C-0A96-4F44-A5F0-E087FF1561F8}");
|
||||
|
||||
~FbxImportRequestHandler() override = default;
|
||||
|
||||
@@ -38,8 +47,13 @@ namespace AZ
|
||||
Events::LoadingResult LoadAsset(Containers::Scene& scene, const AZStd::string& path, const Uuid& guid,
|
||||
RequestingApplication requester) override;
|
||||
|
||||
static void GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided);
|
||||
|
||||
private:
|
||||
static const char* s_extension;
|
||||
|
||||
SceneImporterSettings m_settings;
|
||||
|
||||
static constexpr const char* SettingsFilename = "AssetImporterSettings.json";
|
||||
};
|
||||
} // namespace FbxSceneImporter
|
||||
} // namespace SceneAPI
|
||||
|
||||
@@ -260,7 +260,7 @@ namespace AZ
|
||||
{
|
||||
AZ_TraceContext("Importer", "Animation");
|
||||
|
||||
aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiScene* scene = context.m_sourceScene.GetAssImpScene();
|
||||
|
||||
// Add check for animation layers at the scene level.
|
||||
@@ -387,11 +387,10 @@ namespace AZ
|
||||
}
|
||||
|
||||
Events::ProcessingResultCombiner combinedAnimationResult;
|
||||
for (AZ::u32 meshIndex = 0; meshIndex < currentNode->mNumMeshes; ++meshIndex)
|
||||
if (context.m_sourceNode.ContainsMesh())
|
||||
{
|
||||
aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[meshIndex]];
|
||||
|
||||
if (NodeToChannelToMorphAnim::iterator channelsForMeshName = meshMorphAnimations.find(mesh->mName.C_Str());
|
||||
const aiMesh* firstMesh = scene->mMeshes[currentNode->mMeshes[0]];
|
||||
if (NodeToChannelToMorphAnim::iterator channelsForMeshName = meshMorphAnimations.find(firstMesh->mName.C_Str());
|
||||
channelsForMeshName != meshMorphAnimations.end())
|
||||
{
|
||||
const auto [nodeIterName, channels] = *channelsForMeshName;
|
||||
@@ -399,7 +398,7 @@ namespace AZ
|
||||
{
|
||||
const auto& [animation, morphAnimation] = animAndMorphAnim;
|
||||
combinedAnimationResult += ImportBlendShapeAnimation(
|
||||
context, animation, morphAnimation, mesh);
|
||||
context, animation, morphAnimation, firstMesh);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -413,32 +412,39 @@ namespace AZ
|
||||
if (boneAnimations.empty() && !meshMorphAnimations.empty())
|
||||
{
|
||||
const aiAnimation* animation = scene->mAnimations[0];
|
||||
|
||||
// Morph animations need a regular animation on the node, as well.
|
||||
// If there is no bone animation on the current node, then generate one here.
|
||||
AZStd::shared_ptr<SceneData::GraphData::AnimationData> createdAnimationData =
|
||||
AZStd::make_shared<SceneData::GraphData::AnimationData>();
|
||||
|
||||
const size_t numKeyframes = animation->mDuration + 1; // +1 because we start at 0 and the last keyframe is at mDuration instead of mDuration-1
|
||||
createdAnimationData->ReserveKeyFrames(numKeyframes);
|
||||
|
||||
const double timeStepBetweenFrames = 1.0 / animation->mTicksPerSecond;
|
||||
createdAnimationData->SetTimeStepBetweenFrames(timeStepBetweenFrames);
|
||||
|
||||
// Set every frame of the animation to the start location of the node.
|
||||
aiMatrix4x4 combinedTransform = GetConcatenatedLocalTransform(currentNode);
|
||||
DataTypes::MatrixType localTransform = AssImpSDKWrapper::AssImpTypeConverter::ToTransform(combinedTransform);
|
||||
context.m_sourceSceneSystem.SwapTransformForUpAxis(localTransform);
|
||||
context.m_sourceSceneSystem.ConvertUnit(localTransform);
|
||||
for (AZ::u32 time = 0; time <= animation->mDuration; ++time)
|
||||
for (AZ::u32 channelIndex = 0; channelIndex < animation->mNumMorphMeshChannels; ++channelIndex)
|
||||
{
|
||||
createdAnimationData->AddKeyFrame(localTransform);
|
||||
const aiMeshMorphAnim* nodeAnim = animation->mMorphMeshChannels[channelIndex];
|
||||
// Morph animations need a regular animation on the node, as well.
|
||||
// If there is no bone animation on the current node, then generate one here.
|
||||
AZStd::shared_ptr<SceneData::GraphData::AnimationData> createdAnimationData =
|
||||
AZStd::make_shared<SceneData::GraphData::AnimationData>();
|
||||
|
||||
const size_t numKeyframes = GetNumKeyFrames(
|
||||
nodeAnim->mNumKeys,
|
||||
animation->mDuration,
|
||||
animation->mTicksPerSecond);
|
||||
createdAnimationData->ReserveKeyFrames(numKeyframes);
|
||||
|
||||
const double timeStepBetweenFrames = 1.0 / animation->mTicksPerSecond;
|
||||
createdAnimationData->SetTimeStepBetweenFrames(timeStepBetweenFrames);
|
||||
|
||||
// Set every frame of the animation to the start location of the node.
|
||||
aiMatrix4x4 combinedTransform = GetConcatenatedLocalTransform(currentNode);
|
||||
DataTypes::MatrixType localTransform = AssImpSDKWrapper::AssImpTypeConverter::ToTransform(combinedTransform);
|
||||
context.m_sourceSceneSystem.SwapTransformForUpAxis(localTransform);
|
||||
context.m_sourceSceneSystem.ConvertUnit(localTransform);
|
||||
for (AZ::u32 time = 0; time <= numKeyframes; ++time)
|
||||
{
|
||||
createdAnimationData->AddKeyFrame(localTransform);
|
||||
}
|
||||
|
||||
const AZStd::string stubBoneAnimForMorphName(AZStd::string::format("%s%s", nodeName.c_str(), nodeAnim->mName.C_Str()));
|
||||
Containers::SceneGraph::NodeIndex addNode = context.m_scene.GetGraph().AddChild(
|
||||
context.m_currentGraphPosition, stubBoneAnimForMorphName.c_str(), AZStd::move(createdAnimationData));
|
||||
context.m_scene.GetGraph().MakeEndPoint(addNode);
|
||||
}
|
||||
|
||||
Containers::SceneGraph::NodeIndex addNode = context.m_scene.GetGraph().AddChild(
|
||||
context.m_currentGraphPosition, nodeName.c_str(), AZStd::move(createdAnimationData));
|
||||
context.m_scene.GetGraph().MakeEndPoint(addNode);
|
||||
|
||||
|
||||
return combinedAnimationResult.GetResult();
|
||||
}
|
||||
decltype(boneAnimations) parentFillerAnimations;
|
||||
@@ -446,8 +452,8 @@ namespace AZ
|
||||
// Go through all the animations and make sure we create animations for bones who's parents don't have an animation
|
||||
for (auto&& anim : boneAnimations)
|
||||
{
|
||||
aiNode* node = scene->mRootNode->FindNode(anim.first.c_str());
|
||||
aiNode* parent = node->mParent;
|
||||
const aiNode* node = scene->mRootNode->FindNode(anim.first.c_str());
|
||||
const aiNode* parent = node->mParent;
|
||||
|
||||
while (parent && parent != scene->mRootNode)
|
||||
{
|
||||
@@ -598,7 +604,8 @@ namespace AZ
|
||||
// Keyframes generated for every single frame of the animation.
|
||||
typedef AZStd::map<int, AZStd::vector<KeyData>> ValueToKeyDataMap;
|
||||
ValueToKeyDataMap valueToKeyDataMap;
|
||||
|
||||
// Key time can be less than zero, normalize to have zero be the lowest time.
|
||||
double keyOffset = 0;
|
||||
for (int keyIdx = 0; keyIdx < meshMorphAnim->mNumKeys; keyIdx++)
|
||||
{
|
||||
aiMeshMorphKey& key = meshMorphAnim->mKeys[keyIdx];
|
||||
@@ -609,6 +616,10 @@ namespace AZ
|
||||
valueToKeyDataMap[currentValue].insert(
|
||||
AZStd::upper_bound(valueToKeyDataMap[currentValue].begin(), valueToKeyDataMap[currentValue].end(),thisKey),
|
||||
thisKey);
|
||||
if (key.mTime < keyOffset)
|
||||
{
|
||||
keyOffset = key.mTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -631,7 +642,7 @@ namespace AZ
|
||||
const double time = GetTimeForFrame(frame, animation->mTicksPerSecond);
|
||||
|
||||
float weight = 0;
|
||||
if (!SampleKeyFrame(weight, keys, keys.size(), time, keyIdx))
|
||||
if (!SampleKeyFrame(weight, keys, keys.size(), time + keyOffset, keyIdx))
|
||||
{
|
||||
return Events::ProcessingResult::Failure;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
|
||||
#include <assimp/scene.h>
|
||||
#include <assimp/mesh.h>
|
||||
|
||||
namespace AZ
|
||||
{
|
||||
namespace SceneAPI
|
||||
@@ -44,7 +43,7 @@ namespace AZ
|
||||
SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context);
|
||||
if (serializeContext)
|
||||
{
|
||||
serializeContext->Class<AssImpBitangentStreamImporter, SceneCore::LoadingComponent>()->Version(2); // LYN-2576
|
||||
serializeContext->Class<AssImpBitangentStreamImporter, SceneCore::LoadingComponent>()->Version(3); // LYN-3250
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,62 +54,79 @@ namespace AZ
|
||||
{
|
||||
return Events::ProcessingResult::Ignored;
|
||||
}
|
||||
aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiScene* scene = context.m_sourceScene.GetAssImpScene();
|
||||
|
||||
GetMeshDataFromParentResult meshDataResult(GetMeshDataFromParent(context));
|
||||
if (!meshDataResult.IsSuccess())
|
||||
const auto meshHasTangentsAndBitangents = [&scene](const unsigned int meshIndex)
|
||||
{
|
||||
return meshDataResult.GetError();
|
||||
}
|
||||
const SceneData::GraphData::MeshData* const parentMeshData(meshDataResult.GetValue());
|
||||
return scene->mMeshes[meshIndex]->HasTangentsAndBitangents();
|
||||
};
|
||||
|
||||
size_t vertexCount = parentMeshData->GetVertexCount();
|
||||
|
||||
int sdkMeshIndex = parentMeshData->GetSdkMeshIndex();
|
||||
if (sdkMeshIndex < 0 || sdkMeshIndex >= currentNode->mNumMeshes)
|
||||
{
|
||||
AZ_Error(Utilities::ErrorWindow, false,
|
||||
"Tried to construct bitangent stream attribute for invalid or non-mesh parent data, mesh index is invalid");
|
||||
return Events::ProcessingResult::Failure;
|
||||
}
|
||||
|
||||
aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
|
||||
|
||||
if (!mesh->HasTangentsAndBitangents())
|
||||
// If there are no bitangents on any meshes, there's nothing to import in this function.
|
||||
const bool anyMeshHasTangentsAndBitangents = AZStd::any_of(currentNode->mMeshes, currentNode->mMeshes + currentNode->mNumMeshes, meshHasTangentsAndBitangents);
|
||||
if (!anyMeshHasTangentsAndBitangents)
|
||||
{
|
||||
return Events::ProcessingResult::Ignored;
|
||||
}
|
||||
|
||||
// AssImp nodes with multiple meshes on them occur when AssImp split a mesh on material.
|
||||
// This logic recombines those meshes to minimize the changes needed to replace FBX SDK with AssImp, FBX SDK did not separate meshes,
|
||||
// and the engine has code to do this later.
|
||||
const bool allMeshesHaveTangentsAndBitangents = AZStd::all_of(currentNode->mMeshes, currentNode->mMeshes + currentNode->mNumMeshes, meshHasTangentsAndBitangents);
|
||||
if (!allMeshesHaveTangentsAndBitangents)
|
||||
{
|
||||
AZ_Error(
|
||||
Utilities::ErrorWindow, false,
|
||||
"Node with name %s has meshes with and without bitangents. "
|
||||
"Placeholder incorrect bitangents will be generated to allow the data to process, "
|
||||
"but the source art needs to be fixed to correct this. Either apply bitangents to all meshes on this node, "
|
||||
"or remove all bitangents from all meshes on this node.",
|
||||
currentNode->mName.C_Str());
|
||||
}
|
||||
|
||||
const uint64_t vertexCount = GetVertexCountForAllMeshesOnNode(*currentNode, *scene);
|
||||
|
||||
AZStd::shared_ptr<SceneData::GraphData::MeshVertexBitangentData> bitangentStream =
|
||||
AZStd::make_shared<AZ::SceneData::GraphData::MeshVertexBitangentData>();
|
||||
|
||||
// AssImp only has one bitangentStream per mesh.
|
||||
bitangentStream->SetBitangentSetIndex(0);
|
||||
|
||||
bitangentStream->SetTangentSpace(AZ::SceneAPI::DataTypes::TangentSpace::FromFbx);
|
||||
bitangentStream->ReserveContainerSpace(vertexCount);
|
||||
|
||||
for (int v = 0; v < mesh->mNumVertices; ++v)
|
||||
for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
|
||||
{
|
||||
const Vector3 bitangent(
|
||||
AssImpSDKWrapper::AssImpTypeConverter::ToVector3(mesh->mBitangents[v]));
|
||||
bitangentStream->AppendBitangent(bitangent);
|
||||
const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
|
||||
|
||||
for (int v = 0; v < mesh->mNumVertices; ++v)
|
||||
{
|
||||
if (!mesh->HasTangentsAndBitangents())
|
||||
{
|
||||
// This node has mixed meshes with and without bitangents.
|
||||
// An error was already thrown above. Output stub bitangents so
|
||||
// the mesh can still be output in some form, even if the data isn't correct.
|
||||
// The bitangent count needs to match the vertex count on the associated mesh node.
|
||||
bitangentStream->AppendBitangent(Vector3::CreateAxisY());
|
||||
}
|
||||
else
|
||||
{
|
||||
const Vector3 bitangent(
|
||||
AssImpSDKWrapper::AssImpTypeConverter::ToVector3(mesh->mBitangents[v]));
|
||||
bitangentStream->AppendBitangent(bitangent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AZStd::string nodeName(AZStd::string::format("%s",m_defaultNodeName));
|
||||
Containers::SceneGraph::NodeIndex newIndex =
|
||||
context.m_scene.GetGraph().AddChild(context.m_currentGraphPosition, nodeName.c_str());
|
||||
context.m_scene.GetGraph().AddChild(context.m_currentGraphPosition, m_defaultNodeName);
|
||||
|
||||
Events::ProcessingResult bitangentResults;
|
||||
AssImpSceneAttributeDataPopulatedContext dataPopulated(context, bitangentStream, newIndex, nodeName.c_str());
|
||||
AssImpSceneAttributeDataPopulatedContext dataPopulated(context, bitangentStream, newIndex, m_defaultNodeName);
|
||||
bitangentResults = Events::Process(dataPopulated);
|
||||
|
||||
if (bitangentResults != Events::ProcessingResult::Failure)
|
||||
{
|
||||
bitangentResults = AddAttributeDataNodeWithContexts(dataPopulated);
|
||||
}
|
||||
|
||||
return bitangentResults;
|
||||
}
|
||||
|
||||
|
||||
@@ -74,37 +74,51 @@ namespace AZ
|
||||
{
|
||||
return meshDataResult.GetError();
|
||||
}
|
||||
const SceneData::GraphData::MeshData* const parentMeshData(meshDataResult.GetValue());
|
||||
int parentMeshIndex = parentMeshData->GetSdkMeshIndex();
|
||||
|
||||
Events::ProcessingResultCombiner combinedBlendShapeResult;
|
||||
|
||||
// 1. Loop through meshes & anims
|
||||
// Create storage: Anim to meshes
|
||||
// 2. Loop through anims & meshes
|
||||
// Create an anim mesh for each anim, with meshes re-combined.
|
||||
// AssImp separates meshes that have multiple materials.
|
||||
// This code re-combines them to match previous FBX SDK behavior,
|
||||
// so they can be separated by engine code instead.
|
||||
AZStd::map<AZStd::string_view, AZStd::vector<AZStd::pair<int, int>>> animToMeshToAnimMeshIndices;
|
||||
for (int nodeMeshIdx = 0; nodeMeshIdx < numMesh; nodeMeshIdx++)
|
||||
{
|
||||
int sceneMeshIdx = context.m_sourceNode.GetAssImpNode()->mMeshes[nodeMeshIdx];
|
||||
const aiMesh* aiMesh = context.m_sourceScene.GetAssImpScene()->mMeshes[sceneMeshIdx];
|
||||
|
||||
// Each mesh gets its own node in the scene graph, so only generate
|
||||
// morph targets for the current mesh.
|
||||
if (parentMeshIndex != nodeMeshIdx || !aiMesh->mNumAnimMeshes)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int animIdx = 0; animIdx < aiMesh->mNumAnimMeshes; animIdx++)
|
||||
{
|
||||
AZStd::shared_ptr<SceneData::GraphData::BlendShapeData> blendShapeData =
|
||||
AZStd::make_shared<SceneData::GraphData::BlendShapeData>();
|
||||
|
||||
aiAnimMesh* aiAnimMesh = aiMesh->mAnimMeshes[animIdx];
|
||||
AZStd::string nodeName(aiAnimMesh->mName.C_Str());
|
||||
size_t dotIndex = nodeName.rfind('.');
|
||||
if (dotIndex != AZStd::string::npos)
|
||||
{
|
||||
nodeName.erase(0, dotIndex + 1);
|
||||
}
|
||||
RenamedNodesMap::SanitizeNodeName(nodeName, context.m_scene.GetGraph(), context.m_currentGraphPosition, "BlendShape");
|
||||
AZ_TraceContext("Blend shape name", nodeName);
|
||||
animToMeshToAnimMeshIndices[aiAnimMesh->mName.C_Str()].emplace_back(nodeMeshIdx, animIdx);
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& animToMeshIndex : animToMeshToAnimMeshIndices)
|
||||
{
|
||||
AZStd::shared_ptr<SceneData::GraphData::BlendShapeData> blendShapeData =
|
||||
AZStd::make_shared<SceneData::GraphData::BlendShapeData>();
|
||||
|
||||
// Some DCC tools, like Maya, include a full path separated by '.' in the node names.
|
||||
// For example, "cone_skin_blendShapeNode.cone_squash"
|
||||
// Downstream processing doesn't want anything but the last part of that node name,
|
||||
// so find the last '.' and remove anything before it.
|
||||
AZStd::string nodeName(animToMeshIndex.first);
|
||||
size_t dotIndex = nodeName.rfind('.');
|
||||
if (dotIndex != AZStd::string::npos)
|
||||
{
|
||||
nodeName.erase(0, dotIndex + 1);
|
||||
}
|
||||
int vertexOffset = 0;
|
||||
RenamedNodesMap::SanitizeNodeName(nodeName, context.m_scene.GetGraph(), context.m_currentGraphPosition, "BlendShape");
|
||||
AZ_TraceContext("Blend shape name", nodeName);
|
||||
for (const auto& meshIndex : animToMeshIndex.second)
|
||||
{
|
||||
int sceneMeshIdx = context.m_sourceNode.GetAssImpNode()->mMeshes[meshIndex.first];
|
||||
const aiMesh* aiMesh = context.m_sourceScene.GetAssImpScene()->mMeshes[sceneMeshIdx];
|
||||
const aiAnimMesh* aiAnimMesh = aiMesh->mAnimMeshes[meshIndex.second];
|
||||
|
||||
AZStd::bitset<SceneData::GraphData::BlendShapeData::MaxNumUVSets> uvSetUsedFlags;
|
||||
for (AZ::u8 uvSetIndex = 0; uvSetIndex < SceneData::GraphData::BlendShapeData::MaxNumUVSets; ++uvSetIndex)
|
||||
@@ -128,7 +142,7 @@ namespace AZ
|
||||
context.m_sourceSceneSystem.ConvertUnit(vertex);
|
||||
|
||||
blendShapeData->AddPosition(vertex);
|
||||
blendShapeData->SetVertexIndexToControlPointIndexMap(vertIdx, vertIdx);
|
||||
blendShapeData->SetVertexIndexToControlPointIndexMap(vertIdx + vertexOffset, vertIdx + vertexOffset);
|
||||
|
||||
// Add normals
|
||||
if (aiAnimMesh->HasNormals())
|
||||
@@ -191,33 +205,36 @@ namespace AZ
|
||||
}
|
||||
for (int idx = 0; idx < face.mNumIndices; ++idx)
|
||||
{
|
||||
blendFace.vertexIndex[idx] = face.mIndices[idx];
|
||||
blendFace.vertexIndex[idx] = face.mIndices[idx] + vertexOffset;
|
||||
}
|
||||
|
||||
blendShapeData->AddFace(blendFace);
|
||||
}
|
||||
vertexOffset += aiMesh->mNumVertices;
|
||||
|
||||
// Report problem if no vertex or face converted to MeshData
|
||||
if (blendShapeData->GetVertexCount() <= 0 || blendShapeData->GetFaceCount() <= 0)
|
||||
{
|
||||
AZ_Error(Utilities::ErrorWindow, false, "Missing geometry data in blendshape node %s.", nodeName.c_str());
|
||||
return Events::ProcessingResult::Failure;
|
||||
}
|
||||
|
||||
Containers::SceneGraph::NodeIndex newIndex =
|
||||
context.m_scene.GetGraph().AddChild(context.m_currentGraphPosition, nodeName.c_str());
|
||||
|
||||
Events::ProcessingResult blendShapeResult;
|
||||
AssImpSceneAttributeDataPopulatedContext dataPopulated(context, blendShapeData, newIndex, nodeName);
|
||||
blendShapeResult = Events::Process(dataPopulated);
|
||||
|
||||
if (blendShapeResult != Events::ProcessingResult::Failure)
|
||||
{
|
||||
blendShapeResult = AddAttributeDataNodeWithContexts(dataPopulated);
|
||||
}
|
||||
combinedBlendShapeResult += blendShapeResult;
|
||||
}
|
||||
|
||||
|
||||
// Report problem if no vertex or face converted to MeshData
|
||||
if (blendShapeData->GetVertexCount() <= 0 || blendShapeData->GetFaceCount() <= 0)
|
||||
{
|
||||
AZ_Error(Utilities::ErrorWindow, false, "Missing geometry data in blendshape node %s.", nodeName.c_str());
|
||||
return Events::ProcessingResult::Failure;
|
||||
}
|
||||
|
||||
Containers::SceneGraph::NodeIndex newIndex =
|
||||
context.m_scene.GetGraph().AddChild(context.m_currentGraphPosition, nodeName.c_str());
|
||||
|
||||
Events::ProcessingResult blendShapeResult;
|
||||
AssImpSceneAttributeDataPopulatedContext dataPopulated(context, blendShapeData, newIndex, nodeName);
|
||||
blendShapeResult = Events::Process(dataPopulated);
|
||||
|
||||
if (blendShapeResult != Events::ProcessingResult::Failure)
|
||||
{
|
||||
blendShapeResult = AddAttributeDataNodeWithContexts(dataPopulated);
|
||||
}
|
||||
combinedBlendShapeResult += blendShapeResult;
|
||||
}
|
||||
|
||||
return combinedBlendShapeResult.GetResult();
|
||||
|
||||
@@ -46,8 +46,8 @@ namespace AZ
|
||||
}
|
||||
|
||||
void EnumBonesInNode(
|
||||
const aiScene* scene, const aiNode* node, AZStd::unordered_map<AZStd::string, aiNode*>& mainBoneList,
|
||||
AZStd::unordered_map<AZStd::string, aiBone*>& boneLookup)
|
||||
const aiScene* scene, const aiNode* node, AZStd::unordered_map<AZStd::string, const aiNode*>& mainBoneList,
|
||||
AZStd::unordered_map<AZStd::string, const aiBone*>& boneLookup)
|
||||
{
|
||||
/* From AssImp Documentation
|
||||
a) Create a map or a similar container to store which nodes are necessary for the skeleton. Pre-initialise it for all nodes with a "no".
|
||||
@@ -62,14 +62,14 @@ namespace AZ
|
||||
|
||||
for (unsigned meshIndex = 0; meshIndex < node->mNumMeshes; ++meshIndex)
|
||||
{
|
||||
aiMesh* mesh = scene->mMeshes[node->mMeshes[meshIndex]];
|
||||
const aiMesh* mesh = scene->mMeshes[node->mMeshes[meshIndex]];
|
||||
|
||||
for (unsigned boneIndex = 0; boneIndex < mesh->mNumBones; ++boneIndex)
|
||||
{
|
||||
aiBone* bone = mesh->mBones[boneIndex];
|
||||
const aiBone* bone = mesh->mBones[boneIndex];
|
||||
|
||||
aiNode* boneNode = scene->mRootNode->FindNode(bone->mName);
|
||||
aiNode* boneParent = boneNode->mParent;
|
||||
const aiNode* boneNode = scene->mRootNode->FindNode(bone->mName);
|
||||
const aiNode* boneParent = boneNode->mParent;
|
||||
|
||||
mainBoneList[bone->mName.C_Str()] = boneNode;
|
||||
boneLookup[bone->mName.C_Str()] = bone;
|
||||
@@ -85,8 +85,8 @@ namespace AZ
|
||||
}
|
||||
|
||||
void EnumChildren(
|
||||
const aiScene* scene, const aiNode* node, AZStd::unordered_map<AZStd::string, aiNode*>& mainBoneList,
|
||||
AZStd::unordered_map<AZStd::string, aiBone*>& boneLookup)
|
||||
const aiScene* scene, const aiNode* node, AZStd::unordered_map<AZStd::string, const aiNode*>& mainBoneList,
|
||||
AZStd::unordered_map<AZStd::string, const aiBone*>& boneLookup)
|
||||
{
|
||||
EnumBonesInNode(scene, node, mainBoneList, boneLookup);
|
||||
|
||||
@@ -102,7 +102,7 @@ namespace AZ
|
||||
{
|
||||
AZ_TraceContext("Importer", "Bone");
|
||||
|
||||
aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiScene* scene = context.m_sourceScene.GetAssImpScene();
|
||||
|
||||
if (IsPivotNode(currentNode->mName))
|
||||
@@ -118,8 +118,8 @@ namespace AZ
|
||||
}
|
||||
else
|
||||
{
|
||||
AZStd::unordered_map<AZStd::string, aiNode*> mainBoneList;
|
||||
AZStd::unordered_map<AZStd::string, aiBone*> boneLookup;
|
||||
AZStd::unordered_map<AZStd::string, const aiNode*> mainBoneList;
|
||||
AZStd::unordered_map<AZStd::string, const aiBone*> boneLookup;
|
||||
EnumChildren(scene, scene->mRootNode, mainBoneList, boneLookup);
|
||||
|
||||
if (mainBoneList.find(currentNode->mName.C_Str()) != mainBoneList.end())
|
||||
@@ -172,7 +172,7 @@ namespace AZ
|
||||
}
|
||||
|
||||
aiMatrix4x4 transform = currentNode->mTransformation;
|
||||
aiNode* parent = currentNode->mParent;
|
||||
const aiNode* parent = currentNode->mParent;
|
||||
|
||||
while (parent)
|
||||
{
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
|
||||
#include <AzCore/Serialization/SerializeContext.h>
|
||||
#include <AzCore/std/numeric.h>
|
||||
#include <AzCore/std/smart_ptr/make_shared.h>
|
||||
#include <AzToolsFramework/Debug/TraceContext.h>
|
||||
#include <SceneAPI/FbxSceneBuilder/Importers/AssImpColorStreamImporter.h>
|
||||
@@ -44,7 +45,7 @@ namespace AZ
|
||||
SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context);
|
||||
if (serializeContext)
|
||||
{
|
||||
serializeContext->Class<AssImpColorStreamImporter, SceneCore::LoadingComponent>()->Version(2); // LYN-2576
|
||||
serializeContext->Class<AssImpColorStreamImporter, SceneCore::LoadingComponent>()->Version(3); // LYN-3250
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,43 +56,64 @@ namespace AZ
|
||||
{
|
||||
return Events::ProcessingResult::Ignored;
|
||||
}
|
||||
aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiScene* scene = context.m_sourceScene.GetAssImpScene();
|
||||
|
||||
GetMeshDataFromParentResult meshDataResult(GetMeshDataFromParent(context));
|
||||
if (!meshDataResult.IsSuccess())
|
||||
{
|
||||
return meshDataResult.GetError();
|
||||
}
|
||||
const SceneData::GraphData::MeshData* const parentMeshData(meshDataResult.GetValue());
|
||||
// This node has at least one mesh, verify that the color channel counts are the same for all meshes.
|
||||
const int expectedColorChannels = scene->mMeshes[currentNode->mMeshes[0]]->GetNumColorChannels();
|
||||
const bool allMeshesHaveSameNumberOfColorChannels =
|
||||
AZStd::all_of(currentNode->mMeshes + 1, currentNode->mMeshes + currentNode->mNumMeshes, [scene, expectedColorChannels](const unsigned int meshIndex)
|
||||
{
|
||||
return scene->mMeshes[meshIndex]->GetNumColorChannels() == expectedColorChannels;
|
||||
});
|
||||
|
||||
size_t vertexCount = parentMeshData->GetVertexCount();
|
||||
AZ_Error(
|
||||
Utilities::ErrorWindow,
|
||||
allMeshesHaveSameNumberOfColorChannels,
|
||||
"Color channel counts for node %s has meshes with different color channel counts. "
|
||||
"The color channel count for the first mesh will be used, and placeholder incorrect color values "
|
||||
"will be generated to allow the data to process, but the source art needs to be fixed to correct this. "
|
||||
"All meshes on this node should have the same number of color channels.",
|
||||
currentNode->mName.C_Str());
|
||||
|
||||
int sdkMeshIndex = parentMeshData->GetSdkMeshIndex();
|
||||
if (sdkMeshIndex < 0)
|
||||
if (expectedColorChannels == 0)
|
||||
{
|
||||
AZ_Error(Utilities::ErrorWindow, false,
|
||||
"Tried to construct color stream attribute for invalid or non-mesh parent data, mesh index is missing");
|
||||
return Events::ProcessingResult::Failure;
|
||||
return Events::ProcessingResult::Ignored;
|
||||
}
|
||||
|
||||
aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
|
||||
const uint64_t vertexCount = GetVertexCountForAllMeshesOnNode(*currentNode, *scene);
|
||||
|
||||
Events::ProcessingResultCombiner combinedVertexColorResults;
|
||||
for (int colorSetIndex = 0; colorSetIndex < mesh->GetNumColorChannels(); ++colorSetIndex)
|
||||
for (int colorSetIndex = 0; colorSetIndex < expectedColorChannels; ++colorSetIndex)
|
||||
{
|
||||
|
||||
AZStd::shared_ptr<SceneData::GraphData::MeshVertexColorData> vertexColors =
|
||||
AZStd::make_shared<AZ::SceneData::GraphData::MeshVertexColorData>();
|
||||
vertexColors->ReserveContainerSpace(vertexCount);
|
||||
|
||||
for (int v = 0; v < mesh->mNumVertices; ++v)
|
||||
for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
|
||||
{
|
||||
AZ::SceneAPI::DataTypes::Color vertexColor(
|
||||
AssImpSDKWrapper::AssImpTypeConverter::ToColor(mesh->mColors[colorSetIndex][v]));
|
||||
vertexColors->AppendColor(vertexColor);
|
||||
const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
|
||||
for (int v = 0; v < mesh->mNumVertices; ++v)
|
||||
{
|
||||
if (colorSetIndex < mesh->GetNumColorChannels())
|
||||
{
|
||||
AZ::SceneAPI::DataTypes::Color vertexColor(
|
||||
AssImpSDKWrapper::AssImpTypeConverter::ToColor(mesh->mColors[colorSetIndex][v]));
|
||||
vertexColors->AppendColor(vertexColor);
|
||||
}
|
||||
else
|
||||
{
|
||||
// An error was already emitted if this mesh has less color channels
|
||||
// than other meshes on the parent node. Append an arbitrary color value, fully opaque black,
|
||||
// so the mesh can still be processed.
|
||||
// It's better to let the engine load a partially valid mesh than to completely fail.
|
||||
vertexColors->AppendColor(AZ::SceneAPI::DataTypes::Color(0.0f,0.0f,0.0f,1.0f));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AZStd::string nodeName(AZStd::string::format("%s%d",m_defaultNodeName,colorSetIndex));
|
||||
AZStd::string nodeName(AZStd::string::format("%s%d", m_defaultNodeName, colorSetIndex));
|
||||
Containers::SceneGraph::NodeIndex newIndex =
|
||||
context.m_scene.GetGraph().AddChild(context.m_currentGraphPosition, nodeName.c_str());
|
||||
|
||||
@@ -106,9 +128,7 @@ namespace AZ
|
||||
|
||||
combinedVertexColorResults += colorMapResults;
|
||||
}
|
||||
|
||||
return combinedVertexColorResults.GetResult();
|
||||
|
||||
}
|
||||
|
||||
} // namespace FbxSceneBuilder
|
||||
|
||||
@@ -69,7 +69,7 @@ namespace AZ
|
||||
|
||||
aiMatrix4x4 GetConcatenatedLocalTransform(const aiNode* currentNode)
|
||||
{
|
||||
aiNode* parent = currentNode->mParent;
|
||||
const aiNode* parent = currentNode->mParent;
|
||||
aiMatrix4x4 combinedTransform = currentNode->mTransformation;
|
||||
|
||||
while (parent)
|
||||
|
||||
@@ -62,7 +62,7 @@ namespace AZ
|
||||
for (int idx = 0; idx < context.m_sourceNode.m_assImpNode->mNumMeshes; ++idx)
|
||||
{
|
||||
int meshIndex = context.m_sourceNode.m_assImpNode->mMeshes[idx];
|
||||
aiMesh* assImpMesh = context.m_sourceScene.GetAssImpScene()->mMeshes[meshIndex];
|
||||
const aiMesh* assImpMesh = context.m_sourceScene.GetAssImpScene()->mMeshes[meshIndex];
|
||||
AZ_Assert(assImpMesh, "Asset Importer Mesh should not be null.");
|
||||
int materialIndex = assImpMesh->mMaterialIndex;
|
||||
AZ_TraceContext("Material Index", materialIndex);
|
||||
|
||||
@@ -45,7 +45,7 @@ namespace AZ
|
||||
{
|
||||
AZ_TraceContext("Importer", "Mesh");
|
||||
|
||||
aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiScene* scene = context.m_sourceScene.GetAssImpScene();
|
||||
|
||||
if (!context.m_sourceNode.ContainsMesh() || IsSkinnedMesh(*currentNode, *scene))
|
||||
|
||||
@@ -45,7 +45,7 @@ namespace AZ
|
||||
{
|
||||
AZ_TraceContext("Importer", "Skin");
|
||||
|
||||
aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiScene* scene = context.m_sourceScene.GetAssImpScene();
|
||||
|
||||
if (!context.m_sourceNode.ContainsMesh() || !IsSkinnedMesh(*currentNode, *scene))
|
||||
|
||||
@@ -51,7 +51,7 @@ namespace AZ
|
||||
{
|
||||
AZ_TraceContext("Importer", "Skin Weights");
|
||||
|
||||
aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiScene* scene = context.m_sourceScene.GetAssImpScene();
|
||||
|
||||
if(currentNode->mNumMeshes <= 0)
|
||||
@@ -59,35 +59,21 @@ namespace AZ
|
||||
return Events::ProcessingResult::Ignored;
|
||||
}
|
||||
|
||||
GetMeshDataFromParentResult meshDataResult(GetMeshDataFromParent(context));
|
||||
if (!meshDataResult.IsSuccess())
|
||||
{
|
||||
return meshDataResult.GetError();
|
||||
}
|
||||
const SceneData::GraphData::MeshData* const parentMeshData(meshDataResult.GetValue());
|
||||
|
||||
int parentMeshIndex = parentMeshData->GetSdkMeshIndex();
|
||||
|
||||
Events::ProcessingResultCombiner combinedSkinWeightsResult;
|
||||
|
||||
// Don't create this until a bone with weights is encountered
|
||||
Containers::SceneGraph::NodeIndex weightsIndexForMesh;
|
||||
AZStd::string skinWeightName;
|
||||
AZStd::shared_ptr<SceneData::GraphData::SkinWeightData> skinWeightData;
|
||||
|
||||
const uint64_t totalVertices = GetVertexCountForAllMeshesOnNode(*currentNode, *scene);
|
||||
|
||||
int vertexCount = 0;
|
||||
for(unsigned nodeMeshIndex = 0; nodeMeshIndex < currentNode->mNumMeshes; ++nodeMeshIndex)
|
||||
{
|
||||
if (nodeMeshIndex != parentMeshIndex)
|
||||
{
|
||||
// Only generate skinning data for the parent mesh.
|
||||
// Each AssImp mesh is assigned to a unique node,
|
||||
// so the skinning data should be generated as a child node
|
||||
// for the associated parent mesh.
|
||||
continue;
|
||||
}
|
||||
int sceneMeshIndex = currentNode->mMeshes[nodeMeshIndex];
|
||||
const aiMesh* mesh = scene->mMeshes[sceneMeshIndex];
|
||||
|
||||
// Don't create this until a bone with weights is encountered
|
||||
Containers::SceneGraph::NodeIndex weightsIndexForMesh;
|
||||
AZStd::string skinWeightName;
|
||||
AZStd::shared_ptr<SceneData::GraphData::SkinWeightData> skinWeightData;
|
||||
|
||||
for(unsigned b = 0; b < mesh->mNumBones; ++b)
|
||||
{
|
||||
const aiBone* bone = mesh->mBones[b];
|
||||
@@ -100,7 +86,6 @@ namespace AZ
|
||||
if (!weightsIndexForMesh.IsValid())
|
||||
{
|
||||
skinWeightName = s_skinWeightName;
|
||||
skinWeightName += AZStd::to_string(nodeMeshIndex);
|
||||
RenamedNodesMap::SanitizeNodeName(skinWeightName, context.m_scene.GetGraph(), context.m_currentGraphPosition);
|
||||
|
||||
weightsIndexForMesh =
|
||||
@@ -116,23 +101,25 @@ namespace AZ
|
||||
}
|
||||
Pending pending;
|
||||
pending.m_bone = bone;
|
||||
pending.m_numVertices = mesh->mNumVertices;
|
||||
pending.m_numVertices = totalVertices;
|
||||
pending.m_skinWeightData = skinWeightData;
|
||||
pending.m_vertOffset = vertexCount;
|
||||
m_pendingSkinWeights.push_back(pending);
|
||||
}
|
||||
|
||||
Events::ProcessingResult skinWeightsResult;
|
||||
AssImpSceneAttributeDataPopulatedContext dataPopulated(context, skinWeightData, weightsIndexForMesh, skinWeightName);
|
||||
skinWeightsResult = Events::Process(dataPopulated);
|
||||
|
||||
if (skinWeightsResult != Events::ProcessingResult::Failure)
|
||||
{
|
||||
skinWeightsResult = AddAttributeDataNodeWithContexts(dataPopulated);
|
||||
}
|
||||
|
||||
combinedSkinWeightsResult += skinWeightsResult;
|
||||
vertexCount += mesh->mNumVertices;
|
||||
}
|
||||
|
||||
Events::ProcessingResult skinWeightsResult;
|
||||
AssImpSceneAttributeDataPopulatedContext dataPopulated(context, skinWeightData, weightsIndexForMesh, skinWeightName);
|
||||
skinWeightsResult = Events::Process(dataPopulated);
|
||||
|
||||
if (skinWeightsResult != Events::ProcessingResult::Failure)
|
||||
{
|
||||
skinWeightsResult = AddAttributeDataNodeWithContexts(dataPopulated);
|
||||
}
|
||||
|
||||
combinedSkinWeightsResult += skinWeightsResult;
|
||||
|
||||
return combinedSkinWeightsResult.GetResult();
|
||||
}
|
||||
|
||||
@@ -153,7 +140,7 @@ namespace AZ
|
||||
link.boneId = boneId;
|
||||
link.weight = it.m_bone->mWeights[weight].mWeight;
|
||||
|
||||
it.m_skinWeightData->AddAndSortLink(it.m_bone->mWeights[weight].mVertexId, link);
|
||||
it.m_skinWeightData->AddAndSortLink(it.m_bone->mWeights[weight].mVertexId + it.m_vertOffset, link);
|
||||
}
|
||||
}
|
||||
const auto result = m_pendingSkinWeights.empty() ? Events::ProcessingResult::Ignored : Events::ProcessingResult::Success;
|
||||
|
||||
@@ -61,6 +61,7 @@ namespace AZ
|
||||
{
|
||||
const aiBone* m_bone = nullptr;
|
||||
unsigned m_numVertices = 0;
|
||||
unsigned m_vertOffset = 0;
|
||||
AZStd::shared_ptr<SceneData::GraphData::SkinWeightData> m_skinWeightData;
|
||||
};
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
|
||||
#include <AzCore/Serialization/SerializeContext.h>
|
||||
#include <AzCore/std/numeric.h>
|
||||
#include <AzCore/std/smart_ptr/make_shared.h>
|
||||
#include <AzToolsFramework/Debug/TraceContext.h>
|
||||
#include <SceneAPI/FbxSceneBuilder/Importers/AssImpTangentStreamImporter.h>
|
||||
@@ -44,7 +45,7 @@ namespace AZ
|
||||
SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context);
|
||||
if (serializeContext)
|
||||
{
|
||||
serializeContext->Class<AssImpTangentStreamImporter, SceneCore::LoadingComponent>()->Version(2); // LYN-2576
|
||||
serializeContext->Class<AssImpTangentStreamImporter, SceneCore::LoadingComponent>()->Version(3); // LYN-3250
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,62 +56,79 @@ namespace AZ
|
||||
{
|
||||
return Events::ProcessingResult::Ignored;
|
||||
}
|
||||
aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiScene* scene = context.m_sourceScene.GetAssImpScene();
|
||||
|
||||
GetMeshDataFromParentResult meshDataResult(GetMeshDataFromParent(context));
|
||||
if (!meshDataResult.IsSuccess())
|
||||
|
||||
const auto meshHasTangentsAndBitangents = [&scene](const unsigned int meshIndex)
|
||||
{
|
||||
return meshDataResult.GetError();
|
||||
}
|
||||
const SceneData::GraphData::MeshData* const parentMeshData(meshDataResult.GetValue());
|
||||
return scene->mMeshes[meshIndex]->HasTangentsAndBitangents();
|
||||
};
|
||||
|
||||
size_t vertexCount = parentMeshData->GetVertexCount();
|
||||
|
||||
int sdkMeshIndex = parentMeshData->GetSdkMeshIndex();
|
||||
if (sdkMeshIndex < 0 || sdkMeshIndex >= currentNode->mNumMeshes)
|
||||
{
|
||||
AZ_Error(Utilities::ErrorWindow, false,
|
||||
"Tried to construct tangent stream attribute for invalid or non-mesh parent data, mesh index is invalid");
|
||||
return Events::ProcessingResult::Failure;
|
||||
}
|
||||
|
||||
aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
|
||||
|
||||
if (!mesh->HasTangentsAndBitangents())
|
||||
// If there are no tangents on any meshes, there's nothing to import in this function.
|
||||
const bool anyMeshHasTangentsAndBitangents = AZStd::any_of(currentNode->mMeshes, currentNode->mMeshes + currentNode->mNumMeshes, meshHasTangentsAndBitangents);
|
||||
if (!anyMeshHasTangentsAndBitangents)
|
||||
{
|
||||
return Events::ProcessingResult::Ignored;
|
||||
}
|
||||
|
||||
// AssImp nodes with multiple meshes on them occur when AssImp split a mesh on material.
|
||||
// This logic recombines those meshes to minimize the changes needed to replace FBX SDK with AssImp, FBX SDK did not separate meshes,
|
||||
// and the engine has code to do this later.
|
||||
const bool allMeshesHaveTangentsAndBitangents = AZStd::all_of(currentNode->mMeshes, currentNode->mMeshes + currentNode->mNumMeshes, meshHasTangentsAndBitangents);
|
||||
if (!allMeshesHaveTangentsAndBitangents)
|
||||
{
|
||||
AZ_Error(
|
||||
Utilities::ErrorWindow, false,
|
||||
"Node with name %s has meshes with and without tangents. "
|
||||
"Placeholder incorrect tangents will be generated to allow the data to process, "
|
||||
"but the source art needs to be fixed to correct this. Either apply tangents to all meshes on this node, "
|
||||
"or remove all tangents from all meshes on this node.",
|
||||
currentNode->mName.C_Str());
|
||||
}
|
||||
|
||||
const uint64_t vertexCount = GetVertexCountForAllMeshesOnNode(*currentNode, *scene);
|
||||
|
||||
AZStd::shared_ptr<SceneData::GraphData::MeshVertexTangentData> tangentStream =
|
||||
AZStd::make_shared<AZ::SceneData::GraphData::MeshVertexTangentData>();
|
||||
|
||||
// AssImp only has one tangentStream per mesh.
|
||||
tangentStream->SetTangentSetIndex(0);
|
||||
|
||||
tangentStream->SetTangentSpace(AZ::SceneAPI::DataTypes::TangentSpace::FromFbx);
|
||||
tangentStream->ReserveContainerSpace(vertexCount);
|
||||
|
||||
for (int v = 0; v < mesh->mNumVertices; ++v)
|
||||
for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
|
||||
{
|
||||
// Vector4's constructor that takes in a vector3 sets w to 1.0f automatically.
|
||||
const Vector4 tangent(AssImpSDKWrapper::AssImpTypeConverter::ToVector3(mesh->mTangents[v]));
|
||||
tangentStream->AppendTangent(tangent);
|
||||
const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
|
||||
|
||||
for (int v = 0; v < mesh->mNumVertices; ++v)
|
||||
{
|
||||
if (!mesh->HasTangentsAndBitangents())
|
||||
{
|
||||
// This node has mixed meshes with and without tangents.
|
||||
// An error was already thrown above. Output stub tangents so
|
||||
// the mesh can still be output in some form, even if the data isn't correct.
|
||||
// The tangent count needs to match the vertex count on the associated mesh node.
|
||||
tangentStream->AppendTangent(Vector4(0.f, 1.f, 0.f, 1.f));
|
||||
}
|
||||
else
|
||||
{
|
||||
const Vector4 tangent(
|
||||
AssImpSDKWrapper::AssImpTypeConverter::ToVector3(mesh->mTangents[v]));
|
||||
tangentStream->AppendTangent(tangent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AZStd::string nodeName(AZStd::string::format("%s", m_defaultNodeName));
|
||||
Containers::SceneGraph::NodeIndex newIndex =
|
||||
context.m_scene.GetGraph().AddChild(context.m_currentGraphPosition, nodeName.c_str());
|
||||
context.m_scene.GetGraph().AddChild(context.m_currentGraphPosition, m_defaultNodeName);
|
||||
|
||||
Events::ProcessingResult tangentResults;
|
||||
AssImpSceneAttributeDataPopulatedContext dataPopulated(context, tangentStream, newIndex, nodeName.c_str());
|
||||
AssImpSceneAttributeDataPopulatedContext dataPopulated(context, tangentStream, newIndex, m_defaultNodeName);
|
||||
tangentResults = Events::Process(dataPopulated);
|
||||
|
||||
if (tangentResults != Events::ProcessingResult::Failure)
|
||||
{
|
||||
tangentResults = AddAttributeDataNodeWithContexts(dataPopulated);
|
||||
}
|
||||
|
||||
return tangentResults;
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ namespace AZ
|
||||
Events::ProcessingResult AssImpTransformImporter::ImportTransform(AssImpSceneNodeAppendedContext& context)
|
||||
{
|
||||
AZ_TraceContext("Importer", "transform");
|
||||
aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiScene* scene = context.m_sourceScene.GetAssImpScene();
|
||||
|
||||
if (currentNode == scene->mRootNode || IsPivotNode(currentNode->mName))
|
||||
|
||||
@@ -12,17 +12,19 @@
|
||||
|
||||
#include <AzCore/Math/Vector2.h>
|
||||
#include <AzCore/Serialization/SerializeContext.h>
|
||||
#include <AzCore/std/containers/array.h>
|
||||
#include <AzCore/std/numeric.h>
|
||||
#include <AzCore/std/smart_ptr/make_shared.h>
|
||||
#include <AzToolsFramework/Debug/TraceContext.h>
|
||||
#include <SceneAPI/FbxSceneBuilder/ImportContexts/AssImpImportContexts.h>
|
||||
#include <SceneAPI/FbxSceneBuilder/Importers/AssImpUvMapImporter.h>
|
||||
#include <SceneAPI/FbxSceneBuilder/Importers/ImporterUtilities.h>
|
||||
#include <SceneAPI/FbxSceneBuilder/Importers/Utilities/AssImpMeshImporterUtilities.h>
|
||||
#include <SceneAPI/SDKWrapper/AssImpNodeWrapper.h>
|
||||
#include <SceneAPI/SDKWrapper/AssImpSceneWrapper.h>
|
||||
#include <SceneAPI/SceneCore/Utilities/Reporting.h>
|
||||
#include <SceneAPI/SceneData/GraphData/MeshData.h>
|
||||
#include <SceneAPI/SceneData/GraphData/MeshVertexUVData.h>
|
||||
#include <SceneAPI/SceneCore/Utilities/Reporting.h>
|
||||
#include <SceneAPI/SDKWrapper/AssImpNodeWrapper.h>
|
||||
#include <SceneAPI/SDKWrapper/AssImpSceneWrapper.h>
|
||||
|
||||
#include <assimp/scene.h>
|
||||
#include <assimp/mesh.h>
|
||||
@@ -45,7 +47,7 @@ namespace AZ
|
||||
SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context);
|
||||
if (serializeContext)
|
||||
{
|
||||
serializeContext->Class<AssImpUvMapImporter, SceneCore::LoadingComponent>()->Version(3); // LYN-2506
|
||||
serializeContext->Class<AssImpUvMapImporter, SceneCore::LoadingComponent>()->Version(4); // LYN-3250
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,28 +58,53 @@ namespace AZ
|
||||
{
|
||||
return Events::ProcessingResult::Ignored;
|
||||
}
|
||||
aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiNode* currentNode = context.m_sourceNode.GetAssImpNode();
|
||||
const aiScene* scene = context.m_sourceScene.GetAssImpScene();
|
||||
|
||||
GetMeshDataFromParentResult meshDataResult(GetMeshDataFromParent(context));
|
||||
if (!meshDataResult.IsSuccess())
|
||||
// AssImp separates meshes that have multiple materials.
|
||||
// This code re-combines them to match previous FBX SDK behavior,
|
||||
// so they can be separated by engine code instead.
|
||||
bool foundTextureCoordinates = false;
|
||||
AZStd::array<int, AI_MAX_NUMBER_OF_TEXTURECOORDS> meshesPerTextureCoordinateIndex = {};
|
||||
for (int localMeshIndex = 0; localMeshIndex < currentNode->mNumMeshes; ++localMeshIndex)
|
||||
{
|
||||
return meshDataResult.GetError();
|
||||
aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[localMeshIndex]];
|
||||
for (int texCoordIndex = 0; texCoordIndex < meshesPerTextureCoordinateIndex.size(); ++texCoordIndex)
|
||||
{
|
||||
if (!mesh->mTextureCoords[texCoordIndex])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
++meshesPerTextureCoordinateIndex[texCoordIndex];
|
||||
foundTextureCoordinates = true;
|
||||
}
|
||||
}
|
||||
const SceneData::GraphData::MeshData* const parentMeshData(meshDataResult.GetValue());
|
||||
|
||||
size_t vertexCount = parentMeshData->GetVertexCount();
|
||||
if (!foundTextureCoordinates)
|
||||
{
|
||||
return Events::ProcessingResult::Ignored;
|
||||
}
|
||||
|
||||
int sdkMeshIndex = parentMeshData->GetSdkMeshIndex();
|
||||
AZ_Assert(sdkMeshIndex >= 0,
|
||||
"Tried to construct uv stream attribute for invalid or non-mesh parent data, mesh index is missing");
|
||||
const uint64_t vertexCount = GetVertexCountForAllMeshesOnNode(*currentNode, *scene);
|
||||
|
||||
aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
|
||||
for (int texCoordIndex = 0; texCoordIndex < meshesPerTextureCoordinateIndex.size(); ++texCoordIndex)
|
||||
{
|
||||
AZ_Error(
|
||||
Utilities::ErrorWindow,
|
||||
meshesPerTextureCoordinateIndex[texCoordIndex] == 0 ||
|
||||
meshesPerTextureCoordinateIndex[texCoordIndex] == currentNode->mNumMeshes,
|
||||
"Texture coordinate index %d for node %s is not on all meshes on this node. "
|
||||
"Placeholder arbitrary texture values will be generated to allow the data to process, but the source art "
|
||||
"needs to be fixed to correct this. All meshes on this node should have the same number of texture coordinate channels.",
|
||||
texCoordIndex,
|
||||
currentNode->mName.C_Str());
|
||||
}
|
||||
|
||||
Events::ProcessingResultCombiner combinedUvMapResults;
|
||||
for (int texCoordIndex = 0; texCoordIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++texCoordIndex)
|
||||
for (int texCoordIndex = 0; texCoordIndex < meshesPerTextureCoordinateIndex.size(); ++texCoordIndex)
|
||||
{
|
||||
if (!mesh->mTextureCoords[texCoordIndex])
|
||||
// No meshes have this texture coordinate index, skip it.
|
||||
if (meshesPerTextureCoordinateIndex[texCoordIndex] == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -85,24 +112,55 @@ namespace AZ
|
||||
AZStd::shared_ptr<SceneData::GraphData::MeshVertexUVData> uvMap =
|
||||
AZStd::make_shared<AZ::SceneData::GraphData::MeshVertexUVData>();
|
||||
uvMap->ReserveContainerSpace(vertexCount);
|
||||
|
||||
bool customNameFound = false;
|
||||
AZStd::string name(AZStd::string::format("%s%d", m_defaultNodeName, texCoordIndex));
|
||||
if (mesh->mTextureCoordsNames[texCoordIndex].length)
|
||||
for (int sdkMeshIndex = 0; sdkMeshIndex < currentNode->mNumMeshes; ++sdkMeshIndex)
|
||||
{
|
||||
name = mesh->mTextureCoordsNames[texCoordIndex].C_Str();
|
||||
const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[sdkMeshIndex]];
|
||||
if(mesh->mTextureCoords[texCoordIndex])
|
||||
{
|
||||
if (mesh->mTextureCoordsNames[texCoordIndex].length > 0)
|
||||
{
|
||||
if (!customNameFound)
|
||||
{
|
||||
name = mesh->mTextureCoordsNames[texCoordIndex].C_Str();
|
||||
customNameFound = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
AZ_Warning(Utilities::WarningWindow,
|
||||
strcmp(name.c_str(), mesh->mTextureCoordsNames[texCoordIndex].C_Str()) == 0,
|
||||
"Node %s has conflicting mesh coordinate names at index %d, %s and %s. Using %s.",
|
||||
currentNode->mName.C_Str(),
|
||||
texCoordIndex,
|
||||
name.c_str(),
|
||||
mesh->mTextureCoordsNames[texCoordIndex].C_Str(),
|
||||
name.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int v = 0; v < mesh->mNumVertices; ++v)
|
||||
{
|
||||
if (mesh->mTextureCoords[texCoordIndex])
|
||||
{
|
||||
AZ::Vector2 vertexUV(
|
||||
mesh->mTextureCoords[texCoordIndex][v].x,
|
||||
// The engine's V coordinate is reverse of how it's stored in the FBX file.
|
||||
1.0f - mesh->mTextureCoords[texCoordIndex][v].y);
|
||||
uvMap->AppendUV(vertexUV);
|
||||
}
|
||||
else
|
||||
{
|
||||
// An error was already emitted if the UV channels for all meshes on this node do not match.
|
||||
// Append an arbitrary UV value so that the mesh can still be processed.
|
||||
// It's better to let the engine load a partially valid mesh than to completely fail.
|
||||
uvMap->AppendUV(AZ::Vector2::CreateZero());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
uvMap->SetCustomName(name.c_str());
|
||||
|
||||
for (int v = 0; v < mesh->mNumVertices; ++v)
|
||||
{
|
||||
AZ::Vector2 vertexUV(
|
||||
mesh->mTextureCoords[texCoordIndex][v].x,
|
||||
// The engine's V coordinate is reverse of how it's stored in the FBX file.
|
||||
1.0f - mesh->mTextureCoords[texCoordIndex][v].y);
|
||||
uvMap->AppendUV(vertexUV);
|
||||
}
|
||||
|
||||
Containers::SceneGraph::NodeIndex newIndex =
|
||||
context.m_scene.GetGraph().AddChild(context.m_currentGraphPosition, name.c_str());
|
||||
|
||||
@@ -116,6 +174,7 @@ namespace AZ
|
||||
}
|
||||
|
||||
combinedUvMapResults += uvMapResults;
|
||||
|
||||
}
|
||||
|
||||
return combinedUvMapResults.GetResult();
|
||||
|
||||
+24
-12
@@ -13,6 +13,7 @@
|
||||
#include <assimp/mesh.h>
|
||||
#include <assimp/scene.h>
|
||||
#include <AzCore/Casting/numeric_cast.h>
|
||||
#include <AzCore/std/numeric.h>
|
||||
#include <AzCore/std/smart_ptr/make_shared.h>
|
||||
#include <SceneAPI/FbxSceneBuilder/FbxSceneSystem.h>
|
||||
#include <SceneAPI/FbxSceneBuilder/ImportContexts/AssImpImportContexts.h>
|
||||
@@ -24,7 +25,7 @@
|
||||
|
||||
namespace AZ::SceneAPI::FbxSceneBuilder
|
||||
{
|
||||
bool BuildSceneMeshFromAssImpMesh(aiNode* currentNode, const aiScene* scene, const FbxSceneSystem& sceneSystem, AZStd::vector<AZStd::shared_ptr<DataTypes::IGraphObject>>& meshes,
|
||||
bool BuildSceneMeshFromAssImpMesh(const aiNode* currentNode, const aiScene* scene, const FbxSceneSystem& sceneSystem, AZStd::vector<AZStd::shared_ptr<DataTypes::IGraphObject>>& meshes,
|
||||
const AZStd::function<AZStd::shared_ptr<SceneData::GraphData::MeshData>()>& makeMeshFunc)
|
||||
{
|
||||
AZStd::unordered_map<int, int> assImpMatIndexToLYIndex;
|
||||
@@ -34,17 +35,18 @@ namespace AZ::SceneAPI::FbxSceneBuilder
|
||||
{
|
||||
return false;
|
||||
}
|
||||
auto newMesh = makeMeshFunc();
|
||||
|
||||
newMesh->SetUnitSizeInMeters(sceneSystem.GetUnitSizeInMeters());
|
||||
newMesh->SetOriginalUnitSizeInMeters(sceneSystem.GetOriginalUnitSizeInMeters());
|
||||
|
||||
// AssImp separates meshes that have multiple materials.
|
||||
// This code re-combines them to match previous FBX SDK behavior,
|
||||
// so they can be separated by engine code instead.
|
||||
int vertOffset = 0;
|
||||
for (int m = 0; m < currentNode->mNumMeshes; ++m)
|
||||
{
|
||||
auto newMesh = makeMeshFunc();
|
||||
|
||||
newMesh->SetUnitSizeInMeters(sceneSystem.GetUnitSizeInMeters());
|
||||
newMesh->SetOriginalUnitSizeInMeters(sceneSystem.GetOriginalUnitSizeInMeters());
|
||||
|
||||
newMesh->SetSdkMeshIndex(m);
|
||||
|
||||
aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[m]];
|
||||
const aiMesh* mesh = scene->mMeshes[currentNode->mMeshes[m]];
|
||||
|
||||
// Lumberyard materials are created in order based on mesh references in the scene
|
||||
if (assImpMatIndexToLYIndex.find(mesh->mMaterialIndex) == assImpMatIndexToLYIndex.end())
|
||||
@@ -59,7 +61,7 @@ namespace AZ::SceneAPI::FbxSceneBuilder
|
||||
sceneSystem.SwapVec3ForUpAxis(vertex);
|
||||
sceneSystem.ConvertUnit(vertex);
|
||||
newMesh->AddPosition(vertex);
|
||||
newMesh->SetVertexIndexToControlPointIndexMap(vertIdx, vertIdx);
|
||||
newMesh->SetVertexIndexToControlPointIndexMap(vertIdx + vertOffset, vertIdx + vertOffset);
|
||||
|
||||
if (mesh->HasNormals())
|
||||
{
|
||||
@@ -86,14 +88,15 @@ namespace AZ::SceneAPI::FbxSceneBuilder
|
||||
}
|
||||
for (int idx = 0; idx < face.mNumIndices; ++idx)
|
||||
{
|
||||
meshFace.vertexIndex[idx] = face.mIndices[idx];
|
||||
meshFace.vertexIndex[idx] = face.mIndices[idx] + vertOffset;
|
||||
}
|
||||
|
||||
newMesh->AddFace(meshFace, assImpMatIndexToLYIndex[mesh->mMaterialIndex]);
|
||||
}
|
||||
vertOffset += mesh->mNumVertices;
|
||||
|
||||
meshes.push_back(newMesh);
|
||||
}
|
||||
meshes.push_back(newMesh);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -127,4 +130,13 @@ namespace AZ::SceneAPI::FbxSceneBuilder
|
||||
azrtti_cast<const SceneData::GraphData::MeshData* const>(parentData);
|
||||
return AZ::Success(parentMeshData);
|
||||
}
|
||||
|
||||
uint64_t GetVertexCountForAllMeshesOnNode(const aiNode& node, const aiScene& scene)
|
||||
{
|
||||
return AZStd::accumulate(node.mMeshes, node.mMeshes + node.mNumMeshes, uint64_t{ 0u },
|
||||
[&scene](auto runningTotal, unsigned int meshIndex)
|
||||
{
|
||||
return runningTotal + scene.mMeshes[meshIndex]->mNumVertices;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+6
-1
@@ -44,11 +44,16 @@ namespace AZ
|
||||
|
||||
namespace FbxSceneBuilder
|
||||
{
|
||||
bool BuildSceneMeshFromAssImpMesh(aiNode* currentNode, const aiScene* scene, const FbxSceneSystem& sceneSystem, AZStd::vector<AZStd::shared_ptr<DataTypes::IGraphObject>>& meshes,
|
||||
bool BuildSceneMeshFromAssImpMesh(const aiNode* currentNode, const aiScene* scene, const FbxSceneSystem& sceneSystem, AZStd::vector<AZStd::shared_ptr<DataTypes::IGraphObject>>& meshes,
|
||||
const AZStd::function<AZStd::shared_ptr<SceneData::GraphData::MeshData>()>& makeMeshFunc);
|
||||
|
||||
typedef AZ::Outcome<const SceneData::GraphData::MeshData* const, Events::ProcessingResult> GetMeshDataFromParentResult;
|
||||
GetMeshDataFromParentResult GetMeshDataFromParent(AssImpSceneNodeAppendedContext& context);
|
||||
|
||||
// If a node in the original scene file has a mesh with multiple materials on it, the associated AssImp
|
||||
// node will have multiple meshes on it, broken apart per material. This returns the total number
|
||||
// of vertices on all meshes on the given node.
|
||||
uint64_t GetVertexCountForAllMeshesOnNode(const aiNode& node, const aiScene& scene);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ namespace AZ
|
||||
Containers::SceneGraph::NodeIndex parentNode, const char* defaultName)
|
||||
{
|
||||
AZ_TraceContext("Node name", name);
|
||||
const AZStd::string originalNodeName(name);
|
||||
|
||||
bool isNameUpdated = false;
|
||||
// Nodes can't have an empty name, except of the root, otherwise nodes can't be referenced.
|
||||
@@ -56,7 +57,7 @@ namespace AZ
|
||||
// can't reference the same parent in that case. This is to make sure the node can be quickly found as
|
||||
// the full path will be unique. To fix any issues, an index is appended.
|
||||
size_t index = 1;
|
||||
size_t offset = name.length();
|
||||
const size_t offset = name.length();
|
||||
while (graph.Find(parentNode, name).IsValid())
|
||||
{
|
||||
// Remove the previously tried extension.
|
||||
@@ -71,7 +72,8 @@ namespace AZ
|
||||
if (isNameUpdated)
|
||||
{
|
||||
AZ_TraceContext("New node name", name);
|
||||
AZ_TracePrintf(Utilities::WarningWindow, "The name of the node was invalid or conflicting and was updated.");
|
||||
AZ_TracePrintf(Utilities::WarningWindow, "The name of the node '%s' was invalid or conflicting and was updated to '%s'.",
|
||||
originalNodeName.c_str(), name.c_str());
|
||||
}
|
||||
|
||||
return isNameUpdated;
|
||||
|
||||
@@ -38,12 +38,14 @@ namespace AZ
|
||||
{
|
||||
AZ_TracePrintf(SceneAPI::Utilities::LogWindow, "AssImpSceneWrapper::LoadSceneFromFile %s", fileName);
|
||||
AZ_TraceContext("Filename", fileName);
|
||||
// aiProcess_JoinIdenticalVertices is not enabled because O3DE has a mesh optimizer that also does this,
|
||||
// this flag is disabled to keep AssImp output similar to FBX SDK to reduce downstream bugs for the initial AssImp release.
|
||||
// There's currently a minimum of properties and flags set to maximize compatibility with the existing node graph.
|
||||
m_importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, false);
|
||||
m_importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_OPTIMIZE_EMPTY_ANIMATION_CURVES, false);
|
||||
m_sceneFileName = fileName;
|
||||
m_assImpScene = m_importer.ReadFile(fileName,
|
||||
aiProcess_Triangulate //Triangulates all faces of all meshes
|
||||
| aiProcess_JoinIdenticalVertices //Identifies and joins identical vertex data sets for the imported meshes
|
||||
| aiProcess_LimitBoneWeights //Limits the number of bones that can affect a vertex to a maximum value
|
||||
//dropping the least important and re-normalizing
|
||||
| aiProcess_GenNormals); //Generate normals for meshes
|
||||
|
||||
@@ -19,6 +19,16 @@ namespace AZ::SceneAPI::Utilities
|
||||
m_output += AZStd::string::format("\t%s: %s\n", name, data);
|
||||
}
|
||||
|
||||
void DebugOutput::WriteArray(const char* name, const unsigned int* data, int size)
|
||||
{
|
||||
m_output += AZStd::string::format("\t%s: ", name);
|
||||
for (int index = 0; index < size; ++index)
|
||||
{
|
||||
m_output += AZStd::string::format("%d, ", data[index]);
|
||||
}
|
||||
m_output += AZStd::string::format("\n");
|
||||
}
|
||||
|
||||
void DebugOutput::Write(const char* name, const AZStd::string& data)
|
||||
{
|
||||
Write(name, data.c_str());
|
||||
|
||||
@@ -29,6 +29,7 @@ namespace AZ::SceneAPI::Utilities
|
||||
void Write(const char* name, const AZStd::vector<AZStd::vector<T>>& data);
|
||||
|
||||
SCENE_CORE_API void Write(const char* name, const char* data);
|
||||
SCENE_CORE_API void WriteArray(const char* name, const unsigned int* data, int size);
|
||||
SCENE_CORE_API void Write(const char* name, const AZStd::string& data);
|
||||
SCENE_CORE_API void Write(const char* name, double data);
|
||||
SCENE_CORE_API void Write(const char* name, uint64_t data);
|
||||
|
||||
@@ -285,8 +285,26 @@ namespace AZ
|
||||
void BlendShapeData::GetDebugOutput(SceneAPI::Utilities::DebugOutput& output) const
|
||||
{
|
||||
output.Write("Positions", m_positions);
|
||||
int index = 0;
|
||||
for (const auto& position : m_positions)
|
||||
{
|
||||
output.Write(AZStd::string::format("\t%d", index).c_str(), position);
|
||||
++index;
|
||||
}
|
||||
index = 0;
|
||||
output.Write("Normals", m_normals);
|
||||
for (const auto& normal : m_normals)
|
||||
{
|
||||
output.Write(AZStd::string::format("\t%d", index).c_str(), normal);
|
||||
++index;
|
||||
}
|
||||
index = 0;
|
||||
output.Write("Faces", m_faces);
|
||||
for (const auto& face : m_faces)
|
||||
{
|
||||
output.WriteArray(AZStd::string::format("\t%d", index).c_str(), face.vertexIndex, 3);
|
||||
++index;
|
||||
}
|
||||
}
|
||||
} // GraphData
|
||||
} // SceneData
|
||||
|
||||
@@ -45,7 +45,6 @@ namespace AZ
|
||||
behaviorContext->Class<MeshData>()
|
||||
->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common)
|
||||
->Attribute(AZ::Script::Attributes::Module, "scene")
|
||||
->Method("GetSdkMeshIndex", &MeshData::GetSdkMeshIndex)
|
||||
->Method("GetControlPointIndex", &MeshData::GetControlPointIndex)
|
||||
->Method("GetUsedControlPointCount", &MeshData::GetUsedControlPointCount)
|
||||
->Method("GetUsedPointIndexForControlPoint", &MeshData::GetUsedPointIndexForControlPoint)
|
||||
@@ -77,10 +76,6 @@ namespace AZ
|
||||
void MeshData::CloneAttributesFrom(const IGraphObject* sourceObject)
|
||||
{
|
||||
IMeshData::CloneAttributesFrom(sourceObject);
|
||||
if (const auto* typedSource = azrtti_cast<const MeshData*>(sourceObject))
|
||||
{
|
||||
SetSdkMeshIndex(typedSource->GetSdkMeshIndex());
|
||||
}
|
||||
}
|
||||
|
||||
void MeshData::AddPosition(const AZ::Vector3& position)
|
||||
@@ -111,15 +106,6 @@ namespace AZ
|
||||
m_faceMaterialIds.push_back(faceMaterialId);
|
||||
}
|
||||
|
||||
void MeshData::SetSdkMeshIndex(int sdkMeshIndex)
|
||||
{
|
||||
m_sdkMeshIndex = sdkMeshIndex;
|
||||
}
|
||||
int MeshData::GetSdkMeshIndex() const
|
||||
{
|
||||
return m_sdkMeshIndex;
|
||||
}
|
||||
|
||||
void MeshData::SetVertexIndexToControlPointIndexMap(int vertexIndex, int controlPointIndex)
|
||||
{
|
||||
m_vertexIndexToControlPointIndexMap[vertexIndex] = controlPointIndex;
|
||||
@@ -206,8 +192,26 @@ namespace AZ
|
||||
void MeshData::GetDebugOutput(SceneAPI::Utilities::DebugOutput& output) const
|
||||
{
|
||||
output.Write("Positions", m_positions);
|
||||
int index = 0;
|
||||
for (const auto& position : m_positions)
|
||||
{
|
||||
output.Write(AZStd::string::format("\t%d", index).c_str(), position);
|
||||
++index;
|
||||
}
|
||||
index = 0;
|
||||
output.Write("Normals", m_normals);
|
||||
for (const auto& normal : m_normals)
|
||||
{
|
||||
output.Write(AZStd::string::format("\t%d", index).c_str(), normal);
|
||||
++index;
|
||||
}
|
||||
index = 0;
|
||||
output.Write("FaceList", m_faceList);
|
||||
for (const auto& face : m_faceList)
|
||||
{
|
||||
output.WriteArray(AZStd::string::format("\t%d", index).c_str(), face.vertexIndex, 3);
|
||||
++index;
|
||||
}
|
||||
output.Write("FaceMaterialIds", m_faceMaterialIds);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,9 +49,6 @@ namespace AZ
|
||||
SCENE_DATA_API void AddFace(const AZ::SceneAPI::DataTypes::IMeshData::Face& face,
|
||||
unsigned int faceMaterialId = AZ::SceneAPI::DataTypes::IMeshData::s_invalidMaterialId);
|
||||
|
||||
SCENE_DATA_API void SetSdkMeshIndex(int sdkMeshIndex);
|
||||
SCENE_DATA_API int GetSdkMeshIndex() const;
|
||||
|
||||
SCENE_DATA_API void SetVertexIndexToControlPointIndexMap(int vertexIndex, int controlPointIndex);
|
||||
SCENE_DATA_API size_t GetUsedControlPointCount() const override;
|
||||
SCENE_DATA_API int GetControlPointIndex(int vertexIndex) const override;
|
||||
@@ -80,8 +77,6 @@ namespace AZ
|
||||
|
||||
AZStd::unordered_map<int, int> m_vertexIndexToControlPointIndexMap;
|
||||
AZStd::unordered_map<int, int> m_controlPointToUsedVertexIndexMap;
|
||||
|
||||
int m_sdkMeshIndex = -1;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +57,6 @@ namespace AZ
|
||||
meshData->AddNormal(Vector3{0.1f, 0.2f, 0.3f});
|
||||
meshData->AddNormal(Vector3{0.4f, 0.5f, 0.6f});
|
||||
meshData->SetOriginalUnitSizeInMeters(10.0f);
|
||||
meshData->SetSdkMeshIndex(1337);
|
||||
meshData->SetUnitSizeInMeters(0.5f);
|
||||
meshData->SetVertexIndexToControlPointIndexMap(0, 10);
|
||||
meshData->SetVertexIndexToControlPointIndexMap(1, 11);
|
||||
@@ -252,7 +251,6 @@ namespace AZ
|
||||
ExpectExecute("TestExpectFloatEquals(meshData:GetNormal(1).z, 0.6)");
|
||||
ExpectExecute("TestExpectFloatEquals(meshData:GetOriginalUnitSizeInMeters(), 10.0)");
|
||||
ExpectExecute("TestExpectFloatEquals(meshData:GetUnitSizeInMeters(), 0.5)");
|
||||
ExpectExecute("TestExpectIntegerEquals(meshData:GetSdkMeshIndex(), 1337)");
|
||||
ExpectExecute("TestExpectIntegerEquals(meshData:GetUsedControlPointCount(), 4)");
|
||||
ExpectExecute("TestExpectIntegerEquals(meshData:GetControlPointIndex(0), 10)");
|
||||
ExpectExecute("TestExpectIntegerEquals(meshData:GetControlPointIndex(1), 11)");
|
||||
|
||||
Reference in New Issue
Block a user