PhysicsCharacter.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. /**
  2. * PhysicsCharacter.cpp
  3. *
  4. * Much of the collision detection code for this implementation is based off the
  5. * btbtKinematicCharacterController class from Bullet Physics 2.7.6.
  6. */
  7. #include "Base.h"
  8. #include "PhysicsCharacter.h"
  9. #include "Scene.h"
  10. #include "Game.h"
  11. #include "PhysicsController.h"
  12. namespace gameplay
  13. {
  14. class ClosestNotMeConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback
  15. {
  16. public:
  17. /**
  18. * @see btCollisionWorld::ClosestConvexResultCallback::ClosestConvexResultCallback
  19. */
  20. ClosestNotMeConvexResultCallback(PhysicsCollisionObject* me, const btVector3& up, btScalar minSlopeDot)
  21. : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)), _me(me), _up(up), _minSlopeDot(minSlopeDot)
  22. {
  23. }
  24. /**
  25. * @see btCollisionWorld::ClosestConvexResultCallback::addSingleResult
  26. */
  27. btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)
  28. {
  29. PhysicsCollisionObject* object = reinterpret_cast<PhysicsCollisionObject*>(convexResult.m_hitCollisionObject->getUserPointer());
  30. GP_ASSERT(object);
  31. if (object == _me || object->getType() == PhysicsCollisionObject::GHOST_OBJECT)
  32. return 1.0f;
  33. /*
  34. btVector3 hitNormalWorld;
  35. if (normalInWorldSpace)
  36. {
  37. hitNormalWorld = convexResult.m_hitNormalLocal;
  38. } else
  39. {
  40. // transform normal into worldspace
  41. hitNormalWorld = convexResult.m_hitCollisionObject->getWorldTransform().getBasis()*convexResult.m_hitNormalLocal;
  42. }
  43. btScalar dotUp = _up.dot(hitNormalWorld);
  44. if (dotUp < _minSlopeDot)
  45. {
  46. return btScalar(1.0);
  47. }
  48. */
  49. return ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace);
  50. }
  51. protected:
  52. PhysicsCollisionObject* _me;
  53. const btVector3 _up;
  54. btScalar _minSlopeDot;
  55. };
  56. PhysicsCharacter::PhysicsCharacter(Node* node, const PhysicsCollisionShape::Definition& shape, float mass)
  57. : PhysicsGhostObject(node, shape), _moveVelocity(0,0,0), _forwardVelocity(0.0f), _rightVelocity(0.0f),
  58. _verticalVelocity(0, 0, 0), _currentVelocity(0,0,0), _normalizedVelocity(0,0,0),
  59. _colliding(false), _collisionNormal(0,0,0), _currentPosition(0,0,0), _stepHeight(0.1f),
  60. _slopeAngle(0.0f), _cosSlopeAngle(0.0f), _physicsEnabled(true), _mass(mass)
  61. {
  62. setMaxSlopeAngle(45.0f);
  63. // Set the collision flags on the ghost object to indicate it's a character.
  64. GP_ASSERT(_ghostObject);
  65. _ghostObject->setCollisionFlags(_ghostObject->getCollisionFlags() | btCollisionObject::CF_CHARACTER_OBJECT | btCollisionObject::CF_NO_CONTACT_RESPONSE);
  66. // Register ourselves as an action on the physics world so we are called back during physics ticks.
  67. GP_ASSERT(Game::getInstance()->getPhysicsController() && Game::getInstance()->getPhysicsController()->_world);
  68. Game::getInstance()->getPhysicsController()->_world->addAction(this);
  69. }
  70. PhysicsCharacter::~PhysicsCharacter()
  71. {
  72. // Unregister ourselves as action from world.
  73. GP_ASSERT(Game::getInstance()->getPhysicsController() && Game::getInstance()->getPhysicsController()->_world);
  74. Game::getInstance()->getPhysicsController()->_world->removeAction(this);
  75. }
  76. PhysicsCharacter* PhysicsCharacter::create(Node* node, Properties* properties)
  77. {
  78. // Check if the properties is valid and has a valid namespace.
  79. if (!properties || !(strcmp(properties->getNamespace(), "character") == 0))
  80. {
  81. GP_ERROR("Failed to load physics character from properties object: must be non-null object and have namespace equal to 'character'.");
  82. return NULL;
  83. }
  84. // Load the physics collision shape definition.
  85. PhysicsCollisionShape::Definition* shape = PhysicsCollisionShape::Definition::create(node, properties);
  86. if (shape == NULL)
  87. {
  88. GP_ERROR("Failed to create collision shape during physics character creation.");
  89. return NULL;
  90. }
  91. // Load the character's parameters.
  92. properties->rewind();
  93. float mass = 1.0f;
  94. float maxStepHeight = 0.1f;
  95. float maxSlopeAngle = 0.0f;
  96. const char* name = NULL;
  97. while ((name = properties->getNextProperty()) != NULL)
  98. {
  99. if (strcmp(name, "mass") == 0)
  100. {
  101. mass = properties->getFloat();
  102. }
  103. else if (strcmp(name, "maxStepHeight") == 0)
  104. {
  105. maxStepHeight = properties->getFloat();
  106. }
  107. else if (strcmp(name, "maxSlopeAngle") == 0)
  108. {
  109. maxSlopeAngle = properties->getFloat();
  110. }
  111. else
  112. {
  113. // Ignore this case (the attributes for the character's collision shape would end up here).
  114. }
  115. }
  116. // Create the physics character.
  117. PhysicsCharacter* character = new PhysicsCharacter(node, *shape, mass);
  118. character->setMaxStepHeight(maxStepHeight);
  119. character->setMaxSlopeAngle(maxSlopeAngle);
  120. SAFE_DELETE(shape);
  121. return character;
  122. }
  123. PhysicsCollisionObject::Type PhysicsCharacter::getType() const
  124. {
  125. return PhysicsCollisionObject::CHARACTER;
  126. }
  127. btCollisionObject* PhysicsCharacter::getCollisionObject() const
  128. {
  129. return _ghostObject;
  130. }
  131. bool PhysicsCharacter::isPhysicsEnabled() const
  132. {
  133. return _physicsEnabled;
  134. }
  135. void PhysicsCharacter::setPhysicsEnabled(bool enabled)
  136. {
  137. _physicsEnabled = enabled;
  138. }
  139. float PhysicsCharacter::getMaxStepHeight() const
  140. {
  141. return _stepHeight;
  142. }
  143. void PhysicsCharacter::setMaxStepHeight(float height)
  144. {
  145. _stepHeight = height;
  146. }
  147. float PhysicsCharacter::getMaxSlopeAngle() const
  148. {
  149. return _slopeAngle;
  150. }
  151. void PhysicsCharacter::setMaxSlopeAngle(float angle)
  152. {
  153. _slopeAngle = angle;
  154. _cosSlopeAngle = std::cos(MATH_DEG_TO_RAD(angle));
  155. }
  156. void PhysicsCharacter::setVelocity(const Vector3& velocity)
  157. {
  158. _moveVelocity.setValue(velocity.x, velocity.y, velocity.z);
  159. }
  160. void PhysicsCharacter::rotate(const Vector3& axis, float angle)
  161. {
  162. GP_ASSERT(_node);
  163. _node->rotate(axis, angle);
  164. }
  165. void PhysicsCharacter::rotate(const Quaternion& rotation)
  166. {
  167. GP_ASSERT(_node);
  168. _node->rotate(rotation);
  169. }
  170. void PhysicsCharacter::setRotation(const Vector3& axis, float angle)
  171. {
  172. GP_ASSERT(_node);
  173. _node->setRotation(axis, angle);
  174. }
  175. void PhysicsCharacter::setRotation(const Quaternion& rotation)
  176. {
  177. GP_ASSERT(_node);
  178. _node->setRotation(rotation);
  179. }
  180. void PhysicsCharacter::setForwardVelocity(float velocity)
  181. {
  182. _forwardVelocity = velocity;
  183. }
  184. void PhysicsCharacter::setRightVelocity(float velocity)
  185. {
  186. _rightVelocity = velocity;
  187. }
  188. Vector3 PhysicsCharacter::getCurrentVelocity() const
  189. {
  190. Vector3 v(_currentVelocity.x(), _currentVelocity.y(), _currentVelocity.z());
  191. v.x += _verticalVelocity.x();
  192. v.y += _verticalVelocity.y();
  193. v.z += _verticalVelocity.z();
  194. return v;
  195. }
  196. void PhysicsCharacter::jump(float height)
  197. {
  198. // TODO: Add support for different jump modes (i.e. double jump, changing direction in air, holding down jump button for extra height, etc)
  199. if (!_verticalVelocity.isZero())
  200. return;
  201. // v = sqrt(v0^2 + 2 a s)
  202. // v0 == initial velocity (zero for jumping)
  203. // a == acceleration (inverse gravity)
  204. // s == linear displacement (height)
  205. GP_ASSERT(Game::getInstance()->getPhysicsController());
  206. Vector3 jumpVelocity = -Game::getInstance()->getPhysicsController()->getGravity() * height * 2.0f;
  207. jumpVelocity.set(
  208. jumpVelocity.x == 0 ? 0 : std::sqrt(jumpVelocity.x),
  209. jumpVelocity.y == 0 ? 0 : std::sqrt(jumpVelocity.y),
  210. jumpVelocity.z == 0 ? 0 : std::sqrt(jumpVelocity.z));
  211. _verticalVelocity += BV(jumpVelocity);
  212. }
  213. void PhysicsCharacter::updateCurrentVelocity()
  214. {
  215. GP_ASSERT(_node);
  216. Vector3 temp;
  217. btScalar velocity2 = 0;
  218. // Reset velocity vector.
  219. _normalizedVelocity.setValue(0, 0, 0);
  220. // Add movement velocity contribution.
  221. if (!_moveVelocity.isZero())
  222. {
  223. _normalizedVelocity = _moveVelocity;
  224. velocity2 = _moveVelocity.length2();
  225. }
  226. // Add forward velocity contribution.
  227. if (_forwardVelocity != 0)
  228. {
  229. _node->getWorldMatrix().getForwardVector(&temp);
  230. temp.normalize();
  231. temp *= -_forwardVelocity;
  232. _normalizedVelocity += btVector3(temp.x, temp.y, temp.z);
  233. velocity2 = std::max(std::abs(velocity2), std::abs(_forwardVelocity*_forwardVelocity));
  234. }
  235. // Add right velocity contribution.
  236. if (_rightVelocity != 0)
  237. {
  238. _node->getWorldMatrix().getRightVector(&temp);
  239. temp.normalize();
  240. temp *= _rightVelocity;
  241. _normalizedVelocity += btVector3(temp.x, temp.y, temp.z);
  242. velocity2 = std::max(std::abs(velocity2), std::abs(_rightVelocity*_rightVelocity));
  243. }
  244. // Compute final combined movement vectors
  245. if (_normalizedVelocity.isZero())
  246. {
  247. _currentVelocity.setZero();
  248. }
  249. else
  250. {
  251. _normalizedVelocity.normalize();
  252. _currentVelocity = _normalizedVelocity * std::sqrt(velocity2);
  253. }
  254. }
  255. void PhysicsCharacter::updateAction(btCollisionWorld* collisionWorld, btScalar deltaTimeStep)
  256. {
  257. GP_ASSERT(_ghostObject);
  258. GP_ASSERT(_node);
  259. // First check for existing collisions and attempt to respond/fix them.
  260. // Basically we are trying to move the character so that it does not penetrate
  261. // any other collision objects in the scene. We need to do this to ensure that
  262. // the following steps (movement) start from a clean slate, where the character
  263. // is not colliding with anything. Also, this step handles collision between
  264. // dynamic objects (i.e. objects that moved and now intersect the character).
  265. if (_physicsEnabled)
  266. {
  267. _colliding = false;
  268. int stepCount = 0;
  269. while (fixCollision(collisionWorld))
  270. {
  271. _colliding = true;
  272. if (++stepCount > 4)
  273. {
  274. // Most likely we are wedged between a number of different collision objects.
  275. break;
  276. }
  277. }
  278. }
  279. // Update current and target world positions.
  280. btVector3 startPosition = _ghostObject->getWorldTransform().getOrigin();
  281. _currentPosition = startPosition;
  282. // Process movement in the up direction.
  283. if (_physicsEnabled)
  284. stepUp(collisionWorld, deltaTimeStep);
  285. // Process horizontal movement.
  286. stepForwardAndStrafe(collisionWorld, deltaTimeStep);
  287. // Process movement in the down direction.
  288. if (_physicsEnabled)
  289. stepDown(collisionWorld, deltaTimeStep);
  290. // Set new position.
  291. btVector3 translation = _currentPosition - startPosition;
  292. _node->translate(translation.x(), translation.y(), translation.z());
  293. }
  294. void PhysicsCharacter::stepUp(btCollisionWorld* collisionWorld, btScalar time)
  295. {
  296. btVector3 targetPosition(_currentPosition);
  297. if (_verticalVelocity.isZero())
  298. {
  299. // Simply increase our poisiton by step height to enable us
  300. // to smoothly move over steps.
  301. targetPosition += btVector3(0, _stepHeight, 0);
  302. }
  303. // TODO: Convex sweep test to ensure we didn't hit anything during the step up.
  304. _currentPosition = targetPosition;
  305. }
  306. void PhysicsCharacter::stepForwardAndStrafe(btCollisionWorld* collisionWorld, float time)
  307. {
  308. updateCurrentVelocity();
  309. // Calculate final velocity
  310. btVector3 velocity(_currentVelocity);
  311. velocity *= time; // since velocity is in meters per second
  312. if (velocity.isZero())
  313. {
  314. // No velocity, so we aren't moving
  315. return;
  316. }
  317. // Translate the target position by the velocity vector (already scaled by t)
  318. btVector3 targetPosition = _currentPosition + velocity;
  319. // If physics is disabled, simply update current position without checking collisions
  320. if (!_physicsEnabled)
  321. {
  322. _currentPosition = targetPosition;
  323. return;
  324. }
  325. // Check for collisions by performing a bullet convex sweep test
  326. btTransform start;
  327. btTransform end;
  328. start.setIdentity();
  329. end.setIdentity();
  330. btScalar fraction = 1.0;
  331. btScalar distance2;
  332. if (_colliding && (_normalizedVelocity.dot(_collisionNormal) > btScalar(0.0)))
  333. {
  334. updateTargetPositionFromCollision(targetPosition, _collisionNormal);
  335. }
  336. int maxIter = 10;
  337. GP_ASSERT(_ghostObject && _ghostObject->getBroadphaseHandle());
  338. GP_ASSERT(_collisionShape);
  339. GP_ASSERT(collisionWorld);
  340. GP_ASSERT(Game::getInstance()->getPhysicsController());
  341. while (fraction > btScalar(0.01) && maxIter-- > 0)
  342. {
  343. start.setOrigin(_currentPosition);
  344. end.setOrigin(targetPosition);
  345. btVector3 sweepDirNegative(_currentPosition - targetPosition);
  346. ClosestNotMeConvexResultCallback callback(this, sweepDirNegative, btScalar(0.0));
  347. callback.m_collisionFilterGroup = _ghostObject->getBroadphaseHandle()->m_collisionFilterGroup;
  348. callback.m_collisionFilterMask = _ghostObject->getBroadphaseHandle()->m_collisionFilterMask;
  349. _ghostObject->convexSweepTest(static_cast<btConvexShape*>(_collisionShape->getShape()), start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  350. fraction -= callback.m_closestHitFraction;
  351. if (callback.hasHit())
  352. {
  353. Vector3 normal(callback.m_hitNormalWorld.x(), callback.m_hitNormalWorld.y(), callback.m_hitNormalWorld.z());
  354. PhysicsCollisionObject* o = Game::getInstance()->getPhysicsController()->getCollisionObject(callback.m_hitCollisionObject);
  355. GP_ASSERT(o);
  356. if (o->getType() == PhysicsCollisionObject::RIGID_BODY && o->isDynamic())
  357. {
  358. PhysicsRigidBody* rb = static_cast<PhysicsRigidBody*>(o);
  359. GP_ASSERT(rb);
  360. normal.normalize();
  361. rb->applyImpulse(_mass * -normal * velocity.length());
  362. }
  363. updateTargetPositionFromCollision(targetPosition, callback.m_hitNormalWorld);
  364. btVector3 currentDir = targetPosition - _currentPosition;
  365. distance2 = currentDir.length2();
  366. if (distance2 > FLT_EPSILON)
  367. {
  368. currentDir.normalize();
  369. // If velocity is against original velocity, stop to avoid tiny oscilations in sloping corners.
  370. if (currentDir.dot(_normalizedVelocity) <= btScalar(0.0))
  371. {
  372. break;
  373. }
  374. }
  375. }
  376. else
  377. {
  378. // Nothing in our way
  379. break;
  380. }
  381. }
  382. _currentPosition = targetPosition;
  383. }
  384. void PhysicsCharacter::stepDown(btCollisionWorld* collisionWorld, btScalar time)
  385. {
  386. GP_ASSERT(Game::getInstance()->getPhysicsController() && Game::getInstance()->getPhysicsController()->_world);
  387. GP_ASSERT(_ghostObject && _ghostObject->getBroadphaseHandle());
  388. GP_ASSERT(_collisionShape);
  389. GP_ASSERT(collisionWorld);
  390. // Contribute gravity to vertical velocity.
  391. btVector3 gravity = Game::getInstance()->getPhysicsController()->_world->getGravity();
  392. _verticalVelocity += (gravity * time);
  393. // Compute new position from vertical velocity.
  394. btVector3 targetPosition = _currentPosition + (_verticalVelocity * time);
  395. targetPosition -= btVector3(0, _stepHeight, 0);
  396. // Perform a convex sweep test between current and target position.
  397. btTransform start;
  398. btTransform end;
  399. start.setIdentity();
  400. end.setIdentity();
  401. btScalar fraction = 1.0;
  402. int maxIter = 10;
  403. while (fraction > btScalar(0.01) && maxIter-- > 0)
  404. {
  405. start.setOrigin(_currentPosition);
  406. end.setOrigin(targetPosition);
  407. btVector3 sweepDirNegative(_currentPosition - targetPosition);
  408. ClosestNotMeConvexResultCallback callback(this, sweepDirNegative, 0.0);
  409. callback.m_collisionFilterGroup = _ghostObject->getBroadphaseHandle()->m_collisionFilterGroup;
  410. callback.m_collisionFilterMask = _ghostObject->getBroadphaseHandle()->m_collisionFilterMask;
  411. _ghostObject->convexSweepTest(static_cast<btConvexShape*>(_collisionShape->getShape()), start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  412. fraction -= callback.m_closestHitFraction;
  413. if (callback.hasHit())
  414. {
  415. // Collision detected, fix it.
  416. Vector3 normal(callback.m_hitNormalWorld.x(), callback.m_hitNormalWorld.y(), callback.m_hitNormalWorld.z());
  417. normal.normalize();
  418. float dot = normal.dot(Vector3::unitY());
  419. if (dot > 1.0f - MATH_EPSILON)
  420. {
  421. targetPosition.setInterpolate3(_currentPosition, targetPosition, callback.m_closestHitFraction);
  422. // Zero out fall velocity when we hit an object going straight down.
  423. _verticalVelocity.setZero();
  424. break;
  425. }
  426. else
  427. {
  428. PhysicsCollisionObject* o = Game::getInstance()->getPhysicsController()->getCollisionObject(callback.m_hitCollisionObject);
  429. GP_ASSERT(o);
  430. if (o->getType() == PhysicsCollisionObject::RIGID_BODY && o->isDynamic())
  431. {
  432. PhysicsRigidBody* rb = static_cast<PhysicsRigidBody*>(o);
  433. GP_ASSERT(rb);
  434. normal.normalize();
  435. rb->applyImpulse(_mass * -normal * sqrt(BV(normal).dot(_verticalVelocity)));
  436. }
  437. updateTargetPositionFromCollision(targetPosition, BV(normal));
  438. }
  439. }
  440. else
  441. {
  442. // Nothing is in the way.
  443. break;
  444. }
  445. }
  446. // Calculate what the vertical velocity actually is.
  447. // In cases where the character might not actually be able to move down,
  448. // but isn't intersecting with an object straight down either, we don't
  449. // want to keep increasing the vertical velocity until the character
  450. // randomly drops through the floor when it can finally move due to its
  451. // vertical velocity having such a great magnitude.
  452. if (!_verticalVelocity.isZero() && time > 0.0f)
  453. _verticalVelocity = ((targetPosition + btVector3(0.0, _stepHeight, 0.0)) - _currentPosition) / time;
  454. _currentPosition = targetPosition;
  455. }
  456. /*
  457. * Returns the reflection direction of a ray going 'direction' hitting a surface with normal 'normal'.
  458. */
  459. btVector3 computeReflectionDirection(const btVector3& direction, const btVector3& normal)
  460. {
  461. return direction - (btScalar(2.0) * direction.dot(normal)) * normal;
  462. }
  463. /*
  464. * Returns the portion of 'direction' that is parallel to 'normal'.
  465. */
  466. btVector3 parallelComponent(const btVector3& direction, const btVector3& normal)
  467. {
  468. btScalar magnitude = direction.dot(normal);
  469. return normal * magnitude;
  470. }
  471. /*
  472. * Returns the portion of 'direction' that is perpindicular to 'normal'.
  473. */
  474. btVector3 perpindicularComponent(const btVector3& direction, const btVector3& normal)
  475. {
  476. return direction - parallelComponent(direction, normal);
  477. }
  478. void PhysicsCharacter::updateTargetPositionFromCollision(btVector3& targetPosition, const btVector3& collisionNormal)
  479. {
  480. btVector3 movementDirection = targetPosition - _currentPosition;
  481. btScalar movementLength = movementDirection.length();
  482. if (movementLength > FLT_EPSILON)
  483. {
  484. movementDirection.normalize();
  485. btVector3 reflectDir = computeReflectionDirection(movementDirection, collisionNormal);
  486. reflectDir.normalize();
  487. btVector3 perpindicularDir = perpindicularComponent(reflectDir, collisionNormal);
  488. targetPosition = _currentPosition;
  489. // Disallow the character from moving up during collision recovery (using an arbitrary reasonable epsilon).
  490. // Note that this will need to be generalized to allow for an arbitrary up axis.
  491. if (perpindicularDir.y() < _stepHeight + 0.001)
  492. {
  493. btVector3 perpComponent = perpindicularDir * movementLength;
  494. targetPosition += perpComponent;
  495. }
  496. }
  497. }
  498. bool PhysicsCharacter::fixCollision(btCollisionWorld* world)
  499. {
  500. GP_ASSERT(_node);
  501. GP_ASSERT(_ghostObject);
  502. GP_ASSERT(world && world->getDispatcher());
  503. GP_ASSERT(Game::getInstance()->getPhysicsController());
  504. bool collision = false;
  505. btOverlappingPairCache* pairCache = _ghostObject->getOverlappingPairCache();
  506. GP_ASSERT(pairCache);
  507. // Tell the world to dispatch collision events for our ghost object.
  508. world->getDispatcher()->dispatchAllCollisionPairs(pairCache, world->getDispatchInfo(), world->getDispatcher());
  509. // Store our current world position.
  510. Vector3 startPosition;
  511. _node->getWorldMatrix().getTranslation(&startPosition);
  512. btVector3 currentPosition = BV(startPosition);
  513. // Handle all collisions/overlappign pairs.
  514. btScalar maxPenetration = btScalar(0.0);
  515. for (int i = 0, count = pairCache->getNumOverlappingPairs(); i < count; ++i)
  516. {
  517. _manifoldArray.resize(0);
  518. // Query contacts between this overlapping pair (store in _manifoldArray).
  519. btBroadphasePair* collisionPair = &pairCache->getOverlappingPairArray()[i];
  520. if (collisionPair->m_algorithm)
  521. {
  522. collisionPair->m_algorithm->getAllContactManifolds(_manifoldArray);
  523. }
  524. for (int j = 0, manifoldCount = _manifoldArray.size(); j < manifoldCount; ++j)
  525. {
  526. btPersistentManifold* manifold = _manifoldArray[j];
  527. GP_ASSERT(manifold);
  528. // Get the direction of the contact points (used to scale normal vector in the correct direction).
  529. btScalar directionSign = manifold->getBody0() == _ghostObject ? -1.0f : 1.0f;
  530. // Skip ghost objects.
  531. PhysicsCollisionObject* object = Game::getInstance()->getPhysicsController()->getCollisionObject(
  532. (btCollisionObject*)(manifold->getBody0() == _ghostObject ? manifold->getBody1() : manifold->getBody0()));
  533. if (!object || object->getType() == PhysicsCollisionObject::GHOST_OBJECT)
  534. continue;
  535. for (int p = 0, contactCount = manifold->getNumContacts(); p < contactCount; ++p)
  536. {
  537. const btManifoldPoint& pt = manifold->getContactPoint(p);
  538. // Get penetration distance for this contact point.
  539. btScalar dist = pt.getDistance();
  540. if (dist < 0.0)
  541. {
  542. // A negative distance means the objects are overlapping.
  543. if (dist < maxPenetration)
  544. {
  545. // Store collision normal for this point.
  546. maxPenetration = dist;
  547. _collisionNormal = pt.m_normalWorldOnB * directionSign;
  548. }
  549. // Calculate new position for object, which is translated back along the collision normal.
  550. currentPosition += pt.m_normalWorldOnB * directionSign * dist * 0.2f;
  551. collision = true;
  552. }
  553. }
  554. }
  555. }
  556. // Set the new world transformation to apply to fix the collision.
  557. _node->translate(Vector3(currentPosition.x(), currentPosition.y(), currentPosition.z()) - startPosition);
  558. return collision;
  559. }
  560. void PhysicsCharacter::debugDraw(btIDebugDraw* debugDrawer)
  561. {
  562. // debug drawing handled by PhysicsController
  563. }
  564. }