CompoundShape.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt.h>
  4. #include <Physics/Collision/Shape/CompoundShape.h>
  5. #include <Physics/Collision/CollisionDispatch.h>
  6. #include <Physics/Collision/ShapeCast.h>
  7. #include <Physics/Collision/CastResult.h>
  8. #include <Physics/Collision/TransformedShape.h>
  9. #include <Core/Profiler.h>
  10. #include <Core/StreamIn.h>
  11. #include <Core/StreamOut.h>
  12. #include <ObjectStream/TypeDeclarations.h>
  13. #ifdef JPH_DEBUG_RENDERER
  14. #include <Renderer/DebugRenderer.h>
  15. #endif // JPH_DEBUG_RENDERER
  16. namespace JPH {
  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. uint32 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::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy) const
  146. {
  147. outTotalVolume = 0.0f;
  148. outSubmergedVolume = 0.0f;
  149. outCenterOfBuoyancy = Vec3::sZero();
  150. for (const SubShape &shape : mSubShapes)
  151. {
  152. // Get center of mass transform of child
  153. Mat44 transform = inCenterOfMassTransform * shape.GetLocalTransformNoScale(inScale);
  154. // Recurse to child
  155. float total_volume, submerged_volume;
  156. Vec3 center_of_buoyancy;
  157. shape.mShape->GetSubmergedVolume(transform, shape.TransformScale(inScale), inSurface, total_volume, submerged_volume, center_of_buoyancy);
  158. // Accumulate volumes
  159. outTotalVolume += total_volume;
  160. outSubmergedVolume += submerged_volume;
  161. // The center of buoyancy is the weighted average of the center of buoyancy of our child shapes
  162. outCenterOfBuoyancy += submerged_volume * center_of_buoyancy;
  163. }
  164. if (outSubmergedVolume > 0.0f)
  165. outCenterOfBuoyancy /= outSubmergedVolume;
  166. #ifdef JPH_DEBUG_RENDERER
  167. // Draw senter of buoyancy
  168. if (sDrawSubmergedVolumes)
  169. DebugRenderer::sInstance->DrawWireSphere(outCenterOfBuoyancy, 0.05f, Color::sRed, 1);
  170. #endif // JPH_DEBUG_RENDERER
  171. }
  172. #ifdef JPH_DEBUG_RENDERER
  173. void CompoundShape::Draw(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  174. {
  175. for (const SubShape &shape : mSubShapes)
  176. {
  177. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  178. shape.mShape->Draw(inRenderer, inCenterOfMassTransform * transform, shape.TransformScale(inScale), inColor, inUseMaterialColors, inDrawWireframe);
  179. }
  180. }
  181. void CompoundShape::DrawGetSupportFunction(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inDrawSupportDirection) const
  182. {
  183. for (const SubShape &shape : mSubShapes)
  184. {
  185. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  186. shape.mShape->DrawGetSupportFunction(inRenderer, inCenterOfMassTransform * transform, shape.TransformScale(inScale), inColor, inDrawSupportDirection);
  187. }
  188. }
  189. void CompoundShape::DrawGetSupportingFace(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  190. {
  191. for (const SubShape &shape : mSubShapes)
  192. {
  193. Mat44 transform = shape.GetLocalTransformNoScale(inScale);
  194. shape.mShape->DrawGetSupportingFace(inRenderer, inCenterOfMassTransform * transform, shape.TransformScale(inScale));
  195. }
  196. }
  197. #endif // JPH_DEBUG_RENDERER
  198. void CompoundShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  199. {
  200. for (const SubShape &shape : mSubShapes)
  201. shape.mShape->TransformShape(inCenterOfMassTransform * Mat44::sRotationTranslation(shape.GetRotation(), shape.GetPositionCOM()), ioCollector);
  202. }
  203. 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)
  204. {
  205. JPH_PROFILE_FUNCTION();
  206. // Fetch compound shape from cast shape
  207. JPH_ASSERT(inShapeCast.mShape->GetType() == EShapeType::Compound);
  208. const CompoundShape *compound = static_cast<const CompoundShape *>(inShapeCast.mShape);
  209. // Number of sub shapes
  210. int n = (int)compound->mSubShapes.size();
  211. // Determine amount of bits for sub shape
  212. uint sub_shape_bits = compound->GetSubShapeIDBits();
  213. // Recurse to sub shapes
  214. for (int i = 0; i < n; ++i)
  215. {
  216. const SubShape &shape = compound->mSubShapes[i];
  217. // Create ID for sub shape
  218. SubShapeIDCreator shape1_sub_shape_id = inSubShapeIDCreator1.PushID(i, sub_shape_bits);
  219. // Transform the shape cast and update the shape
  220. Mat44 transform = inShapeCast.mCenterOfMassStart * shape.GetLocalTransformNoScale(inShapeCast.mScale);
  221. Vec3 scale = shape.TransformScale(inShapeCast.mScale);
  222. ShapeCast shape_cast(shape.mShape, scale, transform, inShapeCast.mDirection);
  223. CollisionDispatch::sCastShapeVsShape(shape_cast, inShapeCastSettings, inShape, inScale, inShapeFilter, inCenterOfMassTransform2, shape1_sub_shape_id, inSubShapeIDCreator2, ioCollector);
  224. if (ioCollector.ShouldEarlyOut())
  225. break;
  226. }
  227. }
  228. void CompoundShape::SaveBinaryState(StreamOut &inStream) const
  229. {
  230. Shape::SaveBinaryState(inStream);
  231. inStream.Write(mCenterOfMass);
  232. inStream.Write(mLocalBounds.mMin);
  233. inStream.Write(mLocalBounds.mMax);
  234. inStream.Write(mInnerRadius);
  235. // Write sub shapes
  236. size_t len = mSubShapes.size();
  237. inStream.Write(len);
  238. if (!inStream.IsFailed())
  239. for (size_t i = 0; i < len; ++i)
  240. {
  241. const SubShape &s = mSubShapes[i];
  242. inStream.Write(s.mUserData);
  243. inStream.Write(s.mPositionCOM);
  244. inStream.Write(s.mRotation);
  245. }
  246. }
  247. void CompoundShape::RestoreBinaryState(StreamIn &inStream)
  248. {
  249. Shape::RestoreBinaryState(inStream);
  250. inStream.Read(mCenterOfMass);
  251. inStream.Read(mLocalBounds.mMin);
  252. inStream.Read(mLocalBounds.mMax);
  253. inStream.Read(mInnerRadius);
  254. // Read sub shapes
  255. size_t len = 0;
  256. inStream.Read(len);
  257. if (!inStream.IsEOF() && !inStream.IsFailed())
  258. {
  259. mSubShapes.resize(len);
  260. for (size_t i = 0; i < len; ++i)
  261. {
  262. SubShape &s = mSubShapes[i];
  263. inStream.Read(s.mUserData);
  264. inStream.Read(s.mPositionCOM);
  265. inStream.Read(s.mRotation);
  266. s.mIsRotationIdentity = s.mRotation == Float3(0, 0, 0);
  267. }
  268. }
  269. }
  270. void CompoundShape::SaveSubShapeState(ShapeList &outSubShapes) const
  271. {
  272. outSubShapes.clear();
  273. outSubShapes.reserve(mSubShapes.size());
  274. for (const SubShape &shape : mSubShapes)
  275. outSubShapes.push_back(shape.mShape);
  276. }
  277. void CompoundShape::RestoreSubShapeState(const ShapeRefC *inSubShapes, uint inNumShapes)
  278. {
  279. JPH_ASSERT(mSubShapes.size() == inNumShapes);
  280. for (uint i = 0; i < inNumShapes; ++i)
  281. mSubShapes[i].mShape = inSubShapes[i];
  282. }
  283. Shape::Stats CompoundShape::GetStatsRecursive(VisitedShapes &ioVisitedShapes) const
  284. {
  285. // Get own stats
  286. Stats stats = Shape::GetStatsRecursive(ioVisitedShapes);
  287. // Add child stats
  288. for (const SubShape &shape : mSubShapes)
  289. {
  290. Stats child_stats = shape.mShape->GetStatsRecursive(ioVisitedShapes);
  291. stats.mSizeBytes += child_stats.mSizeBytes;
  292. stats.mNumTriangles += child_stats.mNumTriangles;
  293. }
  294. return stats;
  295. }
  296. float CompoundShape::GetVolume() const
  297. {
  298. float volume = 0.0f;
  299. for (const SubShape &shape : mSubShapes)
  300. volume += shape.mShape->GetVolume();
  301. return volume;
  302. }
  303. bool CompoundShape::IsValidScale(Vec3Arg inScale) const
  304. {
  305. if (!Shape::IsValidScale(inScale))
  306. return false;
  307. for (const SubShape &shape : mSubShapes)
  308. {
  309. // Test if the scale is non-uniform and the shape is rotated
  310. if (!shape.IsValidScale(inScale))
  311. return false;
  312. // Test the child shape
  313. if (!shape.mShape->IsValidScale(shape.TransformScale(inScale)))
  314. return false;
  315. }
  316. return true;
  317. }
  318. void CompoundShape::sRegister()
  319. {
  320. for (EShapeSubType s1 : sCompoundSubShapeTypes)
  321. for (EShapeSubType s2 : sAllSubShapeTypes)
  322. CollisionDispatch::sRegisterCastShape(s1, s2, sCastCompoundVsShape);
  323. }
  324. } // JPH