Shape.cpp 8.5 KB

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