Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCylinderShape.cpp
9913 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2024 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#include <Jolt/Jolt.h>56#include <Jolt/Physics/Collision/Shape/TaperedCylinderShape.h>7#include <Jolt/Physics/Collision/Shape/CylinderShape.h>8#include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>9#include <Jolt/Physics/Collision/CollidePointResult.h>10#include <Jolt/Physics/Collision/TransformedShape.h>11#include <Jolt/Physics/Collision/CollideSoftBodyVertexIterator.h>12#include <Jolt/ObjectStream/TypeDeclarations.h>13#include <Jolt/Core/StreamIn.h>14#include <Jolt/Core/StreamOut.h>15#ifdef JPH_DEBUG_RENDERER16#include <Jolt/Renderer/DebugRenderer.h>17#endif // JPH_DEBUG_RENDERER1819JPH_NAMESPACE_BEGIN2021// Approximation of a face of the tapered cylinder22static const Vec3 cTaperedCylinderFace[] =23{24Vec3(0.0f, 0.0f, 1.0f),25Vec3(0.707106769f, 0.0f, 0.707106769f),26Vec3(1.0f, 0.0f, 0.0f),27Vec3(0.707106769f, 0.0f, -0.707106769f),28Vec3(-0.0f, 0.0f, -1.0f),29Vec3(-0.707106769f, 0.0f, -0.707106769f),30Vec3(-1.0f, 0.0f, 0.0f),31Vec3(-0.707106769f, 0.0f, 0.707106769f)32};3334JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(TaperedCylinderShapeSettings)35{36JPH_ADD_BASE_CLASS(TaperedCylinderShapeSettings, ConvexShapeSettings)3738JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mHalfHeight)39JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mTopRadius)40JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mBottomRadius)41JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mConvexRadius)42}4344ShapeSettings::ShapeResult TaperedCylinderShapeSettings::Create() const45{46if (mCachedResult.IsEmpty())47{48Ref<Shape> shape;49if (mTopRadius == mBottomRadius)50{51// Convert to regular cylinder52CylinderShapeSettings settings;53settings.mHalfHeight = mHalfHeight;54settings.mRadius = mTopRadius;55settings.mMaterial = mMaterial;56settings.mConvexRadius = mConvexRadius;57new CylinderShape(settings, mCachedResult);58}59else60{61// Normal tapered cylinder shape62new TaperedCylinderShape(*this, mCachedResult);63}64}65return mCachedResult;66}6768TaperedCylinderShapeSettings::TaperedCylinderShapeSettings(float inHalfHeightOfTaperedCylinder, float inTopRadius, float inBottomRadius, float inConvexRadius, const PhysicsMaterial *inMaterial) :69ConvexShapeSettings(inMaterial),70mHalfHeight(inHalfHeightOfTaperedCylinder),71mTopRadius(inTopRadius),72mBottomRadius(inBottomRadius),73mConvexRadius(inConvexRadius)74{75}7677TaperedCylinderShape::TaperedCylinderShape(const TaperedCylinderShapeSettings &inSettings, ShapeResult &outResult) :78ConvexShape(EShapeSubType::TaperedCylinder, inSettings, outResult),79mTopRadius(inSettings.mTopRadius),80mBottomRadius(inSettings.mBottomRadius),81mConvexRadius(inSettings.mConvexRadius)82{83if (mTopRadius < 0.0f)84{85outResult.SetError("Invalid top radius");86return;87}8889if (mBottomRadius < 0.0f)90{91outResult.SetError("Invalid bottom radius");92return;93}9495if (inSettings.mHalfHeight <= 0.0f)96{97outResult.SetError("Invalid height");98return;99}100101if (inSettings.mConvexRadius < 0.0f)102{103outResult.SetError("Invalid convex radius");104return;105}106107if (inSettings.mTopRadius < inSettings.mConvexRadius)108{109outResult.SetError("Convex radius must be smaller than convex radius");110return;111}112113if (inSettings.mBottomRadius < inSettings.mConvexRadius)114{115outResult.SetError("Convex radius must be smaller than bottom radius");116return;117}118119// Calculate the center of mass (using wxMaxima).120// Radius of cross section for tapered cylinder from 0 to h:121// r(x):=br+x*(tr-br)/h;122// Area:123// area(x):=%pi*r(x)^2;124// Total volume of cylinder:125// volume(h):=integrate(area(x),x,0,h);126// Center of mass:127// com(br,tr,h):=integrate(x*area(x),x,0,h)/volume(h);128// Results:129// ratsimp(com(br,tr,h),br,bt);130// Non-tapered cylinder should have com = 0.5:131// ratsimp(com(r,r,h));132// Cone with tip at origin and height h should have com = 3/4 h133// ratsimp(com(0,r,h));134float h = 2.0f * inSettings.mHalfHeight;135float tr = mTopRadius;136float tr2 = Square(tr);137float br = mBottomRadius;138float br2 = Square(br);139float com = h * (3 * tr2 + 2 * br * tr + br2) / (4.0f * (tr2 + br * tr + br2));140mTop = h - com;141mBottom = -com;142143outResult.Set(this);144}145146class TaperedCylinderShape::TaperedCylinder final : public Support147{148public:149TaperedCylinder(float inTop, float inBottom, float inTopRadius, float inBottomRadius, float inConvexRadius) :150mTop(inTop),151mBottom(inBottom),152mTopRadius(inTopRadius),153mBottomRadius(inBottomRadius),154mConvexRadius(inConvexRadius)155{156static_assert(sizeof(TaperedCylinder) <= sizeof(SupportBuffer), "Buffer size too small");157JPH_ASSERT(IsAligned(this, alignof(TaperedCylinder)));158}159160virtual Vec3 GetSupport(Vec3Arg inDirection) const override161{162float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();163float o = sqrt(Square(x) + Square(z));164if (o > 0.0f)165{166Vec3 top_support((mTopRadius * x) / o, mTop, (mTopRadius * z) / o);167Vec3 bottom_support((mBottomRadius * x) / o, mBottom, (mBottomRadius * z) / o);168return inDirection.Dot(top_support) > inDirection.Dot(bottom_support)? top_support : bottom_support;169}170else171{172if (y > 0.0f)173return Vec3(0, mTop, 0);174else175return Vec3(0, mBottom, 0);176}177}178179virtual float GetConvexRadius() const override180{181return mConvexRadius;182}183184private:185float mTop;186float mBottom;187float mTopRadius;188float mBottomRadius;189float mConvexRadius;190};191192JPH_INLINE void TaperedCylinderShape::GetScaled(Vec3Arg inScale, float &outTop, float &outBottom, float &outTopRadius, float &outBottomRadius, float &outConvexRadius) const193{194Vec3 abs_scale = inScale.Abs();195float scale_xz = abs_scale.GetX();196float scale_y = inScale.GetY();197198outTop = scale_y * mTop;199outBottom = scale_y * mBottom;200outTopRadius = scale_xz * mTopRadius;201outBottomRadius = scale_xz * mBottomRadius;202outConvexRadius = min(abs_scale.GetY(), scale_xz) * mConvexRadius;203204// Negative Y-scale flips the top and bottom205if (outBottom > outTop)206{207std::swap(outTop, outBottom);208std::swap(outTopRadius, outBottomRadius);209}210}211212const ConvexShape::Support *TaperedCylinderShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const213{214JPH_ASSERT(IsValidScale(inScale));215216// Get scaled tapered cylinder217float top, bottom, top_radius, bottom_radius, convex_radius;218GetScaled(inScale, top, bottom, top_radius, bottom_radius, convex_radius);219220switch (inMode)221{222case ESupportMode::IncludeConvexRadius:223case ESupportMode::Default:224return new (&inBuffer) TaperedCylinder(top, bottom, top_radius, bottom_radius, 0.0f);225226case ESupportMode::ExcludeConvexRadius:227return new (&inBuffer) TaperedCylinder(top - convex_radius, bottom + convex_radius, top_radius - convex_radius, bottom_radius - convex_radius, convex_radius);228}229230JPH_ASSERT(false);231return nullptr;232}233234JPH_INLINE static Vec3 sCalculateSideNormalXZ(Vec3Arg inSurfacePosition)235{236return (Vec3(1, 0, 1) * inSurfacePosition).NormalizedOr(Vec3::sAxisX());237}238239JPH_INLINE static Vec3 sCalculateSideNormal(Vec3Arg inNormalXZ, float inTop, float inBottom, float inTopRadius, float inBottomRadius)240{241float tan_alpha = (inBottomRadius - inTopRadius) / (inTop - inBottom);242return Vec3(inNormalXZ.GetX(), tan_alpha, inNormalXZ.GetZ()).Normalized();243}244245void TaperedCylinderShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const246{247JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");248JPH_ASSERT(IsValidScale(inScale));249250// Get scaled tapered cylinder251float top, bottom, top_radius, bottom_radius, convex_radius;252GetScaled(inScale, top, bottom, top_radius, bottom_radius, convex_radius);253254// Get the normal of the side of the cylinder255Vec3 normal_xz = sCalculateSideNormalXZ(-inDirection);256Vec3 normal = sCalculateSideNormal(normal_xz, top, bottom, top_radius, bottom_radius);257258constexpr float cMinRadius = 1.0e-3f;259260// Check if the normal is closer to the side than to the top or bottom261if (abs(normal.Dot(inDirection)) > abs(inDirection.GetY()))262{263// Return the side of the cylinder264outVertices.push_back(inCenterOfMassTransform * (normal_xz * top_radius + Vec3(0, top, 0)));265outVertices.push_back(inCenterOfMassTransform * (normal_xz * bottom_radius + Vec3(0, bottom, 0)));266}267else268{269// When the inDirection is more than 5 degrees from vertical, align the vertices so that 1 of the vertices270// points towards inDirection in the XZ plane. This ensures that we always have a vertex towards max penetration depth.271Mat44 transform = inCenterOfMassTransform;272Vec4 base_x = Vec4(inDirection.GetX(), 0, inDirection.GetZ(), 0);273float xz_sq = base_x.LengthSq();274float y_sq = Square(inDirection.GetY());275if (xz_sq > 0.00765427f * y_sq)276{277base_x /= sqrt(xz_sq);278Vec4 base_z = base_x.Swizzle<SWIZZLE_Z, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_W>() * Vec4(-1, 0, 1, 0);279transform = transform * Mat44(base_x, Vec4(0, 1, 0, 0), base_z, Vec4(0, 0, 0, 1));280}281282if (inDirection.GetY() < 0.0f)283{284// Top of the cylinder285if (top_radius > cMinRadius)286{287Vec3 top_3d(0, top, 0);288for (Vec3 v : cTaperedCylinderFace)289outVertices.push_back(transform * (top_radius * v + top_3d));290}291}292else293{294// Bottom of the cylinder295if (bottom_radius > cMinRadius)296{297Vec3 bottom_3d(0, bottom, 0);298for (const Vec3 *v = cTaperedCylinderFace + std::size(cTaperedCylinderFace) - 1; v >= cTaperedCylinderFace; --v)299outVertices.push_back(transform * (bottom_radius * *v + bottom_3d));300}301}302}303}304305MassProperties TaperedCylinderShape::GetMassProperties() const306{307MassProperties p;308309// Calculate mass310float density = GetDensity();311p.mMass = GetVolume() * density;312313// Calculate inertia of a tapered cylinder (using wxMaxima)314// Radius:315// r(x):=br+(x-b)*(tr-br)/(t-b);316// Where t=top, b=bottom, tr=top radius, br=bottom radius317// Area of the cross section of the cylinder at x:318// area(x):=%pi*r(x)^2;319// Inertia x slice at x (using inertia of a solid disc, see https://en.wikipedia.org/wiki/List_of_moments_of_inertia, note needs to be multiplied by density):320// dix(x):=area(x)*r(x)^2/4;321// Inertia y slice at y (note needs to be multiplied by density)322// diy(x):=area(x)*r(x)^2/2;323// Volume:324// volume(b,t):=integrate(area(x),x,b,t);325// The constant density (note that we have this through GetDensity() so we'll use that instead):326// density(b,t):=m/volume(b,t);327// Inertia tensor element xx, note that we use the parallel axis theorem to move the inertia: Ixx' = Ixx + m translation^2, also note we multiply by density here:328// Ixx(br,tr,b,t):=integrate(dix(x)+area(x)*x^2,x,b,t)*density(b,t);329// Inertia tensor element yy:330// Iyy(br,tr,b,t):=integrate(diy(x),x,b,t)*density(b,t);331// Note that we can simplify Ixx by using:332// Ixx_delta(br,tr,b,t):=Ixx(br,tr,b,t)-Iyy(br,tr,b,t)/2;333// For a cylinder this formula matches what is listed on the wiki:334// factor(Ixx(r,r,-h/2,h/2));335// factor(Iyy(r,r,-h/2,h/2));336// For a cone with tip at origin too:337// factor(Ixx(0,r,0,h));338// factor(Iyy(0,r,0,h));339// Now for the tapered cylinder:340// rat(Ixx(br,tr,b,t),br,bt);341// rat(Iyy(br,tr,b,t),br,bt);342// rat(Ixx_delta(br,tr,b,t),br,bt);343float t = mTop;344float t2 = Square(t);345float t3 = t * t2;346347float b = mBottom;348float b2 = Square(b);349float b3 = b * b2;350351float br = mBottomRadius;352float br2 = Square(br);353float br3 = br * br2;354float br4 = Square(br2);355356float tr = mTopRadius;357float tr2 = Square(tr);358float tr3 = tr * tr2;359float tr4 = Square(tr2);360361float inertia_y = (JPH_PI / 10.0f) * density * (t - b) * (br4 + tr * br3 + tr2 * br2 + tr3 * br + tr4);362float inertia_x_delta = (JPH_PI / 30.0f) * density * ((t3 + 2 * b * t2 + 3 * b2 * t - 6 * b3) * br2 + (3 * t3 + b * t2 - b2 * t - 3 * b3) * tr * br + (6 * t3 - 3 * b * t2 - 2 * b2 * t - b3) * tr2);363float inertia_x = inertia_x_delta + inertia_y / 2;364float inertia_z = inertia_x;365p.mInertia = Mat44::sScale(Vec3(inertia_x, inertia_y, inertia_z));366return p;367}368369Vec3 TaperedCylinderShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const370{371JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");372373constexpr float cEpsilon = 1.0e-5f;374375if (inLocalSurfacePosition.GetY() > mTop - cEpsilon)376return Vec3(0, 1, 0);377else if (inLocalSurfacePosition.GetY() < mBottom + cEpsilon)378return Vec3(0, -1, 0);379else380return sCalculateSideNormal(sCalculateSideNormalXZ(inLocalSurfacePosition), mTop, mBottom, mTopRadius, mBottomRadius);381}382383AABox TaperedCylinderShape::GetLocalBounds() const384{385float max_radius = max(mTopRadius, mBottomRadius);386return AABox(Vec3(-max_radius, mBottom, -max_radius), Vec3(max_radius, mTop, max_radius));387}388389void TaperedCylinderShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const390{391// Test shape filter392if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))393return;394395// Check if the point is in the tapered cylinder396if (inPoint.GetY() >= mBottom && inPoint.GetY() <= mTop // Within height397&& Square(inPoint.GetX()) + Square(inPoint.GetZ()) <= Square(mBottomRadius + (inPoint.GetY() - mBottom) * (mTopRadius - mBottomRadius) / (mTop - mBottom))) // Within the radius398ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });399}400401void TaperedCylinderShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const402{403JPH_ASSERT(IsValidScale(inScale));404405Mat44 inverse_transform = inCenterOfMassTransform.InversedRotationTranslation();406407// Get scaled tapered cylinder408float top, bottom, top_radius, bottom_radius, convex_radius;409GetScaled(inScale, top, bottom, top_radius, bottom_radius, convex_radius);410Vec3 top_3d(0, top, 0);411Vec3 bottom_3d(0, bottom, 0);412413for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v)414if (v.GetInvMass() > 0.0f)415{416Vec3 local_pos = inverse_transform * v.GetPosition();417418// Calculate penetration into side surface419Vec3 normal_xz = sCalculateSideNormalXZ(local_pos);420Vec3 side_normal = sCalculateSideNormal(normal_xz, top, bottom, top_radius, bottom_radius);421Vec3 side_support_top = normal_xz * top_radius + top_3d;422float side_penetration = (side_support_top - local_pos).Dot(side_normal);423424// Calculate penetration into top and bottom plane425float top_penetration = top - local_pos.GetY();426float bottom_penetration = local_pos.GetY() - bottom;427float min_top_bottom_penetration = min(top_penetration, bottom_penetration);428429Vec3 point, normal;430if (side_penetration < 0.0f || min_top_bottom_penetration < 0.0f)431{432// We're outside the cylinder433// Calculate the closest point on the line segment from bottom to top support point:434// closest_point = bottom + fraction * (top - bottom) / |top - bottom|^2435Vec3 side_support_bottom = normal_xz * bottom_radius + bottom_3d;436Vec3 bottom_to_top = side_support_top - side_support_bottom;437float fraction = (local_pos - side_support_bottom).Dot(bottom_to_top);438439// Calculate the distance to the axis of the cylinder440float distance_to_axis = normal_xz.Dot(local_pos);441bool inside_top_radius = distance_to_axis <= top_radius;442bool inside_bottom_radius = distance_to_axis <= bottom_radius;443444/*445Regions of tapered cylinder (side view):446447_ B | |448--_ | A |449t-------+450C / \451/ tapered \452_ / cylinder \453--_ / \454b-----------------+455D | E |456| |457458t = side_support_top, b = side_support_bottom459Lines between B and C and C and D are at a 90 degree angle to the line between t and b460*/461if (fraction >= bottom_to_top.LengthSq() // Region B: Above the line segment462&& !inside_top_radius) // Outside the top radius463{464// Top support point is closest465point = side_support_top;466normal = (local_pos - point).NormalizedOr(Vec3::sAxisY());467}468else if (fraction < 0.0f // Region D: Below the line segment469&& !inside_bottom_radius) // Outside the bottom radius470{471// Bottom support point is closest472point = side_support_bottom;473normal = (local_pos - point).NormalizedOr(Vec3::sAxisY());474}475else if (top_penetration < 0.0f // Region A: Above the top plane476&& inside_top_radius) // Inside the top radius477{478// Top plane is closest479point = top_3d;480normal = Vec3(0, 1, 0);481}482else if (bottom_penetration < 0.0f // Region E: Below the bottom plane483&& inside_bottom_radius) // Inside the bottom radius484{485// Bottom plane is closest486point = bottom_3d;487normal = Vec3(0, -1, 0);488}489else // Region C490{491// Side surface is closest492point = side_support_top;493normal = side_normal;494}495}496else if (side_penetration < min_top_bottom_penetration)497{498// Side surface is closest499point = side_support_top;500normal = side_normal;501}502else if (top_penetration < bottom_penetration)503{504// Top plane is closest505point = top_3d;506normal = Vec3(0, 1, 0);507}508else509{510// Bottom plane is closest511point = bottom_3d;512normal = Vec3(0, -1, 0);513}514515// Calculate penetration516Plane plane = Plane::sFromPointAndNormal(point, normal);517float penetration = -plane.SignedDistance(local_pos);518if (v.UpdatePenetration(penetration))519v.SetCollision(plane.GetTransformed(inCenterOfMassTransform), inCollidingShapeIndex);520}521}522523class TaperedCylinderShape::TCSGetTrianglesContext524{525public:526explicit TCSGetTrianglesContext(Mat44Arg inTransform) : mTransform(inTransform) { }527528Mat44 mTransform;529uint mProcessed = 0; // Which elements we processed, bit 0 = top, bit 1 = bottom, bit 2 = side530};531532void TaperedCylinderShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const533{534static_assert(sizeof(TCSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");535JPH_ASSERT(IsAligned(&ioContext, alignof(TCSGetTrianglesContext)));536537// Make sure the scale is not inside out538Vec3 scale = ScaleHelpers::IsInsideOut(inScale)? Vec3(-1, 1, 1) * inScale : inScale;539540// Mark top and bottom processed if their radius is too small541TCSGetTrianglesContext *context = new (&ioContext) TCSGetTrianglesContext(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(scale));542constexpr float cMinRadius = 1.0e-3f;543if (mTopRadius < cMinRadius)544context->mProcessed |= 0b001;545if (mBottomRadius < cMinRadius)546context->mProcessed |= 0b010;547}548549int TaperedCylinderShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const550{551constexpr int cNumVertices = int(std::size(cTaperedCylinderFace));552553static_assert(cGetTrianglesMinTrianglesRequested >= 2 * cNumVertices);554JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);555556TCSGetTrianglesContext &context = (TCSGetTrianglesContext &)ioContext;557558int total_num_triangles = 0;559560// Top cap561Vec3 top_3d(0, mTop, 0);562if ((context.mProcessed & 0b001) == 0)563{564Vec3 v0 = context.mTransform * (top_3d + mTopRadius * cTaperedCylinderFace[0]);565Vec3 v1 = context.mTransform * (top_3d + mTopRadius * cTaperedCylinderFace[1]);566567for (const Vec3 *v = cTaperedCylinderFace + 2, *v_end = cTaperedCylinderFace + cNumVertices; v < v_end; ++v)568{569Vec3 v2 = context.mTransform * (top_3d + mTopRadius * *v);570571v0.StoreFloat3(outTriangleVertices++);572v1.StoreFloat3(outTriangleVertices++);573v2.StoreFloat3(outTriangleVertices++);574575v1 = v2;576}577578total_num_triangles = cNumVertices - 2;579context.mProcessed |= 0b001;580}581582// Bottom cap583Vec3 bottom_3d(0, mBottom, 0);584if ((context.mProcessed & 0b010) == 0585&& total_num_triangles + cNumVertices - 2 < inMaxTrianglesRequested)586{587Vec3 v0 = context.mTransform * (bottom_3d + mBottomRadius * cTaperedCylinderFace[0]);588Vec3 v1 = context.mTransform * (bottom_3d + mBottomRadius * cTaperedCylinderFace[1]);589590for (const Vec3 *v = cTaperedCylinderFace + 2, *v_end = cTaperedCylinderFace + cNumVertices; v < v_end; ++v)591{592Vec3 v2 = context.mTransform * (bottom_3d + mBottomRadius * *v);593594v0.StoreFloat3(outTriangleVertices++);595v2.StoreFloat3(outTriangleVertices++);596v1.StoreFloat3(outTriangleVertices++);597598v1 = v2;599}600601total_num_triangles += cNumVertices - 2;602context.mProcessed |= 0b010;603}604605// Side606if ((context.mProcessed & 0b100) == 0607&& total_num_triangles + 2 * cNumVertices < inMaxTrianglesRequested)608{609Vec3 v0t = context.mTransform * (top_3d + mTopRadius * cTaperedCylinderFace[cNumVertices - 1]);610Vec3 v0b = context.mTransform * (bottom_3d + mBottomRadius * cTaperedCylinderFace[cNumVertices - 1]);611612for (const Vec3 *v = cTaperedCylinderFace, *v_end = cTaperedCylinderFace + cNumVertices; v < v_end; ++v)613{614Vec3 v1t = context.mTransform * (top_3d + mTopRadius * *v);615v0t.StoreFloat3(outTriangleVertices++);616v0b.StoreFloat3(outTriangleVertices++);617v1t.StoreFloat3(outTriangleVertices++);618619Vec3 v1b = context.mTransform * (bottom_3d + mBottomRadius * *v);620v1t.StoreFloat3(outTriangleVertices++);621v0b.StoreFloat3(outTriangleVertices++);622v1b.StoreFloat3(outTriangleVertices++);623624v0t = v1t;625v0b = v1b;626}627628total_num_triangles += 2 * cNumVertices;629context.mProcessed |= 0b100;630}631632// Store materials633if (outMaterials != nullptr)634{635const PhysicsMaterial *material = GetMaterial();636for (const PhysicsMaterial **m = outMaterials, **m_end = outMaterials + total_num_triangles; m < m_end; ++m)637*m = material;638}639640return total_num_triangles;641}642643#ifdef JPH_DEBUG_RENDERER644void TaperedCylinderShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const645{646// Preserve flip along y axis but make sure we're not inside out647Vec3 scale = ScaleHelpers::IsInsideOut(inScale)? Vec3(-1, 1, 1) * inScale : inScale;648RMat44 world_transform = inCenterOfMassTransform * Mat44::sScale(scale);649650DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;651inRenderer->DrawTaperedCylinder(world_transform, mTop, mBottom, mTopRadius, mBottomRadius, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);652}653#endif // JPH_DEBUG_RENDERER654655void TaperedCylinderShape::SaveBinaryState(StreamOut &inStream) const656{657ConvexShape::SaveBinaryState(inStream);658659inStream.Write(mTop);660inStream.Write(mBottom);661inStream.Write(mTopRadius);662inStream.Write(mBottomRadius);663inStream.Write(mConvexRadius);664}665666void TaperedCylinderShape::RestoreBinaryState(StreamIn &inStream)667{668ConvexShape::RestoreBinaryState(inStream);669670inStream.Read(mTop);671inStream.Read(mBottom);672inStream.Read(mTopRadius);673inStream.Read(mBottomRadius);674inStream.Read(mConvexRadius);675}676677float TaperedCylinderShape::GetVolume() const678{679// Volume of a tapered cylinder is: integrate(%pi*(b+x*(t-b)/h)^2,x,0,h) where t is the top radius, b is the bottom radius and h is the height680return (JPH_PI / 3.0f) * (mTop - mBottom) * (Square(mTopRadius) + mTopRadius * mBottomRadius + Square(mBottomRadius));681}682683bool TaperedCylinderShape::IsValidScale(Vec3Arg inScale) const684{685return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScaleXZ(inScale.Abs());686}687688Vec3 TaperedCylinderShape::MakeScaleValid(Vec3Arg inScale) const689{690Vec3 scale = ScaleHelpers::MakeNonZeroScale(inScale);691692return scale.GetSign() * ScaleHelpers::MakeUniformScaleXZ(scale.Abs());693}694695void TaperedCylinderShape::sRegister()696{697ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::TaperedCylinder);698f.mConstruct = []() -> Shape * { return new TaperedCylinderShape; };699f.mColor = Color::sGreen;700}701702JPH_NAMESPACE_END703704705