CollisionShape.cpp 26 KB

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