CollisionShape.cpp 38 KB

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