CollisionShape.cpp 38 KB

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