PhysicsController.cpp 30 KB

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