playerControllerComponent.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "T3D/components/physics/playerControllercomponent.h"
  23. #include "platform/platform.h"
  24. #include "console/consoleTypes.h"
  25. #include "core/util/safeDelete.h"
  26. #include "core/resourceManager.h"
  27. #include "core/stream/fileStream.h"
  28. #include "console/consoleTypes.h"
  29. #include "console/consoleObject.h"
  30. #include "ts/tsShapeInstance.h"
  31. #include "core/stream/bitStream.h"
  32. #include "gfx/gfxTransformSaver.h"
  33. #include "console/engineAPI.h"
  34. #include "lighting/lightQuery.h"
  35. #include "T3D/gameBase/gameConnection.h"
  36. #include "collision/collision.h"
  37. #include "T3D/physics/physicsPlayer.h"
  38. #include "T3D/physics/physicsPlugin.h"
  39. #include "T3D/components/collision/collisionInterfaces.h"
  40. #include "T3D/trigger.h"
  41. #include "T3D/components/collision/collisionTrigger.h"
  42. // Movement constants
  43. static F32 sVerticalStepDot = 0.173f; // 80
  44. static F32 sMinFaceDistance = 0.01f;
  45. static F32 sTractionDistance = 0.04f;
  46. static F32 sNormalElasticity = 0.01f;
  47. static U32 sMoveRetryCount = 5;
  48. static F32 sMaxImpulseVelocity = 200.0f;
  49. //////////////////////////////////////////////////////////////////////////
  50. // Callbacks
  51. IMPLEMENT_CALLBACK(PlayerControllerComponent, updateMove, void, (PlayerControllerComponent* obj), (obj),
  52. "Called when the player updates it's movement, only called if object is set to callback in script(doUpdateMove).\n"
  53. "@param obj the Player object\n");
  54. //////////////////////////////////////////////////////////////////////////
  55. // Constructor/Destructor
  56. //////////////////////////////////////////////////////////////////////////
  57. PlayerControllerComponent::PlayerControllerComponent() : Component()
  58. {
  59. addComponentField("isStatic", "If enabled, object will not simulate physics", "bool", "0", "");
  60. addComponentField("gravity", "The direction of gravity affecting this object, as a vector", "vector", "0 0 -9", "");
  61. addComponentField("drag", "The drag coefficient that constantly affects the object", "float", "0.7", "");
  62. addComponentField("mass", "The mass of the object", "float", "1", "");
  63. mBuoyancy = 0.f;
  64. mFriction = 0.3f;
  65. mElasticity = 0.4f;
  66. mMaxVelocity = 3000.f;
  67. mSticky = false;
  68. mFalling = false;
  69. mSwimming = false;
  70. mInWater = false;
  71. mDelta.pos = mDelta.posVec = Point3F::Zero;
  72. mDelta.warpTicks = mDelta.warpCount = 0;
  73. mDelta.rot[0].identity();
  74. mDelta.rot[1].identity();
  75. mDelta.dt = 1;
  76. mUseDirectMoveInput = false;
  77. mFriendlyName = "Player Controller";
  78. mComponentType = "Physics";
  79. mDescription = getDescriptionText("A general-purpose physics player controller.");
  80. mNetFlags.set(Ghostable | ScopeAlways);
  81. mMass = 9.0f; // from ShapeBase
  82. mDrag = 1.0f; // from ShapeBase
  83. maxStepHeight = 1.0f;
  84. moveSurfaceAngle = 60.0f;
  85. contactSurfaceAngle = 85.0f;
  86. fallingSpeedThreshold = -10.0f;
  87. horizMaxSpeed = 80.0f;
  88. horizMaxAccel = 100.0f;
  89. horizResistSpeed = 38.0f;
  90. horizResistFactor = 1.0f;
  91. upMaxSpeed = 80.0f;
  92. upMaxAccel = 100.0f;
  93. upResistSpeed = 38.0f;
  94. upResistFactor = 1.0f;
  95. // Air control
  96. airControl = 0.0f;
  97. //Grav mod
  98. mGravityMod = 1;
  99. mInputVelocity = Point3F(0, 0, 0);
  100. mPhysicsRep = NULL;
  101. mPhysicsWorld = NULL;
  102. }
  103. PlayerControllerComponent::~PlayerControllerComponent()
  104. {
  105. for (S32 i = 0; i < mFields.size(); ++i)
  106. {
  107. ComponentField &field = mFields[i];
  108. SAFE_DELETE_ARRAY(field.mFieldDescription);
  109. }
  110. SAFE_DELETE_ARRAY(mDescription);
  111. }
  112. IMPLEMENT_CO_NETOBJECT_V1(PlayerControllerComponent);
  113. //////////////////////////////////////////////////////////////////////////
  114. bool PlayerControllerComponent::onAdd()
  115. {
  116. if (!Parent::onAdd())
  117. return false;
  118. return true;
  119. }
  120. void PlayerControllerComponent::onRemove()
  121. {
  122. Parent::onRemove();
  123. SAFE_DELETE(mPhysicsRep);
  124. }
  125. void PlayerControllerComponent::onComponentAdd()
  126. {
  127. Parent::onComponentAdd();
  128. updatePhysics();
  129. }
  130. void PlayerControllerComponent::componentAddedToOwner(Component *comp)
  131. {
  132. if (comp->getId() == getId())
  133. return;
  134. //test if this is a shape component!
  135. CollisionInterface *collisionInterface = dynamic_cast<CollisionInterface*>(comp);
  136. if (collisionInterface)
  137. {
  138. collisionInterface->onCollisionChanged.notify(this, &PlayerControllerComponent::updatePhysics);
  139. mOwnerCollisionInterface = collisionInterface;
  140. updatePhysics();
  141. }
  142. }
  143. void PlayerControllerComponent::componentRemovedFromOwner(Component *comp)
  144. {
  145. if (comp->getId() == getId()) //?????????
  146. return;
  147. //test if this is a shape component!
  148. CollisionInterface *collisionInterface = dynamic_cast<CollisionInterface*>(comp);
  149. if (collisionInterface)
  150. {
  151. collisionInterface->onCollisionChanged.remove(this, &PlayerControllerComponent::updatePhysics);
  152. mOwnerCollisionInterface = NULL;
  153. updatePhysics();
  154. }
  155. }
  156. void PlayerControllerComponent::updatePhysics(PhysicsCollision *collision)
  157. {
  158. if (!PHYSICSMGR)
  159. return;
  160. mPhysicsWorld = PHYSICSMGR->getWorld(isServerObject() ? "server" : "client");
  161. //first, clear the old physRep
  162. SAFE_DELETE(mPhysicsRep);
  163. mPhysicsRep = PHYSICSMGR->createPlayer();
  164. F32 runSurfaceCos = mCos(mDegToRad(moveSurfaceAngle));
  165. Point3F ownerBounds = mOwner->getObjBox().getExtents() * mOwner->getScale();
  166. mPhysicsRep->init("", ownerBounds, runSurfaceCos, maxStepHeight, mOwner, mPhysicsWorld);
  167. mPhysicsRep->setTransform(mOwner->getTransform());
  168. }
  169. void PlayerControllerComponent::initPersistFields()
  170. {
  171. Parent::initPersistFields();
  172. addField("inputVelocity", TypePoint3F, Offset(mInputVelocity, PlayerControllerComponent), "");
  173. addField("useDirectMoveInput", TypePoint3F, Offset(mUseDirectMoveInput, PlayerControllerComponent), "");
  174. }
  175. U32 PlayerControllerComponent::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  176. {
  177. U32 retMask = Parent::packUpdate(con, mask, stream);
  178. return retMask;
  179. }
  180. void PlayerControllerComponent::unpackUpdate(NetConnection *con, BitStream *stream)
  181. {
  182. Parent::unpackUpdate(con, stream);
  183. }
  184. //
  185. void PlayerControllerComponent::processTick()
  186. {
  187. Parent::processTick();
  188. if (!isServerObject() || !isActive())
  189. return;
  190. // Warp to catch up to server
  191. if (mDelta.warpCount < mDelta.warpTicks)
  192. {
  193. mDelta.warpCount++;
  194. // Set new pos.
  195. mDelta.pos = mOwner->getPosition();
  196. mDelta.pos += mDelta.warpOffset;
  197. mDelta.rot[0] = mDelta.rot[1];
  198. mDelta.rot[1].interpolate(mDelta.warpRot[0], mDelta.warpRot[1], F32(mDelta.warpCount) / mDelta.warpTicks);
  199. MatrixF trans;
  200. mDelta.rot[1].setMatrix(&trans);
  201. trans.setPosition(mDelta.pos);
  202. mOwner->setTransform(trans);
  203. // Pos backstepping
  204. mDelta.posVec.x = -mDelta.warpOffset.x;
  205. mDelta.posVec.y = -mDelta.warpOffset.y;
  206. mDelta.posVec.z = -mDelta.warpOffset.z;
  207. }
  208. else
  209. {
  210. // Save current rigid state interpolation
  211. mDelta.posVec = mOwner->getPosition();
  212. mDelta.rot[0] = mOwner->getTransform();
  213. updateMove();
  214. updatePos(TickSec);
  215. // Wrap up interpolation info
  216. mDelta.pos = mOwner->getPosition();
  217. mDelta.posVec -= mOwner->getPosition();
  218. mDelta.rot[1] = mOwner->getTransform();
  219. // Update container database
  220. setTransform(mOwner->getTransform());
  221. setMaskBits(VelocityMask);
  222. setMaskBits(PositionMask);
  223. }
  224. }
  225. void PlayerControllerComponent::interpolateTick(F32 dt)
  226. {
  227. }
  228. void PlayerControllerComponent::ownerTransformSet(MatrixF *mat)
  229. {
  230. if (mPhysicsRep)
  231. mPhysicsRep->setTransform(mOwner->getTransform());
  232. }
  233. void PlayerControllerComponent::setTransform(const MatrixF& mat)
  234. {
  235. mOwner->setTransform(mat);
  236. setMaskBits(UpdateMask);
  237. }
  238. //
  239. void PlayerControllerComponent::updateMove()
  240. {
  241. if (!PHYSICSMGR)
  242. return;
  243. Move *move = &mOwner->lastMove;
  244. //If we're not set to use mUseDirectMoveInput, then we allow for an override in the form of mInputVelocity
  245. if (!mUseDirectMoveInput)
  246. {
  247. move->x = mInputVelocity.x;
  248. move->y = mInputVelocity.y;
  249. move->z = mInputVelocity.z;
  250. }
  251. // Is waterCoverage high enough to be 'swimming'?
  252. {
  253. bool swimming = mOwner->getContainerInfo().waterCoverage > 0.65f/* && canSwim()*/;
  254. if (swimming != mSwimming)
  255. {
  256. mSwimming = swimming;
  257. }
  258. }
  259. // Update current orientation
  260. bool doStandardMove = true;
  261. GameConnection* con = mOwner->getControllingClient();
  262. #ifdef TORQUE_EXTENDED_MOVE
  263. // Work with an absolute rotation from the ExtendedMove class?
  264. if (con && con->getControlSchemeAbsoluteRotation())
  265. {
  266. doStandardMove = false;
  267. const ExtendedMove* emove = dynamic_cast<const ExtendedMove*>(move);
  268. U32 emoveIndex = smExtendedMoveHeadPosRotIndex;
  269. if (emoveIndex >= ExtendedMove::MaxPositionsRotations)
  270. emoveIndex = 0;
  271. if (emove->EulerBasedRotation[emoveIndex])
  272. {
  273. // Head pitch
  274. mHead.x += (emove->rotX[emoveIndex] - mLastAbsolutePitch);
  275. // Do we also include the relative yaw value?
  276. if (con->getControlSchemeAddPitchToAbsRot())
  277. {
  278. F32 x = move->pitch;
  279. if (x > M_PI_F)
  280. x -= M_2PI_F;
  281. mHead.x += x;
  282. }
  283. // Constrain the range of mHead.x
  284. while (mHead.x < -M_PI_F)
  285. mHead.x += M_2PI_F;
  286. while (mHead.x > M_PI_F)
  287. mHead.x -= M_2PI_F;
  288. // Rotate (heading) head or body?
  289. if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson())))
  290. {
  291. // Rotate head
  292. mHead.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw);
  293. // Do we also include the relative yaw value?
  294. if (con->getControlSchemeAddYawToAbsRot())
  295. {
  296. F32 z = move->yaw;
  297. if (z > M_PI_F)
  298. z -= M_2PI_F;
  299. mHead.z += z;
  300. }
  301. // Constrain the range of mHead.z
  302. while (mHead.z < 0.0f)
  303. mHead.z += M_2PI_F;
  304. while (mHead.z > M_2PI_F)
  305. mHead.z -= M_2PI_F;
  306. }
  307. else
  308. {
  309. // Rotate body
  310. mRot.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw);
  311. // Do we also include the relative yaw value?
  312. if (con->getControlSchemeAddYawToAbsRot())
  313. {
  314. F32 z = move->yaw;
  315. if (z > M_PI_F)
  316. z -= M_2PI_F;
  317. mRot.z += z;
  318. }
  319. // Constrain the range of mRot.z
  320. while (mRot.z < 0.0f)
  321. mRot.z += M_2PI_F;
  322. while (mRot.z > M_2PI_F)
  323. mRot.z -= M_2PI_F;
  324. }
  325. mLastAbsoluteYaw = emove->rotZ[emoveIndex];
  326. mLastAbsolutePitch = emove->rotX[emoveIndex];
  327. // Head bank
  328. mHead.y = emove->rotY[emoveIndex];
  329. // Constrain the range of mHead.y
  330. while (mHead.y > M_PI_F)
  331. mHead.y -= M_2PI_F;
  332. }
  333. }
  334. #endif
  335. MatrixF zRot;
  336. zRot.set(EulerF(0.0f, 0.0f, mOwner->getRotation().asEulerF().z));
  337. // Desired move direction & speed
  338. VectorF moveVec;
  339. F32 moveSpeed = mInputVelocity.len();
  340. zRot.getColumn(0, &moveVec);
  341. moveVec *= move->x;
  342. VectorF tv;
  343. zRot.getColumn(1, &tv);
  344. moveVec += tv * move->y;
  345. // Acceleration due to gravity
  346. VectorF acc(mPhysicsWorld->getGravity() * mGravityMod * TickSec);
  347. // Determine ground contact normal. Only look for contacts if
  348. // we can move and aren't mounted.
  349. mContactInfo.contactNormal = VectorF::Zero;
  350. mContactInfo.jump = false;
  351. mContactInfo.run = false;
  352. bool jumpSurface = false, runSurface = false;
  353. if (!mOwner->isMounted())
  354. findContact(&mContactInfo.run, &mContactInfo.jump, &mContactInfo.contactNormal);
  355. if (mContactInfo.jump)
  356. mJumpSurfaceNormal = mContactInfo.contactNormal;
  357. // If we don't have a runSurface but we do have a contactNormal,
  358. // then we are standing on something that is too steep.
  359. // Deflect the force of gravity by the normal so we slide.
  360. // We could also try aligning it to the runSurface instead,
  361. // but this seems to work well.
  362. if (!mContactInfo.run && !mContactInfo.contactNormal.isZero())
  363. acc = (acc - 2 * mContactInfo.contactNormal * mDot(acc, mContactInfo.contactNormal));
  364. // Acceleration on run surface
  365. if (mContactInfo.run && !mSwimming)
  366. {
  367. mContactTimer = 0;
  368. VectorF pv = moveVec;
  369. // Adjust the player's requested dir. to be parallel
  370. // to the contact surface.
  371. F32 pvl = pv.len();
  372. // Convert to acceleration
  373. if (pvl)
  374. pv *= moveSpeed / pvl;
  375. VectorF runAcc = pv - (mVelocity + acc);
  376. F32 runSpeed = runAcc.len();
  377. // Clamp acceleration, player also accelerates faster when
  378. // in his hard landing recover state.
  379. F32 maxAcc;
  380. maxAcc = (horizMaxAccel / mMass) * TickSec;
  381. if (runSpeed > maxAcc)
  382. runAcc *= maxAcc / runSpeed;
  383. acc += runAcc;
  384. }
  385. else if (!mSwimming && airControl > 0.0f)
  386. {
  387. VectorF pv;
  388. pv = moveVec;
  389. F32 pvl = pv.len();
  390. if (pvl)
  391. pv *= moveSpeed / pvl;
  392. VectorF runAcc = pv - (mVelocity + acc);
  393. runAcc.z = 0;
  394. runAcc.x = runAcc.x * airControl;
  395. runAcc.y = runAcc.y * airControl;
  396. F32 runSpeed = runAcc.len();
  397. // We don't test for sprinting when performing air control
  398. F32 maxAcc = (horizMaxAccel / mMass) * TickSec * 0.3f;
  399. if (runSpeed > maxAcc)
  400. runAcc *= maxAcc / runSpeed;
  401. acc += runAcc;
  402. // There are no special air control animations
  403. // so... increment this unless you really want to
  404. // play the run anims in the air.
  405. mContactTimer++;
  406. }
  407. else if (mSwimming)
  408. {
  409. // Remove acc into contact surface (should only be gravity)
  410. // Clear out floating point acc errors, this will allow
  411. // the player to "rest" on the ground.
  412. F32 vd = -mDot(acc, mContactInfo.contactNormal);
  413. if (vd > 0.0f)
  414. {
  415. VectorF dv = mContactInfo.contactNormal * (vd + 0.002f);
  416. acc += dv;
  417. if (acc.len() < 0.0001f)
  418. acc.set(0.0f, 0.0f, 0.0f);
  419. }
  420. // get the head pitch and add it to the moveVec
  421. // This more accurate swim vector calc comes from Matt Fairfax
  422. MatrixF xRot, zRot;
  423. xRot.set(EulerF(mOwner->getRotation().asEulerF().x, 0, 0));
  424. zRot.set(EulerF(0, 0, mOwner->getRotation().asEulerF().z));
  425. MatrixF rot;
  426. rot.mul(zRot, xRot);
  427. rot.getColumn(0, &moveVec);
  428. moveVec *= move->x;
  429. VectorF tv;
  430. rot.getColumn(1, &tv);
  431. moveVec += tv * move->y;
  432. rot.getColumn(2, &tv);
  433. moveVec += tv * move->z;
  434. // Force a 0 move if there is no energy, and only drain
  435. // move energy if we're moving.
  436. VectorF swimVec = moveVec;
  437. // If we are swimming but close enough to the shore/ground
  438. // we can still have a surface-normal. In this case align the
  439. // velocity to the normal to make getting out of water easier.
  440. moveVec.normalize();
  441. F32 isSwimUp = mDot(moveVec, mContactInfo.contactNormal);
  442. if (!mContactInfo.contactNormal.isZero() && isSwimUp < 0.1f)
  443. {
  444. F32 pvl = swimVec.len();
  445. if (pvl)
  446. {
  447. VectorF nn;
  448. mCross(swimVec, VectorF(0.0f, 0.0f, 1.0f), &nn);
  449. nn *= 1.0f / pvl;
  450. VectorF cv = mContactInfo.contactNormal;
  451. cv -= nn * mDot(nn, cv);
  452. swimVec -= cv * mDot(swimVec, cv);
  453. }
  454. }
  455. F32 swimVecLen = swimVec.len();
  456. // Convert to acceleration.
  457. if (swimVecLen)
  458. swimVec *= moveSpeed / swimVecLen;
  459. VectorF swimAcc = swimVec - (mVelocity + acc);
  460. F32 swimSpeed = swimAcc.len();
  461. // Clamp acceleration.
  462. F32 maxAcc = (horizMaxAccel / mMass) * TickSec;
  463. if (swimSpeed > maxAcc)
  464. swimAcc *= maxAcc / swimSpeed;
  465. acc += swimAcc;
  466. mContactTimer++;
  467. }
  468. else
  469. mContactTimer++;
  470. // Add in force from physical zones...
  471. acc += (mOwner->getContainerInfo().appliedForce / mMass) * TickSec;
  472. // Adjust velocity with all the move & gravity acceleration
  473. // TG: I forgot why doesn't the TickSec multiply happen here...
  474. mVelocity += acc;
  475. // apply horizontal air resistance
  476. F32 hvel = mSqrt(mVelocity.x * mVelocity.x + mVelocity.y * mVelocity.y);
  477. if (hvel > horizResistSpeed)
  478. {
  479. F32 speedCap = hvel;
  480. if (speedCap > horizMaxSpeed)
  481. speedCap = horizMaxSpeed;
  482. speedCap -= horizResistFactor * TickSec * (speedCap - horizResistSpeed);
  483. F32 scale = speedCap / hvel;
  484. mVelocity.x *= scale;
  485. mVelocity.y *= scale;
  486. }
  487. if (mVelocity.z > upResistSpeed)
  488. {
  489. if (mVelocity.z > upMaxSpeed)
  490. mVelocity.z = upMaxSpeed;
  491. mVelocity.z -= upResistFactor * TickSec * (mVelocity.z - upResistSpeed);
  492. }
  493. // Apply drag
  494. mVelocity -= mVelocity * mDrag * TickSec;
  495. // Clamp very small velocity to zero
  496. if (mVelocity.isZero())
  497. mVelocity = Point3F::Zero;
  498. // If we are not touching anything and have sufficient -z vel,
  499. // we are falling.
  500. if (mContactInfo.run)
  501. {
  502. mFalling = false;
  503. }
  504. else
  505. {
  506. VectorF vel;
  507. mOwner->getWorldToObj().mulV(mVelocity, &vel);
  508. mFalling = vel.z < fallingSpeedThreshold;
  509. }
  510. // Enter/Leave Liquid
  511. if (!mInWater && mOwner->getContainerInfo().waterCoverage > 0.0f)
  512. {
  513. mInWater = true;
  514. }
  515. else if (mInWater && mOwner->getContainerInfo().waterCoverage <= 0.0f)
  516. {
  517. mInWater = false;
  518. }
  519. }
  520. void PlayerControllerComponent::updatePos(const F32 travelTime)
  521. {
  522. if (!PHYSICSMGR)
  523. return;
  524. PROFILE_SCOPE(PlayerControllerComponent_UpdatePos);
  525. Point3F newPos;
  526. Collision col;
  527. dMemset(&col, 0, sizeof(col));
  528. static CollisionList collisionList;
  529. collisionList.clear();
  530. newPos = mPhysicsRep->move(mVelocity * travelTime, collisionList);
  531. bool haveCollisions = false;
  532. bool wasFalling = mFalling;
  533. if (collisionList.getCount() > 0)
  534. {
  535. mFalling = false;
  536. haveCollisions = true;
  537. //TODO: clean this up so the phys component doesn't have to tell the col interface to do this
  538. CollisionInterface* colInterface = mOwner->getComponent<CollisionInterface>();
  539. if (colInterface)
  540. {
  541. colInterface->handleCollisionList(collisionList, mVelocity);
  542. }
  543. }
  544. if (haveCollisions)
  545. {
  546. // Pick the collision that most closely matches our direction
  547. VectorF velNormal = mVelocity;
  548. velNormal.normalizeSafe();
  549. const Collision *collision = &collisionList[0];
  550. F32 collisionDot = mDot(velNormal, collision->normal);
  551. const Collision *cp = collision + 1;
  552. const Collision *ep = collision + collisionList.getCount();
  553. for (; cp != ep; cp++)
  554. {
  555. F32 dp = mDot(velNormal, cp->normal);
  556. if (dp < collisionDot)
  557. {
  558. collisionDot = dp;
  559. collision = cp;
  560. }
  561. }
  562. // Modify our velocity based on collisions
  563. for (U32 i = 0; i<collisionList.getCount(); ++i)
  564. {
  565. F32 bd = -mDot(mVelocity, collisionList[i].normal);
  566. VectorF dv = collisionList[i].normal * (bd + sNormalElasticity);
  567. mVelocity += dv;
  568. }
  569. // Store the last collision for use later on. The handle collision
  570. // code only expects a single collision object.
  571. if (collisionList.getCount() > 0)
  572. col = collisionList[collisionList.getCount() - 1];
  573. // We'll handle any player-to-player collision, and the last collision
  574. // with other obejct types.
  575. for (U32 i = 0; i<collisionList.getCount(); ++i)
  576. {
  577. Collision& colCheck = collisionList[i];
  578. if (colCheck.object)
  579. {
  580. col = colCheck;
  581. }
  582. }
  583. }
  584. MatrixF newMat;
  585. newMat.setPosition(newPos);
  586. mPhysicsRep->setTransform(newMat);
  587. mOwner->setPosition(newPos);
  588. }
  589. //
  590. void PlayerControllerComponent::setVelocity(const VectorF& vel)
  591. {
  592. mVelocity = vel;
  593. // Clamp against the maximum velocity.
  594. if (mMaxVelocity > 0)
  595. {
  596. F32 len = mVelocity.magnitudeSafe();
  597. if (len > mMaxVelocity)
  598. {
  599. Point3F excess = mVelocity * (1.0f - (mMaxVelocity / len));
  600. mVelocity -= excess;
  601. }
  602. }
  603. setMaskBits(VelocityMask);
  604. }
  605. void PlayerControllerComponent::findContact(bool *run, bool *jump, VectorF *contactNormal)
  606. {
  607. SceneObject *contactObject = NULL;
  608. Vector<SceneObject*> overlapObjects;
  609. mPhysicsRep->findContact(&contactObject, contactNormal, &overlapObjects);
  610. F32 vd = (*contactNormal).z;
  611. *run = vd > mCos(mDegToRad(moveSurfaceAngle));
  612. *jump = vd > mCos(mDegToRad(contactSurfaceAngle));
  613. // Check for triggers
  614. for (U32 i = 0; i < overlapObjects.size(); i++)
  615. {
  616. SceneObject *obj = overlapObjects[i];
  617. U32 objectMask = obj->getTypeMask();
  618. // Check: triggers, corpses and items...
  619. //
  620. if (objectMask & TriggerObjectType)
  621. {
  622. if (Trigger* pTrigger = dynamic_cast<Trigger*>(obj))
  623. {
  624. pTrigger->potentialEnterObject(mOwner);
  625. }
  626. else if (CollisionTrigger* pTriggerEx = dynamic_cast<CollisionTrigger*>(obj))
  627. {
  628. if (pTriggerEx)
  629. pTriggerEx->potentialEnterObject(mOwner);
  630. }
  631. //Add any other custom classes and the sort here that should be filtered against
  632. /*else if (TriggerExample* pTriggerEx = dynamic_cast<TriggerExample*>(obj))
  633. {
  634. if (pTriggerEx)
  635. pTriggerEx->potentialEnterObject(mOwner);
  636. }*/
  637. }
  638. }
  639. mContactInfo.contacted = contactObject != NULL;
  640. mContactInfo.contactObject = contactObject;
  641. if (mContactInfo.contacted)
  642. mContactInfo.contactNormal = *contactNormal;
  643. }
  644. void PlayerControllerComponent::applyImpulse(const Point3F &pos, const VectorF &vec)
  645. {
  646. AssertFatal(!mIsNaN(vec), "Player::applyImpulse() - The vector is NaN!");
  647. // Players ignore angular velocity
  648. VectorF vel;
  649. vel.x = vec.x / getMass();
  650. vel.y = vec.y / getMass();
  651. vel.z = vec.z / getMass();
  652. // Make sure the impulse isn't too bigg
  653. F32 len = vel.magnitudeSafe();
  654. if (len > sMaxImpulseVelocity)
  655. {
  656. Point3F excess = vel * (1.0f - (sMaxImpulseVelocity / len));
  657. vel -= excess;
  658. }
  659. setVelocity(mVelocity + vel);
  660. }
  661. DefineEngineMethod(PlayerControllerComponent, applyImpulse, bool, (Point3F pos, VectorF vel), ,
  662. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  663. "@param pos impulse world position\n"
  664. "@param vel impulse velocity (impulse force F = m * v)\n"
  665. "@return Always true\n"
  666. "@note Not all objects that derrive from GameBase have this defined.\n")
  667. {
  668. object->applyImpulse(pos, vel);
  669. return true;
  670. }
  671. DefineEngineMethod(PlayerControllerComponent, getContactNormal, Point3F, (), ,
  672. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  673. "@param pos impulse world position\n"
  674. "@param vel impulse velocity (impulse force F = m * v)\n"
  675. "@return Always true\n"
  676. "@note Not all objects that derrive from GameBase have this defined.\n")
  677. {
  678. return object->getContactNormal();
  679. }
  680. DefineEngineMethod(PlayerControllerComponent, getContactObject, SceneObject*, (), ,
  681. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  682. "@param pos impulse world position\n"
  683. "@param vel impulse velocity (impulse force F = m * v)\n"
  684. "@return Always true\n"
  685. "@note Not all objects that derrive from GameBase have this defined.\n")
  686. {
  687. return object->getContactObject();
  688. }
  689. DefineEngineMethod(PlayerControllerComponent, isContacted, bool, (), ,
  690. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  691. "@param pos impulse world position\n"
  692. "@param vel impulse velocity (impulse force F = m * v)\n"
  693. "@return Always true\n"
  694. "@note Not all objects that derrive from GameBase have this defined.\n")
  695. {
  696. return object->isContacted();
  697. }