PhysicsCharacter.cpp 21 KB

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