CompoundShape.cpp 12 KB

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