Files
o3de/Gems/LmbrCentral/Code/Source/Shape/BoxShape.cpp
T
Esteban Papp 1f9b284de2 Merge branch 'development' into cmake/SPEC-7179
Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>

# Conflicts:
#	Code/Editor/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin_precompiled.h
#	Code/Editor/Plugins/EditorCommon/EditorCommon_precompiled.h
#	Code/Editor/Plugins/EditorCommon/stdafx.cpp
#	Code/Editor/Plugins/FFMPEGPlugin/FFMPEGPlugin_precompiled.h
#	Code/Editor/Plugins/PerforcePlugin/PerforcePlugin_precompiled.h
#	Code/Editor/Plugins/ProjectSettingsTool/ProjectSettingsTool_precompiled.h
#	Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFramework_precompiled.h
#	Code/Tools/AssetProcessor/native/precompiled.h
#	Code/Tools/Standalone/StandaloneTools_precompiled.h
#	Gems/AssetMemoryAnalyzer/Code/Source/AssetMemoryAnalyzer_precompiled.h
#	Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessing_precompiled.h
#	Gems/Atom/RHI/DX12/Code/Source/RHI/Atom_RHI_DX12_precompiled.h
#	Gems/Atom/RHI/Metal/Code/Include/Platform/Mac/Atom_RHI_Metal_precompiled_Platform.h
#	Gems/Atom/RHI/Metal/Code/Include/Platform/iOS/Atom_RHI_Metal_precompiled_Platform.h
#	Gems/Atom/RHI/Metal/Code/Source/Atom_RHI_Metal_precompiled.h
#	Gems/Atom/RHI/Metal/Code/atom_rhi_metal_common_files.cmake
#	Gems/Atom/RHI/Null/Code/Source/Atom_RHI_Null_precompiled.h
#	Gems/Atom/RHI/Null/Code/atom_rhi_null_common_files.cmake
#	Gems/Atom/RHI/Vulkan/Code/Include/Platform/Android/Atom_RHI_Vulkan_precompiled_Platform.h
#	Gems/Atom/RHI/Vulkan/Code/Include/Platform/Linux/Atom_RHI_Vulkan_precompiled_Platform.h
#	Gems/Atom/RHI/Vulkan/Code/Include/Platform/Mac/Atom_RHI_Vulkan_precompiled_Platform.h
#	Gems/Atom/RHI/Vulkan/Code/Include/Platform/Windows/Atom_RHI_Vulkan_precompiled_Platform.h
#	Gems/Atom/RHI/Vulkan/Code/Source/Atom_RHI_Vulkan_precompiled.h
#	Gems/Atom/RHI/Vulkan/Code/Source/RHI/SwapChain.cpp
#	Gems/Atom/RHI/Vulkan/Code/atom_rhi_vulkan_common_files.cmake
#	Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/AtomFont_precompiled.h
#	Gems/Blast/Code/Source/StdAfx.cpp
#	Gems/Camera/Code/Source/Camera_precompiled.h
#	Gems/EMotionFX/Code/Source/EMotionFX_precompiled.h
#	Gems/FastNoise/Code/Source/FastNoise_precompiled.h
#	Gems/Gestures/Code/Source/Gestures_precompiled.h
#	Gems/GradientSignal/Code/Source/GradientSignal_precompiled.h
#	Gems/GraphCanvas/Code/precompiled.h
#	Gems/ImGui/Code/Source/ImGui_precompiled.h
#	Gems/InAppPurchases/Code/Source/InAppPurchases_precompiled.h
#	Gems/LmbrCentral/Code/Source/LmbrCentral_precompiled.h
#	Gems/LmbrCentral/Code/Tests/ShapeGeometryUtilTest.cpp
#	Gems/LyShine/Code/Editor/UiCanvasEditor_precompiled.h
#	Gems/LyShine/Code/Source/Animation/LyShine_precompiled.h
#	Gems/LyShine/Code/Source/LyShine_precompiled.h
#	Gems/LyShineExamples/Code/Source/LyShineExamples_precompiled.h
#	Gems/Maestro/Code/Source/Cinematics/Maestro_precompiled.h
#	Gems/Maestro/Code/Source/Maestro_precompiled.h
#	Gems/MessagePopup/Code/Source/MessagePopup_precompiled.h
#	Gems/Metastream/Code/Source/Metastream_precompiled.h
#	Gems/Microphone/Code/Source/Microphone_precompiled.h
#	Gems/Multiplayer/Code/Source/Multiplayer_precompiled.h
#	Gems/PhysX/Code/NumericalMethods/Source/NumericalMethods_precompiled.h
#	Gems/PhysX/Code/Source/PhysXUnsupported_precompiled.h
#	Gems/PhysX/Code/Source/PhysX_precompiled.h
#	Gems/PhysX/Code/physx_unsupported_files.cmake
#	Gems/PhysXDebug/Code/Source/PhysXDebugUnsupported_precompiled.h
#	Gems/PhysXDebug/Code/Source/PhysXDebug_precompiled.h
#	Gems/ScriptCanvas/Code/Editor/precompiled.h
#	Gems/ScriptCanvas/Code/Source/precompiled.h
#	Gems/ScriptCanvasDeveloper/Code/Source/precompiled.h
#	Gems/ScriptCanvasPhysics/Code/Source/ScriptCanvasPhysics_precompiled.h
#	Gems/ScriptEvents/Code/Source/precompiled.h
#	Gems/ScriptEvents/Code/Tests/Editor/EditorTests.cpp
#	Gems/ScriptedEntityTweener/Code/Source/ScriptedEntityTweener_precompiled.h
#	Gems/SliceFavorites/Code/Source/SliceFavorites_precompiled.h
#	Gems/StartingPointCamera/Code/Source/StartingPointCamera_precompiled.h
#	Gems/StartingPointInput/Code/Source/StartingPointInput_precompiled.h
#	Gems/StartingPointMovement/Code/Source/StartingPointMovement_precompiled.h
#	Gems/SurfaceData/Code/Source/SurfaceData_precompiled.h
#	Gems/TextureAtlas/Code/Source/TextureAtlas_precompiled.h
#	Gems/TickBusOrderViewer/Code/Source/TickBusOrderViewer_precompiled.h
#	Gems/Twitch/Code/Source/Twitch_precompiled.h
#	Gems/VirtualGamepad/Code/Source/VirtualGamepad_precompiled.h
#	Gems/WhiteBox/Code/Source/WhiteBoxUnsupported_precompiled.h
#	Gems/WhiteBox/Code/Source/WhiteBox_precompiled.h
2021-07-16 15:42:37 -07:00

298 lines
12 KiB
C++

/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "BoxShape.h"
#include <AzCore/Math/Color.h>
#include <AzCore/Math/IntersectSegment.h>
#include <AzCore/Math/Transform.h>
#include <AzCore/Math/Matrix3x3.h>
#include <AzCore/Math/Random.h>
#include <AzCore/Math/Sfmt.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/std/algorithm.h>
#include <AzCore/std/containers/array.h>
#include <AzFramework/Entity/EntityDebugDisplayBus.h>
#include <Shape/ShapeDisplay.h>
#include <random>
namespace LmbrCentral
{
BoxShape::BoxShape()
: m_nonUniformScaleChangedHandler([this](const AZ::Vector3& scale) {this->OnNonUniformScaleChanged(scale); })
{
}
void BoxShape::Reflect(AZ::ReflectContext* context)
{
BoxShapeConfig::Reflect(context);
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<BoxShape>()
->Version(1)
->Field("Configuration", &BoxShape::m_boxShapeConfig)
;
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<BoxShape>("Box Shape", "Box shape configuration parameters")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->DataElement(AZ::Edit::UIHandlers::Default, &BoxShape::m_boxShapeConfig, "Box Configuration", "Box shape configuration")
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
;
}
}
}
void BoxShape::Activate(AZ::EntityId entityId)
{
m_entityId = entityId;
m_currentTransform = AZ::Transform::CreateIdentity();
AZ::TransformBus::EventResult(m_currentTransform, m_entityId, &AZ::TransformBus::Events::GetWorldTM);
m_currentNonUniformScale = AZ::Vector3::CreateOne();
AZ::NonUniformScaleRequestBus::EventResult(m_currentNonUniformScale, m_entityId, &AZ::NonUniformScaleRequests::GetScale);
m_intersectionDataCache.InvalidateCache(InvalidateShapeCacheReason::ShapeChange);
AZ::TransformNotificationBus::Handler::BusConnect(m_entityId);
ShapeComponentRequestsBus::Handler::BusConnect(m_entityId);
BoxShapeComponentRequestsBus::Handler::BusConnect(m_entityId);
AZ::NonUniformScaleRequestBus::Event(m_entityId, &AZ::NonUniformScaleRequests::RegisterScaleChangedEvent,
m_nonUniformScaleChangedHandler);
}
void BoxShape::Deactivate()
{
m_nonUniformScaleChangedHandler.Disconnect();
BoxShapeComponentRequestsBus::Handler::BusDisconnect();
ShapeComponentRequestsBus::Handler::BusDisconnect();
AZ::TransformNotificationBus::Handler::BusDisconnect();
}
void BoxShape::InvalidateCache(InvalidateShapeCacheReason reason)
{
m_intersectionDataCache.InvalidateCache(reason);
}
void BoxShape::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world)
{
m_currentTransform = world;
m_intersectionDataCache.InvalidateCache(InvalidateShapeCacheReason::TransformChange);
ShapeComponentNotificationsBus::Event(
m_entityId, &ShapeComponentNotificationsBus::Events::OnShapeChanged,
ShapeComponentNotifications::ShapeChangeReasons::TransformChanged);
}
void BoxShape::OnNonUniformScaleChanged(const AZ::Vector3& scale)
{
m_currentNonUniformScale = scale;
m_intersectionDataCache.InvalidateCache(InvalidateShapeCacheReason::ShapeChange);
ShapeComponentNotificationsBus::Event(
m_entityId, &ShapeComponentNotificationsBus::Events::OnShapeChanged,
ShapeComponentNotifications::ShapeChangeReasons::ShapeChanged);
}
void BoxShape::SetBoxDimensions(const AZ::Vector3& dimensions)
{
m_boxShapeConfig.m_dimensions = dimensions;
m_intersectionDataCache.InvalidateCache(InvalidateShapeCacheReason::ShapeChange);
ShapeComponentNotificationsBus::Event(
m_entityId, &ShapeComponentNotificationsBus::Events::OnShapeChanged,
ShapeComponentNotifications::ShapeChangeReasons::ShapeChanged);
}
AZ::Aabb BoxShape::GetEncompassingAabb()
{
m_intersectionDataCache.UpdateIntersectionParams(m_currentTransform, m_boxShapeConfig, m_currentNonUniformScale);
return m_intersectionDataCache.m_aabb;
}
void BoxShape::GetTransformAndLocalBounds(AZ::Transform& transform, AZ::Aabb& bounds)
{
const AZ::Vector3 extent(m_boxShapeConfig.m_dimensions * m_currentNonUniformScale * 0.5f);
bounds = AZ::Aabb::CreateFromMinMax(-extent, extent);
transform = m_currentTransform;
}
bool BoxShape::IsPointInside(const AZ::Vector3& point)
{
m_intersectionDataCache.UpdateIntersectionParams(m_currentTransform, m_boxShapeConfig, m_currentNonUniformScale);
if (m_intersectionDataCache.m_axisAligned)
{
return m_intersectionDataCache.m_aabb.Contains(point);
}
return m_intersectionDataCache.m_obb.Contains(point);
}
float BoxShape::DistanceSquaredFromPoint(const AZ::Vector3& point)
{
m_intersectionDataCache.UpdateIntersectionParams(m_currentTransform, m_boxShapeConfig, m_currentNonUniformScale);
if (m_intersectionDataCache.m_axisAligned)
{
return m_intersectionDataCache.m_aabb.GetDistanceSq(point);
}
return m_intersectionDataCache.m_obb.GetDistanceSq(point);
}
bool BoxShape::IntersectRay(const AZ::Vector3& src, const AZ::Vector3& dir, float& distance)
{
m_intersectionDataCache.UpdateIntersectionParams(m_currentTransform, m_boxShapeConfig, m_currentNonUniformScale);
if (m_intersectionDataCache.m_axisAligned)
{
const float rayLength = 1000.0f;
AZ::Vector3 scaledDir = dir * rayLength;
AZ::Vector3 startNormal;
float end;
float t;
const bool intersection = AZ::Intersect::IntersectRayAABB(
src, scaledDir, scaledDir.GetReciprocal(),
m_intersectionDataCache.m_aabb, t, end, startNormal) > 0;
distance = rayLength * t;
return intersection;
}
const bool intersection = AZ::Intersect::IntersectRayObb(src, dir, m_intersectionDataCache.m_obb, distance) > 0;
return intersection;
}
AZ::Vector3 BoxShape::GenerateRandomPointInside(AZ::RandomDistributionType randomDistribution)
{
m_intersectionDataCache.UpdateIntersectionParams(m_currentTransform, m_boxShapeConfig, m_currentNonUniformScale);
float x = 0;
float y = 0;
float z = 0;
// Points should be generated just inside the shape boundary
constexpr float insideMargin = 0.999f;
AZ::Vector3 boxMin = m_intersectionDataCache.m_scaledDimensions * -0.5f * insideMargin;
AZ::Vector3 boxMax = m_intersectionDataCache.m_scaledDimensions * 0.5f * insideMargin;
// As std:normal_distribution requires a std:random_engine to be passed in,
// As std:normal_distribution requires a std:random_engine to be passed in, create one using a random seed that is guaranteed to be properly
// random each time it is called
time_t seedVal;
seedVal = AZ::Sfmt::GetInstance().Rand64();
std::default_random_engine generator;
generator.seed(static_cast<unsigned int>(seedVal));
switch(randomDistribution)
{
case AZ::RandomDistributionType::Normal:
{
const float mean = 0.0f; //Mean will always be 0
//stdDev will be the sqrt of the max value (which is the total variation)
float stdDev = sqrtf(boxMax.GetX());
std::normal_distribution<float> normalDist =
std::normal_distribution<float>(mean, stdDev);
x = normalDist(generator);
//Normal distributions can sometimes produce values outside of our desired range
//We just need to clamp
x = AZStd::clamp<float>(x, boxMin.GetX(), boxMax.GetX());
stdDev = sqrtf(boxMax.GetY());
normalDist = std::normal_distribution<float>(mean, stdDev);
y = normalDist(generator);
y = AZStd::clamp<float>(y, boxMin.GetY(), boxMax.GetY());
stdDev = sqrtf(boxMax.GetZ());
normalDist = std::normal_distribution<float>(mean, stdDev);
z = normalDist(generator);
z = AZStd::clamp<float>(z, boxMin.GetZ(), boxMax.GetZ());
}
break;
case AZ::RandomDistributionType::UniformReal:
{
std::uniform_real_distribution<float> uniformRealDist =
std::uniform_real_distribution<float>(boxMin.GetX(), boxMax.GetX());
x = uniformRealDist(generator);
uniformRealDist = std::uniform_real_distribution<float>(boxMin.GetY(), boxMax.GetY());
y = uniformRealDist(generator);
uniformRealDist = std::uniform_real_distribution<float>(boxMin.GetZ(), boxMax.GetZ());
z = uniformRealDist(generator);
}
break;
default:
AZ_Warning("BoxShape", false, "Unsupported random distribution type. Returning default vector (0,0,0)");
break;
}
// transform to world space
return m_currentTransform.TransformPoint(AZ::Vector3(x, y, z));
}
void BoxShape::BoxIntersectionDataCache::UpdateIntersectionParamsImpl(
const AZ::Transform& currentTransform, const BoxShapeConfig& configuration, const AZ::Vector3& currentNonUniformScale)
{
AZ::Transform worldFromLocalNormalized = currentTransform;
const float entityScale = worldFromLocalNormalized.ExtractUniformScale();
m_currentPosition = worldFromLocalNormalized.GetTranslation();
m_scaledDimensions = configuration.m_dimensions * currentNonUniformScale * entityScale;
AZ::Quaternion worldFromLocalQuaternion = worldFromLocalNormalized.GetRotation();
if (worldFromLocalQuaternion.IsClose(AZ::Quaternion::CreateIdentity()))
{
AZ::Vector3 boxMin = m_scaledDimensions * -0.5f;
boxMin = worldFromLocalNormalized.TransformPoint(boxMin);
AZ::Vector3 boxMax = m_scaledDimensions * 0.5f;
boxMax = worldFromLocalNormalized.TransformPoint(boxMax);
m_aabb = AZ::Aabb::CreateFromMinMax(boxMin, boxMax);
m_obb = AZ::Obb::CreateFromAabb(m_aabb);
m_axisAligned = true;
}
else
{
const AZ::Vector3 halfLengthVector = m_scaledDimensions * 0.5f;
m_obb = AZ::Obb::CreateFromPositionRotationAndHalfLengths(
m_currentPosition,
worldFromLocalNormalized.GetRotation(),
halfLengthVector);
m_aabb = AZ::Aabb::CreateFromObb(m_obb);
m_axisAligned = false;
}
}
void DrawBoxShape(
const ShapeDrawParams& shapeDrawParams, const BoxShapeConfig& boxShapeConfig,
AzFramework::DebugDisplayRequests& debugDisplay, const AZ::Vector3& nonUniformScale)
{
const AZ::Vector3 boxMin = boxShapeConfig.m_dimensions * nonUniformScale * -0.5f;
const AZ::Vector3 boxMax = boxShapeConfig.m_dimensions * nonUniformScale * 0.5f;
if (shapeDrawParams.m_filled)
{
debugDisplay.SetColor(shapeDrawParams.m_shapeColor.GetAsVector4());
debugDisplay.DrawSolidBox(boxMin, boxMax);
}
debugDisplay.SetColor(shapeDrawParams.m_wireColor.GetAsVector4());
debugDisplay.DrawWireBox(boxMin, boxMax);
}
} // namespace LmbrCentral