CollisionShape.h 11 KB

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