CollisionShape.cpp 38 KB

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