CollisionShape.cpp 30 KB

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