btKinematicCharacterController.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2008 Erwin Coumans http://bulletphysics.com
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. #include <stdio.h>
  14. #include "LinearMath/btIDebugDraw.h"
  15. #include "BulletCollision/CollisionDispatch/btGhostObject.h"
  16. #include "BulletCollision/CollisionShapes/btMultiSphereShape.h"
  17. #include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h"
  18. #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
  19. #include "BulletCollision/CollisionDispatch/btCollisionWorld.h"
  20. #include "LinearMath/btDefaultMotionState.h"
  21. #include "btKinematicCharacterController.h"
  22. // static helper method
  23. static btVector3
  24. getNormalizedVector(const btVector3& v)
  25. {
  26. btVector3 n(0, 0, 0);
  27. if (v.length() > SIMD_EPSILON)
  28. {
  29. n = v.normalized();
  30. }
  31. return n;
  32. }
  33. ///@todo Interact with dynamic objects,
  34. ///Ride kinematicly animated platforms properly
  35. ///More realistic (or maybe just a config option) falling
  36. /// -> Should integrate falling velocity manually and use that in stepDown()
  37. ///Support jumping
  38. ///Support ducking
  39. class btKinematicClosestNotMeRayResultCallback : public btCollisionWorld::ClosestRayResultCallback
  40. {
  41. public:
  42. btKinematicClosestNotMeRayResultCallback(btCollisionObject* me) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))
  43. {
  44. m_me = me;
  45. }
  46. virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)
  47. {
  48. if (rayResult.m_collisionObject == m_me)
  49. return 1.0;
  50. return ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace);
  51. }
  52. protected:
  53. btCollisionObject* m_me;
  54. };
  55. class btKinematicClosestNotMeConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback
  56. {
  57. public:
  58. btKinematicClosestNotMeConvexResultCallback(btCollisionObject* me, const btVector3& up, btScalar minSlopeDot)
  59. : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)), m_me(me), m_up(up), m_minSlopeDot(minSlopeDot)
  60. {
  61. }
  62. virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)
  63. {
  64. if (convexResult.m_hitCollisionObject == m_me)
  65. return btScalar(1.0);
  66. if (!convexResult.m_hitCollisionObject->hasContactResponse())
  67. return btScalar(1.0);
  68. btVector3 hitNormalWorld;
  69. if (normalInWorldSpace)
  70. {
  71. hitNormalWorld = convexResult.m_hitNormalLocal;
  72. }
  73. else
  74. {
  75. ///need to transform normal into worldspace
  76. hitNormalWorld = convexResult.m_hitCollisionObject->getWorldTransform().getBasis() * convexResult.m_hitNormalLocal;
  77. }
  78. btScalar dotUp = m_up.dot(hitNormalWorld);
  79. if (dotUp < m_minSlopeDot)
  80. {
  81. return btScalar(1.0);
  82. }
  83. return ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace);
  84. }
  85. protected:
  86. btCollisionObject* m_me;
  87. const btVector3 m_up;
  88. btScalar m_minSlopeDot;
  89. };
  90. /*
  91. * Returns the reflection direction of a ray going 'direction' hitting a surface with normal 'normal'
  92. *
  93. * from: http://www-cs-students.stanford.edu/~adityagp/final/node3.html
  94. */
  95. btVector3 btKinematicCharacterController::computeReflectionDirection(const btVector3& direction, const btVector3& normal)
  96. {
  97. return direction - (btScalar(2.0) * direction.dot(normal)) * normal;
  98. }
  99. /*
  100. * Returns the portion of 'direction' that is parallel to 'normal'
  101. */
  102. btVector3 btKinematicCharacterController::parallelComponent(const btVector3& direction, const btVector3& normal)
  103. {
  104. btScalar magnitude = direction.dot(normal);
  105. return normal * magnitude;
  106. }
  107. /*
  108. * Returns the portion of 'direction' that is perpindicular to 'normal'
  109. */
  110. btVector3 btKinematicCharacterController::perpindicularComponent(const btVector3& direction, const btVector3& normal)
  111. {
  112. return direction - parallelComponent(direction, normal);
  113. }
  114. btKinematicCharacterController::btKinematicCharacterController(btPairCachingGhostObject* ghostObject, btConvexShape* convexShape, btScalar stepHeight, const btVector3& up)
  115. {
  116. m_ghostObject = ghostObject;
  117. m_up.setValue(0.0f, 0.0f, 1.0f);
  118. m_jumpAxis.setValue(0.0f, 0.0f, 1.0f);
  119. m_addedMargin = 0.02;
  120. m_walkDirection.setValue(0.0, 0.0, 0.0);
  121. m_AngVel.setValue(0.0, 0.0, 0.0);
  122. m_useGhostObjectSweepTest = true;
  123. m_turnAngle = btScalar(0.0);
  124. m_convexShape = convexShape;
  125. m_useWalkDirection = true; // use walk direction by default, legacy behavior
  126. m_velocityTimeInterval = 0.0;
  127. m_verticalVelocity = 0.0;
  128. m_verticalOffset = 0.0;
  129. m_gravity = 9.8 * 3.0; // 3G acceleration.
  130. m_fallSpeed = 55.0; // Terminal velocity of a sky diver in m/s.
  131. m_jumpSpeed = 10.0; // ?
  132. m_SetjumpSpeed = m_jumpSpeed;
  133. m_wasOnGround = false;
  134. m_wasJumping = false;
  135. m_interpolateUp = true;
  136. m_currentStepOffset = 0.0;
  137. m_maxPenetrationDepth = 0.2;
  138. full_drop = false;
  139. bounce_fix = false;
  140. m_linearDamping = btScalar(0.0);
  141. m_angularDamping = btScalar(0.0);
  142. setUp(up);
  143. setStepHeight(stepHeight);
  144. setMaxSlope(btRadians(45.0));
  145. }
  146. btKinematicCharacterController::~btKinematicCharacterController()
  147. {
  148. }
  149. btPairCachingGhostObject* btKinematicCharacterController::getGhostObject()
  150. {
  151. return m_ghostObject;
  152. }
  153. bool btKinematicCharacterController::recoverFromPenetration(btCollisionWorld* collisionWorld)
  154. {
  155. // Here we must refresh the overlapping paircache as the penetrating movement itself or the
  156. // previous recovery iteration might have used setWorldTransform and pushed us into an object
  157. // that is not in the previous cache contents from the last timestep, as will happen if we
  158. // are pushed into a new AABB overlap. Unhandled this means the next convex sweep gets stuck.
  159. //
  160. // Do this by calling the broadphase's setAabb with the moved AABB, this will update the broadphase
  161. // paircache and the ghostobject's internal paircache at the same time. /BW
  162. btVector3 minAabb, maxAabb;
  163. m_convexShape->getAabb(m_ghostObject->getWorldTransform(), minAabb, maxAabb);
  164. collisionWorld->getBroadphase()->setAabb(m_ghostObject->getBroadphaseHandle(),
  165. minAabb,
  166. maxAabb,
  167. collisionWorld->getDispatcher());
  168. bool penetration = false;
  169. collisionWorld->getDispatcher()->dispatchAllCollisionPairs(m_ghostObject->getOverlappingPairCache(), collisionWorld->getDispatchInfo(), collisionWorld->getDispatcher());
  170. m_currentPosition = m_ghostObject->getWorldTransform().getOrigin();
  171. // btScalar maxPen = btScalar(0.0);
  172. for (int i = 0; i < m_ghostObject->getOverlappingPairCache()->getNumOverlappingPairs(); i++)
  173. {
  174. m_manifoldArray.resize(0);
  175. btBroadphasePair* collisionPair = &m_ghostObject->getOverlappingPairCache()->getOverlappingPairArray()[i];
  176. btCollisionObject* obj0 = static_cast<btCollisionObject*>(collisionPair->m_pProxy0->m_clientObject);
  177. btCollisionObject* obj1 = static_cast<btCollisionObject*>(collisionPair->m_pProxy1->m_clientObject);
  178. if ((obj0 && !obj0->hasContactResponse()) || (obj1 && !obj1->hasContactResponse()))
  179. continue;
  180. if (!needsCollision(obj0, obj1))
  181. continue;
  182. if (collisionPair->m_algorithm)
  183. collisionPair->m_algorithm->getAllContactManifolds(m_manifoldArray);
  184. for (int j = 0; j < m_manifoldArray.size(); j++)
  185. {
  186. btPersistentManifold* manifold = m_manifoldArray[j];
  187. btScalar directionSign = manifold->getBody0() == m_ghostObject ? btScalar(-1.0) : btScalar(1.0);
  188. for (int p = 0; p < manifold->getNumContacts(); p++)
  189. {
  190. const btManifoldPoint& pt = manifold->getContactPoint(p);
  191. btScalar dist = pt.getDistance();
  192. if (dist < -m_maxPenetrationDepth)
  193. {
  194. // TODO: cause problems on slopes, not sure if it is needed
  195. //if (dist < maxPen)
  196. //{
  197. // maxPen = dist;
  198. // m_touchingNormal = pt.m_normalWorldOnB * directionSign;//??
  199. //}
  200. m_currentPosition += pt.m_normalWorldOnB * directionSign * dist * btScalar(0.2);
  201. penetration = true;
  202. }
  203. else
  204. {
  205. //printf("touching %f\n", dist);
  206. }
  207. }
  208. //manifold->clearManifold();
  209. }
  210. }
  211. btTransform newTrans = m_ghostObject->getWorldTransform();
  212. newTrans.setOrigin(m_currentPosition);
  213. m_ghostObject->setWorldTransform(newTrans);
  214. // printf("m_touchingNormal = %f,%f,%f\n",m_touchingNormal[0],m_touchingNormal[1],m_touchingNormal[2]);
  215. return penetration;
  216. }
  217. void btKinematicCharacterController::stepUp(btCollisionWorld* world)
  218. {
  219. btScalar stepHeight = 0.0f;
  220. if (m_verticalVelocity < 0.0)
  221. stepHeight = m_stepHeight;
  222. // phase 1: up
  223. btTransform start, end;
  224. start.setIdentity();
  225. end.setIdentity();
  226. /* FIXME: Handle penetration properly */
  227. start.setOrigin(m_currentPosition);
  228. m_targetPosition = m_currentPosition + m_up * (stepHeight) + m_jumpAxis * ((m_verticalOffset > 0.f ? m_verticalOffset : 0.f));
  229. m_currentPosition = m_targetPosition;
  230. end.setOrigin(m_targetPosition);
  231. start.setRotation(m_currentOrientation);
  232. end.setRotation(m_targetOrientation);
  233. btKinematicClosestNotMeConvexResultCallback callback(m_ghostObject, -m_up, m_maxSlopeCosine);
  234. callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  235. callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  236. if (m_useGhostObjectSweepTest)
  237. {
  238. m_ghostObject->convexSweepTest(m_convexShape, start, end, callback, world->getDispatchInfo().m_allowedCcdPenetration);
  239. }
  240. else
  241. {
  242. world->convexSweepTest(m_convexShape, start, end, callback, world->getDispatchInfo().m_allowedCcdPenetration);
  243. }
  244. if (callback.hasHit() && m_ghostObject->hasContactResponse() && needsCollision(m_ghostObject, callback.m_hitCollisionObject))
  245. {
  246. // Only modify the position if the hit was a slope and not a wall or ceiling.
  247. if (callback.m_hitNormalWorld.dot(m_up) > 0.0)
  248. {
  249. // we moved up only a fraction of the step height
  250. m_currentStepOffset = stepHeight * callback.m_closestHitFraction;
  251. if (m_interpolateUp == true)
  252. m_currentPosition.setInterpolate3(m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  253. else
  254. m_currentPosition = m_targetPosition;
  255. }
  256. btTransform& xform = m_ghostObject->getWorldTransform();
  257. xform.setOrigin(m_currentPosition);
  258. m_ghostObject->setWorldTransform(xform);
  259. // fix penetration if we hit a ceiling for example
  260. int numPenetrationLoops = 0;
  261. m_touchingContact = false;
  262. while (recoverFromPenetration(world))
  263. {
  264. numPenetrationLoops++;
  265. m_touchingContact = true;
  266. if (numPenetrationLoops > 4)
  267. {
  268. //printf("character could not recover from penetration = %d\n", numPenetrationLoops);
  269. break;
  270. }
  271. }
  272. m_targetPosition = m_ghostObject->getWorldTransform().getOrigin();
  273. m_currentPosition = m_targetPosition;
  274. if (m_verticalOffset > 0)
  275. {
  276. m_verticalOffset = 0.0;
  277. m_verticalVelocity = 0.0;
  278. m_currentStepOffset = m_stepHeight;
  279. }
  280. }
  281. else
  282. {
  283. m_currentStepOffset = stepHeight;
  284. m_currentPosition = m_targetPosition;
  285. }
  286. }
  287. bool btKinematicCharacterController::needsCollision(const btCollisionObject* body0, const btCollisionObject* body1)
  288. {
  289. bool collides = (body0->getBroadphaseHandle()->m_collisionFilterGroup & body1->getBroadphaseHandle()->m_collisionFilterMask) != 0;
  290. collides = collides && (body1->getBroadphaseHandle()->m_collisionFilterGroup & body0->getBroadphaseHandle()->m_collisionFilterMask);
  291. return collides;
  292. }
  293. void btKinematicCharacterController::updateTargetPositionBasedOnCollision(const btVector3& hitNormal, btScalar tangentMag, btScalar normalMag)
  294. {
  295. btVector3 movementDirection = m_targetPosition - m_currentPosition;
  296. btScalar movementLength = movementDirection.length();
  297. if (movementLength > SIMD_EPSILON)
  298. {
  299. movementDirection.normalize();
  300. btVector3 reflectDir = computeReflectionDirection(movementDirection, hitNormal);
  301. reflectDir.normalize();
  302. btVector3 parallelDir, perpindicularDir;
  303. parallelDir = parallelComponent(reflectDir, hitNormal);
  304. perpindicularDir = perpindicularComponent(reflectDir, hitNormal);
  305. m_targetPosition = m_currentPosition;
  306. if (0) //tangentMag != 0.0)
  307. {
  308. btVector3 parComponent = parallelDir * btScalar(tangentMag * movementLength);
  309. // printf("parComponent=%f,%f,%f\n",parComponent[0],parComponent[1],parComponent[2]);
  310. m_targetPosition += parComponent;
  311. }
  312. if (normalMag != 0.0)
  313. {
  314. btVector3 perpComponent = perpindicularDir * btScalar(normalMag * movementLength);
  315. // printf("perpComponent=%f,%f,%f\n",perpComponent[0],perpComponent[1],perpComponent[2]);
  316. m_targetPosition += perpComponent;
  317. }
  318. }
  319. else
  320. {
  321. // printf("movementLength don't normalize a zero vector\n");
  322. }
  323. }
  324. void btKinematicCharacterController::stepForwardAndStrafe(btCollisionWorld* collisionWorld, const btVector3& walkMove)
  325. {
  326. // printf("m_normalizedDirection=%f,%f,%f\n",
  327. // m_normalizedDirection[0],m_normalizedDirection[1],m_normalizedDirection[2]);
  328. // phase 2: forward and strafe
  329. btTransform start, end;
  330. m_targetPosition = m_currentPosition + walkMove;
  331. start.setIdentity();
  332. end.setIdentity();
  333. btScalar fraction = 1.0;
  334. btScalar distance2 = (m_currentPosition - m_targetPosition).length2();
  335. // printf("distance2=%f\n",distance2);
  336. int maxIter = 10;
  337. while (fraction > btScalar(0.01) && maxIter-- > 0)
  338. {
  339. start.setOrigin(m_currentPosition);
  340. end.setOrigin(m_targetPosition);
  341. btVector3 sweepDirNegative(m_currentPosition - m_targetPosition);
  342. start.setRotation(m_currentOrientation);
  343. end.setRotation(m_targetOrientation);
  344. btKinematicClosestNotMeConvexResultCallback callback(m_ghostObject, sweepDirNegative, btScalar(0.0));
  345. callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  346. callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  347. btScalar margin = m_convexShape->getMargin();
  348. m_convexShape->setMargin(margin + m_addedMargin);
  349. if (!(start == end))
  350. {
  351. if (m_useGhostObjectSweepTest)
  352. {
  353. m_ghostObject->convexSweepTest(m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  354. }
  355. else
  356. {
  357. collisionWorld->convexSweepTest(m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  358. }
  359. }
  360. m_convexShape->setMargin(margin);
  361. fraction -= callback.m_closestHitFraction;
  362. if (callback.hasHit() && m_ghostObject->hasContactResponse() && needsCollision(m_ghostObject, callback.m_hitCollisionObject))
  363. {
  364. // we moved only a fraction
  365. //btScalar hitDistance;
  366. //hitDistance = (callback.m_hitPointWorld - m_currentPosition).length();
  367. // m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  368. updateTargetPositionBasedOnCollision(callback.m_hitNormalWorld);
  369. btVector3 currentDir = m_targetPosition - m_currentPosition;
  370. distance2 = currentDir.length2();
  371. if (distance2 > SIMD_EPSILON)
  372. {
  373. currentDir.normalize();
  374. /* See Quake2: "If velocity is against original velocity, stop ead to avoid tiny oscilations in sloping corners." */
  375. if (currentDir.dot(m_normalizedDirection) <= btScalar(0.0))
  376. {
  377. break;
  378. }
  379. }
  380. else
  381. {
  382. // printf("currentDir: don't normalize a zero vector\n");
  383. break;
  384. }
  385. }
  386. else
  387. {
  388. m_currentPosition = m_targetPosition;
  389. }
  390. }
  391. }
  392. void btKinematicCharacterController::stepDown(btCollisionWorld* collisionWorld, btScalar dt)
  393. {
  394. btTransform start, end, end_double;
  395. bool runonce = false;
  396. // phase 3: down
  397. /*btScalar additionalDownStep = (m_wasOnGround && !onGround()) ? m_stepHeight : 0.0;
  398. btVector3 step_drop = m_up * (m_currentStepOffset + additionalDownStep);
  399. btScalar downVelocity = (additionalDownStep == 0.0 && m_verticalVelocity<0.0?-m_verticalVelocity:0.0) * dt;
  400. btVector3 gravity_drop = m_up * downVelocity;
  401. m_targetPosition -= (step_drop + gravity_drop);*/
  402. btVector3 orig_position = m_targetPosition;
  403. btScalar downVelocity = (m_verticalVelocity < 0.f ? -m_verticalVelocity : 0.f) * dt;
  404. if (m_verticalVelocity > 0.0)
  405. return;
  406. if (downVelocity > 0.0 && downVelocity > m_fallSpeed && (m_wasOnGround || !m_wasJumping))
  407. downVelocity = m_fallSpeed;
  408. btVector3 step_drop = m_up * (m_currentStepOffset + downVelocity);
  409. m_targetPosition -= step_drop;
  410. btKinematicClosestNotMeConvexResultCallback callback(m_ghostObject, m_up, m_maxSlopeCosine);
  411. callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  412. callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  413. btKinematicClosestNotMeConvexResultCallback callback2(m_ghostObject, m_up, m_maxSlopeCosine);
  414. callback2.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  415. callback2.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  416. while (1)
  417. {
  418. start.setIdentity();
  419. end.setIdentity();
  420. end_double.setIdentity();
  421. start.setOrigin(m_currentPosition);
  422. end.setOrigin(m_targetPosition);
  423. start.setRotation(m_currentOrientation);
  424. end.setRotation(m_targetOrientation);
  425. //set double test for 2x the step drop, to check for a large drop vs small drop
  426. end_double.setOrigin(m_targetPosition - step_drop);
  427. if (m_useGhostObjectSweepTest)
  428. {
  429. m_ghostObject->convexSweepTest(m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  430. if (!callback.hasHit() && m_ghostObject->hasContactResponse())
  431. {
  432. //test a double fall height, to see if the character should interpolate it's fall (full) or not (partial)
  433. m_ghostObject->convexSweepTest(m_convexShape, start, end_double, callback2, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  434. }
  435. }
  436. else
  437. {
  438. collisionWorld->convexSweepTest(m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  439. if (!callback.hasHit() && m_ghostObject->hasContactResponse())
  440. {
  441. //test a double fall height, to see if the character should interpolate it's fall (large) or not (small)
  442. collisionWorld->convexSweepTest(m_convexShape, start, end_double, callback2, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  443. }
  444. }
  445. btScalar downVelocity2 = (m_verticalVelocity < 0.f ? -m_verticalVelocity : 0.f) * dt;
  446. bool has_hit;
  447. if (bounce_fix == true)
  448. has_hit = (callback.hasHit() || callback2.hasHit()) && m_ghostObject->hasContactResponse() && needsCollision(m_ghostObject, callback.m_hitCollisionObject);
  449. else
  450. has_hit = callback2.hasHit() && m_ghostObject->hasContactResponse() && needsCollision(m_ghostObject, callback2.m_hitCollisionObject);
  451. btScalar stepHeight = 0.0f;
  452. if (m_verticalVelocity < 0.0)
  453. stepHeight = m_stepHeight;
  454. if (downVelocity2 > 0.0 && downVelocity2 < stepHeight && has_hit == true && runonce == false && (m_wasOnGround || !m_wasJumping))
  455. {
  456. //redo the velocity calculation when falling a small amount, for fast stairs motion
  457. //for larger falls, use the smoother/slower interpolated movement by not touching the target position
  458. m_targetPosition = orig_position;
  459. downVelocity = stepHeight;
  460. step_drop = m_up * (m_currentStepOffset + downVelocity);
  461. m_targetPosition -= step_drop;
  462. runonce = true;
  463. continue; //re-run previous tests
  464. }
  465. break;
  466. }
  467. if ((m_ghostObject->hasContactResponse() && (callback.hasHit() && needsCollision(m_ghostObject, callback.m_hitCollisionObject))) || runonce == true)
  468. {
  469. // we dropped a fraction of the height -> hit floor
  470. btScalar fraction = (m_currentPosition.getY() - callback.m_hitPointWorld.getY()) / 2;
  471. //printf("hitpoint: %g - pos %g\n", callback.m_hitPointWorld.getY(), m_currentPosition.getY());
  472. if (bounce_fix == true)
  473. {
  474. if (full_drop == true)
  475. m_currentPosition.setInterpolate3(m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  476. else
  477. //due to errors in the closestHitFraction variable when used with large polygons, calculate the hit fraction manually
  478. m_currentPosition.setInterpolate3(m_currentPosition, m_targetPosition, fraction);
  479. }
  480. else
  481. m_currentPosition.setInterpolate3(m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  482. full_drop = false;
  483. m_verticalVelocity = 0.0;
  484. m_verticalOffset = 0.0;
  485. m_wasJumping = false;
  486. }
  487. else
  488. {
  489. // we dropped the full height
  490. full_drop = true;
  491. if (bounce_fix == true)
  492. {
  493. downVelocity = (m_verticalVelocity < 0.f ? -m_verticalVelocity : 0.f) * dt;
  494. if (downVelocity > m_fallSpeed && (m_wasOnGround || !m_wasJumping))
  495. {
  496. m_targetPosition += step_drop; //undo previous target change
  497. downVelocity = m_fallSpeed;
  498. step_drop = m_up * (m_currentStepOffset + downVelocity);
  499. m_targetPosition -= step_drop;
  500. }
  501. }
  502. //printf("full drop - %g, %g\n", m_currentPosition.getY(), m_targetPosition.getY());
  503. m_currentPosition = m_targetPosition;
  504. }
  505. }
  506. void btKinematicCharacterController::setWalkDirection(
  507. const btVector3& walkDirection)
  508. {
  509. m_useWalkDirection = true;
  510. m_walkDirection = walkDirection;
  511. m_normalizedDirection = getNormalizedVector(m_walkDirection);
  512. }
  513. void btKinematicCharacterController::setVelocityForTimeInterval(
  514. const btVector3& velocity,
  515. btScalar timeInterval)
  516. {
  517. // printf("setVelocity!\n");
  518. // printf(" interval: %f\n", timeInterval);
  519. // printf(" velocity: (%f, %f, %f)\n",
  520. // velocity.x(), velocity.y(), velocity.z());
  521. m_useWalkDirection = false;
  522. m_walkDirection = velocity;
  523. m_normalizedDirection = getNormalizedVector(m_walkDirection);
  524. m_velocityTimeInterval += timeInterval;
  525. }
  526. void btKinematicCharacterController::setAngularVelocity(const btVector3& velocity)
  527. {
  528. m_AngVel = velocity;
  529. }
  530. const btVector3& btKinematicCharacterController::getAngularVelocity() const
  531. {
  532. return m_AngVel;
  533. }
  534. void btKinematicCharacterController::setLinearVelocity(const btVector3& velocity)
  535. {
  536. m_walkDirection = velocity;
  537. // HACK: if we are moving in the direction of the up, treat it as a jump :(
  538. if (m_walkDirection.length2() > 0)
  539. {
  540. btVector3 w = velocity.normalized();
  541. btScalar c = w.dot(m_up);
  542. if (c != 0)
  543. {
  544. //there is a component in walkdirection for vertical velocity
  545. btVector3 upComponent = m_up * (btSin(SIMD_HALF_PI - btAcos(c)) * m_walkDirection.length());
  546. m_walkDirection -= upComponent;
  547. m_verticalVelocity = (c < 0.0f ? -1 : 1) * upComponent.length();
  548. if (c > 0.0f)
  549. {
  550. m_wasJumping = true;
  551. m_jumpPosition = m_ghostObject->getWorldTransform().getOrigin();
  552. }
  553. }
  554. }
  555. else
  556. m_verticalVelocity = 0.0f;
  557. }
  558. btVector3 btKinematicCharacterController::getLinearVelocity() const
  559. {
  560. return m_walkDirection + (m_verticalVelocity * m_up);
  561. }
  562. void btKinematicCharacterController::reset(btCollisionWorld* collisionWorld)
  563. {
  564. m_verticalVelocity = 0.0;
  565. m_verticalOffset = 0.0;
  566. m_wasOnGround = false;
  567. m_wasJumping = false;
  568. m_walkDirection.setValue(0, 0, 0);
  569. m_velocityTimeInterval = 0.0;
  570. //clear pair cache
  571. btHashedOverlappingPairCache* cache = m_ghostObject->getOverlappingPairCache();
  572. while (cache->getOverlappingPairArray().size() > 0)
  573. {
  574. cache->removeOverlappingPair(cache->getOverlappingPairArray()[0].m_pProxy0, cache->getOverlappingPairArray()[0].m_pProxy1, collisionWorld->getDispatcher());
  575. }
  576. }
  577. void btKinematicCharacterController::warp(const btVector3& origin)
  578. {
  579. btTransform xform;
  580. xform.setIdentity();
  581. xform.setOrigin(origin);
  582. m_ghostObject->setWorldTransform(xform);
  583. }
  584. void btKinematicCharacterController::preStep(btCollisionWorld* collisionWorld)
  585. {
  586. m_currentPosition = m_ghostObject->getWorldTransform().getOrigin();
  587. m_targetPosition = m_currentPosition;
  588. m_currentOrientation = m_ghostObject->getWorldTransform().getRotation();
  589. m_targetOrientation = m_currentOrientation;
  590. // printf("m_targetPosition=%f,%f,%f\n",m_targetPosition[0],m_targetPosition[1],m_targetPosition[2]);
  591. }
  592. void btKinematicCharacterController::playerStep(btCollisionWorld* collisionWorld, btScalar dt)
  593. {
  594. // printf("playerStep(): ");
  595. // printf(" dt = %f", dt);
  596. if (m_AngVel.length2() > 0.0f)
  597. {
  598. m_AngVel *= btPow(btScalar(1) - m_angularDamping, dt);
  599. }
  600. // integrate for angular velocity
  601. if (m_AngVel.length2() > 0.0f)
  602. {
  603. btTransform xform;
  604. xform = m_ghostObject->getWorldTransform();
  605. btQuaternion rot(m_AngVel.normalized(), m_AngVel.length() * dt);
  606. btQuaternion orn = rot * xform.getRotation();
  607. xform.setRotation(orn);
  608. m_ghostObject->setWorldTransform(xform);
  609. m_currentPosition = m_ghostObject->getWorldTransform().getOrigin();
  610. m_targetPosition = m_currentPosition;
  611. m_currentOrientation = m_ghostObject->getWorldTransform().getRotation();
  612. m_targetOrientation = m_currentOrientation;
  613. }
  614. // quick check...
  615. if (!m_useWalkDirection && (m_velocityTimeInterval <= 0.0 || m_walkDirection.fuzzyZero()))
  616. {
  617. // printf("\n");
  618. return; // no motion
  619. }
  620. m_wasOnGround = onGround();
  621. //btVector3 lvel = m_walkDirection;
  622. //btScalar c = 0.0f;
  623. if (m_walkDirection.length2() > 0)
  624. {
  625. // apply damping
  626. m_walkDirection *= btPow(btScalar(1) - m_linearDamping, dt);
  627. }
  628. m_verticalVelocity *= btPow(btScalar(1) - m_linearDamping, dt);
  629. // Update fall velocity.
  630. m_verticalVelocity -= m_gravity * dt;
  631. if (m_verticalVelocity > 0.0 && m_verticalVelocity > m_jumpSpeed)
  632. {
  633. m_verticalVelocity = m_jumpSpeed;
  634. }
  635. if (m_verticalVelocity < 0.0 && btFabs(m_verticalVelocity) > btFabs(m_fallSpeed))
  636. {
  637. m_verticalVelocity = -btFabs(m_fallSpeed);
  638. }
  639. m_verticalOffset = m_verticalVelocity * dt;
  640. btTransform xform;
  641. xform = m_ghostObject->getWorldTransform();
  642. // printf("walkDirection(%f,%f,%f)\n",walkDirection[0],walkDirection[1],walkDirection[2]);
  643. // printf("walkSpeed=%f\n",walkSpeed);
  644. stepUp(collisionWorld);
  645. //todo: Experimenting with behavior of controller when it hits a ceiling..
  646. //bool hitUp = stepUp (collisionWorld);
  647. //if (hitUp)
  648. //{
  649. // m_verticalVelocity -= m_gravity * dt;
  650. // if (m_verticalVelocity > 0.0 && m_verticalVelocity > m_jumpSpeed)
  651. // {
  652. // m_verticalVelocity = m_jumpSpeed;
  653. // }
  654. // if (m_verticalVelocity < 0.0 && btFabs(m_verticalVelocity) > btFabs(m_fallSpeed))
  655. // {
  656. // m_verticalVelocity = -btFabs(m_fallSpeed);
  657. // }
  658. // m_verticalOffset = m_verticalVelocity * dt;
  659. // xform = m_ghostObject->getWorldTransform();
  660. //}
  661. if (m_useWalkDirection)
  662. {
  663. stepForwardAndStrafe(collisionWorld, m_walkDirection);
  664. }
  665. else
  666. {
  667. //printf(" time: %f", m_velocityTimeInterval);
  668. // still have some time left for moving!
  669. btScalar dtMoving =
  670. (dt < m_velocityTimeInterval) ? dt : m_velocityTimeInterval;
  671. m_velocityTimeInterval -= dt;
  672. // how far will we move while we are moving?
  673. btVector3 move = m_walkDirection * dtMoving;
  674. //printf(" dtMoving: %f", dtMoving);
  675. // okay, step
  676. stepForwardAndStrafe(collisionWorld, move);
  677. }
  678. stepDown(collisionWorld, dt);
  679. //todo: Experimenting with max jump height
  680. //if (m_wasJumping)
  681. //{
  682. // btScalar ds = m_currentPosition[m_upAxis] - m_jumpPosition[m_upAxis];
  683. // if (ds > m_maxJumpHeight)
  684. // {
  685. // // substract the overshoot
  686. // m_currentPosition[m_upAxis] -= ds - m_maxJumpHeight;
  687. // // max height was reached, so potential energy is at max
  688. // // and kinematic energy is 0, thus velocity is 0.
  689. // if (m_verticalVelocity > 0.0)
  690. // m_verticalVelocity = 0.0;
  691. // }
  692. //}
  693. // printf("\n");
  694. xform.setOrigin(m_currentPosition);
  695. m_ghostObject->setWorldTransform(xform);
  696. int numPenetrationLoops = 0;
  697. m_touchingContact = false;
  698. while (recoverFromPenetration(collisionWorld))
  699. {
  700. numPenetrationLoops++;
  701. m_touchingContact = true;
  702. if (numPenetrationLoops > 4)
  703. {
  704. //printf("character could not recover from penetration = %d\n", numPenetrationLoops);
  705. break;
  706. }
  707. }
  708. }
  709. void btKinematicCharacterController::setFallSpeed(btScalar fallSpeed)
  710. {
  711. m_fallSpeed = fallSpeed;
  712. }
  713. void btKinematicCharacterController::setJumpSpeed(btScalar jumpSpeed)
  714. {
  715. m_jumpSpeed = jumpSpeed;
  716. m_SetjumpSpeed = m_jumpSpeed;
  717. }
  718. void btKinematicCharacterController::setMaxJumpHeight(btScalar maxJumpHeight)
  719. {
  720. m_maxJumpHeight = maxJumpHeight;
  721. }
  722. bool btKinematicCharacterController::canJump() const
  723. {
  724. return onGround();
  725. }
  726. void btKinematicCharacterController::jump(const btVector3& v)
  727. {
  728. m_jumpSpeed = v.length2() == 0 ? m_SetjumpSpeed : v.length();
  729. m_verticalVelocity = m_jumpSpeed;
  730. m_wasJumping = true;
  731. m_jumpAxis = v.length2() == 0 ? m_up : v.normalized();
  732. m_jumpPosition = m_ghostObject->getWorldTransform().getOrigin();
  733. #if 0
  734. currently no jumping.
  735. btTransform xform;
  736. m_rigidBody->getMotionState()->getWorldTransform (xform);
  737. btVector3 up = xform.getBasis()[1];
  738. up.normalize ();
  739. btScalar magnitude = (btScalar(1.0)/m_rigidBody->getInvMass()) * btScalar(8.0);
  740. m_rigidBody->applyCentralImpulse (up * magnitude);
  741. #endif
  742. }
  743. void btKinematicCharacterController::setGravity(const btVector3& gravity)
  744. {
  745. if (gravity.length2() > 0) setUpVector(-gravity);
  746. m_gravity = gravity.length();
  747. }
  748. btVector3 btKinematicCharacterController::getGravity() const
  749. {
  750. return -m_gravity * m_up;
  751. }
  752. void btKinematicCharacterController::setMaxSlope(btScalar slopeRadians)
  753. {
  754. m_maxSlopeRadians = slopeRadians;
  755. m_maxSlopeCosine = btCos(slopeRadians);
  756. }
  757. btScalar btKinematicCharacterController::getMaxSlope() const
  758. {
  759. return m_maxSlopeRadians;
  760. }
  761. void btKinematicCharacterController::setMaxPenetrationDepth(btScalar d)
  762. {
  763. m_maxPenetrationDepth = d;
  764. }
  765. btScalar btKinematicCharacterController::getMaxPenetrationDepth() const
  766. {
  767. return m_maxPenetrationDepth;
  768. }
  769. bool btKinematicCharacterController::onGround() const
  770. {
  771. return (fabs(m_verticalVelocity) < SIMD_EPSILON) && (fabs(m_verticalOffset) < SIMD_EPSILON);
  772. }
  773. void btKinematicCharacterController::setStepHeight(btScalar h)
  774. {
  775. m_stepHeight = h;
  776. }
  777. btVector3* btKinematicCharacterController::getUpAxisDirections()
  778. {
  779. static btVector3 sUpAxisDirection[3] = {btVector3(1.0f, 0.0f, 0.0f), btVector3(0.0f, 1.0f, 0.0f), btVector3(0.0f, 0.0f, 1.0f)};
  780. return sUpAxisDirection;
  781. }
  782. void btKinematicCharacterController::debugDraw(btIDebugDraw* debugDrawer)
  783. {
  784. }
  785. void btKinematicCharacterController::setUpInterpolate(bool value)
  786. {
  787. m_interpolateUp = value;
  788. }
  789. void btKinematicCharacterController::setUp(const btVector3& up)
  790. {
  791. if (up.length2() > 0 && m_gravity > 0.0f)
  792. {
  793. setGravity(-m_gravity * up.normalized());
  794. return;
  795. }
  796. setUpVector(up);
  797. }
  798. void btKinematicCharacterController::setUpVector(const btVector3& up)
  799. {
  800. if (m_up == up)
  801. return;
  802. btVector3 u = m_up;
  803. if (up.length2() > 0)
  804. m_up = up.normalized();
  805. else
  806. m_up = btVector3(0.0, 0.0, 0.0);
  807. if (!m_ghostObject) return;
  808. btQuaternion rot = getRotation(m_up, u);
  809. //set orientation with new up
  810. btTransform xform;
  811. xform = m_ghostObject->getWorldTransform();
  812. btQuaternion orn = rot.inverse() * xform.getRotation();
  813. xform.setRotation(orn);
  814. m_ghostObject->setWorldTransform(xform);
  815. }
  816. btQuaternion btKinematicCharacterController::getRotation(btVector3& v0, btVector3& v1) const
  817. {
  818. if (v0.length2() == 0.0f || v1.length2() == 0.0f)
  819. {
  820. btQuaternion q;
  821. return q;
  822. }
  823. return shortestArcQuatNormalize2(v0, v1);
  824. }