CollisionShape.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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. void GetVertexAndIndexData(const Model* model, unsigned lodLevel, SharedArrayPtr<Vector3>& destVertexData, unsigned& destVertexCount,
  56. SharedArrayPtr<unsigned>& destIndexData, unsigned& destIndexCount, const Vector3& scale)
  57. {
  58. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  59. destVertexCount = 0;
  60. destIndexCount = 0;
  61. for (unsigned i = 0; i < geometries.Size(); ++i)
  62. {
  63. unsigned subGeometryLodLevel = Clamp(lodLevel, 0, geometries[i].Size());
  64. Geometry* geom = geometries[i][subGeometryLodLevel];
  65. if (!geom)
  66. continue;
  67. destVertexCount += geom->GetVertexCount();
  68. destIndexCount += geom->GetIndexCount();
  69. }
  70. if ((!destVertexCount) || (!destIndexCount))
  71. return;
  72. destVertexData = new Vector3[destVertexCount];
  73. destIndexData = new unsigned[destIndexCount];
  74. unsigned firstVertex = 0;
  75. unsigned firstIndex = 0;
  76. for (unsigned i = 0; i < geometries.Size(); ++i)
  77. {
  78. unsigned subGeometryLodLevel = lodLevel;
  79. if (subGeometryLodLevel >= geometries[i].Size())
  80. subGeometryLodLevel = geometries[i].Size() / 2;
  81. Geometry* geom = geometries[i][subGeometryLodLevel];
  82. if (!geom)
  83. continue;
  84. const unsigned char* vertexData;
  85. const unsigned char* indexData;
  86. unsigned vertexSize;
  87. unsigned indexSize;
  88. geom->LockRawData(vertexData, vertexSize, indexData, indexSize);
  89. if ((!vertexData) || (!indexData))
  90. continue;
  91. unsigned vertexStart = geom->GetVertexStart();
  92. unsigned vertexCount = geom->GetVertexCount();
  93. // Copy vertex data
  94. for (unsigned j = 0; j < vertexCount; ++j)
  95. {
  96. const Vector3& v = *((const Vector3*)(&vertexData[(vertexStart + j) * vertexSize]));
  97. destVertexData[firstVertex + j] = scale * v;
  98. }
  99. unsigned indexStart = geom->GetIndexStart();
  100. unsigned indexCount = geom->GetIndexCount();
  101. // 16-bit indices
  102. if (indexSize == sizeof(unsigned short))
  103. {
  104. const unsigned short* indices = (const unsigned short*)indexData;
  105. for (unsigned j = 0; j < indexCount; j += 3)
  106. {
  107. // Rebase the indices according to our vertex numbering
  108. destIndexData[firstIndex + j] = indices[indexStart + j] - vertexStart + firstVertex;
  109. destIndexData[firstIndex + j + 1] = indices[indexStart + j + 1] - vertexStart + firstVertex;
  110. destIndexData[firstIndex + j + 2] = indices[indexStart + j + 2] - vertexStart + firstVertex;
  111. }
  112. }
  113. // 32-bit indices
  114. else
  115. {
  116. const unsigned* indices = (const unsigned*)indexData;
  117. for (unsigned j = 0; j < indexCount; j += 3)
  118. {
  119. // Rebase the indices according to our vertex numbering
  120. destIndexData[firstIndex + j] = indices[indexStart + j] - vertexStart + firstVertex;
  121. destIndexData[firstIndex + j + 1] = indices[indexStart + j + 1] - vertexStart + firstVertex;
  122. destIndexData[firstIndex + j + 2] = indices[indexStart + j + 2] - vertexStart + firstVertex;
  123. }
  124. }
  125. firstVertex += vertexCount;
  126. firstIndex += indexCount;
  127. geom->UnlockRawData();
  128. }
  129. }
  130. TriangleMeshData::TriangleMeshData(Model* model, bool makeConvexHull, float thickness, unsigned lodLevel, const Vector3& scale) :
  131. triMesh_(0)
  132. {
  133. modelName_ = model->GetName();
  134. unsigned vertexCount;
  135. unsigned indexCount;
  136. if (!makeConvexHull)
  137. GetVertexAndIndexData(model, lodLevel, vertexData_, vertexCount, indexData_, indexCount, scale);
  138. else
  139. {
  140. SharedArrayPtr<Vector3> originalVertices;
  141. SharedArrayPtr<unsigned> originalIndices;
  142. unsigned originalVertexCount;
  143. unsigned originalIndexCount;
  144. GetVertexAndIndexData(model, lodLevel, originalVertices, originalVertexCount, originalIndices, originalIndexCount, scale);
  145. // Build the convex hull from the raw geometry
  146. StanHull::HullDesc desc;
  147. desc.SetHullFlag(StanHull::QF_TRIANGLES);
  148. desc.mVcount = originalVertexCount;
  149. desc.mVertices = (float*)originalVertices.GetPtr();
  150. desc.mVertexStride = 3 * sizeof(float);
  151. desc.mSkinWidth = thickness;
  152. StanHull::HullLibrary lib;
  153. StanHull::HullResult result;
  154. lib.CreateConvexHull(desc, result);
  155. vertexCount = result.mNumOutputVertices;
  156. indexCount = result.mNumIndices;
  157. // Copy vertex data
  158. vertexData_ = new Vector3[vertexCount];
  159. memcpy(vertexData_.GetPtr(), result.mOutputVertices, vertexCount * sizeof(Vector3));
  160. // Copy index data
  161. indexData_ = new unsigned[indexCount];
  162. memcpy(indexData_.GetPtr(), result.mIndices, indexCount * sizeof(unsigned));
  163. lib.ReleaseResult(result);
  164. }
  165. triMesh_ = dGeomTriMeshDataCreate();
  166. dGeomTriMeshDataBuildSingle(triMesh_, vertexData_.GetPtr(), sizeof(Vector3), vertexCount,
  167. indexData_.GetPtr(), indexCount, 3 * sizeof(unsigned));
  168. }
  169. TriangleMeshData::~TriangleMeshData()
  170. {
  171. if (triMesh_)
  172. {
  173. dGeomTriMeshDataDestroy(triMesh_);
  174. triMesh_ = 0;
  175. }
  176. }
  177. HeightfieldData::HeightfieldData(Model* model, IntVector2 numPoints, float thickness, unsigned lodLevel,
  178. const Vector3& scale) :
  179. heightfield_(0)
  180. {
  181. modelName_ = model->GetName();
  182. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  183. if (!geometries.Size())
  184. return;
  185. lodLevel = Clamp(lodLevel, 0, geometries[0].Size());
  186. Geometry* geom = geometries[0][lodLevel];
  187. if (!geom)
  188. return;
  189. const unsigned char* vertexData;
  190. const unsigned char* indexData;
  191. unsigned vertexSize;
  192. unsigned indexSize;
  193. geom->LockRawData(vertexData, vertexSize, indexData, indexSize);
  194. if ((!vertexData) || (!indexData))
  195. return;
  196. unsigned indexStart = geom->GetIndexStart();
  197. unsigned indexCount = geom->GetIndexCount();
  198. // If X & Z size not specified, try to guess them
  199. if (numPoints == IntVector2::ZERO)
  200. numPoints.x_ = numPoints.y_ = (int)sqrtf((float)geom->GetVertexCount());
  201. unsigned dataSize = numPoints.x_ * numPoints.y_;
  202. // Then allocate the heightfield
  203. BoundingBox box = model->GetBoundingBox();
  204. heightData_ = new float[dataSize];
  205. // Calculate spacing from model's bounding box
  206. float xSpacing = (box.max_.x_ - box.min_.x_) / (numPoints.x_ - 1);
  207. float zSpacing = (box.max_.z_ - box.min_.z_) / (numPoints.y_ - 1);
  208. // Initialize the heightfield with minimum height
  209. for (unsigned i = 0; i < dataSize; ++i)
  210. heightData_[i] = box.min_.y_ * scale.y_;
  211. unsigned vertexStart = geom->GetVertexStart();
  212. unsigned vertexCount = geom->GetVertexCount();
  213. // Now go through vertex data and fit the vertices into the heightfield
  214. for (unsigned i = vertexStart; i < vertexStart + vertexCount; ++i)
  215. {
  216. const Vector3& vertex = *((const Vector3*)(&vertexData[i * vertexSize]));
  217. int x = (int)((vertex.x_ - box.min_.x_) / xSpacing + 0.25f);
  218. int z = (int)((vertex.z_ - box.min_.z_) / zSpacing + 0.25f);
  219. if (x >= numPoints.x_)
  220. x = numPoints.x_ - 1;
  221. if (z >= numPoints.y_)
  222. z = numPoints.y_ - 1;
  223. if (vertex.y_ > heightData_[z * numPoints.x_ + x])
  224. heightData_[z * numPoints.x_ + x] = vertex.y_ * scale.y_;
  225. }
  226. geom->UnlockRawData();
  227. heightfield_ = dGeomHeightfieldDataCreate();
  228. dGeomHeightfieldDataBuildSingle(heightfield_, heightData_.GetPtr(), 0, (box.max_.x_ - box.min_.x_) * scale.x_,
  229. (box.max_.z_ - box.min_.z_) * scale.z_, numPoints.x_, numPoints.y_, 1.0f, 0.0f, thickness, 0);
  230. dGeomHeightfieldDataSetBounds(heightfield_, box.min_.y_ * scale.y_, box.max_.y_ * scale.y_);
  231. }
  232. HeightfieldData::~HeightfieldData()
  233. {
  234. if (heightfield_)
  235. {
  236. dGeomHeightfieldDataDestroy(heightfield_);
  237. heightfield_ = 0;
  238. }
  239. }
  240. OBJECTTYPESTATIC(CollisionShape);
  241. CollisionShape::CollisionShape(Context* context) :
  242. Component(context),
  243. geometry_(0),
  244. shapeType_(SHAPE_NONE),
  245. size_(Vector3::ZERO),
  246. thickness_(0.0f),
  247. lodLevel_(M_MAX_UNSIGNED),
  248. position_(Vector3::ZERO),
  249. rotation_(Quaternion::IDENTITY),
  250. geometryScale_(Vector3::UNITY),
  251. collisionGroup_(M_MAX_UNSIGNED),
  252. collisionMask_(M_MAX_UNSIGNED),
  253. friction_(DEFAULT_FRICTION),
  254. bounce_(DEFAULT_BOUNCE)
  255. {
  256. }
  257. CollisionShape::~CollisionShape()
  258. {
  259. Clear();
  260. }
  261. void CollisionShape::RegisterObject(Context* context)
  262. {
  263. context->RegisterFactory<CollisionShape>();
  264. ENUM_ATTRIBUTE(CollisionShape, "Shape Type", shapeType_, typeNames, SHAPE_NONE);
  265. ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Size", size_, Vector3::ZERO);
  266. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Hull Thickness", thickness_, 0.0f);
  267. ATTRIBUTE(CollisionShape, VAR_INT, "Model LOD Level", lodLevel_, M_MAX_UNSIGNED);
  268. ATTRIBUTE(CollisionShape, VAR_VECTOR3, "Offset Position", position_, Vector3::ZERO);
  269. ATTRIBUTE(CollisionShape, VAR_QUATERNION, "Rotation", rotation_, Quaternion::IDENTITY);
  270. ATTRIBUTE(CollisionShape, VAR_INT, "Collision Group", collisionGroup_, M_MAX_UNSIGNED);
  271. ATTRIBUTE(CollisionShape, VAR_INT, "Collision Mask", collisionMask_, M_MAX_UNSIGNED);
  272. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Friction", friction_, DEFAULT_FRICTION);
  273. ATTRIBUTE(CollisionShape, VAR_FLOAT, "Bounce", bounce_, DEFAULT_BOUNCE);
  274. ATTRIBUTE(CollisionShape, VAR_RESOURCEREF, "Model", model_, ResourceRef(Model::GetTypeStatic()));
  275. }
  276. void CollisionShape::OnSetAttribute(const AttributeInfo& attr, const Variant& value)
  277. {
  278. ResourceCache* cache = GetSubsystem<ResourceCache>();
  279. switch (attr.offset_)
  280. {
  281. case offsetof(CollisionShape, model_):
  282. model_ = cache->GetResource<Model>(value.GetResourceRef().id_);
  283. break;
  284. default:
  285. Serializable::OnSetAttribute(attr, value);
  286. break;
  287. }
  288. }
  289. Variant CollisionShape::OnGetAttribute(const AttributeInfo& attr)
  290. {
  291. switch (attr.offset_)
  292. {
  293. case offsetof(CollisionShape, model_):
  294. return GetResourceRef(model_, Model::GetTypeStatic());
  295. default:
  296. return Serializable::OnGetAttribute(attr);
  297. }
  298. }
  299. void CollisionShape::PostLoad()
  300. {
  301. CreateGeometry();
  302. }
  303. void CollisionShape::Clear()
  304. {
  305. ReleaseGeometry();
  306. shapeType_ = SHAPE_NONE;
  307. }
  308. void CollisionShape::SetSphere(float radius, const Vector3& position, const Quaternion& rotation)
  309. {
  310. ReleaseGeometry();
  311. shapeType_ = SHAPE_SPHERE;
  312. size_ = Vector3(radius, radius, radius);
  313. position_ = position;
  314. rotation_ = rotation;
  315. CreateGeometry();
  316. }
  317. void CollisionShape::SetBox(const Vector3& size, const Vector3& position, const Quaternion& rotation)
  318. {
  319. ReleaseGeometry();
  320. shapeType_ = SHAPE_BOX;
  321. size_ = size;
  322. position_ = position;
  323. rotation_ = rotation;
  324. CreateGeometry();
  325. }
  326. void CollisionShape::SetCapsule(float radius, float height, const Vector3& position, const Quaternion& rotation)
  327. {
  328. ReleaseGeometry();
  329. shapeType_ = SHAPE_CAPSULE;
  330. size_ = Vector3(radius, radius, height);
  331. position_ = position;
  332. rotation_ = rotation;
  333. CreateGeometry();
  334. }
  335. void CollisionShape::SetCylinder(float radius, float height, const Vector3& position, const Quaternion& rotation)
  336. {
  337. ReleaseGeometry();
  338. shapeType_ = SHAPE_CYLINDER;
  339. size_ = Vector3(radius, radius, height);
  340. position_ = position;
  341. rotation_ = rotation;
  342. CreateGeometry();
  343. }
  344. void CollisionShape::SetTriangleMesh(Model* model, unsigned lodLevel, const Vector3& position, const Quaternion& rotation)
  345. {
  346. PROFILE(SetTriangleMeshShape);
  347. if (!model)
  348. {
  349. LOGERROR("Null model, can not set triangle mesh");
  350. return;
  351. }
  352. ReleaseGeometry();
  353. model_ = model;
  354. shapeType_ = SHAPE_TRIANGLEMESH;
  355. lodLevel_ = lodLevel;
  356. size_ = model->GetBoundingBox().GetSize();
  357. position_ = position;
  358. rotation_ = rotation;
  359. CreateGeometry();
  360. }
  361. void CollisionShape::SetHeightfield(Model* model, const IntVector2& numPoints, float thickness, unsigned lodLevel, const Vector3& position, const Quaternion& rotation)
  362. {
  363. PROFILE(SetHeightFieldShape);
  364. if (!model)
  365. {
  366. LOGERROR("Null model, can not set heightfield");
  367. return;
  368. }
  369. ReleaseGeometry();
  370. model_ = model;
  371. shapeType_ = SHAPE_HEIGHTFIELD;
  372. numPoints_ = numPoints;
  373. thickness_ = thickness;
  374. lodLevel_ = lodLevel;
  375. position_ = position;
  376. rotation_ = rotation;
  377. size_ = model->GetBoundingBox().GetSize();
  378. CreateGeometry();
  379. }
  380. void CollisionShape::SetConvexHull(Model* model, float thickness, unsigned lodLevel, const Vector3& position, const Quaternion& rotation)
  381. {
  382. PROFILE(SetConvexHullShape);
  383. if (!model)
  384. {
  385. LOGERROR("Null model, can not set convex hull");
  386. return;
  387. }
  388. ReleaseGeometry();
  389. model_ = model;
  390. shapeType_ = SHAPE_CONVEXHULL;
  391. thickness_ = thickness;
  392. lodLevel_ = lodLevel;
  393. size_ = model->GetBoundingBox().GetSize();
  394. position_ = position;
  395. rotation_ = rotation;
  396. CreateGeometry();
  397. }
  398. void CollisionShape::SetPosition(const Vector3& position)
  399. {
  400. position_ = position;
  401. UpdateTransform();
  402. }
  403. void CollisionShape::SetRotation(const Quaternion& rotation)
  404. {
  405. rotation_ = rotation;
  406. UpdateTransform();
  407. }
  408. void CollisionShape::SetTransform(const Vector3& position, const Quaternion& rotation)
  409. {
  410. position_ = position;
  411. rotation_ = rotation;
  412. UpdateTransform();
  413. }
  414. void CollisionShape::SetCollisionGroup(unsigned group)
  415. {
  416. collisionGroup_ = group;
  417. if (geometry_)
  418. dGeomSetCategoryBits(geometry_, group);
  419. }
  420. void CollisionShape::SetCollisionMask(unsigned mask)
  421. {
  422. collisionMask_ = mask;
  423. if (geometry_)
  424. dGeomSetCollideBits(geometry_, mask);
  425. }
  426. void CollisionShape::SetFriction(float friction)
  427. {
  428. friction_ = Max(friction, 0.0f);
  429. }
  430. void CollisionShape::SetBounce(float bounce)
  431. {
  432. bounce_ = Max(bounce, 0.0f);
  433. }
  434. void CollisionShape::UpdateTransform()
  435. {
  436. if (!geometry_)
  437. return;
  438. // Get the ODE body ID from the RigidBody component, if it exists
  439. dBodyID body = 0;
  440. RigidBody* rigidBody = GetComponent<RigidBody>();
  441. if (rigidBody)
  442. body = rigidBody->GetBody();
  443. // If body already assigned, need to do nothing
  444. if (body)
  445. {
  446. if (dGeomGetBody(geometry_) == body)
  447. return;
  448. // Assign the body, then set offset transform if necessary
  449. dGeomSetBody(geometry_, body);
  450. if ((position_ != Vector3::ZERO) || (rotation_ != Quaternion::IDENTITY))
  451. {
  452. Vector3 offset = geometryScale_ * position_;
  453. dGeomSetOffsetPosition(geometry_, offset.x_, offset.y_, offset.z_);
  454. dGeomSetOffsetQuaternion(geometry_, rotation_.GetData());
  455. }
  456. }
  457. else
  458. {
  459. // No rigid body. Must update the geometry transform manually
  460. Vector3 nodePos = GetWorldPosition();
  461. Quaternion nodeRot = GetWorldRotation();
  462. Vector3 geoposition_ = nodePos + (nodeRot * (geometryScale_ * position_));
  463. Quaternion geomRot = nodeRot * rotation_;
  464. dGeomSetPosition(geometry_, geoposition_.x_, geoposition_.y_, geoposition_.z_);
  465. dGeomSetQuaternion(geometry_, geomRot.GetData());
  466. }
  467. }
  468. void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  469. {
  470. if (!geometry_)
  471. return;
  472. Color color(0.0f, 1.0f, 0.0f);
  473. RigidBody* rigidBody = GetComponent<RigidBody>();
  474. if ((rigidBody) && (rigidBody->IsActive()))
  475. color = Color(1.0f, 1.0f, 1.0f);
  476. // Drawing all the debug geometries of a large world may be expensive (especially triangle meshes)
  477. // so check the geometry AABB against the debug geometry frustum first
  478. float aabb[6];
  479. dGeomGetAABB(geometry_, aabb);
  480. BoundingBox box;
  481. box.min_.x_ = aabb[0];
  482. box.max_.x_ = aabb[1];
  483. box.min_.y_ = aabb[2];
  484. box.max_.y_ = aabb[3];
  485. box.min_.z_ = aabb[4];
  486. box.max_.z_ = aabb[5];
  487. if (!debug->IsInside(box))
  488. return;
  489. const dReal* pos = dGeomGetPosition(geometry_);
  490. dQuaternion quat;
  491. dGeomGetQuaternion(geometry_, quat);
  492. Matrix4x3 transform(Vector3(pos[0], pos[1], pos[2]), Quaternion(quat[0], quat[1], quat[2], quat[3]), 1.0f);
  493. switch (dGeomGetClass(geometry_))
  494. {
  495. case dSphereClass:
  496. {
  497. float radius = dGeomSphereGetRadius(geometry_);
  498. for (unsigned i = 0; i < 360; i += 45)
  499. {
  500. unsigned j = i + 45;
  501. float a = radius * sinf(i * M_DEGTORAD);
  502. float b = radius * cosf(i * M_DEGTORAD);
  503. float c = radius * sinf(j * M_DEGTORAD);
  504. float d = radius * cosf(j * M_DEGTORAD);
  505. Vector3 start, end;
  506. start = transform * Vector3(a, b, 0.0f);
  507. end = transform * Vector3(c, d, 0.0f);
  508. debug->AddLine(start, end, color, depthTest);
  509. start = transform * Vector3(a, 0.0f, b);
  510. end = transform * Vector3(c, 0.0f, d);
  511. debug->AddLine(start, end, color, depthTest);
  512. start = transform * Vector3(0.0f, a, b);
  513. end = transform * Vector3(0.0f, c, d);
  514. debug->AddLine(start, end, color, depthTest);
  515. }
  516. }
  517. break;
  518. case dBoxClass:
  519. {
  520. dVector3 size;
  521. dGeomBoxGetLengths(geometry_, size);
  522. BoundingBox box(0.5f * Vector3(size[0], size[1], size[2]), 0.5f * Vector3(-size[0], -size[1], -size[2]));
  523. debug->AddBoundingBox(box, transform, color, depthTest);
  524. }
  525. break;
  526. case dCapsuleClass:
  527. {
  528. float radius, length;
  529. dGeomCapsuleGetParams(geometry_, &radius, &length);
  530. for (unsigned i = 0; i < 360; i += 45)
  531. {
  532. unsigned j = i + 45;
  533. float a = radius * sinf(i * M_DEGTORAD);
  534. float b = radius * cosf(i * M_DEGTORAD);
  535. float c = radius * sinf(j * M_DEGTORAD);
  536. float d = radius * cosf(j * M_DEGTORAD);
  537. Vector3 start, end;
  538. start = transform * Vector3(a, b, 0.5f * length);
  539. end = transform * Vector3(c, d, 0.5f * length);
  540. debug->AddLine(start, end, color, depthTest);
  541. start = transform * Vector3(a, b, -0.5f * length);
  542. end = transform * Vector3(c, d, -0.5f * length);
  543. debug->AddLine(start, end, color, depthTest);
  544. if (!(i & 1))
  545. {
  546. start = transform * Vector3(a, b, 0.5f * length);
  547. end = transform * Vector3(a, b, -0.5f * length);
  548. debug->AddLine(start, end, color, depthTest);
  549. }
  550. if (b > -M_EPSILON)
  551. {
  552. start = transform * Vector3(a, 0.0f, b + 0.5f * length);
  553. end = transform * Vector3(c, 0.0f, d + 0.5f * length);
  554. debug->AddLine(start, end, color, depthTest);
  555. start = transform * Vector3(0.0f, a, b + 0.5f * length);
  556. end = transform * Vector3(0.0f, c, d + 0.5f * length);
  557. debug->AddLine(start, end, color, depthTest);
  558. start = transform * Vector3(a, 0.0f, -b - 0.5f * length);
  559. end = transform * Vector3(c, 0.0f, -d - 0.5f * length);
  560. debug->AddLine(start, end, color, depthTest);
  561. start = transform * Vector3(0.0f, a, -b - 0.5f * length);
  562. end = transform * Vector3(0.0f, c, -d - 0.5f * length);
  563. debug->AddLine(start, end, color, depthTest);
  564. }
  565. }
  566. }
  567. break;
  568. case dCylinderClass:
  569. {
  570. float radius, length;
  571. dGeomCylinderGetParams(geometry_, &radius, &length);
  572. for (unsigned i = 0; i < 360; i += 45)
  573. {
  574. unsigned j = i + 45;
  575. float a = radius * sinf(i * M_DEGTORAD);
  576. float b = radius * cosf(i * M_DEGTORAD);
  577. float c = radius * sinf(j * M_DEGTORAD);
  578. float d = radius * cosf(j * M_DEGTORAD);
  579. Vector3 start, end;
  580. start = transform * Vector3(a, b, 0.5f * length);
  581. end = transform * Vector3(c, d, 0.5f * length);
  582. debug->AddLine(start, end, color, depthTest);
  583. start = transform * Vector3(a, b, -0.5f * length);
  584. end = transform * Vector3(c, d, -0.5f * length);
  585. debug->AddLine(start, end, color, depthTest);
  586. start = transform * Vector3(a, b, 0.5f * length);
  587. end = transform * Vector3(a, b, -0.5f * length);
  588. debug->AddLine(start, end, color, depthTest);
  589. }
  590. }
  591. break;
  592. case dTriMeshClass:
  593. {
  594. unsigned numTriangles = dGeomTriMeshGetTriangleCount(geometry_);
  595. for (unsigned i = 0; i < numTriangles; ++i)
  596. {
  597. dVector3 v0;
  598. dVector3 v1;
  599. dVector3 v2;
  600. dGeomTriMeshGetTriangle(geometry_, i, &v0, &v1, &v2);
  601. Vector3 a(v0[0], v0[1], v0[2]);
  602. Vector3 b(v1[0], v1[1], v1[2]);
  603. Vector3 c(v2[0], v2[1], v2[2]);
  604. debug->AddLine(a, b, color, depthTest);
  605. debug->AddLine(b, c, color, depthTest);
  606. debug->AddLine(c, a, color, depthTest);
  607. }
  608. }
  609. break;
  610. case dHeightfieldClass:
  611. {
  612. dHeightfieldDataID heightData = dGeomHeightfieldGetHeightfieldData(geometry_);
  613. unsigned xPoints = heightData->m_nWidthSamples;
  614. unsigned zPoints = heightData->m_nDepthSamples;
  615. float xWidth = heightData->m_fWidth;
  616. float zWidth = heightData->m_fDepth;
  617. float xBase = -0.5f * xWidth;
  618. float zBase = -0.5f * zWidth;
  619. float xSpacing = xWidth / (xPoints - 1);
  620. float zSpacing = zWidth / (zPoints - 1);
  621. float* heights = (float*)heightData->m_pHeightData;
  622. for (unsigned z = 0; z < zPoints - 1; ++z)
  623. {
  624. for (unsigned x = 0; x < xPoints - 1; ++x)
  625. {
  626. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  627. Vector3 b = transform * Vector3(xBase + (x + 1) * xSpacing, heights[z * xPoints + x + 1], zBase + z * zSpacing);
  628. Vector3 c = transform * Vector3(xBase + x * xSpacing, heights[(z + 1) * xPoints + x], zBase + (z + 1) * zSpacing);
  629. debug->AddLine(a, b, color, depthTest);
  630. debug->AddLine(a, c, color, depthTest);
  631. }
  632. }
  633. for (unsigned z = 0; z < zPoints - 1; ++z)
  634. {
  635. unsigned x = xPoints - 1;
  636. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  637. Vector3 b = transform * Vector3(xBase + x * xSpacing, heights[(z + 1) * xPoints + x], zBase + (z + 1) * zSpacing);
  638. debug->AddLine(a, b, color, depthTest);
  639. }
  640. for (unsigned x = 0; x < xPoints - 1; ++x)
  641. {
  642. unsigned z = zPoints - 1;
  643. Vector3 a = transform * Vector3(xBase + x * xSpacing, heights[z * xPoints + x], zBase + z * zSpacing);
  644. Vector3 b = transform * Vector3(xBase + (x + 1) * xSpacing, heights[z * xPoints + x + 1], zBase + z * zSpacing);
  645. debug->AddLine(a, b, color, depthTest);
  646. }
  647. }
  648. break;
  649. }
  650. }
  651. void CollisionShape::OnMarkedDirty(Node* node)
  652. {
  653. // If scale has changed, must recreate the geometry
  654. if (GetWorldScale() != geometryScale_)
  655. CreateGeometry();
  656. else
  657. UpdateTransform();
  658. }
  659. void CollisionShape::OnNodeSet(Node* node)
  660. {
  661. if (node)
  662. {
  663. Scene* scene = node->GetScene();
  664. if (scene)
  665. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  666. node->AddListener(this);
  667. }
  668. }
  669. void CollisionShape::CreateGeometry()
  670. {
  671. PROFILE(CreateCollisionShape);
  672. if (!physicsWorld_)
  673. {
  674. LOGERROR("Null physics world, can not create collision shape");
  675. return;
  676. }
  677. // Destroy previous geometry if exists
  678. if (geometry_)
  679. {
  680. dGeomDestroy(geometry_);
  681. geometry_ = 0;
  682. }
  683. geometryScale_ = GetWorldScale();
  684. Vector3 size = size_ * geometryScale_;
  685. dSpaceID space = physicsWorld_->GetSpace();
  686. switch (shapeType_)
  687. {
  688. case SHAPE_BOX:
  689. geometry_ = dCreateBox(space, size.x_, size.y_, size.z_);
  690. break;
  691. case SHAPE_SPHERE:
  692. geometry_ = dCreateSphere(space, size.x_);
  693. break;
  694. case SHAPE_CAPSULE:
  695. geometry_ = dCreateCapsule(space, size.x_, size.z_);
  696. break;
  697. case SHAPE_CYLINDER:
  698. geometry_ = dCreateCylinder(space, size.x_, size.z_);
  699. break;
  700. case SHAPE_TRIANGLEMESH:
  701. case SHAPE_CONVEXHULL:
  702. {
  703. // Check the geometry cache
  704. String id = model_->GetName() + "_" + geometryScale_ + "_" + lodLevel_;
  705. if (shapeType_ == SHAPE_CONVEXHULL)
  706. id += "_" + String(thickness_);
  707. Map<String, SharedPtr<TriangleMeshData> >& cache = physicsWorld_->GetTriangleMeshCache();
  708. Map<String, SharedPtr<TriangleMeshData> >::Iterator j = cache.Find(id);
  709. if (j != cache.End())
  710. {
  711. geometry_ = dCreateTriMesh(space, j->second_->triMesh_, 0, 0, 0);
  712. geometryData_ = StaticCast<CollisionGeometryData>(j->second_);
  713. }
  714. else
  715. {
  716. SharedPtr<TriangleMeshData> newData(new TriangleMeshData(model_, shapeType_ == SHAPE_CONVEXHULL, thickness_,
  717. lodLevel_, geometryScale_));
  718. cache[id] = newData;
  719. geometry_ = dCreateTriMesh(space, newData->triMesh_, 0, 0, 0);
  720. geometryData_ = StaticCast<CollisionGeometryData>(newData);
  721. }
  722. }
  723. break;
  724. case SHAPE_HEIGHTFIELD:
  725. {
  726. // Check the geometry cache
  727. String id = model_->GetName() + "_" + numPoints_ + "_" + thickness_ + "_" + lodLevel_;
  728. Map<String, SharedPtr<HeightfieldData> >& cache = physicsWorld_->GetHeightfieldCache();
  729. Map<String, SharedPtr<HeightfieldData> >::Iterator j = cache.Find(id);
  730. if (j != cache.End())
  731. {
  732. geometry_ = dCreateHeightfield(space, j->second_->heightfield_, 1);
  733. geometryData_ = StaticCast<CollisionGeometryData>(j->second_);
  734. }
  735. else
  736. {
  737. SharedPtr<HeightfieldData> newData(new HeightfieldData(model_, numPoints_, thickness_, lodLevel_, geometryScale_));
  738. cache[id] = newData;
  739. geometry_ = dCreateHeightfield(space, newData->heightfield_, 1);
  740. geometryData_ = StaticCast<CollisionGeometryData>(newData);
  741. }
  742. }
  743. break;
  744. }
  745. // Set collision group and mask & userdata
  746. if (geometry_)
  747. {
  748. dGeomSetCategoryBits(geometry_, collisionGroup_);
  749. dGeomSetCollideBits(geometry_, collisionMask_);
  750. dGeomSetData(geometry_, this);
  751. }
  752. UpdateTransform();
  753. // If rigid body component exists, let it recalculate its mass now
  754. RigidBody* rigidBody = GetComponent<RigidBody>();
  755. if (rigidBody)
  756. rigidBody->UpdateMass();
  757. }
  758. void CollisionShape::ReleaseGeometry(bool notifyBody)
  759. {
  760. if (geometry_)
  761. {
  762. dGeomDestroy(geometry_);
  763. geometry_ = 0;
  764. }
  765. model_.Reset();
  766. geometryData_.Reset();
  767. if (physicsWorld_)
  768. physicsWorld_->CleanupGeometryCache();
  769. // If rigid body component exists, let it recalculate its mass now
  770. if (notifyBody)
  771. {
  772. RigidBody* rigidBody = GetComponent<RigidBody>();
  773. if (rigidBody)
  774. rigidBody->UpdateMass();
  775. }
  776. }