CylinderShape.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 vector<Vec3> sUnitCylinderTriangles = []() {
  40. 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(Vec3Arg inDirection, Vec3Arg inScale, SupportingFace &outVertices) const
  159. {
  160. JPH_ASSERT(IsValidScale(inScale));
  161. // Get scaled cylinder
  162. Vec3 abs_scale = inScale.Abs();
  163. float scale_xz = abs_scale.GetX();
  164. float scale_y = abs_scale.GetY();
  165. float scaled_half_height = scale_y * mHalfHeight;
  166. float scaled_radius = scale_xz * mRadius;
  167. float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();
  168. float o = sqrt(Square(x) + Square(z));
  169. // If o / |y| > scaled_radius / scaled_half_height, we're hitting the side
  170. if (o * scaled_half_height > scaled_radius * abs(y))
  171. {
  172. // Hitting side
  173. float f = -scaled_radius / o;
  174. float vx = x * f;
  175. float vz = z * f;
  176. outVertices.push_back(Vec3(vx, scaled_half_height, vz));
  177. outVertices.push_back(Vec3(vx, -scaled_half_height, vz));
  178. }
  179. else
  180. {
  181. // Hitting top or bottom
  182. Vec3 multiplier = y < 0.0f? Vec3(scaled_radius, scaled_half_height, scaled_radius) : Vec3(-scaled_radius, -scaled_half_height, scaled_radius);
  183. for (const Vec3 &v : cTopFace)
  184. outVertices.push_back(multiplier * v);
  185. }
  186. }
  187. MassProperties CylinderShape::GetMassProperties() const
  188. {
  189. MassProperties p;
  190. // Mass is surface of circle * height
  191. float radius_sq = Square(mRadius);
  192. float height = 2.0f * mHalfHeight;
  193. p.mMass = JPH_PI * radius_sq * height * GetDensity();
  194. // Inertia according to https://en.wikipedia.org/wiki/List_of_moments_of_inertia:
  195. float inertia_y = radius_sq * p.mMass * 0.5f;
  196. float inertia_x = inertia_y * 0.5f + p.mMass * height * height / 12.0f;
  197. float inertia_z = inertia_x;
  198. // Set inertia
  199. p.mInertia = Mat44::sScale(Vec3(inertia_x, inertia_y, inertia_z));
  200. return p;
  201. }
  202. Vec3 CylinderShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  203. {
  204. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  205. // Calculate distance to infinite cylinder surface
  206. Vec3 local_surface_position_xz(inLocalSurfacePosition.GetX(), 0, inLocalSurfacePosition.GetZ());
  207. float local_surface_position_xz_len = local_surface_position_xz.Length();
  208. float distance_to_curved_surface = abs(local_surface_position_xz_len - mRadius);
  209. // Calculate distance to top or bottom plane
  210. float distance_to_top_or_bottom = abs(abs(inLocalSurfacePosition.GetY()) - mHalfHeight);
  211. // Return normal according to closest surface
  212. if (distance_to_curved_surface < distance_to_top_or_bottom)
  213. return local_surface_position_xz / local_surface_position_xz_len;
  214. else
  215. return inLocalSurfacePosition.GetY() > 0.0f? Vec3::sAxisY() : -Vec3::sAxisY();
  216. }
  217. AABox CylinderShape::GetLocalBounds() const
  218. {
  219. Vec3 extent = Vec3(mRadius, mHalfHeight, mRadius);
  220. return AABox(-extent, extent);
  221. }
  222. #ifdef JPH_DEBUG_RENDERER
  223. void CylinderShape::Draw(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  224. {
  225. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  226. inRenderer->DrawCylinder(inCenterOfMassTransform * Mat44::sScale(inScale.Abs()), mHalfHeight, mRadius, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  227. }
  228. #endif // JPH_DEBUG_RENDERER
  229. bool CylinderShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  230. {
  231. // Test ray against capsule
  232. float fraction = RayCylinder(inRay.mOrigin, inRay.mDirection, mHalfHeight, mRadius);
  233. if (fraction < ioHit.mFraction)
  234. {
  235. ioHit.mFraction = fraction;
  236. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  237. return true;
  238. }
  239. return false;
  240. }
  241. void CylinderShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector) const
  242. {
  243. // Check if the point is in the cylinder
  244. if (abs(inPoint.GetY()) <= mHalfHeight // Within the height
  245. && Square(inPoint.GetX()) + Square(inPoint.GetZ()) <= Square(mRadius)) // Within the radius
  246. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  247. }
  248. void CylinderShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  249. {
  250. Vec3 scale;
  251. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  252. TransformedShape ts(transform.GetTranslation(), transform.GetRotation().GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  253. Vec3 abs_scale = scale.Abs();
  254. float xz = 0.5f * (abs_scale.GetX() + abs_scale.GetZ());
  255. ts.SetShapeScale(Vec3(xz, abs_scale.GetY(), xz));
  256. ioCollector.AddHit(ts);
  257. }
  258. void CylinderShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  259. {
  260. Mat44 unit_cylinder_transform(Vec4(mRadius, 0, 0, 0), Vec4(0, mHalfHeight, 0, 0), Vec4(0, 0, mRadius, 0), Vec4(0, 0, 0, 1));
  261. new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, inScale, unit_cylinder_transform, sUnitCylinderTriangles.data(), sUnitCylinderTriangles.size(), GetMaterial());
  262. }
  263. int CylinderShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  264. {
  265. return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);
  266. }
  267. void CylinderShape::SaveBinaryState(StreamOut &inStream) const
  268. {
  269. ConvexShape::SaveBinaryState(inStream);
  270. inStream.Write(mHalfHeight);
  271. inStream.Write(mRadius);
  272. inStream.Write(mConvexRadius);
  273. }
  274. void CylinderShape::RestoreBinaryState(StreamIn &inStream)
  275. {
  276. ConvexShape::RestoreBinaryState(inStream);
  277. inStream.Read(mHalfHeight);
  278. inStream.Read(mRadius);
  279. inStream.Read(mConvexRadius);
  280. }
  281. bool CylinderShape::IsValidScale(Vec3Arg inScale) const
  282. {
  283. // X and Z need same scale
  284. Vec3 abs_scale = inScale.Abs();
  285. return ConvexShape::IsValidScale(inScale) && abs_scale.Swizzle<SWIZZLE_Z, SWIZZLE_Y, SWIZZLE_X>().IsClose(abs_scale, ScaleHelpers::cScaleToleranceSq);
  286. }
  287. void CylinderShape::sRegister()
  288. {
  289. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Cylinder);
  290. f.mConstruct = []() -> Shape * { return new CylinderShape; };
  291. f.mColor = Color::sGreen;
  292. }
  293. JPH_NAMESPACE_END