CollisionShape.h 13 KB

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