PhysicsCharacter.cpp 24 KB

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