CompoundShape.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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.empty())
  80. {
  81. // If there are no sub-shapes, we must return an empty box to avoid overflows in the broadphase
  82. return AABox(inCenterOfMassTransform.GetTranslation(), inCenterOfMassTransform.GetTranslation());
  83. }
  84. else if (mSubShapes.size() <= 10)
  85. {
  86. AABox bounds;
  87. for (const SubShape &shape : mSubShapes)
  88. {
  89. Mat44 transform = inCenterOfMassTransform * shape.GetLocalTransformNoScale(inScale);
  90. bounds.Encapsulate(shape.mShape->GetWorldSpaceBounds(transform, shape.TransformScale(inScale)));
  91. }
  92. return bounds;
  93. }
  94. else
  95. {
  96. // If there are too many shapes, use the base class function (this will result in a slightly wider bounding box)
  97. return Shape::GetWorldSpaceBounds(inCenterOfMassTransform, inScale);
  98. }
  99. }
  100. uint CompoundShape::GetSubShapeIDBitsRecursive() const
  101. {
  102. // Add max of child bits to our bits
  103. uint child_bits = 0;
  104. for (const SubShape &shape : mSubShapes)
  105. child_bits = max(child_bits, shape.mShape->GetSubShapeIDBitsRecursive());
  106. return child_bits + GetSubShapeIDBits();
  107. }
  108. const PhysicsMaterial *CompoundShape::GetMaterial(const SubShapeID &inSubShapeID) const
  109. {
  110. // Decode sub shape index
  111. SubShapeID remainder;
  112. uint32 index = GetSubShapeIndexFromID(inSubShapeID, remainder);
  113. // Pass call on
  114. return mSubShapes[index].mShape->GetMaterial(remainder);
  115. }
  116. const Shape *CompoundShape::GetLeafShape(const SubShapeID &inSubShapeID, SubShapeID &outRemainder) const
  117. {
  118. // Decode sub shape index
  119. SubShapeID remainder;
  120. uint32 index = GetSubShapeIndexFromID(inSubShapeID, remainder);
  121. if (index >= mSubShapes.size())
  122. {
  123. // No longer valid index
  124. outRemainder = SubShapeID();
  125. return nullptr;
  126. }
  127. // Pass call on
  128. return mSubShapes[index].mShape->GetLeafShape(remainder, outRemainder);
  129. }
  130. uint64 CompoundShape::GetSubShapeUserData(const SubShapeID &inSubShapeID) const
  131. {
  132. // Decode sub shape index
  133. SubShapeID remainder;
  134. uint32 index = GetSubShapeIndexFromID(inSubShapeID, remainder);
  135. if (index >= mSubShapes.size())
  136. return 0; // No longer valid index
  137. // Pass call on
  138. return mSubShapes[index].mShape->GetSubShapeUserData(remainder);
  139. }
  140. TransformedShape CompoundShape::GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, SubShapeID &outRemainder) const
  141. {
  142. // Get the sub shape
  143. const SubShape &sub_shape = mSubShapes[GetSubShapeIndexFromID(inSubShapeID, outRemainder)];
  144. // Calculate transform for sub shape
  145. Vec3 position = inPositionCOM + inRotation * (inScale * sub_shape.GetPositionCOM());
  146. Quat rotation = inRotation * sub_shape.GetRotation();
  147. Vec3 scale = sub_shape.TransformScale(inScale);
  148. // Return transformed shape
  149. TransformedShape ts(RVec3(position), rotation, sub_shape.mShape, BodyID());
  150. ts.SetShapeScale(scale);
  151. return ts;
  152. }
  153. Vec3 CompoundShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  154. {
  155. // Decode sub shape index
  156. SubShapeID remainder;
  157. uint32 index = GetSubShapeIndexFromID(inSubShapeID, remainder);
  158. // Transform surface position to local space and pass call on
  159. const SubShape &shape = mSubShapes[index];
  160. Mat44 transform = Mat44::sInverseRotationTranslation(shape.GetRotation(), shape.GetPositionCOM());
  161. Vec3 normal = shape.mShape->GetSurfaceNormal(remainder, transform * inLocalSurfacePosition);
  162. // Transform normal to this shape's space
  163. return transform.Multiply3x3Transposed(normal);
  164. }
  165. void CompoundShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  166. {
  167. // Decode sub shape index
  168. SubShapeID remainder;
  169. uint32 index = GetSubShapeIndexFromID(inSubShapeID, remainder);
  170. // Apply transform and pass on to sub shape
  171. const SubShape &shape = mSubShapes[index];
  172. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  173. shape.mShape->GetSupportingFace(remainder, transform.Multiply3x3Transposed(inDirection), shape.TransformScale(inScale), inCenterOfMassTransform * transform, outVertices);
  174. }
  175. void CompoundShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const
  176. {
  177. outTotalVolume = 0.0f;
  178. outSubmergedVolume = 0.0f;
  179. outCenterOfBuoyancy = Vec3::sZero();
  180. for (const SubShape &shape : mSubShapes)
  181. {
  182. // Get center of mass transform of child
  183. Mat44 transform = inCenterOfMassTransform * shape.GetLocalTransformNoScale(inScale);
  184. // Recurse to child
  185. float total_volume, submerged_volume;
  186. Vec3 center_of_buoyancy;
  187. shape.mShape->GetSubmergedVolume(transform, shape.TransformScale(inScale), inSurface, total_volume, submerged_volume, center_of_buoyancy JPH_IF_DEBUG_RENDERER(, inBaseOffset));
  188. // Accumulate volumes
  189. outTotalVolume += total_volume;
  190. outSubmergedVolume += submerged_volume;
  191. // The center of buoyancy is the weighted average of the center of buoyancy of our child shapes
  192. outCenterOfBuoyancy += submerged_volume * center_of_buoyancy;
  193. }
  194. if (outSubmergedVolume > 0.0f)
  195. outCenterOfBuoyancy /= outSubmergedVolume;
  196. #ifdef JPH_DEBUG_RENDERER
  197. // Draw center of buoyancy
  198. if (sDrawSubmergedVolumes)
  199. DebugRenderer::sInstance->DrawWireSphere(inBaseOffset + outCenterOfBuoyancy, 0.05f, Color::sRed, 1);
  200. #endif // JPH_DEBUG_RENDERER
  201. }
  202. #ifdef JPH_DEBUG_RENDERER
  203. void CompoundShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  204. {
  205. for (const SubShape &shape : mSubShapes)
  206. {
  207. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  208. shape.mShape->Draw(inRenderer, inCenterOfMassTransform * transform, shape.TransformScale(inScale), inColor, inUseMaterialColors, inDrawWireframe);
  209. }
  210. }
  211. void CompoundShape::DrawGetSupportFunction(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inDrawSupportDirection) const
  212. {
  213. for (const SubShape &shape : mSubShapes)
  214. {
  215. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  216. shape.mShape->DrawGetSupportFunction(inRenderer, inCenterOfMassTransform * transform, shape.TransformScale(inScale), inColor, inDrawSupportDirection);
  217. }
  218. }
  219. void CompoundShape::DrawGetSupportingFace(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  220. {
  221. for (const SubShape &shape : mSubShapes)
  222. {
  223. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  224. shape.mShape->DrawGetSupportingFace(inRenderer, inCenterOfMassTransform * transform, shape.TransformScale(inScale));
  225. }
  226. }
  227. #endif // JPH_DEBUG_RENDERER
  228. void CompoundShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const
  229. {
  230. for (const SubShape &shape : mSubShapes)
  231. {
  232. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  233. shape.mShape->CollideSoftBodyVertices(inCenterOfMassTransform * transform, shape.TransformScale(inScale), inVertices, inNumVertices, inCollidingShapeIndex);
  234. }
  235. }
  236. void CompoundShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  237. {
  238. for (const SubShape &shape : mSubShapes)
  239. shape.mShape->TransformShape(inCenterOfMassTransform * Mat44::sRotationTranslation(shape.GetRotation(), shape.GetPositionCOM()), ioCollector);
  240. }
  241. 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)
  242. {
  243. JPH_PROFILE_FUNCTION();
  244. // Fetch compound shape from cast shape
  245. JPH_ASSERT(inShapeCast.mShape->GetType() == EShapeType::Compound);
  246. const CompoundShape *compound = static_cast<const CompoundShape *>(inShapeCast.mShape);
  247. // Number of sub shapes
  248. int n = (int)compound->mSubShapes.size();
  249. // Determine amount of bits for sub shape
  250. uint sub_shape_bits = compound->GetSubShapeIDBits();
  251. // Recurse to sub shapes
  252. for (int i = 0; i < n; ++i)
  253. {
  254. const SubShape &shape = compound->mSubShapes[i];
  255. // Create ID for sub shape
  256. SubShapeIDCreator shape1_sub_shape_id = inSubShapeIDCreator1.PushID(i, sub_shape_bits);
  257. // Transform the shape cast and update the shape
  258. Mat44 transform = inShapeCast.mCenterOfMassStart * shape.GetLocalTransformNoScale(inShapeCast.mScale);
  259. Vec3 scale = shape.TransformScale(inShapeCast.mScale);
  260. ShapeCast shape_cast(shape.mShape, scale, transform, inShapeCast.mDirection);
  261. CollisionDispatch::sCastShapeVsShapeLocalSpace(shape_cast, inShapeCastSettings, inShape, inScale, inShapeFilter, inCenterOfMassTransform2, shape1_sub_shape_id, inSubShapeIDCreator2, ioCollector);
  262. if (ioCollector.ShouldEarlyOut())
  263. break;
  264. }
  265. }
  266. void CompoundShape::SaveBinaryState(StreamOut &inStream) const
  267. {
  268. Shape::SaveBinaryState(inStream);
  269. inStream.Write(mCenterOfMass);
  270. inStream.Write(mLocalBounds.mMin);
  271. inStream.Write(mLocalBounds.mMax);
  272. inStream.Write(mInnerRadius);
  273. // Write sub shapes
  274. inStream.Write(mSubShapes, [](const SubShape &inElement, StreamOut &inS) {
  275. inS.Write(inElement.mUserData);
  276. inS.Write(inElement.mPositionCOM);
  277. inS.Write(inElement.mRotation);
  278. });
  279. }
  280. void CompoundShape::RestoreBinaryState(StreamIn &inStream)
  281. {
  282. Shape::RestoreBinaryState(inStream);
  283. inStream.Read(mCenterOfMass);
  284. inStream.Read(mLocalBounds.mMin);
  285. inStream.Read(mLocalBounds.mMax);
  286. inStream.Read(mInnerRadius);
  287. // Read sub shapes
  288. inStream.Read(mSubShapes, [](StreamIn &inS, SubShape &outElement) {
  289. inS.Read(outElement.mUserData);
  290. inS.Read(outElement.mPositionCOM);
  291. inS.Read(outElement.mRotation);
  292. outElement.mIsRotationIdentity = outElement.mRotation == Float3(0, 0, 0);
  293. });
  294. }
  295. void CompoundShape::SaveSubShapeState(ShapeList &outSubShapes) const
  296. {
  297. outSubShapes.clear();
  298. outSubShapes.reserve(mSubShapes.size());
  299. for (const SubShape &shape : mSubShapes)
  300. outSubShapes.push_back(shape.mShape);
  301. }
  302. void CompoundShape::RestoreSubShapeState(const ShapeRefC *inSubShapes, uint inNumShapes)
  303. {
  304. JPH_ASSERT(mSubShapes.size() == inNumShapes);
  305. for (uint i = 0; i < inNumShapes; ++i)
  306. mSubShapes[i].mShape = inSubShapes[i];
  307. }
  308. Shape::Stats CompoundShape::GetStatsRecursive(VisitedShapes &ioVisitedShapes) const
  309. {
  310. // Get own stats
  311. Stats stats = Shape::GetStatsRecursive(ioVisitedShapes);
  312. // Add child stats
  313. for (const SubShape &shape : mSubShapes)
  314. {
  315. Stats child_stats = shape.mShape->GetStatsRecursive(ioVisitedShapes);
  316. stats.mSizeBytes += child_stats.mSizeBytes;
  317. stats.mNumTriangles += child_stats.mNumTriangles;
  318. }
  319. return stats;
  320. }
  321. float CompoundShape::GetVolume() const
  322. {
  323. float volume = 0.0f;
  324. for (const SubShape &shape : mSubShapes)
  325. volume += shape.mShape->GetVolume();
  326. return volume;
  327. }
  328. bool CompoundShape::IsValidScale(Vec3Arg inScale) const
  329. {
  330. if (!Shape::IsValidScale(inScale))
  331. return false;
  332. for (const SubShape &shape : mSubShapes)
  333. {
  334. // Test if the scale is non-uniform and the shape is rotated
  335. if (!shape.IsValidScale(inScale))
  336. return false;
  337. // Test the child shape
  338. if (!shape.mShape->IsValidScale(shape.TransformScale(inScale)))
  339. return false;
  340. }
  341. return true;
  342. }
  343. Vec3 CompoundShape::MakeScaleValid(Vec3Arg inScale) const
  344. {
  345. Vec3 scale = ScaleHelpers::MakeNonZeroScale(inScale);
  346. if (CompoundShape::IsValidScale(scale))
  347. return scale;
  348. Vec3 abs_uniform_scale = ScaleHelpers::MakeUniformScale(scale.Abs());
  349. Vec3 uniform_scale = scale.GetSign() * abs_uniform_scale;
  350. if (CompoundShape::IsValidScale(uniform_scale))
  351. return uniform_scale;
  352. return Sign(scale.GetX()) * abs_uniform_scale;
  353. }
  354. void CompoundShape::sRegister()
  355. {
  356. for (EShapeSubType s1 : sCompoundSubShapeTypes)
  357. for (EShapeSubType s2 : sAllSubShapeTypes)
  358. CollisionDispatch::sRegisterCastShape(s1, s2, sCastCompoundVsShape);
  359. }
  360. JPH_NAMESPACE_END