CylinderShape.cpp 12 KB

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