CollisionShape.cpp 25 KB

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