player.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  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. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #ifndef _PLAYER_H_
  27. #define _PLAYER_H_
  28. #ifndef _SHAPEBASE_H_
  29. #include "T3D/shapeBase.h"
  30. #endif
  31. #ifndef _BOXCONVEX_H_
  32. #include "collision/boxConvex.h"
  33. #endif
  34. #include "T3D/assets/SoundAsset.h"
  35. #include "T3D/gameBase/gameProcess.h"
  36. class Material;
  37. class ParticleEmitter;
  38. class ParticleEmitterData;
  39. class DecalData;
  40. class SplashData;
  41. class PhysicsPlayer;
  42. class Player;
  43. #ifdef TORQUE_OPENVR
  44. class OpenVRTrackedObject;
  45. #endif
  46. //----------------------------------------------------------------------------
  47. struct PlayerData: public ShapeBaseData {
  48. typedef ShapeBaseData Parent;
  49. enum Constants {
  50. RecoverDelayBits = 7,
  51. JumpDelayBits = 7,
  52. NumSpineNodes = 6,
  53. ImpactBits = 3,
  54. NUM_SPLASH_EMITTERS = 3,
  55. BUBBLE_EMITTER = 2,
  56. };
  57. bool renderFirstPerson; ///< Render the player shape in first person
  58. /// Render shadows while in first person when
  59. /// renderFirstPerson is disabled.
  60. bool firstPersonShadows;
  61. StringTableEntry imageAnimPrefix; ///< Passed along to mounted images to modify
  62. /// animation sequences played in third person. [optional]
  63. bool allowImageStateAnimation; ///< When true a new thread is added to the player to allow for
  64. /// mounted images to request a sequence be played on the player
  65. /// through the image's state machine. It is only optional so
  66. /// that we don't create a TSThread on the player if we don't
  67. /// need to.
  68. DECLARE_SHAPEASSET_ARRAY(PlayerData, ShapeFP, ShapeBase::MaxMountedImages); ///< Used to render with mounted images in first person [optional]
  69. DECLARE_ASSET_ARRAY_SETGET(PlayerData, ShapeFP);
  70. StringTableEntry imageAnimPrefixFP; ///< Passed along to mounted images to modify
  71. /// animation sequences played in first person. [optional]
  72. U32 mCRCFP[ShapeBase::MaxMountedImages]; ///< Computed CRC values for the first person mounted image shapes
  73. /// Depends on the ShapeBaseData computeCRC field.
  74. bool mValidShapeFP[ShapeBase::MaxMountedImages]; ///< Indicates that there is a valid first person mounted image shape
  75. F32 pickupRadius; ///< Radius around player for items (on server)
  76. F32 maxTimeScale; ///< Max timeScale for action animations
  77. F32 minLookAngle; ///< Lowest angle (radians) the player can look
  78. F32 maxLookAngle; ///< Highest angle (radians) the player can look
  79. F32 maxFreelookAngle; ///< Max left/right angle the player can look
  80. /// @name Physics constants
  81. /// @{
  82. F32 maxStepHeight; ///< Maximum height the player can step up
  83. F32 runSurfaceAngle; ///< Maximum angle from vertical in degrees the player can run up
  84. F32 horizMaxSpeed; ///< Max speed attainable in the horizontal
  85. F32 horizResistSpeed; ///< Speed at which resistance will take place
  86. F32 horizResistFactor; ///< Factor of resistance once horizResistSpeed has been reached
  87. F32 upMaxSpeed; ///< Max vertical speed attainable
  88. F32 upResistSpeed; ///< Speed at which resistance will take place
  89. F32 upResistFactor; ///< Factor of resistance once upResistSpeed has been reached
  90. F32 fallingSpeedThreshold; ///< Downward speed at which we consider the player falling
  91. S32 recoverDelay; ///< # tick
  92. F32 recoverRunForceScale; ///< RunForce multiplier in recover state
  93. F32 landSequenceTime; ///< If greater than 0 then the legacy fall recovery system will be bypassed
  94. /// in favour of just playing the player's land sequence. The time to
  95. /// recover from a fall then becomes this parameter's time and the land
  96. /// sequence's playback will be scaled to match.
  97. bool transitionToLand; ///< When going from a fall to a land, should we transition between the two?
  98. // Running/Walking
  99. F32 runForce; ///< Force used to accelerate player
  100. F32 runEnergyDrain; ///< Energy drain/tick
  101. F32 minRunEnergy; ///< Minimum energy required to run
  102. F32 maxForwardSpeed; ///< Maximum forward speed when running
  103. F32 maxBackwardSpeed; ///< Maximum backward speed when running
  104. F32 maxSideSpeed; ///< Maximum side speed when running
  105. // Jumping
  106. F32 jumpForce; ///< Force exerted per jump
  107. F32 jumpEnergyDrain; ///< Energy drained per jump
  108. F32 minJumpEnergy; ///< Minimum energy required to jump
  109. F32 minJumpSpeed; ///< Minimum speed needed to jump
  110. F32 maxJumpSpeed; ///< Maximum speed before the player can no longer jump
  111. F32 jumpSurfaceAngle; ///< Angle from vertical in degrees where the player can jump
  112. S32 jumpDelay; ///< Delay time in ticks between jumps
  113. // Sprinting
  114. F32 sprintForce; ///< Force used to accelerate player
  115. F32 sprintEnergyDrain; ///< Energy drain/tick
  116. F32 minSprintEnergy; ///< Minimum energy required to sprint
  117. F32 maxSprintForwardSpeed; ///< Maximum forward speed when sprinting
  118. F32 maxSprintBackwardSpeed; ///< Maximum backward speed when sprinting
  119. F32 maxSprintSideSpeed; ///< Maximum side speed when sprinting
  120. F32 sprintStrafeScale; ///< Amount to scale strafing motion vector while sprinting
  121. F32 sprintYawScale; ///< Amount to scale yaw motion while sprinting
  122. F32 sprintPitchScale; ///< Amount to scale pitch motion while sprinting
  123. bool sprintCanJump; ///< Can the player jump while sprinting
  124. // Swimming
  125. F32 swimForce; ///< Force used to accelerate player while swimming
  126. F32 maxUnderwaterForwardSpeed; ///< Maximum underwater forward speed when running
  127. F32 maxUnderwaterBackwardSpeed; ///< Maximum underwater backward speed when running
  128. F32 maxUnderwaterSideSpeed; ///< Maximum underwater side speed when running
  129. // Crouching
  130. F32 crouchForce; ///< Force used to accelerate player while crouching
  131. F32 maxCrouchForwardSpeed; ///< Maximum forward speed when crouching
  132. F32 maxCrouchBackwardSpeed; ///< Maximum backward speed when crouching
  133. F32 maxCrouchSideSpeed; ///< Maximum side speed when crouching
  134. // Prone
  135. F32 proneForce; ///< Force used to accelerate player while prone
  136. F32 maxProneForwardSpeed; ///< Maximum forward speed when prone
  137. F32 maxProneBackwardSpeed; ///< Maximum backward speed when prone
  138. F32 maxProneSideSpeed; ///< Maximum side speed when prone
  139. // Jetting
  140. F32 jetJumpForce;
  141. F32 jetJumpEnergyDrain; ///< Energy per jump
  142. F32 jetMinJumpEnergy;
  143. F32 jetMinJumpSpeed;
  144. F32 jetMaxJumpSpeed;
  145. F32 jetJumpSurfaceAngle; ///< Angle vertical degrees
  146. /// @}
  147. /// @name Hitboxes
  148. /// @{
  149. F32 boxHeadPercentage;
  150. F32 boxTorsoPercentage;
  151. F32 boxHeadLeftPercentage;
  152. F32 boxHeadRightPercentage;
  153. F32 boxHeadBackPercentage;
  154. F32 boxHeadFrontPercentage;
  155. /// @}
  156. F32 minImpactSpeed; ///< Minimum impact speed required to apply fall damage
  157. F32 minLateralImpactSpeed; ///< Minimum impact speed required to apply non-falling damage.
  158. F32 decalOffset;
  159. F32 groundImpactMinSpeed; ///< Minimum impact speed required to apply fall damage with the ground
  160. VectorF groundImpactShakeFreq; ///< Frequency in each direction for the camera to shake
  161. VectorF groundImpactShakeAmp; ///< How much to shake
  162. F32 groundImpactShakeDuration; ///< How long to shake
  163. F32 groundImpactShakeFalloff; ///< How fast the shake disapates
  164. /// Zounds!
  165. enum Sounds {
  166. FootSoft,
  167. FootHard,
  168. FootMetal,
  169. FootSnow,
  170. WaterStart,
  171. FootShallowSplash,
  172. FootWading,
  173. FootUnderWater,
  174. FootBubbles,
  175. MoveBubbles,
  176. WaterBreath,
  177. ImpactStart,
  178. ImpactSoft,
  179. ImpactHard,
  180. ImpactMetal,
  181. ImpactSnow,
  182. ImpactWaterEasy,
  183. ImpactWaterMedium,
  184. ImpactWaterHard,
  185. ExitWater,
  186. MaxSounds
  187. };
  188. DECLARE_SOUNDASSET_ARRAY(PlayerData, PlayerSound, Sounds::MaxSounds);
  189. Point3F boxSize; ///< Width, depth, height
  190. Point3F crouchBoxSize;
  191. Point3F proneBoxSize;
  192. Point3F swimBoxSize;
  193. /// Animation and other data initialized in onAdd
  194. struct ActionAnimationDef {
  195. const char* name; ///< Sequence name
  196. struct Vector {
  197. F32 x,y,z;
  198. } dir; ///< Default direction
  199. };
  200. struct ActionAnimation {
  201. const char* name; ///< Sequence name
  202. S32 sequence; ///< Sequence index
  203. VectorF dir; ///< Dir of animation ground transform
  204. F32 speed; ///< Speed in m/s
  205. bool velocityScale; ///< Scale animation by velocity
  206. bool death; ///< Are we dying?
  207. };
  208. enum {
  209. // *** WARNING ***
  210. // These enum values are used to index the ActionAnimationList
  211. // array instantiated in player.cc
  212. // The first several are selected in the move state based on velocity
  213. RootAnim,
  214. RunForwardAnim,
  215. BackBackwardAnim,
  216. SideLeftAnim,
  217. SideRightAnim,
  218. SprintRootAnim,
  219. SprintForwardAnim,
  220. SprintBackwardAnim,
  221. SprintLeftAnim,
  222. SprintRightAnim,
  223. CrouchRootAnim,
  224. CrouchForwardAnim,
  225. CrouchBackwardAnim,
  226. CrouchLeftAnim,
  227. CrouchRightAnim,
  228. ProneRootAnim,
  229. ProneForwardAnim,
  230. ProneBackwardAnim,
  231. SwimRootAnim,
  232. SwimForwardAnim,
  233. SwimBackwardAnim,
  234. SwimLeftAnim,
  235. SwimRightAnim,
  236. // These are set explicitly based on player actions
  237. FallAnim,
  238. JumpAnim,
  239. StandJumpAnim,
  240. LandAnim,
  241. JetAnim,
  242. //
  243. NumTableActionAnims = JetAnim + 1,
  244. NumExtraActionAnims = 512 - NumTableActionAnims,
  245. NumActionAnims = NumTableActionAnims + NumExtraActionAnims,
  246. ActionAnimBits = 9,
  247. NullAnimation = (1 << ActionAnimBits) - 1
  248. };
  249. static ActionAnimationDef ActionAnimationList[NumTableActionAnims];
  250. ActionAnimation actionList[NumActionAnims];
  251. U32 actionCount;
  252. U32 lookAction;
  253. S32 spineNode[NumSpineNodes];
  254. S32 pickupDelta; ///< Base off of pcikupRadius
  255. F32 runSurfaceCos; ///< Angle from vertical in cos(runSurfaceAngle)
  256. F32 jumpSurfaceCos; ///< Angle from vertical in cos(jumpSurfaceAngle)
  257. enum Impacts {
  258. ImpactNone,
  259. ImpactNormal,
  260. };
  261. enum Recoil {
  262. LightRecoil,
  263. MediumRecoil,
  264. HeavyRecoil,
  265. NumRecoilSequences
  266. };
  267. S32 recoilSequence[NumRecoilSequences];
  268. /// @name Particles
  269. /// All of the data relating to environmental effects
  270. /// @{
  271. ParticleEmitterData * footPuffEmitter;
  272. S32 footPuffID;
  273. S32 footPuffNumParts;
  274. F32 footPuffRadius;
  275. DecalData* decalData;
  276. S32 decalID;
  277. ParticleEmitterData * dustEmitter;
  278. S32 dustID;
  279. SplashData* splash;
  280. S32 splashId;
  281. F32 splashVelocity;
  282. F32 splashAngle;
  283. F32 splashFreqMod;
  284. F32 splashVelEpsilon;
  285. F32 bubbleEmitTime;
  286. F32 medSplashSoundVel;
  287. F32 hardSplashSoundVel;
  288. F32 exitSplashSoundVel;
  289. F32 footSplashHeight;
  290. // Air control
  291. F32 airControl;
  292. // Jump off surfaces at their normal rather than straight up
  293. bool jumpTowardsNormal;
  294. // For use if/when mPhysicsPlayer is created
  295. StringTableEntry physicsPlayerType;
  296. ParticleEmitterData* splashEmitterList[NUM_SPLASH_EMITTERS];
  297. S32 splashEmitterIDList[NUM_SPLASH_EMITTERS];
  298. /// @}
  299. //
  300. DECLARE_CONOBJECT(PlayerData);
  301. PlayerData();
  302. bool preload(bool server, String &errorStr);
  303. void getGroundInfo(TSShapeInstance*,TSThread*,ActionAnimation*);
  304. bool isTableSequence(S32 seq);
  305. bool isJumpAction(U32 action);
  306. static void initPersistFields();
  307. virtual void packData(BitStream* stream);
  308. virtual void unpackData(BitStream* stream);
  309. /// @name Callbacks
  310. /// @{
  311. DECLARE_CALLBACK( void, onPoseChange, ( Player* obj, const char* oldPose, const char* newPose ) );
  312. DECLARE_CALLBACK( void, onStartSwim, ( Player* obj ) );
  313. DECLARE_CALLBACK( void, onStopSwim, ( Player* obj ) );
  314. DECLARE_CALLBACK( void, onStartSprintMotion, ( Player* obj ) );
  315. DECLARE_CALLBACK( void, onStopSprintMotion, ( Player* obj ) );
  316. DECLARE_CALLBACK( void, doDismount, ( Player* obj ) );
  317. DECLARE_CALLBACK( void, onEnterLiquid, ( Player* obj, F32 coverage, const char* type ) );
  318. DECLARE_CALLBACK( void, onLeaveLiquid, ( Player* obj, const char* type ) );
  319. DECLARE_CALLBACK( void, animationDone, ( Player* obj ) );
  320. DECLARE_CALLBACK( void, onEnterMissionArea, ( Player* obj ) );
  321. DECLARE_CALLBACK( void, onLeaveMissionArea, ( Player* obj ) );
  322. /// @}
  323. };
  324. //----------------------------------------------------------------------------
  325. class Player: public ShapeBase
  326. {
  327. typedef ShapeBase Parent;
  328. public:
  329. enum Pose {
  330. StandPose = 0,
  331. SprintPose,
  332. CrouchPose,
  333. PronePose,
  334. SwimPose,
  335. NumPoseBits = 3
  336. };
  337. /// The ExtendedMove position/rotation index used for head movements
  338. static S32 smExtendedMoveHeadPosRotIndex;
  339. protected:
  340. /// Bit masks for different types of events
  341. enum MaskBits {
  342. ActionMask = Parent::NextFreeMask << 0,
  343. MoveMask = Parent::NextFreeMask << 1,
  344. ImpactMask = Parent::NextFreeMask << 2,
  345. TriggerMask = Parent::NextFreeMask << 3,
  346. NextFreeMask = Parent::NextFreeMask << 4
  347. };
  348. SimObjectPtr<ParticleEmitter> mSplashEmitter[PlayerData::NUM_SPLASH_EMITTERS];
  349. F32 mBubbleEmitterTime;
  350. /// Client interpolation/warp data
  351. struct StateDelta {
  352. Move move; ///< Last move from server
  353. F32 dt; ///< Last interpolation time
  354. /// @name Interpolation data
  355. /// @{
  356. Point3F pos;
  357. Point3F rot;
  358. Point3F head;
  359. VectorF posVec;
  360. VectorF rotVec;
  361. VectorF headVec;
  362. /// @}
  363. /// @name Warp data
  364. /// @{
  365. S32 warpTicks;
  366. Point3F warpOffset;
  367. Point3F rotOffset;
  368. /// @}
  369. };
  370. StateDelta mDelta; ///< Used for interpolation on the client. @see StateDelta
  371. S32 mPredictionCount; ///< Number of ticks to predict
  372. // Current pos, vel etc.
  373. Point3F mHead; ///< Head rotation, uses only x & z
  374. Point3F mRot; ///< Body rotation, uses only z
  375. VectorF mVelocity; ///< Velocity
  376. Point3F mAnchorPoint; ///< Pos compression anchor
  377. S32 mImpactSound;
  378. bool mUseHeadZCalc; ///< Including mHead.z in transform calculations
  379. F32 mLastAbsoluteYaw; ///< Stores that last absolute yaw value as passed in by ExtendedMove
  380. F32 mLastAbsolutePitch; ///< Stores that last absolute pitch value as passed in by ExtendedMove
  381. F32 mLastAbsoluteRoll; ///< Stores that last absolute roll value as passed in by ExtendedMove
  382. S32 mMountPending; ///< mMountPending suppresses tickDelay countdown so players will sit until
  383. ///< their mount, or another animation, comes through (or 13 seconds elapses).
  384. /// Main player state
  385. enum ActionState {
  386. NullState,
  387. MoveState,
  388. RecoverState,
  389. NumStateBits = 3
  390. };
  391. ActionState mState; ///< What is the player doing? @see ActionState
  392. bool mFalling; ///< Falling in mid-air?
  393. S32 mJumpDelay; ///< Delay till next jump
  394. Pose mPose;
  395. bool mAllowJumping;
  396. bool mAllowJetJumping;
  397. bool mAllowSprinting;
  398. bool mAllowCrouching;
  399. bool mAllowProne;
  400. bool mAllowSwimming;
  401. S32 mContactTimer; ///< Ticks since last contact
  402. Point3F mJumpSurfaceNormal; ///< Normal of the surface the player last jumped on
  403. U32 mJumpSurfaceLastContact; ///< How long it's been since the player landed (ticks)
  404. F32 mWeaponBackFraction; ///< Amount to slide the weapon back (if it's up against something)
  405. SFXSource* mMoveBubbleSound; ///< Sound for moving bubbles
  406. SFXSource* mWaterBreathSound; ///< Sound for underwater breath
  407. SimObjectPtr<ShapeBase> mControlObject; ///< Controlling object
  408. /// @name Animation threads & data
  409. /// @{
  410. struct ActionAnimation {
  411. S32 action;
  412. TSThread* thread;
  413. S32 delayTicks; // before picking another.
  414. bool forward;
  415. bool firstPerson;
  416. bool waitForEnd;
  417. bool holdAtEnd;
  418. bool animateOnServer;
  419. bool atEnd;
  420. } mActionAnimation;
  421. struct ArmAnimation {
  422. U32 action;
  423. TSThread* thread;
  424. } mArmAnimation;
  425. TSThread* mArmThread;
  426. TSThread* mHeadVThread;
  427. TSThread* mHeadHThread;
  428. TSThread* mRecoilThread;
  429. TSThread* mImageStateThread;
  430. /// @}
  431. bool mInMissionArea; ///< Are we in the mission area?
  432. //
  433. S32 mRecoverTicks; ///< same as recoverTicks in the player datablock
  434. U32 mReversePending;
  435. F32 mRecoverDelay; ///< When bypassing the legacy recover system and only using the land sequence,
  436. /// this is how long the player will be in the land sequence.
  437. bool mInWater; ///< Is true if WaterCoverage is greater than zero
  438. bool mSwimming; ///< Is true if WaterCoverage is above the swimming threshold
  439. //
  440. PlayerData* mDataBlock; ///< MMmmmmm...datablock...
  441. Point3F mLastPos; ///< Holds the last position for physics updates
  442. Point3F mLastWaterPos; ///< Same as mLastPos, but for water
  443. #ifdef TORQUE_OPENVR
  444. SimObjectPtr<OpenVRTrackedObject> mControllers[2];
  445. #endif
  446. struct ContactInfo
  447. {
  448. bool contacted, jump, run;
  449. SceneObject *contactObject;
  450. VectorF contactNormal;
  451. void clear()
  452. {
  453. contacted=jump=run=false;
  454. contactObject = NULL;
  455. contactNormal.set(1,1,1);
  456. }
  457. ContactInfo() { clear(); }
  458. } mContactInfo;
  459. struct Death {
  460. F32 lastPos;
  461. Point3F posAdd;
  462. VectorF rotate;
  463. VectorF curNormal;
  464. F32 curSink;
  465. void clear() {dMemset(this, 0, sizeof(*this)); initFall();}
  466. VectorF getPosAdd() {VectorF ret(posAdd); posAdd.set(0,0,0); return ret;}
  467. bool haveVelocity() {return posAdd.x != 0 || posAdd.y != 0;}
  468. void initFall() {curNormal.set(0,0,1); curSink = 0;}
  469. Death() {clear();}
  470. MatrixF* fallToGround(F32 adjust, const Point3F& pos, F32 zrot, F32 boxRad);
  471. } mDeath;
  472. PhysicsPlayer *mPhysicsRep;
  473. // First person mounted image shapes
  474. TSShapeInstance* mShapeFPInstance[ShapeBase::MaxMountedImages];
  475. TSThread *mShapeFPAmbientThread[ShapeBase::MaxMountedImages];
  476. TSThread *mShapeFPVisThread[ShapeBase::MaxMountedImages];
  477. TSThread *mShapeFPAnimThread[ShapeBase::MaxMountedImages];
  478. TSThread *mShapeFPFlashThread[ShapeBase::MaxMountedImages];
  479. TSThread *mShapeFPSpinThread[ShapeBase::MaxMountedImages];
  480. public:
  481. // New collision
  482. OrthoBoxConvex mConvex;
  483. Box3F mWorkingQueryBox;
  484. /// Standing / Crouched / Prone or Swimming
  485. Pose getPose() const { return mPose; }
  486. virtual const char* getPoseName() const;
  487. /// Setting this from script directly might not actually work,
  488. /// This is really just a helper for the player class so that its bounding box
  489. /// will get resized appropriately when the pose changes
  490. void setPose( Pose pose );
  491. PhysicsPlayer* getPhysicsRep() const { return mPhysicsRep; }
  492. #ifdef TORQUE_OPENVR
  493. void setControllers(Vector<OpenVRTrackedObject*> controllerList);
  494. #endif
  495. protected:
  496. virtual void reSkin();
  497. void setState(ActionState state, U32 ticks=0);
  498. void updateState();
  499. // Jetting
  500. bool mJetting;
  501. ///Update the movement
  502. virtual void updateMove(const Move *move);
  503. ///Interpolate movement
  504. Point3F _move( const F32 travelTime, Collision *outCol );
  505. F32 _doCollisionImpact( const Collision *collision, bool fallingCollision);
  506. void _handleCollision( const Collision &collision );
  507. virtual bool updatePos(const F32 travelTime = TickSec);
  508. // PATHSHAPE
  509. void updateAttachment();
  510. // PATHSHAPE END
  511. ///Update head animation
  512. void updateLookAnimation(F32 dT = 0.f);
  513. ///Update other animations
  514. void updateAnimation(F32 dt);
  515. void updateAnimationTree(bool firstPerson);
  516. bool step(Point3F *pos,F32 *maxStep,F32 time);
  517. ///See if the player is still in the mission area
  518. void checkMissionArea();
  519. virtual U32 getArmAction() const { return mArmAnimation.action; }
  520. virtual bool setArmThread(U32 action);
  521. virtual void setActionThread(U32 action,bool forward,bool hold = false,bool wait = false,bool fsp = false, bool forceSet = false);
  522. virtual void updateActionThread();
  523. virtual void pickBestMoveAction(U32 startAnim, U32 endAnim, U32 * action, bool * forward) const;
  524. virtual void pickActionAnimation();
  525. /// @name Mounted objects
  526. /// @{
  527. virtual void onUnmount( SceneObject *obj, S32 node );
  528. virtual void unmount();
  529. /// @}
  530. void setPosition(const Point3F& pos,const Point3F& viewRot);
  531. void setRenderPosition(const Point3F& pos,const Point3F& viewRot,F32 dt=-1);
  532. void _findContact( SceneObject **contactObject, VectorF *contactNormal, Vector<SceneObject*> *outOverlapObjects );
  533. void findContact( bool *run, bool *jump, VectorF *contactNormal );
  534. void buildImagePrefixPaths(String* prefixPaths);
  535. S32 findPrefixSequence(String* prefixPaths, const String& baseSeq);
  536. S32 convertActionToImagePrefix(U32 action);
  537. virtual void onImage(U32 imageSlot, bool unmount);
  538. virtual void onImageRecoil(U32 imageSlot,ShapeBaseImageData::StateData::RecoilState);
  539. virtual void onImageStateAnimation(U32 imageSlot, const char* seqName, bool direction, bool scaleToState, F32 stateTimeOutValue);
  540. virtual const char* getImageAnimPrefix(U32 imageSlot, S32 imageShapeIndex);
  541. virtual void onImageAnimThreadChange(U32 imageSlot, S32 imageShapeIndex, ShapeBaseImageData::StateData* lastState, const char* anim, F32 pos, F32 timeScale, bool reset=false);
  542. virtual void onImageAnimThreadUpdate(U32 imageSlot, S32 imageShapeIndex, F32 dt);
  543. virtual void updateDamageLevel();
  544. virtual void updateDamageState();
  545. /// Set which client is controlling this player
  546. void setControllingClient(GameConnection* client);
  547. void calcClassRenderData();
  548. /// Play sound for foot contact.
  549. ///
  550. /// @param triggeredLeft If true, left foot hit; right otherwise.
  551. /// @param contactMaterial Material onto which the player stepped; may be NULL.
  552. /// @param contactObject Object onto which the player stepped; may be NULL.
  553. void playFootstepSound( bool triggeredLeft, Material* contactMaterial, SceneObject* contactObject );
  554. /// Play an impact sound.
  555. void playImpactSound();
  556. /// Are we in the process of dying?
  557. bool inDeathAnim();
  558. F32 deathDelta(Point3F &delta);
  559. void updateDeathOffsets();
  560. bool inSittingAnim();
  561. /// @name Water
  562. /// @{
  563. void updateSplash(); ///< Update the splash effect
  564. void updateFroth( F32 dt ); ///< Update any froth
  565. void updateWaterSounds( F32 dt ); ///< Update water sounds
  566. void createSplash( Point3F &pos, F32 speed ); ///< Creates a splash
  567. bool collidingWithWater( Point3F &waterHeight ); ///< Are we colliding with water?
  568. /// @}
  569. void disableHeadZCalc() { mUseHeadZCalc = false; }
  570. void enableHeadZCalc() { mUseHeadZCalc = true; }
  571. public:
  572. DECLARE_CONOBJECT(Player);
  573. Player();
  574. ~Player();
  575. static void consoleInit();
  576. /// @name Transforms
  577. /// @{
  578. void setTransform(const MatrixF &mat);
  579. void getEyeTransform(MatrixF* mat);
  580. void getEyeBaseTransform(MatrixF* mat, bool includeBank);
  581. void getRenderEyeTransform(MatrixF* mat);
  582. void getRenderEyeBaseTransform(MatrixF* mat, bool includeBank);
  583. void getCameraParameters(F32 *min, F32 *max, Point3F *offset, MatrixF *rot);
  584. void getMuzzleTransform(U32 imageSlot,MatrixF* mat);
  585. void getRenderMuzzleTransform(U32 imageSlot,MatrixF* mat);
  586. virtual void getMuzzleVector(U32 imageSlot,VectorF* vec);
  587. /// @}
  588. F32 getSpeed() const;
  589. Point3F getVelocity() const;
  590. void setVelocity(const VectorF& vel);
  591. /// Apply an impulse at the given point, with magnitude/direction of vec
  592. void applyImpulse(const Point3F& pos,const VectorF& vec);
  593. /// Get the rotation of the player
  594. const Point3F& getRotation() { return mRot; }
  595. /// Get the rotation of the head of the player
  596. const Point3F& getHeadRotation() { return mHead; }
  597. void getDamageLocation(const Point3F& in_rPos, const char *&out_rpVert, const char *&out_rpQuad);
  598. void allowAllPoses();
  599. void allowJumping(bool state) { mAllowJumping = state; }
  600. void allowJetJumping(bool state) { mAllowJetJumping = state; }
  601. void allowSprinting(bool state) { mAllowSprinting = state; }
  602. void allowCrouching(bool state) { mAllowCrouching = state; }
  603. void allowProne(bool state) { mAllowProne = state; }
  604. void allowSwimming(bool state) { mAllowSwimming = state; }
  605. bool canJump(); ///< Can the player jump?
  606. bool canJetJump(); ///< Can the player jet?
  607. bool canSwim(); ///< Can the player swim?
  608. bool canCrouch();
  609. bool canStand();
  610. bool canProne();
  611. bool canSprint();
  612. bool haveContact() const { return !mContactTimer; } ///< Is it in contact with something
  613. void getMuzzlePointAI( U32 imageSlot, Point3F *point );
  614. F32 getMaxForwardVelocity() const { return (mDataBlock != NULL ? mDataBlock->maxForwardSpeed : 0); }
  615. virtual bool isDisplacable() const;
  616. virtual Point3F getMomentum() const;
  617. virtual void setMomentum(const Point3F &momentum);
  618. virtual bool displaceObject(const Point3F& displaceVector);
  619. virtual bool getAIMove(Move*);
  620. bool checkDismountPosition(const MatrixF& oldPos, const MatrixF& newPos); ///< Is it safe to dismount here?
  621. //
  622. bool onAdd();
  623. void onRemove();
  624. bool onNewDataBlock( GameBaseData *dptr, bool reload );
  625. void onScaleChanged();
  626. Box3F mScaledBox;
  627. // Animation
  628. const char* getStateName();
  629. bool setActionThread(const char* sequence,bool hold,bool wait,bool fsp = false);
  630. const String& getArmThread() const;
  631. bool setArmThread(const char* sequence);
  632. // Object control
  633. void setControlObject(ShapeBase *obj);
  634. ShapeBase* getControlObject();
  635. //
  636. void updateWorkingCollisionSet();
  637. virtual void processTick(const Move *move);
  638. void interpolateTick(F32 delta);
  639. void advanceTime(F32 dt);
  640. bool castRay(const Point3F &start, const Point3F &end, RayInfo* info);
  641. bool buildPolyList(PolyListContext context, AbstractPolyList* polyList, const Box3F &box, const SphereF &sphere);
  642. void buildConvex(const Box3F& box, Convex* convex);
  643. bool isControlObject();
  644. void onCameraScopeQuery(NetConnection *cr, CameraScopeQuery *);
  645. void writePacketData(GameConnection *conn, BitStream *stream);
  646. void readPacketData (GameConnection *conn, BitStream *stream);
  647. U32 packUpdate (NetConnection *conn, U32 mask, BitStream *stream);
  648. void unpackUpdate(NetConnection *conn, BitStream *stream);
  649. virtual void prepRenderImage( SceneRenderState* state );
  650. virtual void renderConvex( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat );
  651. virtual void renderMountedImage( U32 imageSlot, TSRenderState &rstate, SceneRenderState *state );
  652. private:
  653. static void afx_consoleInit();
  654. void afx_init();
  655. U32 afx_packUpdate(NetConnection*, U32 mask, BitStream*, U32 retMask);
  656. void afx_unpackUpdate(NetConnection*, BitStream*);
  657. private:
  658. static bool sCorpsesHiddenFromRayCast;
  659. public:
  660. virtual void restoreAnimation(U32 tag);
  661. virtual U32 getAnimationID(const char* name);
  662. virtual U32 playAnimationByID(U32 anim_id, F32 pos, F32 rate, F32 trans, bool hold, bool wait, bool is_death_anim);
  663. virtual F32 getAnimationDurationByID(U32 anim_id);
  664. virtual bool isBlendAnimation(const char* name);
  665. virtual const char* getLastClipName(U32 clip_tag);
  666. virtual void unlockAnimation(U32 tag, bool force=false);
  667. virtual U32 lockAnimation();
  668. virtual bool isAnimationLocked() const { return ((anim_clip_flags & BLOCK_USER_CONTROL) != 0); }
  669. protected:
  670. bool overrideLookAnimation;
  671. F32 armLookOverridePos;
  672. F32 headVLookOverridePos;
  673. F32 headHLookOverridePos;
  674. public:
  675. void setLookAnimationOverride(bool flag);
  676. void copyHeadRotation(const Player* p) { mHead = p->mHead; }
  677. public:
  678. bool ignore_updates;
  679. void resetContactTimer() { mContactTimer = 0; }
  680. private:
  681. U8 move_trigger_states;
  682. U32 fx_s_triggers;
  683. U32 mark_fx_c_triggers;
  684. U32 fx_c_triggers;
  685. F32 z_velocity;
  686. bool mark_idle;
  687. F32 idle_timer;
  688. bool mark_s_landing;
  689. void process_client_triggers(bool triggeredLeft, bool triggeredRight);
  690. public:
  691. enum {
  692. // server events
  693. PLAYER_MOVE_TRIGGER_0 = BIT(0),
  694. PLAYER_MOVE_TRIGGER_1 = BIT(1),
  695. PLAYER_MOVE_TRIGGER_2 = BIT(2),
  696. PLAYER_MOVE_TRIGGER_3 = BIT(3),
  697. PLAYER_MOVE_TRIGGER_4 = BIT(4),
  698. PLAYER_MOVE_TRIGGER_5 = BIT(5),
  699. PLAYER_LANDING_S_TRIGGER = BIT(6),
  700. PLAYER_FIRE_S_TRIGGER = PLAYER_MOVE_TRIGGER_0,
  701. PLAYER_FIRE_ALT_S_TRIGGER = PLAYER_MOVE_TRIGGER_1,
  702. PLAYER_JUMP_S_TRIGGER = BIT(7),
  703. // client events
  704. PLAYER_LF_FOOT_C_TRIGGER = BIT(16),
  705. PLAYER_RT_FOOT_C_TRIGGER = BIT(17),
  706. PLAYER_LANDING_C_TRIGGER = BIT(18),
  707. PLAYER_IDLE_C_TRIGGER = BIT(19),
  708. };
  709. U32 getClientEventTriggers() const { return fx_c_triggers; }
  710. U32 getServerEventTriggers() const { return fx_s_triggers; }
  711. private:
  712. F32 speed_bias;
  713. F32 speed_bias_goal;
  714. bool override_movement;
  715. Point3F movement_data;
  716. U8 movement_op;
  717. U32 last_movement_tag;
  718. static U32 unique_movement_tag_counter;
  719. public:
  720. void setMovementSpeedBias(F32 bias);
  721. U32 setMovementOverride(F32 bias, const Point3F* mov=0, U32 op=1);
  722. void restoreMovement(U32 tag);
  723. private:
  724. S32 footfallDecalOverride;
  725. S32 footfallSoundOverride;
  726. S32 footfallDustOverride;
  727. bool noFootfallFX;
  728. public:
  729. void overrideFootfallFX(bool decals=true, bool sounds=true, bool dust=true);
  730. void restoreFootfallFX(bool decals=true, bool sounds=true, bool dust=true);
  731. };
  732. typedef Player::Pose PlayerPose;
  733. DefineEnumType( PlayerPose );
  734. #endif