Shape.cpp 8.4 KB

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