CollisionShape.cpp 38 KB

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