PhysicsPlayerController.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. // Copyright (C) 2009-2016, Panagiotis Christopoulos Charitos.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <anki/physics/PhysicsPlayerController.h>
  6. #include <anki/physics/PhysicsWorld.h>
  7. namespace anki
  8. {
  9. //==============================================================================
  10. // Static =
  11. //==============================================================================
  12. //==============================================================================
  13. class CustomControllerConvexRayFilter
  14. {
  15. public:
  16. const NewtonBody* m_me = nullptr;
  17. Vec4 m_hitContact = Vec4(0.0);
  18. Vec4 m_hitNormal = Vec4(0.0);
  19. const NewtonBody* m_hitBody = nullptr;
  20. const NewtonCollision* m_shapeHit = nullptr;
  21. U32 m_collisionId = 0;
  22. F32 m_intersectParam = 1.2;
  23. static F32 filterCallback(const NewtonBody* const body,
  24. const NewtonCollision* const shapeHit,
  25. const dFloat* const hitContact,
  26. const dFloat* const hitNormal,
  27. dLong collisionId,
  28. void* const userData,
  29. dFloat intersectParam)
  30. {
  31. CustomControllerConvexRayFilter* filter =
  32. static_cast<CustomControllerConvexRayFilter*>(userData);
  33. ANKI_ASSERT(body != filter->m_me);
  34. if(intersectParam < filter->m_intersectParam)
  35. {
  36. filter->m_hitBody = body;
  37. filter->m_shapeHit = shapeHit;
  38. filter->m_collisionId = collisionId;
  39. filter->m_intersectParam = intersectParam;
  40. filter->m_hitContact =
  41. Vec4(hitContact[0], hitContact[1], hitContact[2], 0.0);
  42. filter->m_hitNormal =
  43. Vec4(hitNormal[0], hitNormal[1], hitNormal[2], 0.0);
  44. }
  45. return intersectParam;
  46. }
  47. static unsigned prefilterCallback(const NewtonBody* const body,
  48. const NewtonCollision* const myCollision,
  49. void* const userData)
  50. {
  51. CustomControllerConvexRayFilter* filter =
  52. static_cast<CustomControllerConvexRayFilter*>(userData);
  53. return (body != filter->m_me) ? 1 : 0;
  54. }
  55. };
  56. //==============================================================================
  57. struct CustomControllerConvexCastPreFilter
  58. {
  59. const NewtonBody* m_me = nullptr;
  60. CustomControllerConvexCastPreFilter(NewtonBody* body)
  61. : m_me(body)
  62. {
  63. ANKI_ASSERT(m_me != nullptr);
  64. }
  65. static unsigned prefilterCallback(const NewtonBody* const body,
  66. const NewtonCollision* const myCollision,
  67. void* const userData)
  68. {
  69. CustomControllerConvexCastPreFilter* filter =
  70. static_cast<CustomControllerConvexCastPreFilter*>(userData);
  71. return (body != filter->m_me) ? 1 : 0;
  72. }
  73. };
  74. //==============================================================================
  75. static Vec4 calcAverageOmega(Quat q0, const Quat& q1, F32 invdt)
  76. {
  77. if(q0.dot(q1) < 0.0)
  78. {
  79. q0 *= -1.0f;
  80. }
  81. Quat dq(q0.getConjugated().combineRotations(q1));
  82. Vec4 omegaDir(dq.x(), dq.y(), dq.z(), 0.0);
  83. F32 dirMag2 = omegaDir.getLengthSquared();
  84. if(dirMag2 < 1.0e-5 * 1.0e-5)
  85. {
  86. return Vec4(0.0);
  87. }
  88. F32 dirMagInv = 1.0 / sqrt(dirMag2);
  89. F32 dirMag = dirMag2 * dirMagInv;
  90. F32 omegaMag = 2.0 * atan2(dirMag, dq.w()) * invdt;
  91. return omegaDir * (dirMagInv * omegaMag);
  92. }
  93. //==============================================================================
  94. static Quat integrateOmega(const Quat& rot, const Vec4& omega, F32 dt)
  95. {
  96. ANKI_ASSERT(omega.w() == 0.0);
  97. Quat rotation(rot);
  98. F32 omegaMag2 = omega.dot(omega);
  99. F32 errAngle2 = toRad(0.0125) * toRad(0.0125);
  100. if(omegaMag2 > errAngle2)
  101. {
  102. F32 invOmegaMag = 1.0 / sqrt(omegaMag2);
  103. Vec4 omegaAxis(omega * invOmegaMag);
  104. F32 omegaAngle = invOmegaMag * omegaMag2 * dt;
  105. Quat deltaRotation(Axisang(omegaAngle, omegaAxis.xyz()));
  106. rotation = rotation.combineRotations(deltaRotation);
  107. rotation = rotation * (1.0 / sqrt(rotation.dot(rotation)));
  108. }
  109. return rotation;
  110. }
  111. //==============================================================================
  112. // PhysicsPlayerController =
  113. //==============================================================================
  114. //==============================================================================
  115. PhysicsPlayerController::~PhysicsPlayerController()
  116. {
  117. NewtonDestroyCollision(m_upperBodyShape);
  118. NewtonDestroyCollision(m_supportShape);
  119. NewtonDestroyCollision(m_castingShape);
  120. NewtonDestroyBody(m_body);
  121. }
  122. //==============================================================================
  123. Error PhysicsPlayerController::create(
  124. const PhysicsPlayerControllerInitInfo& init)
  125. {
  126. NewtonWorld* world = m_world->_getNewtonWorld();
  127. m_restrainingDistance = MIN_RESTRAINING_DISTANCE;
  128. m_innerRadius = init.m_innerRadius;
  129. m_outerRadius = init.m_outerRadius;
  130. m_height = init.m_height;
  131. m_stepHeight = init.m_stepHeight;
  132. m_isJumping = false;
  133. m_gravity = m_world->getGravity();
  134. setClimbSlope(toRad(45.0));
  135. Mat4 localAxis(Mat4::getIdentity());
  136. m_upDir = localAxis.getColumn(1);
  137. m_frontDir = localAxis.getColumn(2);
  138. m_groundPlane = Vec4(0.0);
  139. m_groundVelocity = Vec4(0.0);
  140. const U steps = 12;
  141. Array2d<Vec4, 2, steps> convexPoints;
  142. // Create an inner thin cylinder
  143. F32 shapeHeight = m_height;
  144. ANKI_ASSERT(shapeHeight > 0.0);
  145. Vec4 p0(m_innerRadius, 0.0, 0.0, 0.0);
  146. Vec4 p1(m_innerRadius, shapeHeight, 0.0, 0.0);
  147. for(U i = 0; i < steps; ++i)
  148. {
  149. Mat3 rotm3(Axisang(toRad(320.0) / steps * i, m_upDir.xyz()));
  150. Mat4 rotation(rotm3);
  151. convexPoints[0][i] = localAxis * (rotation * p0);
  152. convexPoints[1][i] = localAxis * (rotation * p1);
  153. }
  154. NewtonCollision* supportShape = NewtonCreateConvexHull(world,
  155. steps * 2,
  156. &convexPoints[0][0][0],
  157. sizeof(Vec4),
  158. 0.0,
  159. 0,
  160. nullptr);
  161. if(supportShape == nullptr)
  162. {
  163. ANKI_LOGE("NewtonCreateConvexHull() failed");
  164. return ErrorCode::FUNCTION_FAILED;
  165. }
  166. // Create the outer thick cylinder
  167. Mat4 outerShapeRot(Mat3(Axisang(getPi<F32>() / 2.0, Vec3(0.0, 0.0, 1.0))));
  168. Mat4 outerShapeMatrix = localAxis * outerShapeRot;
  169. F32 capsuleHeight = m_height - m_stepHeight;
  170. ANKI_ASSERT(capsuleHeight > 0.0);
  171. m_sphereCastOrigin = capsuleHeight * 0.5 + m_stepHeight;
  172. Vec4 transl(m_upDir * m_sphereCastOrigin);
  173. transl.w() = 1.0;
  174. outerShapeMatrix.setTranslationPart(transl);
  175. outerShapeMatrix.transpose();
  176. NewtonCollision* bodyCapsule =
  177. NewtonCreateCapsule(world, 0.25, 0.5, 0, &outerShapeMatrix[0]);
  178. if(bodyCapsule == nullptr)
  179. {
  180. ANKI_LOGE("NewtonCreateCapsule() failed");
  181. return ErrorCode::FUNCTION_FAILED;
  182. }
  183. NewtonCollisionSetScale(
  184. bodyCapsule, capsuleHeight, m_outerRadius * 4.0, m_outerRadius * 4.0);
  185. // Compound collision player controller
  186. NewtonCollision* playerShape = NewtonCreateCompoundCollision(world, 0);
  187. if(playerShape == nullptr)
  188. {
  189. ANKI_LOGE("NewtonCreateCompoundCollision() failed");
  190. return ErrorCode::FUNCTION_FAILED;
  191. }
  192. NewtonCompoundCollisionBeginAddRemove(playerShape);
  193. NewtonCompoundCollisionAddSubCollision(playerShape, supportShape);
  194. NewtonCompoundCollisionAddSubCollision(playerShape, bodyCapsule);
  195. NewtonCompoundCollisionEndAddRemove(playerShape);
  196. // Create the kinematic body
  197. Mat4 locationMatrix(Mat4::getIdentity());
  198. locationMatrix.setTranslationPart(init.m_position.xyz1());
  199. m_body = NewtonCreateKinematicBody(
  200. world, playerShape, &toNewton(locationMatrix)[0]);
  201. if(m_body == nullptr)
  202. {
  203. ANKI_LOGE("NewtonCreateKinematicBody() failed");
  204. return ErrorCode::FUNCTION_FAILED;
  205. }
  206. NewtonBodySetUserData(m_body, this);
  207. NewtonBodySetTransformCallback(m_body, onTransformCallback);
  208. NewtonBodySetMaterialGroupID(
  209. m_body, NewtonMaterialGetDefaultGroupID(m_world->_getNewtonWorld()));
  210. // Players must have weight, otherwise they are infinitely strong when
  211. // they collide
  212. NewtonCollision* shape = NewtonBodyGetCollision(m_body);
  213. if(shape == nullptr)
  214. {
  215. ANKI_LOGE("NewtonBodyGetCollision() failed");
  216. return ErrorCode::FUNCTION_FAILED;
  217. }
  218. NewtonBodySetMassProperties(m_body, init.m_mass, shape);
  219. NewtonBodySetCollidable(m_body, true);
  220. // Create yet another collision shape
  221. F32 castHeight = capsuleHeight * 0.4;
  222. F32 castRadius = min(m_innerRadius * 0.5, 0.05);
  223. Vec4 q0(castRadius, 0.0, 0.0, 0.0);
  224. Vec4 q1(castRadius, castHeight, 0.0, 0.0);
  225. for(U i = 0; i < steps; ++i)
  226. {
  227. Mat3 rotm3(Axisang(toRad(320.0) / steps * i, m_upDir.xyz()));
  228. Mat4 rotation(rotm3);
  229. convexPoints[0][i] = localAxis * (rotation * q0);
  230. convexPoints[1][i] = localAxis * (rotation * q1);
  231. }
  232. m_castingShape = NewtonCreateConvexHull(world,
  233. steps * 2,
  234. &convexPoints[0][0][0],
  235. sizeof(Vec4),
  236. 0.0,
  237. 0,
  238. nullptr);
  239. if(m_castingShape == nullptr)
  240. {
  241. ANKI_LOGE("NewtonCreateConvexHull() failed");
  242. return ErrorCode::FUNCTION_FAILED;
  243. }
  244. // Finish
  245. m_supportShape = NewtonCompoundCollisionGetCollisionFromNode(
  246. shape, NewtonCompoundCollisionGetNodeByIndex(shape, 0));
  247. m_upperBodyShape = NewtonCompoundCollisionGetCollisionFromNode(
  248. shape, NewtonCompoundCollisionGetNodeByIndex(shape, 1));
  249. NewtonDestroyCollision(bodyCapsule);
  250. NewtonDestroyCollision(supportShape);
  251. NewtonDestroyCollision(playerShape);
  252. return ErrorCode::NONE;
  253. }
  254. //==============================================================================
  255. Vec4 PhysicsPlayerController::calculateDesiredOmega(
  256. const Vec4& frontDir, F32 dt) const
  257. {
  258. Quat playerRotation;
  259. NewtonBodyGetRotation(m_body, &playerRotation[0]);
  260. playerRotation = toAnki(playerRotation);
  261. Quat targetRotation;
  262. targetRotation.setFrom2Vec3(m_frontDir.xyz(), frontDir.xyz());
  263. return calcAverageOmega(playerRotation, targetRotation, 0.5 / dt);
  264. }
  265. //==============================================================================
  266. Vec4 PhysicsPlayerController::calculateDesiredVelocity(F32 forwardSpeed,
  267. F32 strafeSpeed,
  268. F32 verticalSpeed,
  269. const Vec4& gravity,
  270. F32 dt) const
  271. {
  272. Mat4 matrix;
  273. NewtonBodyGetMatrix(m_body, &matrix[0]);
  274. matrix = toAnki(matrix);
  275. matrix.setTranslationPart(Vec4(0.0, 0.0, 0.0, 1.0));
  276. Vec4 updir(matrix * m_upDir);
  277. Vec4 frontDir(matrix * m_frontDir);
  278. Vec4 rightDir(frontDir.cross(updir));
  279. Vec4 veloc(0.0);
  280. Vec4 groundPlaneDir = m_groundPlane.xyz0();
  281. if((verticalSpeed <= 0.0) && groundPlaneDir.getLengthSquared() > 0.0)
  282. {
  283. // Plane is supported by a ground plane, apply the player input velocity
  284. if(groundPlaneDir.dot(updir) >= m_maxSlope)
  285. {
  286. // Player is in a legal slope, he is in full control of his movement
  287. Vec4 bodyVeloc(0.0);
  288. NewtonBodyGetVelocity(m_body, &bodyVeloc[0]);
  289. veloc = updir * bodyVeloc.dot(updir) + gravity * dt
  290. + frontDir * forwardSpeed + rightDir * strafeSpeed
  291. + updir * verticalSpeed;
  292. veloc += m_groundVelocity - updir * updir.dot(m_groundVelocity);
  293. F32 speedLimitMag2 = forwardSpeed * forwardSpeed
  294. + strafeSpeed * strafeSpeed + verticalSpeed * verticalSpeed
  295. + m_groundVelocity.dot(m_groundVelocity) + 0.1;
  296. F32 speedMag2 = veloc.getLengthSquared();
  297. if(speedMag2 > speedLimitMag2)
  298. {
  299. veloc = veloc * sqrt(speedLimitMag2 / speedMag2);
  300. }
  301. F32 normalVeloc = groundPlaneDir.dot(veloc - m_groundVelocity);
  302. if(normalVeloc < 0.0)
  303. {
  304. veloc -= groundPlaneDir * normalVeloc;
  305. }
  306. }
  307. else
  308. {
  309. // Player is in an illegal ramp, he slides down hill an loses
  310. // control of his movement
  311. NewtonBodyGetVelocity(m_body, &veloc[0]);
  312. veloc += updir * verticalSpeed;
  313. veloc += gravity * dt;
  314. F32 normalVeloc = groundPlaneDir.dot(veloc - m_groundVelocity);
  315. if(normalVeloc < 0.0)
  316. {
  317. veloc -= groundPlaneDir * normalVeloc;
  318. }
  319. }
  320. }
  321. else
  322. {
  323. // Player is on free fall, only apply the gravity
  324. NewtonBodyGetVelocity(m_body, &veloc[0]);
  325. veloc += updir * verticalSpeed;
  326. veloc += gravity * dt;
  327. }
  328. return veloc;
  329. }
  330. //==============================================================================
  331. void PhysicsPlayerController::calculateVelocity(F32 dt)
  332. {
  333. Vec4 omega(calculateDesiredOmega(m_forwardDir, dt));
  334. Vec4 veloc(calculateDesiredVelocity(
  335. m_forwardSpeed, m_strafeSpeed, m_jumpSpeed, m_gravity, dt));
  336. NewtonBodySetOmega(m_body, &omega[0]);
  337. NewtonBodySetVelocity(m_body, &veloc[0]);
  338. if(m_jumpSpeed > 0.0)
  339. {
  340. m_isJumping = true;
  341. }
  342. }
  343. //==============================================================================
  344. F32 PhysicsPlayerController::calculateContactKinematics(
  345. const Vec4& veloc, const NewtonWorldConvexCastReturnInfo* contactInfo) const
  346. {
  347. Vec4 contactVeloc(0.0);
  348. if(contactInfo->m_hitBody)
  349. {
  350. NewtonBodyGetPointVelocity(
  351. contactInfo->m_hitBody, contactInfo->m_point, &contactVeloc[0]);
  352. }
  353. const F32 restitution = 0.0;
  354. Vec4 normal(contactInfo->m_normal[0],
  355. contactInfo->m_normal[1],
  356. contactInfo->m_normal[2],
  357. 0.0);
  358. F32 reboundVelocMag =
  359. -((veloc - contactVeloc).dot(normal)) * (1.0 + restitution);
  360. return max(reboundVelocMag, 0.0f);
  361. }
  362. //==============================================================================
  363. void PhysicsPlayerController::updateGroundPlane(
  364. Mat4& matrix, const Mat4& castMatrix, const Vec4& dst, int threadIndex)
  365. {
  366. NewtonWorld* world = m_world->_getNewtonWorld();
  367. CustomControllerConvexRayFilter filter;
  368. filter.m_me = m_body;
  369. NewtonWorldConvexRayCast(world,
  370. m_castingShape,
  371. &toNewton(castMatrix)[0],
  372. reinterpret_cast<const F32*>(&dst),
  373. CustomControllerConvexRayFilter::filterCallback,
  374. &filter,
  375. CustomControllerConvexRayFilter::prefilterCallback,
  376. threadIndex);
  377. m_groundPlane = Vec4(0.0);
  378. m_groundVelocity = Vec4(0.0);
  379. if(filter.m_hitBody)
  380. {
  381. m_isJumping = false;
  382. Vec4 castMatrixTransl = castMatrix.getTranslationPart().xyz0();
  383. Vec4 supportPoint(castMatrixTransl
  384. + (dst - castMatrixTransl) * filter.m_intersectParam);
  385. m_groundPlane = filter.m_hitNormal;
  386. m_groundPlane.w() = -supportPoint.dot(filter.m_hitNormal);
  387. NewtonBodyGetPointVelocity(
  388. filter.m_hitBody, &supportPoint[0], &m_groundVelocity[0]);
  389. matrix.setTranslationPart(supportPoint.xyz1());
  390. }
  391. }
  392. //==============================================================================
  393. void PhysicsPlayerController::postUpdate(F32 dt, int threadIndex)
  394. {
  395. Mat4 matrix;
  396. Quat bodyRotation;
  397. Vec4 veloc(0.0);
  398. Vec4 omega(0.0);
  399. NewtonWorld* world = m_world->_getNewtonWorld();
  400. calculateVelocity(dt);
  401. // Get the body motion state
  402. NewtonBodyGetMatrix(m_body, &matrix[0]);
  403. matrix = toAnki(matrix);
  404. NewtonBodyGetVelocity(m_body, &veloc[0]);
  405. NewtonBodyGetOmega(m_body, &omega[0]);
  406. // Integrate body angular velocity
  407. NewtonBodyGetRotation(m_body, &bodyRotation[0]);
  408. bodyRotation = toAnki(bodyRotation);
  409. bodyRotation = integrateOmega(bodyRotation, omega, dt);
  410. matrix.setRotationPart(Mat3(bodyRotation));
  411. // Integrate linear velocity
  412. F32 normalizedTimeLeft = 1.0;
  413. F32 step = dt * veloc.getLength();
  414. F32 descreteTimeStep = dt * (1.0 / DESCRETE_MOTION_STEPS);
  415. U prevContactCount = 0;
  416. CustomControllerConvexCastPreFilter castFilterData(m_body);
  417. Array<NewtonWorldConvexCastReturnInfo, MAX_CONTACTS> prevInfo;
  418. Vec4 updir(matrix.getRotationPart() * m_upDir.xyz(), 0.0);
  419. Vec4 scale(0.0);
  420. NewtonCollisionGetScale(
  421. m_upperBodyShape, &scale.x(), &scale.y(), &scale.z());
  422. F32 radio = (m_outerRadius + m_restrainingDistance) * 4.0;
  423. NewtonCollisionSetScale(
  424. m_upperBodyShape, m_height - m_stepHeight, radio, radio);
  425. NewtonWorldConvexCastReturnInfo upConstraint;
  426. memset(&upConstraint, 0, sizeof(upConstraint));
  427. upConstraint.m_normal[0] = m_upDir.x();
  428. upConstraint.m_normal[1] = m_upDir.y();
  429. upConstraint.m_normal[2] = m_upDir.z();
  430. upConstraint.m_normal[3] = m_upDir.w();
  431. for(U j = 0; (j < MAX_INTERGRATION_STEPS) && (normalizedTimeLeft > 1.0e-5f);
  432. ++j)
  433. {
  434. if((veloc.getLengthSquared()) < 1.0e-6)
  435. {
  436. break;
  437. }
  438. F32 timetoImpact;
  439. Array<NewtonWorldConvexCastReturnInfo, MAX_CONTACTS> info;
  440. Vec4 destPosit(matrix.getTranslationPart().xyz0() + veloc * dt);
  441. U contactCount = NewtonWorldConvexCast(world,
  442. &matrix.getTransposed()[0],
  443. &destPosit[0],
  444. m_upperBodyShape,
  445. &timetoImpact,
  446. &castFilterData,
  447. CustomControllerConvexCastPreFilter::prefilterCallback,
  448. &info[0],
  449. info.getSize(),
  450. threadIndex);
  451. if(contactCount > 0)
  452. {
  453. matrix.setTranslationPart(
  454. matrix.getTranslationPart() + veloc * (timetoImpact * dt));
  455. if(timetoImpact > 0.0)
  456. {
  457. Vec4 tmp = matrix.getTranslationPart()
  458. - veloc * (CONTACT_SKIN_THICKNESS / veloc.getLength());
  459. matrix.setTranslationPart(tmp.xyz1());
  460. }
  461. normalizedTimeLeft -= timetoImpact;
  462. Array<F32, MAX_CONTACTS * 2> speed;
  463. Array<F32, MAX_CONTACTS * 2> bounceSpeed;
  464. Array<Vec4, MAX_CONTACTS * 2> bounceNormal;
  465. for(U i = 1; i < contactCount; ++i)
  466. {
  467. Vec4 n0(info[i - 1].m_normal);
  468. for(U j = 0; j < i; ++j)
  469. {
  470. Vec4 n1(info[j].m_normal);
  471. if((n0.dot(n1)) > 0.9999)
  472. {
  473. info[i] = info[contactCount - 1];
  474. --i;
  475. --contactCount;
  476. break;
  477. }
  478. }
  479. }
  480. U count = 0;
  481. if(!m_isJumping)
  482. {
  483. Vec4 matTls = matrix.getTranslationPart();
  484. upConstraint.m_point[0] = matTls.x();
  485. upConstraint.m_point[1] = matTls.y();
  486. upConstraint.m_point[2] = matTls.z();
  487. upConstraint.m_point[3] = matTls.w();
  488. speed[count] = 0.0;
  489. bounceNormal[count] = Vec4(upConstraint.m_normal);
  490. bounceSpeed[count] =
  491. calculateContactKinematics(veloc, &upConstraint);
  492. ++count;
  493. }
  494. for(U i = 0; i < contactCount; ++i)
  495. {
  496. speed[count] = 0.0;
  497. bounceNormal[count] = Vec4(info[i].m_normal);
  498. bounceSpeed[count] =
  499. calculateContactKinematics(veloc, &info[i]);
  500. ++count;
  501. }
  502. for(U i = 0; i < prevContactCount; ++i)
  503. {
  504. speed[count] = 0.0;
  505. bounceNormal[count] = Vec4(prevInfo[i].m_normal);
  506. bounceSpeed[count] =
  507. calculateContactKinematics(veloc, &prevInfo[i]);
  508. ++count;
  509. }
  510. F32 residual = 10.0;
  511. Vec4 auxBounceVeloc(0.0);
  512. for(U i = 0; (i < MAX_SOLVER_ITERATIONS) && (residual > 1.0e-3);
  513. ++i)
  514. {
  515. residual = 0.0;
  516. for(U k = 0; k < count; ++k)
  517. {
  518. Vec4 normal(bounceNormal[k]);
  519. F32 v = bounceSpeed[k] - normal.dot(auxBounceVeloc);
  520. F32 x = speed[k] + v;
  521. if(x < 0.0)
  522. {
  523. v = 0.0;
  524. x = 0.0;
  525. }
  526. if(abs(v) > residual)
  527. {
  528. residual = abs(v);
  529. }
  530. auxBounceVeloc += normal * (x - speed[k]);
  531. speed[k] = x;
  532. }
  533. }
  534. Vec4 velocStep(0.0);
  535. for(U i = 0; i < count; ++i)
  536. {
  537. Vec4 normal(bounceNormal[i]);
  538. velocStep += normal * speed[i];
  539. }
  540. veloc += velocStep;
  541. F32 velocMag2 = velocStep.getLengthSquared();
  542. if(velocMag2 < 1.0e-6)
  543. {
  544. F32 advanceTime =
  545. min(descreteTimeStep, normalizedTimeLeft * dt);
  546. Vec4 tmp = matrix.getTranslationPart() + veloc * advanceTime;
  547. matrix.setTranslationPart(tmp.xyz1());
  548. normalizedTimeLeft -= advanceTime / dt;
  549. }
  550. prevContactCount = contactCount;
  551. memcpy(&prevInfo[0],
  552. &info[0],
  553. prevContactCount * sizeof(NewtonWorldConvexCastReturnInfo));
  554. }
  555. else
  556. {
  557. matrix.setTranslationPart(destPosit.xyz1());
  558. break;
  559. }
  560. }
  561. NewtonCollisionSetScale(m_upperBodyShape, scale.x(), scale.y(), scale.z());
  562. // determine if player is standing on some plane
  563. Mat4 supportMatrix(matrix);
  564. Vec4 tmp = supportMatrix.getTranslationPart() + updir * m_sphereCastOrigin;
  565. supportMatrix.setTranslationPart(tmp.xyz1());
  566. if(m_isJumping)
  567. {
  568. Vec4 dst = matrix.getTranslationPart().xyz0();
  569. updateGroundPlane(matrix, supportMatrix, dst, threadIndex);
  570. }
  571. else
  572. {
  573. step = abs(updir.dot(veloc * dt));
  574. F32 castDist =
  575. (m_groundPlane.getLengthSquared() > 0.0) ? m_stepHeight : step;
  576. Vec4 tmp = matrix.getTranslationPart() - updir * (castDist * 2.0);
  577. Vec4 dst = tmp.xyz0();
  578. updateGroundPlane(matrix, supportMatrix, dst, threadIndex);
  579. }
  580. // set player velocity, position and orientation
  581. NewtonBodySetVelocity(m_body, &veloc[0]);
  582. NewtonBodySetMatrix(m_body, &toNewton(matrix)[0]);
  583. }
  584. //==============================================================================
  585. void PhysicsPlayerController::postUpdateKernelCallback(
  586. NewtonWorld* const world, void* const context, int threadIndex)
  587. {
  588. PhysicsPlayerController* x = static_cast<PhysicsPlayerController*>(context);
  589. x->postUpdate(x->m_world->getDeltaTime(), threadIndex);
  590. }
  591. //==============================================================================
  592. void PhysicsPlayerController::moveToPosition(const Vec4& position)
  593. {
  594. Mat4 trf;
  595. NewtonBodyGetMatrix(m_body, &trf[0]);
  596. trf.transpose();
  597. trf.setTranslationPart(position.xyz1());
  598. NewtonBodySetMatrix(m_body, &trf[0]);
  599. }
  600. //==============================================================================
  601. void PhysicsPlayerController::onTransformCallback(const NewtonBody* const body,
  602. const dFloat* const matrix,
  603. int /*threadIndex*/)
  604. {
  605. ANKI_ASSERT(body);
  606. ANKI_ASSERT(matrix);
  607. Mat4 trf;
  608. memcpy(&trf, matrix, sizeof(Mat4));
  609. void* ud = NewtonBodyGetUserData(body);
  610. ANKI_ASSERT(ud);
  611. PhysicsPlayerController* self = static_cast<PhysicsPlayerController*>(ud);
  612. self->onTransform(trf);
  613. }
  614. //==============================================================================
  615. void PhysicsPlayerController::onTransform(Mat4 trf)
  616. {
  617. if(trf != m_prevTrf)
  618. {
  619. m_prevTrf = trf;
  620. trf.transpose();
  621. m_trf = Transform(trf);
  622. m_updated = true;
  623. }
  624. }
  625. } // end namespace anki