2
0

CollisionShape.cpp 31 KB

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