PhysicsController.cpp 49 KB

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