btKinematicCharacterController.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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 "bullet/LinearMath/btIDebugDraw.h"
  15. #include "bullet/BulletCollision//CollisionDispatch/btGhostObject.h"
  16. #include "bullet/BulletCollision//CollisionShapes/btMultiSphereShape.h"
  17. #include "bullet/BulletCollision//BroadphaseCollision/btOverlappingPairCache.h"
  18. #include "bullet/BulletCollision//BroadphaseCollision/btCollisionAlgorithm.h"
  19. #include "bullet/BulletCollision//CollisionDispatch/btCollisionWorld.h"
  20. #include "bullet/LinearMath/btDefaultMotionState.h"
  21. #include "btKinematicCharacterController.h"
  22. // static helper method
  23. static btVector3
  24. getNormalizedVector(const btVector3& v)
  25. {
  26. btVector3 n = v.normalized();
  27. if (n.length() < SIMD_EPSILON) {
  28. n.setValue(0, 0, 0);
  29. }
  30. return n;
  31. }
  32. ///@todo Interact with dynamic objects,
  33. ///Ride kinematicly animated platforms properly
  34. ///More realistic (or maybe just a config option) falling
  35. /// -> Should integrate falling velocity manually and use that in stepDown()
  36. ///Support jumping
  37. ///Support ducking
  38. class btKinematicClosestNotMeRayResultCallback : public btCollisionWorld::ClosestRayResultCallback
  39. {
  40. public:
  41. btKinematicClosestNotMeRayResultCallback (btCollisionObject* me) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))
  42. {
  43. m_me = me;
  44. }
  45. virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace)
  46. {
  47. if (rayResult.m_collisionObject == m_me)
  48. return 1.0;
  49. return ClosestRayResultCallback::addSingleResult (rayResult, normalInWorldSpace);
  50. }
  51. protected:
  52. btCollisionObject* m_me;
  53. };
  54. class btKinematicClosestNotMeConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback
  55. {
  56. public:
  57. btKinematicClosestNotMeConvexResultCallback (btCollisionObject* me, const btVector3& up, btScalar minSlopeDot)
  58. : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))
  59. , m_me(me)
  60. , m_up(up)
  61. , m_minSlopeDot(minSlopeDot)
  62. {
  63. }
  64. virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult,bool normalInWorldSpace)
  65. {
  66. if (convexResult.m_hitCollisionObject == m_me)
  67. return btScalar(1.0);
  68. if (!convexResult.m_hitCollisionObject->hasContactResponse())
  69. return btScalar(1.0);
  70. btVector3 hitNormalWorld;
  71. if (normalInWorldSpace)
  72. {
  73. hitNormalWorld = convexResult.m_hitNormalLocal;
  74. } else
  75. {
  76. ///need to transform normal into worldspace
  77. hitNormalWorld = convexResult.m_hitCollisionObject->getWorldTransform().getBasis()*convexResult.m_hitNormalLocal;
  78. }
  79. btScalar dotUp = m_up.dot(hitNormalWorld);
  80. if (dotUp < m_minSlopeDot) {
  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, int upAxis)
  115. {
  116. m_upAxis = upAxis;
  117. m_addedMargin = 0.02;
  118. m_walkDirection.setValue(0,0,0);
  119. m_useGhostObjectSweepTest = true;
  120. m_ghostObject = ghostObject;
  121. m_stepHeight = stepHeight;
  122. m_turnAngle = btScalar(0.0);
  123. m_convexShape=convexShape;
  124. m_useWalkDirection = true; // use walk direction by default, legacy behavior
  125. m_velocityTimeInterval = 0.0;
  126. m_verticalVelocity = 0.0;
  127. m_verticalOffset = 0.0;
  128. m_gravity = 9.8 * 3 ; // 3G acceleration.
  129. m_fallSpeed = 55.0; // Terminal velocity of a sky diver in m/s.
  130. m_jumpSpeed = 10.0; // ?
  131. m_wasOnGround = false;
  132. m_wasJumping = false;
  133. m_interpolateUp = true;
  134. setMaxSlope(btRadians(45.0));
  135. m_currentStepOffset = 0;
  136. full_drop = false;
  137. bounce_fix = false;
  138. }
  139. btKinematicCharacterController::~btKinematicCharacterController ()
  140. {
  141. }
  142. btPairCachingGhostObject* btKinematicCharacterController::getGhostObject()
  143. {
  144. return m_ghostObject;
  145. }
  146. bool btKinematicCharacterController::recoverFromPenetration ( btCollisionWorld* collisionWorld)
  147. {
  148. // Here we must refresh the overlapping paircache as the penetrating movement itself or the
  149. // previous recovery iteration might have used setWorldTransform and pushed us into an object
  150. // that is not in the previous cache contents from the last timestep, as will happen if we
  151. // are pushed into a new AABB overlap. Unhandled this means the next convex sweep gets stuck.
  152. //
  153. // Do this by calling the broadphase's setAabb with the moved AABB, this will update the broadphase
  154. // paircache and the ghostobject's internal paircache at the same time. /BW
  155. btVector3 minAabb, maxAabb;
  156. m_convexShape->getAabb(m_ghostObject->getWorldTransform(), minAabb,maxAabb);
  157. collisionWorld->getBroadphase()->setAabb(m_ghostObject->getBroadphaseHandle(),
  158. minAabb,
  159. maxAabb,
  160. collisionWorld->getDispatcher());
  161. bool penetration = false;
  162. collisionWorld->getDispatcher()->dispatchAllCollisionPairs(m_ghostObject->getOverlappingPairCache(), collisionWorld->getDispatchInfo(), collisionWorld->getDispatcher());
  163. m_currentPosition = m_ghostObject->getWorldTransform().getOrigin();
  164. btScalar maxPen = btScalar(0.0);
  165. for (int i = 0; i < m_ghostObject->getOverlappingPairCache()->getNumOverlappingPairs(); i++)
  166. {
  167. m_manifoldArray.resize(0);
  168. btBroadphasePair* collisionPair = &m_ghostObject->getOverlappingPairCache()->getOverlappingPairArray()[i];
  169. btCollisionObject* obj0 = static_cast<btCollisionObject*>(collisionPair->m_pProxy0->m_clientObject);
  170. btCollisionObject* obj1 = static_cast<btCollisionObject*>(collisionPair->m_pProxy1->m_clientObject);
  171. if ((obj0 && !obj0->hasContactResponse()) || (obj1 && !obj1->hasContactResponse()))
  172. continue;
  173. if (collisionPair->m_algorithm)
  174. collisionPair->m_algorithm->getAllContactManifolds(m_manifoldArray);
  175. for (int j=0;j<m_manifoldArray.size();j++)
  176. {
  177. btPersistentManifold* manifold = m_manifoldArray[j];
  178. btScalar directionSign = manifold->getBody0() == m_ghostObject ? btScalar(-1.0) : btScalar(1.0);
  179. for (int p=0;p<manifold->getNumContacts();p++)
  180. {
  181. const btManifoldPoint&pt = manifold->getContactPoint(p);
  182. btScalar dist = pt.getDistance();
  183. if (dist < 0.0)
  184. {
  185. if (dist < maxPen)
  186. {
  187. maxPen = dist;
  188. m_touchingNormal = pt.m_normalWorldOnB * directionSign;//??
  189. }
  190. m_currentPosition += pt.m_normalWorldOnB * directionSign * dist * btScalar(0.2);
  191. penetration = true;
  192. } else {
  193. //printf("touching %f\n", dist);
  194. }
  195. }
  196. //manifold->clearManifold();
  197. }
  198. }
  199. btTransform newTrans = m_ghostObject->getWorldTransform();
  200. newTrans.setOrigin(m_currentPosition);
  201. m_ghostObject->setWorldTransform(newTrans);
  202. // printf("m_touchingNormal = %f,%f,%f\n",m_touchingNormal[0],m_touchingNormal[1],m_touchingNormal[2]);
  203. return penetration;
  204. }
  205. void btKinematicCharacterController::stepUp ( btCollisionWorld* world)
  206. {
  207. // phase 1: up
  208. btTransform start, end;
  209. m_targetPosition = m_currentPosition + getUpAxisDirections()[m_upAxis] * (m_stepHeight + (m_verticalOffset > 0.f?m_verticalOffset:0.f));
  210. start.setIdentity ();
  211. end.setIdentity ();
  212. /* FIXME: Handle penetration properly */
  213. start.setOrigin (m_currentPosition + getUpAxisDirections()[m_upAxis] * (m_convexShape->getMargin() + m_addedMargin));
  214. end.setOrigin (m_targetPosition);
  215. btKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, -getUpAxisDirections()[m_upAxis], btScalar(0.7071));
  216. callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  217. callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  218. if (m_useGhostObjectSweepTest)
  219. {
  220. m_ghostObject->convexSweepTest (m_convexShape, start, end, callback, world->getDispatchInfo().m_allowedCcdPenetration);
  221. }
  222. else
  223. {
  224. world->convexSweepTest (m_convexShape, start, end, callback);
  225. }
  226. if (callback.hasHit())
  227. {
  228. // Only modify the position if the hit was a slope and not a wall or ceiling.
  229. if(callback.m_hitNormalWorld.dot(getUpAxisDirections()[m_upAxis]) > 0.0)
  230. {
  231. // we moved up only a fraction of the step height
  232. m_currentStepOffset = m_stepHeight * callback.m_closestHitFraction;
  233. if (m_interpolateUp == true)
  234. m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  235. else
  236. m_currentPosition = m_targetPosition;
  237. }
  238. m_verticalVelocity = 0.0;
  239. m_verticalOffset = 0.0;
  240. } else {
  241. m_currentStepOffset = m_stepHeight;
  242. m_currentPosition = m_targetPosition;
  243. }
  244. }
  245. void btKinematicCharacterController::updateTargetPositionBasedOnCollision (const btVector3& hitNormal, btScalar tangentMag, btScalar normalMag)
  246. {
  247. btVector3 movementDirection = m_targetPosition - m_currentPosition;
  248. btScalar movementLength = movementDirection.length();
  249. if (movementLength>SIMD_EPSILON)
  250. {
  251. movementDirection.normalize();
  252. btVector3 reflectDir = computeReflectionDirection (movementDirection, hitNormal);
  253. reflectDir.normalize();
  254. btVector3 parallelDir, perpindicularDir;
  255. parallelDir = parallelComponent (reflectDir, hitNormal);
  256. perpindicularDir = perpindicularComponent (reflectDir, hitNormal);
  257. m_targetPosition = m_currentPosition;
  258. if (0)//tangentMag != 0.0)
  259. {
  260. btVector3 parComponent = parallelDir * btScalar (tangentMag*movementLength);
  261. // printf("parComponent=%f,%f,%f\n",parComponent[0],parComponent[1],parComponent[2]);
  262. m_targetPosition += parComponent;
  263. }
  264. if (normalMag != 0.0)
  265. {
  266. btVector3 perpComponent = perpindicularDir * btScalar (normalMag*movementLength);
  267. // printf("perpComponent=%f,%f,%f\n",perpComponent[0],perpComponent[1],perpComponent[2]);
  268. m_targetPosition += perpComponent;
  269. }
  270. } else
  271. {
  272. // printf("movementLength don't normalize a zero vector\n");
  273. }
  274. }
  275. void btKinematicCharacterController::stepForwardAndStrafe ( btCollisionWorld* collisionWorld, const btVector3& walkMove)
  276. {
  277. // printf("m_normalizedDirection=%f,%f,%f\n",
  278. // m_normalizedDirection[0],m_normalizedDirection[1],m_normalizedDirection[2]);
  279. // phase 2: forward and strafe
  280. btTransform start, end;
  281. m_targetPosition = m_currentPosition + walkMove;
  282. start.setIdentity ();
  283. end.setIdentity ();
  284. btScalar fraction = 1.0;
  285. btScalar distance2 = (m_currentPosition-m_targetPosition).length2();
  286. // printf("distance2=%f\n",distance2);
  287. if (m_touchingContact)
  288. {
  289. if (m_normalizedDirection.dot(m_touchingNormal) > btScalar(0.0))
  290. {
  291. //interferes with step movement
  292. //updateTargetPositionBasedOnCollision (m_touchingNormal);
  293. }
  294. }
  295. int maxIter = 10;
  296. while (fraction > btScalar(0.01) && maxIter-- > 0)
  297. {
  298. start.setOrigin (m_currentPosition);
  299. end.setOrigin (m_targetPosition);
  300. btVector3 sweepDirNegative(m_currentPosition - m_targetPosition);
  301. btKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, sweepDirNegative, btScalar(0.0));
  302. callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  303. callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  304. btScalar margin = m_convexShape->getMargin();
  305. m_convexShape->setMargin(margin + m_addedMargin);
  306. if (m_useGhostObjectSweepTest)
  307. {
  308. m_ghostObject->convexSweepTest (m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  309. } else
  310. {
  311. collisionWorld->convexSweepTest (m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  312. }
  313. m_convexShape->setMargin(margin);
  314. fraction -= callback.m_closestHitFraction;
  315. if (callback.hasHit())
  316. {
  317. // we moved only a fraction
  318. btScalar hitDistance;
  319. hitDistance = (callback.m_hitPointWorld - m_currentPosition).length();
  320. // m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  321. updateTargetPositionBasedOnCollision (callback.m_hitNormalWorld);
  322. btVector3 currentDir = m_targetPosition - m_currentPosition;
  323. distance2 = currentDir.length2();
  324. if (distance2 > SIMD_EPSILON)
  325. {
  326. currentDir.normalize();
  327. /* See Quake2: "If velocity is against original velocity, stop ead to avoid tiny oscilations in sloping corners." */
  328. if (currentDir.dot(m_normalizedDirection) <= btScalar(0.0))
  329. {
  330. break;
  331. }
  332. } else
  333. {
  334. // printf("currentDir: don't normalize a zero vector\n");
  335. break;
  336. }
  337. } else {
  338. // we moved whole way
  339. m_currentPosition = m_targetPosition;
  340. }
  341. // if (callback.m_closestHitFraction == 0.f)
  342. // break;
  343. }
  344. }
  345. void btKinematicCharacterController::stepDown ( btCollisionWorld* collisionWorld, btScalar dt)
  346. {
  347. btTransform start, end, end_double;
  348. bool runonce = false;
  349. // phase 3: down
  350. /*btScalar additionalDownStep = (m_wasOnGround && !onGround()) ? m_stepHeight : 0.0;
  351. btVector3 step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + additionalDownStep);
  352. btScalar downVelocity = (additionalDownStep == 0.0 && m_verticalVelocity<0.0?-m_verticalVelocity:0.0) * dt;
  353. btVector3 gravity_drop = getUpAxisDirections()[m_upAxis] * downVelocity;
  354. m_targetPosition -= (step_drop + gravity_drop);*/
  355. btVector3 orig_position = m_targetPosition;
  356. btScalar downVelocity = (m_verticalVelocity<0.f?-m_verticalVelocity:0.f) * dt;
  357. if(downVelocity > 0.0 && downVelocity > m_fallSpeed
  358. && (m_wasOnGround || !m_wasJumping))
  359. downVelocity = m_fallSpeed;
  360. btVector3 step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + downVelocity);
  361. m_targetPosition -= step_drop;
  362. btKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, getUpAxisDirections()[m_upAxis], m_maxSlopeCosine);
  363. callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  364. callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  365. btKinematicClosestNotMeConvexResultCallback callback2 (m_ghostObject, getUpAxisDirections()[m_upAxis], m_maxSlopeCosine);
  366. callback2.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  367. callback2.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  368. while (1)
  369. {
  370. start.setIdentity ();
  371. end.setIdentity ();
  372. end_double.setIdentity ();
  373. start.setOrigin (m_currentPosition);
  374. end.setOrigin (m_targetPosition);
  375. //set double test for 2x the step drop, to check for a large drop vs small drop
  376. end_double.setOrigin (m_targetPosition - step_drop);
  377. if (m_useGhostObjectSweepTest)
  378. {
  379. m_ghostObject->convexSweepTest (m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  380. if (!callback.hasHit())
  381. {
  382. //test a double fall height, to see if the character should interpolate it's fall (full) or not (partial)
  383. m_ghostObject->convexSweepTest (m_convexShape, start, end_double, callback2, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  384. }
  385. } else
  386. {
  387. collisionWorld->convexSweepTest (m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  388. if (!callback.hasHit())
  389. {
  390. //test a double fall height, to see if the character should interpolate it's fall (large) or not (small)
  391. collisionWorld->convexSweepTest (m_convexShape, start, end_double, callback2, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  392. }
  393. }
  394. btScalar downVelocity2 = (m_verticalVelocity<0.f?-m_verticalVelocity:0.f) * dt;
  395. bool has_hit = false;
  396. if (bounce_fix == true)
  397. has_hit = callback.hasHit() || callback2.hasHit();
  398. else
  399. has_hit = callback2.hasHit();
  400. if(downVelocity2 > 0.0 && downVelocity2 < m_stepHeight && has_hit == true && runonce == false
  401. && (m_wasOnGround || !m_wasJumping))
  402. {
  403. //redo the velocity calculation when falling a small amount, for fast stairs motion
  404. //for larger falls, use the smoother/slower interpolated movement by not touching the target position
  405. m_targetPosition = orig_position;
  406. downVelocity = m_stepHeight;
  407. btVector3 step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + downVelocity);
  408. m_targetPosition -= step_drop;
  409. runonce = true;
  410. continue; //re-run previous tests
  411. }
  412. break;
  413. }
  414. if (callback.hasHit() || runonce == true)
  415. {
  416. // we dropped a fraction of the height -> hit floor
  417. btScalar fraction = (m_currentPosition.getY() - callback.m_hitPointWorld.getY()) / 2;
  418. //printf("hitpoint: %g - pos %g\n", callback.m_hitPointWorld.getY(), m_currentPosition.getY());
  419. if (bounce_fix == true)
  420. {
  421. if (full_drop == true)
  422. m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  423. else
  424. //due to errors in the closestHitFraction variable when used with large polygons, calculate the hit fraction manually
  425. m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, fraction);
  426. }
  427. else
  428. m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  429. full_drop = false;
  430. m_verticalVelocity = 0.0;
  431. m_verticalOffset = 0.0;
  432. m_wasJumping = false;
  433. } else {
  434. // we dropped the full height
  435. full_drop = true;
  436. if (bounce_fix == true)
  437. {
  438. downVelocity = (m_verticalVelocity<0.f?-m_verticalVelocity:0.f) * dt;
  439. if (downVelocity > m_fallSpeed && (m_wasOnGround || !m_wasJumping))
  440. {
  441. m_targetPosition += step_drop; //undo previous target change
  442. downVelocity = m_fallSpeed;
  443. step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + downVelocity);
  444. m_targetPosition -= step_drop;
  445. }
  446. }
  447. //printf("full drop - %g, %g\n", m_currentPosition.getY(), m_targetPosition.getY());
  448. m_currentPosition = m_targetPosition;
  449. }
  450. }
  451. void btKinematicCharacterController::setWalkDirection
  452. (
  453. const btVector3& walkDirection
  454. )
  455. {
  456. m_useWalkDirection = true;
  457. m_walkDirection = walkDirection;
  458. m_normalizedDirection = getNormalizedVector(m_walkDirection);
  459. }
  460. void btKinematicCharacterController::setVelocityForTimeInterval
  461. (
  462. const btVector3& velocity,
  463. btScalar timeInterval
  464. )
  465. {
  466. // printf("setVelocity!\n");
  467. // printf(" interval: %f\n", timeInterval);
  468. // printf(" velocity: (%f, %f, %f)\n",
  469. // velocity.x(), velocity.y(), velocity.z());
  470. m_useWalkDirection = false;
  471. m_walkDirection = velocity;
  472. m_normalizedDirection = getNormalizedVector(m_walkDirection);
  473. m_velocityTimeInterval += timeInterval;
  474. }
  475. void btKinematicCharacterController::reset ( btCollisionWorld* collisionWorld )
  476. {
  477. m_verticalVelocity = 0.0;
  478. m_verticalOffset = 0.0;
  479. m_wasOnGround = false;
  480. m_wasJumping = false;
  481. m_walkDirection.setValue(0,0,0);
  482. m_velocityTimeInterval = 0.0;
  483. //clear pair cache
  484. btHashedOverlappingPairCache *cache = m_ghostObject->getOverlappingPairCache();
  485. while (cache->getOverlappingPairArray().size() > 0)
  486. {
  487. cache->removeOverlappingPair(cache->getOverlappingPairArray()[0].m_pProxy0, cache->getOverlappingPairArray()[0].m_pProxy1, collisionWorld->getDispatcher());
  488. }
  489. }
  490. void btKinematicCharacterController::warp (const btVector3& origin)
  491. {
  492. btTransform xform;
  493. xform.setIdentity();
  494. xform.setOrigin (origin);
  495. m_ghostObject->setWorldTransform (xform);
  496. }
  497. void btKinematicCharacterController::preStep ( btCollisionWorld* collisionWorld)
  498. {
  499. int numPenetrationLoops = 0;
  500. m_touchingContact = false;
  501. while (recoverFromPenetration (collisionWorld))
  502. {
  503. numPenetrationLoops++;
  504. m_touchingContact = true;
  505. if (numPenetrationLoops > 4)
  506. {
  507. //printf("character could not recover from penetration = %d\n", numPenetrationLoops);
  508. break;
  509. }
  510. }
  511. m_currentPosition = m_ghostObject->getWorldTransform().getOrigin();
  512. m_targetPosition = m_currentPosition;
  513. // printf("m_targetPosition=%f,%f,%f\n",m_targetPosition[0],m_targetPosition[1],m_targetPosition[2]);
  514. }
  515. #include <stdio.h>
  516. void btKinematicCharacterController::playerStep ( btCollisionWorld* collisionWorld, btScalar dt)
  517. {
  518. // printf("playerStep(): ");
  519. // printf(" dt = %f", dt);
  520. // quick check...
  521. if (!m_useWalkDirection && m_velocityTimeInterval <= 0.0) {
  522. // printf("\n");
  523. return; // no motion
  524. }
  525. m_wasOnGround = onGround();
  526. // Update fall velocity.
  527. m_verticalVelocity -= m_gravity * dt;
  528. if(m_verticalVelocity > 0.0 && m_verticalVelocity > m_jumpSpeed)
  529. {
  530. m_verticalVelocity = m_jumpSpeed;
  531. }
  532. if(m_verticalVelocity < 0.0 && btFabs(m_verticalVelocity) > btFabs(m_fallSpeed))
  533. {
  534. m_verticalVelocity = -btFabs(m_fallSpeed);
  535. }
  536. m_verticalOffset = m_verticalVelocity * dt;
  537. btTransform xform;
  538. xform = m_ghostObject->getWorldTransform ();
  539. // printf("walkDirection(%f,%f,%f)\n",walkDirection[0],walkDirection[1],walkDirection[2]);
  540. // printf("walkSpeed=%f\n",walkSpeed);
  541. stepUp (collisionWorld);
  542. if (m_useWalkDirection) {
  543. stepForwardAndStrafe (collisionWorld, m_walkDirection);
  544. } else {
  545. //printf(" time: %f", m_velocityTimeInterval);
  546. // still have some time left for moving!
  547. btScalar dtMoving =
  548. (dt < m_velocityTimeInterval) ? dt : m_velocityTimeInterval;
  549. m_velocityTimeInterval -= dt;
  550. // how far will we move while we are moving?
  551. btVector3 move = m_walkDirection * dtMoving;
  552. //printf(" dtMoving: %f", dtMoving);
  553. // okay, step
  554. stepForwardAndStrafe(collisionWorld, move);
  555. }
  556. stepDown (collisionWorld, dt);
  557. // printf("\n");
  558. xform.setOrigin (m_currentPosition);
  559. m_ghostObject->setWorldTransform (xform);
  560. }
  561. void btKinematicCharacterController::setFallSpeed (btScalar fallSpeed)
  562. {
  563. m_fallSpeed = fallSpeed;
  564. }
  565. void btKinematicCharacterController::setJumpSpeed (btScalar jumpSpeed)
  566. {
  567. m_jumpSpeed = jumpSpeed;
  568. }
  569. void btKinematicCharacterController::setMaxJumpHeight (btScalar maxJumpHeight)
  570. {
  571. m_maxJumpHeight = maxJumpHeight;
  572. }
  573. bool btKinematicCharacterController::canJump () const
  574. {
  575. return onGround();
  576. }
  577. void btKinematicCharacterController::jump ()
  578. {
  579. if (!canJump())
  580. return;
  581. m_verticalVelocity = m_jumpSpeed;
  582. m_wasJumping = true;
  583. #if 0
  584. currently no jumping.
  585. btTransform xform;
  586. m_rigidBody->getMotionState()->getWorldTransform (xform);
  587. btVector3 up = xform.getBasis()[1];
  588. up.normalize ();
  589. btScalar magnitude = (btScalar(1.0)/m_rigidBody->getInvMass()) * btScalar(8.0);
  590. m_rigidBody->applyCentralImpulse (up * magnitude);
  591. #endif
  592. }
  593. void btKinematicCharacterController::setGravity(btScalar gravity)
  594. {
  595. m_gravity = gravity;
  596. }
  597. btScalar btKinematicCharacterController::getGravity() const
  598. {
  599. return m_gravity;
  600. }
  601. void btKinematicCharacterController::setMaxSlope(btScalar slopeRadians)
  602. {
  603. m_maxSlopeRadians = slopeRadians;
  604. m_maxSlopeCosine = btCos(slopeRadians);
  605. }
  606. btScalar btKinematicCharacterController::getMaxSlope() const
  607. {
  608. return m_maxSlopeRadians;
  609. }
  610. bool btKinematicCharacterController::onGround () const
  611. {
  612. return m_verticalVelocity == 0.0 && m_verticalOffset == 0.0;
  613. }
  614. btVector3* btKinematicCharacterController::getUpAxisDirections()
  615. {
  616. 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) };
  617. return sUpAxisDirection;
  618. }
  619. void btKinematicCharacterController::debugDraw(btIDebugDraw* debugDrawer)
  620. {
  621. }
  622. void btKinematicCharacterController::setUpInterpolate(bool value)
  623. {
  624. m_interpolateUp = value;
  625. }