Team Fortress 2 Source Code as on 22/4/2020
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.

1152 lines
50 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose: Public interfaces to vphysics DLL
  4. //
  5. // $NoKeywords: $
  6. //=============================================================================//
  7. #ifndef VPHYSICS_INTERFACE_H
  8. #define VPHYSICS_INTERFACE_H
  9. #ifdef _WIN32
  10. #pragma once
  11. #endif
  12. #include "tier1/interface.h"
  13. #include "appframework/IAppSystem.h"
  14. #include "mathlib/vector.h"
  15. #include "mathlib/vector4d.h"
  16. #include "vcollide.h"
  17. // ------------------------------------------------------------------------------------
  18. // UNITS:
  19. // ------------------------------------------------------------------------------------
  20. // NOTE: Coordinates are in HL units. 1 unit == 1 inch. X is east (forward), Y is north (left), Z is up (up)
  21. // QAngle are pitch (around y), Yaw (around Z), Roll (around X)
  22. // AngularImpulse are exponetial maps (an axis in HL units scaled by a "twist" angle in degrees)
  23. // They can be transformed like normals/covectors and added linearly
  24. // mass is kg, volume is in^3, acceleration is in/s^2, velocity is in/s
  25. // density is kg/m^3 (water ~= 998 at room temperature)
  26. // preferably, these would be in kg/in^3, but the range of those numbers makes them not very human readable
  27. // having water be about 1000 is really convenient for data entry.
  28. // Since volume is in in^3 and density is in kg/m^3:
  29. // density = (mass / volume) * CUBIC_METERS_PER_CUBIC_INCH
  30. // Force is applied using impulses (kg*in/s)
  31. // Torque is applied using impulses (kg*degrees/s)
  32. // ------------------------------------------------------------------------------------
  33. #define METERS_PER_INCH (0.0254f)
  34. #define CUBIC_METERS_PER_CUBIC_INCH (METERS_PER_INCH*METERS_PER_INCH*METERS_PER_INCH)
  35. // 2.2 lbs / kg
  36. #define POUNDS_PER_KG (2.2f)
  37. #define KG_PER_POUND (1.0f/POUNDS_PER_KG)
  38. // convert from pounds to kg
  39. #define lbs2kg(x) ((x)*KG_PER_POUND)
  40. #define kg2lbs(x) ((x)*POUNDS_PER_KG)
  41. const float VPHYSICS_MIN_MASS = 0.1f;
  42. const float VPHYSICS_MAX_MASS = 5e4f;
  43. class IPhysicsObject;
  44. class IPhysicsEnvironment;
  45. class IPhysicsSurfaceProps;
  46. class IPhysicsConstraint;
  47. class IPhysicsConstraintGroup;
  48. class IPhysicsFluidController;
  49. class IPhysicsSpring;
  50. class IPhysicsVehicleController;
  51. class IConvexInfo;
  52. class IPhysicsObjectPairHash;
  53. class IPhysicsCollisionSet;
  54. class IPhysicsPlayerController;
  55. class IPhysicsFrictionSnapshot;
  56. struct Ray_t;
  57. struct constraint_ragdollparams_t;
  58. struct constraint_hingeparams_t;
  59. struct constraint_fixedparams_t;
  60. struct constraint_ballsocketparams_t;
  61. struct constraint_slidingparams_t;
  62. struct constraint_pulleyparams_t;
  63. struct constraint_lengthparams_t;
  64. struct constraint_groupparams_t;
  65. struct vehicleparams_t;
  66. struct matrix3x4_t;
  67. struct fluidparams_t;
  68. struct springparams_t;
  69. struct objectparams_t;
  70. struct debugcollide_t;
  71. class CGameTrace;
  72. typedef CGameTrace trace_t;
  73. struct physics_stats_t;
  74. struct physics_performanceparams_t;
  75. struct virtualmeshparams_t;
  76. //enum PhysInterfaceId_t;
  77. struct physsaveparams_t;
  78. struct physrestoreparams_t;
  79. struct physprerestoreparams_t;
  80. enum PhysInterfaceId_t
  81. {
  82. PIID_UNKNOWN,
  83. PIID_IPHYSICSOBJECT,
  84. PIID_IPHYSICSFLUIDCONTROLLER,
  85. PIID_IPHYSICSSPRING,
  86. PIID_IPHYSICSCONSTRAINTGROUP,
  87. PIID_IPHYSICSCONSTRAINT,
  88. PIID_IPHYSICSSHADOWCONTROLLER,
  89. PIID_IPHYSICSPLAYERCONTROLLER,
  90. PIID_IPHYSICSMOTIONCONTROLLER,
  91. PIID_IPHYSICSVEHICLECONTROLLER,
  92. PIID_IPHYSICSGAMETRACE,
  93. PIID_NUM_TYPES
  94. };
  95. class ISave;
  96. class IRestore;
  97. #define VPHYSICS_DEBUG_OVERLAY_INTERFACE_VERSION "VPhysicsDebugOverlay001"
  98. abstract_class IVPhysicsDebugOverlay
  99. {
  100. public:
  101. virtual void AddEntityTextOverlay(int ent_index, int line_offset, float duration, int r, int g, int b, int a, PRINTF_FORMAT_STRING const char *format, ...) = 0;
  102. virtual void AddBoxOverlay(const Vector& origin, const Vector& mins, const Vector& max, QAngle const& orientation, int r, int g, int b, int a, float duration) = 0;
  103. virtual void AddTriangleOverlay(const Vector& p1, const Vector& p2, const Vector& p3, int r, int g, int b, int a, bool noDepthTest, float duration) = 0;
  104. virtual void AddLineOverlay(const Vector& origin, const Vector& dest, int r, int g, int b,bool noDepthTest, float duration) = 0;
  105. virtual void AddTextOverlay(const Vector& origin, float duration, PRINTF_FORMAT_STRING const char *format, ...) = 0;
  106. virtual void AddTextOverlay(const Vector& origin, int line_offset, float duration, PRINTF_FORMAT_STRING const char *format, ...) = 0;
  107. virtual void AddScreenTextOverlay(float flXPos, float flYPos,float flDuration, int r, int g, int b, int a, const char *text) = 0;
  108. virtual void AddSweptBoxOverlay(const Vector& start, const Vector& end, const Vector& mins, const Vector& max, const QAngle & angles, int r, int g, int b, int a, float flDuration) = 0;
  109. virtual void AddTextOverlayRGB(const Vector& origin, int line_offset, float duration, float r, float g, float b, float alpha, PRINTF_FORMAT_STRING const char *format, ...) = 0;
  110. };
  111. #define VPHYSICS_INTERFACE_VERSION "VPhysics031"
  112. abstract_class IPhysics : public IAppSystem
  113. {
  114. public:
  115. virtual IPhysicsEnvironment *CreateEnvironment( void ) = 0;
  116. virtual void DestroyEnvironment( IPhysicsEnvironment * ) = 0;
  117. virtual IPhysicsEnvironment *GetActiveEnvironmentByIndex( int index ) = 0;
  118. // Creates a fast hash of pairs of objects
  119. // Useful for maintaining a table of object relationships like pairs that do not collide.
  120. virtual IPhysicsObjectPairHash *CreateObjectPairHash() = 0;
  121. virtual void DestroyObjectPairHash( IPhysicsObjectPairHash *pHash ) = 0;
  122. // holds a cache of these by id. So you can get by id to search for the previously created set
  123. // UNDONE: Sets are currently limited to 32 elements. More elements will return NULL in create.
  124. // NOTE: id is not allowed to be zero.
  125. virtual IPhysicsCollisionSet *FindOrCreateCollisionSet( unsigned int id, int maxElementCount ) = 0;
  126. virtual IPhysicsCollisionSet *FindCollisionSet( unsigned int id ) = 0;
  127. virtual void DestroyAllCollisionSets() = 0;
  128. };
  129. // CPhysConvex is a single convex solid
  130. class CPhysConvex;
  131. // CPhysPolysoup is an abstract triangle soup mesh
  132. class CPhysPolysoup;
  133. class ICollisionQuery;
  134. class IVPhysicsKeyParser;
  135. struct convertconvexparams_t;
  136. class CPackedPhysicsDescription;
  137. class CPolyhedron;
  138. // UNDONE: Find a better place for this? Should be in collisionutils, but it's needs VPHYSICS' solver.
  139. struct truncatedcone_t
  140. {
  141. Vector origin;
  142. Vector normal;
  143. float h; // height of the cone (hl units)
  144. float theta; // cone angle (degrees)
  145. };
  146. #define VPHYSICS_COLLISION_INTERFACE_VERSION "VPhysicsCollision007"
  147. abstract_class IPhysicsCollision
  148. {
  149. public:
  150. virtual ~IPhysicsCollision( void ) {}
  151. // produce a convex element from verts (convex hull around verts)
  152. virtual CPhysConvex *ConvexFromVerts( Vector **pVerts, int vertCount ) = 0;
  153. // produce a convex element from planes (csg of planes)
  154. virtual CPhysConvex *ConvexFromPlanes( float *pPlanes, int planeCount, float mergeDistance ) = 0;
  155. // calculate volume of a convex element
  156. virtual float ConvexVolume( CPhysConvex *pConvex ) = 0;
  157. virtual float ConvexSurfaceArea( CPhysConvex *pConvex ) = 0;
  158. // store game-specific data in a convex solid
  159. virtual void SetConvexGameData( CPhysConvex *pConvex, unsigned int gameData ) = 0;
  160. // If not converted, free the convex elements with this call
  161. virtual void ConvexFree( CPhysConvex *pConvex ) = 0;
  162. virtual CPhysConvex *BBoxToConvex( const Vector &mins, const Vector &maxs ) = 0;
  163. // produce a convex element from a convex polyhedron
  164. virtual CPhysConvex *ConvexFromConvexPolyhedron( const CPolyhedron &ConvexPolyhedron ) = 0;
  165. // produce a set of convex triangles from a convex polygon, normal is assumed to be on the side with forward point ordering, which should be clockwise, output will need to be able to hold exactly (iPointCount-2) convexes
  166. virtual void ConvexesFromConvexPolygon( const Vector &vPolyNormal, const Vector *pPoints, int iPointCount, CPhysConvex **pOutput ) = 0;
  167. // concave objects
  168. // create a triangle soup
  169. virtual CPhysPolysoup *PolysoupCreate( void ) = 0;
  170. // destroy the container and memory
  171. virtual void PolysoupDestroy( CPhysPolysoup *pSoup ) = 0;
  172. // add a triangle to the soup
  173. virtual void PolysoupAddTriangle( CPhysPolysoup *pSoup, const Vector &a, const Vector &b, const Vector &c, int materialIndex7bits ) = 0;
  174. // convert the convex into a compiled collision model
  175. virtual CPhysCollide *ConvertPolysoupToCollide( CPhysPolysoup *pSoup, bool useMOPP ) = 0;
  176. // Convert an array of convex elements to a compiled collision model (this deletes the convex elements)
  177. virtual CPhysCollide *ConvertConvexToCollide( CPhysConvex **pConvex, int convexCount ) = 0;
  178. virtual CPhysCollide *ConvertConvexToCollideParams( CPhysConvex **pConvex, int convexCount, const convertconvexparams_t &convertParams ) = 0;
  179. // Free a collide that was created with ConvertConvexToCollide()
  180. virtual void DestroyCollide( CPhysCollide *pCollide ) = 0;
  181. // Get the memory size in bytes of the collision model for serialization
  182. virtual int CollideSize( CPhysCollide *pCollide ) = 0;
  183. // serialize the collide to a block of memory
  184. virtual int CollideWrite( char *pDest, CPhysCollide *pCollide, bool bSwap = false ) = 0;
  185. // unserialize the collide from a block of memory
  186. virtual CPhysCollide *UnserializeCollide( char *pBuffer, int size, int index ) = 0;
  187. // compute the volume of a collide
  188. virtual float CollideVolume( CPhysCollide *pCollide ) = 0;
  189. // compute surface area for tools
  190. virtual float CollideSurfaceArea( CPhysCollide *pCollide ) = 0;
  191. // Get the support map for a collide in the given direction
  192. virtual Vector CollideGetExtent( const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, const Vector &direction ) = 0;
  193. // Get an AABB for an oriented collision model
  194. virtual void CollideGetAABB( Vector *pMins, Vector *pMaxs, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles ) = 0;
  195. virtual void CollideGetMassCenter( CPhysCollide *pCollide, Vector *pOutMassCenter ) = 0;
  196. virtual void CollideSetMassCenter( CPhysCollide *pCollide, const Vector &massCenter ) = 0;
  197. // get the approximate cross-sectional area projected orthographically on the bbox of the collide
  198. // NOTE: These are fractional areas - unitless. Basically this is the fraction of the OBB on each axis that
  199. // would be visible if the object were rendered orthographically.
  200. // NOTE: This has been precomputed when the collide was built or this function will return 1,1,1
  201. virtual Vector CollideGetOrthographicAreas( const CPhysCollide *pCollide ) = 0;
  202. virtual void CollideSetOrthographicAreas( CPhysCollide *pCollide, const Vector &areas ) = 0;
  203. // query the vcollide index in the physics model for the instance
  204. virtual int CollideIndex( const CPhysCollide *pCollide ) = 0;
  205. // Convert a bbox to a collide
  206. virtual CPhysCollide *BBoxToCollide( const Vector &mins, const Vector &maxs ) = 0;
  207. virtual int GetConvexesUsedInCollideable( const CPhysCollide *pCollideable, CPhysConvex **pOutputArray, int iOutputArrayLimit ) = 0;
  208. // Trace an AABB against a collide
  209. virtual void TraceBox( const Vector &start, const Vector &end, const Vector &mins, const Vector &maxs, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
  210. virtual void TraceBox( const Ray_t &ray, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
  211. virtual void TraceBox( const Ray_t &ray, unsigned int contentsMask, IConvexInfo *pConvexInfo, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
  212. // Trace one collide against another
  213. virtual void TraceCollide( const Vector &start, const Vector &end, const CPhysCollide *pSweepCollide, const QAngle &sweepAngles, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
  214. // relatively slow test for box vs. truncated cone
  215. virtual bool IsBoxIntersectingCone( const Vector &boxAbsMins, const Vector &boxAbsMaxs, const truncatedcone_t &cone ) = 0;
  216. // loads a set of solids into a vcollide_t
  217. virtual void VCollideLoad( vcollide_t *pOutput, int solidCount, const char *pBuffer, int size, bool swap = false ) = 0;
  218. // destroyts the set of solids created by VCollideLoad
  219. virtual void VCollideUnload( vcollide_t *pVCollide ) = 0;
  220. // begins parsing a vcollide. NOTE: This keeps pointers to the text
  221. // If you free the text and call members of IVPhysicsKeyParser, it will crash
  222. virtual IVPhysicsKeyParser *VPhysicsKeyParserCreate( const char *pKeyData ) = 0;
  223. // Free the parser created by VPhysicsKeyParserCreate
  224. virtual void VPhysicsKeyParserDestroy( IVPhysicsKeyParser *pParser ) = 0;
  225. // creates a list of verts from a collision mesh
  226. virtual int CreateDebugMesh( CPhysCollide const *pCollisionModel, Vector **outVerts ) = 0;
  227. // destroy the list of verts created by CreateDebugMesh
  228. virtual void DestroyDebugMesh( int vertCount, Vector *outVerts ) = 0;
  229. // create a queryable version of the collision model
  230. virtual ICollisionQuery *CreateQueryModel( CPhysCollide *pCollide ) = 0;
  231. // destroy the queryable version
  232. virtual void DestroyQueryModel( ICollisionQuery *pQuery ) = 0;
  233. virtual IPhysicsCollision *ThreadContextCreate( void ) = 0;
  234. virtual void ThreadContextDestroy( IPhysicsCollision *pThreadContex ) = 0;
  235. virtual CPhysCollide *CreateVirtualMesh( const virtualmeshparams_t &params ) = 0;
  236. virtual bool SupportsVirtualMesh() = 0;
  237. virtual bool GetBBoxCacheSize( int *pCachedSize, int *pCachedCount ) = 0;
  238. // extracts a polyhedron that defines a CPhysConvex's shape
  239. virtual CPolyhedron *PolyhedronFromConvex( CPhysConvex * const pConvex, bool bUseTempPolyhedron ) = 0;
  240. // dumps info about the collide to Msg()
  241. virtual void OutputDebugInfo( const CPhysCollide *pCollide ) = 0;
  242. virtual unsigned int ReadStat( int statID ) = 0;
  243. };
  244. // this can be used to post-process a collision model
  245. abstract_class ICollisionQuery
  246. {
  247. public:
  248. virtual ~ICollisionQuery() {}
  249. // number of convex pieces in the whole solid
  250. virtual int ConvexCount( void ) = 0;
  251. // triangle count for this convex piece
  252. virtual int TriangleCount( int convexIndex ) = 0;
  253. // get the stored game data
  254. virtual unsigned int GetGameData( int convexIndex ) = 0;
  255. // Gets the triangle's verts to an array
  256. virtual void GetTriangleVerts( int convexIndex, int triangleIndex, Vector *verts ) = 0;
  257. // UNDONE: This doesn't work!!!
  258. virtual void SetTriangleVerts( int convexIndex, int triangleIndex, const Vector *verts ) = 0;
  259. // returns the 7-bit material index
  260. virtual int GetTriangleMaterialIndex( int convexIndex, int triangleIndex ) = 0;
  261. // sets a 7-bit material index for this triangle
  262. virtual void SetTriangleMaterialIndex( int convexIndex, int triangleIndex, int index7bits ) = 0;
  263. };
  264. //-----------------------------------------------------------------------------
  265. // Purpose: Ray traces from game engine.
  266. //-----------------------------------------------------------------------------
  267. abstract_class IPhysicsGameTrace
  268. {
  269. public:
  270. virtual void VehicleTraceRay( const Ray_t &ray, void *pVehicle, trace_t *pTrace ) = 0;
  271. virtual void VehicleTraceRayWithWater( const Ray_t &ray, void *pVehicle, trace_t *pTrace ) = 0;
  272. virtual bool VehiclePointInWater( const Vector &vecPoint ) = 0;
  273. };
  274. // The caller should implement this to return contents masks per convex on a collide
  275. abstract_class IConvexInfo
  276. {
  277. public:
  278. virtual unsigned int GetContents( int convexGameData ) = 0;
  279. };
  280. class CPhysicsEventHandler;
  281. abstract_class IPhysicsCollisionData
  282. {
  283. public:
  284. virtual void GetSurfaceNormal( Vector &out ) = 0; // normal points toward second object (object index 1)
  285. virtual void GetContactPoint( Vector &out ) = 0; // contact point of collision (in world space)
  286. virtual void GetContactSpeed( Vector &out ) = 0; // speed of surface 1 relative to surface 0 (in world space)
  287. };
  288. struct vcollisionevent_t
  289. {
  290. IPhysicsObject *pObjects[2];
  291. int surfaceProps[2];
  292. bool isCollision;
  293. bool isShadowCollision;
  294. float deltaCollisionTime;
  295. float collisionSpeed; // only valid at postCollision
  296. IPhysicsCollisionData *pInternalData; // may change pre/post collision
  297. };
  298. abstract_class IPhysicsCollisionEvent
  299. {
  300. public:
  301. // returns the two objects that collided, time between last collision of these objects
  302. // and an opaque data block of collision information
  303. // NOTE: PreCollision/PostCollision ALWAYS come in matched pairs!!!
  304. virtual void PreCollision( vcollisionevent_t *pEvent ) = 0;
  305. virtual void PostCollision( vcollisionevent_t *pEvent ) = 0;
  306. // This is a scrape event. The object has scraped across another object consuming the indicated energy
  307. virtual void Friction( IPhysicsObject *pObject, float energy, int surfaceProps, int surfacePropsHit, IPhysicsCollisionData *pData ) = 0;
  308. virtual void StartTouch( IPhysicsObject *pObject1, IPhysicsObject *pObject2, IPhysicsCollisionData *pTouchData ) = 0;
  309. virtual void EndTouch( IPhysicsObject *pObject1, IPhysicsObject *pObject2, IPhysicsCollisionData *pTouchData ) = 0;
  310. virtual void FluidStartTouch( IPhysicsObject *pObject, IPhysicsFluidController *pFluid ) = 0;
  311. virtual void FluidEndTouch( IPhysicsObject *pObject, IPhysicsFluidController *pFluid ) = 0;
  312. virtual void PostSimulationFrame() = 0;
  313. virtual void ObjectEnterTrigger( IPhysicsObject *pTrigger, IPhysicsObject *pObject ) {}
  314. virtual void ObjectLeaveTrigger( IPhysicsObject *pTrigger, IPhysicsObject *pObject ) {}
  315. };
  316. abstract_class IPhysicsObjectEvent
  317. {
  318. public:
  319. // these can be used to optimize out queries on sleeping objects
  320. // Called when an object is woken after sleeping
  321. virtual void ObjectWake( IPhysicsObject *pObject ) = 0;
  322. // called when an object goes to sleep (no longer simulating)
  323. virtual void ObjectSleep( IPhysicsObject *pObject ) = 0;
  324. };
  325. abstract_class IPhysicsConstraintEvent
  326. {
  327. public:
  328. // the constraint is now inactive, the game code is required to delete it or re-activate it.
  329. virtual void ConstraintBroken( IPhysicsConstraint * ) = 0;
  330. };
  331. struct hlshadowcontrol_params_t
  332. {
  333. Vector targetPosition;
  334. QAngle targetRotation;
  335. float maxAngular;
  336. float maxDampAngular;
  337. float maxSpeed;
  338. float maxDampSpeed;
  339. float dampFactor;
  340. float teleportDistance;
  341. };
  342. // UNDONE: At some point allow this to be parameterized using hlshadowcontrol_params_t.
  343. // All of the infrastructure is in place to do that.
  344. abstract_class IPhysicsShadowController
  345. {
  346. public:
  347. virtual ~IPhysicsShadowController( void ) {}
  348. virtual void Update( const Vector &position, const QAngle &angles, float timeOffset ) = 0;
  349. virtual void MaxSpeed( float maxSpeed, float maxAngularSpeed ) = 0;
  350. virtual void StepUp( float height ) = 0;
  351. // If the teleport distance is non-zero, the object will be teleported to
  352. // the target location when the error exceeds this quantity.
  353. virtual void SetTeleportDistance( float teleportDistance ) = 0;
  354. virtual bool AllowsTranslation() = 0;
  355. virtual bool AllowsRotation() = 0;
  356. // There are two classes of shadow objects:
  357. // 1) Game physics controlled, shadow follows game physics (this is the default)
  358. // 2) Physically controlled - shadow position is a target, but the game hasn't guaranteed that the space can be occupied by this object
  359. virtual void SetPhysicallyControlled( bool isPhysicallyControlled ) = 0;
  360. virtual bool IsPhysicallyControlled() = 0;
  361. virtual void GetLastImpulse( Vector *pOut ) = 0;
  362. virtual void UseShadowMaterial( bool bUseShadowMaterial ) = 0;
  363. virtual void ObjectMaterialChanged( int materialIndex ) = 0;
  364. //Basically get the last inputs to IPhysicsShadowController::Update(), returns last input to timeOffset in Update()
  365. virtual float GetTargetPosition( Vector *pPositionOut, QAngle *pAnglesOut ) = 0;
  366. virtual float GetTeleportDistance( void ) = 0;
  367. virtual void GetMaxSpeed( float *pMaxSpeedOut, float *pMaxAngularSpeedOut ) = 0;
  368. };
  369. class CPhysicsSimObject;
  370. class IPhysicsMotionController;
  371. // Callback for simulation
  372. class IMotionEvent
  373. {
  374. public:
  375. // These constants instruct the simulator as to how to apply the values copied to linear & angular
  376. // GLOBAL/LOCAL refer to the coordinate system of the values, whereas acceleration/force determine whether or not
  377. // mass is divided out (forces must be divided by mass to compute acceleration)
  378. enum simresult_e { SIM_NOTHING = 0, SIM_LOCAL_ACCELERATION, SIM_LOCAL_FORCE, SIM_GLOBAL_ACCELERATION, SIM_GLOBAL_FORCE };
  379. virtual simresult_e Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular ) = 0;
  380. };
  381. abstract_class IPhysicsMotionController
  382. {
  383. public:
  384. virtual ~IPhysicsMotionController( void ) {}
  385. virtual void SetEventHandler( IMotionEvent *handler ) = 0;
  386. virtual void AttachObject( IPhysicsObject *pObject, bool checkIfAlreadyAttached ) = 0;
  387. virtual void DetachObject( IPhysicsObject *pObject ) = 0;
  388. // returns the number of objects currently attached to the controller
  389. virtual int CountObjects( void ) = 0;
  390. // NOTE: pObjectList is an array with at least CountObjects() allocated
  391. virtual void GetObjects( IPhysicsObject **pObjectList ) = 0;
  392. // detaches all attached objects
  393. virtual void ClearObjects( void ) = 0;
  394. // wakes up all attached objects
  395. virtual void WakeObjects( void ) = 0;
  396. enum priority_t
  397. {
  398. LOW_PRIORITY = 0,
  399. MEDIUM_PRIORITY = 1,
  400. HIGH_PRIORITY = 2,
  401. };
  402. virtual void SetPriority( priority_t priority ) = 0;
  403. };
  404. // -------------------
  405. // Collision filter function. Return 0 if objects should not be tested for collisions, nonzero otherwise
  406. // Install with IPhysicsEnvironment::SetCollisionFilter()
  407. // -------------------
  408. abstract_class IPhysicsCollisionSolver
  409. {
  410. public:
  411. virtual int ShouldCollide( IPhysicsObject *pObj0, IPhysicsObject *pObj1, void *pGameData0, void *pGameData1 ) = 0;
  412. virtual int ShouldSolvePenetration( IPhysicsObject *pObj0, IPhysicsObject *pObj1, void *pGameData0, void *pGameData1, float dt ) = 0;
  413. // pObject has already done the max number of collisions this tick, should we freeze it to save CPU?
  414. virtual bool ShouldFreezeObject( IPhysicsObject *pObject ) = 0;
  415. // The system has already done too many collision checks, performance will suffer.
  416. // How many more should it do?
  417. virtual int AdditionalCollisionChecksThisTick( int currentChecksDone ) = 0;
  418. // This list of objects is in a connected contact graph that is too large to solve quickly
  419. // return true to freeze the system, false to solve it
  420. virtual bool ShouldFreezeContacts( IPhysicsObject **pObjectList, int objectCount ) = 0;
  421. };
  422. enum PhysicsTraceType_t
  423. {
  424. VPHYSICS_TRACE_EVERYTHING = 0,
  425. VPHYSICS_TRACE_STATIC_ONLY,
  426. VPHYSICS_TRACE_MOVING_ONLY,
  427. VPHYSICS_TRACE_TRIGGERS_ONLY,
  428. VPHYSICS_TRACE_STATIC_AND_MOVING,
  429. };
  430. abstract_class IPhysicsTraceFilter
  431. {
  432. public:
  433. virtual bool ShouldHitObject( IPhysicsObject *pObject, int contentsMask ) = 0;
  434. virtual PhysicsTraceType_t GetTraceType() const = 0;
  435. };
  436. abstract_class IPhysicsEnvironment
  437. {
  438. public:
  439. virtual ~IPhysicsEnvironment( void ) {}
  440. virtual void SetDebugOverlay( CreateInterfaceFn debugOverlayFactory ) = 0;
  441. virtual IVPhysicsDebugOverlay *GetDebugOverlay( void ) = 0;
  442. // gravity is a 3-vector in in/s^2
  443. virtual void SetGravity( const Vector &gravityVector ) = 0;
  444. virtual void GetGravity( Vector *pGravityVector ) const = 0;
  445. // air density is in kg / m^3 (water is 1000)
  446. // This controls drag, air that is more dense has more drag.
  447. virtual void SetAirDensity( float density ) = 0;
  448. virtual float GetAirDensity( void ) const = 0;
  449. // object creation
  450. // create a polygonal object. pCollisionModel was created by the physics builder DLL in a pre-process.
  451. virtual IPhysicsObject *CreatePolyObject( const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams ) = 0;
  452. // same as above, but this one cannot move or rotate (infinite mass/inertia)
  453. virtual IPhysicsObject *CreatePolyObjectStatic( const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams ) = 0;
  454. // Create a perfectly spherical object
  455. virtual IPhysicsObject *CreateSphereObject( float radius, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams, bool isStatic ) = 0;
  456. // destroy an object created with CreatePolyObject() or CreatePolyObjectStatic()
  457. virtual void DestroyObject( IPhysicsObject * ) = 0;
  458. // Create a polygonal fluid body out of the specified collision model
  459. // This object will affect any other objects that collide with the collision model
  460. virtual IPhysicsFluidController *CreateFluidController( IPhysicsObject *pFluidObject, fluidparams_t *pParams ) = 0;
  461. // Destroy an object created with CreateFluidController()
  462. virtual void DestroyFluidController( IPhysicsFluidController * ) = 0;
  463. // Create a simulated spring that connects 2 objects
  464. virtual IPhysicsSpring *CreateSpring( IPhysicsObject *pObjectStart, IPhysicsObject *pObjectEnd, springparams_t *pParams ) = 0;
  465. virtual void DestroySpring( IPhysicsSpring * ) = 0;
  466. // Create a constraint in the space of pReferenceObject which is attached by the constraint to pAttachedObject
  467. virtual IPhysicsConstraint *CreateRagdollConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ragdollparams_t &ragdoll ) = 0;
  468. virtual IPhysicsConstraint *CreateHingeConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_hingeparams_t &hinge ) = 0;
  469. virtual IPhysicsConstraint *CreateFixedConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_fixedparams_t &fixed ) = 0;
  470. virtual IPhysicsConstraint *CreateSlidingConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_slidingparams_t &sliding ) = 0;
  471. virtual IPhysicsConstraint *CreateBallsocketConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ballsocketparams_t &ballsocket ) = 0;
  472. virtual IPhysicsConstraint *CreatePulleyConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_pulleyparams_t &pulley ) = 0;
  473. virtual IPhysicsConstraint *CreateLengthConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_lengthparams_t &length ) = 0;
  474. virtual void DestroyConstraint( IPhysicsConstraint * ) = 0;
  475. virtual IPhysicsConstraintGroup *CreateConstraintGroup( const constraint_groupparams_t &groupParams ) = 0;
  476. virtual void DestroyConstraintGroup( IPhysicsConstraintGroup *pGroup ) = 0;
  477. virtual IPhysicsShadowController *CreateShadowController( IPhysicsObject *pObject, bool allowTranslation, bool allowRotation ) = 0;
  478. virtual void DestroyShadowController( IPhysicsShadowController * ) = 0;
  479. virtual IPhysicsPlayerController *CreatePlayerController( IPhysicsObject *pObject ) = 0;
  480. virtual void DestroyPlayerController( IPhysicsPlayerController * ) = 0;
  481. virtual IPhysicsMotionController *CreateMotionController( IMotionEvent *pHandler ) = 0;
  482. virtual void DestroyMotionController( IPhysicsMotionController *pController ) = 0;
  483. virtual IPhysicsVehicleController *CreateVehicleController( IPhysicsObject *pVehicleBodyObject, const vehicleparams_t &params, unsigned int nVehicleType, IPhysicsGameTrace *pGameTrace ) = 0;
  484. virtual void DestroyVehicleController( IPhysicsVehicleController * ) = 0;
  485. // install a function to filter collisions/penentration
  486. virtual void SetCollisionSolver( IPhysicsCollisionSolver *pSolver ) = 0;
  487. // run the simulator for deltaTime seconds
  488. virtual void Simulate( float deltaTime ) = 0;
  489. // true if currently running the simulator (i.e. in a callback during physenv->Simulate())
  490. virtual bool IsInSimulation() const = 0;
  491. // Manage the timestep (period) of the simulator. The main functions are all integrated with
  492. // this period as dt.
  493. virtual float GetSimulationTimestep() const = 0;
  494. virtual void SetSimulationTimestep( float timestep ) = 0;
  495. // returns the current simulation clock's value. This is an absolute time.
  496. virtual float GetSimulationTime() const = 0;
  497. virtual void ResetSimulationClock() = 0;
  498. // returns the current simulation clock's value at the next frame. This is an absolute time.
  499. virtual float GetNextFrameTime( void ) const = 0;
  500. // Collision callbacks (game code collision response)
  501. virtual void SetCollisionEventHandler( IPhysicsCollisionEvent *pCollisionEvents ) = 0;
  502. virtual void SetObjectEventHandler( IPhysicsObjectEvent *pObjectEvents ) = 0;
  503. virtual void SetConstraintEventHandler( IPhysicsConstraintEvent *pConstraintEvents ) = 0;
  504. virtual void SetQuickDelete( bool bQuick ) = 0;
  505. virtual int GetActiveObjectCount() const = 0;
  506. virtual void GetActiveObjects( IPhysicsObject **pOutputObjectList ) const = 0;
  507. virtual const IPhysicsObject **GetObjectList( int *pOutputObjectCount ) const = 0;
  508. virtual bool TransferObject( IPhysicsObject *pObject, IPhysicsEnvironment *pDestinationEnvironment ) = 0;
  509. virtual void CleanupDeleteList( void ) = 0;
  510. virtual void EnableDeleteQueue( bool enable ) = 0;
  511. // Save/Restore methods
  512. virtual bool Save( const physsaveparams_t &params ) = 0;
  513. virtual void PreRestore( const physprerestoreparams_t &params ) = 0;
  514. virtual bool Restore( const physrestoreparams_t &params ) = 0;
  515. virtual void PostRestore() = 0;
  516. // Debugging:
  517. virtual bool IsCollisionModelUsed( CPhysCollide *pCollide ) const = 0;
  518. // Physics world version of the enginetrace API:
  519. virtual void TraceRay( const Ray_t &ray, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace ) = 0;
  520. virtual void SweepCollideable( const CPhysCollide *pCollide, const Vector &vecAbsStart, const Vector &vecAbsEnd,
  521. const QAngle &vecAngles, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace ) = 0;
  522. // performance tuning
  523. virtual void GetPerformanceSettings( physics_performanceparams_t *pOutput ) const = 0;
  524. virtual void SetPerformanceSettings( const physics_performanceparams_t *pSettings ) = 0;
  525. // perf/cost statistics
  526. virtual void ReadStats( physics_stats_t *pOutput ) = 0;
  527. virtual void ClearStats() = 0;
  528. virtual unsigned int GetObjectSerializeSize( IPhysicsObject *pObject ) const = 0;
  529. virtual void SerializeObjectToBuffer( IPhysicsObject *pObject, unsigned char *pBuffer, unsigned int bufferSize ) = 0;
  530. virtual IPhysicsObject *UnserializeObjectFromBuffer( void *pGameData, unsigned char *pBuffer, unsigned int bufferSize, bool enableCollisions ) = 0;
  531. virtual void EnableConstraintNotify( bool bEnable ) = 0;
  532. virtual void DebugCheckContacts(void) = 0;
  533. };
  534. enum callbackflags
  535. {
  536. CALLBACK_GLOBAL_COLLISION = 0x0001,
  537. CALLBACK_GLOBAL_FRICTION = 0x0002,
  538. CALLBACK_GLOBAL_TOUCH = 0x0004,
  539. CALLBACK_GLOBAL_TOUCH_STATIC = 0x0008,
  540. CALLBACK_SHADOW_COLLISION = 0x0010,
  541. CALLBACK_GLOBAL_COLLIDE_STATIC = 0x0020,
  542. CALLBACK_IS_VEHICLE_WHEEL = 0x0040,
  543. CALLBACK_FLUID_TOUCH = 0x0100,
  544. CALLBACK_NEVER_DELETED = 0x0200, // HACKHACK: This means this object will never be deleted (set on the world)
  545. CALLBACK_MARKED_FOR_DELETE = 0x0400, // This allows vphysics to skip some work for this object since it will be
  546. // deleted later this frame. (Set automatically by destroy calls)
  547. CALLBACK_ENABLING_COLLISION = 0x0800, // This is active during the time an object is enabling collisions
  548. // allows us to skip collisions between "new" objects and objects marked for delete
  549. CALLBACK_DO_FLUID_SIMULATION = 0x1000, // remove this to opt out of fluid simulations
  550. CALLBACK_IS_PLAYER_CONTROLLER= 0x2000, // HACKHACK: Set this on players until player cotrollers are unified with shadow controllers
  551. CALLBACK_CHECK_COLLISION_DISABLE = 0x4000,
  552. CALLBACK_MARKED_FOR_TEST = 0x8000, // debug -- marked object is being debugged
  553. };
  554. abstract_class IPhysicsObject
  555. {
  556. public:
  557. virtual ~IPhysicsObject( void ) {}
  558. // returns true if this object is static/unmoveable
  559. // NOTE: returns false for objects that are not created static, but set EnableMotion(false);
  560. // Call IsMoveable() to find if the object is static OR has motion disabled
  561. virtual bool IsStatic() const = 0;
  562. virtual bool IsAsleep() const = 0;
  563. virtual bool IsTrigger() const = 0;
  564. virtual bool IsFluid() const = 0; // fluids are special triggers with fluid controllers attached, they return true to IsTrigger() as well!
  565. virtual bool IsHinged() const = 0;
  566. virtual bool IsCollisionEnabled() const = 0;
  567. virtual bool IsGravityEnabled() const = 0;
  568. virtual bool IsDragEnabled() const = 0;
  569. virtual bool IsMotionEnabled() const = 0;
  570. virtual bool IsMoveable() const = 0; // legacy: IsMotionEnabled() && !IsStatic()
  571. virtual bool IsAttachedToConstraint(bool bExternalOnly) const = 0;
  572. // Enable / disable collisions for this object
  573. virtual void EnableCollisions( bool enable ) = 0;
  574. // Enable / disable gravity for this object
  575. virtual void EnableGravity( bool enable ) = 0;
  576. // Enable / disable air friction / drag for this object
  577. virtual void EnableDrag( bool enable ) = 0;
  578. // Enable / disable motion (pin / unpin the object)
  579. virtual void EnableMotion( bool enable ) = 0;
  580. // Game can store data in each object (link back to game object)
  581. virtual void SetGameData( void *pGameData ) = 0;
  582. virtual void *GetGameData( void ) const = 0;
  583. // This flags word can be defined by the game as well
  584. virtual void SetGameFlags( unsigned short userFlags ) = 0;
  585. virtual unsigned short GetGameFlags( void ) const = 0;
  586. virtual void SetGameIndex( unsigned short gameIndex ) = 0;
  587. virtual unsigned short GetGameIndex( void ) const = 0;
  588. // setup various callbacks for this object
  589. virtual void SetCallbackFlags( unsigned short callbackflags ) = 0;
  590. // get the current callback state for this object
  591. virtual unsigned short GetCallbackFlags( void ) const = 0;
  592. // "wakes up" an object
  593. // NOTE: ALL OBJECTS ARE "Asleep" WHEN CREATED
  594. virtual void Wake( void ) = 0;
  595. virtual void Sleep( void ) = 0;
  596. // call this when the collision filter conditions change due to this
  597. // object's state (e.g. changing solid type or collision group)
  598. virtual void RecheckCollisionFilter() = 0;
  599. // NOTE: Contact points aren't updated when collision rules change, call this to force an update
  600. // UNDONE: Force this in RecheckCollisionFilter() ?
  601. virtual void RecheckContactPoints() = 0;
  602. // mass accessors
  603. virtual void SetMass( float mass ) = 0;
  604. virtual float GetMass( void ) const = 0;
  605. // get 1/mass (it's cached)
  606. virtual float GetInvMass( void ) const = 0;
  607. virtual Vector GetInertia( void ) const = 0;
  608. virtual Vector GetInvInertia( void ) const = 0;
  609. virtual void SetInertia( const Vector &inertia ) = 0;
  610. virtual void SetDamping( const float *speed, const float *rot ) = 0;
  611. virtual void GetDamping( float *speed, float *rot ) const = 0;
  612. // coefficients are optional, pass either
  613. virtual void SetDragCoefficient( float *pDrag, float *pAngularDrag ) = 0;
  614. virtual void SetBuoyancyRatio( float ratio ) = 0; // Override bouyancy
  615. // material index
  616. virtual int GetMaterialIndex() const = 0;
  617. virtual void SetMaterialIndex( int materialIndex ) = 0;
  618. // contents bits
  619. virtual unsigned int GetContents() const = 0;
  620. virtual void SetContents( unsigned int contents ) = 0;
  621. // Get the radius if this is a sphere object (zero if this is a polygonal mesh)
  622. virtual float GetSphereRadius() const = 0;
  623. virtual float GetEnergy() const = 0;
  624. virtual Vector GetMassCenterLocalSpace() const = 0;
  625. // NOTE: This will teleport the object
  626. virtual void SetPosition( const Vector &worldPosition, const QAngle &angles, bool isTeleport ) = 0;
  627. virtual void SetPositionMatrix( const matrix3x4_t&matrix, bool isTeleport ) = 0;
  628. virtual void GetPosition( Vector *worldPosition, QAngle *angles ) const = 0;
  629. virtual void GetPositionMatrix( matrix3x4_t *positionMatrix ) const = 0;
  630. // force the velocity to a new value
  631. // NOTE: velocity is in worldspace, angularVelocity is relative to the object's
  632. // local axes (just like pev->velocity, pev->avelocity)
  633. virtual void SetVelocity( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0;
  634. // like the above, but force the change into the simulator immediately
  635. virtual void SetVelocityInstantaneous( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0;
  636. // NOTE: velocity is in worldspace, angularVelocity is relative to the object's
  637. // local axes (just like pev->velocity, pev->avelocity)
  638. virtual void GetVelocity( Vector *velocity, AngularImpulse *angularVelocity ) const = 0;
  639. // NOTE: These are velocities, not forces. i.e. They will have the same effect regardless of
  640. // the object's mass or inertia
  641. virtual void AddVelocity( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0;
  642. // gets a velocity in the object's local frame of reference at a specific point
  643. virtual void GetVelocityAtPoint( const Vector &worldPosition, Vector *pVelocity ) const = 0;
  644. // gets the velocity actually moved by the object in the last simulation update
  645. virtual void GetImplicitVelocity( Vector *velocity, AngularImpulse *angularVelocity ) const = 0;
  646. // NOTE: These are here for convenience, but you can do them yourself by using the matrix
  647. // returned from GetPositionMatrix()
  648. // convenient coordinate system transformations (params - dest, src)
  649. virtual void LocalToWorld( Vector *worldPosition, const Vector &localPosition ) const = 0;
  650. virtual void WorldToLocal( Vector *localPosition, const Vector &worldPosition ) const = 0;
  651. // transforms a vector (no translation) from object-local to world space
  652. virtual void LocalToWorldVector( Vector *worldVector, const Vector &localVector ) const = 0;
  653. // transforms a vector (no translation) from world to object-local space
  654. virtual void WorldToLocalVector( Vector *localVector, const Vector &worldVector ) const = 0;
  655. // push on an object
  656. // force vector is direction & magnitude of impulse kg in / s
  657. virtual void ApplyForceCenter( const Vector &forceVector ) = 0;
  658. virtual void ApplyForceOffset( const Vector &forceVector, const Vector &worldPosition ) = 0;
  659. // apply torque impulse. This will change the angular velocity on the object.
  660. // HL Axes, kg degrees / s
  661. virtual void ApplyTorqueCenter( const AngularImpulse &torque ) = 0;
  662. // Calculates the force/torque on the center of mass for an offset force impulse (pass output to ApplyForceCenter / ApplyTorqueCenter)
  663. virtual void CalculateForceOffset( const Vector &forceVector, const Vector &worldPosition, Vector *centerForce, AngularImpulse *centerTorque ) const = 0;
  664. // Calculates the linear/angular velocities on the center of mass for an offset force impulse (pass output to AddVelocity)
  665. virtual void CalculateVelocityOffset( const Vector &forceVector, const Vector &worldPosition, Vector *centerVelocity, AngularImpulse *centerAngularVelocity ) const = 0;
  666. // calculate drag scale
  667. virtual float CalculateLinearDrag( const Vector &unitDirection ) const = 0;
  668. virtual float CalculateAngularDrag( const Vector &objectSpaceRotationAxis ) const = 0;
  669. // returns true if the object is in contact with another object
  670. // if true, puts a point on the contact surface in contactPoint, and
  671. // a pointer to the object in contactObject
  672. // NOTE: You can pass NULL for either to avoid computations
  673. // BUGBUG: Use CreateFrictionSnapshot instead of this - this is a simple hack
  674. virtual bool GetContactPoint( Vector *contactPoint, IPhysicsObject **contactObject ) const = 0;
  675. // refactor this a bit - move some of this to IPhysicsShadowController
  676. virtual void SetShadow( float maxSpeed, float maxAngularSpeed, bool allowPhysicsMovement, bool allowPhysicsRotation ) = 0;
  677. virtual void UpdateShadow( const Vector &targetPosition, const QAngle &targetAngles, bool tempDisableGravity, float timeOffset ) = 0;
  678. // returns number of ticks since last Update() call
  679. virtual int GetShadowPosition( Vector *position, QAngle *angles ) const = 0;
  680. virtual IPhysicsShadowController *GetShadowController( void ) const = 0;
  681. virtual void RemoveShadowController() = 0;
  682. // applies the math of the shadow controller to this object.
  683. // for use in your own controllers
  684. // returns the new value of secondsToArrival with dt time elapsed
  685. virtual float ComputeShadowControl( const hlshadowcontrol_params_t &params, float secondsToArrival, float dt ) = 0;
  686. virtual const CPhysCollide *GetCollide( void ) const = 0;
  687. virtual const char *GetName() const = 0;
  688. virtual void BecomeTrigger() = 0;
  689. virtual void RemoveTrigger() = 0;
  690. // sets the object to be hinged. Fixed it place, but able to rotate around one axis.
  691. virtual void BecomeHinged( int localAxis ) = 0;
  692. // resets the object to original state
  693. virtual void RemoveHinged() = 0;
  694. // used to iterate the contact points of an object
  695. virtual IPhysicsFrictionSnapshot *CreateFrictionSnapshot() = 0;
  696. virtual void DestroyFrictionSnapshot( IPhysicsFrictionSnapshot *pSnapshot ) = 0;
  697. // dumps info about the object to Msg()
  698. virtual void OutputDebugInfo() const = 0;
  699. };
  700. abstract_class IPhysicsSpring
  701. {
  702. public:
  703. virtual ~IPhysicsSpring( void ) {}
  704. virtual void GetEndpoints( Vector *worldPositionStart, Vector *worldPositionEnd ) = 0;
  705. virtual void SetSpringConstant( float flSpringContant) = 0;
  706. virtual void SetSpringDamping( float flSpringDamping) = 0;
  707. virtual void SetSpringLength( float flSpringLenght) = 0;
  708. // Get the starting object
  709. virtual IPhysicsObject *GetStartObject( void ) = 0;
  710. // Get the end object
  711. virtual IPhysicsObject *GetEndObject( void ) = 0;
  712. };
  713. //-----------------------------------------------------------------------------
  714. // Purpose: These properties are defined per-material. This is accessible at
  715. // each triangle in a collision mesh
  716. //-----------------------------------------------------------------------------
  717. struct surfacephysicsparams_t
  718. {
  719. // vphysics physical properties
  720. float friction;
  721. float elasticity; // collision elasticity - used to compute coefficient of restitution
  722. float density; // physical density (in kg / m^3)
  723. float thickness; // material thickness if not solid (sheet materials) in inches
  724. float dampening;
  725. };
  726. struct surfaceaudioparams_t
  727. {
  728. // sounds / audio data
  729. float reflectivity; // like elasticity, but how much sound should be reflected by this surface
  730. float hardnessFactor; // like elasticity, but only affects impact sound choices
  731. float roughnessFactor; // like friction, but only affects scrape sound choices
  732. // audio thresholds
  733. float roughThreshold; // surface roughness > this causes "rough" scrapes, < this causes "smooth" scrapes
  734. float hardThreshold; // surface hardness > this causes "hard" impacts, < this causes "soft" impacts
  735. float hardVelocityThreshold; // collision velocity > this causes "hard" impacts, < this causes "soft" impacts
  736. // NOTE: Hard impacts must meet both hardnessFactor AND velocity thresholds
  737. };
  738. struct surfacesoundnames_t
  739. {
  740. unsigned short stepleft;
  741. unsigned short stepright;
  742. unsigned short impactSoft;
  743. unsigned short impactHard;
  744. unsigned short scrapeSmooth;
  745. unsigned short scrapeRough;
  746. unsigned short bulletImpact;
  747. unsigned short rolling;
  748. unsigned short breakSound;
  749. unsigned short strainSound;
  750. };
  751. struct surfacesoundhandles_t
  752. {
  753. short stepleft;
  754. short stepright;
  755. short impactSoft;
  756. short impactHard;
  757. short scrapeSmooth;
  758. short scrapeRough;
  759. short bulletImpact;
  760. short rolling;
  761. short breakSound;
  762. short strainSound;
  763. };
  764. struct surfacegameprops_t
  765. {
  766. // game movement data
  767. float maxSpeedFactor; // Modulates player max speed when walking on this surface
  768. float jumpFactor; // Indicates how much higher the player should jump when on the surface
  769. // Game-specific data
  770. unsigned short material;
  771. // Indicates whether or not the player is on a ladder.
  772. unsigned char climbable;
  773. unsigned char pad;
  774. };
  775. //-----------------------------------------------------------------------------
  776. // Purpose: Each different material has an entry like this
  777. //-----------------------------------------------------------------------------
  778. struct surfacedata_t
  779. {
  780. surfacephysicsparams_t physics; // physics parameters
  781. surfaceaudioparams_t audio; // audio parameters
  782. surfacesoundnames_t sounds; // names of linked sounds
  783. surfacegameprops_t game; // Game data / properties
  784. surfacesoundhandles_t soundhandles;
  785. };
  786. #define VPHYSICS_SURFACEPROPS_INTERFACE_VERSION "VPhysicsSurfaceProps001"
  787. abstract_class IPhysicsSurfaceProps
  788. {
  789. public:
  790. virtual ~IPhysicsSurfaceProps( void ) {}
  791. // parses a text file containing surface prop keys
  792. virtual int ParseSurfaceData( const char *pFilename, const char *pTextfile ) = 0;
  793. // current number of entries in the database
  794. virtual int SurfacePropCount( void ) const = 0;
  795. virtual int GetSurfaceIndex( const char *pSurfacePropName ) const = 0;
  796. virtual void GetPhysicsProperties( int surfaceDataIndex, float *density, float *thickness, float *friction, float *elasticity ) const = 0;
  797. virtual surfacedata_t *GetSurfaceData( int surfaceDataIndex ) = 0;
  798. virtual const char *GetString( unsigned short stringTableIndex ) const = 0;
  799. virtual const char *GetPropName( int surfaceDataIndex ) const = 0;
  800. // sets the global index table for world materials
  801. // UNDONE: Make this per-CPhysCollide
  802. virtual void SetWorldMaterialIndexTable( int *pMapArray, int mapSize ) = 0;
  803. // NOTE: Same as GetPhysicsProperties, but maybe more convenient
  804. virtual void GetPhysicsParameters( int surfaceDataIndex, surfacephysicsparams_t *pParamsOut ) const = 0;
  805. };
  806. abstract_class IPhysicsFluidController
  807. {
  808. public:
  809. virtual ~IPhysicsFluidController( void ) {}
  810. virtual void SetGameData( void *pGameData ) = 0;
  811. virtual void *GetGameData( void ) const = 0;
  812. virtual void GetSurfacePlane( Vector *pNormal, float *pDist ) const = 0;
  813. virtual float GetDensity() const = 0;
  814. virtual void WakeAllSleepingObjects() = 0;
  815. virtual int GetContents() const = 0;
  816. };
  817. //-----------------------------------------------------------------------------
  818. // Purpose: parameter block for creating fluid dynamic motion
  819. // UNDONE: Expose additional fluid model paramters?
  820. //-----------------------------------------------------------------------------
  821. struct fluidparams_t
  822. {
  823. Vector4D surfacePlane; // x,y,z normal, dist (plane constant) fluid surface
  824. Vector currentVelocity; // velocity of the current in inches/second
  825. float damping; // damping factor for buoyancy (tweak)
  826. float torqueFactor;
  827. float viscosityFactor;
  828. void *pGameData;
  829. bool useAerodynamics;// true if this controller should calculate surface pressure
  830. int contents;
  831. fluidparams_t() {}
  832. fluidparams_t( fluidparams_t const& src )
  833. {
  834. Vector4DCopy( src.surfacePlane, surfacePlane );
  835. VectorCopy( src.currentVelocity, currentVelocity );
  836. damping = src.damping;
  837. torqueFactor = src.torqueFactor;
  838. viscosityFactor = src.viscosityFactor;
  839. contents = src.contents;
  840. }
  841. };
  842. //-----------------------------------------------------------------------------
  843. // Purpose: parameter block for creating linear springs
  844. // UNDONE: Expose additional spring model paramters?
  845. //-----------------------------------------------------------------------------
  846. struct springparams_t
  847. {
  848. springparams_t()
  849. {
  850. memset( this, 0, sizeof(*this) );
  851. }
  852. float constant; // spring constant
  853. float naturalLength;// relaxed length
  854. float damping; // damping factor
  855. float relativeDamping; // relative damping (damping proportional to the change in the relative position of the objects)
  856. Vector startPosition;
  857. Vector endPosition;
  858. bool useLocalPositions; // start & end Position are in local space to start and end objects if this is true
  859. bool onlyStretch; // only apply forces when the length is greater than the natural length
  860. };
  861. //-----------------------------------------------------------------------------
  862. // Purpose: parameter block for creating polygonal objects
  863. //-----------------------------------------------------------------------------
  864. struct objectparams_t
  865. {
  866. Vector *massCenterOverride;
  867. float mass;
  868. float inertia;
  869. float damping;
  870. float rotdamping;
  871. float rotInertiaLimit;
  872. const char *pName; // used only for debugging
  873. void *pGameData;
  874. float volume;
  875. float dragCoefficient;
  876. bool enableCollisions;
  877. };
  878. struct convertconvexparams_t
  879. {
  880. bool buildOuterConvexHull;
  881. bool buildDragAxisAreas;
  882. bool buildOptimizedTraceTables;
  883. float dragAreaEpsilon;
  884. CPhysConvex *pForcedOuterHull;
  885. void Defaults()
  886. {
  887. dragAreaEpsilon = 0.25f; // 0.5in x 0.5in square
  888. buildOuterConvexHull = false;
  889. buildDragAxisAreas = false;
  890. buildOptimizedTraceTables = false;
  891. pForcedOuterHull = NULL;
  892. }
  893. };
  894. //-----------------------------------------------------------------------------
  895. // Physics interface IDs
  896. //
  897. // Note that right now the order of the enum also defines the order of save/load
  898. //-----------------------------------------------------------------------------
  899. // Purpose: parameter blocks for save and load operations
  900. //-----------------------------------------------------------------------------
  901. struct physsaveparams_t
  902. {
  903. ISave *pSave;
  904. void *pObject;
  905. PhysInterfaceId_t type;
  906. };
  907. struct physrestoreparams_t
  908. {
  909. IRestore *pRestore;
  910. void **ppObject;
  911. PhysInterfaceId_t type;
  912. void *pGameData;
  913. const char *pName; // used only for debugging
  914. const CPhysCollide *pCollisionModel;
  915. IPhysicsEnvironment *pEnvironment;
  916. IPhysicsGameTrace *pGameTrace;
  917. };
  918. struct physrecreateparams_t
  919. {
  920. void *pOldObject;
  921. void *pNewObject;
  922. };
  923. struct physprerestoreparams_t
  924. {
  925. int recreatedObjectCount;
  926. physrecreateparams_t recreatedObjectList[1];
  927. };
  928. //-------------------------------------
  929. #define DEFINE_PIID( type, enumval ) \
  930. template <> inline PhysInterfaceId_t GetPhysIID<type>( type ** ) { return enumval; }
  931. template <class PHYSPTR> inline PhysInterfaceId_t GetPhysIID(PHYSPTR **); // will get link error if no match
  932. DEFINE_PIID( IPhysicsObject, PIID_IPHYSICSOBJECT );
  933. DEFINE_PIID( IPhysicsFluidController, PIID_IPHYSICSFLUIDCONTROLLER );
  934. DEFINE_PIID( IPhysicsSpring, PIID_IPHYSICSSPRING );
  935. DEFINE_PIID( IPhysicsConstraintGroup, PIID_IPHYSICSCONSTRAINTGROUP );
  936. DEFINE_PIID( IPhysicsConstraint, PIID_IPHYSICSCONSTRAINT );
  937. DEFINE_PIID( IPhysicsShadowController, PIID_IPHYSICSSHADOWCONTROLLER );
  938. DEFINE_PIID( IPhysicsPlayerController, PIID_IPHYSICSPLAYERCONTROLLER );
  939. DEFINE_PIID( IPhysicsMotionController, PIID_IPHYSICSMOTIONCONTROLLER );
  940. DEFINE_PIID( IPhysicsVehicleController, PIID_IPHYSICSVEHICLECONTROLLER );
  941. DEFINE_PIID( IPhysicsGameTrace, PIID_IPHYSICSGAMETRACE );
  942. //-----------------------------------------------------------------------------
  943. #endif // VPHYSICS_INTERFACE_H