PhysicsController.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  1. #include "Base.h"
  2. #include "PhysicsController.h"
  3. #include "PhysicsRigidBody.h"
  4. #include "PhysicsCharacter.h"
  5. #include "PhysicsMotionState.h"
  6. #include "Game.h"
  7. #include "MeshPart.h"
  8. #include "Bundle.h"
  9. #include "BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h"
  10. // The initial capacity of the Bullet debug drawer's vertex batch.
  11. #define INITIAL_CAPACITY 280
  12. namespace gameplay
  13. {
  14. const int PhysicsController::DIRTY = 0x01;
  15. const int PhysicsController::COLLISION = 0x02;
  16. const int PhysicsController::REGISTERED = 0x04;
  17. const int PhysicsController::REMOVE = 0x08;
  18. PhysicsController::PhysicsController()
  19. : _collisionConfiguration(NULL), _dispatcher(NULL),
  20. _overlappingPairCache(NULL), _solver(NULL), _world(NULL), _ghostPairCallback(NULL),
  21. _debugDrawer(NULL), _status(PhysicsController::Listener::DEACTIVATED), _listeners(NULL),
  22. _gravity(btScalar(0.0), btScalar(-9.8), btScalar(0.0))
  23. {
  24. // Default gravity is 9.8 along the negative Y axis.
  25. }
  26. PhysicsController::~PhysicsController()
  27. {
  28. SAFE_DELETE(_ghostPairCallback);
  29. SAFE_DELETE(_debugDrawer);
  30. SAFE_DELETE(_listeners);
  31. }
  32. void PhysicsController::addStatusListener(Listener* listener)
  33. {
  34. if (!_listeners)
  35. _listeners = new std::vector<Listener*>();
  36. _listeners->push_back(listener);
  37. }
  38. PhysicsFixedConstraint* PhysicsController::createFixedConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  39. {
  40. checkConstraintRigidBodies(a, b);
  41. PhysicsFixedConstraint* constraint = new PhysicsFixedConstraint(a, b);
  42. addConstraint(a, b, constraint);
  43. return constraint;
  44. }
  45. PhysicsGenericConstraint* PhysicsController::createGenericConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  46. {
  47. checkConstraintRigidBodies(a, b);
  48. PhysicsGenericConstraint* constraint = new PhysicsGenericConstraint(a, b);
  49. addConstraint(a, b, constraint);
  50. return constraint;
  51. }
  52. PhysicsGenericConstraint* PhysicsController::createGenericConstraint(PhysicsRigidBody* a,
  53. const Quaternion& rotationOffsetA, const Vector3& translationOffsetA, PhysicsRigidBody* b,
  54. const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  55. {
  56. checkConstraintRigidBodies(a, b);
  57. PhysicsGenericConstraint* constraint = new PhysicsGenericConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  58. addConstraint(a, b, constraint);
  59. return constraint;
  60. }
  61. PhysicsHingeConstraint* PhysicsController::createHingeConstraint(PhysicsRigidBody* a,
  62. const Quaternion& rotationOffsetA, const Vector3& translationOffsetA, PhysicsRigidBody* b,
  63. const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  64. {
  65. checkConstraintRigidBodies(a, b);
  66. PhysicsHingeConstraint* constraint = new PhysicsHingeConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  67. addConstraint(a, b, constraint);
  68. return constraint;
  69. }
  70. PhysicsSocketConstraint* PhysicsController::createSocketConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  71. {
  72. checkConstraintRigidBodies(a, b);
  73. PhysicsSocketConstraint* constraint = new PhysicsSocketConstraint(a, b);
  74. addConstraint(a, b, constraint);
  75. return constraint;
  76. }
  77. PhysicsSocketConstraint* PhysicsController::createSocketConstraint(PhysicsRigidBody* a,
  78. const Vector3& translationOffsetA, PhysicsRigidBody* b, const Vector3& translationOffsetB)
  79. {
  80. checkConstraintRigidBodies(a, b);
  81. PhysicsSocketConstraint* constraint = new PhysicsSocketConstraint(a,translationOffsetA, b, translationOffsetB);
  82. addConstraint(a, b, constraint);
  83. return constraint;
  84. }
  85. PhysicsSpringConstraint* PhysicsController::createSpringConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  86. {
  87. checkConstraintRigidBodies(a, b);
  88. PhysicsSpringConstraint* constraint = new PhysicsSpringConstraint(a, b);
  89. addConstraint(a, b, constraint);
  90. return constraint;
  91. }
  92. PhysicsSpringConstraint* PhysicsController::createSpringConstraint(PhysicsRigidBody* a, const Quaternion& rotationOffsetA, const Vector3& translationOffsetA,
  93. PhysicsRigidBody* b, const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  94. {
  95. checkConstraintRigidBodies(a, b);
  96. PhysicsSpringConstraint* constraint = new PhysicsSpringConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  97. addConstraint(a, b, constraint);
  98. return constraint;
  99. }
  100. const Vector3& PhysicsController::getGravity() const
  101. {
  102. return _gravity;
  103. }
  104. void PhysicsController::setGravity(const Vector3& gravity)
  105. {
  106. _gravity = gravity;
  107. if (_world)
  108. _world->setGravity(BV(_gravity));
  109. }
  110. void PhysicsController::drawDebug(const Matrix& viewProjection)
  111. {
  112. _debugDrawer->begin(viewProjection);
  113. _world->debugDrawWorld();
  114. _debugDrawer->end();
  115. }
  116. bool PhysicsController::rayTest(const Ray& ray, float distance, PhysicsController::HitResult* result)
  117. {
  118. btCollisionWorld::ClosestRayResultCallback callback(BV(ray.getOrigin()), BV(distance * ray.getDirection()));
  119. _world->rayTest(BV(ray.getOrigin()), BV(distance * ray.getDirection()), callback);
  120. if (callback.hasHit())
  121. {
  122. if (result)
  123. {
  124. result->object = getCollisionObject(callback.m_collisionObject);
  125. result->point.set(callback.m_hitPointWorld.x(), callback.m_hitPointWorld.y(), callback.m_hitPointWorld.z());
  126. result->fraction = callback.m_closestHitFraction;
  127. result->normal.set(callback.m_hitNormalWorld.x(), callback.m_hitNormalWorld.y(), callback.m_hitNormalWorld.z());
  128. }
  129. return true;
  130. }
  131. return false;
  132. }
  133. bool PhysicsController::sweepTest(PhysicsCollisionObject* object, const Vector3& endPosition, PhysicsController::HitResult* result)
  134. {
  135. class SweepTestCallback : public btCollisionWorld::ClosestConvexResultCallback
  136. {
  137. public:
  138. SweepTestCallback(PhysicsCollisionObject* me)
  139. : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)), me(me)
  140. {
  141. }
  142. btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)
  143. {
  144. PhysicsCollisionObject* object = reinterpret_cast<PhysicsCollisionObject*>(convexResult.m_hitCollisionObject->getUserPointer());
  145. if (object == me)
  146. return 1.0f;
  147. return ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace);
  148. }
  149. PhysicsCollisionObject* me;
  150. };
  151. PhysicsCollisionShape* shape = object->getCollisionShape();
  152. PhysicsCollisionShape::Type type = shape->getType();
  153. if (type != PhysicsCollisionShape::SHAPE_BOX && type != PhysicsCollisionShape::SHAPE_SPHERE && type != PhysicsCollisionShape::SHAPE_CAPSULE)
  154. return false; // unsupported type
  155. // Define the start transform
  156. btTransform start;
  157. start.setIdentity();
  158. if (object->getNode())
  159. {
  160. Vector3 translation;
  161. Quaternion rotation;
  162. const Matrix& m = object->getNode()->getWorldMatrix();
  163. m.getTranslation(&translation);
  164. m.getRotation(&rotation);
  165. start.setIdentity();
  166. start.setOrigin(BV(translation));
  167. start.setRotation(BQ(rotation));
  168. }
  169. // Define the end transform
  170. btTransform end(start);
  171. end.setOrigin(BV(endPosition));
  172. float d1 = object->getNode()->getTranslationWorld().distance(endPosition);
  173. float d2 = start.getOrigin().distance(end.getOrigin());
  174. // Perform bullet convex sweep test
  175. SweepTestCallback callback(object);
  176. // If the object is represented by a ghost object, use the ghost object's convex sweep test
  177. // since it is much faster than the world's version.
  178. // NOTE: Unfortunately the ghost object sweep test does not seem reliable here currently, so using world's version instead.
  179. /*switch (object->getType())
  180. {
  181. case PhysicsCollisionObject::GHOST_OBJECT:
  182. case PhysicsCollisionObject::CHARACTER:
  183. static_cast<PhysicsGhostObject*>(object)->_ghostObject->convexSweepTest(static_cast<btConvexShape*>(shape->getShape()), start, end, callback, _world->getDispatchInfo().m_allowedCcdPenetration);
  184. break;
  185. default:
  186. _world->convexSweepTest(static_cast<btConvexShape*>(shape->getShape()), start, end, callback, _world->getDispatchInfo().m_allowedCcdPenetration);
  187. break;
  188. }*/
  189. _world->convexSweepTest(static_cast<btConvexShape*>(shape->getShape()), start, end, callback, _world->getDispatchInfo().m_allowedCcdPenetration);
  190. // Check for hits and store results
  191. if (callback.hasHit())
  192. {
  193. if (result)
  194. {
  195. result->object = getCollisionObject(callback.m_hitCollisionObject);
  196. result->point.set(callback.m_hitPointWorld.x(), callback.m_hitPointWorld.y(), callback.m_hitPointWorld.z());
  197. result->fraction = callback.m_closestHitFraction;
  198. result->normal.set(callback.m_hitNormalWorld.x(), callback.m_hitNormalWorld.y(), callback.m_hitNormalWorld.z());
  199. }
  200. return true;
  201. }
  202. return false;
  203. }
  204. btScalar PhysicsController::addSingleResult(btManifoldPoint& cp, const btCollisionObject* a, int partIdA, int indexA,
  205. const btCollisionObject* b, int partIdB, int indexB)
  206. {
  207. // Get pointers to the PhysicsCollisionObject objects.
  208. PhysicsCollisionObject* rbA = Game::getInstance()->getPhysicsController()->getCollisionObject(a);
  209. PhysicsCollisionObject* rbB = Game::getInstance()->getPhysicsController()->getCollisionObject(b);
  210. // If the given rigid body pair has collided in the past, then
  211. // we notify the listeners only if the pair was not colliding
  212. // during the previous frame. Otherwise, it's a new pair, so add a
  213. // new entry to the cache with the appropriate listeners and notify them.
  214. PhysicsCollisionObject::CollisionPair pair(rbA, rbB);
  215. CollisionInfo* collisionInfo;
  216. if (_collisionStatus.count(pair) > 0)
  217. {
  218. collisionInfo = &_collisionStatus[pair];
  219. }
  220. else
  221. {
  222. // Add a new collision pair for these objects
  223. collisionInfo = &_collisionStatus[pair];
  224. // Add the appropriate listeners.
  225. PhysicsCollisionObject::CollisionPair p1(pair.objectA, NULL);
  226. if (_collisionStatus.count(p1) > 0)
  227. {
  228. const CollisionInfo& ci = _collisionStatus[p1];
  229. std::vector<PhysicsCollisionObject::CollisionListener*>::const_iterator iter = ci._listeners.begin();
  230. for (; iter != ci._listeners.end(); iter++)
  231. {
  232. collisionInfo->_listeners.push_back(*iter);
  233. }
  234. }
  235. PhysicsCollisionObject::CollisionPair p2(pair.objectB, NULL);
  236. if (_collisionStatus.count(p2) > 0)
  237. {
  238. const CollisionInfo& ci = _collisionStatus[p2];
  239. std::vector<PhysicsCollisionObject::CollisionListener*>::const_iterator iter = ci._listeners.begin();
  240. for (; iter != ci._listeners.end(); iter++)
  241. {
  242. collisionInfo->_listeners.push_back(*iter);
  243. }
  244. }
  245. }
  246. // Fire collision event
  247. if ((collisionInfo->_status & COLLISION) == 0)
  248. {
  249. std::vector<PhysicsCollisionObject::CollisionListener*>::const_iterator iter = collisionInfo->_listeners.begin();
  250. for (; iter != collisionInfo->_listeners.end(); iter++)
  251. {
  252. if ((collisionInfo->_status & REMOVE) == 0)
  253. {
  254. (*iter)->collisionEvent(PhysicsCollisionObject::CollisionListener::COLLIDING, pair, Vector3(cp.getPositionWorldOnA().x(), cp.getPositionWorldOnA().y(), cp.getPositionWorldOnA().z()),
  255. Vector3(cp.getPositionWorldOnB().x(), cp.getPositionWorldOnB().y(), cp.getPositionWorldOnB().z()));
  256. }
  257. }
  258. }
  259. // Update the collision status cache (we remove the dirty bit
  260. // set in the controller's update so that this particular collision pair's
  261. // status is not reset to 'no collision' when the controller's update completes).
  262. collisionInfo->_status &= ~DIRTY;
  263. collisionInfo->_status |= COLLISION;
  264. return 0.0f;
  265. }
  266. void PhysicsController::initialize()
  267. {
  268. _collisionConfiguration = new btDefaultCollisionConfiguration();
  269. _dispatcher = new btCollisionDispatcher(_collisionConfiguration);
  270. _overlappingPairCache = new btDbvtBroadphase();
  271. _solver = new btSequentialImpulseConstraintSolver();
  272. // Create the world.
  273. _world = new btDiscreteDynamicsWorld(_dispatcher, _overlappingPairCache, _solver, _collisionConfiguration);
  274. _world->setGravity(BV(_gravity));
  275. // Register ghost pair callback so bullet detects collisions with ghost objects (used for character collisions).
  276. _ghostPairCallback = bullet_new<btGhostPairCallback>();
  277. _world->getPairCache()->setInternalGhostPairCallback(_ghostPairCallback);
  278. _world->getDispatchInfo().m_allowedCcdPenetration = 0.0001f;
  279. // Set up debug drawing.
  280. _debugDrawer = new DebugDrawer();
  281. _world->setDebugDrawer(_debugDrawer);
  282. }
  283. void PhysicsController::finalize()
  284. {
  285. // Clean up the world and its various components.
  286. SAFE_DELETE(_world);
  287. SAFE_DELETE(_ghostPairCallback);
  288. SAFE_DELETE(_solver);
  289. SAFE_DELETE(_overlappingPairCache);
  290. SAFE_DELETE(_dispatcher);
  291. SAFE_DELETE(_collisionConfiguration);
  292. }
  293. void PhysicsController::pause()
  294. {
  295. // Unused
  296. }
  297. void PhysicsController::resume()
  298. {
  299. // Unused
  300. }
  301. void PhysicsController::update(long elapsedTime)
  302. {
  303. // Update the physics simulation, with a maximum
  304. // of 10 simulation steps being performed in a given frame.
  305. //
  306. // Note that stepSimulation takes elapsed time in seconds
  307. // so we divide by 1000 to convert from milliseconds.
  308. _world->stepSimulation((float)elapsedTime * 0.001, 10);
  309. // If we have status listeners, then check if our status has changed.
  310. if (_listeners)
  311. {
  312. Listener::EventType oldStatus = _status;
  313. if (_status == Listener::DEACTIVATED)
  314. {
  315. for (int i = 0; i < _world->getNumCollisionObjects(); i++)
  316. {
  317. if (_world->getCollisionObjectArray()[i]->isActive())
  318. {
  319. _status = Listener::ACTIVATED;
  320. break;
  321. }
  322. }
  323. }
  324. else
  325. {
  326. bool allInactive = true;
  327. for (int i = 0; i < _world->getNumCollisionObjects(); i++)
  328. {
  329. if (_world->getCollisionObjectArray()[i]->isActive())
  330. {
  331. allInactive = false;
  332. break;
  333. }
  334. }
  335. if (allInactive)
  336. _status = Listener::DEACTIVATED;
  337. }
  338. // If the status has changed, notify our listeners.
  339. if (oldStatus != _status)
  340. {
  341. for (unsigned int k = 0; k < _listeners->size(); k++)
  342. {
  343. (*_listeners)[k]->statusEvent(_status);
  344. }
  345. }
  346. }
  347. // All statuses are set with the DIRTY bit before collision processing occurs.
  348. // During collision processing, if a collision occurs, the status is
  349. // set to COLLISION and the DIRTY bit is cleared. Then, after collision processing
  350. // is finished, if a given status is still dirty, the COLLISION bit is cleared.
  351. //
  352. // If an entry was marked for removal in the last frame, remove it now.
  353. // Dirty the collision status cache entries.
  354. std::map<PhysicsCollisionObject::CollisionPair, CollisionInfo>::iterator iter = _collisionStatus.begin();
  355. for (; iter != _collisionStatus.end();)
  356. {
  357. if ((iter->second._status & REMOVE) != 0)
  358. {
  359. std::map<PhysicsCollisionObject::CollisionPair, CollisionInfo>::iterator eraseIter = iter;
  360. iter++;
  361. _collisionStatus.erase(eraseIter);
  362. }
  363. else
  364. {
  365. iter->second._status |= DIRTY;
  366. iter++;
  367. }
  368. }
  369. // Go through the collision status cache and perform all registered collision tests.
  370. iter = _collisionStatus.begin();
  371. for (; iter != _collisionStatus.end(); iter++)
  372. {
  373. // If this collision pair was one that was registered for listening, then perform the collision test.
  374. // (In the case where we register for all collisions with a rigid body, there will be a lot
  375. // of collision pairs in the status cache that we did not explicitly register for.)
  376. if ((iter->second._status & REGISTERED) != 0 && (iter->second._status & REMOVE) == 0)
  377. {
  378. if (iter->first.objectB)
  379. _world->contactPairTest(iter->first.objectA->getCollisionObject(), iter->first.objectB->getCollisionObject(), *this);
  380. else
  381. _world->contactTest(iter->first.objectA->getCollisionObject(), *this);
  382. }
  383. }
  384. // Update all the collision status cache entries.
  385. iter = _collisionStatus.begin();
  386. for (; iter != _collisionStatus.end(); iter++)
  387. {
  388. if ((iter->second._status & DIRTY) != 0)
  389. {
  390. if ((iter->second._status & COLLISION) != 0 && iter->first.objectB)
  391. {
  392. unsigned int size = iter->second._listeners.size();
  393. for (unsigned int i = 0; i < size; i++)
  394. {
  395. iter->second._listeners[i]->collisionEvent(PhysicsCollisionObject::CollisionListener::NOT_COLLIDING, iter->first);
  396. }
  397. }
  398. iter->second._status &= ~COLLISION;
  399. }
  400. }
  401. }
  402. void PhysicsController::addCollisionListener(PhysicsCollisionObject::CollisionListener* listener, PhysicsCollisionObject* objectA, PhysicsCollisionObject* objectB)
  403. {
  404. PhysicsCollisionObject::CollisionPair pair(objectA, objectB);
  405. // Add the listener and ensure the status includes that this collision pair is registered.
  406. CollisionInfo& info = _collisionStatus[pair];
  407. info._listeners.push_back(listener);
  408. info._status |= PhysicsController::REGISTERED;
  409. }
  410. void PhysicsController::removeCollisionListener(PhysicsCollisionObject::CollisionListener* listener, PhysicsCollisionObject* objectA, PhysicsCollisionObject* objectB)
  411. {
  412. // Mark the collision pair for these objects for removal
  413. PhysicsCollisionObject::CollisionPair pair(objectA, objectB);
  414. if (_collisionStatus.count(pair) > 0)
  415. {
  416. _collisionStatus[pair]._status |= REMOVE;
  417. }
  418. }
  419. void PhysicsController::addCollisionObject(PhysicsCollisionObject* object)
  420. {
  421. // Assign user pointer for the bullet collision object to allow efficient
  422. // lookups of bullet objects -> gameplay objects.
  423. object->getCollisionObject()->setUserPointer(object);
  424. // Add the object to the physics world
  425. switch (object->getType())
  426. {
  427. case PhysicsCollisionObject::RIGID_BODY:
  428. _world->addRigidBody(static_cast<btRigidBody*>(object->getCollisionObject()), btBroadphaseProxy::DefaultFilter, btBroadphaseProxy::DefaultFilter | btBroadphaseProxy::StaticFilter | btBroadphaseProxy::CharacterFilter | btBroadphaseProxy::AllFilter);
  429. break;
  430. case PhysicsCollisionObject::CHARACTER:
  431. _world->addCollisionObject(object->getCollisionObject(), btBroadphaseProxy::CharacterFilter, btBroadphaseProxy::DefaultFilter | btBroadphaseProxy::StaticFilter | btBroadphaseProxy::CharacterFilter | btBroadphaseProxy::AllFilter);
  432. break;
  433. case PhysicsCollisionObject::GHOST_OBJECT:
  434. _world->addCollisionObject(object->getCollisionObject(), btBroadphaseProxy::DefaultFilter, btBroadphaseProxy::DefaultFilter | btBroadphaseProxy::StaticFilter | btBroadphaseProxy::CharacterFilter | btBroadphaseProxy::AllFilter);
  435. break;
  436. default:
  437. assert(0); // unexpected (new type?)
  438. break;
  439. }
  440. }
  441. void PhysicsController::removeCollisionObject(PhysicsCollisionObject* object)
  442. {
  443. // Remove the collision object from the world
  444. if (object->getCollisionObject())
  445. {
  446. switch (object->getType())
  447. {
  448. case PhysicsCollisionObject::RIGID_BODY:
  449. _world->removeRigidBody(static_cast<btRigidBody*>(object->getCollisionObject()));
  450. break;
  451. case PhysicsCollisionObject::CHARACTER:
  452. case PhysicsCollisionObject::GHOST_OBJECT:
  453. _world->removeCollisionObject(object->getCollisionObject());
  454. break;
  455. default:
  456. assert(0); // unexpected (new type?)
  457. break;
  458. }
  459. }
  460. // Find all references to the object in the collision status cache and mark them for removal.
  461. std::map<PhysicsCollisionObject::CollisionPair, CollisionInfo>::iterator iter = _collisionStatus.begin();
  462. for (; iter != _collisionStatus.end(); iter++)
  463. {
  464. if (iter->first.objectA == object || iter->first.objectB == object)
  465. iter->second._status |= REMOVE;
  466. }
  467. }
  468. PhysicsCollisionObject* PhysicsController::getCollisionObject(const btCollisionObject* collisionObject) const
  469. {
  470. // Gameplay rigid bodies are stored in the userPointer data of bullet collision objects
  471. return reinterpret_cast<PhysicsCollisionObject*>(collisionObject->getUserPointer());
  472. }
  473. void getBoundingBox(Node* node, BoundingBox* out, bool merge = false)
  474. {
  475. if (node->getModel())
  476. {
  477. if (merge)
  478. out->merge(node->getModel()->getMesh()->getBoundingBox());
  479. else
  480. {
  481. out->set(node->getModel()->getMesh()->getBoundingBox());
  482. merge = true;
  483. }
  484. }
  485. Node* child = node->getFirstChild();
  486. while (child)
  487. {
  488. getBoundingBox(child, out, merge);
  489. child = child->getNextSibling();
  490. }
  491. }
  492. void getBoundingSphere(Node* node, BoundingSphere* out, bool merge = false)
  493. {
  494. if (node->getModel())
  495. {
  496. if (merge)
  497. out->merge(node->getModel()->getMesh()->getBoundingSphere());
  498. else
  499. {
  500. out->set(node->getModel()->getMesh()->getBoundingSphere());
  501. merge = true;
  502. }
  503. }
  504. Node* child = node->getFirstChild();
  505. while (child)
  506. {
  507. getBoundingSphere(child, out, merge);
  508. child = child->getNextSibling();
  509. }
  510. }
  511. void computeCenterOfMass(const Vector3& center, const Vector3& scale, Vector3* centerOfMassOffset)
  512. {
  513. // Update center of mass offset
  514. *centerOfMassOffset = center;
  515. centerOfMassOffset->x *= scale.x;
  516. centerOfMassOffset->y *= scale.y;
  517. centerOfMassOffset->z *= scale.z;
  518. centerOfMassOffset->negate();
  519. }
  520. PhysicsCollisionShape* PhysicsController::createShape(Node* node, const PhysicsCollisionShape::Definition& shape, Vector3* centerOfMassOffset)
  521. {
  522. PhysicsCollisionShape* collisionShape = NULL;
  523. // Get the node's world scale (we need to apply this during creation since rigid bodies don't scale dynamically).
  524. Vector3 scale;
  525. node->getWorldMatrix().getScale(&scale);
  526. switch (shape.type)
  527. {
  528. case PhysicsCollisionShape::SHAPE_BOX:
  529. {
  530. if (shape.isExplicit)
  531. {
  532. // Use the passed in box information
  533. collisionShape = createBox(Vector3(shape.data.box.extents), Vector3::one());
  534. if (shape.centerAbsolute)
  535. {
  536. computeCenterOfMass(Vector3(shape.data.box.center), Vector3::one(), centerOfMassOffset);
  537. }
  538. else
  539. {
  540. BoundingBox box;
  541. getBoundingBox(node, &box);
  542. computeCenterOfMass(box.getCenter() + Vector3(shape.data.box.center), scale, centerOfMassOffset);
  543. }
  544. }
  545. else
  546. {
  547. // Automatically compute bounding box from mesh's bounding box
  548. BoundingBox box;
  549. getBoundingBox(node, &box);
  550. collisionShape = createBox(Vector3(std::abs(box.max.x - box.min.x), std::abs(box.max.y - box.min.y), std::abs(box.max.z - box.min.z)), scale);
  551. computeCenterOfMass(box.getCenter(), scale, centerOfMassOffset);
  552. }
  553. }
  554. break;
  555. case PhysicsCollisionShape::SHAPE_SPHERE:
  556. {
  557. if (shape.isExplicit)
  558. {
  559. // Use the passed in sphere information
  560. collisionShape = createSphere(shape.data.sphere.radius, Vector3::one());
  561. if (shape.centerAbsolute)
  562. {
  563. computeCenterOfMass(Vector3(shape.data.sphere.center), Vector3::one(), centerOfMassOffset);
  564. }
  565. else
  566. {
  567. BoundingSphere sphere;
  568. getBoundingSphere(node, &sphere);
  569. computeCenterOfMass(sphere.center + Vector3(shape.data.sphere.center), scale, centerOfMassOffset);
  570. }
  571. }
  572. else
  573. {
  574. // Automatically compute bounding sphere from mesh's bounding sphere
  575. BoundingSphere sphere;
  576. getBoundingSphere(node, &sphere);
  577. collisionShape = createSphere(sphere.radius, scale);
  578. computeCenterOfMass(sphere.center, scale, centerOfMassOffset);
  579. }
  580. }
  581. break;
  582. case PhysicsCollisionShape::SHAPE_CAPSULE:
  583. {
  584. if (shape.isExplicit)
  585. {
  586. // Use the passed in capsule information
  587. collisionShape = createCapsule(shape.data.capsule.radius, shape.data.capsule.height, Vector3::one());
  588. if (shape.centerAbsolute)
  589. {
  590. computeCenterOfMass(Vector3(shape.data.capsule.center), Vector3::one(), centerOfMassOffset);
  591. }
  592. else
  593. {
  594. BoundingBox box;
  595. getBoundingBox(node, &box);
  596. computeCenterOfMass(box.getCenter() + Vector3(shape.data.capsule.center), scale, centerOfMassOffset);
  597. }
  598. }
  599. else
  600. {
  601. // Compute a capsule shape that roughly matches the bounding box of the mesh
  602. BoundingBox box;
  603. getBoundingBox(node, &box);
  604. float radius = std::max((box.max.x - box.min.x) * 0.5f, (box.max.z - box.min.z) * 0.5f);
  605. float height = box.max.y - box.min.y;
  606. collisionShape = createCapsule(radius, height, scale);
  607. computeCenterOfMass(box.getCenter(), scale, centerOfMassOffset);
  608. }
  609. }
  610. break;
  611. case PhysicsCollisionShape::SHAPE_HEIGHTFIELD:
  612. {
  613. // Build heightfield rigid body from the passed in shape
  614. collisionShape = createHeightfield(node, shape.data.heightfield, centerOfMassOffset);
  615. }
  616. break;
  617. case PhysicsCollisionShape::SHAPE_MESH:
  618. {
  619. // Build mesh from passed in shape
  620. collisionShape = createMesh(shape.data.mesh, scale);
  621. }
  622. break;
  623. }
  624. return collisionShape;
  625. }
  626. PhysicsCollisionShape* PhysicsController::createBox(const Vector3& extents, const Vector3& scale)
  627. {
  628. btVector3 halfExtents(scale.x * 0.5 * extents.x, scale.y * 0.5 * extents.y, scale.z * 0.5 * extents.z);
  629. PhysicsCollisionShape* shape;
  630. // Return the box shape from the cache if it already exists.
  631. for (unsigned int i = 0; i < _shapes.size(); ++i)
  632. {
  633. shape = _shapes[i];
  634. if (shape->getType() == PhysicsCollisionShape::SHAPE_BOX)
  635. {
  636. btBoxShape* box = static_cast<btBoxShape*>(shape->_shape);
  637. if (box->getHalfExtentsWithMargin() == halfExtents)
  638. {
  639. shape->addRef();
  640. return shape;
  641. }
  642. }
  643. }
  644. // Create the box shape and add it to the cache.
  645. shape = new PhysicsCollisionShape(PhysicsCollisionShape::SHAPE_BOX, bullet_new<btBoxShape>(halfExtents));
  646. _shapes.push_back(shape);
  647. return shape;
  648. }
  649. PhysicsCollisionShape* PhysicsController::createSphere(float radius, const Vector3& scale)
  650. {
  651. // Since sphere shapes depend only on the radius, the best we can do is take
  652. // the largest dimension and apply that as the uniform scale to the rigid body.
  653. float uniformScale = scale.x;
  654. if (uniformScale < scale.y)
  655. uniformScale = scale.y;
  656. if (uniformScale < scale.z)
  657. uniformScale = scale.z;
  658. float scaledRadius = radius * uniformScale;
  659. PhysicsCollisionShape* shape;
  660. // Return the sphere shape from the cache if it already exists.
  661. for (unsigned int i = 0; i < _shapes.size(); ++i)
  662. {
  663. shape = _shapes[i];
  664. if (shape->getType() == PhysicsCollisionShape::SHAPE_SPHERE)
  665. {
  666. btSphereShape* sphere = static_cast<btSphereShape*>(shape->_shape);
  667. if (sphere->getRadius() == scaledRadius)
  668. {
  669. shape->addRef();
  670. return shape;
  671. }
  672. }
  673. }
  674. // Create the sphere shape and add it to the cache.
  675. shape = new PhysicsCollisionShape(PhysicsCollisionShape::SHAPE_SPHERE, bullet_new<btSphereShape>(scaledRadius));
  676. _shapes.push_back(shape);
  677. return shape;
  678. }
  679. PhysicsCollisionShape* PhysicsController::createCapsule(float radius, float height, const Vector3& scale)
  680. {
  681. float girthScale = scale.x;
  682. if (girthScale < scale.z)
  683. girthScale = scale.z;
  684. float scaledRadius = radius * girthScale;
  685. float scaledHeight = height * scale.y - radius * 2;
  686. PhysicsCollisionShape* shape;
  687. // Return the capsule shape from the cache if it already exists.
  688. for (unsigned int i = 0; i < _shapes.size(); i++)
  689. {
  690. shape = _shapes[i];
  691. if (shape->getType() == PhysicsCollisionShape::SHAPE_CAPSULE)
  692. {
  693. btCapsuleShape* capsule = static_cast<btCapsuleShape*>(shape->_shape);
  694. if (capsule->getRadius() == scaledRadius && capsule->getHalfHeight() == 0.5f * scaledHeight)
  695. {
  696. shape->addRef();
  697. return shape;
  698. }
  699. }
  700. }
  701. // Create the capsule shape and add it to the cache.
  702. shape = new PhysicsCollisionShape(PhysicsCollisionShape::SHAPE_CAPSULE, bullet_new<btCapsuleShape>(scaledRadius, scaledHeight));
  703. _shapes.push_back(shape);
  704. return shape;
  705. }
  706. PhysicsCollisionShape* PhysicsController::createHeightfield(Node* node, Image* image, Vector3* centerOfMassOffset)
  707. {
  708. // Get the dimensions of the heightfield.
  709. // If the node has a mesh defined, use the dimensions of the bounding box for the mesh.
  710. // Otherwise simply use the image dimensions (with a max height of 255).
  711. float width, length, minHeight, maxHeight;
  712. if (node->getModel() && node->getModel()->getMesh())
  713. {
  714. const BoundingBox& box = node->getModel()->getMesh()->getBoundingBox();
  715. width = box.max.x - box.min.x;
  716. length = box.max.z - box.min.z;
  717. minHeight = box.min.y;
  718. maxHeight = box.max.y;
  719. }
  720. else
  721. {
  722. width = image->getWidth();
  723. length = image->getHeight();
  724. minHeight = 0.0f;
  725. maxHeight = 255.0f;
  726. }
  727. // Get the size in bytes of a pixel (we ensure that the image's
  728. // pixel format is actually supported before calling this constructor).
  729. unsigned int pixelSize = 0;
  730. switch (image->getFormat())
  731. {
  732. case Image::RGB:
  733. pixelSize = 3;
  734. break;
  735. case Image::RGBA:
  736. pixelSize = 4;
  737. break;
  738. default:
  739. LOG_ERROR("Unsupported pixel format for heightmap image.");
  740. return NULL;
  741. }
  742. // Calculate the heights for each pixel.
  743. float* heights = new float[image->getWidth() * image->getHeight()];
  744. unsigned char* data = image->getData();
  745. for (unsigned int x = 0, w = image->getWidth(); x < w; ++x)
  746. {
  747. for (unsigned int y = 0, h = image->getHeight(); y < h; ++y)
  748. {
  749. heights[x + y * w] = ((((float)data[(x + y * h) * pixelSize + 0]) +
  750. ((float)data[(x + y * h) * pixelSize + 1]) +
  751. ((float)data[(x + y * h) * pixelSize + 2])) / 768.0f) * (maxHeight - minHeight) + minHeight;
  752. }
  753. }
  754. PhysicsCollisionShape::HeightfieldData* heightfieldData = new PhysicsCollisionShape::HeightfieldData();
  755. heightfieldData->heightData = NULL;
  756. heightfieldData->inverseIsDirty = true;
  757. // Generate the heightmap data needed for physics (one height per world unit).
  758. unsigned int sizeWidth = width;
  759. unsigned int sizeHeight = length;
  760. heightfieldData->width = sizeWidth + 1;
  761. heightfieldData->height = sizeHeight + 1;
  762. heightfieldData->heightData = new float[heightfieldData->width * heightfieldData->height];
  763. unsigned int heightIndex = 0;
  764. float widthImageFactor = (float)(image->getWidth() - 1) / sizeWidth;
  765. float heightImageFactor = (float)(image->getHeight() - 1) / sizeHeight;
  766. float x = 0.0f;
  767. float z = 0.0f;
  768. for (unsigned int row = 0, z = 0.0f; row <= sizeHeight; row++, z += 1.0f)
  769. {
  770. for (unsigned int col = 0, x = 0.0f; col <= sizeWidth; col++, x += 1.0f)
  771. {
  772. heightIndex = row * heightfieldData->width + col;
  773. heightfieldData->heightData[heightIndex] = calculateHeight(heights, image->getWidth(), image->getHeight(), x * widthImageFactor, (sizeHeight - z) * heightImageFactor);
  774. }
  775. }
  776. SAFE_DELETE_ARRAY(heights);
  777. // Offset the heightmap's center of mass according to the way that Bullet calculates the origin
  778. // of its heightfield collision shape; see documentation for the btHeightfieldTerrainShape for more info.
  779. Vector3 s;
  780. node->getWorldMatrix().getScale(&s);
  781. centerOfMassOffset->set(0.0f, -(maxHeight - (0.5f * (maxHeight - minHeight))) / s.y, 0.0f);
  782. // Create the bullet terrain shape
  783. btHeightfieldTerrainShape* terrainShape = bullet_new<btHeightfieldTerrainShape>(
  784. heightfieldData->width, heightfieldData->height, heightfieldData->heightData, 1.0f, minHeight, maxHeight, 1, PHY_FLOAT, false);
  785. // Create our collision shape object and store heightfieldData in it
  786. PhysicsCollisionShape* shape = new PhysicsCollisionShape(PhysicsCollisionShape::SHAPE_HEIGHTFIELD, terrainShape);
  787. shape->_shapeData.heightfieldData = heightfieldData;
  788. _shapes.push_back(shape);
  789. return shape;
  790. }
  791. PhysicsCollisionShape* PhysicsController::createMesh(Mesh* mesh, const Vector3& scale)
  792. {
  793. assert(mesh);
  794. // Only support meshes with triangle list primitive types
  795. bool triMesh = true;
  796. if (mesh->getPartCount() > 0)
  797. {
  798. for (unsigned int i = 0; i < mesh->getPartCount(); ++i)
  799. {
  800. if (mesh->getPart(i)->getPrimitiveType() != Mesh::TRIANGLES)
  801. {
  802. triMesh = false;
  803. break;
  804. }
  805. }
  806. }
  807. else
  808. {
  809. triMesh = mesh->getPrimitiveType() == Mesh::TRIANGLES;
  810. }
  811. if (!triMesh)
  812. {
  813. LOG_ERROR("Mesh rigid bodies are currently only supported on meshes with TRIANGLES primitive type.");
  814. return NULL;
  815. }
  816. // The mesh must have a valid URL (i.e. it must have been loaded from a Bundle)
  817. // in order to fetch mesh data for computing mesh rigid body.
  818. if (strlen(mesh->getUrl()) == 0)
  819. {
  820. LOG_ERROR("Cannot create mesh rigid body for mesh without valid URL.");
  821. return NULL;
  822. }
  823. Bundle::MeshData* data = Bundle::readMeshData(mesh->getUrl());
  824. if (data == NULL)
  825. {
  826. return NULL;
  827. }
  828. // Create mesh data to be populated and store in returned collision shape
  829. PhysicsCollisionShape::MeshData* shapeMeshData = new PhysicsCollisionShape::MeshData();
  830. shapeMeshData->vertexData = NULL;
  831. // Copy the scaled vertex position data to the rigid body's local buffer.
  832. Matrix m;
  833. Matrix::createScale(scale, &m);
  834. unsigned int vertexCount = data->vertexCount;
  835. shapeMeshData->vertexData = new float[vertexCount * 3];
  836. Vector3 v;
  837. int vertexStride = data->vertexFormat.getVertexSize();
  838. for (unsigned int i = 0; i < data->vertexCount; i++)
  839. {
  840. v.set(*((float*)&data->vertexData[i * vertexStride + 0 * sizeof(float)]),
  841. *((float*)&data->vertexData[i * vertexStride + 1 * sizeof(float)]),
  842. *((float*)&data->vertexData[i * vertexStride + 2 * sizeof(float)]));
  843. v *= m;
  844. memcpy(&(shapeMeshData->vertexData[i * 3]), &v, sizeof(float) * 3);
  845. }
  846. btTriangleIndexVertexArray* meshInterface = bullet_new<btTriangleIndexVertexArray>();
  847. unsigned int partCount = data->parts.size();
  848. if (partCount > 0)
  849. {
  850. PHY_ScalarType indexType = PHY_UCHAR;
  851. int indexStride = 0;
  852. Bundle::MeshPartData* meshPart = NULL;
  853. for (unsigned int i = 0; i < partCount; i++)
  854. {
  855. meshPart = data->parts[i];
  856. switch (meshPart->indexFormat)
  857. {
  858. case Mesh::INDEX8:
  859. indexType = PHY_UCHAR;
  860. indexStride = 1;
  861. break;
  862. case Mesh::INDEX16:
  863. indexType = PHY_SHORT;
  864. indexStride = 2;
  865. break;
  866. case Mesh::INDEX32:
  867. indexType = PHY_INTEGER;
  868. indexStride = 4;
  869. break;
  870. }
  871. // Move the index data into the rigid body's local buffer.
  872. // Set it to NULL in the MeshPartData so it is not released when the data is freed.
  873. shapeMeshData->indexData.push_back(meshPart->indexData);
  874. meshPart->indexData = NULL;
  875. // Create a btIndexedMesh object for the current mesh part.
  876. btIndexedMesh indexedMesh;
  877. indexedMesh.m_indexType = indexType;
  878. indexedMesh.m_numTriangles = meshPart->indexCount / 3; // assume TRIANGLES primitive type
  879. indexedMesh.m_numVertices = meshPart->indexCount;
  880. indexedMesh.m_triangleIndexBase = (const unsigned char*)shapeMeshData->indexData[i];
  881. indexedMesh.m_triangleIndexStride = indexStride*3;
  882. indexedMesh.m_vertexBase = (const unsigned char*)shapeMeshData->vertexData;
  883. indexedMesh.m_vertexStride = sizeof(float)*3;
  884. indexedMesh.m_vertexType = PHY_FLOAT;
  885. // Add the indexed mesh data to the mesh interface.
  886. meshInterface->addIndexedMesh(indexedMesh, indexType);
  887. }
  888. }
  889. else
  890. {
  891. // Generate index data for the mesh locally in the rigid body.
  892. unsigned int* indexData = new unsigned int[data->vertexCount];
  893. for (unsigned int i = 0; i < data->vertexCount; i++)
  894. {
  895. indexData[i] = i;
  896. }
  897. shapeMeshData->indexData.push_back((unsigned char*)indexData);
  898. // Create a single btIndexedMesh object for the mesh interface.
  899. btIndexedMesh indexedMesh;
  900. indexedMesh.m_indexType = PHY_INTEGER;
  901. indexedMesh.m_numTriangles = data->vertexCount / 3; // assume TRIANGLES primitive type
  902. indexedMesh.m_numVertices = data->vertexCount;
  903. indexedMesh.m_triangleIndexBase = shapeMeshData->indexData[0];
  904. indexedMesh.m_triangleIndexStride = sizeof(unsigned int);
  905. indexedMesh.m_vertexBase = (const unsigned char*)shapeMeshData->vertexData;
  906. indexedMesh.m_vertexStride = sizeof(float)*3;
  907. indexedMesh.m_vertexType = PHY_FLOAT;
  908. // Set the data in the mesh interface.
  909. meshInterface->addIndexedMesh(indexedMesh, indexedMesh.m_indexType);
  910. }
  911. // Create our collision shape object and store shapeMeshData in it
  912. PhysicsCollisionShape* shape = new PhysicsCollisionShape(PhysicsCollisionShape::SHAPE_MESH, bullet_new<btBvhTriangleMeshShape>(meshInterface, true));
  913. shape->_shapeData.meshData = shapeMeshData;
  914. _shapes.push_back(shape);
  915. // Free the temporary mesh data now that it's stored in physics system
  916. SAFE_DELETE(data);
  917. return shape;
  918. }
  919. void PhysicsController::destroyShape(PhysicsCollisionShape* shape)
  920. {
  921. if (shape)
  922. {
  923. if (shape->getRefCount() == 1)
  924. {
  925. // Remove shape from shape cache
  926. std::vector<PhysicsCollisionShape*>::iterator shapeItr = std::find(_shapes.begin(), _shapes.end(), shape);
  927. if (shapeItr != _shapes.end())
  928. _shapes.erase(shapeItr);
  929. }
  930. // Release the shape
  931. shape->release();
  932. }
  933. }
  934. float PhysicsController::calculateHeight(float* data, unsigned int width, unsigned int height, float x, float y)
  935. {
  936. unsigned int x1 = x;
  937. unsigned int y1 = y;
  938. unsigned int x2 = x1 + 1;
  939. unsigned int y2 = y1 + 1;
  940. float tmp;
  941. float xFactor = modf(x, &tmp);
  942. float yFactor = modf(y, &tmp);
  943. float xFactorI = 1.0f - xFactor;
  944. float yFactorI = 1.0f - yFactor;
  945. if (x2 >= width && y2 >= height)
  946. {
  947. return data[x1 + y1 * width];
  948. }
  949. else if (x2 >= width)
  950. {
  951. return data[x1 + y1 * width] * yFactorI + data[x1 + y2 * width] * yFactor;
  952. }
  953. else if (y2 >= height)
  954. {
  955. return data[x1 + y1 * width] * xFactorI + data[x2 + y1 * width] * xFactor;
  956. }
  957. else
  958. {
  959. return data[x1 + y1 * width] * xFactorI * yFactorI + data[x1 + y2 * width] * xFactorI * yFactor +
  960. data[x2 + y2 * width] * xFactor * yFactor + data[x2 + y1 * width] * xFactor * yFactorI;
  961. }
  962. }
  963. void PhysicsController::addConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b, PhysicsConstraint* constraint)
  964. {
  965. a->addConstraint(constraint);
  966. if (b)
  967. {
  968. b->addConstraint(constraint);
  969. }
  970. _world->addConstraint(constraint->_constraint);
  971. }
  972. bool PhysicsController::checkConstraintRigidBodies(PhysicsRigidBody* a, PhysicsRigidBody* b)
  973. {
  974. if (!a->supportsConstraints())
  975. {
  976. WARN_VARG("Rigid body '%s' does not support constraints; unexpected behavior may occur.", a->_node->getId());
  977. return false;
  978. }
  979. if (b && !b->supportsConstraints())
  980. {
  981. WARN_VARG("Rigid body '%s' does not support constraints; unexpected behavior may occur.", b->_node->getId());
  982. return false;
  983. }
  984. return true;
  985. }
  986. void PhysicsController::removeConstraint(PhysicsConstraint* constraint)
  987. {
  988. // Find the constraint and remove it from the physics world.
  989. for (int i = _world->getNumConstraints() - 1; i >= 0; i--)
  990. {
  991. btTypedConstraint* currentConstraint = _world->getConstraint(i);
  992. if (constraint->_constraint == currentConstraint)
  993. {
  994. _world->removeConstraint(currentConstraint);
  995. break;
  996. }
  997. }
  998. }
  999. PhysicsController::DebugDrawer::DebugDrawer()
  1000. : _mode(btIDebugDraw::DBG_DrawAabb | btIDebugDraw::DBG_DrawConstraintLimits | btIDebugDraw::DBG_DrawConstraints |
  1001. btIDebugDraw::DBG_DrawContactPoints | btIDebugDraw::DBG_DrawWireframe), _viewProjection(NULL), _meshBatch(NULL)
  1002. {
  1003. // Vertex shader for drawing colored lines.
  1004. const char* vs_str =
  1005. {
  1006. "uniform mat4 u_viewProjectionMatrix;\n"
  1007. "attribute vec4 a_position;\n"
  1008. "attribute vec4 a_color;\n"
  1009. "varying vec4 v_color;\n"
  1010. "void main(void) {\n"
  1011. " v_color = a_color;\n"
  1012. " gl_Position = u_viewProjectionMatrix * a_position;\n"
  1013. "}"
  1014. };
  1015. // Fragment shader for drawing colored lines.
  1016. const char* fs_str =
  1017. {
  1018. #ifdef OPENGL_ES
  1019. "precision highp float;\n"
  1020. #endif
  1021. "varying vec4 v_color;\n"
  1022. "void main(void) {\n"
  1023. " gl_FragColor = v_color;\n"
  1024. "}"
  1025. };
  1026. Effect* effect = Effect::createFromSource(vs_str, fs_str);
  1027. Material* material = Material::create(effect);
  1028. material->getStateBlock()->setDepthTest(true);
  1029. VertexFormat::Element elements[] =
  1030. {
  1031. VertexFormat::Element(VertexFormat::POSITION, 3),
  1032. VertexFormat::Element(VertexFormat::COLOR, 4),
  1033. };
  1034. _meshBatch = MeshBatch::create(VertexFormat(elements, 2), Mesh::LINES, material, false);
  1035. SAFE_RELEASE(material);
  1036. SAFE_RELEASE(effect);
  1037. }
  1038. PhysicsController::DebugDrawer::~DebugDrawer()
  1039. {
  1040. SAFE_DELETE(_meshBatch);
  1041. }
  1042. void PhysicsController::DebugDrawer::begin(const Matrix& viewProjection)
  1043. {
  1044. _viewProjection = &viewProjection;
  1045. _meshBatch->begin();
  1046. }
  1047. void PhysicsController::DebugDrawer::end()
  1048. {
  1049. _meshBatch->end();
  1050. _meshBatch->getMaterial()->getParameter("u_viewProjectionMatrix")->setValue(_viewProjection);
  1051. _meshBatch->draw();
  1052. }
  1053. void PhysicsController::DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& fromColor, const btVector3& toColor)
  1054. {
  1055. static DebugDrawer::DebugVertex fromVertex, toVertex;
  1056. fromVertex.x = from.getX();
  1057. fromVertex.y = from.getY();
  1058. fromVertex.z = from.getZ();
  1059. fromVertex.r = fromColor.getX();
  1060. fromVertex.g = fromColor.getY();
  1061. fromVertex.b = fromColor.getZ();
  1062. fromVertex.a = 1.0f;
  1063. toVertex.x = to.getX();
  1064. toVertex.y = to.getY();
  1065. toVertex.z = to.getZ();
  1066. toVertex.r = toColor.getX();
  1067. toVertex.g = toColor.getY();
  1068. toVertex.b = toColor.getZ();
  1069. toVertex.a = 1.0f;
  1070. _meshBatch->add(&fromVertex, 1);
  1071. _meshBatch->add(&toVertex, 1);
  1072. }
  1073. void PhysicsController::DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color)
  1074. {
  1075. drawLine(from, to, color, color);
  1076. }
  1077. void PhysicsController::DebugDrawer::drawContactPoint(const btVector3& pointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color)
  1078. {
  1079. drawLine(pointOnB, pointOnB + normalOnB, color);
  1080. }
  1081. void PhysicsController::DebugDrawer::reportErrorWarning(const char* warningString)
  1082. {
  1083. WARN(warningString);
  1084. }
  1085. void PhysicsController::DebugDrawer::draw3dText(const btVector3& location, const char* textString)
  1086. {
  1087. WARN("Physics debug drawing: 3D text is not supported.");
  1088. }
  1089. void PhysicsController::DebugDrawer::setDebugMode(int mode)
  1090. {
  1091. _mode = mode;
  1092. }
  1093. int PhysicsController::DebugDrawer::getDebugMode() const
  1094. {
  1095. return _mode;
  1096. }
  1097. }