CompoundShape.cpp 13 KB

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