CylinderShape.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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/CylinderShape.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/Physics/SoftBody/SoftBodyVertex.h>
  13. #include <Jolt/Geometry/RayCylinder.h>
  14. #include <Jolt/ObjectStream/TypeDeclarations.h>
  15. #include <Jolt/Core/StreamIn.h>
  16. #include <Jolt/Core/StreamOut.h>
  17. #ifdef JPH_DEBUG_RENDERER
  18. #include <Jolt/Renderer/DebugRenderer.h>
  19. #endif // JPH_DEBUG_RENDERER
  20. JPH_NAMESPACE_BEGIN
  21. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(CylinderShapeSettings)
  22. {
  23. JPH_ADD_BASE_CLASS(CylinderShapeSettings, ConvexShapeSettings)
  24. JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mHalfHeight)
  25. JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mRadius)
  26. JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mConvexRadius)
  27. }
  28. // Approximation of top face with 8 vertices
  29. static const float cSin45 = 0.70710678118654752440084436210485f;
  30. static const Vec3 cTopFace[] =
  31. {
  32. Vec3(0.0f, 1.0f, 1.0f),
  33. Vec3(cSin45, 1.0f, cSin45),
  34. Vec3(1.0f, 1.0f, 0.0f),
  35. Vec3(cSin45, 1.0f, -cSin45),
  36. Vec3(-0.0f, 1.0f, -1.0f),
  37. Vec3(-cSin45, 1.0f, -cSin45),
  38. Vec3(-1.0f, 1.0f, 0.0f),
  39. Vec3(-cSin45, 1.0f, cSin45)
  40. };
  41. static const std::vector<Vec3> sUnitCylinderTriangles = []() {
  42. std::vector<Vec3> verts;
  43. const Vec3 bottom_offset(0.0f, -2.0f, 0.0f);
  44. int num_verts = sizeof(cTopFace) / sizeof(Vec3);
  45. for (int i = 0; i < num_verts; ++i)
  46. {
  47. Vec3 t1 = cTopFace[i];
  48. Vec3 t2 = cTopFace[(i + 1) % num_verts];
  49. Vec3 b1 = cTopFace[i] + bottom_offset;
  50. Vec3 b2 = cTopFace[(i + 1) % num_verts] + bottom_offset;
  51. // Top
  52. verts.emplace_back(0.0f, 1.0f, 0.0f);
  53. verts.push_back(t1);
  54. verts.push_back(t2);
  55. // Bottom
  56. verts.emplace_back(0.0f, -1.0f, 0.0f);
  57. verts.push_back(b2);
  58. verts.push_back(b1);
  59. // Side
  60. verts.push_back(t1);
  61. verts.push_back(b1);
  62. verts.push_back(t2);
  63. verts.push_back(t2);
  64. verts.push_back(b1);
  65. verts.push_back(b2);
  66. }
  67. return verts;
  68. }();
  69. ShapeSettings::ShapeResult CylinderShapeSettings::Create() const
  70. {
  71. if (mCachedResult.IsEmpty())
  72. Ref<Shape> shape = new CylinderShape(*this, mCachedResult);
  73. return mCachedResult;
  74. }
  75. CylinderShape::CylinderShape(const CylinderShapeSettings &inSettings, ShapeResult &outResult) :
  76. ConvexShape(EShapeSubType::Cylinder, inSettings, outResult),
  77. mHalfHeight(inSettings.mHalfHeight),
  78. mRadius(inSettings.mRadius),
  79. mConvexRadius(inSettings.mConvexRadius)
  80. {
  81. if (inSettings.mHalfHeight < inSettings.mConvexRadius)
  82. {
  83. outResult.SetError("Invalid height");
  84. return;
  85. }
  86. if (inSettings.mRadius < inSettings.mConvexRadius)
  87. {
  88. outResult.SetError("Invalid radius");
  89. return;
  90. }
  91. if (inSettings.mConvexRadius < 0.0f)
  92. {
  93. outResult.SetError("Invalid convex radius");
  94. return;
  95. }
  96. outResult.Set(this);
  97. }
  98. CylinderShape::CylinderShape(float inHalfHeight, float inRadius, float inConvexRadius, const PhysicsMaterial *inMaterial) :
  99. ConvexShape(EShapeSubType::Cylinder, inMaterial),
  100. mHalfHeight(inHalfHeight),
  101. mRadius(inRadius),
  102. mConvexRadius(inConvexRadius)
  103. {
  104. JPH_ASSERT(inHalfHeight >= inConvexRadius);
  105. JPH_ASSERT(inRadius >= inConvexRadius);
  106. JPH_ASSERT(inConvexRadius >= 0.0f);
  107. }
  108. class CylinderShape::Cylinder final : public Support
  109. {
  110. public:
  111. Cylinder(float inHalfHeight, float inRadius, float inConvexRadius) :
  112. mHalfHeight(inHalfHeight),
  113. mRadius(inRadius),
  114. mConvexRadius(inConvexRadius)
  115. {
  116. static_assert(sizeof(Cylinder) <= sizeof(SupportBuffer), "Buffer size too small");
  117. JPH_ASSERT(IsAligned(this, alignof(Cylinder)));
  118. }
  119. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  120. {
  121. // Support mapping, taken from:
  122. // A Fast and Robust GJK Implementation for Collision Detection of Convex Objects - Gino van den Bergen
  123. // page 8
  124. float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();
  125. float o = sqrt(Square(x) + Square(z));
  126. if (o > 0.0f)
  127. return Vec3((mRadius * x) / o, Sign(y) * mHalfHeight, (mRadius * z) / o);
  128. else
  129. return Vec3(0, Sign(y) * mHalfHeight, 0);
  130. }
  131. virtual float GetConvexRadius() const override
  132. {
  133. return mConvexRadius;
  134. }
  135. private:
  136. float mHalfHeight;
  137. float mRadius;
  138. float mConvexRadius;
  139. };
  140. const ConvexShape::Support *CylinderShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  141. {
  142. JPH_ASSERT(IsValidScale(inScale));
  143. // Get scaled cylinder
  144. Vec3 abs_scale = inScale.Abs();
  145. float scale_xz = abs_scale.GetX();
  146. float scale_y = abs_scale.GetY();
  147. float scaled_half_height = scale_y * mHalfHeight;
  148. float scaled_radius = scale_xz * mRadius;
  149. float scaled_convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale);
  150. switch (inMode)
  151. {
  152. case ESupportMode::IncludeConvexRadius:
  153. case ESupportMode::Default:
  154. return new (&inBuffer) Cylinder(scaled_half_height, scaled_radius, 0.0f);
  155. case ESupportMode::ExcludeConvexRadius:
  156. return new (&inBuffer) Cylinder(scaled_half_height - scaled_convex_radius, scaled_radius - scaled_convex_radius, scaled_convex_radius);
  157. }
  158. JPH_ASSERT(false);
  159. return nullptr;
  160. }
  161. void CylinderShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  162. {
  163. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  164. JPH_ASSERT(IsValidScale(inScale));
  165. // Get scaled cylinder
  166. Vec3 abs_scale = inScale.Abs();
  167. float scale_xz = abs_scale.GetX();
  168. float scale_y = abs_scale.GetY();
  169. float scaled_half_height = scale_y * mHalfHeight;
  170. float scaled_radius = scale_xz * mRadius;
  171. float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();
  172. float o = sqrt(Square(x) + Square(z));
  173. // If o / |y| > scaled_radius / scaled_half_height, we're hitting the side
  174. if (o * scaled_half_height > scaled_radius * abs(y))
  175. {
  176. // Hitting side
  177. float f = -scaled_radius / o;
  178. float vx = x * f;
  179. float vz = z * f;
  180. outVertices.push_back(inCenterOfMassTransform * Vec3(vx, scaled_half_height, vz));
  181. outVertices.push_back(inCenterOfMassTransform * Vec3(vx, -scaled_half_height, vz));
  182. }
  183. else
  184. {
  185. // Hitting top or bottom
  186. Vec3 multiplier = y < 0.0f? Vec3(scaled_radius, scaled_half_height, scaled_radius) : Vec3(-scaled_radius, -scaled_half_height, scaled_radius);
  187. Mat44 transform = inCenterOfMassTransform.PreScaled(multiplier);
  188. for (const Vec3 &v : cTopFace)
  189. outVertices.push_back(transform * v);
  190. }
  191. }
  192. MassProperties CylinderShape::GetMassProperties() const
  193. {
  194. MassProperties p;
  195. // Mass is surface of circle * height
  196. float radius_sq = Square(mRadius);
  197. float height = 2.0f * mHalfHeight;
  198. p.mMass = JPH_PI * radius_sq * height * GetDensity();
  199. // Inertia according to https://en.wikipedia.org/wiki/List_of_moments_of_inertia:
  200. float inertia_y = radius_sq * p.mMass * 0.5f;
  201. float inertia_x = inertia_y * 0.5f + p.mMass * height * height / 12.0f;
  202. float inertia_z = inertia_x;
  203. // Set inertia
  204. p.mInertia = Mat44::sScale(Vec3(inertia_x, inertia_y, inertia_z));
  205. return p;
  206. }
  207. Vec3 CylinderShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  208. {
  209. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  210. // Calculate distance to infinite cylinder surface
  211. Vec3 local_surface_position_xz(inLocalSurfacePosition.GetX(), 0, inLocalSurfacePosition.GetZ());
  212. float local_surface_position_xz_len = local_surface_position_xz.Length();
  213. float distance_to_curved_surface = abs(local_surface_position_xz_len - mRadius);
  214. // Calculate distance to top or bottom plane
  215. float distance_to_top_or_bottom = abs(abs(inLocalSurfacePosition.GetY()) - mHalfHeight);
  216. // Return normal according to closest surface
  217. if (distance_to_curved_surface < distance_to_top_or_bottom)
  218. return local_surface_position_xz / local_surface_position_xz_len;
  219. else
  220. return inLocalSurfacePosition.GetY() > 0.0f? Vec3::sAxisY() : -Vec3::sAxisY();
  221. }
  222. AABox CylinderShape::GetLocalBounds() const
  223. {
  224. Vec3 extent = Vec3(mRadius, mHalfHeight, mRadius);
  225. return AABox(-extent, extent);
  226. }
  227. #ifdef JPH_DEBUG_RENDERER
  228. void CylinderShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  229. {
  230. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  231. inRenderer->DrawCylinder(inCenterOfMassTransform * Mat44::sScale(inScale.Abs()), mHalfHeight, mRadius, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  232. }
  233. #endif // JPH_DEBUG_RENDERER
  234. bool CylinderShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  235. {
  236. // Test ray against capsule
  237. float fraction = RayCylinder(inRay.mOrigin, inRay.mDirection, mHalfHeight, mRadius);
  238. if (fraction < ioHit.mFraction)
  239. {
  240. ioHit.mFraction = fraction;
  241. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  242. return true;
  243. }
  244. return false;
  245. }
  246. void CylinderShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  247. {
  248. // Test shape filter
  249. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  250. return;
  251. // Check if the point is in the cylinder
  252. if (abs(inPoint.GetY()) <= mHalfHeight // Within the height
  253. && Square(inPoint.GetX()) + Square(inPoint.GetZ()) <= Square(mRadius)) // Within the radius
  254. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  255. }
  256. void CylinderShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, SoftBodyVertex *ioVertices, uint inNumVertices, [[maybe_unused]] float inDeltaTime, [[maybe_unused]] Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const
  257. {
  258. JPH_ASSERT(IsValidScale(inScale));
  259. Mat44 inverse_transform = inCenterOfMassTransform.InversedRotationTranslation();
  260. // Get scaled cylinder
  261. Vec3 abs_scale = inScale.Abs();
  262. float half_height = abs_scale.GetY() * mHalfHeight;
  263. float radius = abs_scale.GetX() * mRadius;
  264. for (SoftBodyVertex *v = ioVertices, *sbv_end = ioVertices + inNumVertices; v < sbv_end; ++v)
  265. if (v->mInvMass > 0.0f)
  266. {
  267. Vec3 local_pos = inverse_transform * v->mPosition;
  268. // Calculate penetration into side surface
  269. Vec3 side_normal = local_pos;
  270. side_normal.SetY(0.0f);
  271. float side_normal_length = side_normal.Length();
  272. float side_penetration = radius - side_normal_length;
  273. // Calculate penetration into top or bottom plane
  274. float top_penetration = half_height - abs(local_pos.GetY());
  275. Vec3 point, normal;
  276. if (side_penetration < 0.0f && top_penetration < 0.0f)
  277. {
  278. // We're outside the cylinder height and radius
  279. point = side_normal * (radius / side_normal_length) + Vec3(0, half_height * Sign(local_pos.GetY()), 0);
  280. normal = (local_pos - point).NormalizedOr(Vec3::sAxisY());
  281. }
  282. else if (side_penetration < top_penetration)
  283. {
  284. // Side surface is closest
  285. normal = side_normal_length > 0.0f? side_normal / side_normal_length : Vec3::sAxisX();
  286. point = radius * normal;
  287. }
  288. else
  289. {
  290. // Top or bottom plane is closest
  291. normal = Vec3(0, Sign(local_pos.GetY()), 0);
  292. point = half_height * normal;
  293. }
  294. // Calculate penetration
  295. Plane plane = Plane::sFromPointAndNormal(point, normal);
  296. float penetration = -plane.SignedDistance(local_pos);
  297. if (penetration > v->mLargestPenetration)
  298. {
  299. v->mLargestPenetration = penetration;
  300. // Store collision
  301. v->mCollisionPlane = plane.GetTransformed(inCenterOfMassTransform);
  302. v->mCollidingShapeIndex = inCollidingShapeIndex;
  303. }
  304. }
  305. }
  306. void CylinderShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  307. {
  308. Vec3 scale;
  309. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  310. TransformedShape ts(RVec3(transform.GetTranslation()), transform.GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  311. Vec3 abs_scale = scale.Abs();
  312. float xz = 0.5f * (abs_scale.GetX() + abs_scale.GetZ());
  313. ts.SetShapeScale(Vec3(xz, abs_scale.GetY(), xz));
  314. ioCollector.AddHit(ts);
  315. }
  316. void CylinderShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  317. {
  318. Mat44 unit_cylinder_transform(Vec4(mRadius, 0, 0, 0), Vec4(0, mHalfHeight, 0, 0), Vec4(0, 0, mRadius, 0), Vec4(0, 0, 0, 1));
  319. new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, inScale, unit_cylinder_transform, sUnitCylinderTriangles.data(), sUnitCylinderTriangles.size(), GetMaterial());
  320. }
  321. int CylinderShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  322. {
  323. return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);
  324. }
  325. void CylinderShape::SaveBinaryState(StreamOut &inStream) const
  326. {
  327. ConvexShape::SaveBinaryState(inStream);
  328. inStream.Write(mHalfHeight);
  329. inStream.Write(mRadius);
  330. inStream.Write(mConvexRadius);
  331. }
  332. void CylinderShape::RestoreBinaryState(StreamIn &inStream)
  333. {
  334. ConvexShape::RestoreBinaryState(inStream);
  335. inStream.Read(mHalfHeight);
  336. inStream.Read(mRadius);
  337. inStream.Read(mConvexRadius);
  338. }
  339. bool CylinderShape::IsValidScale(Vec3Arg inScale) const
  340. {
  341. // X and Z need same scale
  342. Vec3 abs_scale = inScale.Abs();
  343. return ConvexShape::IsValidScale(inScale) && abs_scale.Swizzle<SWIZZLE_Z, SWIZZLE_Y, SWIZZLE_X>().IsClose(abs_scale, ScaleHelpers::cScaleToleranceSq);
  344. }
  345. void CylinderShape::sRegister()
  346. {
  347. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Cylinder);
  348. f.mConstruct = []() -> Shape * { return new CylinderShape; };
  349. f.mColor = Color::sGreen;
  350. }
  351. JPH_NAMESPACE_END