PhysicsController.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. #include "Base.h"
  2. #include "Game.h"
  3. #include "MeshPart.h"
  4. #include "PhysicsController.h"
  5. #include "PhysicsMotionState.h"
  6. #include "SceneLoader.h"
  7. // The initial capacity of the Bullet debug drawer's vertex batch.
  8. #define INITIAL_CAPACITY 280
  9. namespace gameplay
  10. {
  11. const int PhysicsController::DIRTY = 0x01;
  12. const int PhysicsController::COLLISION = 0x02;
  13. const int PhysicsController::REGISTERED = 0x04;
  14. const int PhysicsController::REMOVE = 0x08;
  15. PhysicsController::PhysicsController()
  16. : _collisionConfiguration(NULL), _dispatcher(NULL),
  17. _overlappingPairCache(NULL), _solver(NULL), _world(NULL), _debugDrawer(NULL),
  18. _status(PhysicsController::Listener::DEACTIVATED), _listeners(NULL),
  19. _gravity(btScalar(0.0), btScalar(-9.8), btScalar(0.0))
  20. {
  21. // Default gravity is 9.8 along the negative Y axis.
  22. }
  23. PhysicsController::~PhysicsController()
  24. {
  25. SAFE_DELETE(_debugDrawer);
  26. SAFE_DELETE(_listeners);
  27. }
  28. void PhysicsController::addStatusListener(Listener* listener)
  29. {
  30. if (!_listeners)
  31. _listeners = new std::vector<Listener*>();
  32. _listeners->push_back(listener);
  33. }
  34. PhysicsFixedConstraint* PhysicsController::createFixedConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  35. {
  36. checkConstraintRigidBodies(a, b);
  37. PhysicsFixedConstraint* constraint = new PhysicsFixedConstraint(a, b);
  38. addConstraint(a, b, constraint);
  39. return constraint;
  40. }
  41. PhysicsGenericConstraint* PhysicsController::createGenericConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  42. {
  43. checkConstraintRigidBodies(a, b);
  44. PhysicsGenericConstraint* constraint = new PhysicsGenericConstraint(a, b);
  45. addConstraint(a, b, constraint);
  46. return constraint;
  47. }
  48. PhysicsGenericConstraint* PhysicsController::createGenericConstraint(PhysicsRigidBody* a,
  49. const Quaternion& rotationOffsetA, const Vector3& translationOffsetA, PhysicsRigidBody* b,
  50. const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  51. {
  52. checkConstraintRigidBodies(a, b);
  53. PhysicsGenericConstraint* constraint = new PhysicsGenericConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  54. addConstraint(a, b, constraint);
  55. return constraint;
  56. }
  57. PhysicsHingeConstraint* PhysicsController::createHingeConstraint(PhysicsRigidBody* a,
  58. const Quaternion& rotationOffsetA, const Vector3& translationOffsetA, PhysicsRigidBody* b,
  59. const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  60. {
  61. checkConstraintRigidBodies(a, b);
  62. PhysicsHingeConstraint* constraint = new PhysicsHingeConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  63. addConstraint(a, b, constraint);
  64. return constraint;
  65. }
  66. PhysicsSocketConstraint* PhysicsController::createSocketConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  67. {
  68. checkConstraintRigidBodies(a, b);
  69. PhysicsSocketConstraint* constraint = new PhysicsSocketConstraint(a, b);
  70. addConstraint(a, b, constraint);
  71. return constraint;
  72. }
  73. PhysicsSocketConstraint* PhysicsController::createSocketConstraint(PhysicsRigidBody* a,
  74. const Vector3& translationOffsetA, PhysicsRigidBody* b, const Vector3& translationOffsetB)
  75. {
  76. checkConstraintRigidBodies(a, b);
  77. PhysicsSocketConstraint* constraint = new PhysicsSocketConstraint(a,translationOffsetA, b, translationOffsetB);
  78. addConstraint(a, b, constraint);
  79. return constraint;
  80. }
  81. PhysicsSpringConstraint* PhysicsController::createSpringConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  82. {
  83. checkConstraintRigidBodies(a, b);
  84. PhysicsSpringConstraint* constraint = new PhysicsSpringConstraint(a, b);
  85. addConstraint(a, b, constraint);
  86. return constraint;
  87. }
  88. PhysicsSpringConstraint* PhysicsController::createSpringConstraint(PhysicsRigidBody* a, const Quaternion& rotationOffsetA, const Vector3& translationOffsetA,
  89. PhysicsRigidBody* b, const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  90. {
  91. checkConstraintRigidBodies(a, b);
  92. PhysicsSpringConstraint* constraint = new PhysicsSpringConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  93. addConstraint(a, b, constraint);
  94. return constraint;
  95. }
  96. const Vector3& PhysicsController::getGravity() const
  97. {
  98. return _gravity;
  99. }
  100. void PhysicsController::setGravity(const Vector3& gravity)
  101. {
  102. _gravity = gravity;
  103. if (_world)
  104. _world->setGravity(BV(_gravity));
  105. }
  106. void PhysicsController::drawDebug(const Matrix& viewProjection)
  107. {
  108. _debugDrawer->begin(viewProjection);
  109. _world->debugDrawWorld();
  110. _debugDrawer->end();
  111. }
  112. PhysicsRigidBody* PhysicsController::rayTest(const Ray& ray, float distance)
  113. {
  114. btCollisionWorld::ClosestRayResultCallback callback(BV(ray.getOrigin()), BV(distance * ray.getDirection()));
  115. _world->rayTest(BV(ray.getOrigin()), BV(distance * ray.getDirection()), callback);
  116. if (callback.hasHit())
  117. return getRigidBody(callback.m_collisionObject);
  118. return NULL;
  119. }
  120. btScalar PhysicsController::addSingleResult(btManifoldPoint& cp, const btCollisionObject* a, int partIdA, int indexA,
  121. const btCollisionObject* b, int partIdB, int indexB)
  122. {
  123. // Get pointers to the PhysicsRigidBody objects.
  124. PhysicsRigidBody* rbA = Game::getInstance()->getPhysicsController()->getRigidBody(a);
  125. PhysicsRigidBody* rbB = Game::getInstance()->getPhysicsController()->getRigidBody(b);
  126. // If the given rigid body pair has collided in the past, then
  127. // we notify the listeners only if the pair was not colliding
  128. // during the previous frame. Otherwise, it's a new pair, so add a
  129. // new entry to the cache with the appropriate listeners and notify them.
  130. PhysicsRigidBody::CollisionPair pair(rbA, rbB);
  131. if (_collisionStatus.count(pair) > 0)
  132. {
  133. const CollisionInfo& collisionInfo = _collisionStatus[pair];
  134. if ((collisionInfo._status & COLLISION) == 0)
  135. {
  136. std::vector<PhysicsRigidBody::Listener*>::const_iterator iter = collisionInfo._listeners.begin();
  137. for (; iter != collisionInfo._listeners.end(); iter++)
  138. {
  139. if ((collisionInfo._status & REMOVE) == 0)
  140. {
  141. (*iter)->collisionEvent(PhysicsRigidBody::Listener::COLLIDING, pair, Vector3(cp.getPositionWorldOnA().x(), cp.getPositionWorldOnA().y(), cp.getPositionWorldOnA().z()),
  142. Vector3(cp.getPositionWorldOnB().x(), cp.getPositionWorldOnB().y(), cp.getPositionWorldOnB().z()));
  143. }
  144. }
  145. }
  146. }
  147. else
  148. {
  149. CollisionInfo& collisionInfo = _collisionStatus[pair];
  150. // Initialized the status for the new entry.
  151. collisionInfo._status = 0;
  152. // Add the appropriate listeners.
  153. PhysicsRigidBody::CollisionPair p1(pair.rigidBodyA, NULL);
  154. if (_collisionStatus.count(p1) > 0)
  155. {
  156. const CollisionInfo& ci = _collisionStatus[p1];
  157. std::vector<PhysicsRigidBody::Listener*>::const_iterator iter = ci._listeners.begin();
  158. for (; iter != ci._listeners.end(); iter++)
  159. {
  160. collisionInfo._listeners.push_back(*iter);
  161. }
  162. }
  163. PhysicsRigidBody::CollisionPair p2(pair.rigidBodyB, NULL);
  164. if (_collisionStatus.count(p2) > 0)
  165. {
  166. const CollisionInfo& ci = _collisionStatus[p2];
  167. std::vector<PhysicsRigidBody::Listener*>::const_iterator iter = ci._listeners.begin();
  168. for (; iter != ci._listeners.end(); iter++)
  169. {
  170. collisionInfo._listeners.push_back(*iter);
  171. }
  172. }
  173. std::vector<PhysicsRigidBody::Listener*>::iterator iter = collisionInfo._listeners.begin();
  174. for (; iter != collisionInfo._listeners.end(); iter++)
  175. {
  176. if ((collisionInfo._status & REMOVE) == 0)
  177. {
  178. (*iter)->collisionEvent(PhysicsRigidBody::Listener::COLLIDING, pair, Vector3(cp.getPositionWorldOnA().x(), cp.getPositionWorldOnA().y(), cp.getPositionWorldOnA().z()),
  179. Vector3(cp.getPositionWorldOnB().x(), cp.getPositionWorldOnB().y(), cp.getPositionWorldOnB().z()));
  180. }
  181. }
  182. }
  183. // Update the collision status cache (we remove the dirty bit
  184. // set in the controller's update so that this particular collision pair's
  185. // status is not reset to 'no collision' when the controller's update completes).
  186. _collisionStatus[pair]._status &= ~DIRTY;
  187. _collisionStatus[pair]._status |= COLLISION;
  188. return 0.0f;
  189. }
  190. void PhysicsController::initialize()
  191. {
  192. _collisionConfiguration = new btDefaultCollisionConfiguration();
  193. _dispatcher = new btCollisionDispatcher(_collisionConfiguration);
  194. _overlappingPairCache = new btDbvtBroadphase();
  195. _solver = new btSequentialImpulseConstraintSolver();
  196. // Create the world.
  197. _world = new btDiscreteDynamicsWorld(_dispatcher, _overlappingPairCache, _solver, _collisionConfiguration);
  198. _world->setGravity(BV(_gravity));
  199. // Set up debug drawing.
  200. _debugDrawer = new DebugDrawer();
  201. _world->setDebugDrawer(_debugDrawer);
  202. }
  203. void PhysicsController::finalize()
  204. {
  205. // Clean up the world and its various components.
  206. SAFE_DELETE(_world);
  207. SAFE_DELETE(_solver);
  208. SAFE_DELETE(_overlappingPairCache);
  209. SAFE_DELETE(_dispatcher);
  210. SAFE_DELETE(_collisionConfiguration);
  211. }
  212. void PhysicsController::pause()
  213. {
  214. // Unused
  215. }
  216. void PhysicsController::resume()
  217. {
  218. // Unused
  219. }
  220. void PhysicsController::update(long elapsedTime)
  221. {
  222. // Update the physics simulation, with a maximum
  223. // of 10 simulation steps being performed in a given frame.
  224. //
  225. // Note that stepSimulation takes elapsed time in seconds
  226. // so we divide by 1000 to convert from milliseconds.
  227. _world->stepSimulation((float)elapsedTime * 0.001, 10);
  228. // If we have status listeners, then check if our status has changed.
  229. if (_listeners)
  230. {
  231. Listener::EventType oldStatus = _status;
  232. if (_status = Listener::DEACTIVATED)
  233. {
  234. for (int i = 0; i < _world->getNumCollisionObjects(); i++)
  235. {
  236. if (_world->getCollisionObjectArray()[i]->isActive())
  237. {
  238. _status = Listener::ACTIVATED;
  239. break;
  240. }
  241. }
  242. }
  243. else
  244. {
  245. bool allInactive = true;
  246. for (int i = 0; i < _world->getNumCollisionObjects(); i++)
  247. {
  248. if (_world->getCollisionObjectArray()[i]->isActive())
  249. {
  250. allInactive = false;
  251. break;
  252. }
  253. }
  254. if (allInactive)
  255. _status = Listener::DEACTIVATED;
  256. }
  257. // If the status has changed, notify our listeners.
  258. if (oldStatus != _status)
  259. {
  260. for (unsigned int k = 0; k < _listeners->size(); k++)
  261. {
  262. (*_listeners)[k]->statusEvent(_status);
  263. }
  264. }
  265. }
  266. // All statuses are set with the DIRTY bit before collision processing occurs.
  267. // During collision processing, if a collision occurs, the status is
  268. // set to COLLISION and the DIRTY bit is cleared. Then, after collision processing
  269. // is finished, if a given status is still dirty, the COLLISION bit is cleared.
  270. //
  271. // If an entry was marked for removal in the last frame, remove it now.
  272. // Dirty the collision status cache entries.
  273. std::map<PhysicsRigidBody::CollisionPair, CollisionInfo>::iterator iter = _collisionStatus.begin();
  274. for (; iter != _collisionStatus.end();)
  275. {
  276. if ((iter->second._status & REMOVE) != 0)
  277. {
  278. std::map<PhysicsRigidBody::CollisionPair, CollisionInfo>::iterator eraseIter = iter;
  279. iter++;
  280. _collisionStatus.erase(eraseIter);
  281. }
  282. else
  283. {
  284. iter->second._status |= DIRTY;
  285. iter++;
  286. }
  287. }
  288. // Go through the collision status cache and perform all registered collision tests.
  289. iter = _collisionStatus.begin();
  290. for (; iter != _collisionStatus.end(); iter++)
  291. {
  292. // If this collision pair was one that was registered for listening, then perform the collision test.
  293. // (In the case where we register for all collisions with a rigid body, there will be a lot
  294. // of collision pairs in the status cache that we did not explicitly register for.)
  295. if ((iter->second._status & REGISTERED) != 0 && (iter->second._status & REMOVE) == 0)
  296. {
  297. if (iter->first.rigidBodyB)
  298. _world->contactPairTest(iter->first.rigidBodyA->_body, iter->first.rigidBodyB->_body, *this);
  299. else
  300. _world->contactTest(iter->first.rigidBodyA->_body, *this);
  301. }
  302. }
  303. // Update all the collision status cache entries.
  304. iter = _collisionStatus.begin();
  305. for (; iter != _collisionStatus.end(); iter++)
  306. {
  307. if ((iter->second._status & DIRTY) != 0)
  308. {
  309. if ((iter->second._status & COLLISION) != 0 && iter->first.rigidBodyB)
  310. {
  311. unsigned int size = iter->second._listeners.size();
  312. for (unsigned int i = 0; i < size; i++)
  313. {
  314. iter->second._listeners[i]->collisionEvent(PhysicsRigidBody::Listener::NOT_COLLIDING, iter->first);
  315. }
  316. }
  317. iter->second._status &= ~COLLISION;
  318. }
  319. }
  320. }
  321. void PhysicsController::addCollisionListener(PhysicsRigidBody::Listener* listener, PhysicsRigidBody* rbA, PhysicsRigidBody* rbB)
  322. {
  323. PhysicsRigidBody::CollisionPair pair(rbA, rbB);
  324. // Make sure the status of the entry is initialized properly.
  325. if (_collisionStatus.count(pair) == 0)
  326. _collisionStatus[pair]._status = 0;
  327. // Add the listener and ensure the status includes that this collision pair is registered.
  328. _collisionStatus[pair]._listeners.push_back(listener);
  329. if ((_collisionStatus[pair]._status & PhysicsController::REGISTERED) == 0)
  330. _collisionStatus[pair]._status |= PhysicsController::REGISTERED;
  331. }
  332. void PhysicsController::addRigidBody(PhysicsRigidBody* body)
  333. {
  334. _world->addRigidBody(body->_body);
  335. _bodies.push_back(body);
  336. }
  337. void PhysicsController::removeRigidBody(PhysicsRigidBody* rigidBody)
  338. {
  339. // Find the rigid body and remove it from the world.
  340. for (int i = _world->getNumCollisionObjects() - 1; i >= 0 ; i--)
  341. {
  342. btCollisionObject* obj = _world->getCollisionObjectArray()[i];
  343. if (rigidBody->_body == obj)
  344. {
  345. _world->removeCollisionObject(obj);
  346. break;
  347. }
  348. }
  349. // Find the rigid body's collision shape and release the rigid body's reference to it.
  350. for (unsigned int i = 0; i < _shapes.size(); i++)
  351. {
  352. if (_shapes[i]->_shape == rigidBody->_shape)
  353. {
  354. if (_shapes[i]->getRefCount() == 1)
  355. {
  356. _shapes[i]->release();
  357. _shapes.erase(_shapes.begin() + i);
  358. }
  359. else
  360. _shapes[i]->release();
  361. break;
  362. }
  363. }
  364. // Remove the rigid body from the controller's list.
  365. for (unsigned int i = 0; i < _bodies.size(); i++)
  366. {
  367. if (_bodies[i] == rigidBody)
  368. {
  369. _bodies.erase(_bodies.begin() + i);
  370. break;
  371. }
  372. }
  373. // Find all references to the rigid body in the collision status cache and mark them for removal.
  374. std::map<PhysicsRigidBody::CollisionPair, CollisionInfo>::iterator iter = _collisionStatus.begin();
  375. for (; iter != _collisionStatus.end(); iter++)
  376. {
  377. if (iter->first.rigidBodyA == rigidBody || iter->first.rigidBodyB == rigidBody)
  378. iter->second._status |= REMOVE;
  379. }
  380. }
  381. PhysicsRigidBody* PhysicsController::getRigidBody(const btCollisionObject* collisionObject)
  382. {
  383. // Find the rigid body and remove it from the world.
  384. for (unsigned int i = 0; i < _bodies.size(); i++)
  385. {
  386. if (_bodies[i]->_body == collisionObject)
  387. return _bodies[i];
  388. }
  389. return NULL;
  390. }
  391. btCollisionShape* PhysicsController::createBox(const Vector3& min, const Vector3& max, const Vector3& scale)
  392. {
  393. btVector3 halfExtents(scale.x * 0.5 * abs(max.x - min.x), scale.y * 0.5 * abs(max.y - min.y), scale.z * 0.5 * abs(max.z - min.z));
  394. // Return the box shape from the cache if it already exists.
  395. for (unsigned int i = 0; i < _shapes.size(); i++)
  396. {
  397. if (_shapes[i]->_shape->getShapeType() == BOX_SHAPE_PROXYTYPE)
  398. {
  399. btBoxShape* box = static_cast<btBoxShape*>(_shapes[i]->_shape);
  400. if (box->getHalfExtentsWithMargin() == halfExtents)
  401. {
  402. _shapes[i]->addRef();
  403. return box;
  404. }
  405. }
  406. }
  407. // Create the box shape and add it to the cache.
  408. btBoxShape* box = bullet_new<btBoxShape>(halfExtents);
  409. _shapes.push_back(new PhysicsCollisionShape(box));
  410. return box;
  411. }
  412. btCollisionShape* PhysicsController::createCapsule(float radius, float height)
  413. {
  414. // Return the capsule shape from the cache if it already exists.
  415. for (unsigned int i = 0; i < _shapes.size(); i++)
  416. {
  417. if (_shapes[i]->_shape->getShapeType() == CAPSULE_SHAPE_PROXYTYPE)
  418. {
  419. btCapsuleShape* capsule = static_cast<btCapsuleShape*>(_shapes[i]->_shape);
  420. if (capsule->getRadius() == radius && capsule->getHalfHeight() == 0.5f * height)
  421. {
  422. _shapes[i]->addRef();
  423. return capsule;
  424. }
  425. }
  426. }
  427. // Create the capsule shape and add it to the cache.
  428. btCapsuleShape* capsule = bullet_new<btCapsuleShape>(radius, height);
  429. _shapes.push_back(new PhysicsCollisionShape(capsule));
  430. return capsule;
  431. }
  432. btCollisionShape* PhysicsController::createSphere(float radius, const Vector3& scale)
  433. {
  434. // Since sphere shapes depend only on the radius, the best we can do is take
  435. // the largest dimension and apply that as the uniform scale to the rigid body.
  436. float uniformScale = scale.x;
  437. if (uniformScale < scale.y)
  438. uniformScale = scale.y;
  439. if (uniformScale < scale.z)
  440. uniformScale = scale.z;
  441. // Return the sphere shape from the cache if it already exists.
  442. for (unsigned int i = 0; i < _shapes.size(); i++)
  443. {
  444. if (_shapes[i]->_shape->getShapeType() == SPHERE_SHAPE_PROXYTYPE)
  445. {
  446. btSphereShape* sphere = static_cast<btSphereShape*>(_shapes[i]->_shape);
  447. if (sphere->getRadius() == uniformScale * radius)
  448. {
  449. _shapes[i]->addRef();
  450. return sphere;
  451. }
  452. }
  453. }
  454. // Create the sphere shape and add it to the cache.
  455. btSphereShape* sphere = bullet_new<btSphereShape>(uniformScale * radius);
  456. _shapes.push_back(new PhysicsCollisionShape(sphere));
  457. return sphere;
  458. }
  459. btCollisionShape* PhysicsController::createMesh(PhysicsRigidBody* body, const Vector3& scale)
  460. {
  461. // Retrieve the mesh rigid body data from the loaded scene.
  462. const SceneLoader::MeshRigidBodyData* data = SceneLoader::getMeshRigidBodyData(body->_node->getId());
  463. // Copy the scaled vertex position data to the rigid body's local buffer.
  464. Matrix m;
  465. Matrix::createScale(scale, &m);
  466. unsigned int vertexCount = data->mesh->getVertexCount();
  467. body->_vertexData = new float[vertexCount * 3];
  468. Vector3 v;
  469. int vertexStride = data->mesh->getVertexFormat().getVertexSize();
  470. for (unsigned int i = 0; i < vertexCount; i++)
  471. {
  472. v.set(*((float*)&data->vertexData[i * vertexStride + 0 * sizeof(float)]),
  473. *((float*)&data->vertexData[i * vertexStride + 1 * sizeof(float)]),
  474. *((float*)&data->vertexData[i * vertexStride + 2 * sizeof(float)]));
  475. v *= m;
  476. memcpy(&(body->_vertexData[i * 3]), &v, sizeof(float) * 3);
  477. }
  478. btTriangleIndexVertexArray* meshInterface = bullet_new<btTriangleIndexVertexArray>();
  479. if (data->mesh->getPartCount() > 0)
  480. {
  481. PHY_ScalarType indexType = PHY_UCHAR;
  482. int indexStride = 0;
  483. MeshPart* meshPart = NULL;
  484. for (unsigned int i = 0; i < data->mesh->getPartCount(); i++)
  485. {
  486. meshPart = data->mesh->getPart(i);
  487. switch (meshPart->getIndexFormat())
  488. {
  489. case Mesh::INDEX8:
  490. indexType = PHY_UCHAR;
  491. indexStride = 1;
  492. break;
  493. case Mesh::INDEX16:
  494. indexType = PHY_SHORT;
  495. indexStride = 2;
  496. break;
  497. case Mesh::INDEX32:
  498. indexType = PHY_INTEGER;
  499. indexStride = 4;
  500. break;
  501. }
  502. // Copy the index data to the rigid body's local buffer.
  503. unsigned int indexDataSize = meshPart->getIndexCount() * indexStride;
  504. unsigned char* indexData = new unsigned char[indexDataSize];
  505. memcpy(indexData, data->indexData[i], indexDataSize);
  506. body->_indexData.push_back(indexData);
  507. // Create a btIndexedMesh object for the current mesh part.
  508. btIndexedMesh indexedMesh;
  509. indexedMesh.m_indexType = indexType;
  510. indexedMesh.m_numTriangles = meshPart->getIndexCount() / 3;
  511. indexedMesh.m_numVertices = meshPart->getIndexCount();
  512. indexedMesh.m_triangleIndexBase = (const unsigned char*)body->_indexData[i];
  513. indexedMesh.m_triangleIndexStride = indexStride*3;
  514. indexedMesh.m_vertexBase = (const unsigned char*)body->_vertexData;
  515. indexedMesh.m_vertexStride = sizeof(float)*3;
  516. indexedMesh.m_vertexType = PHY_FLOAT;
  517. // Add the indexed mesh data to the mesh interface.
  518. meshInterface->addIndexedMesh(indexedMesh, indexType);
  519. }
  520. }
  521. else
  522. {
  523. // Generate index data for the mesh locally in the rigid body.
  524. unsigned int* indexData = new unsigned int[data->mesh->getVertexCount()];
  525. for (unsigned int i = 0; i < data->mesh->getVertexCount(); i++)
  526. {
  527. indexData[i] = i;
  528. }
  529. body->_indexData.push_back((unsigned char*)indexData);
  530. // Create a single btIndexedMesh object for the mesh interface.
  531. btIndexedMesh indexedMesh;
  532. indexedMesh.m_indexType = PHY_INTEGER;
  533. indexedMesh.m_numTriangles = data->mesh->getVertexCount() / 3;
  534. indexedMesh.m_numVertices = data->mesh->getVertexCount();
  535. indexedMesh.m_triangleIndexBase = body->_indexData[0];
  536. indexedMesh.m_triangleIndexStride = sizeof(unsigned int);
  537. indexedMesh.m_vertexBase = (const unsigned char*)body->_vertexData;
  538. indexedMesh.m_vertexStride = sizeof(float)*3;
  539. indexedMesh.m_vertexType = PHY_FLOAT;
  540. // Set the data in the mesh interface.
  541. meshInterface->addIndexedMesh(indexedMesh, indexedMesh.m_indexType);
  542. }
  543. btBvhTriangleMeshShape* shape = bullet_new<btBvhTriangleMeshShape>(meshInterface, true);
  544. _shapes.push_back(new PhysicsCollisionShape(shape));
  545. return shape;
  546. }
  547. void PhysicsController::addConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b, PhysicsConstraint* constraint)
  548. {
  549. a->addConstraint(constraint);
  550. if (b)
  551. {
  552. b->addConstraint(constraint);
  553. }
  554. _world->addConstraint(constraint->_constraint);
  555. }
  556. bool PhysicsController::checkConstraintRigidBodies(PhysicsRigidBody* a, PhysicsRigidBody* b)
  557. {
  558. if (!a->supportsConstraints())
  559. {
  560. WARN_VARG("Rigid body '%s' does not support constraints; unexpected behavior may occur.", a->_node->getId());
  561. return false;
  562. }
  563. if (b && !b->supportsConstraints())
  564. {
  565. WARN_VARG("Rigid body '%s' does not support constraints; unexpected behavior may occur.", b->_node->getId());
  566. return false;
  567. }
  568. return true;
  569. }
  570. void PhysicsController::removeConstraint(PhysicsConstraint* constraint)
  571. {
  572. // Find the constraint and remove it from the physics world.
  573. for (int i = _world->getNumConstraints() - 1; i >= 0; i--)
  574. {
  575. btTypedConstraint* currentConstraint = _world->getConstraint(i);
  576. if (constraint->_constraint == currentConstraint)
  577. {
  578. _world->removeConstraint(currentConstraint);
  579. break;
  580. }
  581. }
  582. }
  583. PhysicsController::DebugDrawer::DebugDrawer()
  584. : _mode(btIDebugDraw::DBG_DrawAabb | btIDebugDraw::DBG_DrawConstraintLimits | btIDebugDraw::DBG_DrawConstraints |
  585. btIDebugDraw::DBG_DrawContactPoints | btIDebugDraw::DBG_DrawWireframe), _viewProjection(NULL), _meshBatch(NULL)
  586. {
  587. // Vertex shader for drawing colored lines.
  588. const char* vs_str =
  589. {
  590. "uniform mat4 u_viewProjectionMatrix;\n"
  591. "attribute vec4 a_position;\n"
  592. "attribute vec4 a_color;\n"
  593. "varying vec4 v_color;\n"
  594. "void main(void) {\n"
  595. " v_color = a_color;\n"
  596. " gl_Position = u_viewProjectionMatrix * a_position;\n"
  597. "}"
  598. };
  599. // Fragment shader for drawing colored lines.
  600. const char* fs_str =
  601. {
  602. #ifdef OPENGL_ES
  603. "precision highp float;\n"
  604. #endif
  605. "varying vec4 v_color;\n"
  606. "void main(void) {\n"
  607. " gl_FragColor = v_color;\n"
  608. "}"
  609. };
  610. Effect* effect = Effect::createFromSource(vs_str, fs_str);
  611. Material* material = Material::create(effect);
  612. VertexFormat::Element elements[] =
  613. {
  614. VertexFormat::Element(VertexFormat::POSITION, 3),
  615. VertexFormat::Element(VertexFormat::COLOR, 4),
  616. };
  617. _meshBatch = MeshBatch::create(VertexFormat(elements, 2), Mesh::LINES, material, false);
  618. SAFE_RELEASE(material);
  619. SAFE_RELEASE(effect);
  620. }
  621. PhysicsController::DebugDrawer::~DebugDrawer()
  622. {
  623. SAFE_DELETE(_meshBatch);
  624. }
  625. void PhysicsController::DebugDrawer::begin(const Matrix& viewProjection)
  626. {
  627. _viewProjection = &viewProjection;
  628. _meshBatch->begin();
  629. }
  630. void PhysicsController::DebugDrawer::end()
  631. {
  632. _meshBatch->getMaterial()->getParameter("u_viewProjectionMatrix")->setValue(_viewProjection);
  633. _meshBatch->draw();
  634. _meshBatch->end();
  635. }
  636. void PhysicsController::DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& fromColor, const btVector3& toColor)
  637. {
  638. static DebugDrawer::DebugVertex fromVertex, toVertex;
  639. fromVertex.x = from.getX();
  640. fromVertex.y = from.getY();
  641. fromVertex.z = from.getZ();
  642. fromVertex.r = fromColor.getX();
  643. fromVertex.g = fromColor.getY();
  644. fromVertex.b = fromColor.getZ();
  645. fromVertex.a = 1.0f;
  646. toVertex.x = to.getX();
  647. toVertex.y = to.getY();
  648. toVertex.z = to.getZ();
  649. toVertex.r = toColor.getX();
  650. toVertex.g = toColor.getY();
  651. toVertex.b = toColor.getZ();
  652. toVertex.a = 1.0f;
  653. _meshBatch->add(&fromVertex, 1);
  654. _meshBatch->add(&toVertex, 1);
  655. }
  656. void PhysicsController::DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color)
  657. {
  658. drawLine(from, to, color, color);
  659. }
  660. void PhysicsController::DebugDrawer::drawContactPoint(const btVector3& pointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color)
  661. {
  662. drawLine(pointOnB, pointOnB + normalOnB, color);
  663. }
  664. void PhysicsController::DebugDrawer::reportErrorWarning(const char* warningString)
  665. {
  666. WARN(warningString);
  667. }
  668. void PhysicsController::DebugDrawer::draw3dText(const btVector3& location, const char* textString)
  669. {
  670. WARN("Physics debug drawing: 3D text is not supported.");
  671. }
  672. void PhysicsController::DebugDrawer::setDebugMode(int mode)
  673. {
  674. _mode = mode;
  675. }
  676. int PhysicsController::DebugDrawer::getDebugMode() const
  677. {
  678. return _mode;
  679. }
  680. }