CompoundShape.cpp 14 KB

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