TaperedCapsuleShape.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Collision/Shape/TaperedCapsuleShape.h>
  6. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  7. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  8. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  9. #include <Jolt/Physics/Collision/TransformedShape.h>
  10. #include <Jolt/Geometry/RayCapsule.h>
  11. #include <Jolt/ObjectStream/TypeDeclarations.h>
  12. #include <Jolt/Core/StreamIn.h>
  13. #include <Jolt/Core/StreamOut.h>
  14. #ifdef JPH_DEBUG_RENDERER
  15. #include <Jolt/Renderer/DebugRenderer.h>
  16. #endif // JPH_DEBUG_RENDERER
  17. JPH_NAMESPACE_BEGIN
  18. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(TaperedCapsuleShapeSettings)
  19. {
  20. JPH_ADD_BASE_CLASS(TaperedCapsuleShapeSettings, ConvexShapeSettings)
  21. JPH_ADD_ATTRIBUTE(TaperedCapsuleShapeSettings, mHalfHeightOfTaperedCylinder)
  22. JPH_ADD_ATTRIBUTE(TaperedCapsuleShapeSettings, mTopRadius)
  23. JPH_ADD_ATTRIBUTE(TaperedCapsuleShapeSettings, mBottomRadius)
  24. }
  25. bool TaperedCapsuleShapeSettings::IsSphere() const
  26. {
  27. return max(mTopRadius, mBottomRadius) >= 2.0f * mHalfHeightOfTaperedCylinder + min(mTopRadius, mBottomRadius);
  28. }
  29. ShapeSettings::ShapeResult TaperedCapsuleShapeSettings::Create() const
  30. {
  31. if (mCachedResult.IsEmpty())
  32. {
  33. Ref<Shape> shape;
  34. if (IsValid() && IsSphere())
  35. {
  36. // Determine sphere center and radius
  37. float radius, center;
  38. if (mTopRadius > mBottomRadius)
  39. {
  40. radius = mTopRadius;
  41. center = mHalfHeightOfTaperedCylinder;
  42. }
  43. else
  44. {
  45. radius = mBottomRadius;
  46. center = -mHalfHeightOfTaperedCylinder;
  47. }
  48. // Create sphere
  49. shape = new SphereShape(radius, mMaterial);
  50. // Offset sphere if needed
  51. if (abs(center) > 1.0e-6f)
  52. {
  53. RotatedTranslatedShapeSettings rot_trans(Vec3(0, center, 0), Quat::sIdentity(), shape);
  54. mCachedResult = rot_trans.Create();
  55. }
  56. else
  57. mCachedResult.Set(shape);
  58. }
  59. else
  60. {
  61. // Normal tapered capsule shape
  62. shape = new TaperedCapsuleShape(*this, mCachedResult);
  63. }
  64. }
  65. return mCachedResult;
  66. }
  67. TaperedCapsuleShapeSettings::TaperedCapsuleShapeSettings(float inHalfHeightOfTaperedCylinder, float inTopRadius, float inBottomRadius, const PhysicsMaterial *inMaterial) :
  68. ConvexShapeSettings(inMaterial),
  69. mHalfHeightOfTaperedCylinder(inHalfHeightOfTaperedCylinder),
  70. mTopRadius(inTopRadius),
  71. mBottomRadius(inBottomRadius)
  72. {
  73. }
  74. TaperedCapsuleShape::TaperedCapsuleShape(const TaperedCapsuleShapeSettings &inSettings, ShapeResult &outResult) :
  75. ConvexShape(EShapeSubType::TaperedCapsule, inSettings, outResult),
  76. mTopRadius(inSettings.mTopRadius),
  77. mBottomRadius(inSettings.mBottomRadius)
  78. {
  79. if (mTopRadius <= 0.0f)
  80. {
  81. outResult.SetError("Invalid top radius");
  82. return;
  83. }
  84. if (mBottomRadius <= 0.0f)
  85. {
  86. outResult.SetError("Invalid bottom radius");
  87. return;
  88. }
  89. if (inSettings.mHalfHeightOfTaperedCylinder <= 0.0f)
  90. {
  91. outResult.SetError("Invalid height");
  92. return;
  93. }
  94. // If this goes off one of the sphere ends falls totally inside the other and you should use a sphere instead
  95. if (inSettings.IsSphere())
  96. {
  97. outResult.SetError("One sphere embedded in other sphere, please use sphere shape instead");
  98. return;
  99. }
  100. // Approximation: The center of mass is exactly half way between the top and bottom cap of the tapered capsule
  101. mTopCenter = inSettings.mHalfHeightOfTaperedCylinder + 0.5f * (mBottomRadius - mTopRadius);
  102. mBottomCenter = -inSettings.mHalfHeightOfTaperedCylinder + 0.5f * (mBottomRadius - mTopRadius);
  103. // Calculate center of mass
  104. mCenterOfMass = Vec3(0, inSettings.mHalfHeightOfTaperedCylinder - mTopCenter, 0);
  105. // Calculate convex radius
  106. mConvexRadius = min(mTopRadius, mBottomRadius);
  107. JPH_ASSERT(mConvexRadius > 0.0f);
  108. // Calculate the sin and tan of the angle that the cone surface makes with the Y axis
  109. // See: TaperedCapsuleShape.gliffy
  110. mSinAlpha = (mBottomRadius - mTopRadius) / (mTopCenter - mBottomCenter);
  111. JPH_ASSERT(mSinAlpha >= -1.0f && mSinAlpha <= 1.0f);
  112. mTanAlpha = Tan(ASin(mSinAlpha));
  113. outResult.Set(this);
  114. }
  115. class TaperedCapsuleShape::TaperedCapsule final : public Support
  116. {
  117. public:
  118. TaperedCapsule(Vec3Arg inTopCenter, Vec3Arg inBottomCenter, float inTopRadius, float inBottomRadius, float inConvexRadius) :
  119. mTopCenter(inTopCenter),
  120. mBottomCenter(inBottomCenter),
  121. mTopRadius(inTopRadius),
  122. mBottomRadius(inBottomRadius),
  123. mConvexRadius(inConvexRadius)
  124. {
  125. static_assert(sizeof(TaperedCapsule) <= sizeof(SupportBuffer), "Buffer size too small");
  126. JPH_ASSERT(IsAligned(this, alignof(TaperedCapsule)));
  127. }
  128. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  129. {
  130. // Check zero vector
  131. float len = inDirection.Length();
  132. if (len == 0.0f)
  133. return mTopCenter + Vec3(0, mTopRadius, 0); // Return top
  134. // Check if the support of the top sphere or bottom sphere is bigger
  135. Vec3 support_top = mTopCenter + (mTopRadius / len) * inDirection;
  136. Vec3 support_bottom = mBottomCenter + (mBottomRadius / len) * inDirection;
  137. if (support_top.Dot(inDirection) > support_bottom.Dot(inDirection))
  138. return support_top;
  139. else
  140. return support_bottom;
  141. }
  142. virtual float GetConvexRadius() const override
  143. {
  144. return mConvexRadius;
  145. }
  146. private:
  147. Vec3 mTopCenter;
  148. Vec3 mBottomCenter;
  149. float mTopRadius;
  150. float mBottomRadius;
  151. float mConvexRadius;
  152. };
  153. const ConvexShape::Support *TaperedCapsuleShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  154. {
  155. JPH_ASSERT(IsValidScale(inScale));
  156. // Get scaled tapered capsule
  157. Vec3 abs_scale = inScale.Abs();
  158. float scale_xz = abs_scale.GetX();
  159. float scale_y = inScale.GetY(); // The sign of y is important as it flips the tapered capsule
  160. Vec3 scaled_top_center = Vec3(0, scale_y * mTopCenter, 0);
  161. Vec3 scaled_bottom_center = Vec3(0, scale_y * mBottomCenter, 0);
  162. float scaled_top_radius = scale_xz * mTopRadius;
  163. float scaled_bottom_radius = scale_xz * mBottomRadius;
  164. float scaled_convex_radius = scale_xz * mConvexRadius;
  165. switch (inMode)
  166. {
  167. case ESupportMode::IncludeConvexRadius:
  168. return new (&inBuffer) TaperedCapsule(scaled_top_center, scaled_bottom_center, scaled_top_radius, scaled_bottom_radius, 0.0f);
  169. case ESupportMode::ExcludeConvexRadius:
  170. {
  171. // Get radii reduced by convex radius
  172. float tr = scaled_top_radius - scaled_convex_radius;
  173. float br = scaled_bottom_radius - scaled_convex_radius;
  174. JPH_ASSERT(tr >= 0.0f && br >= 0.0f);
  175. JPH_ASSERT(tr == 0.0f || br == 0.0f, "Convex radius should be that of the smallest sphere");
  176. return new (&inBuffer) TaperedCapsule(scaled_top_center, scaled_bottom_center, tr, br, scaled_convex_radius);
  177. }
  178. }
  179. JPH_ASSERT(false);
  180. return nullptr;
  181. }
  182. void TaperedCapsuleShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  183. {
  184. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  185. JPH_ASSERT(IsValidScale(inScale));
  186. // Check zero vector
  187. float len = inDirection.Length();
  188. if (len == 0.0f)
  189. return;
  190. // Get scaled tapered capsule
  191. Vec3 abs_scale = inScale.Abs();
  192. float scale_xz = abs_scale.GetX();
  193. float scale_y = inScale.GetY(); // The sign of y is important as it flips the tapered capsule
  194. Vec3 scaled_top_center = Vec3(0, scale_y * mTopCenter, 0);
  195. Vec3 scaled_bottom_center = Vec3(0, scale_y * mBottomCenter, 0);
  196. float scaled_top_radius = scale_xz * mTopRadius;
  197. float scaled_bottom_radius = scale_xz * mBottomRadius;
  198. // Get support point for top and bottom sphere in the opposite of inDirection (including convex radius)
  199. Vec3 support_top = scaled_top_center - (scaled_top_radius / len) * inDirection;
  200. Vec3 support_bottom = scaled_bottom_center - (scaled_bottom_radius / len) * inDirection;
  201. // Get projection on inDirection
  202. float proj_top = support_top.Dot(inDirection);
  203. float proj_bottom = support_bottom.Dot(inDirection);
  204. // If projection is roughly equal then return line, otherwise we return nothing as there's only 1 point
  205. if (abs(proj_top - proj_bottom) < cCapsuleProjectionSlop * len)
  206. {
  207. outVertices.push_back(inCenterOfMassTransform * support_top);
  208. outVertices.push_back(inCenterOfMassTransform * support_bottom);
  209. }
  210. }
  211. MassProperties TaperedCapsuleShape::GetMassProperties() const
  212. {
  213. AABox box = GetInertiaApproximation();
  214. MassProperties p;
  215. p.SetMassAndInertiaOfSolidBox(box.GetSize(), GetDensity());
  216. return p;
  217. }
  218. Vec3 TaperedCapsuleShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  219. {
  220. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  221. // See: TaperedCapsuleShape.gliffy
  222. // We need to calculate ty and by in order to see if the position is on the top or bottom sphere
  223. // sin(alpha) = by / br = ty / tr
  224. // => by = sin(alpha) * br, ty = sin(alpha) * tr
  225. if (inLocalSurfacePosition.GetY() > mTopCenter + mSinAlpha * mTopRadius)
  226. return (inLocalSurfacePosition - Vec3(0, mTopCenter, 0)).Normalized();
  227. else if (inLocalSurfacePosition.GetY() < mBottomCenter + mSinAlpha * mBottomRadius)
  228. return (inLocalSurfacePosition - Vec3(0, mBottomCenter, 0)).Normalized();
  229. else
  230. {
  231. // Get perpendicular vector to the surface in the xz plane
  232. Vec3 perpendicular = Vec3(inLocalSurfacePosition.GetX(), 0, inLocalSurfacePosition.GetZ()).NormalizedOr(Vec3::sAxisX());
  233. // We know that the perpendicular has length 1 and that it needs a y component where tan(alpha) = y / 1 in order to align it to the surface
  234. perpendicular.SetY(mTanAlpha);
  235. return perpendicular.Normalized();
  236. }
  237. }
  238. AABox TaperedCapsuleShape::GetLocalBounds() const
  239. {
  240. float max_radius = max(mTopRadius, mBottomRadius);
  241. return AABox(Vec3(-max_radius, mBottomCenter - mBottomRadius, -max_radius), Vec3(max_radius, mTopCenter + mTopRadius, max_radius));
  242. }
  243. AABox TaperedCapsuleShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  244. {
  245. JPH_ASSERT(IsValidScale(inScale));
  246. Vec3 abs_scale = inScale.Abs();
  247. float scale_xz = abs_scale.GetX();
  248. float scale_y = inScale.GetY(); // The sign of y is important as it flips the tapered capsule
  249. Vec3 bottom_extent = Vec3::sReplicate(scale_xz * mBottomRadius);
  250. Vec3 bottom_center = inCenterOfMassTransform * Vec3(0, scale_y * mBottomCenter, 0);
  251. Vec3 top_extent = Vec3::sReplicate(scale_xz * mTopRadius);
  252. Vec3 top_center = inCenterOfMassTransform * Vec3(0, scale_y * mTopCenter, 0);
  253. Vec3 p1 = Vec3::sMin(top_center - top_extent, bottom_center - bottom_extent);
  254. Vec3 p2 = Vec3::sMax(top_center + top_extent, bottom_center + bottom_extent);
  255. return AABox(p1, p2);
  256. }
  257. #ifdef JPH_DEBUG_RENDERER
  258. void TaperedCapsuleShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  259. {
  260. if (mGeometry == nullptr)
  261. {
  262. SupportBuffer buffer;
  263. const Support *support = GetSupportFunction(ESupportMode::IncludeConvexRadius, buffer, Vec3::sReplicate(1.0f));
  264. mGeometry = inRenderer->CreateTriangleGeometryForConvex([support](Vec3Arg inDirection) { return support->GetSupport(inDirection); });
  265. }
  266. // Preserve flip along y axis but make sure we're not inside out
  267. Vec3 scale = ScaleHelpers::IsInsideOut(inScale)? Vec3(-1, 1, 1) * inScale : inScale;
  268. RMat44 world_transform = inCenterOfMassTransform * Mat44::sScale(scale);
  269. AABox bounds = Shape::GetWorldSpaceBounds(inCenterOfMassTransform, inScale);
  270. float lod_scale_sq = Square(max(mTopRadius, mBottomRadius));
  271. Color color = inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor;
  272. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  273. inRenderer->DrawGeometry(world_transform, bounds, lod_scale_sq, color, mGeometry, DebugRenderer::ECullMode::CullBackFace, DebugRenderer::ECastShadow::On, draw_mode);
  274. }
  275. #endif // JPH_DEBUG_RENDERER
  276. AABox TaperedCapsuleShape::GetInertiaApproximation() const
  277. {
  278. // TODO: For now the mass and inertia is that of a box
  279. float avg_radius = 0.5f * (mTopRadius + mBottomRadius);
  280. return AABox(Vec3(-avg_radius, mBottomCenter - mBottomRadius, -avg_radius), Vec3(avg_radius, mTopCenter + mTopRadius, avg_radius));
  281. }
  282. void TaperedCapsuleShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  283. {
  284. Vec3 scale;
  285. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  286. TransformedShape ts(RVec3(transform.GetTranslation()), transform.GetRotation().GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  287. ts.SetShapeScale(scale.GetSign() * ScaleHelpers::MakeUniformScale(scale.Abs()));
  288. ioCollector.AddHit(ts);
  289. }
  290. void TaperedCapsuleShape::SaveBinaryState(StreamOut &inStream) const
  291. {
  292. ConvexShape::SaveBinaryState(inStream);
  293. inStream.Write(mCenterOfMass);
  294. inStream.Write(mTopRadius);
  295. inStream.Write(mBottomRadius);
  296. inStream.Write(mTopCenter);
  297. inStream.Write(mBottomCenter);
  298. inStream.Write(mConvexRadius);
  299. inStream.Write(mSinAlpha);
  300. inStream.Write(mTanAlpha);
  301. }
  302. void TaperedCapsuleShape::RestoreBinaryState(StreamIn &inStream)
  303. {
  304. ConvexShape::RestoreBinaryState(inStream);
  305. inStream.Read(mCenterOfMass);
  306. inStream.Read(mTopRadius);
  307. inStream.Read(mBottomRadius);
  308. inStream.Read(mTopCenter);
  309. inStream.Read(mBottomCenter);
  310. inStream.Read(mConvexRadius);
  311. inStream.Read(mSinAlpha);
  312. inStream.Read(mTanAlpha);
  313. }
  314. bool TaperedCapsuleShape::IsValidScale(Vec3Arg inScale) const
  315. {
  316. return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScale(inScale.Abs());
  317. }
  318. void TaperedCapsuleShape::sRegister()
  319. {
  320. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::TaperedCapsule);
  321. f.mConstruct = []() -> Shape * { return new TaperedCapsuleShape; };
  322. f.mColor = Color::sGreen;
  323. }
  324. JPH_NAMESPACE_END