CapsuleShape.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  5. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  6. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  7. #include <Jolt/Physics/Collision/Shape/GetTrianglesContext.h>
  8. #include <Jolt/Physics/Collision/RayCast.h>
  9. #include <Jolt/Physics/Collision/CastResult.h>
  10. #include <Jolt/Physics/Collision/CollidePointResult.h>
  11. #include <Jolt/Physics/Collision/TransformedShape.h>
  12. #include <Jolt/Geometry/RayCapsule.h>
  13. #include <Jolt/ObjectStream/TypeDeclarations.h>
  14. #include <Jolt/Core/StreamIn.h>
  15. #include <Jolt/Core/StreamOut.h>
  16. #ifdef JPH_DEBUG_RENDERER
  17. #include <Jolt/Renderer/DebugRenderer.h>
  18. #endif // JPH_DEBUG_RENDERER
  19. JPH_NAMESPACE_BEGIN
  20. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(CapsuleShapeSettings)
  21. {
  22. JPH_ADD_BASE_CLASS(CapsuleShapeSettings, ConvexShapeSettings)
  23. JPH_ADD_ATTRIBUTE(CapsuleShapeSettings, mRadius)
  24. JPH_ADD_ATTRIBUTE(CapsuleShapeSettings, mHalfHeightOfCylinder)
  25. }
  26. static const int cCapsuleDetailLevel = 2;
  27. static const std::vector<Vec3> sCapsuleTopTriangles = []() {
  28. std::vector<Vec3> verts;
  29. GetTrianglesContextVertexList::sCreateHalfUnitSphereTop(verts, cCapsuleDetailLevel);
  30. return verts;
  31. }();
  32. static const std::vector<Vec3> sCapsuleMiddleTriangles = []() {
  33. std::vector<Vec3> verts;
  34. GetTrianglesContextVertexList::sCreateUnitOpenCylinder(verts, cCapsuleDetailLevel);
  35. return verts;
  36. }();
  37. static const std::vector<Vec3> sCapsuleBottomTriangles = []() {
  38. std::vector<Vec3> verts;
  39. GetTrianglesContextVertexList::sCreateHalfUnitSphereBottom(verts, cCapsuleDetailLevel);
  40. return verts;
  41. }();
  42. ShapeSettings::ShapeResult CapsuleShapeSettings::Create() const
  43. {
  44. if (mCachedResult.IsEmpty())
  45. {
  46. Ref<Shape> shape;
  47. if (IsValid() && IsSphere())
  48. {
  49. // If the capsule has no height, use a sphere instead
  50. shape = new SphereShape(mRadius, mMaterial);
  51. mCachedResult.Set(shape);
  52. }
  53. else
  54. shape = new CapsuleShape(*this, mCachedResult);
  55. }
  56. return mCachedResult;
  57. }
  58. CapsuleShape::CapsuleShape(const CapsuleShapeSettings &inSettings, ShapeResult &outResult) :
  59. ConvexShape(EShapeSubType::Capsule, inSettings, outResult),
  60. mRadius(inSettings.mRadius),
  61. mHalfHeightOfCylinder(inSettings.mHalfHeightOfCylinder)
  62. {
  63. if (inSettings.mHalfHeightOfCylinder <= 0.0f)
  64. {
  65. outResult.SetError("Invalid height");
  66. return;
  67. }
  68. if (inSettings.mRadius <= 0.0f)
  69. {
  70. outResult.SetError("Invalid radius");
  71. return;
  72. }
  73. outResult.Set(this);
  74. }
  75. class CapsuleShape::CapsuleNoConvex final : public Support
  76. {
  77. public:
  78. CapsuleNoConvex(Vec3Arg inHalfHeightOfCylinder, float inConvexRadius) :
  79. mHalfHeightOfCylinder(inHalfHeightOfCylinder),
  80. mConvexRadius(inConvexRadius)
  81. {
  82. static_assert(sizeof(CapsuleNoConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  83. JPH_ASSERT(IsAligned(this, alignof(CapsuleNoConvex)));
  84. }
  85. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  86. {
  87. if (inDirection.GetY() > 0)
  88. return mHalfHeightOfCylinder;
  89. else
  90. return -mHalfHeightOfCylinder;
  91. }
  92. virtual float GetConvexRadius() const override
  93. {
  94. return mConvexRadius;
  95. }
  96. private:
  97. Vec3 mHalfHeightOfCylinder;
  98. float mConvexRadius;
  99. };
  100. class CapsuleShape::CapsuleWithConvex final : public Support
  101. {
  102. public:
  103. CapsuleWithConvex(Vec3Arg inHalfHeightOfCylinder, float inRadius) :
  104. mHalfHeightOfCylinder(inHalfHeightOfCylinder),
  105. mRadius(inRadius)
  106. {
  107. static_assert(sizeof(CapsuleWithConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  108. JPH_ASSERT(IsAligned(this, alignof(CapsuleWithConvex)));
  109. }
  110. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  111. {
  112. float len = inDirection.Length();
  113. Vec3 radius = len > 0.0f? inDirection * (mRadius / len) : Vec3::sZero();
  114. if (inDirection.GetY() > 0)
  115. return radius + mHalfHeightOfCylinder;
  116. else
  117. return radius - mHalfHeightOfCylinder;
  118. }
  119. virtual float GetConvexRadius() const override
  120. {
  121. return 0.0f;
  122. }
  123. private:
  124. Vec3 mHalfHeightOfCylinder;
  125. float mRadius;
  126. };
  127. const ConvexShape::Support *CapsuleShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  128. {
  129. JPH_ASSERT(IsValidScale(inScale));
  130. // Get scaled capsule
  131. Vec3 abs_scale = inScale.Abs();
  132. float scale = abs_scale.GetX();
  133. Vec3 scaled_half_height_of_cylinder = Vec3(0, scale * mHalfHeightOfCylinder, 0);
  134. float scaled_radius = scale * mRadius;
  135. switch (inMode)
  136. {
  137. case ESupportMode::IncludeConvexRadius:
  138. return new (&inBuffer) CapsuleWithConvex(scaled_half_height_of_cylinder, scaled_radius);
  139. case ESupportMode::ExcludeConvexRadius:
  140. return new (&inBuffer) CapsuleNoConvex(scaled_half_height_of_cylinder, scaled_radius);
  141. }
  142. JPH_ASSERT(false);
  143. return nullptr;
  144. }
  145. void CapsuleShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  146. {
  147. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  148. JPH_ASSERT(IsValidScale(inScale));
  149. // Get direction in horizontal plane
  150. Vec3 direction = inDirection;
  151. direction.SetComponent(1, 0.0f);
  152. // Check zero vector, in this case we're hitting from top/bottom so there's no supporting face
  153. float len = direction.Length();
  154. if (len == 0.0f)
  155. return;
  156. // Get scaled capsule
  157. Vec3 abs_scale = inScale.Abs();
  158. float scale = abs_scale.GetX();
  159. Vec3 scaled_half_height_of_cylinder = Vec3(0, scale * mHalfHeightOfCylinder, 0);
  160. float scaled_radius = scale * mRadius;
  161. // Get support point for top and bottom sphere in the opposite of 'direction' (including convex radius)
  162. Vec3 support = (scaled_radius / len) * direction;
  163. Vec3 support_top = scaled_half_height_of_cylinder - support;
  164. Vec3 support_bottom = -scaled_half_height_of_cylinder - support;
  165. // Get projection on inDirection
  166. // Note that inDirection is not normalized, so we need to divide by inDirection.Length() to get the actual projection
  167. // We've multiplied both sides of the if below with inDirection.Length()
  168. float proj_top = support_top.Dot(inDirection);
  169. float proj_bottom = support_bottom.Dot(inDirection);
  170. // If projection is roughly equal then return line, otherwise we return nothing as there's only 1 point
  171. if (abs(proj_top - proj_bottom) < cCapsuleProjectionSlop * inDirection.Length())
  172. {
  173. outVertices.push_back(inCenterOfMassTransform * support_top);
  174. outVertices.push_back(inCenterOfMassTransform * support_bottom);
  175. }
  176. }
  177. MassProperties CapsuleShape::GetMassProperties() const
  178. {
  179. MassProperties p;
  180. float density = GetDensity();
  181. // Calculate inertia and mass according to:
  182. // https://www.gamedev.net/resources/_/technical/math-and-physics/capsule-inertia-tensor-r3856
  183. float radius_sq = mRadius * mRadius;
  184. float height = 2.0f * mHalfHeightOfCylinder;
  185. float cylinder_mass = JPH_PI * height * radius_sq * density;
  186. float hemisphere_mass = (2.0f * JPH_PI / 3.0f) * radius_sq * mRadius * density;
  187. // From cylinder
  188. float inertia_y = radius_sq * cylinder_mass * 0.5f;
  189. float inertia_x = inertia_y * 0.5f + cylinder_mass * height * height / 12.0f;
  190. float inertia_z = inertia_x;
  191. // From hemispheres
  192. float temp0 = hemisphere_mass * 2.0f * radius_sq / 5.0f;
  193. inertia_y += temp0 * 2.0f;
  194. float temp1 = mHalfHeightOfCylinder;
  195. float temp2 = temp0 + hemisphere_mass * (temp1 * temp1 + (3.0f / 8.0f) * height * mRadius);
  196. inertia_x += temp2 * 2.0f;
  197. inertia_z += temp2 * 2.0f;
  198. // Mass is cylinder + hemispheres
  199. p.mMass = cylinder_mass + hemisphere_mass * 2.0f;
  200. // Set inertia
  201. p.mInertia = Mat44::sScale(Vec3(inertia_x, inertia_y, inertia_z));
  202. return p;
  203. }
  204. Vec3 CapsuleShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  205. {
  206. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  207. if (inLocalSurfacePosition.GetY() > mHalfHeightOfCylinder)
  208. return (inLocalSurfacePosition - Vec3(0, mHalfHeightOfCylinder, 0)).Normalized();
  209. else if (inLocalSurfacePosition.GetY() < -mHalfHeightOfCylinder)
  210. return (inLocalSurfacePosition - Vec3(0, -mHalfHeightOfCylinder, 0)).Normalized();
  211. else
  212. return Vec3(inLocalSurfacePosition.GetX(), 0, inLocalSurfacePosition.GetZ()).NormalizedOr(Vec3::sAxisX());
  213. }
  214. AABox CapsuleShape::GetLocalBounds() const
  215. {
  216. Vec3 extent = Vec3::sReplicate(mRadius) + Vec3(0, mHalfHeightOfCylinder, 0);
  217. return AABox(-extent, extent);
  218. }
  219. AABox CapsuleShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  220. {
  221. JPH_ASSERT(IsValidScale(inScale));
  222. Vec3 abs_scale = inScale.Abs();
  223. float scale = abs_scale.GetX();
  224. Vec3 extent = Vec3::sReplicate(scale * mRadius);
  225. Vec3 height = Vec3(0, scale * mHalfHeightOfCylinder, 0);
  226. Vec3 p1 = inCenterOfMassTransform * -height;
  227. Vec3 p2 = inCenterOfMassTransform * height;
  228. return AABox(Vec3::sMin(p1, p2) - extent, Vec3::sMax(p1, p2) + extent);
  229. }
  230. #ifdef JPH_DEBUG_RENDERER
  231. void CapsuleShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  232. {
  233. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  234. inRenderer->DrawCapsule(inCenterOfMassTransform * Mat44::sScale(inScale.Abs().GetX()), mHalfHeightOfCylinder, mRadius, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  235. }
  236. #endif // JPH_DEBUG_RENDERER
  237. bool CapsuleShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  238. {
  239. // Test ray against capsule
  240. float fraction = RayCapsule(inRay.mOrigin, inRay.mDirection, mHalfHeightOfCylinder, mRadius);
  241. if (fraction < ioHit.mFraction)
  242. {
  243. ioHit.mFraction = fraction;
  244. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  245. return true;
  246. }
  247. return false;
  248. }
  249. void CapsuleShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  250. {
  251. // Test shape filter
  252. if (!inShapeFilter.ShouldCollide(inSubShapeIDCreator.GetID()))
  253. return;
  254. float radius_sq = Square(mRadius);
  255. // Get vertical distance to the top/bottom sphere centers
  256. float delta_y = abs(inPoint.GetY()) - mHalfHeightOfCylinder;
  257. // Get distance in horizontal plane
  258. float xz_sq = Square(inPoint.GetX()) + Square(inPoint.GetZ());
  259. // Check if the point is in one of the two spheres
  260. bool in_sphere = xz_sq + Square(delta_y) <= radius_sq;
  261. // Check if the point is in the cylinder in the middle
  262. bool in_cylinder = delta_y <= 0.0f && xz_sq <= radius_sq;
  263. if (in_sphere || in_cylinder)
  264. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  265. }
  266. void CapsuleShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  267. {
  268. Vec3 scale;
  269. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  270. TransformedShape ts(RVec3(transform.GetTranslation()), transform.GetRotation().GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  271. ts.SetShapeScale(ScaleHelpers::MakeUniformScale(scale.Abs()));
  272. ioCollector.AddHit(ts);
  273. }
  274. void CapsuleShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  275. {
  276. JPH_ASSERT(IsValidScale(inScale));
  277. Vec3 abs_scale = inScale.Abs();
  278. float scale = abs_scale.GetX();
  279. GetTrianglesContextMultiVertexList *context = new (&ioContext) GetTrianglesContextMultiVertexList(false, GetMaterial());
  280. Mat44 world_matrix = Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(scale);
  281. Mat44 top_matrix = world_matrix * Mat44(Vec4(mRadius, 0, 0, 0), Vec4(0, mRadius, 0, 0), Vec4(0, 0, mRadius, 0), Vec4(0, mHalfHeightOfCylinder, 0, 1));
  282. context->AddPart(top_matrix, sCapsuleTopTriangles.data(), sCapsuleTopTriangles.size());
  283. Mat44 middle_matrix = world_matrix * Mat44::sScale(Vec3(mRadius, mHalfHeightOfCylinder, mRadius));
  284. context->AddPart(middle_matrix, sCapsuleMiddleTriangles.data(), sCapsuleMiddleTriangles.size());
  285. Mat44 bottom_matrix = world_matrix * Mat44(Vec4(mRadius, 0, 0, 0), Vec4(0, mRadius, 0, 0), Vec4(0, 0, mRadius, 0), Vec4(0, -mHalfHeightOfCylinder, 0, 1));
  286. context->AddPart(bottom_matrix, sCapsuleBottomTriangles.data(), sCapsuleBottomTriangles.size());
  287. }
  288. int CapsuleShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  289. {
  290. return ((GetTrianglesContextMultiVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);
  291. }
  292. void CapsuleShape::SaveBinaryState(StreamOut &inStream) const
  293. {
  294. ConvexShape::SaveBinaryState(inStream);
  295. inStream.Write(mRadius);
  296. inStream.Write(mHalfHeightOfCylinder);
  297. }
  298. void CapsuleShape::RestoreBinaryState(StreamIn &inStream)
  299. {
  300. ConvexShape::RestoreBinaryState(inStream);
  301. inStream.Read(mRadius);
  302. inStream.Read(mHalfHeightOfCylinder);
  303. }
  304. bool CapsuleShape::IsValidScale(Vec3Arg inScale) const
  305. {
  306. return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScale(inScale.Abs());
  307. }
  308. void CapsuleShape::sRegister()
  309. {
  310. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Capsule);
  311. f.mConstruct = []() -> Shape * { return new CapsuleShape; };
  312. f.mColor = Color::sGreen;
  313. }
  314. JPH_NAMESPACE_END