CollisionShape.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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 char* typeNames[] =
  54. {
  55. "None",
  56. "Box",
  57. "Sphere",
  58. "StaticPlane",
  59. "Cylinder",
  60. "Capsule",
  61. "Cone",
  62. "TriangleMesh",
  63. "ConvexHull",
  64. "Terrain",
  65. 0
  66. };
  67. TriangleMeshData::TriangleMeshData(Model* model, unsigned lodLevel) :
  68. meshData_(0),
  69. shape_(0)
  70. {
  71. modelName_ = model->GetName();
  72. meshData_ = new btTriangleMesh();
  73. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  74. for (unsigned i = 0; i < geometries.Size(); ++i)
  75. {
  76. unsigned subGeometryLodLevel = lodLevel;
  77. if (subGeometryLodLevel >= geometries[i].Size())
  78. subGeometryLodLevel = geometries[i].Size() - 1;
  79. Geometry* geom = geometries[i][subGeometryLodLevel];
  80. if (!geom)
  81. {
  82. LOGWARNING("Skipping null geometry for triangle mesh collision");
  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. LOGWARNING("Skipping geometry with no CPU-side geometry data for triangle mesh collision");
  94. continue;
  95. }
  96. unsigned indexStart = geom->GetIndexStart();
  97. unsigned indexCount = geom->GetIndexCount();
  98. // 16-bit indices
  99. if (indexSize == sizeof(unsigned short))
  100. {
  101. const unsigned short* indices = (const unsigned short*)indexData;
  102. for (unsigned j = indexStart; j < indexStart + indexCount; j += 3)
  103. {
  104. const Vector3& v0 = *((const Vector3*)(&vertexData[indices[j] * vertexSize]));
  105. const Vector3& v1 = *((const Vector3*)(&vertexData[indices[j + 1] * vertexSize]));
  106. const Vector3& v2 = *((const Vector3*)(&vertexData[indices[j + 2] * vertexSize]));
  107. meshData_->addTriangle(ToBtVector3(v0), ToBtVector3(v1), ToBtVector3(v2), true);
  108. }
  109. }
  110. // 32-bit indices
  111. else
  112. {
  113. const unsigned* indices = (const unsigned*)indexData;
  114. for (unsigned j = indexStart; j < indexStart + indexCount; j += 3)
  115. {
  116. const Vector3& v0 = *((const Vector3*)(&vertexData[indices[j] * vertexSize]));
  117. const Vector3& v1 = *((const Vector3*)(&vertexData[indices[j + 1] * vertexSize]));
  118. const Vector3& v2 = *((const Vector3*)(&vertexData[indices[j + 2] * vertexSize]));
  119. meshData_->addTriangle(ToBtVector3(v0), ToBtVector3(v1), ToBtVector3(v2), true);
  120. }
  121. }
  122. }
  123. shape_ = new btBvhTriangleMeshShape(meshData_, true, true);
  124. }
  125. TriangleMeshData::~TriangleMeshData()
  126. {
  127. delete shape_;
  128. shape_ = 0;
  129. delete meshData_;
  130. meshData_ = 0;
  131. }
  132. ConvexData::ConvexData(Model* model, unsigned lodLevel)
  133. {
  134. modelName_ = model->GetName();
  135. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  136. PODVector<Vector3> originalVertices;
  137. for (unsigned i = 0; i < geometries.Size(); ++i)
  138. {
  139. unsigned subGeometryLodLevel = lodLevel;
  140. if (subGeometryLodLevel >= geometries[i].Size())
  141. subGeometryLodLevel = geometries[i].Size() - 1;
  142. Geometry* geom = geometries[i][subGeometryLodLevel];
  143. if (!geom)
  144. {
  145. LOGWARNING("Skipping null geometry for convex hull collision");
  146. continue;
  147. };
  148. const unsigned char* vertexData;
  149. const unsigned char* indexData;
  150. unsigned vertexSize;
  151. unsigned indexSize;
  152. unsigned elementMask;
  153. geom->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  154. if (!vertexData || !indexData)
  155. {
  156. LOGWARNING("Skipping geometry with no CPU-side geometry data for convex hull collision");
  157. continue;
  158. }
  159. unsigned vertexStart = geom->GetVertexStart();
  160. unsigned vertexCount = geom->GetVertexCount();
  161. // Copy vertex data
  162. for (unsigned j = 0; j < vertexCount; ++j)
  163. {
  164. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  165. originalVertices.Push(v);
  166. }
  167. }
  168. if (originalVertices.Size())
  169. {
  170. // Build the convex hull from the raw geometry
  171. StanHull::HullDesc desc;
  172. desc.SetHullFlag(StanHull::QF_TRIANGLES);
  173. desc.mVcount = originalVertices.Size();
  174. desc.mVertices = originalVertices[0].Data();
  175. desc.mVertexStride = 3 * sizeof(float);
  176. desc.mSkinWidth = 0.0f;
  177. StanHull::HullLibrary lib;
  178. StanHull::HullResult result;
  179. lib.CreateConvexHull(desc, result);
  180. vertexCount_ = result.mNumOutputVertices;
  181. vertexData_ = new Vector3[vertexCount_];
  182. // Copy vertex data
  183. memcpy(vertexData_.Get(), result.mOutputVertices, vertexCount_ * sizeof(Vector3));
  184. lib.ReleaseResult(result);
  185. }
  186. else
  187. vertexCount_ = 0;
  188. }
  189. ConvexData::~ConvexData()
  190. {
  191. }
  192. HeightfieldData::HeightfieldData(Terrain* terrain) :
  193. heightData_(terrain->GetHeightData()),
  194. spacing_(terrain->GetSpacing()),
  195. size_(terrain->GetNumVertices()),
  196. minHeight_(0.0f),
  197. maxHeight_(0.0f)
  198. {
  199. if (heightData_)
  200. {
  201. unsigned points = size_.x_ * size_.y_;
  202. float* data = heightData_.Get();
  203. minHeight_ = maxHeight_ = data[0];
  204. for (unsigned i = 1; i < points; ++i)
  205. {
  206. minHeight_ = Min(minHeight_, data[i]);
  207. maxHeight_ = Max(maxHeight_, data[i]);
  208. }
  209. }
  210. }
  211. HeightfieldData::~HeightfieldData()
  212. {
  213. }
  214. OBJECTTYPESTATIC(CollisionShape);
  215. CollisionShape::CollisionShape(Context* context) :
  216. Component(context),
  217. shape_(0),
  218. shapeType_(SHAPE_NONE),
  219. position_(Vector3::ZERO),
  220. rotation_(Quaternion::IDENTITY),
  221. size_(Vector3::ONE),
  222. cachedWorldScale_(Vector3::ONE),
  223. lodLevel_(0),
  224. margin_(DEFAULT_COLLISION_MARGIN),
  225. recreateShape_(false)
  226. {
  227. }
  228. CollisionShape::~CollisionShape()
  229. {
  230. ReleaseShape();
  231. if (physicsWorld_)
  232. physicsWorld_->RemoveCollisionShape(this);
  233. }
  234. void CollisionShape::RegisterObject(Context* context)
  235. {
  236. context->RegisterFactory<CollisionShape>();
  237. ENUM_ATTRIBUTE(CollisionShape, "Shape Type", shapeType_, typeNames, SHAPE_NONE, 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. recreateShape_ = false;
  259. }
  260. }
  261. void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  262. {
  263. if (debug && physicsWorld_ && shape_ && node_)
  264. {
  265. physicsWorld_->SetDebugRenderer(debug);
  266. physicsWorld_->SetDebugDepthTest(depthTest);
  267. // Use the rigid body's world transform if possible, as it may be different from the rendering transform
  268. Matrix3x4 worldTransform;
  269. RigidBody* body = GetComponent<RigidBody>();
  270. if (body)
  271. worldTransform = Matrix3x4(body->GetPosition(), body->GetRotation(), node_->GetWorldScale());
  272. else
  273. worldTransform = node_->GetWorldTransform();
  274. Vector3 position = position_;
  275. // For terrains, undo the height centering performed automatically by Bullet
  276. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  277. {
  278. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  279. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  280. }
  281. Vector3 worldPosition = worldTransform * position;
  282. Quaternion worldRotation = worldTransform.Rotation() * rotation_;
  283. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  284. world->debugDrawObject(btTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition)), shape_, btVector3(0.0f,
  285. 1.0f, 0.0f));
  286. physicsWorld_->SetDebugRenderer(0);
  287. }
  288. }
  289. void CollisionShape::Clear()
  290. {
  291. shapeType_ = SHAPE_NONE;
  292. UpdateShape();
  293. NotifyRigidBody();
  294. MarkNetworkUpdate();
  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. void CollisionShape::NotifyRigidBody()
  484. {
  485. btCompoundShape* compound = GetParentCompoundShape();
  486. if (node_ && shape_ && compound)
  487. {
  488. // Remove the shape first to ensure it is not added twice
  489. compound->removeChildShape(shape_);
  490. // Then add with updated offset
  491. Vector3 position = position_;
  492. // For terrains, undo the height centering performed automatically by Bullet
  493. if (shapeType_ == SHAPE_TERRAIN && geometry_)
  494. {
  495. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  496. position.y_ += (heightfield->minHeight_ + heightfield->maxHeight_) * 0.5f;
  497. }
  498. btTransform offset;
  499. offset.setOrigin(ToBtVector3(node_->GetWorldScale() * position));
  500. offset.setRotation(ToBtQuaternion(rotation_));
  501. compound->addChildShape(offset, shape_);
  502. // Finally tell the rigid body to update its mass
  503. rigidBody_->UpdateMass();
  504. }
  505. }
  506. void CollisionShape::SetModelAttr(ResourceRef value)
  507. {
  508. ResourceCache* cache = GetSubsystem<ResourceCache>();
  509. model_ = cache->GetResource<Model>(value.id_);
  510. recreateShape_ = true;
  511. MarkNetworkUpdate();
  512. }
  513. ResourceRef CollisionShape::GetModelAttr() const
  514. {
  515. return GetResourceRef(model_, Model::GetTypeStatic());
  516. }
  517. void CollisionShape::ReleaseShape()
  518. {
  519. btCompoundShape* compound = GetParentCompoundShape();
  520. if (shape_ && compound)
  521. {
  522. compound->removeChildShape(shape_);
  523. rigidBody_->UpdateMass();
  524. }
  525. delete shape_;
  526. shape_ = 0;
  527. geometry_.Reset();
  528. if (physicsWorld_)
  529. physicsWorld_->CleanupGeometryCache();
  530. }
  531. void CollisionShape::OnNodeSet(Node* node)
  532. {
  533. if (node)
  534. {
  535. Scene* scene = GetScene();
  536. if (scene)
  537. {
  538. if (scene == node)
  539. LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  540. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  541. if (physicsWorld_)
  542. physicsWorld_->AddCollisionShape(this);
  543. else
  544. LOGERROR("No physics world component in scene, can not create collision shape");
  545. }
  546. node->AddListener(this);
  547. cachedWorldScale_ = node->GetWorldScale();
  548. // Terrain collision shape depends on the terrain component's geometry updates. Subscribe to them
  549. SubscribeToEvent(node, E_TERRAINCREATED, HANDLER(CollisionShape, HandleTerrainCreated));
  550. }
  551. }
  552. void CollisionShape::OnMarkedDirty(Node* node)
  553. {
  554. Vector3 newWorldScale = node_->GetWorldScale();
  555. if (!newWorldScale.Equals(cachedWorldScale_) && shape_)
  556. {
  557. // Physics operations are not safe from worker threads
  558. Scene* scene = GetScene();
  559. if (scene && scene->IsThreadedUpdate())
  560. {
  561. scene->DelayedMarkedDirty(this);
  562. return;
  563. }
  564. switch (shapeType_)
  565. {
  566. case SHAPE_BOX:
  567. case SHAPE_SPHERE:
  568. case SHAPE_CYLINDER:
  569. case SHAPE_CAPSULE:
  570. case SHAPE_CONE:
  571. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  572. break;
  573. case SHAPE_TRIANGLEMESH:
  574. case SHAPE_CONVEXHULL:
  575. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  576. break;
  577. case SHAPE_TERRAIN:
  578. {
  579. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  580. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  581. newWorldScale * size_));
  582. }
  583. break;
  584. default:
  585. break;
  586. }
  587. NotifyRigidBody();
  588. cachedWorldScale_ = newWorldScale;
  589. }
  590. }
  591. btCompoundShape* CollisionShape::GetParentCompoundShape()
  592. {
  593. if (!rigidBody_)
  594. rigidBody_ = GetComponent<RigidBody>();
  595. return rigidBody_ ? rigidBody_->GetCompoundShape() : 0;
  596. }
  597. void CollisionShape::UpdateShape()
  598. {
  599. PROFILE(UpdateCollisionShape);
  600. ReleaseShape();
  601. if (!physicsWorld_)
  602. return;
  603. if (node_)
  604. {
  605. Vector3 newWorldScale = node_->GetWorldScale();
  606. switch (shapeType_)
  607. {
  608. case SHAPE_BOX:
  609. shape_ = new btBoxShape(ToBtVector3(size_ * 0.5f));
  610. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  611. break;
  612. case SHAPE_SPHERE:
  613. shape_ = new btSphereShape(size_.x_ * 0.5f);
  614. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  615. break;
  616. case SHAPE_STATICPLANE:
  617. /// \todo: plane normal is always hard coded
  618. shape_ = new btStaticPlaneShape(btVector3(0,1,0), size_.y_);
  619. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  620. break;
  621. case SHAPE_CYLINDER:
  622. shape_ = new btCylinderShape(btVector3(size_.x_ * 0.5f, size_.y_ * 0.5f, size_.x_ * 0.5f));
  623. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  624. break;
  625. case SHAPE_CAPSULE:
  626. shape_ = new btCapsuleShape(size_.x_ * 0.5f, Max(size_.y_ - size_.x_, 0.0f));
  627. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  628. break;
  629. case SHAPE_CONE:
  630. shape_ = new btConeShape(size_.x_ * 0.5f, size_.y_);
  631. shape_->setLocalScaling(ToBtVector3(newWorldScale));
  632. break;
  633. case SHAPE_TRIANGLEMESH:
  634. size_ = size_.Abs();
  635. if (model_)
  636. {
  637. // Check the geometry cache
  638. String id = "TriMesh_" + model_->GetName() + "_" + String(lodLevel_);
  639. HashMap<String, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetGeometryCache();
  640. HashMap<String, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id);
  641. if (j != cache.End())
  642. geometry_ = j->second_;
  643. else
  644. {
  645. geometry_ = new TriangleMeshData(model_, lodLevel_);
  646. cache[id] = geometry_;
  647. }
  648. TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
  649. shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_, ToBtVector3(newWorldScale * size_));
  650. }
  651. break;
  652. case SHAPE_CONVEXHULL:
  653. size_ = size_.Abs();
  654. if (model_)
  655. {
  656. // Check the geometry cache
  657. String id = "Convex_" + 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 ConvexData(model_, lodLevel_);
  665. cache[id] = geometry_;
  666. }
  667. ConvexData* convex = static_cast<ConvexData*>(geometry_.Get());
  668. shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3));
  669. shape_->setLocalScaling(ToBtVector3(newWorldScale * size_));
  670. }
  671. break;
  672. case SHAPE_TERRAIN:
  673. size_ = size_.Abs();
  674. {
  675. Terrain* terrain = GetComponent<Terrain>();
  676. if (terrain && terrain->GetHeightData())
  677. {
  678. geometry_ = new HeightfieldData(terrain);
  679. HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get());
  680. shape_ = new btHeightfieldTerrainShape(heightfield->size_.x_, heightfield->size_.y_,
  681. heightfield->heightData_.Get(), 1.0f, heightfield->minHeight_, heightfield->maxHeight_, 1, PHY_FLOAT,
  682. false);
  683. shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) *
  684. newWorldScale * size_));
  685. }
  686. }
  687. break;
  688. default:
  689. break;
  690. }
  691. if (shape_)
  692. {
  693. shape_->setUserPointer(this);
  694. shape_->setMargin(margin_);
  695. }
  696. cachedWorldScale_ = newWorldScale;
  697. }
  698. if (physicsWorld_)
  699. physicsWorld_->CleanupGeometryCache();
  700. }
  701. void CollisionShape::HandleTerrainCreated(StringHash eventType, VariantMap& eventData)
  702. {
  703. if (shapeType_ == SHAPE_TERRAIN)
  704. {
  705. UpdateShape();
  706. NotifyRigidBody();
  707. }
  708. }
  709. }