Shape.cpp 8.6 KB

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