CollisionShape.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. //
  2. // Copyright (c) 2008-2013 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. #include "Precompiled.h"
  23. #include "CollisionShape.h"
  24. #include "Context.h"
  25. #include "DebugRenderer.h"
  26. #include "DrawableEvents.h"
  27. #include "Geometry.h"
  28. #include "Log.h"
  29. #include "Model.h"
  30. #include "PhysicsUtils.h"
  31. #include "PhysicsWorld.h"
  32. #include "Profiler.h"
  33. #include "ResourceCache.h"
  34. #include "RigidBody.h"
  35. #include "Scene.h"
  36. #include "Terrain.h"
  37. #include <BulletCollision/CollisionShapes/btBoxShape.h>
  38. #include <BulletCollision/CollisionShapes/btCapsuleShape.h>
  39. #include <BulletCollision/CollisionShapes/btCompoundShape.h>
  40. #include <BulletCollision/CollisionShapes/btConeShape.h>
  41. #include <BulletCollision/CollisionShapes/btConvexHullShape.h>
  42. #include <BulletCollision/CollisionShapes/btCylinderShape.h>
  43. #include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h>
  44. #include <BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h>
  45. #include <BulletCollision/CollisionShapes/btSphereShape.h>
  46. #include <BulletCollision/CollisionShapes/btTriangleMesh.h>
  47. #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  48. #include <BulletCollision/CollisionShapes/btStaticPlaneShape.h>
  49. #include <hull.h>
  50. namespace Urho3D
  51. {
  52. static const float DEFAULT_COLLISION_MARGIN = 0.04f;
  53. static const btVector3 WHITE(1.0f, 1.0f, 1.0f);
  54. static const btVector3 GREEN(0.0f, 1.0f, 0.0f);
  55. static const char* typeNames[] =
  56. {
  57. "Box",
  58. "Sphere",
  59. "StaticPlane",
  60. "Cylinder",
  61. "Capsule",
  62. "Cone",
  63. "TriangleMesh",
  64. "ConvexHull",
  65. "Terrain",
  66. 0
  67. };
  68. extern const char* PHYSICS_CATEGORY;
  69. TriangleMeshData::TriangleMeshData(Model* model, unsigned lodLevel) :
  70. meshData_(0),
  71. shape_(0)
  72. {
  73. modelName_ = model->GetName();
  74. meshData_ = new btTriangleMesh();
  75. unsigned numGeometries = model->GetNumGeometries();
  76. for (unsigned i = 0; i < numGeometries; ++i)
  77. {
  78. Geometry* geometry = model->GetGeometry(i, lodLevel);
  79. if (!geometry)
  80. {
  81. LOGWARNING("Skipping null geometry for triangle mesh collision");
  82. continue;
  83. }
  84. const unsigned char* vertexData;
  85. const unsigned char* indexData;
  86. unsigned vertexSize;
  87. unsigned indexSize;
  88. unsigned elementMask;
  89. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  90. if (!vertexData || !indexData)
  91. {
  92. LOGWARNING("Skipping geometry with no CPU-side geometry data for triangle mesh collision");
  93. continue;
  94. }
  95. unsigned indexStart = geometry->GetIndexStart();
  96. unsigned indexCount = geometry->GetIndexCount();
  97. // 16-bit indices
  98. if (indexSize == sizeof(unsigned short))
  99. {
  100. const unsigned short* indices = (const unsigned short*)indexData;
  101. for (unsigned j = indexStart; j < indexStart + indexCount; j += 3)
  102. {
  103. const Vector3& v0 = *((const Vector3*)(&vertexData[indices[j] * vertexSize]));
  104. const Vector3& v1 = *((const Vector3*)(&vertexData[indices[j + 1] * vertexSize]));
  105. const Vector3& v2 = *((const Vector3*)(&vertexData[indices[j + 2] * vertexSize]));
  106. meshData_->addTriangle(ToBtVector3(v0), ToBtVector3(v1), ToBtVector3(v2), true);
  107. }
  108. }
  109. // 32-bit indices
  110. else
  111. {
  112. const unsigned* indices = (const unsigned*)indexData;
  113. for (unsigned j = indexStart; j < indexStart + indexCount; j += 3)
  114. {
  115. const Vector3& v0 = *((const Vector3*)(&vertexData[indices[j] * vertexSize]));
  116. const Vector3& v1 = *((const Vector3*)(&vertexData[indices[j + 1] * vertexSize]));
  117. const Vector3& v2 = *((const Vector3*)(&vertexData[indices[j + 2] * vertexSize]));
  118. meshData_->addTriangle(ToBtVector3(v0), ToBtVector3(v1), ToBtVector3(v2), true);
  119. }
  120. }
  121. }
  122. shape_ = new btBvhTriangleMeshShape(meshData_, true, true);
  123. }
  124. TriangleMeshData::~TriangleMeshData()
  125. {
  126. delete shape_;
  127. shape_ = 0;
  128. delete meshData_;
  129. meshData_ = 0;
  130. }
  131. ConvexData::ConvexData(Model* model, unsigned lodLevel)
  132. {
  133. modelName_ = model->GetName();
  134. PODVector<Vector3> originalVertices;
  135. unsigned numGeometries = model->GetNumGeometries();
  136. for (unsigned i = 0; i < numGeometries; ++i)
  137. {
  138. Geometry* geom = model->GetGeometry(i, lodLevel);
  139. if (!geom)
  140. {
  141. LOGWARNING("Skipping null geometry for convex hull collision");
  142. continue;
  143. };
  144. const unsigned char* vertexData;
  145. const unsigned char* indexData;
  146. unsigned vertexSize;
  147. unsigned indexSize;
  148. unsigned elementMask;
  149. geom->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  150. if (!vertexData || !indexData)
  151. {
  152. LOGWARNING("Skipping geometry with no CPU-side geometry data for convex hull collision");
  153. continue;
  154. }
  155. unsigned vertexStart = geom->GetVertexStart();
  156. unsigned vertexCount = geom->GetVertexCount();
  157. // Copy vertex data
  158. for (unsigned j = 0; j < vertexCount; ++j)
  159. {
  160. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  161. originalVertices.Push(v);
  162. }
  163. }
  164. if (originalVertices.Size())
  165. {
  166. // Build the convex hull from the raw geometry
  167. StanHull::HullDesc desc;
  168. desc.SetHullFlag(StanHull::QF_TRIANGLES);
  169. desc.mVcount = originalVertices.Size();
  170. desc.mVertices = originalVertices[0].Data();
  171. desc.mVertexStride = 3 * sizeof(float);
  172. desc.mSkinWidth = 0.0f;
  173. StanHull::HullLibrary lib;
  174. StanHull::HullResult result;
  175. lib.CreateConvexHull(desc, result);
  176. vertexCount_ = result.mNumOutputVertices;
  177. vertexData_ = new Vector3[vertexCount_];
  178. indexCount_ = result.mNumIndices;
  179. indexData_ = new unsigned[indexCount_];
  180. // Copy vertex data & index data
  181. memcpy(vertexData_.Get(), result.mOutputVertices, vertexCount_ * sizeof(Vector3));
  182. memcpy(indexData_.Get(), result.mIndices, indexCount_ * sizeof(unsigned));
  183. lib.ReleaseResult(result);
  184. }
  185. else
  186. vertexCount_ = 0;
  187. }
  188. ConvexData::~ConvexData()
  189. {
  190. }
  191. HeightfieldData::HeightfieldData(Terrain* terrain) :
  192. heightData_(terrain->GetHeightData()),
  193. spacing_(terrain->GetSpacing()),
  194. size_(terrain->GetNumVertices()),
  195. minHeight_(0.0f),
  196. maxHeight_(0.0f)
  197. {
  198. if (heightData_)
  199. {
  200. unsigned points = size_.x_ * size_.y_;
  201. float* data = heightData_.Get();
  202. minHeight_ = maxHeight_ = data[0];
  203. for (unsigned i = 1; i < points; ++i)
  204. {
  205. minHeight_ = Min(minHeight_, data[i]);
  206. maxHeight_ = Max(maxHeight_, data[i]);
  207. }
  208. }
  209. }
  210. HeightfieldData::~HeightfieldData()
  211. {
  212. }
  213. OBJECTTYPESTATIC(CollisionShape);
  214. CollisionShape::CollisionShape(Context* context) :
  215. Component(context),
  216. shape_(0),
  217. shapeType_(SHAPE_BOX),
  218. position_(Vector3::ZERO),
  219. rotation_(Quaternion::IDENTITY),
  220. size_(Vector3::ONE),
  221. cachedWorldScale_(Vector3::ONE),
  222. lodLevel_(0),
  223. margin_(DEFAULT_COLLISION_MARGIN),
  224. recreateShape_(true)
  225. {
  226. }
  227. CollisionShape::~CollisionShape()
  228. {
  229. ReleaseShape();
  230. if (physicsWorld_)
  231. physicsWorld_->RemoveCollisionShape(this);
  232. }
  233. void CollisionShape::RegisterObject(Context* context)
  234. {
  235. context->RegisterFactory<CollisionShape>(PHYSICS_CATEGORY);
  236. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  237. ENUM_ATTRIBUTE(CollisionShape, "Shape Type", shapeType_, typeNames, SHAPE_BOX, AM_DEFAULT);
  238. ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Size", size_, Vector3::ONE, AM_DEFAULT);
  239. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Offset Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT);
  240. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_QUATERNION, "Offset Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_DEFAULT);
  241. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  242. ATTRIBUTE(CollisionShape, VAR_INT, "LOD Level", lodLevel_, 0, AM_DEFAULT);
  243. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Collision Margin", margin_, DEFAULT_COLLISION_MARGIN, AM_DEFAULT);
  244. }
  245. void CollisionShape::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  246. {
  247. Component::OnSetAttribute(attr, src);
  248. // Change of any non-accessor attribute requires recreation of the collision shape
  249. if (!attr.accessor_)
  250. recreateShape_ = true;
  251. }
  252. void CollisionShape::ApplyAttributes()
  253. {
  254. if (recreateShape_)
  255. {
  256. UpdateShape();
  257. NotifyRigidBody();
  258. }
  259. }
  260. void CollisionShape::OnSetEnabled()
  261. {
  262. NotifyRigidBody();
  263. }
  264. void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  265. {
  266. if (debug && physicsWorld_ && shape_ && node_ && IsEnabledEffective())
  267. {
  268. physicsWorld_->SetDebugRenderer(debug);
  269. physicsWorld_->SetDebugDepthTest(depthTest);
  270. // Use the rigid body's world transform if possible, as it may be different from the rendering transform
  271. Matrix3x4 worldTransform;
  272. RigidBody* body = GetComponent<RigidBody>();
  273. bool bodyActive = false;
  274. if (body)
  275. {
  276. worldTransform = Matrix3x4(body->GetPosition(), body->GetRotation(), node_->GetWorldScale());
  277. bodyActive = body->IsActive();
  278. }
  279. else
  280. worldTransform = node_->GetWorldTransform();
  281. Vector3 position = position_;
  282. // For terrains, undo the height centering performed automatically by Bullet
  283. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  284. {
  285. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  286. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  287. }
  288. Vector3 worldPosition(worldTransform * position);
  289. Quaternion worldRotation(worldTransform.Rotation() * rotation_);
  290. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  291. world->debugDrawObject(btTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition)), shape_, bodyActive ?
  292. WHITE : GREEN);
  293. physicsWorld_->SetDebugRenderer(0);
  294. }
  295. }
  296. void CollisionShape::SetBox(const Vector3& size, const Vector3& position, const Quaternion& rotation)
  297. {
  298. shapeType_ = SHAPE_BOX;
  299. size_ = size;
  300. position_ = position;
  301. rotation_ = rotation;
  302. model_.Reset();
  303. UpdateShape();
  304. NotifyRigidBody();
  305. MarkNetworkUpdate();
  306. }
  307. void CollisionShape::SetSphere(float diameter, const Vector3& position, const Quaternion& rotation)
  308. {
  309. shapeType_ = SHAPE_SPHERE;
  310. size_ = Vector3(diameter, diameter, diameter);
  311. position_ = position;
  312. rotation_ = rotation;
  313. model_.Reset();
  314. UpdateShape();
  315. NotifyRigidBody();
  316. MarkNetworkUpdate();
  317. }
  318. void CollisionShape::SetCylinder(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  319. {
  320. shapeType_ = SHAPE_CYLINDER;
  321. size_ = Vector3(diameter, height, diameter);
  322. position_ = position;
  323. rotation_ = rotation;
  324. model_.Reset();
  325. UpdateShape();
  326. NotifyRigidBody();
  327. MarkNetworkUpdate();
  328. }
  329. void CollisionShape::SetCapsule(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  330. {
  331. shapeType_ = SHAPE_CAPSULE;
  332. size_ = Vector3(diameter, height, diameter);
  333. position_ = position;
  334. rotation_ = rotation;
  335. model_.Reset();
  336. UpdateShape();
  337. NotifyRigidBody();
  338. MarkNetworkUpdate();
  339. }
  340. void CollisionShape::SetCone(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  341. {
  342. shapeType_ = SHAPE_CONE;
  343. size_ = Vector3(diameter, height, diameter);
  344. position_ = position;
  345. rotation_ = rotation;
  346. model_.Reset();
  347. UpdateShape();
  348. NotifyRigidBody();
  349. MarkNetworkUpdate();
  350. }
  351. void CollisionShape::SetTriangleMesh(Model* model, unsigned lodLevel, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  352. {
  353. if (!model)
  354. {
  355. LOGERROR("Null model, can not set triangle mesh");
  356. return;
  357. }
  358. shapeType_ = SHAPE_TRIANGLEMESH;
  359. model_ = model;
  360. lodLevel_ = lodLevel;
  361. size_ = scale;
  362. position_ = position;
  363. rotation_ = rotation;
  364. UpdateShape();
  365. NotifyRigidBody();
  366. MarkNetworkUpdate();
  367. }
  368. void CollisionShape::SetConvexHull(Model* model, unsigned lodLevel, const Vector3& scale, const Vector3& position, const Quaternion& rotation)
  369. {
  370. if (!model)
  371. {
  372. LOGERROR("Null model, can not set convex hull");
  373. return;
  374. }
  375. shapeType_ = SHAPE_CONVEXHULL;
  376. model_ = model;
  377. lodLevel_ = lodLevel;
  378. size_ = scale;
  379. position_ = position;
  380. rotation_ = rotation;
  381. UpdateShape();
  382. NotifyRigidBody();
  383. MarkNetworkUpdate();
  384. }
  385. void CollisionShape::SetTerrain()
  386. {
  387. Terrain* terrain = GetComponent<Terrain>();
  388. if (!terrain)
  389. {
  390. LOGERROR("No terrain component, can not set terrain shape");
  391. return;
  392. }
  393. shapeType_ = SHAPE_TERRAIN;
  394. UpdateShape();
  395. NotifyRigidBody();
  396. MarkNetworkUpdate();
  397. }
  398. void CollisionShape::SetShapeType(ShapeType type)
  399. {
  400. if (type != shapeType_)
  401. {
  402. shapeType_ = type;
  403. UpdateShape();
  404. NotifyRigidBody();
  405. MarkNetworkUpdate();
  406. }
  407. }
  408. void CollisionShape::SetSize(const Vector3& size)
  409. {
  410. if (size != size_)
  411. {
  412. size_ = size;
  413. UpdateShape();
  414. NotifyRigidBody();
  415. MarkNetworkUpdate();
  416. }
  417. }
  418. void CollisionShape::SetPosition(const Vector3& position)
  419. {
  420. if (position != position_)
  421. {
  422. position_ = position;
  423. NotifyRigidBody();
  424. MarkNetworkUpdate();
  425. }
  426. }
  427. void CollisionShape::SetRotation(const Quaternion& rotation)
  428. {
  429. if (rotation != rotation_)
  430. {
  431. rotation_ = rotation;
  432. NotifyRigidBody();
  433. MarkNetworkUpdate();
  434. }
  435. }
  436. void CollisionShape::SetTransform(const Vector3& position, const Quaternion& rotation)
  437. {
  438. if (position != position_ || rotation != rotation_)
  439. {
  440. position_ = position;
  441. rotation_ = rotation;
  442. NotifyRigidBody();
  443. MarkNetworkUpdate();
  444. }
  445. }
  446. void CollisionShape::SetMargin(float margin)
  447. {
  448. margin = Max(margin, 0.0f);
  449. if (margin != margin_)
  450. {
  451. if (shape_)
  452. shape_->setMargin(margin);
  453. margin_ = margin;
  454. MarkNetworkUpdate();
  455. }
  456. }
  457. void CollisionShape::SetModel(Model* model)
  458. {
  459. if (model != model_)
  460. {
  461. model_ = model;
  462. if (shapeType_ >= SHAPE_TRIANGLEMESH)
  463. {
  464. UpdateShape();
  465. NotifyRigidBody();
  466. }
  467. MarkNetworkUpdate();
  468. }
  469. }
  470. void CollisionShape::SetLodLevel(unsigned lodLevel)
  471. {
  472. if (lodLevel != lodLevel_)
  473. {
  474. lodLevel_ = lodLevel;
  475. if (shapeType_ >= SHAPE_TRIANGLEMESH)
  476. {
  477. UpdateShape();
  478. NotifyRigidBody();
  479. }
  480. MarkNetworkUpdate();
  481. }
  482. }
  483. BoundingBox CollisionShape::GetWorldBoundingBox() const
  484. {
  485. if (shape_ && node_)
  486. {
  487. // Use the rigid body's world transform if possible, as it may be different from the rendering transform
  488. RigidBody* body = GetComponent<RigidBody>();
  489. Matrix3x4 worldTransform = body ? Matrix3x4(body->GetPosition(), body->GetRotation(), node_->GetWorldScale()) :
  490. node_->GetWorldTransform();
  491. Vector3 worldPosition(worldTransform * position_);
  492. Quaternion worldRotation(worldTransform.Rotation() * rotation_);
  493. btTransform shapeWorldTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition));
  494. btVector3 aabbMin, aabbMax;
  495. shape_->getAabb(shapeWorldTransform, aabbMin, aabbMax);
  496. return BoundingBox(ToVector3(aabbMin), ToVector3(aabbMax));
  497. }
  498. else
  499. return BoundingBox();
  500. }
  501. void CollisionShape::NotifyRigidBody()
  502. {
  503. btCompoundShape* compound = GetParentCompoundShape();
  504. if (node_ && shape_ && compound)
  505. {
  506. // Remove the shape first to ensure it is not added twice
  507. compound->removeChildShape(shape_);
  508. if (IsEnabledEffective())
  509. {
  510. // Then add with updated offset
  511. Vector3 position = position_;
  512. // For terrains, undo the height centering performed automatically by Bullet
  513. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  514. {
  515. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  516. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  517. }
  518. btTransform offset;
  519. offset.setOrigin(ToBtVector3(node_->GetWorldScale() * position));
  520. offset.setRotation(ToBtQuaternion(rotation_));
  521. compound->addChildShape(offset, shape_);
  522. }
  523. // Finally tell the rigid body to update its mass
  524. rigidBody_->UpdateMass();
  525. }
  526. }
  527. void CollisionShape::SetModelAttr(ResourceRef value)
  528. {
  529. ResourceCache* cache = GetSubsystem<ResourceCache>();
  530. model_ = cache->GetResource<Model>(value.id_);
  531. recreateShape_ = true;
  532. MarkNetworkUpdate();
  533. }
  534. ResourceRef CollisionShape::GetModelAttr() const
  535. {
  536. return GetResourceRef(model_, Model::GetTypeStatic());
  537. }
  538. void CollisionShape::ReleaseShape()
  539. {
  540. btCompoundShape* compound = GetParentCompoundShape();
  541. if (shape_ && compound)
  542. {
  543. compound->removeChildShape(shape_);
  544. rigidBody_->UpdateMass();
  545. }
  546. delete shape_;
  547. shape_ = 0;
  548. geometry_.Reset();
  549. if (physicsWorld_)
  550. physicsWorld_->CleanupGeometryCache();
  551. }
  552. void CollisionShape::OnNodeSet(Node* node)
  553. {
  554. if (node)
  555. {
  556. Scene* scene = GetScene();
  557. if (scene)
  558. {
  559. if (scene == node)
  560. LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  561. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  562. if (physicsWorld_)
  563. physicsWorld_->AddCollisionShape(this);
  564. else
  565. LOGERROR("No physics world component in scene, can not create collision shape");
  566. }
  567. node->AddListener(this);
  568. cachedWorldScale_ = node->GetWorldScale();
  569. // Terrain collision shape depends on the terrain component's geometry updates. Subscribe to them
  570. SubscribeToEvent(node, E_TERRAINCREATED, HANDLER(CollisionShape, HandleTerrainCreated));
  571. }
  572. }
  573. void CollisionShape::OnMarkedDirty(Node* node)
  574. {
  575. Vector3 newWorldScale = node_->GetWorldScale();
  576. if (!newWorldScale.Equals(cachedWorldScale_) && shape_)
  577. {
  578. // Physics operations are not safe from worker threads
  579. Scene* scene = GetScene();
  580. if (scene && scene->IsThreadedUpdate())
  581. {
  582. scene->DelayedMarkedDirty(this);
  583. return;
  584. }
  585. switch (shapeType_)
  586. {
  587. case SHAPE_BOX:
  588. case SHAPE_SPHERE:
  589. case SHAPE_CYLINDER:
  590. case SHAPE_CAPSULE:
  591. case SHAPE_CONE:
  592. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  593. break;
  594. case SHAPE_TRIANGLEMESH:
  595. case SHAPE_CONVEXHULL:
  596. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  597. break;
  598. case SHAPE_TERRAIN:
  599. {
  600. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  601. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  602. newWorldScale * size_));
  603. }
  604. break;
  605. default:
  606. break;
  607. }
  608. NotifyRigidBody();
  609. cachedWorldScale_ = newWorldScale;
  610. }
  611. }
  612. btCompoundShape* CollisionShape::GetParentCompoundShape()
  613. {
  614. if (!rigidBody_)
  615. rigidBody_ = GetComponent<RigidBody>();
  616. return rigidBody_ ? rigidBody_->GetCompoundShape() : 0;
  617. }
  618. void CollisionShape::UpdateShape()
  619. {
  620. PROFILE(UpdateCollisionShape);
  621. ReleaseShape();
  622. if (!physicsWorld_)
  623. return;
  624. if (node_)
  625. {
  626. Vector3 newWorldScale = node_->GetWorldScale();
  627. switch (shapeType_)
  628. {
  629. case SHAPE_BOX:
  630. shape_ = new btBoxShape(ToBtVector3(size_ * 0.5f));
  631. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  632. break;
  633. case SHAPE_SPHERE:
  634. shape_ = new btSphereShape(size_.x_ * 0.5f);
  635. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  636. break;
  637. case SHAPE_STATICPLANE:
  638. shape_ = new btStaticPlaneShape(btVector3(0.0f, 1.0f, 0.0f), 0.0f);
  639. break;
  640. case SHAPE_CYLINDER:
  641. shape_ = new btCylinderShape(btVector3(size_.x_ * 0.5f, size_.y_ * 0.5f, size_.x_ * 0.5f));
  642. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  643. break;
  644. case SHAPE_CAPSULE:
  645. shape_ = new btCapsuleShape(size_.x_ * 0.5f, Max(size_.y_ - size_.x_, 0.0f));
  646. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  647. break;
  648. case SHAPE_CONE:
  649. shape_ = new btConeShape(size_.x_ * 0.5f, size_.y_);
  650. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  651. break;
  652. case SHAPE_TRIANGLEMESH:
  653. size_ = size_.Abs();
  654. if (model_)
  655. {
  656. // Check the geometry cache
  657. String id = "TriMesh_" + model_->GetName() + "_" + String(lodLevel_);
  658. HashMap<String, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetGeometryCache();
  659. HashMap<String, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  660. if (j != cache.End())
  661. geometry_ = j->second_;
  662. else
  663. {
  664. geometry_ = new TriangleMeshData(model_, lodLevel_);
  665. cache[id] = geometry_;
  666. }
  667. TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
  668. shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_, ToBtVector3(newWorldScale * size_));
  669. }
  670. break;
  671. case SHAPE_CONVEXHULL:
  672. size_ = size_.Abs();
  673. if (model_)
  674. {
  675. // Check the geometry cache
  676. String id = "Convex_" + model_->GetName() + "_" + String(lodLevel_);
  677. HashMap<String, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetGeometryCache();
  678. HashMap<String, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  679. if (j != cache.End())
  680. geometry_ = j->second_;
  681. else
  682. {
  683. geometry_ = new ConvexData(model_, lodLevel_);
  684. cache[id] = geometry_;
  685. }
  686. ConvexData* convex = static_cast<ConvexData*>(geometry_.Get());
  687. shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3));
  688. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  689. }
  690. break;
  691. case SHAPE_TERRAIN:
  692. size_ = size_.Abs();
  693. {
  694. Terrain* terrain = GetComponent<Terrain>();
  695. if (terrain && terrain->GetHeightData())
  696. {
  697. geometry_ = new HeightfieldData(terrain);
  698. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  699. shape_ = new btHeightfieldTerrainShape(heightfield->size_.x_, heightfield->size_.y_,
  700. heightfield->heightData_.Get(), 1.0f, heightfield->minHeight_, heightfield->maxHeight_, 1, PHY_FLOAT,
  701. false);
  702. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  703. newWorldScale * size_));
  704. }
  705. }
  706. break;
  707. default:
  708. break;
  709. }
  710. if (shape_)
  711. {
  712. shape_->setUserPointer(this);
  713. shape_->setMargin(margin_);
  714. }
  715. cachedWorldScale_ = newWorldScale;
  716. }
  717. if (physicsWorld_)
  718. physicsWorld_->CleanupGeometryCache();
  719. recreateShape_ = false;
  720. }
  721. void CollisionShape::HandleTerrainCreated(StringHash eventType, VariantMap& eventData)
  722. {
  723. if (shapeType_ == SHAPE_TERRAIN)
  724. {
  725. UpdateShape();
  726. NotifyRigidBody();
  727. }
  728. }
  729. }