CollisionShape.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "CollisionShape.h"
  25. #include "Context.h"
  26. #include "DebugRenderer.h"
  27. #include "Geometry.h"
  28. #include "Log.h"
  29. #include "Model.h"
  30. #include "PhysicsWorld.h"
  31. #include "Profiler.h"
  32. #include "ResourceCache.h"
  33. #include "RigidBody.h"
  34. #include "Scene.h"
  35. #include "XMLFile.h"
  36. #include <ode/ode.h>
  37. #include <../ode/src/heightfield.h>
  38. #include <../ode/src/collision_std.h>
  39. #include <hull.h>
  40. #include "DebugNew.h"
  41. static const String typeNames[] =
  42. {
  43. "None",
  44. "Box",
  45. "Sphere",
  46. "Capsule",
  47. "Cylinder",
  48. "TriangleMesh",
  49. "Heightfield",
  50. "ConvexHull",
  51. ""
  52. };
  53. static const float DEFAULT_FRICTION = 0.5f;
  54. static const float DEFAULT_BOUNCE = 0.0f;
  55. static const Quaternion CYLINDER_ROTATION(90.0f, 0.0f, 0.0f);
  56. void GetVertexAndIndexData(const Model* model, unsigned lodLevel, SharedArrayPtr<Vector3>& destVertexData, unsigned& destVertexCount,
  57. SharedArrayPtr<unsigned>& destIndexData, unsigned& destIndexCount, const Vector3& scale)
  58. {
  59. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  60. destVertexCount = 0;
  61. destIndexCount = 0;
  62. for (unsigned i = 0; i < geometries.Size(); ++i)
  63. {
  64. unsigned subGeometryLodLevel = lodLevel;
  65. if (subGeometryLodLevel >= geometries[i].Size())
  66. subGeometryLodLevel = geometries[i].Size() / 2;
  67. Geometry* geom = geometries[i][subGeometryLodLevel];
  68. if (!geom)
  69. continue;
  70. destVertexCount += geom->GetVertexCount();
  71. destIndexCount += geom->GetIndexCount();
  72. }
  73. if (!destVertexCount || !destIndexCount)
  74. return;
  75. destVertexData = new Vector3[destVertexCount];
  76. destIndexData = new unsigned[destIndexCount];
  77. unsigned firstVertex = 0;
  78. unsigned firstIndex = 0;
  79. for (unsigned i = 0; i < geometries.Size(); ++i)
  80. {
  81. unsigned subGeometryLodLevel = lodLevel;
  82. if (subGeometryLodLevel >= geometries[i].Size())
  83. subGeometryLodLevel = geometries[i].Size() / 2;
  84. Geometry* geom = geometries[i][subGeometryLodLevel];
  85. if (!geom)
  86. continue;
  87. const unsigned char* vertexData;
  88. const unsigned char* indexData;
  89. unsigned vertexSize;
  90. unsigned indexSize;
  91. geom->GetRawData(vertexData, vertexSize, indexData, indexSize);
  92. if (!vertexData || !indexData)
  93. continue;
  94. unsigned vertexStart = geom->GetVertexStart();
  95. unsigned vertexCount = geom->GetVertexCount();
  96. // Copy vertex data
  97. for (unsigned j = 0; j < vertexCount; ++j)
  98. {
  99. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  100. destVertexData[firstVertex + j] = scale * v;
  101. }
  102. unsigned indexStart = geom->GetIndexStart();
  103. unsigned indexCount = geom->GetIndexCount();
  104. // 16-bit indices
  105. if (indexSize == sizeof(unsigned short))
  106. {
  107. const unsigned short* indices = (const unsigned short*)indexData;
  108. for (unsigned j = 0; j < indexCount; j += 3)
  109. {
  110. // Rebase the indices according to our vertex numbering
  111. destIndexData[firstIndex + j] = indices[indexStart + j] - vertexStart + firstVertex;
  112. destIndexData[firstIndex + j + 1] = indices[indexStart + j + 1] - vertexStart + firstVertex;
  113. destIndexData[firstIndex + j + 2] = indices[indexStart + j + 2] - vertexStart + firstVertex;
  114. }
  115. }
  116. // 32-bit indices
  117. else
  118. {
  119. const unsigned* indices = (const unsigned*)indexData;
  120. for (unsigned j = 0; j < indexCount; j += 3)
  121. {
  122. // Rebase the indices according to our vertex numbering
  123. destIndexData[firstIndex + j] = indices[indexStart + j] - vertexStart + firstVertex;
  124. destIndexData[firstIndex + j + 1] = indices[indexStart + j + 1] - vertexStart + firstVertex;
  125. destIndexData[firstIndex + j + 2] = indices[indexStart + j + 2] - vertexStart + firstVertex;
  126. }
  127. }
  128. firstVertex += vertexCount;
  129. firstIndex += indexCount;
  130. }
  131. }
  132. TriangleMeshData::TriangleMeshData(Model* model, bool makeConvexHull, float thickness, unsigned lodLevel, const Vector3& scale) :
  133. triMesh_(0),
  134. indexCount_(0)
  135. {
  136. modelName_ = model->GetName();
  137. unsigned vertexCount;
  138. unsigned indexCount;
  139. if (!makeConvexHull)
  140. GetVertexAndIndexData(model, lodLevel, vertexData_, vertexCount, indexData_, indexCount, scale);
  141. else
  142. {
  143. SharedArrayPtr<Vector3> originalVertices;
  144. SharedArrayPtr<unsigned> originalIndices;
  145. unsigned originalVertexCount;
  146. unsigned originalIndexCount;
  147. GetVertexAndIndexData(model, lodLevel, originalVertices, originalVertexCount, originalIndices, originalIndexCount, scale);
  148. // Build the convex hull from the raw geometry
  149. StanHull::HullDesc desc;
  150. desc.SetHullFlag(StanHull::QF_TRIANGLES);
  151. desc.mVcount = originalVertexCount;
  152. desc.mVertices = (float*)originalVertices.Get();
  153. desc.mVertexStride = 3 * sizeof(float);
  154. desc.mSkinWidth = thickness;
  155. StanHull::HullLibrary lib;
  156. StanHull::HullResult result;
  157. lib.CreateConvexHull(desc, result);
  158. vertexCount = result.mNumOutputVertices;
  159. indexCount = result.mNumIndices;
  160. // Copy vertex data
  161. vertexData_ = new Vector3[vertexCount];
  162. memcpy(vertexData_.Get(), result.mOutputVertices, vertexCount * sizeof(Vector3));
  163. // Copy index data
  164. indexData_ = new unsigned[indexCount];
  165. memcpy(indexData_.Get(), result.mIndices, indexCount * sizeof(unsigned));
  166. lib.ReleaseResult(result);
  167. }
  168. triMesh_ = dGeomTriMeshDataCreate();
  169. dGeomTriMeshDataBuildSingle(triMesh_, vertexData_.Get(), sizeof(Vector3), vertexCount,
  170. indexData_.Get(), indexCount, 3 * sizeof(unsigned));
  171. indexCount_ = indexCount;
  172. }
  173. TriangleMeshData::~TriangleMeshData()
  174. {
  175. if (triMesh_)
  176. {
  177. dGeomTriMeshDataDestroy(triMesh_);
  178. triMesh_ = 0;
  179. }
  180. }
  181. HeightfieldData::HeightfieldData(Model* model, IntVector2 numPoints, float thickness, unsigned lodLevel,
  182. const Vector3& scale) :
  183. heightfield_(0)
  184. {
  185. modelName_ = model->GetName();
  186. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  187. if (!geometries.Size())
  188. return;
  189. lodLevel = Clamp(lodLevel, 0, geometries[0].Size());
  190. Geometry* geom = geometries[0][lodLevel];
  191. if (!geom)
  192. return;
  193. const unsigned char* vertexData;
  194. const unsigned char* indexData;
  195. unsigned vertexSize;
  196. unsigned indexSize;
  197. geom->GetRawData(vertexData, vertexSize, indexData, indexSize);
  198. if (!vertexData || !indexData)
  199. return;
  200. unsigned indexStart = geom->GetIndexStart();
  201. unsigned indexCount = geom->GetIndexCount();
  202. // If X & Z size not specified, try to guess them
  203. if (numPoints == IntVector2::ZERO)
  204. numPoints.x_ = numPoints.y_ = (int)sqrtf((float)geom->GetVertexCount());
  205. unsigned dataSize = numPoints.x_ * numPoints.y_;
  206. // Then allocate the heightfield
  207. BoundingBox box = model->GetBoundingBox();
  208. heightData_ = new float[dataSize];
  209. // Calculate spacing from model's bounding box
  210. float xSpacing = (box.max_.x_ - box.min_.x_) / (numPoints.x_ - 1);
  211. float zSpacing = (box.max_.z_ - box.min_.z_) / (numPoints.y_ - 1);
  212. // Initialize the heightfield with minimum height
  213. for (unsigned i = 0; i < dataSize; ++i)
  214. heightData_[i] = box.min_.y_ * scale.y_;
  215. unsigned vertexStart = geom->GetVertexStart();
  216. unsigned vertexCount = geom->GetVertexCount();
  217. // Now go through vertex data and fit the vertices into the heightfield
  218. for (unsigned i = vertexStart; i < vertexStart + vertexCount; ++i)
  219. {
  220. const Vector3& vertex = *((const Vector3*)(&vertexData[i * vertexSize]));
  221. int x = (int)((vertex.x_ - box.min_.x_) / xSpacing + 0.25f);
  222. int z = (int)((vertex.z_ - box.min_.z_) / zSpacing + 0.25f);
  223. if (x >= numPoints.x_)
  224. x = numPoints.x_ - 1;
  225. if (z >= numPoints.y_)
  226. z = numPoints.y_ - 1;
  227. if (vertex.y_ > heightData_[z * numPoints.x_ + x])
  228. heightData_[z * numPoints.x_ + x] = vertex.y_ * scale.y_;
  229. }
  230. heightfield_ = dGeomHeightfieldDataCreate();
  231. dGeomHeightfieldDataBuildSingle(heightfield_, heightData_.Get(), 0, (box.max_.x_ - box.min_.x_) * scale.x_,
  232. (box.max_.z_ - box.min_.z_) * scale.z_, numPoints.x_, numPoints.y_, 1.0f, 0.0f, thickness, 0);
  233. dGeomHeightfieldDataSetBounds(heightfield_, box.min_.y_ * scale.y_, box.max_.y_ * scale.y_);
  234. }
  235. HeightfieldData::~HeightfieldData()
  236. {
  237. if (heightfield_)
  238. {
  239. dGeomHeightfieldDataDestroy(heightfield_);
  240. heightfield_ = 0;
  241. }
  242. }
  243. OBJECTTYPESTATIC(CollisionShape);
  244. CollisionShape::CollisionShape(Context* context) :
  245. Component(context),
  246. geometry_(0),
  247. shapeType_(SHAPE_NONE),
  248. size_(Vector3::ONE),
  249. thickness_(0.0f),
  250. lodLevel_(0),
  251. position_(Vector3::ZERO),
  252. rotation_(Quaternion::IDENTITY),
  253. geometryScale_(Vector3::ONE),
  254. collisionLayer_(M_MAX_UNSIGNED),
  255. collisionMask_(M_MAX_UNSIGNED),
  256. friction_(DEFAULT_FRICTION),
  257. bounce_(DEFAULT_BOUNCE),
  258. phantom_(false),
  259. recreateGeometry_(false)
  260. {
  261. }
  262. CollisionShape::~CollisionShape()
  263. {
  264. Clear();
  265. if (physicsWorld_)
  266. physicsWorld_->RemoveCollisionShape(this);
  267. }
  268. void CollisionShape::RegisterObject(Context* context)
  269. {
  270. context->RegisterFactory<CollisionShape>();
  271. ENUM_ATTRIBUTE(CollisionShape, "Shape Type", shapeType_, typeNames, SHAPE_NONE, AM_DEFAULT);
  272. ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Size", size_, Vector3::ONE, AM_DEFAULT);
  273. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Offset Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT);
  274. REF_ACCESSOR_ATTRIBUTE(CollisionShape, VAR_QUATERNION, "Offset Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_DEFAULT);
  275. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  276. ATTRIBUTE(CollisionShape, VAR_INT, "LOD Level", lodLevel_, 0, AM_DEFAULT);
  277. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Hull Thickness", thickness_, 0.0f, AM_DEFAULT);
  278. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_FLOAT, "Friction", GetFriction, SetFriction, float, DEFAULT_FRICTION, AM_DEFAULT);
  279. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_FLOAT, "Bounce", GetBounce, SetBounce, float, DEFAULT_BOUNCE, AM_DEFAULT);
  280. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_INT, "Collision Group", GetCollisionLayer, SetCollisionLayer, unsigned, M_MAX_UNSIGNED, AM_DEFAULT);
  281. ACCESSOR_ATTRIBUTE(CollisionShape, VAR_INT, "Collision Mask", GetCollisionMask, SetCollisionMask, unsigned, M_MAX_UNSIGNED, AM_DEFAULT);
  282. ATTRIBUTE(CollisionShape, VAR_BOOL, "Is Phantom", phantom_, false, AM_DEFAULT);
  283. }
  284. void CollisionShape::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  285. {
  286. Serializable::OnSetAttribute(attr, src);
  287. // Change of some attributes requires the geometry to be recreated
  288. switch (attr.offset_)
  289. {
  290. case offsetof(CollisionShape, size_):
  291. size_ = size_.Abs(); // Negative size is not allowed
  292. recreateGeometry_ = true;
  293. break;
  294. case offsetof(CollisionShape, shapeType_):
  295. case offsetof(CollisionShape, thickness_):
  296. case offsetof(CollisionShape, lodLevel_):
  297. recreateGeometry_ = true;
  298. break;
  299. }
  300. }
  301. void CollisionShape::ApplyAttributes()
  302. {
  303. if (recreateGeometry_)
  304. {
  305. CreateGeometry();
  306. recreateGeometry_ = false;
  307. }
  308. }
  309. void CollisionShape::Clear()
  310. {
  311. ReleaseGeometry();
  312. shapeType_ = SHAPE_NONE;
  313. }
  314. void CollisionShape::SetSphere(float diameter, const Vector3& position, const Quaternion& rotation)
  315. {
  316. ReleaseGeometry();
  317. shapeType_ = SHAPE_SPHERE;
  318. size_ = Vector3(diameter, diameter, diameter);
  319. position_ = position;
  320. rotation_ = rotation;
  321. CreateGeometry();
  322. }
  323. void CollisionShape::SetBox(const Vector3& size, const Vector3& position, const Quaternion& rotation)
  324. {
  325. ReleaseGeometry();
  326. shapeType_ = SHAPE_BOX;
  327. size_ = size;
  328. position_ = position;
  329. rotation_ = rotation;
  330. CreateGeometry();
  331. }
  332. void CollisionShape::SetCapsule(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  333. {
  334. ReleaseGeometry();
  335. shapeType_ = SHAPE_CAPSULE;
  336. size_ = Vector3(diameter, height, diameter);
  337. position_ = position;
  338. rotation_ = rotation;
  339. CreateGeometry();
  340. }
  341. void CollisionShape::SetCylinder(float diameter, float height, const Vector3& position, const Quaternion& rotation)
  342. {
  343. ReleaseGeometry();
  344. shapeType_ = SHAPE_CYLINDER;
  345. size_ = Vector3(diameter, height, diameter);
  346. position_ = position;
  347. rotation_ = rotation;
  348. CreateGeometry();
  349. }
  350. void CollisionShape::SetTriangleMesh(Model* model, unsigned lodLevel, const Vector3& size, const Vector3& position, const Quaternion& rotation)
  351. {
  352. PROFILE(SetTriangleMeshShape);
  353. if (!model)
  354. {
  355. LOGERROR("Null model, can not set triangle mesh");
  356. return;
  357. }
  358. ReleaseGeometry();
  359. model_ = model;
  360. shapeType_ = SHAPE_TRIANGLEMESH;
  361. lodLevel_ = lodLevel;
  362. size_ = size.Abs();
  363. position_ = position;
  364. rotation_ = rotation;
  365. CreateGeometry();
  366. }
  367. void CollisionShape::SetHeightfield(Model* model, unsigned xPoints, unsigned zPoints, float thickness, unsigned lodLevel, const Vector3& size, const Vector3& position, const Quaternion& rotation)
  368. {
  369. PROFILE(SetHeightFieldShape);
  370. if (!model)
  371. {
  372. LOGERROR("Null model, can not set heightfield");
  373. return;
  374. }
  375. ReleaseGeometry();
  376. model_ = model;
  377. shapeType_ = SHAPE_HEIGHTFIELD;
  378. numPoints_ = IntVector2(xPoints, zPoints);
  379. thickness_ = thickness;
  380. lodLevel_ = lodLevel;
  381. size_ = size.Abs();
  382. position_ = position;
  383. rotation_ = rotation;
  384. CreateGeometry();
  385. }
  386. void CollisionShape::SetConvexHull(Model* model, float thickness, unsigned lodLevel, const Vector3& size, const Vector3& position, const Quaternion& rotation)
  387. {
  388. PROFILE(SetConvexHullShape);
  389. if (!model)
  390. {
  391. LOGERROR("Null model, can not set convex hull");
  392. return;
  393. }
  394. ReleaseGeometry();
  395. model_ = model;
  396. shapeType_ = SHAPE_CONVEXHULL;
  397. thickness_ = thickness;
  398. lodLevel_ = lodLevel;
  399. size_ = size.Abs();
  400. position_ = position;
  401. rotation_ = rotation;
  402. CreateGeometry();
  403. }
  404. void CollisionShape::SetPosition(const Vector3& position)
  405. {
  406. position_ = position;
  407. UpdateTransform();
  408. }
  409. void CollisionShape::SetRotation(const Quaternion& rotation)
  410. {
  411. rotation_ = rotation;
  412. UpdateTransform();
  413. }
  414. void CollisionShape::SetTransform(const Vector3& position, const Quaternion& rotation)
  415. {
  416. position_ = position;
  417. rotation_ = rotation;
  418. UpdateTransform();
  419. }
  420. void CollisionShape::SetCollisionLayer(unsigned group)
  421. {
  422. collisionLayer_ = group;
  423. if (geometry_)
  424. dGeomSetCategoryBits(geometry_, group);
  425. }
  426. void CollisionShape::SetCollisionMask(unsigned mask)
  427. {
  428. collisionMask_ = mask;
  429. if (geometry_)
  430. dGeomSetCollideBits(geometry_, mask);
  431. }
  432. void CollisionShape::SetFriction(float friction)
  433. {
  434. friction_ = Max(friction, 0.0f);
  435. }
  436. void CollisionShape::SetBounce(float bounce)
  437. {
  438. bounce_ = Max(bounce, 0.0f);
  439. }
  440. void CollisionShape::SetPhantom(bool enable)
  441. {
  442. phantom_ = enable;
  443. }
  444. BoundingBox CollisionShape::GetWorldBoundingBox() const
  445. {
  446. if (!geometry_)
  447. return BoundingBox(0.0f, 0.0f);
  448. float aabb[6];
  449. dGeomGetAABB(geometry_, aabb);
  450. BoundingBox box;
  451. box.min_.x_ = aabb[0];
  452. box.max_.x_ = aabb[1];
  453. box.min_.y_ = aabb[2];
  454. box.max_.y_ = aabb[3];
  455. box.min_.z_ = aabb[4];
  456. box.max_.z_ = aabb[5];
  457. box.defined_ = true;
  458. return box;
  459. }
  460. void CollisionShape::UpdateTransform(bool nodeUpdate)
  461. {
  462. if (!geometry_)
  463. return;
  464. // Get the ODE body ID from the RigidBody component, if it exists
  465. RigidBody* rigidBody = GetComponent<RigidBody>();
  466. dBodyID body = rigidBody ? rigidBody->GetBody() : 0;
  467. // Apply an adjustment to the cylinder and capsule shapes to make them upright by default
  468. Quaternion offsetQuaternion = (shapeType_ == SHAPE_CYLINDER || shapeType_ == SHAPE_CAPSULE) ? CYLINDER_ROTATION * rotation_ : rotation_;
  469. if (body)
  470. {
  471. // Assign body now if necessary
  472. if (dGeomGetBody(geometry_) != body)
  473. dGeomSetBody(geometry_, body);
  474. else
  475. {
  476. // If the body is already assigned, and this is a node dirtying update, need to do nothing
  477. if (nodeUpdate)
  478. return;
  479. }
  480. // Update the offset transform
  481. if (position_ != Vector3::ZERO || offsetQuaternion != Quaternion::IDENTITY)
  482. {
  483. Vector3 offset(geometryScale_ * position_);
  484. dGeomSetOffsetPosition(geometry_, offset.x_, offset.y_, offset.z_);
  485. dGeomSetOffsetQuaternion(geometry_, offsetQuaternion.Data());
  486. }
  487. else
  488. dGeomClearOffset(geometry_);
  489. }
  490. else
  491. {
  492. // No rigid body. Must update the geometry transform manually
  493. // Use the target transform in case the node has smoothing enabled
  494. Matrix3x4 transform(node_->GetWorldTargetTransform());
  495. Vector3 nodePos(transform.Translation());
  496. Quaternion nodeRot(transform.Rotation());
  497. Vector3 geomPos(nodePos + (nodeRot * (geometryScale_ * position_)));
  498. Quaternion geomRot(nodeRot * offsetQuaternion);
  499. dGeomSetPosition(geometry_, geomPos.x_, geomPos.y_, geomPos.z_);
  500. dGeomSetQuaternion(geometry_, geomRot.Data());
  501. }
  502. }
  503. void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  504. {
  505. // Drawing all the debug geometries of a large world may be expensive (especially triangle meshes)
  506. // so cull the geometry AABB against the debug geometry frustum first
  507. if (debug && geometry_ && debug->IsInside(GetWorldBoundingBox()))
  508. {
  509. const Color* color;
  510. RigidBody* rigidBody = GetComponent<RigidBody>();
  511. if (rigidBody && rigidBody->IsActive())
  512. color = &Color::WHITE;
  513. else
  514. color = &Color::GREEN;
  515. unsigned uintColor = color->ToUInt();
  516. const Vector3& position = *reinterpret_cast<const Vector3*>(dGeomGetPosition(geometry_));
  517. Quaternion rotation;
  518. dGeomGetQuaternion(geometry_, const_cast<float*>(rotation.Data()));
  519. Matrix3x4 transform(position, rotation, 1.0f);
  520. switch (dGeomGetClass(geometry_))
  521. {
  522. case dSphereClass:
  523. {
  524. float radius = dGeomSphereGetRadius(geometry_);
  525. for (unsigned i = 0; i < 360; i += 45)
  526. {
  527. unsigned j = i + 45;
  528. float a = radius * sinf(i * M_DEGTORAD);
  529. float b = radius * cosf(i * M_DEGTORAD);
  530. float c = radius * sinf(j * M_DEGTORAD);
  531. float d = radius * cosf(j * M_DEGTORAD);
  532. Vector3 start, end;
  533. start = transform * Vector3(a, b, 0.0f);
  534. end = transform * Vector3(c, d, 0.0f);
  535. debug->AddLine(start, end, uintColor, depthTest);
  536. start = transform * Vector3(a, 0.0f, b);
  537. end = transform * Vector3(c, 0.0f, d);
  538. debug->AddLine(start, end, uintColor, depthTest);
  539. start = transform * Vector3(0.0f, a, b);
  540. end = transform * Vector3(0.0f, c, d);
  541. debug->AddLine(start, end, uintColor, depthTest);
  542. }
  543. }
  544. break;
  545. case dBoxClass:
  546. {
  547. dVector3 size;
  548. dGeomBoxGetLengths(geometry_, size);
  549. BoundingBox box(0.5f * Vector3(size[0], size[1], size[2]), 0.5f * Vector3(-size[0], -size[1], -size[2]));
  550. debug->AddBoundingBox(box, transform, *color, depthTest);
  551. }
  552. break;
  553. case dCapsuleClass:
  554. {
  555. float radius, length;
  556. dGeomCapsuleGetParams(geometry_, &radius, &length);
  557. for (unsigned i = 0; i < 360; i += 45)
  558. {
  559. unsigned j = i + 45;
  560. float a = radius * sinf(i * M_DEGTORAD);
  561. float b = radius * cosf(i * M_DEGTORAD);
  562. float c = radius * sinf(j * M_DEGTORAD);
  563. float d = radius * cosf(j * M_DEGTORAD);
  564. Vector3 start, end;
  565. start = transform * Vector3(a, b, 0.5f * length);
  566. end = transform * Vector3(c, d, 0.5f * length);
  567. debug->AddLine(start, end, uintColor, depthTest);
  568. start = transform * Vector3(a, b, -0.5f * length);
  569. end = transform * Vector3(c, d, -0.5f * length);
  570. debug->AddLine(start, end, uintColor, depthTest);
  571. if (!(i & 1))
  572. {
  573. start = transform * Vector3(a, b, 0.5f * length);
  574. end = transform * Vector3(a, b, -0.5f * length);
  575. debug->AddLine(start, end, uintColor, depthTest);
  576. }
  577. if (b > -M_EPSILON)
  578. {
  579. start = transform * Vector3(a, 0.0f, b + 0.5f * length);
  580. end = transform * Vector3(c, 0.0f, d + 0.5f * length);
  581. debug->AddLine(start, end, uintColor, depthTest);
  582. start = transform * Vector3(0.0f, a, b + 0.5f * length);
  583. end = transform * Vector3(0.0f, c, d + 0.5f * length);
  584. debug->AddLine(start, end, uintColor, depthTest);
  585. start = transform * Vector3(a, 0.0f, -b - 0.5f * length);
  586. end = transform * Vector3(c, 0.0f, -d - 0.5f * length);
  587. debug->AddLine(start, end, uintColor, depthTest);
  588. start = transform * Vector3(0.0f, a, -b - 0.5f * length);
  589. end = transform * Vector3(0.0f, c, -d - 0.5f * length);
  590. debug->AddLine(start, end, uintColor, depthTest);
  591. }
  592. }
  593. }
  594. break;
  595. case dCylinderClass:
  596. {
  597. float radius, length;
  598. dGeomCylinderGetParams(geometry_, &radius, &length);
  599. for (unsigned i = 0; i < 360; i += 45)
  600. {
  601. unsigned j = i + 45;
  602. float a = radius * sinf(i * M_DEGTORAD);
  603. float b = radius * cosf(i * M_DEGTORAD);
  604. float c = radius * sinf(j * M_DEGTORAD);
  605. float d = radius * cosf(j * M_DEGTORAD);
  606. Vector3 start, end;
  607. start = transform * Vector3(a, b, 0.5f * length);
  608. end = transform * Vector3(c, d, 0.5f * length);
  609. debug->AddLine(start, end, uintColor, depthTest);
  610. start = transform * Vector3(a, b, -0.5f * length);
  611. end = transform * Vector3(c, d, -0.5f * length);
  612. debug->AddLine(start, end, uintColor, depthTest);
  613. start = transform * Vector3(a, b, 0.5f * length);
  614. end = transform * Vector3(a, b, -0.5f * length);
  615. debug->AddLine(start, end, uintColor, depthTest);
  616. }
  617. }
  618. break;
  619. case dTriMeshClass:
  620. {
  621. TriangleMeshData* data = static_cast<TriangleMeshData*>(geometryData_.Get());
  622. if (data)
  623. {
  624. debug->AddTriangleMesh(data->vertexData_.Get(), sizeof(Vector3), data->indexData_.Get(), sizeof(unsigned), 0,
  625. data->indexCount_, transform, *color, depthTest);
  626. }
  627. }
  628. break;
  629. case dHeightfieldClass:
  630. {
  631. dHeightfieldDataID heightData = dGeomHeightfieldGetHeightfieldData(geometry_);
  632. unsigned xPoints = heightData->m_nWidthSamples;
  633. unsigned zPoints = heightData->m_nDepthSamples;
  634. float xWidth = heightData->m_fWidth;
  635. float zWidth = heightData->m_fDepth;
  636. float xBase = -0.5f * xWidth;
  637. float zBase = -0.5f * zWidth;
  638. float xSpacing = xWidth / (xPoints - 1);
  639. float zSpacing = zWidth / (zPoints - 1);
  640. float* heights = (float*)heightData->m_pHeightData;
  641. for (unsigned z = 0; z < zPoints - 1; ++z)
  642. {
  643. for (unsigned x = 0; x < xPoints - 1; ++x)
  644. {
  645. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  646. Vector3 b = transform * Vector3(xBase + (x + 1) * xSpacing, heights[z * xPoints + x + 1], zBase + z * zSpacing);
  647. Vector3 c = transform * Vector3(xBase + x * xSpacing, heights[(z + 1) * xPoints + x], zBase + (z + 1) * zSpacing);
  648. debug->AddLine(a, b, uintColor, depthTest);
  649. debug->AddLine(a, c, uintColor, depthTest);
  650. }
  651. }
  652. for (unsigned z = 0; z < zPoints - 1; ++z)
  653. {
  654. unsigned x = xPoints - 1;
  655. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  656. Vector3 b = transform * Vector3(xBase + x * xSpacing, heights[(z + 1) * xPoints + x], zBase + (z + 1) * zSpacing);
  657. debug->AddLine(a, b, uintColor, depthTest);
  658. }
  659. for (unsigned x = 0; x < xPoints - 1; ++x)
  660. {
  661. unsigned z = zPoints - 1;
  662. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  663. Vector3 b = transform * Vector3(xBase + (x + 1) * xSpacing, heights[z * xPoints + x + 1], zBase + z * zSpacing);
  664. debug->AddLine(a, b, uintColor, depthTest);
  665. }
  666. }
  667. break;
  668. }
  669. }
  670. }
  671. void CollisionShape::OnMarkedDirty(Node* node)
  672. {
  673. // Physics operations are not safe from worker threads
  674. Scene* scene = node->GetScene();
  675. if (scene && scene->IsThreadedUpdate())
  676. {
  677. scene->DelayedMarkedDirty(this);
  678. return;
  679. }
  680. // If scale has changed, must recreate the geometry
  681. if (node->GetWorldScale() != geometryScale_)
  682. CreateGeometry();
  683. else
  684. UpdateTransform(true);
  685. }
  686. void CollisionShape::SetModelAttr(ResourceRef value)
  687. {
  688. ResourceCache* cache = GetSubsystem<ResourceCache>();
  689. model_ = cache->GetResource<Model>(value.id_);
  690. recreateGeometry_ = true;
  691. }
  692. ResourceRef CollisionShape::GetModelAttr() const
  693. {
  694. return GetResourceRef(model_, Model::GetTypeStatic());
  695. }
  696. void CollisionShape::OnNodeSet(Node* node)
  697. {
  698. if (node)
  699. {
  700. Scene* scene = node->GetScene();
  701. if (scene)
  702. {
  703. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  704. if (physicsWorld_)
  705. physicsWorld_->AddCollisionShape(this);
  706. }
  707. node->AddListener(this);
  708. }
  709. }
  710. void CollisionShape::CreateGeometry()
  711. {
  712. PROFILE(CreateCollisionShape);
  713. if (!physicsWorld_)
  714. {
  715. LOGERROR("Null physics world, can not create collision shape");
  716. return;
  717. }
  718. // Destroy previous geometry if exists
  719. if (geometry_)
  720. {
  721. dGeomDestroy(geometry_);
  722. geometry_ = 0;
  723. }
  724. geometryScale_ = node_->GetWorldScale();
  725. Vector3 size = size_ * geometryScale_;
  726. dSpaceID space = physicsWorld_->GetSpace();
  727. switch (shapeType_)
  728. {
  729. case SHAPE_BOX:
  730. geometry_ = dCreateBox(space, size.x_, size.y_, size.z_);
  731. break;
  732. case SHAPE_SPHERE:
  733. geometry_ = dCreateSphere(space, 0.5f * size.x_);
  734. break;
  735. case SHAPE_CAPSULE:
  736. geometry_ = dCreateCapsule(space, 0.5f * size.x_, Max(size.y_ - size.x_, 0.0f));
  737. break;
  738. case SHAPE_CYLINDER:
  739. geometry_ = dCreateCylinder(space, 0.5f * size.x_, size.y_);
  740. break;
  741. case SHAPE_TRIANGLEMESH:
  742. case SHAPE_CONVEXHULL:
  743. {
  744. // For mesh cache lookup purposes, quantize size to 3 decimals only. Otherwise floating point inaccuracy from world
  745. // matrix multiplications and rotation/scale decomposing causes several slightly differing meshes to be created
  746. char sizeText[CONVERSION_BUFFER_LENGTH];
  747. sprintf(sizeText, "%.3f%.3f%.3f", size.x_, size.y_, size.z_);
  748. // Check the geometry cache
  749. String id = model_->GetName() + "_" + String(sizeText) + "_" + String(lodLevel_);
  750. if (shapeType_ == SHAPE_CONVEXHULL)
  751. id += "_" + String(thickness_);
  752. Map<String, SharedPtr<TriangleMeshData> >& cache = physicsWorld_->GetTriangleMeshCache();
  753. Map<String, SharedPtr<TriangleMeshData> >::Iterator j = cache.Find(id);
  754. if (j != cache.End())
  755. {
  756. geometry_ = dCreateTriMesh(space, j->second_->triMesh_, 0, 0, 0);
  757. geometryData_ = StaticCast<CollisionGeometryData>(j->second_);
  758. }
  759. else
  760. {
  761. SharedPtr<TriangleMeshData> newData(new TriangleMeshData(model_, shapeType_ == SHAPE_CONVEXHULL, thickness_,
  762. lodLevel_, size));
  763. cache[id] = newData;
  764. geometry_ = dCreateTriMesh(space, newData->triMesh_, 0, 0, 0);
  765. geometryData_ = StaticCast<CollisionGeometryData>(newData);
  766. }
  767. }
  768. break;
  769. case SHAPE_HEIGHTFIELD:
  770. {
  771. char sizeText[CONVERSION_BUFFER_LENGTH];
  772. sprintf(sizeText, "%.3f%.3f%.3f", size.x_, size.y_, size.z_);
  773. // Check the geometry cache
  774. String id = model_->GetName() + "_" + String(sizeText) + "_" + String(numPoints_) + "_" + String(thickness_) + "_" +
  775. String(lodLevel_);
  776. Map<String, SharedPtr<HeightfieldData> >& cache = physicsWorld_->GetHeightfieldCache();
  777. Map<String, SharedPtr<HeightfieldData> >::Iterator j = cache.Find(id);
  778. if (j != cache.End())
  779. {
  780. geometry_ = dCreateHeightfield(space, j->second_->heightfield_, 1);
  781. geometryData_ = StaticCast<CollisionGeometryData>(j->second_);
  782. }
  783. else
  784. {
  785. SharedPtr<HeightfieldData> newData(new HeightfieldData(model_, numPoints_, thickness_, lodLevel_, size));
  786. cache[id] = newData;
  787. geometry_ = dCreateHeightfield(space, newData->heightfield_, 1);
  788. geometryData_ = StaticCast<CollisionGeometryData>(newData);
  789. }
  790. }
  791. break;
  792. }
  793. // Set collision group and mask & userdata
  794. if (geometry_)
  795. {
  796. dGeomSetCategoryBits(geometry_, collisionLayer_);
  797. dGeomSetCollideBits(geometry_, collisionMask_);
  798. dGeomSetData(geometry_, this);
  799. }
  800. UpdateTransform();
  801. // If rigid body component exists, let it recalculate its mass now
  802. RigidBody* rigidBody = GetComponent<RigidBody>();
  803. if (rigidBody)
  804. rigidBody->UpdateMass();
  805. }
  806. void CollisionShape::ReleaseGeometry(bool notifyBody)
  807. {
  808. if (!physicsWorld_)
  809. return;
  810. if (geometry_)
  811. {
  812. dGeomDestroy(geometry_);
  813. geometry_ = 0;
  814. }
  815. model_.Reset();
  816. geometryData_.Reset();
  817. physicsWorld_->CleanupGeometryCache();
  818. // If rigid body component exists, let it recalculate its mass now
  819. if (notifyBody)
  820. {
  821. RigidBody* rigidBody = GetComponent<RigidBody>();
  822. if (rigidBody)
  823. rigidBody->UpdateMass();
  824. }
  825. }