CollisionShape.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. /// \file
  4. #pragma once
  5. #include "../Container/ArrayPtr.h"
  6. #include "../Math/BoundingBox.h"
  7. #include "../Math/Quaternion.h"
  8. #include "../Scene/Component.h"
  9. #include <memory>
  10. class btBvhTriangleMeshShape;
  11. class btCollisionShape;
  12. class btCompoundShape;
  13. class btGImpactMeshShape;
  14. class btTriangleMesh;
  15. struct btTriangleInfoMap;
  16. namespace Urho3D
  17. {
  18. class CustomGeometry;
  19. class Geometry;
  20. class Model;
  21. class PhysicsWorld;
  22. class RigidBody;
  23. class Terrain;
  24. class TriangleMeshInterface;
  25. /// Collision shape type.
  26. enum ShapeType
  27. {
  28. SHAPE_BOX = 0,
  29. SHAPE_SPHERE,
  30. SHAPE_STATICPLANE,
  31. SHAPE_CYLINDER,
  32. SHAPE_CAPSULE,
  33. SHAPE_CONE,
  34. SHAPE_TRIANGLEMESH,
  35. SHAPE_CONVEXHULL,
  36. SHAPE_TERRAIN,
  37. SHAPE_GIMPACTMESH
  38. };
  39. /// Base class for collision shape geometry data.
  40. struct CollisionGeometryData : public RefCounted
  41. {
  42. };
  43. /// Cache of collision geometry data.
  44. /// \todo Remove duplicate declaration
  45. using CollisionGeometryDataCache = HashMap<Pair<Model*, i32>, SharedPtr<CollisionGeometryData>>;
  46. /// Triangle mesh geometry data.
  47. struct TriangleMeshData : public CollisionGeometryData
  48. {
  49. /// Construct from a model.
  50. TriangleMeshData(Model* model, i32 lodLevel);
  51. /// Construct from a custom geometry.
  52. explicit TriangleMeshData(CustomGeometry* custom);
  53. /// Bullet triangle mesh interface.
  54. std::unique_ptr<TriangleMeshInterface> meshInterface_;
  55. /// Bullet triangle mesh collision shape.
  56. std::unique_ptr<btBvhTriangleMeshShape> shape_;
  57. /// Bullet triangle info map.
  58. std::unique_ptr<btTriangleInfoMap> infoMap_;
  59. };
  60. /// Triangle mesh geometry data.
  61. struct GImpactMeshData : public CollisionGeometryData
  62. {
  63. /// Construct from a model.
  64. GImpactMeshData(Model* model, i32 lodLevel);
  65. /// Construct from a custom geometry.
  66. explicit GImpactMeshData(CustomGeometry* custom);
  67. /// Bullet triangle mesh interface.
  68. std::unique_ptr<TriangleMeshInterface> meshInterface_;
  69. };
  70. /// Convex hull geometry data.
  71. struct ConvexData : public CollisionGeometryData
  72. {
  73. /// Construct from a model.
  74. ConvexData(Model* model, i32 lodLevel);
  75. /// Construct from a custom geometry.
  76. explicit ConvexData(CustomGeometry* custom);
  77. /// Build the convex hull from vertices.
  78. void BuildHull(const Vector<Vector3>& vertices);
  79. /// Vertex data.
  80. SharedArrayPtr<Vector3> vertexData_;
  81. /// Number of vertices.
  82. unsigned vertexCount_{};
  83. /// Index data.
  84. SharedArrayPtr<unsigned> indexData_;
  85. /// Number of indices.
  86. unsigned indexCount_{};
  87. };
  88. /// Heightfield geometry data.
  89. struct HeightfieldData : public CollisionGeometryData
  90. {
  91. /// Construct from a terrain.
  92. HeightfieldData(Terrain* terrain, i32 lodLevel);
  93. /// Height data. On LOD level 0 the original height data will be used.
  94. SharedArrayPtr<float> heightData_;
  95. /// Vertex spacing.
  96. Vector3 spacing_;
  97. /// Heightmap size.
  98. IntVector2 size_;
  99. /// Minimum height.
  100. float minHeight_;
  101. /// Maximum height.
  102. float maxHeight_;
  103. };
  104. /// Physics collision shape component.
  105. class URHO3D_API CollisionShape : public Component
  106. {
  107. URHO3D_OBJECT(CollisionShape, Component);
  108. public:
  109. /// Construct.
  110. explicit CollisionShape(Context* context);
  111. /// Destruct. Free the geometry data and clean up unused data from the geometry data cache.
  112. ~CollisionShape() override;
  113. /// Register object factory.
  114. /// @nobind
  115. static void RegisterObject(Context* context);
  116. /// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
  117. void ApplyAttributes() override;
  118. /// Handle enabled/disabled state change.
  119. void OnSetEnabled() override;
  120. /// Visualize the component as debug geometry.
  121. void DrawDebugGeometry(DebugRenderer* debug, bool depthTest) override;
  122. /// Set as a box.
  123. void SetBox(const Vector3& size, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  124. /// Set as a sphere.
  125. void SetSphere(float diameter, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  126. /// Set as a static plane.
  127. void SetStaticPlane(const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  128. /// Set as a cylinder.
  129. void SetCylinder(float diameter, float height, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  130. /// Set as a capsule.
  131. void SetCapsule(float diameter, float height, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  132. /// Set as a cone.
  133. void SetCone(float diameter, float height, const Vector3& position = Vector3::ZERO, const Quaternion& rotation = Quaternion::IDENTITY);
  134. /// Set as a triangle mesh from Model. If you update a model's geometry and want to reapply the shape, call physicsWorld->RemoveCachedGeometry(model) first.
  135. void SetTriangleMesh(Model* model, i32 lodLevel = 0, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  136. const Quaternion& rotation = Quaternion::IDENTITY);
  137. /// Set as a triangle mesh from CustomGeometry.
  138. void SetCustomTriangleMesh(CustomGeometry* custom, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  139. const Quaternion& rotation = Quaternion::IDENTITY);
  140. /// Set as a convex hull from Model.
  141. void SetConvexHull(Model* model, i32 lodLevel = 0, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  142. const Quaternion& rotation = Quaternion::IDENTITY);
  143. /// Set as a convex hull from CustomGeometry.
  144. void SetCustomConvexHull(CustomGeometry* custom, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  145. const Quaternion& rotation = Quaternion::IDENTITY);
  146. /// Set as a triangle mesh from Model. If you update a model's geometry and want to reapply the shape, call physicsWorld->RemoveCachedGeometry(model) first.
  147. void SetGImpactMesh(Model* model, i32 lodLevel = 0, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  148. const Quaternion& rotation = Quaternion::IDENTITY);
  149. /// Set as a triangle mesh from CustomGeometry.
  150. void SetCustomGImpactMesh(CustomGeometry* custom, const Vector3& scale = Vector3::ONE, const Vector3& position = Vector3::ZERO,
  151. const Quaternion& rotation = Quaternion::IDENTITY);
  152. /// Set as a terrain. Only works if the same scene node contains a Terrain component.
  153. void SetTerrain(i32 lodLevel = 0);
  154. /// Set shape type.
  155. /// @property
  156. void SetShapeType(ShapeType type);
  157. /// Set shape size.
  158. /// @property
  159. void SetSize(const Vector3& size);
  160. /// Set offset position.
  161. /// @property
  162. void SetPosition(const Vector3& position);
  163. /// Set offset rotation.
  164. /// @property
  165. void SetRotation(const Quaternion& rotation);
  166. /// Set offset transform.
  167. void SetTransform(const Vector3& position, const Quaternion& rotation);
  168. /// Set collision margin.
  169. /// @property
  170. void SetMargin(float margin);
  171. /// Set triangle mesh / convex hull model.
  172. /// @property
  173. void SetModel(Model* model);
  174. /// Set model LOD level.
  175. /// @property
  176. void SetLodLevel(i32 lodLevel);
  177. /// Return Bullet collision shape.
  178. btCollisionShape* GetCollisionShape() const { return shape_.get(); }
  179. /// Return the shared geometry data.
  180. CollisionGeometryData* GetGeometryData() const { return geometry_; }
  181. /// Return physics world.
  182. PhysicsWorld* GetPhysicsWorld() const { return physicsWorld_; }
  183. /// Return shape type.
  184. /// @property
  185. ShapeType GetShapeType() const { return shapeType_; }
  186. /// Return shape size.
  187. /// @property
  188. const Vector3& GetSize() const { return size_; }
  189. /// Return offset position.
  190. /// @property
  191. const Vector3& GetPosition() const { return position_; }
  192. /// Return offset rotation.
  193. /// @property
  194. const Quaternion& GetRotation() const { return rotation_; }
  195. /// Return collision margin.
  196. /// @property
  197. float GetMargin() const { return margin_; }
  198. /// Return triangle mesh / convex hull model.
  199. /// @property
  200. Model* GetModel() const { return model_; }
  201. /// Return model LOD level.
  202. /// @property
  203. i32 GetLodLevel() const { return lodLevel_; }
  204. /// Return world-space bounding box.
  205. /// @property
  206. BoundingBox GetWorldBoundingBox() const;
  207. /// Update the new collision shape to the RigidBody.
  208. void NotifyRigidBody(bool updateMass = true);
  209. /// Set model attribute.
  210. void SetModelAttr(const ResourceRef& value);
  211. /// Return model attribute.
  212. ResourceRef GetModelAttr() const;
  213. /// Release the collision shape.
  214. void ReleaseShape();
  215. protected:
  216. /// Handle node being assigned.
  217. void OnNodeSet(Node* node) override;
  218. /// Handle scene being assigned.
  219. void OnSceneSet(Scene* scene) override;
  220. /// Handle node transform being dirtied.
  221. void OnMarkedDirty(Node* node) override;
  222. /**
  223. * Called when instantiating a collision shape that is not one of ShapeType (default no-op).
  224. *
  225. * Useful for custom shape types that subclass CollisionShape and use a non-standard underlying
  226. * btCollisionShape. UpdateDerivedShape can then be overridden to create the required
  227. * btCollisionShape subclass.
  228. */
  229. virtual btCollisionShape* UpdateDerivedShape(int shapeType, const Vector3& newWorldScale);
  230. private:
  231. /// Find the parent rigid body component and return its compound collision shape.
  232. btCompoundShape* GetParentCompoundShape();
  233. /// Update the collision shape after attribute changes.
  234. void UpdateShape();
  235. /// Update cached geometry collision shape.
  236. void UpdateCachedGeometryShape(CollisionGeometryDataCache& cache);
  237. /// Set as specified shape type using model and LOD.
  238. void SetModelShape(ShapeType shapeType, Model* model, i32 lodLevel,
  239. const Vector3& scale, const Vector3& position, const Quaternion& rotation);
  240. /// Set as specified shape type using CustomGeometry.
  241. void SetCustomShape(ShapeType shapeType, CustomGeometry* custom,
  242. const Vector3& scale, const Vector3& position, const Quaternion& rotation);
  243. /// Update terrain collision shape from the terrain component.
  244. void HandleTerrainCreated(StringHash eventType, VariantMap& eventData);
  245. /// Update trimesh or convex shape after a model has reloaded itself.
  246. void HandleModelReloadFinished(StringHash eventType, VariantMap& eventData);
  247. /// Mark shape dirty.
  248. void MarkShapeDirty() { recreateShape_ = true; }
  249. /// Physics world.
  250. WeakPtr<PhysicsWorld> physicsWorld_;
  251. /// Rigid body.
  252. WeakPtr<RigidBody> rigidBody_;
  253. /// Model.
  254. SharedPtr<Model> model_;
  255. /// Shared geometry data.
  256. SharedPtr<CollisionGeometryData> geometry_;
  257. /// Bullet collision shape.
  258. std::unique_ptr<btCollisionShape> shape_;
  259. /// Collision shape type.
  260. ShapeType shapeType_;
  261. /// Offset position.
  262. Vector3 position_;
  263. /// Offset rotation.
  264. Quaternion rotation_;
  265. /// Shape size.
  266. Vector3 size_;
  267. /// Cached world scale for determining if the collision shape needs update.
  268. Vector3 cachedWorldScale_;
  269. /// Model LOD level.
  270. i32 lodLevel_;
  271. /// CustomGeometry component ID. 0 if not creating the convex hull / triangle mesh from a CustomGeometry.
  272. unsigned customGeometryID_;
  273. /// Collision margin.
  274. float margin_;
  275. /// Recreate collision shape flag.
  276. bool recreateShape_;
  277. /// Shape creation retry flag if attributes initially set without scene.
  278. bool retryCreation_;
  279. };
  280. }