Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/BoxShape.cpp
9913 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#include <Jolt/Jolt.h>56#include <Jolt/Physics/Collision/Shape/BoxShape.h>7#include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>8#include <Jolt/Physics/Collision/Shape/GetTrianglesContext.h>9#include <Jolt/Physics/Collision/RayCast.h>10#include <Jolt/Physics/Collision/CastResult.h>11#include <Jolt/Physics/Collision/CollidePointResult.h>12#include <Jolt/Physics/Collision/TransformedShape.h>13#include <Jolt/Physics/Collision/CollideSoftBodyVertexIterator.h>14#include <Jolt/Geometry/RayAABox.h>15#include <Jolt/ObjectStream/TypeDeclarations.h>16#include <Jolt/Core/StreamIn.h>17#include <Jolt/Core/StreamOut.h>18#ifdef JPH_DEBUG_RENDERER19#include <Jolt/Renderer/DebugRenderer.h>20#endif // JPH_DEBUG_RENDERER2122JPH_NAMESPACE_BEGIN2324JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(BoxShapeSettings)25{26JPH_ADD_BASE_CLASS(BoxShapeSettings, ConvexShapeSettings)2728JPH_ADD_ATTRIBUTE(BoxShapeSettings, mHalfExtent)29JPH_ADD_ATTRIBUTE(BoxShapeSettings, mConvexRadius)30}3132static const Vec3 sUnitBoxTriangles[] = {33Vec3(-1, 1, -1), Vec3(-1, 1, 1), Vec3(1, 1, 1),34Vec3(-1, 1, -1), Vec3(1, 1, 1), Vec3(1, 1, -1),35Vec3(-1, -1, -1), Vec3(1, -1, -1), Vec3(1, -1, 1),36Vec3(-1, -1, -1), Vec3(1, -1, 1), Vec3(-1, -1, 1),37Vec3(-1, 1, -1), Vec3(-1, -1, -1), Vec3(-1, -1, 1),38Vec3(-1, 1, -1), Vec3(-1, -1, 1), Vec3(-1, 1, 1),39Vec3(1, 1, 1), Vec3(1, -1, 1), Vec3(1, -1, -1),40Vec3(1, 1, 1), Vec3(1, -1, -1), Vec3(1, 1, -1),41Vec3(-1, 1, 1), Vec3(-1, -1, 1), Vec3(1, -1, 1),42Vec3(-1, 1, 1), Vec3(1, -1, 1), Vec3(1, 1, 1),43Vec3(-1, 1, -1), Vec3(1, 1, -1), Vec3(1, -1, -1),44Vec3(-1, 1, -1), Vec3(1, -1, -1), Vec3(-1, -1, -1)45};4647ShapeSettings::ShapeResult BoxShapeSettings::Create() const48{49if (mCachedResult.IsEmpty())50Ref<Shape> shape = new BoxShape(*this, mCachedResult);51return mCachedResult;52}5354BoxShape::BoxShape(const BoxShapeSettings &inSettings, ShapeResult &outResult) :55ConvexShape(EShapeSubType::Box, inSettings, outResult),56mHalfExtent(inSettings.mHalfExtent),57mConvexRadius(inSettings.mConvexRadius)58{59// Check convex radius60if (inSettings.mConvexRadius < 0.0f61|| inSettings.mHalfExtent.ReduceMin() < inSettings.mConvexRadius)62{63outResult.SetError("Invalid convex radius");64return;65}6667// Result is valid68outResult.Set(this);69}7071class BoxShape::Box final : public Support72{73public:74Box(const AABox &inBox, float inConvexRadius) :75mBox(inBox),76mConvexRadius(inConvexRadius)77{78static_assert(sizeof(Box) <= sizeof(SupportBuffer), "Buffer size too small");79JPH_ASSERT(IsAligned(this, alignof(Box)));80}8182virtual Vec3 GetSupport(Vec3Arg inDirection) const override83{84return mBox.GetSupport(inDirection);85}8687virtual float GetConvexRadius() const override88{89return mConvexRadius;90}9192private:93AABox mBox;94float mConvexRadius;95};9697const ConvexShape::Support *BoxShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const98{99// Scale our half extents100Vec3 scaled_half_extent = inScale.Abs() * mHalfExtent;101102switch (inMode)103{104case ESupportMode::IncludeConvexRadius:105case ESupportMode::Default:106{107// Make box out of our half extents108AABox box = AABox(-scaled_half_extent, scaled_half_extent);109JPH_ASSERT(box.IsValid());110return new (&inBuffer) Box(box, 0.0f);111}112113case ESupportMode::ExcludeConvexRadius:114{115// Reduce the box by our convex radius116float convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale);117Vec3 convex_radius3 = Vec3::sReplicate(convex_radius);118Vec3 reduced_half_extent = scaled_half_extent - convex_radius3;119AABox box = AABox(-reduced_half_extent, reduced_half_extent);120JPH_ASSERT(box.IsValid());121return new (&inBuffer) Box(box, convex_radius);122}123}124125JPH_ASSERT(false);126return nullptr;127}128129void BoxShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const130{131JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");132133Vec3 scaled_half_extent = inScale.Abs() * mHalfExtent;134AABox box(-scaled_half_extent, scaled_half_extent);135box.GetSupportingFace(inDirection, outVertices);136137// Transform to world space138for (Vec3 &v : outVertices)139v = inCenterOfMassTransform * v;140}141142MassProperties BoxShape::GetMassProperties() const143{144MassProperties p;145p.SetMassAndInertiaOfSolidBox(2.0f * mHalfExtent, GetDensity());146return p;147}148149Vec3 BoxShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const150{151JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");152153// Get component that is closest to the surface of the box154int index = (inLocalSurfacePosition.Abs() - mHalfExtent).Abs().GetLowestComponentIndex();155156// Calculate normal157Vec3 normal = Vec3::sZero();158normal.SetComponent(index, inLocalSurfacePosition[index] > 0.0f? 1.0f : -1.0f);159return normal;160}161162#ifdef JPH_DEBUG_RENDERER163void BoxShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const164{165DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;166inRenderer->DrawBox(inCenterOfMassTransform * Mat44::sScale(inScale.Abs()), GetLocalBounds(), inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);167}168#endif // JPH_DEBUG_RENDERER169170bool BoxShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const171{172// Test hit against box173float fraction = max(RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent), 0.0f);174if (fraction < ioHit.mFraction)175{176ioHit.mFraction = fraction;177ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();178return true;179}180return false;181}182183void BoxShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const184{185// Test shape filter186if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))187return;188189float min_fraction, max_fraction;190RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent, min_fraction, max_fraction);191if (min_fraction <= max_fraction // Ray should intersect192&& max_fraction >= 0.0f // End of ray should be inside box193&& min_fraction < ioCollector.GetEarlyOutFraction()) // Start of ray should be before early out fraction194{195// Better hit than the current hit196RayCastResult hit;197hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());198hit.mSubShapeID2 = inSubShapeIDCreator.GetID();199200// Check front side201if (inRayCastSettings.mTreatConvexAsSolid || min_fraction > 0.0f)202{203hit.mFraction = max(0.0f, min_fraction);204ioCollector.AddHit(hit);205}206207// Check back side hit208if (inRayCastSettings.mBackFaceModeConvex == EBackFaceMode::CollideWithBackFaces209&& max_fraction < ioCollector.GetEarlyOutFraction())210{211hit.mFraction = max_fraction;212ioCollector.AddHit(hit);213}214}215}216217void BoxShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const218{219// Test shape filter220if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))221return;222223if (Vec3::sLessOrEqual(inPoint.Abs(), mHalfExtent).TestAllXYZTrue())224ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });225}226227void BoxShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const228{229Mat44 inverse_transform = inCenterOfMassTransform.InversedRotationTranslation();230Vec3 half_extent = inScale.Abs() * mHalfExtent;231232for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v)233if (v.GetInvMass() > 0.0f)234{235// Convert to local space236Vec3 local_pos = inverse_transform * v.GetPosition();237238// Clamp point to inside box239Vec3 clamped_point = Vec3::sMax(Vec3::sMin(local_pos, half_extent), -half_extent);240241// Test if point was inside242if (clamped_point == local_pos)243{244// Calculate closest distance to surface245Vec3 delta = half_extent - local_pos.Abs();246int index = delta.GetLowestComponentIndex();247float penetration = delta[index];248if (v.UpdatePenetration(penetration))249{250// Calculate contact point and normal251Vec3 possible_normals[] = { Vec3::sAxisX(), Vec3::sAxisY(), Vec3::sAxisZ() };252Vec3 normal = local_pos.GetSign() * possible_normals[index];253Vec3 point = normal * half_extent;254255// Store collision256v.SetCollision(Plane::sFromPointAndNormal(point, normal).GetTransformed(inCenterOfMassTransform), inCollidingShapeIndex);257}258}259else260{261// Calculate normal262Vec3 normal = local_pos - clamped_point;263float normal_length = normal.Length();264265// Penetration will be negative since we're not penetrating266float penetration = -normal_length;267if (v.UpdatePenetration(penetration))268{269normal /= normal_length;270271// Store collision272v.SetCollision(Plane::sFromPointAndNormal(clamped_point, normal).GetTransformed(inCenterOfMassTransform), inCollidingShapeIndex);273}274}275}276}277278void BoxShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const279{280new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, inScale, Mat44::sScale(mHalfExtent), sUnitBoxTriangles, std::size(sUnitBoxTriangles), GetMaterial());281}282283int BoxShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const284{285return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);286}287288void BoxShape::SaveBinaryState(StreamOut &inStream) const289{290ConvexShape::SaveBinaryState(inStream);291292inStream.Write(mHalfExtent);293inStream.Write(mConvexRadius);294}295296void BoxShape::RestoreBinaryState(StreamIn &inStream)297{298ConvexShape::RestoreBinaryState(inStream);299300inStream.Read(mHalfExtent);301inStream.Read(mConvexRadius);302}303304void BoxShape::sRegister()305{306ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Box);307f.mConstruct = []() -> Shape * { return new BoxShape; };308f.mColor = Color::sGreen;309}310311JPH_NAMESPACE_END312313314