CollisionShape.cpp 35 KB

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