Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CylinderShape.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/CylinderShape.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/RayCylinder.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(CylinderShapeSettings)25{26JPH_ADD_BASE_CLASS(CylinderShapeSettings, ConvexShapeSettings)2728JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mHalfHeight)29JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mRadius)30JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mConvexRadius)31}3233// Approximation of top face with 8 vertices34static const Vec3 cCylinderTopFace[] =35{36Vec3(0.0f, 1.0f, 1.0f),37Vec3(0.707106769f, 1.0f, 0.707106769f),38Vec3(1.0f, 1.0f, 0.0f),39Vec3(0.707106769f, 1.0f, -0.707106769f),40Vec3(-0.0f, 1.0f, -1.0f),41Vec3(-0.707106769f, 1.0f, -0.707106769f),42Vec3(-1.0f, 1.0f, 0.0f),43Vec3(-0.707106769f, 1.0f, 0.707106769f)44};4546static const StaticArray<Vec3, 96> sUnitCylinderTriangles = []() {47StaticArray<Vec3, 96> verts;4849const Vec3 bottom_offset(0.0f, -2.0f, 0.0f);5051int num_verts = sizeof(cCylinderTopFace) / sizeof(Vec3);52for (int i = 0; i < num_verts; ++i)53{54Vec3 t1 = cCylinderTopFace[i];55Vec3 t2 = cCylinderTopFace[(i + 1) % num_verts];56Vec3 b1 = cCylinderTopFace[i] + bottom_offset;57Vec3 b2 = cCylinderTopFace[(i + 1) % num_verts] + bottom_offset;5859// Top60verts.emplace_back(0.0f, 1.0f, 0.0f);61verts.push_back(t1);62verts.push_back(t2);6364// Bottom65verts.emplace_back(0.0f, -1.0f, 0.0f);66verts.push_back(b2);67verts.push_back(b1);6869// Side70verts.push_back(t1);71verts.push_back(b1);72verts.push_back(t2);7374verts.push_back(t2);75verts.push_back(b1);76verts.push_back(b2);77}7879return verts;80}();8182ShapeSettings::ShapeResult CylinderShapeSettings::Create() const83{84if (mCachedResult.IsEmpty())85Ref<Shape> shape = new CylinderShape(*this, mCachedResult);86return mCachedResult;87}8889CylinderShape::CylinderShape(const CylinderShapeSettings &inSettings, ShapeResult &outResult) :90ConvexShape(EShapeSubType::Cylinder, inSettings, outResult),91mHalfHeight(inSettings.mHalfHeight),92mRadius(inSettings.mRadius),93mConvexRadius(inSettings.mConvexRadius)94{95if (inSettings.mHalfHeight < inSettings.mConvexRadius)96{97outResult.SetError("Invalid height");98return;99}100101if (inSettings.mRadius < inSettings.mConvexRadius)102{103outResult.SetError("Invalid radius");104return;105}106107if (inSettings.mConvexRadius < 0.0f)108{109outResult.SetError("Invalid convex radius");110return;111}112113outResult.Set(this);114}115116CylinderShape::CylinderShape(float inHalfHeight, float inRadius, float inConvexRadius, const PhysicsMaterial *inMaterial) :117ConvexShape(EShapeSubType::Cylinder, inMaterial),118mHalfHeight(inHalfHeight),119mRadius(inRadius),120mConvexRadius(inConvexRadius)121{122JPH_ASSERT(inHalfHeight >= inConvexRadius);123JPH_ASSERT(inRadius >= inConvexRadius);124JPH_ASSERT(inConvexRadius >= 0.0f);125}126127class CylinderShape::Cylinder final : public Support128{129public:130Cylinder(float inHalfHeight, float inRadius, float inConvexRadius) :131mHalfHeight(inHalfHeight),132mRadius(inRadius),133mConvexRadius(inConvexRadius)134{135static_assert(sizeof(Cylinder) <= sizeof(SupportBuffer), "Buffer size too small");136JPH_ASSERT(IsAligned(this, alignof(Cylinder)));137}138139virtual Vec3 GetSupport(Vec3Arg inDirection) const override140{141// Support mapping, taken from:142// A Fast and Robust GJK Implementation for Collision Detection of Convex Objects - Gino van den Bergen143// page 8144float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();145float o = sqrt(Square(x) + Square(z));146if (o > 0.0f)147return Vec3((mRadius * x) / o, Sign(y) * mHalfHeight, (mRadius * z) / o);148else149return Vec3(0, Sign(y) * mHalfHeight, 0);150}151152virtual float GetConvexRadius() const override153{154return mConvexRadius;155}156157private:158float mHalfHeight;159float mRadius;160float mConvexRadius;161};162163const ConvexShape::Support *CylinderShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const164{165JPH_ASSERT(IsValidScale(inScale));166167// Get scaled cylinder168Vec3 abs_scale = inScale.Abs();169float scale_xz = abs_scale.GetX();170float scale_y = abs_scale.GetY();171float scaled_half_height = scale_y * mHalfHeight;172float scaled_radius = scale_xz * mRadius;173float scaled_convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale);174175switch (inMode)176{177case ESupportMode::IncludeConvexRadius:178case ESupportMode::Default:179return new (&inBuffer) Cylinder(scaled_half_height, scaled_radius, 0.0f);180181case ESupportMode::ExcludeConvexRadius:182return new (&inBuffer) Cylinder(scaled_half_height - scaled_convex_radius, scaled_radius - scaled_convex_radius, scaled_convex_radius);183}184185JPH_ASSERT(false);186return nullptr;187}188189void CylinderShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const190{191JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");192JPH_ASSERT(IsValidScale(inScale));193194// Get scaled cylinder195Vec3 abs_scale = inScale.Abs();196float scale_xz = abs_scale.GetX();197float scale_y = abs_scale.GetY();198float scaled_half_height = scale_y * mHalfHeight;199float scaled_radius = scale_xz * mRadius;200201float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();202float xz_sq = Square(x) + Square(z);203float y_sq = Square(y);204205// Check which component is bigger206if (xz_sq > y_sq)207{208// Hitting side209float f = -scaled_radius / sqrt(xz_sq);210float vx = x * f;211float vz = z * f;212outVertices.push_back(inCenterOfMassTransform * Vec3(vx, scaled_half_height, vz));213outVertices.push_back(inCenterOfMassTransform * Vec3(vx, -scaled_half_height, vz));214}215else216{217// Hitting top or bottom218219// When the inDirection is more than 5 degrees from vertical, align the vertices so that 1 of the vertices220// points towards inDirection in the XZ plane. This ensures that we always have a vertex towards max penetration depth.221Mat44 transform = inCenterOfMassTransform;222if (xz_sq > 0.00765427f * y_sq)223{224Vec4 base_x = Vec4(x, 0, z, 0) / sqrt(xz_sq);225Vec4 base_z = base_x.Swizzle<SWIZZLE_Z, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_W>() * Vec4(-1, 0, 1, 0);226transform = transform * Mat44(base_x, Vec4(0, 1, 0, 0), base_z, Vec4(0, 0, 0, 1));227}228229// Adjust for scale and height230Vec3 multiplier = y < 0.0f? Vec3(scaled_radius, scaled_half_height, scaled_radius) : Vec3(-scaled_radius, -scaled_half_height, scaled_radius);231transform = transform.PreScaled(multiplier);232233for (const Vec3 &v : cCylinderTopFace)234outVertices.push_back(transform * v);235}236}237238MassProperties CylinderShape::GetMassProperties() const239{240MassProperties p;241242// Mass is surface of circle * height243float radius_sq = Square(mRadius);244float height = 2.0f * mHalfHeight;245p.mMass = JPH_PI * radius_sq * height * GetDensity();246247// Inertia according to https://en.wikipedia.org/wiki/List_of_moments_of_inertia:248float inertia_y = radius_sq * p.mMass * 0.5f;249float inertia_x = inertia_y * 0.5f + p.mMass * height * height / 12.0f;250float inertia_z = inertia_x;251252// Set inertia253p.mInertia = Mat44::sScale(Vec3(inertia_x, inertia_y, inertia_z));254255return p;256}257258Vec3 CylinderShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const259{260JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");261262// Calculate distance to infinite cylinder surface263Vec3 local_surface_position_xz(inLocalSurfacePosition.GetX(), 0, inLocalSurfacePosition.GetZ());264float local_surface_position_xz_len = local_surface_position_xz.Length();265float distance_to_curved_surface = abs(local_surface_position_xz_len - mRadius);266267// Calculate distance to top or bottom plane268float distance_to_top_or_bottom = abs(abs(inLocalSurfacePosition.GetY()) - mHalfHeight);269270// Return normal according to closest surface271if (distance_to_curved_surface < distance_to_top_or_bottom)272return local_surface_position_xz / local_surface_position_xz_len;273else274return inLocalSurfacePosition.GetY() > 0.0f? Vec3::sAxisY() : -Vec3::sAxisY();275}276277AABox CylinderShape::GetLocalBounds() const278{279Vec3 extent = Vec3(mRadius, mHalfHeight, mRadius);280return AABox(-extent, extent);281}282283#ifdef JPH_DEBUG_RENDERER284void CylinderShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const285{286DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;287inRenderer->DrawCylinder(inCenterOfMassTransform * Mat44::sScale(inScale.Abs()), mHalfHeight, mRadius, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);288}289#endif // JPH_DEBUG_RENDERER290291bool CylinderShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const292{293// Test ray against capsule294float fraction = RayCylinder(inRay.mOrigin, inRay.mDirection, mHalfHeight, mRadius);295if (fraction < ioHit.mFraction)296{297ioHit.mFraction = fraction;298ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();299return true;300}301return false;302}303304void CylinderShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const305{306// Test shape filter307if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))308return;309310// Check if the point is in the cylinder311if (abs(inPoint.GetY()) <= mHalfHeight // Within the height312&& Square(inPoint.GetX()) + Square(inPoint.GetZ()) <= Square(mRadius)) // Within the radius313ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });314}315316void CylinderShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const317{318JPH_ASSERT(IsValidScale(inScale));319320Mat44 inverse_transform = inCenterOfMassTransform.InversedRotationTranslation();321322// Get scaled cylinder323Vec3 abs_scale = inScale.Abs();324float half_height = abs_scale.GetY() * mHalfHeight;325float radius = abs_scale.GetX() * mRadius;326327for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v)328if (v.GetInvMass() > 0.0f)329{330Vec3 local_pos = inverse_transform * v.GetPosition();331332// Calculate penetration into side surface333Vec3 side_normal = local_pos;334side_normal.SetY(0.0f);335float side_normal_length = side_normal.Length();336float side_penetration = radius - side_normal_length;337338// Calculate penetration into top or bottom plane339float top_penetration = half_height - abs(local_pos.GetY());340341Vec3 point, normal;342if (side_penetration < 0.0f && top_penetration < 0.0f)343{344// We're outside the cylinder height and radius345point = side_normal * (radius / side_normal_length) + Vec3(0, half_height * Sign(local_pos.GetY()), 0);346normal = (local_pos - point).NormalizedOr(Vec3::sAxisY());347}348else if (side_penetration < top_penetration)349{350// Side surface is closest351normal = side_normal_length > 0.0f? side_normal / side_normal_length : Vec3::sAxisX();352point = radius * normal;353}354else355{356// Top or bottom plane is closest357normal = Vec3(0, Sign(local_pos.GetY()), 0);358point = half_height * normal;359}360361// Calculate penetration362Plane plane = Plane::sFromPointAndNormal(point, normal);363float penetration = -plane.SignedDistance(local_pos);364if (v.UpdatePenetration(penetration))365v.SetCollision(plane.GetTransformed(inCenterOfMassTransform), inCollidingShapeIndex);366}367}368369void CylinderShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const370{371Mat44 unit_cylinder_transform(Vec4(mRadius, 0, 0, 0), Vec4(0, mHalfHeight, 0, 0), Vec4(0, 0, mRadius, 0), Vec4(0, 0, 0, 1));372new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, inScale, unit_cylinder_transform, sUnitCylinderTriangles.data(), sUnitCylinderTriangles.size(), GetMaterial());373}374375int CylinderShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const376{377return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);378}379380void CylinderShape::SaveBinaryState(StreamOut &inStream) const381{382ConvexShape::SaveBinaryState(inStream);383384inStream.Write(mHalfHeight);385inStream.Write(mRadius);386inStream.Write(mConvexRadius);387}388389void CylinderShape::RestoreBinaryState(StreamIn &inStream)390{391ConvexShape::RestoreBinaryState(inStream);392393inStream.Read(mHalfHeight);394inStream.Read(mRadius);395inStream.Read(mConvexRadius);396}397398bool CylinderShape::IsValidScale(Vec3Arg inScale) const399{400return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScaleXZ(inScale.Abs());401}402403Vec3 CylinderShape::MakeScaleValid(Vec3Arg inScale) const404{405Vec3 scale = ScaleHelpers::MakeNonZeroScale(inScale);406407return scale.GetSign() * ScaleHelpers::MakeUniformScaleXZ(scale.Abs());408}409410void CylinderShape::sRegister()411{412ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Cylinder);413f.mConstruct = []() -> Shape * { return new CylinderShape; };414f.mColor = Color::sGreen;415}416417JPH_NAMESPACE_END418419420