CompoundShape.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 senter 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::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  210. {
  211. for (const SubShape &shape : mSubShapes)
  212. shape.mShape->TransformShape(inCenterOfMassTransform * Mat44::sRotationTranslation(shape.GetRotation(), shape.GetPositionCOM()), ioCollector);
  213. }
  214. 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)
  215. {
  216. JPH_PROFILE_FUNCTION();
  217. // Fetch compound shape from cast shape
  218. JPH_ASSERT(inShapeCast.mShape->GetType() == EShapeType::Compound);
  219. const CompoundShape *compound = static_cast<const CompoundShape *>(inShapeCast.mShape);
  220. // Number of sub shapes
  221. int n = (int)compound->mSubShapes.size();
  222. // Determine amount of bits for sub shape
  223. uint sub_shape_bits = compound->GetSubShapeIDBits();
  224. // Recurse to sub shapes
  225. for (int i = 0; i < n; ++i)
  226. {
  227. const SubShape &shape = compound->mSubShapes[i];
  228. // Create ID for sub shape
  229. SubShapeIDCreator shape1_sub_shape_id = inSubShapeIDCreator1.PushID(i, sub_shape_bits);
  230. // Transform the shape cast and update the shape
  231. Mat44 transform = inShapeCast.mCenterOfMassStart * shape.GetLocalTransformNoScale(inShapeCast.mScale);
  232. Vec3 scale = shape.TransformScale(inShapeCast.mScale);
  233. ShapeCast shape_cast(shape.mShape, scale, transform, inShapeCast.mDirection);
  234. CollisionDispatch::sCastShapeVsShapeLocalSpace(shape_cast, inShapeCastSettings, inShape, inScale, inShapeFilter, inCenterOfMassTransform2, shape1_sub_shape_id, inSubShapeIDCreator2, ioCollector);
  235. if (ioCollector.ShouldEarlyOut())
  236. break;
  237. }
  238. }
  239. void CompoundShape::SaveBinaryState(StreamOut &inStream) const
  240. {
  241. Shape::SaveBinaryState(inStream);
  242. inStream.Write(mCenterOfMass);
  243. inStream.Write(mLocalBounds.mMin);
  244. inStream.Write(mLocalBounds.mMax);
  245. inStream.Write(mInnerRadius);
  246. // Write sub shapes
  247. size_t len = mSubShapes.size();
  248. inStream.Write(len);
  249. if (!inStream.IsFailed())
  250. for (size_t i = 0; i < len; ++i)
  251. {
  252. const SubShape &s = mSubShapes[i];
  253. inStream.Write(s.mUserData);
  254. inStream.Write(s.mPositionCOM);
  255. inStream.Write(s.mRotation);
  256. }
  257. }
  258. void CompoundShape::RestoreBinaryState(StreamIn &inStream)
  259. {
  260. Shape::RestoreBinaryState(inStream);
  261. inStream.Read(mCenterOfMass);
  262. inStream.Read(mLocalBounds.mMin);
  263. inStream.Read(mLocalBounds.mMax);
  264. inStream.Read(mInnerRadius);
  265. // Read sub shapes
  266. size_t len = 0;
  267. inStream.Read(len);
  268. if (!inStream.IsEOF() && !inStream.IsFailed())
  269. {
  270. mSubShapes.resize(len);
  271. for (size_t i = 0; i < len; ++i)
  272. {
  273. SubShape &s = mSubShapes[i];
  274. inStream.Read(s.mUserData);
  275. inStream.Read(s.mPositionCOM);
  276. inStream.Read(s.mRotation);
  277. s.mIsRotationIdentity = s.mRotation == Float3(0, 0, 0);
  278. }
  279. }
  280. }
  281. void CompoundShape::SaveSubShapeState(ShapeList &outSubShapes) const
  282. {
  283. outSubShapes.clear();
  284. outSubShapes.reserve(mSubShapes.size());
  285. for (const SubShape &shape : mSubShapes)
  286. outSubShapes.push_back(shape.mShape);
  287. }
  288. void CompoundShape::RestoreSubShapeState(const ShapeRefC *inSubShapes, uint inNumShapes)
  289. {
  290. JPH_ASSERT(mSubShapes.size() == inNumShapes);
  291. for (uint i = 0; i < inNumShapes; ++i)
  292. mSubShapes[i].mShape = inSubShapes[i];
  293. }
  294. Shape::Stats CompoundShape::GetStatsRecursive(VisitedShapes &ioVisitedShapes) const
  295. {
  296. // Get own stats
  297. Stats stats = Shape::GetStatsRecursive(ioVisitedShapes);
  298. // Add child stats
  299. for (const SubShape &shape : mSubShapes)
  300. {
  301. Stats child_stats = shape.mShape->GetStatsRecursive(ioVisitedShapes);
  302. stats.mSizeBytes += child_stats.mSizeBytes;
  303. stats.mNumTriangles += child_stats.mNumTriangles;
  304. }
  305. return stats;
  306. }
  307. float CompoundShape::GetVolume() const
  308. {
  309. float volume = 0.0f;
  310. for (const SubShape &shape : mSubShapes)
  311. volume += shape.mShape->GetVolume();
  312. return volume;
  313. }
  314. bool CompoundShape::IsValidScale(Vec3Arg inScale) const
  315. {
  316. if (!Shape::IsValidScale(inScale))
  317. return false;
  318. for (const SubShape &shape : mSubShapes)
  319. {
  320. // Test if the scale is non-uniform and the shape is rotated
  321. if (!shape.IsValidScale(inScale))
  322. return false;
  323. // Test the child shape
  324. if (!shape.mShape->IsValidScale(shape.TransformScale(inScale)))
  325. return false;
  326. }
  327. return true;
  328. }
  329. void CompoundShape::sRegister()
  330. {
  331. for (EShapeSubType s1 : sCompoundSubShapeTypes)
  332. for (EShapeSubType s2 : sAllSubShapeTypes)
  333. CollisionDispatch::sRegisterCastShape(s1, s2, sCastCompoundVsShape);
  334. }
  335. JPH_NAMESPACE_END