CollisionShape.cpp 26 KB

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