CompoundShape.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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/CompoundShape.h>
  6. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  7. #include <Jolt/Physics/Collision/ShapeCast.h>
  8. #include <Jolt/Physics/Collision/CastResult.h>
  9. #include <Jolt/Physics/Collision/TransformedShape.h>
  10. #include <Jolt/Core/Profiler.h>
  11. #include <Jolt/Core/StreamIn.h>
  12. #include <Jolt/Core/StreamOut.h>
  13. #include <Jolt/ObjectStream/TypeDeclarations.h>
  14. #ifdef JPH_DEBUG_RENDERER
  15. #include <Jolt/Renderer/DebugRenderer.h>
  16. #endif // JPH_DEBUG_RENDERER
  17. JPH_NAMESPACE_BEGIN
  18. JPH_IMPLEMENT_SERIALIZABLE_ABSTRACT(CompoundShapeSettings)
  19. {
  20. JPH_ADD_BASE_CLASS(CompoundShapeSettings, ShapeSettings)
  21. JPH_ADD_ATTRIBUTE(CompoundShapeSettings, mSubShapes)
  22. }
  23. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(CompoundShapeSettings::SubShapeSettings)
  24. {
  25. JPH_ADD_ATTRIBUTE(CompoundShapeSettings::SubShapeSettings, mShape)
  26. JPH_ADD_ATTRIBUTE(CompoundShapeSettings::SubShapeSettings, mPosition)
  27. JPH_ADD_ATTRIBUTE(CompoundShapeSettings::SubShapeSettings, mRotation)
  28. JPH_ADD_ATTRIBUTE(CompoundShapeSettings::SubShapeSettings, mUserData)
  29. }
  30. void CompoundShapeSettings::AddShape(Vec3Arg inPosition, QuatArg inRotation, const ShapeSettings *inShape, uint32 inUserData)
  31. {
  32. // Add shape
  33. SubShapeSettings shape;
  34. shape.mPosition = inPosition;
  35. shape.mRotation = inRotation;
  36. shape.mShape = inShape;
  37. shape.mUserData = inUserData;
  38. mSubShapes.push_back(shape);
  39. }
  40. void CompoundShapeSettings::AddShape(Vec3Arg inPosition, QuatArg inRotation, const Shape *inShape, uint32 inUserData)
  41. {
  42. // Add shape
  43. SubShapeSettings shape;
  44. shape.mPosition = inPosition;
  45. shape.mRotation = inRotation;
  46. shape.mShapePtr = inShape;
  47. shape.mUserData = inUserData;
  48. mSubShapes.push_back(shape);
  49. }
  50. bool CompoundShape::MustBeStatic() const
  51. {
  52. for (const SubShape &shape : mSubShapes)
  53. if (shape.mShape->MustBeStatic())
  54. return true;
  55. return false;
  56. }
  57. MassProperties CompoundShape::GetMassProperties() const
  58. {
  59. MassProperties p;
  60. // Calculate mass and inertia
  61. p.mMass = 0.0f;
  62. p.mInertia = Mat44::sZero();
  63. for (const SubShape &shape : mSubShapes)
  64. {
  65. // Rotate and translate inertia of child into place
  66. MassProperties child = shape.mShape->GetMassProperties();
  67. child.Rotate(Mat44::sRotation(shape.GetRotation()));
  68. child.Translate(shape.GetPositionCOM());
  69. // Accumulate mass and inertia
  70. p.mMass += child.mMass;
  71. p.mInertia += child.mInertia;
  72. }
  73. // Ensure that inertia is a 3x3 matrix, adding inertias causes the bottom right element to change
  74. p.mInertia.SetColumn4(3, Vec4(0, 0, 0, 1));
  75. return p;
  76. }
  77. AABox CompoundShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  78. {
  79. if (mSubShapes.size() <= 10)
  80. {
  81. AABox bounds;
  82. for (const SubShape &shape : mSubShapes)
  83. {
  84. Mat44 transform = inCenterOfMassTransform * shape.GetLocalTransformNoScale(inScale);
  85. bounds.Encapsulate(shape.mShape->GetWorldSpaceBounds(transform, shape.TransformScale(inScale)));
  86. }
  87. return bounds;
  88. }
  89. else
  90. {
  91. // If there are too many shapes, use the base class function (this will result in a slightly wider bounding box)
  92. return Shape::GetWorldSpaceBounds(inCenterOfMassTransform, inScale);
  93. }
  94. }
  95. uint CompoundShape::GetSubShapeIDBitsRecursive() const
  96. {
  97. // Add max of child bits to our bits
  98. uint child_bits = 0;
  99. for (const SubShape &shape : mSubShapes)
  100. child_bits = max(child_bits, shape.mShape->GetSubShapeIDBitsRecursive());
  101. return child_bits + GetSubShapeIDBits();
  102. }
  103. const PhysicsMaterial *CompoundShape::GetMaterial(const SubShapeID &inSubShapeID) const
  104. {
  105. // Decode sub shape index
  106. SubShapeID remainder;
  107. uint32 index = GetSubShapeIndexFromID(inSubShapeID, remainder);
  108. // Pass call on
  109. return mSubShapes[index].mShape->GetMaterial(remainder);
  110. }
  111. const Shape *CompoundShape::GetLeafShape(const SubShapeID &inSubShapeID, SubShapeID &outRemainder) const
  112. {
  113. // Decode sub shape index
  114. SubShapeID remainder;
  115. uint32 index = GetSubShapeIndexFromID(inSubShapeID, remainder);
  116. if (index >= mSubShapes.size())
  117. {
  118. // No longer valid index
  119. outRemainder = SubShapeID();
  120. return nullptr;
  121. }
  122. // Pass call on
  123. return mSubShapes[index].mShape->GetLeafShape(remainder, outRemainder);
  124. }
  125. uint64 CompoundShape::GetSubShapeUserData(const SubShapeID &inSubShapeID) const
  126. {
  127. // Decode sub shape index
  128. SubShapeID remainder;
  129. uint32 index = GetSubShapeIndexFromID(inSubShapeID, remainder);
  130. if (index >= mSubShapes.size())
  131. return 0; // No longer valid index
  132. // Pass call on
  133. return mSubShapes[index].mShape->GetSubShapeUserData(remainder);
  134. }
  135. TransformedShape CompoundShape::GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, SubShapeID &outRemainder) const
  136. {
  137. // Get the sub shape
  138. const SubShape &sub_shape = mSubShapes[GetSubShapeIndexFromID(inSubShapeID, outRemainder)];
  139. // Calculate transform for sub shape
  140. Vec3 position = inPositionCOM + inRotation * (inScale * sub_shape.GetPositionCOM());
  141. Quat rotation = inRotation * sub_shape.GetRotation();
  142. Vec3 scale = sub_shape.TransformScale(inScale);
  143. // Return transformed shape
  144. TransformedShape ts(RVec3(position), rotation, sub_shape.mShape, BodyID());
  145. ts.SetShapeScale(scale);
  146. return ts;
  147. }
  148. Vec3 CompoundShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  149. {
  150. // Decode sub shape index
  151. SubShapeID remainder;
  152. uint32 index = GetSubShapeIndexFromID(inSubShapeID, remainder);
  153. // Transform surface position to local space and pass call on
  154. const SubShape &shape = mSubShapes[index];
  155. Mat44 transform = Mat44::sInverseRotationTranslation(shape.GetRotation(), shape.GetPositionCOM());
  156. Vec3 normal = shape.mShape->GetSurfaceNormal(remainder, transform * inLocalSurfacePosition);
  157. // Transform normal to this shape's space
  158. return transform.Multiply3x3Transposed(normal);
  159. }
  160. void CompoundShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  161. {
  162. // Decode sub shape index
  163. SubShapeID remainder;
  164. uint32 index = GetSubShapeIndexFromID(inSubShapeID, remainder);
  165. // Apply transform and pass on to sub shape
  166. const SubShape &shape = mSubShapes[index];
  167. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  168. shape.mShape->GetSupportingFace(remainder, transform.Multiply3x3Transposed(inDirection), shape.TransformScale(inScale), inCenterOfMassTransform * transform, outVertices);
  169. }
  170. void CompoundShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const
  171. {
  172. outTotalVolume = 0.0f;
  173. outSubmergedVolume = 0.0f;
  174. outCenterOfBuoyancy = Vec3::sZero();
  175. for (const SubShape &shape : mSubShapes)
  176. {
  177. // Get center of mass transform of child
  178. Mat44 transform = inCenterOfMassTransform * shape.GetLocalTransformNoScale(inScale);
  179. // Recurse to child
  180. float total_volume, submerged_volume;
  181. Vec3 center_of_buoyancy;
  182. shape.mShape->GetSubmergedVolume(transform, shape.TransformScale(inScale), inSurface, total_volume, submerged_volume, center_of_buoyancy JPH_IF_DEBUG_RENDERER(, inBaseOffset));
  183. // Accumulate volumes
  184. outTotalVolume += total_volume;
  185. outSubmergedVolume += submerged_volume;
  186. // The center of buoyancy is the weighted average of the center of buoyancy of our child shapes
  187. outCenterOfBuoyancy += submerged_volume * center_of_buoyancy;
  188. }
  189. if (outSubmergedVolume > 0.0f)
  190. outCenterOfBuoyancy /= outSubmergedVolume;
  191. #ifdef JPH_DEBUG_RENDERER
  192. // Draw center of buoyancy
  193. if (sDrawSubmergedVolumes)
  194. DebugRenderer::sInstance->DrawWireSphere(inBaseOffset + outCenterOfBuoyancy, 0.05f, Color::sRed, 1);
  195. #endif // JPH_DEBUG_RENDERER
  196. }
  197. #ifdef JPH_DEBUG_RENDERER
  198. void CompoundShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  199. {
  200. for (const SubShape &shape : mSubShapes)
  201. {
  202. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  203. shape.mShape->Draw(inRenderer, inCenterOfMassTransform * transform, shape.TransformScale(inScale), inColor, inUseMaterialColors, inDrawWireframe);
  204. }
  205. }
  206. void CompoundShape::DrawGetSupportFunction(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inDrawSupportDirection) const
  207. {
  208. for (const SubShape &shape : mSubShapes)
  209. {
  210. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  211. shape.mShape->DrawGetSupportFunction(inRenderer, inCenterOfMassTransform * transform, shape.TransformScale(inScale), inColor, inDrawSupportDirection);
  212. }
  213. }
  214. void CompoundShape::DrawGetSupportingFace(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  215. {
  216. for (const SubShape &shape : mSubShapes)
  217. {
  218. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  219. shape.mShape->DrawGetSupportingFace(inRenderer, inCenterOfMassTransform * transform, shape.TransformScale(inScale));
  220. }
  221. }
  222. #endif // JPH_DEBUG_RENDERER
  223. void CompoundShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, SoftBodyVertex *ioVertices, uint inNumVertices, float inDeltaTime, Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const
  224. {
  225. for (const SubShape &shape : mSubShapes)
  226. {
  227. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  228. shape.mShape->CollideSoftBodyVertices(inCenterOfMassTransform * transform, shape.TransformScale(inScale), ioVertices, inNumVertices, inDeltaTime, inDisplacementDueToGravity, inCollidingShapeIndex);
  229. }
  230. }
  231. void CompoundShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  232. {
  233. for (const SubShape &shape : mSubShapes)
  234. shape.mShape->TransformShape(inCenterOfMassTransform * Mat44::sRotationTranslation(shape.GetRotation(), shape.GetPositionCOM()), ioCollector);
  235. }
  236. void CompoundShape::sCastCompoundVsShape(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  237. {
  238. JPH_PROFILE_FUNCTION();
  239. // Fetch compound shape from cast shape
  240. JPH_ASSERT(inShapeCast.mShape->GetType() == EShapeType::Compound);
  241. const CompoundShape *compound = static_cast<const CompoundShape *>(inShapeCast.mShape);
  242. // Number of sub shapes
  243. int n = (int)compound->mSubShapes.size();
  244. // Determine amount of bits for sub shape
  245. uint sub_shape_bits = compound->GetSubShapeIDBits();
  246. // Recurse to sub shapes
  247. for (int i = 0; i < n; ++i)
  248. {
  249. const SubShape &shape = compound->mSubShapes[i];
  250. // Create ID for sub shape
  251. SubShapeIDCreator shape1_sub_shape_id = inSubShapeIDCreator1.PushID(i, sub_shape_bits);
  252. // Transform the shape cast and update the shape
  253. Mat44 transform = inShapeCast.mCenterOfMassStart * shape.GetLocalTransformNoScale(inShapeCast.mScale);
  254. Vec3 scale = shape.TransformScale(inShapeCast.mScale);
  255. ShapeCast shape_cast(shape.mShape, scale, transform, inShapeCast.mDirection);
  256. CollisionDispatch::sCastShapeVsShapeLocalSpace(shape_cast, inShapeCastSettings, inShape, inScale, inShapeFilter, inCenterOfMassTransform2, shape1_sub_shape_id, inSubShapeIDCreator2, ioCollector);
  257. if (ioCollector.ShouldEarlyOut())
  258. break;
  259. }
  260. }
  261. void CompoundShape::SaveBinaryState(StreamOut &inStream) const
  262. {
  263. Shape::SaveBinaryState(inStream);
  264. inStream.Write(mCenterOfMass);
  265. inStream.Write(mLocalBounds.mMin);
  266. inStream.Write(mLocalBounds.mMax);
  267. inStream.Write(mInnerRadius);
  268. // Write sub shapes
  269. inStream.Write(mSubShapes, [](const SubShape &inElement, StreamOut &inS) {
  270. inS.Write(inElement.mUserData);
  271. inS.Write(inElement.mPositionCOM);
  272. inS.Write(inElement.mRotation);
  273. });
  274. }
  275. void CompoundShape::RestoreBinaryState(StreamIn &inStream)
  276. {
  277. Shape::RestoreBinaryState(inStream);
  278. inStream.Read(mCenterOfMass);
  279. inStream.Read(mLocalBounds.mMin);
  280. inStream.Read(mLocalBounds.mMax);
  281. inStream.Read(mInnerRadius);
  282. // Read sub shapes
  283. inStream.Read(mSubShapes, [](StreamIn &inS, SubShape &outElement) {
  284. inS.Read(outElement.mUserData);
  285. inS.Read(outElement.mPositionCOM);
  286. inS.Read(outElement.mRotation);
  287. outElement.mIsRotationIdentity = outElement.mRotation == Float3(0, 0, 0);
  288. });
  289. }
  290. void CompoundShape::SaveSubShapeState(ShapeList &outSubShapes) const
  291. {
  292. outSubShapes.clear();
  293. outSubShapes.reserve(mSubShapes.size());
  294. for (const SubShape &shape : mSubShapes)
  295. outSubShapes.push_back(shape.mShape);
  296. }
  297. void CompoundShape::RestoreSubShapeState(const ShapeRefC *inSubShapes, uint inNumShapes)
  298. {
  299. JPH_ASSERT(mSubShapes.size() == inNumShapes);
  300. for (uint i = 0; i < inNumShapes; ++i)
  301. mSubShapes[i].mShape = inSubShapes[i];
  302. }
  303. Shape::Stats CompoundShape::GetStatsRecursive(VisitedShapes &ioVisitedShapes) const
  304. {
  305. // Get own stats
  306. Stats stats = Shape::GetStatsRecursive(ioVisitedShapes);
  307. // Add child stats
  308. for (const SubShape &shape : mSubShapes)
  309. {
  310. Stats child_stats = shape.mShape->GetStatsRecursive(ioVisitedShapes);
  311. stats.mSizeBytes += child_stats.mSizeBytes;
  312. stats.mNumTriangles += child_stats.mNumTriangles;
  313. }
  314. return stats;
  315. }
  316. float CompoundShape::GetVolume() const
  317. {
  318. float volume = 0.0f;
  319. for (const SubShape &shape : mSubShapes)
  320. volume += shape.mShape->GetVolume();
  321. return volume;
  322. }
  323. bool CompoundShape::IsValidScale(Vec3Arg inScale) const
  324. {
  325. if (!Shape::IsValidScale(inScale))
  326. return false;
  327. for (const SubShape &shape : mSubShapes)
  328. {
  329. // Test if the scale is non-uniform and the shape is rotated
  330. if (!shape.IsValidScale(inScale))
  331. return false;
  332. // Test the child shape
  333. if (!shape.mShape->IsValidScale(shape.TransformScale(inScale)))
  334. return false;
  335. }
  336. return true;
  337. }
  338. Vec3 CompoundShape::MakeScaleValid(Vec3Arg inScale) const
  339. {
  340. Vec3 scale = ScaleHelpers::MakeNonZeroScale(inScale);
  341. if (CompoundShape::IsValidScale(scale))
  342. return scale;
  343. Vec3 abs_uniform_scale = ScaleHelpers::MakeUniformScale(scale.Abs());
  344. Vec3 uniform_scale = scale.GetSign() * abs_uniform_scale;
  345. if (CompoundShape::IsValidScale(uniform_scale))
  346. return uniform_scale;
  347. return Sign(scale.GetX()) * abs_uniform_scale;
  348. }
  349. void CompoundShape::sRegister()
  350. {
  351. for (EShapeSubType s1 : sCompoundSubShapeTypes)
  352. for (EShapeSubType s2 : sAllSubShapeTypes)
  353. CollisionDispatch::sRegisterCastShape(s1, s2, sCastCompoundVsShape);
  354. }
  355. JPH_NAMESPACE_END