CollisionShape.cpp 37 KB

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