Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1021 lines
38 KiB

  1. //===== Copyright 1996-2005, Valve Corporation, All rights reserved. ======//
  2. //
  3. // Purpose:
  4. //
  5. // $Workfile: $
  6. // $NoKeywords: $
  7. //===========================================================================//
  8. #ifndef C_BASEANIMATING_H
  9. #define C_BASEANIMATING_H
  10. #ifdef _WIN32
  11. #pragma once
  12. #endif
  13. #include "studio.h"
  14. #include "utlvector.h"
  15. #include "ragdoll.h"
  16. #include "mouthinfo.h"
  17. // Shared activities
  18. #include "ai_activity.h"
  19. #include "animationlayer.h"
  20. #include "sequence_Transitioner.h"
  21. #include "bone_accessor.h"
  22. #include "bone_merge_cache.h"
  23. #include "ragdoll_shared.h"
  24. #include "tier0/threadtools.h"
  25. #include "datacache/idatacache.h"
  26. #include "toolframework/itoolframework.h"
  27. #include "materialsystem/custommaterialowner.h"
  28. #define LIPSYNC_POSEPARAM_NAME "mouth"
  29. #define NUM_HITBOX_FIRES 10
  30. class C_BaseEntity;
  31. /*
  32. class C_BaseClientShader
  33. {
  34. virtual void RenderMaterial( C_BaseEntity *pEntity, int count, const vec4_t *verts, const vec4_t *normals, const vec2_t *texcoords, vec4_t *lightvalues );
  35. };
  36. */
  37. class IRagdoll;
  38. class C_ClientRagdoll;
  39. class CIKContext;
  40. class CIKState;
  41. class ConVar;
  42. class C_RopeKeyframe;
  43. class CBoneBitList;
  44. class CBoneList;
  45. class KeyValues;
  46. class CJiggleBones;
  47. class IBoneSetup;
  48. class C_BaseAnimatingOverlay;
  49. #if defined( _PS3 )
  50. class IBoneSetup_PS3;
  51. #endif
  52. FORWARD_DECLARE_HANDLE( memhandle_t );
  53. typedef unsigned short MDLHandle_t;
  54. extern ConVar vcollide_wireframe;
  55. extern IDataCache *datacache;
  56. struct ClientModelRenderInfo_t : public ModelRenderInfo_t
  57. {
  58. // Added space for lighting origin override. Just allocated space, need to set base pointer
  59. matrix3x4_t lightingOffset;
  60. // Added space for model to world matrix. Just allocated space, need to set base pointer
  61. matrix3x4_t modelToWorld;
  62. };
  63. struct RagdollInfo_t
  64. {
  65. bool m_bActive;
  66. float m_flSaveTime;
  67. int m_nNumBones;
  68. BoneVector m_rgBonePos[MAXSTUDIOBONES];
  69. BoneQuaternion m_rgBoneQuaternion[MAXSTUDIOBONES];
  70. };
  71. enum {
  72. ANIMLODFLAG_DISTANT = 0x01,
  73. ANIMLODFLAG_OUTSIDEVIEWFRUSTUM = 0x02,
  74. ANIMLODFLAG_INVISIBLELOCALPLAYER = 0x04,
  75. ANIMLODFLAG_DORMANT = 0x08,
  76. //ANIMLODFLAG_UNUSED = 0x10,
  77. //ANIMLODFLAG_UNUSED = 0x20,
  78. };
  79. class CAttachmentData
  80. {
  81. public:
  82. matrix3x4_t m_AttachmentToWorld;
  83. QAngle m_angRotation;
  84. Vector m_vOriginVelocity;
  85. int m_nLastFramecount : 31;
  86. bool m_bAnglesComputed : 1;
  87. };
  88. typedef unsigned int ClientSideAnimationListHandle_t;
  89. #define INVALID_CLIENTSIDEANIMATION_LIST_HANDLE (ClientSideAnimationListHandle_t)~0
  90. class C_BaseAnimating : public C_BaseEntity, public CCustomMaterialOwner
  91. {
  92. public:
  93. DECLARE_CLASS( C_BaseAnimating, C_BaseEntity );
  94. DECLARE_CLIENTCLASS();
  95. DECLARE_PREDICTABLE();
  96. DECLARE_INTERPOLATION();
  97. DECLARE_FRIEND_DATADESC_ACCESS();
  98. DECLARE_ENT_SCRIPTDESC();
  99. enum
  100. {
  101. NUM_POSEPAREMETERS = 24,
  102. NUM_BONECTRLS = 4
  103. };
  104. // Inherited from IClientUnknown
  105. public:
  106. virtual IClientModelRenderable* GetClientModelRenderable();
  107. // Inherited from IClientModelRenderable
  108. public:
  109. virtual bool GetRenderData( void *pData, ModelDataCategory_t nCategory );
  110. public:
  111. C_BaseAnimating();
  112. ~C_BaseAnimating();
  113. #ifdef DEBUG
  114. CUtlVector<float> m_flBoneSetupPerfHistory;
  115. #endif
  116. virtual C_BaseAnimating* GetBaseAnimating() { return this; }
  117. bool UsesPowerOfTwoFrameBufferTexture( void );
  118. int GetRenderFlags( void );
  119. virtual bool Interpolate( float currentTime );
  120. virtual bool Simulate();
  121. virtual void Release();
  122. float GetAnimTimeInterval( void ) const;
  123. // Get bone controller values.
  124. virtual void GetBoneControllers(float controllers[MAXSTUDIOBONECTRLS]);
  125. virtual float SetBoneController ( int iController, float flValue );
  126. LocalFlexController_t GetNumFlexControllers( void );
  127. const char *GetFlexDescFacs( int iFlexDesc );
  128. const char *GetFlexControllerName( LocalFlexController_t iFlexController );
  129. const char *GetFlexControllerType( LocalFlexController_t iFlexController );
  130. virtual void GetAimEntOrigin( IClientEntity *pAttachedTo, Vector *pAbsOrigin, QAngle *pAbsAngles );
  131. // Computes a box that surrounds all hitboxes
  132. bool ComputeHitboxSurroundingBox( Vector *pVecWorldMins, Vector *pVecWorldMaxs );
  133. bool ComputeEntitySpaceHitboxSurroundingBox( Vector *pVecWorldMins, Vector *pVecWorldMaxs );
  134. // Gets the hitbox-to-world transforms, returns false if there was a problem
  135. bool HitboxToWorldTransforms( matrix3x4_t *pHitboxToWorld[MAXSTUDIOBONES] );
  136. // base model functionality
  137. float ClampCycle( float cycle, bool isLooping );
  138. virtual void GetPoseParameters( CStudioHdr *pStudioHdr, float poseParameter[MAXSTUDIOPOSEPARAM] );
  139. void CalcBoneMerge( int boneMask );
  140. virtual void BuildTransformations( CStudioHdr *pStudioHdr, BoneVector *pos, BoneQuaternion q[], const matrix3x4_t& cameraTransform, int boneMask, CBoneBitList &boneComputed );
  141. void BuildJiggleTransformations( int boneIndex, const mstudiojigglebone_t *jiggleParams, const matrix3x4_t &goalMX, bool coordSystemIsFlipped );
  142. virtual void ApplyBoneMatrixTransform( matrix3x4_t& transform );
  143. virtual int VPhysicsGetObjectList( IPhysicsObject **pList, int listMax );
  144. // model specific
  145. virtual bool SetupBones( matrix3x4a_t *pBoneToWorldOut, int nMaxBones, int boneMask, float currentTime );
  146. #if defined( _PS3 )
  147. virtual bool StandardBlendingRules_Pass1( CStudioHdr *hdr, float currentTime, int nMaxBones, int boneMask, int bonesMaskNeedRecalc, int oldReadableBones, matrix3x4_t &parentTransform );
  148. virtual bool StandardBlendingRules_Pass2( void );
  149. virtual bool SetupBones_Pass1( float currentTime );
  150. virtual bool SetupBones_Pass2( void );
  151. void MaintainSequenceTransitions_AddPoseCalls( IBoneSetup_PS3 &boneSetup, float flCycle, BoneVector pos[], BoneQuaternion q[] );
  152. virtual void AccumulateLayers_AddPoseCalls( IBoneSetup_PS3 &boneSetup, BoneVector pos[], BoneQuaternion q[], float currentTime );
  153. #endif
  154. virtual void UpdateIKLocks( float currentTime );
  155. virtual void CalculateIKLocks( float currentTime );
  156. virtual int DrawModel( int flags, const RenderableInstance_t &instance );
  157. virtual int InternalDrawModel( int flags, const RenderableInstance_t &instance );
  158. virtual bool OnInternalDrawModel( ClientModelRenderInfo_t *pInfo );
  159. virtual bool OnPostInternalDrawModel( ClientModelRenderInfo_t *pInfo );
  160. void DoInternalDrawModel( class IMatRenderContext *pRenderContext, ClientModelRenderInfo_t *pInfo, DrawModelState_t *pState, matrix3x4_t *pBoneToWorldArray = NULL );
  161. //
  162. virtual CMouthInfo *GetMouth();
  163. virtual void ControlMouth( CStudioHdr *pStudioHdr );
  164. virtual void DoExtraBoneProcessing( CStudioHdr *pStudioHdr, BoneVector pos[], BoneQuaternion q[], matrix3x4a_t boneToWorld[], CBoneBitList &boneComputed, CIKContext *pIKContext ) { Assert(false); }
  165. // override in sub-classes
  166. virtual void DoAnimationEvents( CStudioHdr *pStudio );
  167. virtual void FireEvent( const Vector& origin, const QAngle& angles, int event, const char *options );
  168. virtual void FireObsoleteEvent( const Vector& origin, const QAngle& angles, int event, const char *options );
  169. virtual const char* ModifyEventParticles( const char* token ) { return token; }
  170. // Parses and distributes muzzle flash events
  171. virtual bool DispatchMuzzleEffect( const char *options, bool isFirstPerson );
  172. virtual void EjectParticleBrass( const char *pEffectName, const int iAttachment );
  173. // virtual void AllocateMaterials( void );
  174. // virtual void FreeMaterials( void );
  175. virtual CStudioHdr *OnNewModel( void );
  176. CStudioHdr *GetModelPtr() const;
  177. virtual void InvalidateMdlCache() { UnlockStudioHdr(); delete m_pStudioHdr; m_pStudioHdr = NULL; }
  178. virtual void SetPredictable( bool state );
  179. void UseClientSideAnimation();
  180. bool IsUsingClientSideAnimation() { return m_bClientSideAnimation; }
  181. // C_BaseClientShader **p_ClientShaders;
  182. virtual void StandardBlendingRules( CStudioHdr *pStudioHdr, BoneVector pos[], BoneQuaternionAligned q[], float currentTime, int boneMask );
  183. void UnragdollBlend( CStudioHdr *hdr, BoneVector pos[], BoneQuaternion q[], float currentTime );
  184. bool m_bMaintainSequenceTransitions; // kill-switch so entities can opt out of automatic transitions
  185. void MaintainSequenceTransitions( IBoneSetup &boneSetup, float flCycle, BoneVector pos[], BoneQuaternion q[] );
  186. virtual void AccumulateLayers( IBoneSetup &boneSetup, BoneVector pos[], BoneQuaternion q[], float currentTime );
  187. // Attachments
  188. virtual int LookupAttachment( const char *pAttachmentName );
  189. int LookupRandomAttachment( const char *pAttachmentNameSubstring );
  190. int LookupPoseParameter( CStudioHdr *pStudioHdr, const char *szName );
  191. inline int LookupPoseParameter( const char *szName ) { return LookupPoseParameter(GetModelPtr(), szName); }
  192. float SetPoseParameter( CStudioHdr *pStudioHdr, const char *szName, float flValue );
  193. inline float SetPoseParameter( const char *szName, float flValue ) { return SetPoseParameter( GetModelPtr(), szName, flValue ); }
  194. float SetPoseParameter( CStudioHdr *pStudioHdr, int iParameter, float flValue );
  195. inline float SetPoseParameter( int iParameter, float flValue ) { return SetPoseParameter( GetModelPtr(), iParameter, flValue ); }
  196. float GetPoseParameter( int iParameter );
  197. float GetPoseParameterRaw( int iPoseParameter ); // returns raw 0..1 value
  198. bool GetPoseParameterRange( int iPoseParameter, float &minValue, float &maxValue );
  199. int LookupBone( const char *szName );
  200. void GetBonePosition( int iBone, Vector &origin, QAngle &angles );
  201. void GetBonePosition( int iBone, Vector &origin );
  202. void GetBoneTransform( int iBone, matrix3x4_t &pBoneToWorld );
  203. int GetHitboxBone( int hitboxIndex );
  204. void GetHitboxBonePosition( int iBone, Vector &origin, QAngle &angles, QAngle hitboxOrientation );
  205. void GetHitboxBoneTransform( int iBone, QAngle hitboxOrientation, matrix3x4_t &pOut );
  206. void CopySequenceTransitions( C_BaseAnimating *pCopyFrom );
  207. //bool solveIK(float a, float b, const Vector &Foot, const Vector &Knee1, Vector &Knee2);
  208. //void DebugIK( mstudioikchain_t *pikchain );
  209. // Bone attachments
  210. virtual void AttachEntityToBone( C_BaseAnimating* attachTarget, int boneIndexAttached=-1, Vector bonePosition=Vector(0,0,0), QAngle boneAngles=QAngle(0,0,0) );
  211. void AddBoneAttachment( C_BaseAnimating* newBoneAttachment );
  212. void RemoveBoneAttachment( C_BaseAnimating* boneAttachment );
  213. void RemoveBoneAttachments();
  214. void DestroyBoneAttachments();
  215. void MoveBoneAttachments( C_BaseAnimating* attachTarget );
  216. int GetNumBoneAttachments();
  217. C_BaseAnimating* GetBoneAttachment( int i );
  218. virtual void NotifyBoneAttached( C_BaseAnimating* attachTarget );
  219. virtual void PostBuildTransformations( CStudioHdr *pStudioHdr, BoneVector *pos, BoneQuaternion q[] ) {}
  220. private:
  221. virtual void UpdateBoneAttachments( void );
  222. public:
  223. virtual void PreDataUpdate( DataUpdateType_t updateType );
  224. virtual void PostDataUpdate( DataUpdateType_t updateType );
  225. virtual void NotifyShouldTransmit( ShouldTransmitState_t state );
  226. virtual void OnPreDataChanged( DataUpdateType_t updateType );
  227. virtual void OnDataChanged( DataUpdateType_t updateType );
  228. // This can be used to force client side animation to be on. Only use if you know what you're doing!
  229. // Normally, the server entity should set this.
  230. void ForceClientSideAnimationOn();
  231. void AddToClientSideAnimationList();
  232. void RemoveFromClientSideAnimationList();
  233. virtual bool IsSelfAnimating();
  234. virtual void ResetLatched();
  235. // implements these so ragdolls can handle frustum culling & leaf visibility
  236. virtual Vector GetThirdPersonViewPosition( void );
  237. virtual void GetRenderBounds( Vector& theMins, Vector& theMaxs );
  238. virtual const Vector& GetRenderOrigin( void );
  239. virtual const QAngle& GetRenderAngles( void );
  240. virtual bool GetSoundSpatialization( SpatializationInfo_t& info );
  241. // Attachments.
  242. bool GetAttachment( const char *szName, Vector &absOrigin );
  243. bool GetAttachment( const char *szName, Vector &absOrigin, QAngle &absAngles );
  244. // Inherited from C_BaseEntity
  245. virtual bool GetAttachment( int number, Vector &origin );
  246. virtual bool GetAttachment( int number, Vector &origin, QAngle &angles );
  247. virtual bool GetAttachment( int number, matrix3x4_t &matrix );
  248. virtual bool GetAttachmentVelocity( int number, Vector &originVel, Quaternion &angleVel );
  249. virtual bool ComputeLightingOrigin( int nAttachmentIndex, Vector modelLightingCenter, const matrix3x4_t &matrix, Vector &transformedLightingCenter );
  250. virtual void InvalidateAttachments();
  251. // Returns the attachment in local space
  252. bool GetAttachmentLocal( int iAttachment, matrix3x4_t &attachmentToLocal );
  253. bool GetAttachmentLocal( int iAttachment, Vector &origin, QAngle &angles );
  254. bool GetAttachmentLocal( int iAttachment, Vector &origin );
  255. // Should this object cast render-to-texture shadows?
  256. virtual ShadowType_t ShadowCastType();
  257. // Should we collide?
  258. virtual CollideType_t GetCollideType( void );
  259. virtual bool TestCollision( const Ray_t &ray, unsigned int fContentsMask, trace_t& tr );
  260. virtual bool TestHitboxes( const Ray_t &ray, unsigned int fContentsMask, trace_t& tr );
  261. // returns true if we are of type C_ClientRagdoll
  262. virtual bool IsClientRagdoll() const { return false; }
  263. // returns true if we're currently being ragdolled
  264. bool IsRagdoll() const;
  265. virtual C_BaseAnimating *BecomeRagdollOnClient();
  266. virtual C_ClientRagdoll *CreateClientRagdoll( bool bRestoring = false );
  267. C_BaseAnimating *CreateRagdollCopy();
  268. bool InitAsClientRagdoll( const matrix3x4_t *pDeltaBones0, const matrix3x4_t *pDeltaBones1, const matrix3x4_t *pCurrentBonePosition, float boneDt, Vector vecForceOverride, bool bleedOut=true );
  269. bool InitAsClientRagdoll( const matrix3x4_t *pDeltaBones0, const matrix3x4_t *pDeltaBones1, const matrix3x4_t *pCurrentBonePosition, float boneDt, bool bleedOut=true );
  270. void IgniteRagdoll( C_BaseAnimating *pSource );
  271. void TransferDissolveFrom( C_BaseAnimating *pSource );
  272. virtual void SaveRagdollInfo( int numbones, const matrix3x4_t &cameraTransform, CBoneAccessor &pBoneToWorld );
  273. virtual bool RetrieveRagdollInfo( BoneVector *pos, BoneQuaternion *q );
  274. virtual void Clear( void );
  275. void ClearRagdoll();
  276. void CreateUnragdollInfo( C_BaseAnimating *pRagdoll );
  277. void ForceSetupBonesAtTime( matrix3x4a_t *pBonesOut, float flTime );
  278. virtual void GetRagdollInitBoneArrays( matrix3x4a_t *pDeltaBones0, matrix3x4a_t *pDeltaBones1, matrix3x4a_t *pCurrentBones, float boneDt );
  279. // For shadows rendering the correct body + sequence...
  280. virtual int GetBody() { return m_nBody; }
  281. virtual int GetSkin() { return m_nSkin; }
  282. bool IsOnFire() { return ( (GetFlags() & FL_ONFIRE) != 0 ); }
  283. float GetFrozenAmount() { return m_flFrozen; }
  284. inline float GetPlaybackRate() const;
  285. inline void SetPlaybackRate( float rate );
  286. void SetModelScale( float scale, ModelScaleType_t scaleType = HIERARCHICAL_MODEL_SCALE );
  287. inline float GetModelScale() const { return m_flModelScale; }
  288. float GetModelHierarchyScale() const; // Get the overall scale of the entire hierarchy (model scale can be local, per-bone)
  289. ModelScaleType_t GetModelScaleType() const;
  290. void SetModelScaleType( ModelScaleType_t scaleType );
  291. inline bool IsModelScaleFractional() const; /// very fast way to ask if the model scale is < 1.0f (faster than if (GetModelScale() < 1.0f) )
  292. int GetSequence();
  293. virtual void SetSequence(int nSequence);
  294. inline void ResetSequence(int nSequence);
  295. void OnNewSequence( );
  296. float GetSequenceGroundSpeed( CStudioHdr *pStudioHdr, int iSequence );
  297. inline float GetSequenceGroundSpeed( int iSequence ) { return GetSequenceGroundSpeed(GetModelPtr(), iSequence); }
  298. bool IsSequenceLooping( CStudioHdr *pStudioHdr, int iSequence );
  299. inline bool IsSequenceLooping( int iSequence ) { return IsSequenceLooping(GetModelPtr(),iSequence); }
  300. float GetSequenceMoveDist( CStudioHdr *pStudioHdr, int iSequence );
  301. void GetSequenceLinearMotion( int iSequence, Vector *pVec );
  302. float GetSequenceLinearMotionAndDuration( int iSequence, Vector *pVec );
  303. bool GetSequenceMovement( int nSequence, float fromCycle, float toCycle, Vector &deltaPosition, QAngle &deltaAngles );
  304. void GetBlendedLinearVelocity( Vector *pVec );
  305. void SetMovementPoseParams( const Vector &vecLocalVelocity, int iMoveX, int iMoveY, int iXSign = 1, int iYSign = 1 );
  306. int LookupSequence ( const char *label );
  307. int LookupSequence ( CStudioHdr* pHdr, const char *label );
  308. int LookupActivity( const char *label );
  309. float GetFirstSequenceAnimTag( int sequence, int nDesiredTag, float flStart = 0, float flEnd = 1 );
  310. float GetAnySequenceAnimTag( int sequence, int nDesiredTag, float flDefault );
  311. char const *GetSequenceName( int iSequence );
  312. char const *GetSequenceActivityName( int iSequence );
  313. Activity GetSequenceActivity( int iSequence );
  314. virtual void StudioFrameAdvance(); // advance animation frame to some time in the future
  315. void ExtractBbox( int nSequence, Vector &mins, Vector &maxs );
  316. // Clientside animation
  317. virtual float FrameAdvance( float flInterval = 0.0f );
  318. virtual float GetSequenceCycleRate( CStudioHdr *pStudioHdr, int iSequence );
  319. virtual float GetLayerSequenceCycleRate( C_AnimationLayer *pLayer, int iSequence ) { return GetSequenceCycleRate(GetModelPtr(),iSequence); }
  320. virtual void UpdateClientSideAnimation();
  321. void ClientSideAnimationChanged();
  322. virtual unsigned int ComputeClientSideAnimationFlags();
  323. float GetGroundSpeed( void ) { return m_flGroundSpeed; }
  324. virtual void ReachedEndOfSequence() { return; }
  325. void SetCycle( float flCycle );
  326. float GetCycle() const;
  327. void SetBodygroup( int iGroup, int iValue );
  328. int GetBodygroup( int iGroup );
  329. void SetBodygroupPreset( char const *szName );
  330. void SetSkin( int iSkin );
  331. void SetBody( int iBody );
  332. const char *GetBodygroupName( int iGroup );
  333. int FindBodygroupByName( const char *name );
  334. int GetBodygroupCount( int iGroup );
  335. int GetNumBodyGroups( void );
  336. void SetHitboxSet( int setnum );
  337. void SetHitboxSetByName( const char *setname );
  338. int GetHitboxSet( void );
  339. char const *GetHitboxSetName( void );
  340. int GetHitboxSetCount( void );
  341. void DrawClientHitboxes( float duration = 0.0f, bool monocolor = false );
  342. void DrawSkeleton( CStudioHdr const* pHdr, int iBoneMask ) const;
  343. C_BaseAnimating* FindFollowedEntity();
  344. virtual bool IsActivityFinished( void ) { return m_bSequenceFinished; }
  345. inline bool IsSequenceFinished( void );
  346. inline bool SequenceLoops( void ) { return m_bSequenceLoops; }
  347. // All view model attachments origins are stretched so you can place entities at them and
  348. // they will match up with where the attachment winds up being drawn on the view model, since
  349. // the view models are drawn with a different FOV.
  350. //
  351. // If you're drawing something inside of a view model's DrawModel() function, then you want the
  352. // original attachment origin instead of the adjusted one. To get that, call this on the
  353. // adjusted attachment origin.
  354. virtual void UncorrectViewModelAttachment( Vector &vOrigin ) {}
  355. // Call this if SetupBones() has already been called this frame but you need to move the
  356. // entity and rerender.
  357. void InvalidateBoneCache();
  358. bool IsBoneCacheValid() const; // Returns true if the bone cache is considered good for this frame.
  359. void GetCachedBoneMatrix( int boneIndex, matrix3x4_t &out );
  360. // Wrappers for CBoneAccessor.
  361. const matrix3x4a_t& GetBone( int iBone ) const;
  362. matrix3x4a_t& GetBoneForWrite( int iBone );
  363. matrix3x4a_t* GetBoneArrayForWrite();
  364. bool isBoneAvailableForRead( int iBone ) const;
  365. bool isBoneAvailableForWrite( int iBone ) const;
  366. // Used for debugging. Will produce asserts if someone tries to setup bones or
  367. // attachments before it's allowed.
  368. // Use the "AutoAllowBoneAccess" class to auto push/pop bone access.
  369. // Use a distinct "tag" when pushing/popping - asserts when push/pop tags do not match.
  370. struct AutoAllowBoneAccess
  371. {
  372. AutoAllowBoneAccess( bool bAllowForNormalModels, bool bAllowForViewModels );
  373. ~AutoAllowBoneAccess( void );
  374. };
  375. static void PushAllowBoneAccess( bool bAllowForNormalModels, bool bAllowForViewModels, char const *tagPush );
  376. static void PopBoneAccess( char const *tagPop );
  377. static void ThreadedBoneSetup();
  378. static bool InThreadedBoneSetup();
  379. static void InitBoneSetupThreadPool();
  380. static void ShutdownBoneSetupThreadPool();
  381. void MarkForThreadedBoneSetup();
  382. static void SetupBonesOnBaseAnimating( C_BaseAnimating *&pBaseAnimating );
  383. #if defined( _PS3 )
  384. void SaveSetupBones_PS3( void );
  385. void RestoreSetupBones_PS3( void );
  386. static int InitAllPS3BoneJobs( int nCount );
  387. void PS3BoneJob_PreInit( void );
  388. void PS3BoneJob_Start( float currentTime );
  389. void PS3BoneJob_End( void );
  390. void PS3BoneJob_Run( CStudioHdr *hdr, float currentTime, float fCycle, int nMaxBones, int boneMask, int bonesMaskNeedRecalc, int oldReadableBones, matrix3x4_t &parentTransform, float* poseparam );
  391. void PS3BoneJob_WaitForFinish( void );
  392. void PS3BoneJob_RestartPPU( void );
  393. static void ThreadedBoneSetup_PS3( int nCount );
  394. static int SetupBonesOnBaseAnimating_PS3( C_BaseAnimating *&pBaseAnimating, int nGen );
  395. #endif
  396. // Invalidate bone caches so all SetupBones() calls force bone transforms to be regenerated.
  397. static void InvalidateBoneCaches();
  398. // Enable/Disable use of stale data, instead of updating contents of bonecache
  399. static void EnableNewBoneSetupRequest( bool bEnable ) { s_bEnableNewBoneSetupRequest = bEnable; };
  400. // Enable/Disable Invalidation of Bone Caches
  401. static void EnableInvalidateBoneCache( bool bEnable ) { s_bEnableInvalidateBoneCache = bEnable; };
  402. // Purpose: My physics object has been updated, react or extract data
  403. virtual void VPhysicsUpdate( IPhysicsObject *pPhysics );
  404. void DisableMuzzleFlash(); // Turn off the muzzle flash (ie: signal that we handled the server's event).
  405. virtual void DoMuzzleFlash(); // Force a muzzle flash event. Note: this only QUEUES an event, so
  406. // ProcessMuzzleFlashEvent will get called later.
  407. bool ShouldMuzzleFlash() const; // Is the muzzle flash event on?
  408. // This is called to do the actual muzzle flash effect.
  409. virtual void ProcessMuzzleFlashEvent();
  410. // Update client side animations
  411. static void UpdateClientSideAnimations();
  412. // Load the model's keyvalues section and create effects listed inside it
  413. void InitModelEffects( void );
  414. // Sometimes the server wants to update the client's cycle to get the two to run in sync (for proper hit detection)
  415. virtual void SetServerIntendedCycle( float intended ) { intended; }
  416. virtual float GetServerIntendedCycle( void ) { return -1.0f; }
  417. // For prediction
  418. int SelectWeightedSequence ( int activity );
  419. int SelectWeightedSequenceFromModifiers( Activity activity, CUtlSymbol *pActivityModifiers, int iModifierCount );
  420. void ResetSequenceInfo( void );
  421. float SequenceDuration( void );
  422. float SequenceDuration( CStudioHdr *pStudioHdr, int iSequence );
  423. inline float SequenceDuration( int iSequence ) { return SequenceDuration(GetModelPtr(), iSequence); }
  424. int FindTransitionSequence( int iCurrentSequence, int iGoalSequence, int *piDir );
  425. void RagdollMoved( void );
  426. virtual void GetToolRecordingState( KeyValues *msg );
  427. virtual void CleanupToolRecordingState( KeyValues *msg );
  428. void SetReceivedSequence( void );
  429. virtual bool ShouldResetSequenceOnNewModel( void );
  430. // View models say yes to this.
  431. virtual bool IsViewModel( void ) const;
  432. virtual bool ShouldFlipModel( void ) { return false; }
  433. // viewmodel or viewmodelattachmentmodel or lowerbody
  434. virtual bool IsViewModelOrAttachment( void ) const;
  435. void EnableJiggleBones( void );
  436. void DisableJiggleBones( void );
  437. void ScriptSetPoseParameter( const char *szName, float fValue );
  438. void SetRenderOriginOverride( const Vector &vec );
  439. void DisableRenderOriginOverride( void );
  440. bool IsUsingRenderOriginOverride( void ) { return m_vecRenderOriginOverride != vec3_invalid; }
  441. virtual C_BaseAnimating * GetBoneSetupDependancy( void ) { return GetMoveParent() ? GetMoveParent()->GetBaseAnimating() : NULL; }
  442. bool GetRootBone( matrix3x4_t &rootBone );
  443. inline void SetUseParentLightingOrigin( bool value ){ m_bUseParentLightingOrigin = value; }
  444. virtual void SetCustomMaterial( ICustomMaterial *pCustomMaterial, int nIndex = 0 ) OVERRIDE;
  445. virtual void SetAllowFastPath( bool bAllow ) { m_bCanUseFastPath = bAllow; }
  446. protected:
  447. // View models scale their attachment positions to account for FOV. To get the unmodified
  448. // attachment position (like if you're rendering something else during the view model's DrawModel call),
  449. // use TransformViewModelAttachmentToWorld.
  450. virtual void FormatViewModelAttachment( int nAttachment, matrix3x4_t &attachmentToWorld ) {}
  451. bool IsBoneAccessAllowed() const;
  452. CMouthInfo& MouthInfo();
  453. // Models used in a ModelPanel say yes to this
  454. virtual bool IsMenuModel() const;
  455. // Allow studio models to tell C_BaseEntity what their m_nBody value is
  456. virtual int GetStudioBody( void ) { return m_nBody; }
  457. virtual bool CalcAttachments();
  458. virtual bool ComputeStencilState( ShaderStencilState_t *pStencilState );
  459. virtual bool WantsInterpolatedVars() { return true; }
  460. virtual void ResetSequenceLooping() { m_bSequenceFinished = false; }
  461. private:
  462. // This method should return true if the bones have changed + SetupBones needs to be called
  463. virtual float LastBoneChangedTime() { return FLT_MAX; }
  464. CBoneList* RecordBones( CStudioHdr *hdr, matrix3x4_t *pBoneState );
  465. bool PutAttachment( int number, const matrix3x4_t &attachmentToWorld );
  466. void TermRopes();
  467. void DelayedInitModelEffects( void );
  468. void ParseModelEffects( KeyValues *modelKeyValues );
  469. void UpdateRelevantInterpolatedVars();
  470. void AddBaseAnimatingInterpolatedVars();
  471. void RemoveBaseAnimatingInterpolatedVars();
  472. void LockStudioHdr();
  473. void UnlockStudioHdr();
  474. public:
  475. CRagdoll *m_pRagdoll;
  476. CBaseAnimating *m_pClientsideRagdoll;
  477. // Hitbox set to use (default 0)
  478. int m_nHitboxSet;
  479. CSequenceTransitioner m_SequenceTransitioner;
  480. private:
  481. // BEGIN PREDICTION DATA COMPACTION (these fields are together to allow for faster copying in prediction system)
  482. // FTYPEDESC_INSENDTABLE STUFF
  483. protected:
  484. //float m_flCycle;
  485. // This needs to be ranged checked because some interpolation edge cases
  486. // can assign it to values far out of range. Interpolation vars will only
  487. // clamp range checked vars.
  488. CRangeCheckedVar<float, -2, 2, 0> m_flCycle;
  489. float m_flPlaybackRate;// Animation playback framerate
  490. // FTYPEDESC_INSENDTABLE STUFF (end)
  491. public:
  492. int m_nSkin;// Texture group to use
  493. int m_nBody;// Object bodygroup
  494. int m_nCustomBlendingRuleMask;
  495. unsigned int m_nAnimLODflags;
  496. unsigned int m_nAnimLODflagsOld;
  497. inline void SetAnimLODflag( unsigned int nNewFlag ) { m_nAnimLODflags |= (nNewFlag); }
  498. inline void UnSetAnimLODflag( unsigned int nNewFlag ) { m_nAnimLODflags &= (~nNewFlag); }
  499. inline bool IsAnimLODflagSet( unsigned int nFlag ) { return (m_nAnimLODflags & (nFlag)) != 0; }
  500. inline void ClearAnimLODflags( void ) { m_nAnimLODflags = 0; }
  501. int m_nComputedLODframe;
  502. float m_flDistanceFromCamera;
  503. protected:
  504. int m_nNewSequenceParity;
  505. int m_nResetEventsParity;
  506. int m_nPrevNewSequenceParity;
  507. int m_nPrevResetEventsParity;
  508. float m_flEncodedController[MAXSTUDIOBONECTRLS];
  509. private:
  510. // This is compared against m_nOldMuzzleFlashParity to determine if the entity should muzzle flash.
  511. unsigned char m_nMuzzleFlashParity;
  512. // END PREDICTION DATA COMPACTION
  513. bool ShouldSkipAnimationFrame( float currentTime );
  514. int m_nLastNonSkippedFrame;
  515. BoneVector m_pos_cached[MAXSTUDIOBONES];
  516. BoneQuaternionAligned m_q_cached[MAXSTUDIOBONES];
  517. protected:
  518. CIKContext *m_pIk;
  519. int m_iEyeAttachment;
  520. // Decomposed ragdoll info
  521. bool m_bStoreRagdollInfo;
  522. RagdollInfo_t *m_pRagdollInfo;
  523. Vector m_vecForce;
  524. int m_nForceBone;
  525. // Is bone cache valid
  526. // bone transformation matrix
  527. unsigned long m_iMostRecentModelBoneCounter;
  528. unsigned long m_iMostRecentBoneSetupRequest;
  529. C_BaseAnimating * m_pNextForThreadedBoneSetup;
  530. int m_iPrevBoneMask;
  531. int m_iAccumulatedBoneMask;
  532. static bool s_bEnableInvalidateBoneCache;
  533. static bool s_bEnableNewBoneSetupRequest;
  534. CBoneAccessor m_BoneAccessor;
  535. CThreadFastMutex m_BoneSetupLock;
  536. ClientSideAnimationListHandle_t m_ClientSideAnimationListHandle;
  537. // Client-side animation
  538. bool m_bClientSideFrameReset;
  539. // Bone attachments. Used for attaching one BaseAnimating to another's bones.
  540. // Client side only.
  541. CUtlVector<CHandle<C_BaseAnimating> > m_BoneAttachments;
  542. int m_boneIndexAttached;
  543. Vector m_bonePosition;
  544. QAngle m_boneAngles;
  545. CHandle<C_BaseAnimating> m_pAttachedTo;
  546. protected:
  547. float m_flFrozen;
  548. // Can we use the fast rendering path?
  549. bool m_bCanUseFastPath;
  550. private:
  551. float m_flGroundSpeed; // computed linear movement rate for current sequence
  552. float m_flLastEventCheck; // cycle index of when events were last checked
  553. bool m_bSequenceFinished;// flag set when StudioAdvanceFrame moves across a frame boundry
  554. bool m_bSequenceLoops; // true if the sequence loops
  555. bool m_bIsUsingRelativeLighting;
  556. // Mouth lipsync/envelope following values
  557. CMouthInfo m_mouth;
  558. CNetworkVar( float, m_flModelScale );
  559. CNetworkVar( ModelScaleType_t, m_ScaleType );
  560. // Ropes that got spawned when the model was created.
  561. CUtlLinkedList<C_RopeKeyframe*,unsigned short> m_Ropes;
  562. // event processing info
  563. float m_flPrevEventCycle;
  564. int m_nEventSequence;
  565. // Animation blending factors
  566. float m_flPoseParameter[MAXSTUDIOPOSEPARAM];
  567. CInterpolatedVarArray< float, MAXSTUDIOPOSEPARAM > m_iv_flPoseParameter;
  568. float m_flOldPoseParameters[MAXSTUDIOPOSEPARAM];
  569. CInterpolatedVarArray< float, MAXSTUDIOBONECTRLS > m_iv_flEncodedController;
  570. float m_flOldEncodedController[MAXSTUDIOBONECTRLS];
  571. // Clientside animation
  572. bool m_bClientSideAnimation;
  573. bool m_bLastClientSideFrameReset;
  574. Vector m_vecPreRagdollMins;
  575. Vector m_vecPreRagdollMaxs;
  576. bool m_builtRagdoll;
  577. bool m_bReceivedSequence;
  578. bool m_bIsStaticProp;
  579. // Current animation sequence
  580. int m_nSequence;
  581. // Current cycle location from server
  582. protected:
  583. CInterpolatedVar< CRangeCheckedVar<float, -2, 2, 0> > m_iv_flCycle;
  584. //CInterpolatedVar< float > m_iv_flCycle;
  585. float m_flOldCycle;
  586. float m_prevClientCycle;
  587. float m_prevClientAnimTime;
  588. // True if bone setup should latch bones for demo polish subsystem
  589. bool m_bBonePolishSetup;
  590. virtual bool UpdateBlending( int flags, const RenderableInstance_t &instance );
  591. void CheckIfEntityShouldForceRTTShadows( void );
  592. ShadowType_t GetShadowCastTypeForStudio( CStudioHdr *pStudioHdr );
  593. bool m_bForceRTTShadows;
  594. private:
  595. int m_nPrevBody;
  596. int m_nPrevSkin;
  597. float m_flOldModelScale;
  598. int m_nOldSequence;
  599. CBoneMergeCache *m_pBoneMergeCache; // This caches the strcmp lookups that it has to do
  600. // when merg
  601. CUtlVector< matrix3x4a_t, CUtlMemoryAligned<matrix3x4a_t,16> > m_CachedBoneData; // never access this directly. Use m_BoneAccessor.
  602. float m_flLastBoneSetupTime;
  603. CJiggleBones *m_pJiggleBones;
  604. bool m_isJiggleBonesEnabled;
  605. // Calculated attachment points
  606. CUtlVector<CAttachmentData> m_Attachments;
  607. void SetupBones_AttachmentHelper( CStudioHdr *pStudioHdr );
  608. EHANDLE m_hLightingOrigin;
  609. unsigned char m_nOldMuzzleFlashParity;
  610. bool m_bInitModelEffects;
  611. static bool m_bBoneListInUse;
  612. static CBoneList m_recordingBoneList;
  613. bool m_bSuppressAnimSounds;
  614. private:
  615. mutable CStudioHdr *m_pStudioHdr;
  616. mutable MDLHandle_t m_hStudioHdr;
  617. CThreadFastMutex m_StudioHdrInitLock;
  618. CUtlReference<CNewParticleEffect> m_ejectBrassEffect;
  619. int m_iEjectBrassAttachment;
  620. Vector m_vecRenderOriginOverride;
  621. bool m_bUseParentLightingOrigin;
  622. #if defined( DBGFLAG_ASSERT )
  623. Vector m_vBoneSetupCachedOrigin;
  624. QAngle m_qBoneSetupCachedAngles;
  625. #endif
  626. #if defined( _PS3 )
  627. int m_iPS3BoneJob_ID; // index into bone job data, -1 => not running
  628. int m_iPS3BoneJob_DependantID; // id of job that must complete before me
  629. int m_iPS3BoneJob_Gen; // generation (for sorting)
  630. int m_iPS3BoneJob_Port; // for syncing SPU jobs
  631. // SAVE DATA, used to reset C_BaseAnimating so we can run again
  632. unsigned long m_iMostRecentModelBoneCounter_SAVE;
  633. unsigned long m_iMostRecentBoneSetupRequest_SAVE;
  634. int m_iPrevBoneMask_SAVE;
  635. int m_iAccumulatedBoneMask_SAVE;
  636. int m_iOldReadableBones_SAVE;
  637. int m_iOldWriteableBones_SAVE;
  638. float m_flLastBoneSetupTime_SAVE;
  639. #endif
  640. friend class C_BaseAnimatingOverlay;
  641. };
  642. enum
  643. {
  644. RAGDOLL_FRICTION_OFF = -2,
  645. RAGDOLL_FRICTION_NONE,
  646. RAGDOLL_FRICTION_IN,
  647. RAGDOLL_FRICTION_HOLD,
  648. RAGDOLL_FRICTION_OUT,
  649. };
  650. class C_ClientRagdoll : public C_BaseAnimating, public IPVSNotify
  651. {
  652. public:
  653. C_ClientRagdoll( bool bRestoring = true , bool fullInit = true);
  654. public:
  655. DECLARE_CLASS( C_ClientRagdoll, C_BaseAnimating );
  656. DECLARE_DATADESC();
  657. // inherited from IClientUnknown
  658. virtual IClientModelRenderable* GetClientModelRenderable();
  659. // inherited from IPVSNotify
  660. virtual void OnPVSStatusChanged( bool bInPVS );
  661. virtual void Release( void );
  662. virtual void SetupWeights( const matrix3x4_t *pBoneToWorld, int nFlexWeightCount, float *pFlexWeights, float *pFlexDelayedWeights );
  663. virtual void ImpactTrace( trace_t *pTrace, int iDamageType, char *pCustomImpactName );
  664. void ClientThink( void );
  665. void ReleaseRagdoll( void ) { m_bReleaseRagdoll = true; }
  666. bool ShouldSavePhysics( void ) { return true; }
  667. virtual void OnSave();
  668. virtual void OnRestore();
  669. virtual int ObjectCaps( void ) { return BaseClass::ObjectCaps() | FCAP_SAVE_NON_NETWORKABLE; }
  670. virtual IPVSNotify* GetPVSNotifyInterface() { return this; }
  671. void HandleAnimatedFriction( void );
  672. virtual void SUB_Remove( void );
  673. void FadeOut( void );
  674. virtual float LastBoneChangedTime();
  675. inline bool IsFadingOut() { return m_bFadingOut; }
  676. bool m_bFadeOut;
  677. bool m_bImportant;
  678. float m_flEffectTime;
  679. // returns true if we are of type C_ClientRagdoll
  680. virtual bool IsClientRagdoll() const { return true; }
  681. private:
  682. int m_iCurrentFriction;
  683. int m_iMinFriction;
  684. int m_iMaxFriction;
  685. float m_flFrictionModTime;
  686. float m_flFrictionTime;
  687. int m_iFrictionAnimState;
  688. bool m_bReleaseRagdoll;
  689. bool m_bFadingOut;
  690. float m_flScaleEnd[NUM_HITBOX_FIRES];
  691. float m_flScaleTimeStart[NUM_HITBOX_FIRES];
  692. float m_flScaleTimeEnd[NUM_HITBOX_FIRES];
  693. };
  694. //-----------------------------------------------------------------------------
  695. // Purpose: Serves the 90% case of calling SetSequence / ResetSequenceInfo.
  696. //-----------------------------------------------------------------------------
  697. inline void C_BaseAnimating::ResetSequence(int nSequence)
  698. {
  699. SetSequence( nSequence );
  700. ResetSequenceInfo();
  701. }
  702. inline float C_BaseAnimating::GetPlaybackRate() const
  703. {
  704. return m_flPlaybackRate * clamp( 1.0f - m_flFrozen, 0.0f, 1.0f );
  705. }
  706. inline void C_BaseAnimating::SetPlaybackRate( float rate )
  707. {
  708. m_flPlaybackRate = rate;
  709. }
  710. inline const matrix3x4a_t& C_BaseAnimating::GetBone( int iBone ) const
  711. {
  712. return m_BoneAccessor.GetBone( iBone );
  713. }
  714. inline matrix3x4a_t& C_BaseAnimating::GetBoneForWrite( int iBone )
  715. {
  716. return m_BoneAccessor.GetBoneForWrite( iBone );
  717. }
  718. inline matrix3x4a_t* C_BaseAnimating::GetBoneArrayForWrite()
  719. {
  720. return m_BoneAccessor.GetBoneArrayForWrite();
  721. }
  722. inline bool C_BaseAnimating::isBoneAvailableForRead( int iBone ) const
  723. {
  724. return m_BoneAccessor.isBoneAvailableForRead( iBone );
  725. }
  726. inline bool C_BaseAnimating::isBoneAvailableForWrite( int iBone ) const
  727. {
  728. return m_BoneAccessor.isBoneAvailableForWrite( iBone );
  729. }
  730. inline bool C_BaseAnimating::ShouldMuzzleFlash() const
  731. {
  732. return m_nOldMuzzleFlashParity != m_nMuzzleFlashParity;
  733. }
  734. inline float C_BaseAnimating::GetCycle() const
  735. {
  736. return m_flCycle;
  737. }
  738. //-----------------------------------------------------------------------------
  739. // Purpose: return a pointer to an updated studiomdl cache cache
  740. //-----------------------------------------------------------------------------
  741. inline CStudioHdr *C_BaseAnimating::GetModelPtr() const
  742. {
  743. #ifdef _DEBUG
  744. #ifndef _GAMECONSOLE
  745. // Consoles don't need to lock the modeldata cache since it never flushes
  746. static IDataCacheSection *pModelCache = g_pDataCache->FindSection( "ModelData" );
  747. AssertOnce( pModelCache->IsFrameLocking() );
  748. #endif
  749. #endif
  750. // GetModelPtr() is often called before OnNewModel() so go ahead and set it up first chance.
  751. if ( !m_pStudioHdr && GetModel() )
  752. {
  753. const_cast<C_BaseAnimating *>(this)->LockStudioHdr();
  754. }
  755. return ( m_pStudioHdr && m_pStudioHdr->IsValid() ) ? m_pStudioHdr : NULL;
  756. }
  757. inline bool C_BaseAnimating::IsModelScaleFractional() const /// very fast way to ask if the model scale is < 1.0f
  758. {
  759. COMPILE_TIME_ASSERT( sizeof( m_flModelScale ) == sizeof( int ) );
  760. return *((const int *) &m_flModelScale) < 0x3f800000;
  761. }
  762. //-----------------------------------------------------------------------------
  763. // Sequence access
  764. //-----------------------------------------------------------------------------
  765. inline int C_BaseAnimating::GetSequence()
  766. {
  767. return m_nSequence;
  768. }
  769. inline bool C_BaseAnimating::IsSequenceFinished( void )
  770. {
  771. return m_bSequenceFinished;
  772. }
  773. inline float C_BaseAnimating::SequenceDuration( void )
  774. {
  775. return SequenceDuration( GetSequence() );
  776. }
  777. //-----------------------------------------------------------------------------
  778. // Mouth
  779. //-----------------------------------------------------------------------------
  780. inline CMouthInfo& C_BaseAnimating::MouthInfo()
  781. {
  782. return m_mouth;
  783. }
  784. // FIXME: move these to somewhere that makes sense
  785. void GetColumn( matrix3x4_t& src, int column, Vector &dest );
  786. void SetColumn( Vector &src, int column, matrix3x4_t& dest );
  787. EXTERN_RECV_TABLE(DT_BaseAnimating);
  788. extern void DevMsgRT( PRINTF_FORMAT_STRING char const* pMsg, ... );
  789. #endif // C_BASEANIMATING_H