Shape.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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/Shape.h>
  6. #include <Jolt/Physics/Collision/Shape/ScaledShape.h>
  7. #include <Jolt/Physics/Collision/Shape/StaticCompoundShape.h>
  8. #include <Jolt/Physics/Collision/TransformedShape.h>
  9. #include <Jolt/Physics/Collision/PhysicsMaterial.h>
  10. #include <Jolt/Physics/Collision/RayCast.h>
  11. #include <Jolt/Physics/Collision/CastResult.h>
  12. #include <Jolt/Physics/Collision/CollidePointResult.h>
  13. #include <Jolt/Core/StreamIn.h>
  14. #include <Jolt/Core/StreamOut.h>
  15. #include <Jolt/Core/Factory.h>
  16. #include <Jolt/ObjectStream/TypeDeclarations.h>
  17. JPH_NAMESPACE_BEGIN
  18. JPH_IMPLEMENT_SERIALIZABLE_ABSTRACT_BASE(ShapeSettings)
  19. {
  20. JPH_ADD_BASE_CLASS(ShapeSettings, SerializableObject)
  21. JPH_ADD_ATTRIBUTE(ShapeSettings, mUserData)
  22. }
  23. #ifdef JPH_DEBUG_RENDERER
  24. bool Shape::sDrawSubmergedVolumes = false;
  25. #endif // JPH_DEBUG_RENDERER
  26. ShapeFunctions ShapeFunctions::sRegistry[NumSubShapeTypes];
  27. TransformedShape Shape::GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, SubShapeID &outRemainder) const
  28. {
  29. // We have reached the leaf shape so there is no remainder
  30. outRemainder = SubShapeID();
  31. // Just return the transformed shape for this shape
  32. TransformedShape ts(RVec3(inPositionCOM), inRotation, this, BodyID());
  33. ts.SetShapeScale(inScale);
  34. return ts;
  35. }
  36. void Shape::CollectTransformedShapes(const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, const SubShapeIDCreator &inSubShapeIDCreator, TransformedShapeCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  37. {
  38. // Test shape filter
  39. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  40. return;
  41. TransformedShape ts(RVec3(inPositionCOM), inRotation, this, TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator);
  42. ts.SetShapeScale(inScale);
  43. ioCollector.AddHit(ts);
  44. }
  45. void Shape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  46. {
  47. Vec3 scale;
  48. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  49. TransformedShape ts(RVec3(transform.GetTranslation()), transform.GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  50. ts.SetShapeScale(scale);
  51. ioCollector.AddHit(ts);
  52. }
  53. void Shape::SaveBinaryState(StreamOut &inStream) const
  54. {
  55. inStream.Write(mShapeSubType);
  56. inStream.Write(mUserData);
  57. }
  58. void Shape::RestoreBinaryState(StreamIn &inStream)
  59. {
  60. // Type hash read by sRestoreFromBinaryState
  61. inStream.Read(mUserData);
  62. }
  63. Shape::ShapeResult Shape::sRestoreFromBinaryState(StreamIn &inStream)
  64. {
  65. ShapeResult result;
  66. // Read the type of the shape
  67. EShapeSubType shape_sub_type;
  68. inStream.Read(shape_sub_type);
  69. if (inStream.IsEOF() || inStream.IsFailed())
  70. {
  71. result.SetError("Failed to read type id");
  72. return result;
  73. }
  74. // Construct and read the data of the shape
  75. Ref<Shape> shape = ShapeFunctions::sGet(shape_sub_type).mConstruct();
  76. shape->RestoreBinaryState(inStream);
  77. if (inStream.IsEOF() || inStream.IsFailed())
  78. {
  79. result.SetError("Failed to restore shape");
  80. return result;
  81. }
  82. result.Set(shape);
  83. return result;
  84. }
  85. void Shape::SaveWithChildren(StreamOut &inStream, ShapeToIDMap &ioShapeMap, MaterialToIDMap &ioMaterialMap) const
  86. {
  87. ShapeToIDMap::const_iterator shape_id_iter = ioShapeMap.find(this);
  88. if (shape_id_iter == ioShapeMap.end())
  89. {
  90. // Write shape ID of this shape
  91. uint32 shape_id = (uint32)ioShapeMap.size();
  92. ioShapeMap[this] = shape_id;
  93. inStream.Write(shape_id);
  94. // Write the shape itself
  95. SaveBinaryState(inStream);
  96. // Write the ID's of all sub shapes
  97. ShapeList sub_shapes;
  98. SaveSubShapeState(sub_shapes);
  99. inStream.Write(sub_shapes.size());
  100. for (const Shape *shape : sub_shapes)
  101. {
  102. if (shape == nullptr)
  103. inStream.Write(~uint32(0));
  104. else
  105. shape->SaveWithChildren(inStream, ioShapeMap, ioMaterialMap);
  106. }
  107. // Write the materials
  108. PhysicsMaterialList materials;
  109. SaveMaterialState(materials);
  110. StreamUtils::SaveObjectArray(inStream, materials, &ioMaterialMap);
  111. }
  112. else
  113. {
  114. // Known shape, just write the ID
  115. inStream.Write(shape_id_iter->second);
  116. }
  117. }
  118. Shape::ShapeResult Shape::sRestoreWithChildren(StreamIn &inStream, IDToShapeMap &ioShapeMap, IDToMaterialMap &ioMaterialMap)
  119. {
  120. ShapeResult result;
  121. // Read ID of this shape
  122. uint32 shape_id;
  123. inStream.Read(shape_id);
  124. if (inStream.IsEOF() || inStream.IsFailed())
  125. {
  126. result.SetError("Failed to read shape id");
  127. return result;
  128. }
  129. // Check nullptr shape
  130. if (shape_id == ~uint32(0))
  131. {
  132. result.Set(nullptr);
  133. return result;
  134. }
  135. // Check if we already read this shape
  136. if (shape_id < ioShapeMap.size())
  137. {
  138. result.Set(ioShapeMap[shape_id]);
  139. return result;
  140. }
  141. // Read the shape
  142. result = sRestoreFromBinaryState(inStream);
  143. if (result.HasError())
  144. return result;
  145. JPH_ASSERT(ioShapeMap.size() == shape_id); // Assert that this is the next ID in the map
  146. ioShapeMap.push_back(result.Get());
  147. // Read the sub shapes
  148. size_t len;
  149. inStream.Read(len);
  150. if (inStream.IsEOF() || inStream.IsFailed())
  151. {
  152. result.SetError("Failed to read stream");
  153. return result;
  154. }
  155. ShapeList sub_shapes;
  156. sub_shapes.reserve(len);
  157. for (size_t i = 0; i < len; ++i)
  158. {
  159. ShapeResult sub_shape_result = sRestoreWithChildren(inStream, ioShapeMap, ioMaterialMap);
  160. if (sub_shape_result.HasError())
  161. return sub_shape_result;
  162. sub_shapes.push_back(sub_shape_result.Get());
  163. }
  164. result.Get()->RestoreSubShapeState(sub_shapes.data(), (uint)sub_shapes.size());
  165. // Read the materials
  166. Result mlresult = StreamUtils::RestoreObjectArray<PhysicsMaterialList>(inStream, ioMaterialMap);
  167. if (mlresult.HasError())
  168. {
  169. result.SetError(mlresult.GetError());
  170. return result;
  171. }
  172. const PhysicsMaterialList &materials = mlresult.Get();
  173. result.Get()->RestoreMaterialState(materials.data(), (uint)materials.size());
  174. return result;
  175. }
  176. Shape::Stats Shape::GetStatsRecursive(VisitedShapes &ioVisitedShapes) const
  177. {
  178. Stats stats = GetStats();
  179. // If shape is already visited, don't count its size again
  180. if (!ioVisitedShapes.insert(this).second)
  181. stats.mSizeBytes = 0;
  182. return stats;
  183. }
  184. Shape::ShapeResult Shape::ScaleShape(Vec3Arg inScale) const
  185. {
  186. const Vec3 unit_scale = Vec3::sReplicate(1.0f);
  187. if (inScale.IsNearZero())
  188. {
  189. ShapeResult result;
  190. result.SetError("Can't use zero scale!");
  191. return result;
  192. }
  193. // First test if we can just wrap this shape in a scaled shape
  194. if (IsValidScale(inScale))
  195. {
  196. // Test if the scale is near unit
  197. ShapeResult result;
  198. if (inScale.IsClose(unit_scale))
  199. result.Set(const_cast<Shape *>(this));
  200. else
  201. result.Set(new ScaledShape(this, inScale));
  202. return result;
  203. }
  204. // Collect the leaf shapes and their transforms
  205. struct Collector : TransformedShapeCollector
  206. {
  207. virtual void AddHit(const ResultType &inResult) override
  208. {
  209. mShapes.push_back(inResult);
  210. }
  211. Array<TransformedShape> mShapes;
  212. };
  213. Collector collector;
  214. TransformShape(Mat44::sScale(inScale) * Mat44::sTranslation(GetCenterOfMass()), collector);
  215. // Construct a compound shape
  216. StaticCompoundShapeSettings compound;
  217. compound.mSubShapes.reserve(collector.mShapes.size());
  218. for (const TransformedShape &ts : collector.mShapes)
  219. {
  220. const Shape *shape = ts.mShape;
  221. // Construct a scaled shape if scale is not unit
  222. Vec3 scale = ts.GetShapeScale();
  223. if (!scale.IsClose(unit_scale))
  224. shape = new ScaledShape(shape, scale);
  225. // Add the shape
  226. compound.AddShape(Vec3(ts.mShapePositionCOM) - ts.mShapeRotation * shape->GetCenterOfMass(), ts.mShapeRotation, shape);
  227. }
  228. return compound.Create();
  229. }
  230. void Shape::sCollidePointUsingRayCast(const Shape &inShape, Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter)
  231. {
  232. // First test if we're inside our bounding box
  233. AABox bounds = inShape.GetLocalBounds();
  234. if (bounds.Contains(inPoint))
  235. {
  236. // A collector that just counts the number of hits
  237. class HitCountCollector : public CastRayCollector
  238. {
  239. public:
  240. virtual void AddHit(const RayCastResult &inResult) override
  241. {
  242. // Store the last sub shape ID so that we can provide something to our outer hit collector
  243. mSubShapeID = inResult.mSubShapeID2;
  244. ++mHitCount;
  245. }
  246. int mHitCount = 0;
  247. SubShapeID mSubShapeID;
  248. };
  249. HitCountCollector collector;
  250. // Configure the raycast
  251. RayCastSettings settings;
  252. settings.mBackFaceMode = EBackFaceMode::CollideWithBackFaces;
  253. // Cast a ray that's 10% longer than the height of our bounding box
  254. inShape.CastRay(RayCast { inPoint, 1.1f * bounds.GetSize().GetY() * Vec3::sAxisY() }, settings, inSubShapeIDCreator, collector, inShapeFilter);
  255. // Odd amount of hits means inside
  256. if ((collector.mHitCount & 1) == 1)
  257. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), collector.mSubShapeID });
  258. }
  259. }
  260. JPH_NAMESPACE_END