ConvexShape.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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/ConvexShape.h>
  6. #include <Jolt/Physics/Collision/RayCast.h>
  7. #include <Jolt/Physics/Collision/ShapeCast.h>
  8. #include <Jolt/Physics/Collision/CollideShape.h>
  9. #include <Jolt/Physics/Collision/CastResult.h>
  10. #include <Jolt/Physics/Collision/CollidePointResult.h>
  11. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  12. #include <Jolt/Physics/Collision/Shape/GetTrianglesContext.h>
  13. #include <Jolt/Physics/Collision/Shape/PolyhedronSubmergedVolumeCalculator.h>
  14. #include <Jolt/Physics/Collision/TransformedShape.h>
  15. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  16. #include <Jolt/Physics/Collision/NarrowPhaseStats.h>
  17. #include <Jolt/Physics/PhysicsSettings.h>
  18. #include <Jolt/Core/StreamIn.h>
  19. #include <Jolt/Core/StreamOut.h>
  20. #include <Jolt/Geometry/EPAPenetrationDepth.h>
  21. #include <Jolt/Geometry/OrientedBox.h>
  22. #include <Jolt/ObjectStream/TypeDeclarations.h>
  23. JPH_NAMESPACE_BEGIN
  24. JPH_IMPLEMENT_SERIALIZABLE_ABSTRACT(ConvexShapeSettings)
  25. {
  26. JPH_ADD_BASE_CLASS(ConvexShapeSettings, ShapeSettings)
  27. JPH_ADD_ATTRIBUTE(ConvexShapeSettings, mDensity)
  28. JPH_ADD_ATTRIBUTE(ConvexShapeSettings, mMaterial)
  29. }
  30. const std::vector<Vec3> ConvexShape::sUnitSphereTriangles = []() {
  31. const int level = 2;
  32. std::vector<Vec3> verts;
  33. GetTrianglesContextVertexList::sCreateHalfUnitSphereTop(verts, level);
  34. GetTrianglesContextVertexList::sCreateHalfUnitSphereBottom(verts, level);
  35. return verts;
  36. }();
  37. void ConvexShape::sCollideConvexVsConvex(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter)
  38. {
  39. JPH_PROFILE_FUNCTION();
  40. // Get the shapes
  41. JPH_ASSERT(inShape1->GetType() == EShapeType::Convex);
  42. JPH_ASSERT(inShape2->GetType() == EShapeType::Convex);
  43. const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);
  44. const ConvexShape *shape2 = static_cast<const ConvexShape *>(inShape2);
  45. // Get transforms
  46. Mat44 inverse_transform1 = inCenterOfMassTransform1.InversedRotationTranslation();
  47. Mat44 transform_2_to_1 = inverse_transform1 * inCenterOfMassTransform2;
  48. // Get bounding boxes
  49. AABox shape1_bbox = shape1->GetLocalBounds().Scaled(inScale1);
  50. shape1_bbox.ExpandBy(Vec3::sReplicate(inCollideShapeSettings.mMaxSeparationDistance));
  51. AABox shape2_bbox = shape2->GetLocalBounds().Scaled(inScale2);
  52. // Check if they overlap
  53. if (!OrientedBox(transform_2_to_1, shape2_bbox).Overlaps(shape1_bbox))
  54. return;
  55. // Note: As we don't remember the penetration axis from the last iteration, and it is likely that shape2 is pushed out of
  56. // collision relative to shape1 by comparing their COM's, we use that as an initial penetration axis: shape2.com - shape1.com
  57. // This has been seen to improve performance by approx. 1% over using a fixed axis like (1, 0, 0).
  58. Vec3 penetration_axis = transform_2_to_1.GetTranslation();
  59. // Ensure that we do not pass in a near zero penetration axis
  60. if (penetration_axis.IsNearZero())
  61. penetration_axis = Vec3::sAxisX();
  62. Vec3 point1, point2;
  63. EPAPenetrationDepth pen_depth;
  64. EPAPenetrationDepth::EStatus status;
  65. // Scope to limit lifetime of SupportBuffer
  66. {
  67. // Create support function
  68. SupportBuffer buffer1_excl_cvx_radius, buffer2_excl_cvx_radius;
  69. const Support *shape1_excl_cvx_radius = shape1->GetSupportFunction(ConvexShape::ESupportMode::ExcludeConvexRadius, buffer1_excl_cvx_radius, inScale1);
  70. const Support *shape2_excl_cvx_radius = shape2->GetSupportFunction(ConvexShape::ESupportMode::ExcludeConvexRadius, buffer2_excl_cvx_radius, inScale2);
  71. // Transform shape 2 in the space of shape 1
  72. TransformedConvexObject<Support> transformed2_excl_cvx_radius(transform_2_to_1, *shape2_excl_cvx_radius);
  73. // Perform GJK step
  74. status = pen_depth.GetPenetrationDepthStepGJK(*shape1_excl_cvx_radius, shape1_excl_cvx_radius->GetConvexRadius() + inCollideShapeSettings.mMaxSeparationDistance, transformed2_excl_cvx_radius, shape2_excl_cvx_radius->GetConvexRadius(), inCollideShapeSettings.mCollisionTolerance, penetration_axis, point1, point2);
  75. }
  76. // Check result of collision detection
  77. switch (status)
  78. {
  79. case EPAPenetrationDepth::EStatus::Colliding:
  80. break;
  81. case EPAPenetrationDepth::EStatus::NotColliding:
  82. return;
  83. case EPAPenetrationDepth::EStatus::Indeterminate:
  84. {
  85. // Need to run expensive EPA algorithm
  86. // Create support function
  87. SupportBuffer buffer1_incl_cvx_radius, buffer2_incl_cvx_radius;
  88. const Support *shape1_incl_cvx_radius = shape1->GetSupportFunction(ConvexShape::ESupportMode::IncludeConvexRadius, buffer1_incl_cvx_radius, inScale1);
  89. const Support *shape2_incl_cvx_radius = shape2->GetSupportFunction(ConvexShape::ESupportMode::IncludeConvexRadius, buffer2_incl_cvx_radius, inScale2);
  90. // Add separation distance
  91. AddConvexRadius<Support> shape1_add_max_separation_distance(*shape1_incl_cvx_radius, inCollideShapeSettings.mMaxSeparationDistance);
  92. // Transform shape 2 in the space of shape 1
  93. TransformedConvexObject<Support> transformed2_incl_cvx_radius(transform_2_to_1, *shape2_incl_cvx_radius);
  94. // Perform EPA step
  95. if (!pen_depth.GetPenetrationDepthStepEPA(shape1_add_max_separation_distance, transformed2_incl_cvx_radius, inCollideShapeSettings.mPenetrationTolerance, penetration_axis, point1, point2))
  96. return;
  97. break;
  98. }
  99. }
  100. // Check if the penetration is bigger than the early out fraction
  101. float penetration_depth = (point2 - point1).Length() - inCollideShapeSettings.mMaxSeparationDistance;
  102. if (-penetration_depth >= ioCollector.GetEarlyOutFraction())
  103. return;
  104. // Correct point1 for the added separation distance
  105. float penetration_axis_len = penetration_axis.Length();
  106. if (penetration_axis_len > 0.0f)
  107. point1 -= penetration_axis * (inCollideShapeSettings.mMaxSeparationDistance / penetration_axis_len);
  108. // Convert to world space
  109. point1 = inCenterOfMassTransform1 * point1;
  110. point2 = inCenterOfMassTransform1 * point2;
  111. Vec3 penetration_axis_world = inCenterOfMassTransform1.Multiply3x3(penetration_axis);
  112. // Create collision result
  113. CollideShapeResult result(point1, point2, penetration_axis_world, penetration_depth, inSubShapeIDCreator1.GetID(), inSubShapeIDCreator2.GetID(), TransformedShape::sGetBodyID(ioCollector.GetContext()));
  114. // Gather faces
  115. if (inCollideShapeSettings.mCollectFacesMode == ECollectFacesMode::CollectFaces)
  116. {
  117. // Get supporting face of shape 1
  118. shape1->GetSupportingFace(SubShapeID(), -penetration_axis, inScale1, inCenterOfMassTransform1, result.mShape1Face);
  119. // Get supporting face of shape 2
  120. shape2->GetSupportingFace(SubShapeID(), transform_2_to_1.Multiply3x3Transposed(penetration_axis), inScale2, inCenterOfMassTransform2, result.mShape2Face);
  121. }
  122. // Notify the collector
  123. JPH_IF_TRACK_NARROWPHASE_STATS(TrackNarrowPhaseCollector track;)
  124. ioCollector.AddHit(result);
  125. }
  126. bool ConvexShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  127. {
  128. // Note: This is a fallback routine, most convex shapes should implement a more performant version!
  129. JPH_PROFILE_FUNCTION();
  130. // Create support function
  131. SupportBuffer buffer;
  132. const Support *support = GetSupportFunction(ConvexShape::ESupportMode::IncludeConvexRadius, buffer, Vec3::sReplicate(1.0f));
  133. // Cast ray
  134. GJKClosestPoint gjk;
  135. if (gjk.CastRay(inRay.mOrigin, inRay.mDirection, cDefaultCollisionTolerance, *support, ioHit.mFraction))
  136. {
  137. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  138. return true;
  139. }
  140. return false;
  141. }
  142. void ConvexShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  143. {
  144. // Note: This is a fallback routine, most convex shapes should implement a more performant version!
  145. // Test shape filter
  146. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  147. return;
  148. // First do a normal raycast, limited to the early out fraction
  149. RayCastResult hit;
  150. hit.mFraction = ioCollector.GetEarlyOutFraction();
  151. if (CastRay(inRay, inSubShapeIDCreator, hit))
  152. {
  153. // Check front side
  154. if (inRayCastSettings.mTreatConvexAsSolid || hit.mFraction > 0.0f)
  155. {
  156. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  157. ioCollector.AddHit(hit);
  158. }
  159. // Check if we want back facing hits and the collector still accepts additional hits
  160. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::CollideWithBackFaces && !ioCollector.ShouldEarlyOut())
  161. {
  162. // Invert the ray, going from the early out fraction back to the fraction where we found our forward hit
  163. float start_fraction = min(1.0f, ioCollector.GetEarlyOutFraction());
  164. float delta_fraction = hit.mFraction - start_fraction;
  165. if (delta_fraction < 0.0f)
  166. {
  167. RayCast inverted_ray { inRay.mOrigin + start_fraction * inRay.mDirection, delta_fraction * inRay.mDirection };
  168. // Cast another ray
  169. RayCastResult inverted_hit;
  170. inverted_hit.mFraction = 1.0f;
  171. if (CastRay(inverted_ray, inSubShapeIDCreator, inverted_hit)
  172. && inverted_hit.mFraction > 0.0f) // Ignore hits with fraction 0, this means the ray ends inside the object and we don't want to report it as a back facing hit
  173. {
  174. // Invert fraction and rescale it to the fraction of the original ray
  175. inverted_hit.mFraction = hit.mFraction + (inverted_hit.mFraction - 1.0f) * delta_fraction;
  176. inverted_hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  177. ioCollector.AddHit(inverted_hit);
  178. }
  179. }
  180. }
  181. }
  182. }
  183. void ConvexShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  184. {
  185. // Test shape filter
  186. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  187. return;
  188. // First test bounding box
  189. if (GetLocalBounds().Contains(inPoint))
  190. {
  191. // Create support function
  192. SupportBuffer buffer;
  193. const Support *support = GetSupportFunction(ConvexShape::ESupportMode::IncludeConvexRadius, buffer, Vec3::sReplicate(1.0f));
  194. // Create support function for point
  195. PointConvexSupport point { inPoint };
  196. // Test intersection
  197. GJKClosestPoint gjk;
  198. Vec3 v = inPoint;
  199. if (gjk.Intersects(*support, point, cDefaultCollisionTolerance, v))
  200. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  201. }
  202. }
  203. void ConvexShape::sCastConvexVsConvex(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  204. {
  205. JPH_PROFILE_FUNCTION();
  206. // Only supported for convex shapes
  207. JPH_ASSERT(inShapeCast.mShape->GetType() == EShapeType::Convex);
  208. const ConvexShape *cast_shape = static_cast<const ConvexShape *>(inShapeCast.mShape);
  209. JPH_ASSERT(inShape->GetType() == EShapeType::Convex);
  210. const ConvexShape *shape = static_cast<const ConvexShape *>(inShape);
  211. // Determine if we want to use the actual shape or a shrunken shape with convex radius
  212. ConvexShape::ESupportMode support_mode = inShapeCastSettings.mUseShrunkenShapeAndConvexRadius? ConvexShape::ESupportMode::ExcludeConvexRadius : ConvexShape::ESupportMode::IncludeConvexRadius;
  213. // Create support function for shape to cast
  214. SupportBuffer cast_buffer;
  215. const Support *cast_support = cast_shape->GetSupportFunction(support_mode, cast_buffer, inShapeCast.mScale);
  216. // Create support function for target shape
  217. SupportBuffer target_buffer;
  218. const Support *target_support = shape->GetSupportFunction(support_mode, target_buffer, inScale);
  219. // Do a raycast against the result
  220. EPAPenetrationDepth epa;
  221. float fraction = ioCollector.GetEarlyOutFraction();
  222. Vec3 contact_point_a, contact_point_b, contact_normal;
  223. if (epa.CastShape(inShapeCast.mCenterOfMassStart, inShapeCast.mDirection, inShapeCastSettings.mCollisionTolerance, inShapeCastSettings.mPenetrationTolerance, *cast_support, *target_support, cast_support->GetConvexRadius(), target_support->GetConvexRadius(), inShapeCastSettings.mReturnDeepestPoint, fraction, contact_point_a, contact_point_b, contact_normal)
  224. && (inShapeCastSettings.mBackFaceModeConvex == EBackFaceMode::CollideWithBackFaces
  225. || contact_normal.Dot(inShapeCast.mDirection) > 0.0f)) // Test if backfacing
  226. {
  227. // Convert to world space
  228. contact_point_a = inCenterOfMassTransform2 * contact_point_a;
  229. contact_point_b = inCenterOfMassTransform2 * contact_point_b;
  230. Vec3 contact_normal_world = inCenterOfMassTransform2.Multiply3x3(contact_normal);
  231. ShapeCastResult result(fraction, contact_point_a, contact_point_b, contact_normal_world, false, inSubShapeIDCreator1.GetID(), inSubShapeIDCreator2.GetID(), TransformedShape::sGetBodyID(ioCollector.GetContext()));
  232. // Gather faces
  233. if (inShapeCastSettings.mCollectFacesMode == ECollectFacesMode::CollectFaces)
  234. {
  235. // Get supporting face of shape 1
  236. Mat44 transform_1_to_2 = inShapeCast.mCenterOfMassStart;
  237. transform_1_to_2.SetTranslation(transform_1_to_2.GetTranslation() + fraction * inShapeCast.mDirection);
  238. cast_shape->GetSupportingFace(SubShapeID(), transform_1_to_2.Multiply3x3Transposed(-contact_normal), inShapeCast.mScale, inCenterOfMassTransform2 * transform_1_to_2, result.mShape1Face);
  239. // Get supporting face of shape 2
  240. shape->GetSupportingFace(SubShapeID(), contact_normal, inScale, inCenterOfMassTransform2, result.mShape2Face);
  241. }
  242. JPH_IF_TRACK_NARROWPHASE_STATS(TrackNarrowPhaseCollector track;)
  243. ioCollector.AddHit(result);
  244. }
  245. }
  246. class ConvexShape::CSGetTrianglesContext
  247. {
  248. public:
  249. CSGetTrianglesContext(const ConvexShape *inShape, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) :
  250. mLocalToWorld(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale)),
  251. mIsInsideOut(ScaleHelpers::IsInsideOut(inScale))
  252. {
  253. mSupport = inShape->GetSupportFunction(ESupportMode::IncludeConvexRadius, mSupportBuffer, Vec3::sReplicate(1.0f));
  254. }
  255. SupportBuffer mSupportBuffer;
  256. const Support * mSupport;
  257. Mat44 mLocalToWorld;
  258. bool mIsInsideOut;
  259. size_t mCurrentVertex = 0;
  260. };
  261. void ConvexShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  262. {
  263. static_assert(sizeof(CSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  264. JPH_ASSERT(IsAligned(&ioContext, alignof(CSGetTrianglesContext)));
  265. new (&ioContext) CSGetTrianglesContext(this, inPositionCOM, inRotation, inScale);
  266. }
  267. int ConvexShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  268. {
  269. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  270. CSGetTrianglesContext &context = (CSGetTrianglesContext &)ioContext;
  271. int total_num_vertices = min(inMaxTrianglesRequested * 3, int(sUnitSphereTriangles.size() - context.mCurrentVertex));
  272. if (context.mIsInsideOut)
  273. {
  274. // Store triangles flipped
  275. for (const Vec3 *v = sUnitSphereTriangles.data() + context.mCurrentVertex, *v_end = v + total_num_vertices; v < v_end; v += 3)
  276. {
  277. (context.mLocalToWorld * context.mSupport->GetSupport(v[0])).StoreFloat3(outTriangleVertices++);
  278. (context.mLocalToWorld * context.mSupport->GetSupport(v[2])).StoreFloat3(outTriangleVertices++);
  279. (context.mLocalToWorld * context.mSupport->GetSupport(v[1])).StoreFloat3(outTriangleVertices++);
  280. }
  281. }
  282. else
  283. {
  284. // Store triangles
  285. for (const Vec3 *v = sUnitSphereTriangles.data() + context.mCurrentVertex, *v_end = v + total_num_vertices; v < v_end; v += 3)
  286. {
  287. (context.mLocalToWorld * context.mSupport->GetSupport(v[0])).StoreFloat3(outTriangleVertices++);
  288. (context.mLocalToWorld * context.mSupport->GetSupport(v[1])).StoreFloat3(outTriangleVertices++);
  289. (context.mLocalToWorld * context.mSupport->GetSupport(v[2])).StoreFloat3(outTriangleVertices++);
  290. }
  291. }
  292. context.mCurrentVertex += total_num_vertices;
  293. int total_num_triangles = total_num_vertices / 3;
  294. // Store materials
  295. if (outMaterials != nullptr)
  296. {
  297. const PhysicsMaterial *material = GetMaterial();
  298. for (const PhysicsMaterial **m = outMaterials, **m_end = outMaterials + total_num_triangles; m < m_end; ++m)
  299. *m = material;
  300. }
  301. return total_num_triangles;
  302. }
  303. void ConvexShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const
  304. {
  305. // Calculate total volume
  306. Vec3 abs_scale = inScale.Abs();
  307. Vec3 extent = GetLocalBounds().GetExtent() * abs_scale;
  308. outTotalVolume = 8.0f * extent.GetX() * extent.GetY() * extent.GetZ();
  309. // Points of the bounding box
  310. Vec3 points[] =
  311. {
  312. Vec3(-1, -1, -1),
  313. Vec3( 1, -1, -1),
  314. Vec3(-1, 1, -1),
  315. Vec3( 1, 1, -1),
  316. Vec3(-1, -1, 1),
  317. Vec3( 1, -1, 1),
  318. Vec3(-1, 1, 1),
  319. Vec3( 1, 1, 1),
  320. };
  321. // Faces of the bounding box
  322. using Face = int[5];
  323. #define MAKE_FACE(a, b, c, d) { a, b, c, d, ((1 << a) | (1 << b) | (1 << c) | (1 << d)) } // Last int is a bit mask that indicates which indices are used
  324. Face faces[] =
  325. {
  326. MAKE_FACE(0, 2, 3, 1),
  327. MAKE_FACE(4, 6, 2, 0),
  328. MAKE_FACE(4, 5, 7, 6),
  329. MAKE_FACE(1, 3, 7, 5),
  330. MAKE_FACE(2, 6, 7, 3),
  331. MAKE_FACE(0, 1, 5, 4),
  332. };
  333. PolyhedronSubmergedVolumeCalculator::Point *buffer = (PolyhedronSubmergedVolumeCalculator::Point *)JPH_STACK_ALLOC(8 * sizeof(PolyhedronSubmergedVolumeCalculator::Point));
  334. PolyhedronSubmergedVolumeCalculator submerged_vol_calc(inCenterOfMassTransform * Mat44::sScale(extent), points, sizeof(Vec3), 8, inSurface, buffer JPH_IF_DEBUG_RENDERER(, inBaseOffset));
  335. if (submerged_vol_calc.AreAllAbove())
  336. {
  337. // We're above the water
  338. outSubmergedVolume = 0.0f;
  339. outCenterOfBuoyancy = Vec3::sZero();
  340. }
  341. else if (submerged_vol_calc.AreAllBelow())
  342. {
  343. // We're fully submerged
  344. outSubmergedVolume = outTotalVolume;
  345. outCenterOfBuoyancy = inCenterOfMassTransform.GetTranslation();
  346. }
  347. else
  348. {
  349. // Calculate submerged volume
  350. int reference_point_bit = 1 << submerged_vol_calc.GetReferencePointIdx();
  351. for (const Face &f : faces)
  352. {
  353. // Test if this face includes the reference point
  354. if ((f[4] & reference_point_bit) == 0)
  355. {
  356. // Triangulate the face (a quad)
  357. submerged_vol_calc.AddFace(f[0], f[1], f[2]);
  358. submerged_vol_calc.AddFace(f[0], f[2], f[3]);
  359. }
  360. }
  361. submerged_vol_calc.GetResult(outSubmergedVolume, outCenterOfBuoyancy);
  362. }
  363. }
  364. #ifdef JPH_DEBUG_RENDERER
  365. void ConvexShape::DrawGetSupportFunction(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inDrawSupportDirection) const
  366. {
  367. // Get the support function with convex radius
  368. SupportBuffer buffer;
  369. const Support *support = GetSupportFunction(ESupportMode::ExcludeConvexRadius, buffer, inScale);
  370. AddConvexRadius<Support> add_convex(*support, support->GetConvexRadius());
  371. // Draw the shape
  372. DebugRenderer::GeometryRef geometry = inRenderer->CreateTriangleGeometryForConvex([&add_convex](Vec3Arg inDirection) { return add_convex.GetSupport(inDirection); });
  373. AABox bounds = geometry->mBounds.Transformed(inCenterOfMassTransform);
  374. float lod_scale_sq = geometry->mBounds.GetExtent().LengthSq();
  375. inRenderer->DrawGeometry(inCenterOfMassTransform, bounds, lod_scale_sq, inColor, geometry);
  376. if (inDrawSupportDirection)
  377. {
  378. // Iterate on all directions and draw the support point and an arrow in the direction that was sampled to test if the support points make sense
  379. for (Vec3 v : Vec3::sUnitSphere)
  380. {
  381. Vec3 direction = 0.05f * v;
  382. Vec3 pos = add_convex.GetSupport(direction);
  383. RVec3 from = inCenterOfMassTransform * pos;
  384. RVec3 to = inCenterOfMassTransform * (pos + direction);
  385. inRenderer->DrawMarker(from, Color::sWhite, 0.001f);
  386. inRenderer->DrawArrow(from, to, Color::sWhite, 0.001f);
  387. }
  388. }
  389. }
  390. void ConvexShape::DrawGetSupportingFace(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  391. {
  392. // Sample directions and map which faces belong to which directions
  393. using FaceToDirection = UnorderedMap<SupportingFace, Array<Vec3>>;
  394. FaceToDirection faces;
  395. for (Vec3 v : Vec3::sUnitSphere)
  396. {
  397. Vec3 direction = 0.05f * v;
  398. SupportingFace face;
  399. GetSupportingFace(SubShapeID(), direction, inScale, Mat44::sIdentity(), face);
  400. if (!face.empty())
  401. {
  402. JPH_ASSERT(face.size() >= 2, "The GetSupportingFace function should either return nothing or at least an edge");
  403. faces[face].push_back(direction);
  404. }
  405. }
  406. // Draw each face in a unique color and draw corresponding directions
  407. int color_it = 0;
  408. for (FaceToDirection::value_type &ftd : faces)
  409. {
  410. Color color = Color::sGetDistinctColor(color_it++);
  411. // Create copy of face (key in map is read only)
  412. SupportingFace face = ftd.first;
  413. // Displace the face a little bit forward so it is easier to see
  414. Vec3 normal = face.size() >= 3? (face[2] - face[1]).Cross(face[0] - face[1]).Normalized() : Vec3::sZero();
  415. Vec3 displacement = 0.001f * normal;
  416. // Transform face to world space and calculate center of mass
  417. Vec3 com_ls = Vec3::sZero();
  418. for (Vec3 &v : face)
  419. {
  420. v = inCenterOfMassTransform.Multiply3x3(v + displacement);
  421. com_ls += v;
  422. }
  423. RVec3 com = inCenterOfMassTransform.GetTranslation() + com_ls / (float)face.size();
  424. // Draw the polygon and directions
  425. inRenderer->DrawWirePolygon(RMat44::sTranslation(inCenterOfMassTransform.GetTranslation()), face, color, face.size() >= 3? 0.001f : 0.0f);
  426. if (face.size() >= 3)
  427. inRenderer->DrawArrow(com, com + inCenterOfMassTransform.Multiply3x3(normal), color, 0.01f);
  428. for (Vec3 &v : ftd.second)
  429. inRenderer->DrawArrow(com, com + inCenterOfMassTransform.Multiply3x3(-v), color, 0.001f);
  430. }
  431. }
  432. #endif // JPH_DEBUG_RENDERER
  433. void ConvexShape::SaveBinaryState(StreamOut &inStream) const
  434. {
  435. Shape::SaveBinaryState(inStream);
  436. inStream.Write(mDensity);
  437. }
  438. void ConvexShape::RestoreBinaryState(StreamIn &inStream)
  439. {
  440. Shape::RestoreBinaryState(inStream);
  441. inStream.Read(mDensity);
  442. }
  443. void ConvexShape::SaveMaterialState(PhysicsMaterialList &outMaterials) const
  444. {
  445. outMaterials.clear();
  446. outMaterials.push_back(mMaterial);
  447. }
  448. void ConvexShape::RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials)
  449. {
  450. JPH_ASSERT(inNumMaterials == 1);
  451. mMaterial = inMaterials[0];
  452. }
  453. void ConvexShape::sRegister()
  454. {
  455. for (EShapeSubType s1 : sConvexSubShapeTypes)
  456. for (EShapeSubType s2 : sConvexSubShapeTypes)
  457. {
  458. CollisionDispatch::sRegisterCollideShape(s1, s2, sCollideConvexVsConvex);
  459. CollisionDispatch::sRegisterCastShape(s1, s2, sCastConvexVsConvex);
  460. }
  461. }
  462. JPH_NAMESPACE_END