PhysicsController.cpp 51 KB

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