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.

3592 lines
102 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose: Base combat character with no AI
  4. //
  5. //=============================================================================//
  6. #include "cbase.h"
  7. #include "basecombatcharacter.h"
  8. #include "basecombatweapon.h"
  9. #include "animation.h"
  10. #include "gib.h"
  11. #include "entitylist.h"
  12. #include "gamerules.h"
  13. #include "ai_basenpc.h"
  14. #include "ai_squadslot.h"
  15. #include "ammodef.h"
  16. #include "ndebugoverlay.h"
  17. #include "player.h"
  18. #include "physics.h"
  19. #include "engine/IEngineSound.h"
  20. #include "tier1/strtools.h"
  21. #include "sendproxy.h"
  22. #include "EntityFlame.h"
  23. #include "CRagdollMagnet.h"
  24. #include "IEffects.h"
  25. #include "iservervehicle.h"
  26. #include "igamesystem.h"
  27. #include "globals.h"
  28. #include "physics_prop_ragdoll.h"
  29. #include "physics_impact_damage.h"
  30. #include "saverestore_utlvector.h"
  31. #include "eventqueue.h"
  32. #include "world.h"
  33. #include "globalstate.h"
  34. #include "items.h"
  35. #include "movevars_shared.h"
  36. #include "RagdollBoogie.h"
  37. #include "rumble_shared.h"
  38. #include "saverestoretypes.h"
  39. #include "nav_mesh.h"
  40. #ifdef NEXT_BOT
  41. #include "NextBot/NextBotManager.h"
  42. #endif
  43. #ifdef HL2_DLL
  44. #include "weapon_physcannon.h"
  45. #include "hl2_gamerules.h"
  46. #endif
  47. #ifdef PORTAL
  48. #include "portal_util_shared.h"
  49. #include "prop_portal_shared.h"
  50. #include "portal_shareddefs.h"
  51. #endif
  52. // memdbgon must be the last include file in a .cpp file!!!
  53. #include "tier0/memdbgon.h"
  54. #ifdef HL2_DLL
  55. extern int g_interactionBarnacleVictimReleased;
  56. #endif //HL2_DLL
  57. extern ConVar weapon_showproficiency;
  58. ConVar ai_show_hull_attacks( "ai_show_hull_attacks", "0" );
  59. ConVar ai_force_serverside_ragdoll( "ai_force_serverside_ragdoll", "0" );
  60. ConVar nb_last_area_update_tolerance( "nb_last_area_update_tolerance", "4.0", FCVAR_CHEAT, "Distance a character needs to travel in order to invalidate cached area" ); // 4.0 tested as sweet spot (for wanderers, at least). More resulted in little benefit, less quickly diminished benefit [7/31/2008 tom]
  61. #ifndef _RETAIL
  62. ConVar ai_use_visibility_cache( "ai_use_visibility_cache", "1" );
  63. #define ShouldUseVisibilityCache() ai_use_visibility_cache.GetBool()
  64. #else
  65. #define ShouldUseVisibilityCache() true
  66. #endif
  67. BEGIN_DATADESC( CBaseCombatCharacter )
  68. #ifdef INVASION_DLL
  69. DEFINE_FIELD( m_iPowerups, FIELD_INTEGER ),
  70. DEFINE_ARRAY( m_flPowerupAttemptTimes, FIELD_TIME, MAX_POWERUPS ),
  71. DEFINE_ARRAY( m_flPowerupEndTimes, FIELD_TIME, MAX_POWERUPS ),
  72. DEFINE_FIELD( m_flFractionalBoost, FIELD_FLOAT ),
  73. #endif
  74. DEFINE_FIELD( m_flNextAttack, FIELD_TIME ),
  75. DEFINE_FIELD( m_eHull, FIELD_INTEGER ),
  76. DEFINE_FIELD( m_bloodColor, FIELD_INTEGER ),
  77. DEFINE_FIELD( m_iDamageCount, FIELD_INTEGER ),
  78. DEFINE_FIELD( m_flFieldOfView, FIELD_FLOAT ),
  79. DEFINE_FIELD( m_HackedGunPos, FIELD_VECTOR ),
  80. DEFINE_KEYFIELD( m_RelationshipString, FIELD_STRING, "Relationship" ),
  81. DEFINE_FIELD( m_LastHitGroup, FIELD_INTEGER ),
  82. DEFINE_FIELD( m_flDamageAccumulator, FIELD_FLOAT ),
  83. DEFINE_INPUT( m_impactEnergyScale, FIELD_FLOAT, "physdamagescale" ),
  84. DEFINE_FIELD( m_CurrentWeaponProficiency, FIELD_INTEGER),
  85. DEFINE_UTLVECTOR( m_Relationship, FIELD_EMBEDDED),
  86. DEFINE_AUTO_ARRAY( m_iAmmo, FIELD_INTEGER ),
  87. DEFINE_AUTO_ARRAY( m_hMyWeapons, FIELD_EHANDLE ),
  88. DEFINE_FIELD( m_hActiveWeapon, FIELD_EHANDLE ),
  89. DEFINE_FIELD( m_bForceServerRagdoll, FIELD_BOOLEAN ),
  90. DEFINE_FIELD( m_bPreventWeaponPickup, FIELD_BOOLEAN ),
  91. DEFINE_INPUTFUNC( FIELD_VOID, "KilledNPC", InputKilledNPC ),
  92. END_DATADESC()
  93. BEGIN_SIMPLE_DATADESC( Relationship_t )
  94. DEFINE_FIELD( entity, FIELD_EHANDLE ),
  95. DEFINE_FIELD( classType, FIELD_INTEGER ),
  96. DEFINE_FIELD( disposition, FIELD_INTEGER ),
  97. DEFINE_FIELD( priority, FIELD_INTEGER ),
  98. END_DATADESC()
  99. //-----------------------------------------------------------------------------
  100. // Init static variables
  101. //-----------------------------------------------------------------------------
  102. int CBaseCombatCharacter::m_lastInteraction = 0;
  103. Relationship_t** CBaseCombatCharacter::m_DefaultRelationship = NULL;
  104. //-----------------------------------------------------------------------------
  105. // Purpose:
  106. //-----------------------------------------------------------------------------
  107. class CCleanupDefaultRelationShips : public CAutoGameSystem
  108. {
  109. public:
  110. CCleanupDefaultRelationShips( char const *name ) : CAutoGameSystem( name )
  111. {
  112. }
  113. virtual void Shutdown()
  114. {
  115. if ( !CBaseCombatCharacter::m_DefaultRelationship )
  116. return;
  117. for ( int i=0; i<NUM_AI_CLASSES; ++i )
  118. {
  119. delete[] CBaseCombatCharacter::m_DefaultRelationship[ i ];
  120. }
  121. delete[] CBaseCombatCharacter::m_DefaultRelationship;
  122. CBaseCombatCharacter::m_DefaultRelationship = NULL;
  123. }
  124. };
  125. static CCleanupDefaultRelationShips g_CleanupDefaultRelationships( "CCleanupDefaultRelationShips" );
  126. void *SendProxy_SendBaseCombatCharacterLocalDataTable( const SendProp *pProp, const void *pStruct, const void *pVarData, CSendProxyRecipients *pRecipients, int objectID )
  127. {
  128. // Only send to local player if this is a player
  129. pRecipients->ClearAllRecipients();
  130. CBaseCombatCharacter *pBCC = ( CBaseCombatCharacter * )pStruct;
  131. if ( pBCC != NULL)
  132. {
  133. if ( pBCC->IsPlayer() )
  134. {
  135. pRecipients->SetOnly( pBCC->entindex() - 1 );
  136. }
  137. else
  138. {
  139. // If it's a vehicle, send to "driver" (e.g., operator of tf2 manned guns)
  140. IServerVehicle *pVehicle = pBCC->GetServerVehicle();
  141. if ( pVehicle != NULL )
  142. {
  143. CBaseCombatCharacter *pDriver = pVehicle->GetPassenger();
  144. if ( pDriver != NULL )
  145. {
  146. pRecipients->SetOnly( pDriver->entindex() - 1 );
  147. }
  148. }
  149. }
  150. }
  151. return ( void * )pVarData;
  152. }
  153. REGISTER_SEND_PROXY_NON_MODIFIED_POINTER( SendProxy_SendBaseCombatCharacterLocalDataTable );
  154. // Only send active weapon index to local player
  155. BEGIN_SEND_TABLE_NOBASE( CBaseCombatCharacter, DT_BCCLocalPlayerExclusive )
  156. SendPropTime( SENDINFO( m_flNextAttack ) ),
  157. END_SEND_TABLE();
  158. //-----------------------------------------------------------------------------
  159. // This table encodes the CBaseCombatCharacter
  160. //-----------------------------------------------------------------------------
  161. IMPLEMENT_SERVERCLASS_ST(CBaseCombatCharacter, DT_BaseCombatCharacter)
  162. #ifdef GLOWS_ENABLE
  163. SendPropBool( SENDINFO( m_bGlowEnabled ) ),
  164. #endif // GLOWS_ENABLE
  165. // Data that only gets sent to the local player.
  166. SendPropDataTable( "bcc_localdata", 0, &REFERENCE_SEND_TABLE(DT_BCCLocalPlayerExclusive), SendProxy_SendBaseCombatCharacterLocalDataTable ),
  167. SendPropEHandle( SENDINFO( m_hActiveWeapon ) ),
  168. SendPropArray3( SENDINFO_ARRAY3(m_hMyWeapons), SendPropEHandle( SENDINFO_ARRAY(m_hMyWeapons) ) ),
  169. #ifdef INVASION_DLL
  170. SendPropInt( SENDINFO(m_iPowerups), MAX_POWERUPS, SPROP_UNSIGNED ),
  171. #endif
  172. END_SEND_TABLE()
  173. //-----------------------------------------------------------------------------
  174. // Interactions
  175. //-----------------------------------------------------------------------------
  176. void CBaseCombatCharacter::InitInteractionSystem()
  177. {
  178. // interaction ids continue to go up with every map load, otherwise you get
  179. // collisions if a future map has a different set of NPCs from a current map
  180. }
  181. //-----------------------------------------------------------------------------
  182. // Purpose: Return an interaction ID (so we have no collisions)
  183. //-----------------------------------------------------------------------------
  184. int CBaseCombatCharacter::GetInteractionID(void)
  185. {
  186. m_lastInteraction++;
  187. return (m_lastInteraction);
  188. }
  189. // ============================================================================
  190. bool CBaseCombatCharacter::HasHumanGibs( void )
  191. {
  192. #if defined( HL2_DLL )
  193. Class_T myClass = Classify();
  194. if ( myClass == CLASS_CITIZEN_PASSIVE ||
  195. myClass == CLASS_CITIZEN_REBEL ||
  196. myClass == CLASS_COMBINE ||
  197. myClass == CLASS_CONSCRIPT ||
  198. myClass == CLASS_METROPOLICE ||
  199. myClass == CLASS_PLAYER )
  200. return true;
  201. #elif defined( HL1_DLL )
  202. Class_T myClass = Classify();
  203. if ( myClass == CLASS_HUMAN_MILITARY ||
  204. myClass == CLASS_PLAYER_ALLY ||
  205. myClass == CLASS_HUMAN_PASSIVE ||
  206. myClass == CLASS_PLAYER )
  207. {
  208. return true;
  209. }
  210. #elif defined( CSPORT_DLL )
  211. Class_T myClass = Classify();
  212. if ( myClass == CLASS_PLAYER )
  213. {
  214. return true;
  215. }
  216. #endif
  217. return false;
  218. }
  219. bool CBaseCombatCharacter::HasAlienGibs( void )
  220. {
  221. #if defined( HL2_DLL )
  222. Class_T myClass = Classify();
  223. if ( myClass == CLASS_BARNACLE ||
  224. myClass == CLASS_STALKER ||
  225. myClass == CLASS_ZOMBIE ||
  226. myClass == CLASS_VORTIGAUNT ||
  227. myClass == CLASS_HEADCRAB )
  228. {
  229. return true;
  230. }
  231. #elif defined( HL1_DLL )
  232. Class_T myClass = Classify();
  233. if ( myClass == CLASS_ALIEN_MILITARY ||
  234. myClass == CLASS_ALIEN_MONSTER ||
  235. myClass == CLASS_INSECT ||
  236. myClass == CLASS_ALIEN_PREDATOR ||
  237. myClass == CLASS_ALIEN_PREY )
  238. {
  239. return true;
  240. }
  241. #endif
  242. return false;
  243. }
  244. void CBaseCombatCharacter::CorpseFade( void )
  245. {
  246. StopAnimation();
  247. SetAbsVelocity( vec3_origin );
  248. SetMoveType( MOVETYPE_NONE );
  249. SetLocalAngularVelocity( vec3_angle );
  250. m_flAnimTime = gpGlobals->curtime;
  251. IncrementInterpolationFrame();
  252. SUB_StartFadeOut();
  253. }
  254. //-----------------------------------------------------------------------------
  255. // Visibility caching
  256. //-----------------------------------------------------------------------------
  257. struct VisibilityCacheEntry_t
  258. {
  259. CBaseEntity *pEntity1;
  260. CBaseEntity *pEntity2;
  261. EHANDLE pBlocker;
  262. float time;
  263. };
  264. class CVisibilityCacheEntryLess
  265. {
  266. public:
  267. CVisibilityCacheEntryLess( int ) {}
  268. bool operator!() const { return false; }
  269. bool operator()( const VisibilityCacheEntry_t &lhs, const VisibilityCacheEntry_t &rhs ) const
  270. {
  271. return ( memcmp( &lhs, &rhs, offsetof( VisibilityCacheEntry_t, pBlocker ) ) < 0 );
  272. }
  273. };
  274. static CUtlRBTree<VisibilityCacheEntry_t, unsigned short, CVisibilityCacheEntryLess> g_VisibilityCache;
  275. const float VIS_CACHE_ENTRY_LIFE = ( !IsXbox() ) ? .090 : .500;
  276. bool CBaseCombatCharacter::FVisible( CBaseEntity *pEntity, int traceMask, CBaseEntity **ppBlocker )
  277. {
  278. VPROF( "CBaseCombatCharacter::FVisible" );
  279. if ( traceMask != MASK_BLOCKLOS || !ShouldUseVisibilityCache() || pEntity == this
  280. #if defined(HL2_DLL)
  281. || Classify() == CLASS_BULLSEYE || pEntity->Classify() == CLASS_BULLSEYE
  282. #endif
  283. )
  284. {
  285. return BaseClass::FVisible( pEntity, traceMask, ppBlocker );
  286. }
  287. VisibilityCacheEntry_t cacheEntry;
  288. if ( this < pEntity )
  289. {
  290. cacheEntry.pEntity1 = this;
  291. cacheEntry.pEntity2 = pEntity;
  292. }
  293. else
  294. {
  295. cacheEntry.pEntity1 = pEntity;
  296. cacheEntry.pEntity2 = this;
  297. }
  298. int iCache = g_VisibilityCache.Find( cacheEntry );
  299. if ( iCache != g_VisibilityCache.InvalidIndex() )
  300. {
  301. if ( gpGlobals->curtime - g_VisibilityCache[iCache].time < VIS_CACHE_ENTRY_LIFE )
  302. {
  303. bool bCachedResult = !g_VisibilityCache[iCache].pBlocker.IsValid();
  304. if ( bCachedResult )
  305. {
  306. if ( ppBlocker )
  307. {
  308. *ppBlocker = g_VisibilityCache[iCache].pBlocker;
  309. if ( !*ppBlocker )
  310. {
  311. *ppBlocker = GetWorldEntity();
  312. }
  313. }
  314. }
  315. else
  316. {
  317. if ( ppBlocker )
  318. {
  319. *ppBlocker = NULL;
  320. }
  321. }
  322. return bCachedResult;
  323. }
  324. }
  325. else
  326. {
  327. if ( g_VisibilityCache.Count() != g_VisibilityCache.InvalidIndex() )
  328. {
  329. iCache = g_VisibilityCache.Insert( cacheEntry );
  330. }
  331. else
  332. {
  333. return BaseClass::FVisible( pEntity, traceMask, ppBlocker );
  334. }
  335. }
  336. CBaseEntity *pBlocker = NULL;
  337. if ( ppBlocker == NULL )
  338. {
  339. ppBlocker = &pBlocker;
  340. }
  341. bool bResult = BaseClass::FVisible( pEntity, traceMask, ppBlocker );
  342. if ( !bResult )
  343. {
  344. g_VisibilityCache[iCache].pBlocker = *ppBlocker;
  345. }
  346. else
  347. {
  348. g_VisibilityCache[iCache].pBlocker = NULL;
  349. }
  350. g_VisibilityCache[iCache].time = gpGlobals->curtime;
  351. return bResult;
  352. }
  353. void CBaseCombatCharacter::ResetVisibilityCache( CBaseCombatCharacter *pBCC )
  354. {
  355. VPROF( "CBaseCombatCharacter::ResetVisibilityCache" );
  356. if ( !pBCC )
  357. {
  358. g_VisibilityCache.RemoveAll();
  359. return;
  360. }
  361. int i = g_VisibilityCache.FirstInorder();
  362. CUtlVector<unsigned short> removals;
  363. while ( i != g_VisibilityCache.InvalidIndex() )
  364. {
  365. if ( g_VisibilityCache[i].pEntity1 == pBCC || g_VisibilityCache[i].pEntity2 == pBCC )
  366. {
  367. removals.AddToTail( i );
  368. }
  369. i = g_VisibilityCache.NextInorder( i );
  370. }
  371. for ( i = 0; i < removals.Count(); i++ )
  372. {
  373. g_VisibilityCache.RemoveAt( removals[i] );
  374. }
  375. }
  376. #ifdef PORTAL
  377. bool CBaseCombatCharacter::FVisibleThroughPortal( const CProp_Portal *pPortal, CBaseEntity *pEntity, int traceMask, CBaseEntity **ppBlocker )
  378. {
  379. VPROF( "CBaseCombatCharacter::FVisible" );
  380. if ( pEntity->GetFlags() & FL_NOTARGET )
  381. return false;
  382. #if HL1_DLL
  383. // FIXME: only block LOS through opaque water
  384. // don't look through water
  385. if ((m_nWaterLevel != 3 && pEntity->m_nWaterLevel == 3)
  386. || (m_nWaterLevel == 3 && pEntity->m_nWaterLevel == 0))
  387. return false;
  388. #endif
  389. Vector vecLookerOrigin = EyePosition();//look through the caller's 'eyes'
  390. Vector vecTargetOrigin = pEntity->EyePosition();
  391. // Use the custom LOS trace filter
  392. CTraceFilterLOS traceFilter( this, COLLISION_GROUP_NONE, pEntity );
  393. Vector vecTranslatedTargetOrigin;
  394. UTIL_Portal_PointTransform( pPortal->m_hLinkedPortal->MatrixThisToLinked(), vecTargetOrigin, vecTranslatedTargetOrigin );
  395. Ray_t ray;
  396. ray.Init( vecLookerOrigin, vecTranslatedTargetOrigin );
  397. trace_t tr;
  398. // If we're doing an opaque search, include NPCs.
  399. if ( traceMask == MASK_BLOCKLOS )
  400. {
  401. traceMask = MASK_BLOCKLOS_AND_NPCS;
  402. }
  403. UTIL_Portal_TraceRay_Bullets( pPortal, ray, traceMask, &traceFilter, &tr );
  404. if (tr.fraction != 1.0 || tr.startsolid )
  405. {
  406. // If we hit the entity we're looking for, it's visible
  407. if ( tr.m_pEnt == pEntity )
  408. return true;
  409. // Got line of sight on the vehicle the player is driving!
  410. if ( pEntity && pEntity->IsPlayer() )
  411. {
  412. CBasePlayer *pPlayer = assert_cast<CBasePlayer*>( pEntity );
  413. if ( tr.m_pEnt == pPlayer->GetVehicleEntity() )
  414. return true;
  415. }
  416. if (ppBlocker)
  417. {
  418. *ppBlocker = tr.m_pEnt;
  419. }
  420. return false;// Line of sight is not established
  421. }
  422. return true;// line of sight is valid.
  423. }
  424. #endif
  425. //-----------------------------------------------------------------------------
  426. //=========================================================
  427. // FInViewCone - returns true is the passed ent is in
  428. // the caller's forward view cone. The dot product is performed
  429. // in 2d, making the view cone infinitely tall.
  430. //=========================================================
  431. bool CBaseCombatCharacter::FInViewCone( CBaseEntity *pEntity )
  432. {
  433. return FInViewCone( pEntity->WorldSpaceCenter() );
  434. }
  435. //=========================================================
  436. // FInViewCone - returns true is the passed Vector is in
  437. // the caller's forward view cone. The dot product is performed
  438. // in 2d, making the view cone infinitely tall.
  439. //=========================================================
  440. bool CBaseCombatCharacter::FInViewCone( const Vector &vecSpot )
  441. {
  442. Vector los = ( vecSpot - EyePosition() );
  443. // do this in 2D
  444. los.z = 0;
  445. VectorNormalize( los );
  446. Vector facingDir = EyeDirection2D( );
  447. float flDot = DotProduct( los, facingDir );
  448. if ( flDot > m_flFieldOfView )
  449. return true;
  450. return false;
  451. }
  452. #ifdef PORTAL
  453. //=========================================================
  454. // FInViewCone - returns true is the passed ent is in
  455. // the caller's forward view cone. The dot product is performed
  456. // in 2d, making the view cone infinitely tall.
  457. //=========================================================
  458. CProp_Portal* CBaseCombatCharacter::FInViewConeThroughPortal( CBaseEntity *pEntity )
  459. {
  460. return FInViewConeThroughPortal( pEntity->WorldSpaceCenter() );
  461. }
  462. //=========================================================
  463. // FInViewCone - returns true is the passed Vector is in
  464. // the caller's forward view cone. The dot product is performed
  465. // in 2d, making the view cone infinitely tall.
  466. //=========================================================
  467. CProp_Portal* CBaseCombatCharacter::FInViewConeThroughPortal( const Vector &vecSpot )
  468. {
  469. int iPortalCount = CProp_Portal_Shared::AllPortals.Count();
  470. if( iPortalCount == 0 )
  471. return NULL;
  472. const Vector ptEyePosition = EyePosition();
  473. float fDistToBeat = 1e20; //arbitrarily high number
  474. CProp_Portal *pBestPortal = NULL;
  475. CProp_Portal **pPortals = CProp_Portal_Shared::AllPortals.Base();
  476. // Check through both portals
  477. for ( int iPortal = 0; iPortal < iPortalCount; ++iPortal )
  478. {
  479. CProp_Portal *pPortal = pPortals[iPortal];
  480. // Check if this portal is active, linked, and in the view cone
  481. if( pPortal->IsActivedAndLinked() && FInViewCone( pPortal ) )
  482. {
  483. // The facing direction is the eye to the portal to set up a proper FOV through the relatively small portal hole
  484. Vector facingDir = pPortal->GetAbsOrigin() - ptEyePosition;
  485. // If the portal isn't facing the eye, bail
  486. if ( facingDir.Dot( pPortal->m_plane_Origin.normal ) > 0.0f )
  487. continue;
  488. // If the point is behind the linked portal, bail
  489. if ( ( vecSpot - pPortal->m_hLinkedPortal->GetAbsOrigin() ).Dot( pPortal->m_hLinkedPortal->m_plane_Origin.normal ) < 0.0f )
  490. continue;
  491. // Remove height from the equation
  492. facingDir.z = 0.0f;
  493. float fPortalDist = VectorNormalize( facingDir );
  494. // Translate the target spot across the portal
  495. Vector vTranslatedVecSpot;
  496. UTIL_Portal_PointTransform( pPortal->m_hLinkedPortal->MatrixThisToLinked(), vecSpot, vTranslatedVecSpot );
  497. // do this in 2D
  498. Vector los = ( vTranslatedVecSpot - ptEyePosition );
  499. los.z = 0.0f;
  500. float fSpotDist = VectorNormalize( los );
  501. if( fSpotDist > fDistToBeat )
  502. continue; //no point in going further, we already have a better portal
  503. // If the target point is closer than the portal (banana juice), bail
  504. // HACK: Extra 32 is a fix for the player who's origin can be on one side of a portal while his center mirrored across is closer than the portal.
  505. if ( fPortalDist > fSpotDist + 32.0f )
  506. continue;
  507. // Get the worst case FOV from the portal's corners
  508. float fFOVThroughPortal = 1.0f;
  509. for ( int i = 0; i < 4; ++i )
  510. {
  511. //Vector vPortalCorner = pPortal->GetAbsOrigin() + vPortalRight * PORTAL_HALF_WIDTH * ( ( i / 2 == 0 ) ? ( 1.0f ) : ( -1.0f ) ) +
  512. // vPortalUp * PORTAL_HALF_HEIGHT * ( ( i % 2 == 0 ) ? ( 1.0f ) : ( -1.0f ) );
  513. Vector vEyeToCorner = pPortal->m_vPortalCorners[i] - ptEyePosition;
  514. vEyeToCorner.z = 0.0f;
  515. VectorNormalize( vEyeToCorner );
  516. float flCornerDot = DotProduct( vEyeToCorner, facingDir );
  517. if ( flCornerDot < fFOVThroughPortal )
  518. fFOVThroughPortal = flCornerDot;
  519. }
  520. float flDot = DotProduct( los, facingDir );
  521. // Use the tougher FOV of either the standard FOV or FOV clipped to the portal hole
  522. if ( flDot > MAX( fFOVThroughPortal, m_flFieldOfView ) )
  523. {
  524. float fActualDist = ptEyePosition.DistToSqr( vTranslatedVecSpot );
  525. if( fActualDist < fDistToBeat )
  526. {
  527. fDistToBeat = fActualDist;
  528. pBestPortal = pPortal;
  529. }
  530. }
  531. }
  532. }
  533. return pBestPortal;
  534. }
  535. #endif
  536. //=========================================================
  537. // FInAimCone - returns true is the passed ent is in
  538. // the caller's forward aim cone. The dot product is performed
  539. // in 2d, making the aim cone infinitely tall.
  540. //=========================================================
  541. bool CBaseCombatCharacter::FInAimCone( CBaseEntity *pEntity )
  542. {
  543. return FInAimCone( pEntity->BodyTarget( EyePosition() ) );
  544. }
  545. //=========================================================
  546. // FInAimCone - returns true is the passed Vector is in
  547. // the caller's forward aim cone. The dot product is performed
  548. // in 2d, making the view cone infinitely tall. By default, the
  549. // callers aim cone is assumed to be very narrow
  550. //=========================================================
  551. bool CBaseCombatCharacter::FInAimCone( const Vector &vecSpot )
  552. {
  553. Vector los = ( vecSpot - GetAbsOrigin() );
  554. // do this in 2D
  555. los.z = 0;
  556. VectorNormalize( los );
  557. Vector facingDir = BodyDirection2D( );
  558. float flDot = DotProduct( los, facingDir );
  559. if ( flDot > 0.994 )//!!!BUGBUG - magic number same as FacingIdeal(), what is this?
  560. return true;
  561. return false;
  562. }
  563. //-----------------------------------------------------------------------------
  564. // Purpose: This is a generic function (to be implemented by sub-classes) to
  565. // handle specific interactions between different types of characters
  566. // (For example the barnacle grabbing an NPC)
  567. // Input : The type of interaction, extra info pointer, and who started it
  568. // Output : true - if sub-class has a response for the interaction
  569. // false - if sub-class has no response
  570. //-----------------------------------------------------------------------------
  571. bool CBaseCombatCharacter::HandleInteraction( int interactionType, void *data, CBaseCombatCharacter* sourceEnt )
  572. {
  573. #ifdef HL2_DLL
  574. if ( interactionType == g_interactionBarnacleVictimReleased )
  575. {
  576. // For now, throw away the NPC and leave the ragdoll.
  577. UTIL_Remove( this );
  578. return true;
  579. }
  580. #endif // HL2_DLL
  581. return false;
  582. }
  583. //-----------------------------------------------------------------------------
  584. // Purpose: Constructor : Initialize some fields
  585. //-----------------------------------------------------------------------------
  586. CBaseCombatCharacter::CBaseCombatCharacter( void )
  587. {
  588. #ifdef _DEBUG
  589. // necessary since in debug, we initialize vectors to NAN for debugging
  590. m_HackedGunPos.Init();
  591. #endif
  592. // Zero the damage accumulator.
  593. m_flDamageAccumulator = 0.0f;
  594. // Init weapon and Ammo data
  595. m_hActiveWeapon = NULL;
  596. // reset all ammo values to 0
  597. RemoveAllAmmo();
  598. // not alive yet
  599. m_aliveTimer.Invalidate();
  600. m_hasBeenInjured = 0;
  601. for( int t=0; t<MAX_DAMAGE_TEAMS; ++t )
  602. {
  603. m_damageHistory[t].team = TEAM_INVALID;
  604. }
  605. // not standing on a nav area yet
  606. m_lastNavArea = NULL;
  607. m_registeredNavTeam = TEAM_INVALID;
  608. for (int i = 0; i < MAX_WEAPONS; i++)
  609. {
  610. m_hMyWeapons.Set( i, NULL );
  611. }
  612. // Default so that spawned entities have this set
  613. m_impactEnergyScale = 1.0f;
  614. m_bForceServerRagdoll = ai_force_serverside_ragdoll.GetBool();
  615. #ifdef GLOWS_ENABLE
  616. m_bGlowEnabled.Set( false );
  617. #endif // GLOWS_ENABLE
  618. }
  619. //------------------------------------------------------------------------------
  620. // Purpose : Destructor
  621. // Input :
  622. // Output :
  623. //------------------------------------------------------------------------------
  624. CBaseCombatCharacter::~CBaseCombatCharacter( void )
  625. {
  626. ResetVisibilityCache( this );
  627. ClearLastKnownArea();
  628. }
  629. //-----------------------------------------------------------------------------
  630. // Purpose: Put the combat character into the environment
  631. //-----------------------------------------------------------------------------
  632. void CBaseCombatCharacter::Spawn( void )
  633. {
  634. BaseClass::Spawn();
  635. SetBlocksLOS( false );
  636. m_aliveTimer.Start();
  637. m_hasBeenInjured = 0;
  638. for( int t=0; t<MAX_DAMAGE_TEAMS; ++t )
  639. {
  640. m_damageHistory[t].team = TEAM_INVALID;
  641. }
  642. // not standing on a nav area yet
  643. ClearLastKnownArea();
  644. }
  645. //-----------------------------------------------------------------------------
  646. // Purpose:
  647. //-----------------------------------------------------------------------------
  648. void CBaseCombatCharacter::Precache()
  649. {
  650. BaseClass::Precache();
  651. PrecacheScriptSound( "BaseCombatCharacter.CorpseGib" );
  652. PrecacheScriptSound( "BaseCombatCharacter.StopWeaponSounds" );
  653. PrecacheScriptSound( "BaseCombatCharacter.AmmoPickup" );
  654. for ( int i = m_Relationship.Count() - 1; i >= 0 ; i--)
  655. {
  656. if ( !m_Relationship[i].entity && m_Relationship[i].classType == CLASS_NONE )
  657. {
  658. DevMsg( 2, "Removing relationship for lost entity\n" );
  659. m_Relationship.FastRemove( i );
  660. }
  661. }
  662. }
  663. //-----------------------------------------------------------------------------
  664. // Purpose:
  665. //-----------------------------------------------------------------------------
  666. int CBaseCombatCharacter::Restore( IRestore &restore )
  667. {
  668. int status = BaseClass::Restore(restore);
  669. if ( !status )
  670. return 0;
  671. if ( gpGlobals->eLoadType == MapLoad_Transition )
  672. {
  673. DevMsg( 2, "%s (%s) removing class relationships due to level transition\n", STRING( GetEntityName() ), GetClassname() );
  674. for ( int i = m_Relationship.Count() - 1; i >= 0; --i )
  675. {
  676. if ( !m_Relationship[i].entity && m_Relationship[i].classType != CLASS_NONE )
  677. {
  678. m_Relationship.FastRemove( i );
  679. }
  680. }
  681. }
  682. return status;
  683. }
  684. //-----------------------------------------------------------------------------
  685. // Purpose:
  686. //-----------------------------------------------------------------------------
  687. void CBaseCombatCharacter::UpdateOnRemove( void )
  688. {
  689. int i;
  690. // Make sure any weapons I didn't drop get removed.
  691. for (i=0;i<MAX_WEAPONS;i++)
  692. {
  693. if (m_hMyWeapons[i])
  694. {
  695. UTIL_Remove( m_hMyWeapons[i] );
  696. }
  697. }
  698. // tell owner ( if any ) that we're dead.This is mostly for NPCMaker functionality.
  699. CBaseEntity *pOwner = GetOwnerEntity();
  700. if ( pOwner )
  701. {
  702. pOwner->DeathNotice( this );
  703. SetOwnerEntity( NULL );
  704. }
  705. #ifdef GLOWS_ENABLE
  706. RemoveGlowEffect();
  707. #endif // GLOWS_ENABLE
  708. // Chain at end to mimic destructor unwind order
  709. BaseClass::UpdateOnRemove();
  710. }
  711. //=========================================================
  712. // CorpseGib - create some gore and get rid of a character's
  713. // model.
  714. //=========================================================
  715. bool CBaseCombatCharacter::CorpseGib( const CTakeDamageInfo &info )
  716. {
  717. trace_t tr;
  718. bool gibbed = false;
  719. EmitSound( "BaseCombatCharacter.CorpseGib" );
  720. // only humans throw skulls !!!UNDONE - eventually NPCs will have their own sets of gibs
  721. if ( HasHumanGibs() )
  722. {
  723. CGib::SpawnHeadGib( this );
  724. CGib::SpawnRandomGibs( this, 4, GIB_HUMAN ); // throw some human gibs.
  725. gibbed = true;
  726. }
  727. else if ( HasAlienGibs() )
  728. {
  729. CGib::SpawnRandomGibs( this, 4, GIB_ALIEN ); // Throw alien gibs
  730. gibbed = true;
  731. }
  732. return gibbed;
  733. }
  734. //=========================================================
  735. // GetDeathActivity - determines the best type of death
  736. // anim to play.
  737. //=========================================================
  738. Activity CBaseCombatCharacter::GetDeathActivity ( void )
  739. {
  740. Activity deathActivity;
  741. bool fTriedDirection;
  742. float flDot;
  743. trace_t tr;
  744. Vector vecSrc;
  745. if (IsPlayer())
  746. {
  747. // die in an interesting way
  748. switch( random->RandomInt(0,7) )
  749. {
  750. case 0: return ACT_DIESIMPLE;
  751. case 1: return ACT_DIEBACKWARD;
  752. case 2: return ACT_DIEFORWARD;
  753. case 3: return ACT_DIEVIOLENT;
  754. case 4: return ACT_DIE_HEADSHOT;
  755. case 5: return ACT_DIE_CHESTSHOT;
  756. case 6: return ACT_DIE_GUTSHOT;
  757. case 7: return ACT_DIE_BACKSHOT;
  758. }
  759. }
  760. vecSrc = WorldSpaceCenter();
  761. fTriedDirection = false;
  762. deathActivity = ACT_DIESIMPLE;// in case we can't find any special deaths to do.
  763. Vector forward;
  764. AngleVectors( GetLocalAngles(), &forward );
  765. flDot = -DotProduct( forward, g_vecAttackDir );
  766. switch ( m_LastHitGroup )
  767. {
  768. // try to pick a region-specific death.
  769. case HITGROUP_HEAD:
  770. deathActivity = ACT_DIE_HEADSHOT;
  771. break;
  772. case HITGROUP_STOMACH:
  773. deathActivity = ACT_DIE_GUTSHOT;
  774. break;
  775. case HITGROUP_GENERIC:
  776. // try to pick a death based on attack direction
  777. fTriedDirection = true;
  778. if ( flDot > 0.3 )
  779. {
  780. deathActivity = ACT_DIEFORWARD;
  781. }
  782. else if ( flDot <= -0.3 )
  783. {
  784. deathActivity = ACT_DIEBACKWARD;
  785. }
  786. break;
  787. default:
  788. // try to pick a death based on attack direction
  789. fTriedDirection = true;
  790. if ( flDot > 0.3 )
  791. {
  792. deathActivity = ACT_DIEFORWARD;
  793. }
  794. else if ( flDot <= -0.3 )
  795. {
  796. deathActivity = ACT_DIEBACKWARD;
  797. }
  798. break;
  799. }
  800. // can we perform the prescribed death?
  801. if ( SelectWeightedSequence ( deathActivity ) == ACTIVITY_NOT_AVAILABLE )
  802. {
  803. // no! did we fail to perform a directional death?
  804. if ( fTriedDirection )
  805. {
  806. // if yes, we're out of options. Go simple.
  807. deathActivity = ACT_DIESIMPLE;
  808. }
  809. else
  810. {
  811. // cannot perform the ideal region-specific death, so try a direction.
  812. if ( flDot > 0.3 )
  813. {
  814. deathActivity = ACT_DIEFORWARD;
  815. }
  816. else if ( flDot <= -0.3 )
  817. {
  818. deathActivity = ACT_DIEBACKWARD;
  819. }
  820. }
  821. }
  822. if ( SelectWeightedSequence ( deathActivity ) == ACTIVITY_NOT_AVAILABLE )
  823. {
  824. // if we're still invalid, simple is our only option.
  825. deathActivity = ACT_DIESIMPLE;
  826. if ( SelectWeightedSequence ( deathActivity ) == ACTIVITY_NOT_AVAILABLE )
  827. {
  828. Msg( "ERROR! %s missing ACT_DIESIMPLE\n", STRING(GetModelName()) );
  829. }
  830. }
  831. if ( deathActivity == ACT_DIEFORWARD )
  832. {
  833. // make sure there's room to fall forward
  834. UTIL_TraceHull ( vecSrc, vecSrc + forward * 64, Vector(-16,-16,-18),
  835. Vector(16,16,18), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
  836. if ( tr.fraction != 1.0 )
  837. {
  838. deathActivity = ACT_DIESIMPLE;
  839. }
  840. }
  841. if ( deathActivity == ACT_DIEBACKWARD )
  842. {
  843. // make sure there's room to fall backward
  844. UTIL_TraceHull ( vecSrc, vecSrc - forward * 64, Vector(-16,-16,-18),
  845. Vector(16,16,18), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
  846. if ( tr.fraction != 1.0 )
  847. {
  848. deathActivity = ACT_DIESIMPLE;
  849. }
  850. }
  851. return deathActivity;
  852. }
  853. // UNDONE: Should these operate on a list of weapon/items
  854. Activity CBaseCombatCharacter::Weapon_TranslateActivity( Activity baseAct, bool *pRequired )
  855. {
  856. Activity translated = baseAct;
  857. if ( m_hActiveWeapon )
  858. {
  859. translated = m_hActiveWeapon->ActivityOverride( baseAct, pRequired );
  860. }
  861. else if (pRequired)
  862. {
  863. *pRequired = false;
  864. }
  865. return translated;
  866. }
  867. //-----------------------------------------------------------------------------
  868. // Purpose: NPCs should override this function to translate activities
  869. // such as ACT_WALK, etc.
  870. // Input :
  871. // Output :
  872. //-----------------------------------------------------------------------------
  873. Activity CBaseCombatCharacter::NPC_TranslateActivity( Activity baseAct )
  874. {
  875. return baseAct;
  876. }
  877. void CBaseCombatCharacter::Weapon_SetActivity( Activity newActivity, float duration )
  878. {
  879. if ( m_hActiveWeapon )
  880. {
  881. m_hActiveWeapon->SetActivity( newActivity, duration );
  882. }
  883. }
  884. void CBaseCombatCharacter::Weapon_FrameUpdate( void )
  885. {
  886. if ( m_hActiveWeapon )
  887. {
  888. m_hActiveWeapon->Operator_FrameUpdate( this );
  889. }
  890. }
  891. //------------------------------------------------------------------------------
  892. // Purpose : expects a length to trace, amount
  893. // of damage to do, and damage type. Returns a pointer to
  894. // the damaged entity in case the NPC wishes to do
  895. // other stuff to the victim (punchangle, etc)
  896. //
  897. // Used for many contact-range melee attacks. Bites, claws, etc.
  898. // Input :
  899. // Output :
  900. //------------------------------------------------------------------------------
  901. CBaseEntity *CBaseCombatCharacter::CheckTraceHullAttack( float flDist, const Vector &mins, const Vector &maxs, int iDamage, int iDmgType, float forceScale, bool bDamageAnyNPC )
  902. {
  903. // If only a length is given assume we want to trace in our facing direction
  904. Vector forward;
  905. AngleVectors( GetAbsAngles(), &forward );
  906. Vector vStart = GetAbsOrigin();
  907. // The ideal place to start the trace is in the center of the attacker's bounding box.
  908. // however, we need to make sure there's enough clearance. Some of the smaller monsters aren't
  909. // as big as the hull we try to trace with. (SJB)
  910. float flVerticalOffset = WorldAlignSize().z * 0.5;
  911. if( flVerticalOffset < maxs.z )
  912. {
  913. // There isn't enough room to trace this hull, it's going to drag the ground.
  914. // so make the vertical offset just enough to clear the ground.
  915. flVerticalOffset = maxs.z + 1.0;
  916. }
  917. vStart.z += flVerticalOffset;
  918. Vector vEnd = vStart + (forward * flDist );
  919. return CheckTraceHullAttack( vStart, vEnd, mins, maxs, iDamage, iDmgType, forceScale, bDamageAnyNPC );
  920. }
  921. //-----------------------------------------------------------------------------
  922. // Purpose:
  923. // Input : *pHandleEntity -
  924. // contentsMask -
  925. // Output : Returns true on success, false on failure.
  926. //-----------------------------------------------------------------------------
  927. bool CTraceFilterMelee::ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask )
  928. {
  929. if ( !StandardFilterRules( pHandleEntity, contentsMask ) )
  930. return false;
  931. if ( !PassServerEntityFilter( pHandleEntity, m_pPassEnt ) )
  932. return false;
  933. // Don't test if the game code tells us we should ignore this collision...
  934. CBaseEntity *pEntity = EntityFromEntityHandle( pHandleEntity );
  935. if ( pEntity )
  936. {
  937. if ( !pEntity->ShouldCollide( m_collisionGroup, contentsMask ) )
  938. return false;
  939. if ( !g_pGameRules->ShouldCollide( m_collisionGroup, pEntity->GetCollisionGroup() ) )
  940. return false;
  941. if ( pEntity->m_takedamage == DAMAGE_NO )
  942. return false;
  943. // FIXME: Do not translate this to the driver because the driver only accepts damage from the vehicle
  944. // Translate the vehicle into its driver for damage
  945. /*
  946. if ( pEntity->GetServerVehicle() != NULL )
  947. {
  948. CBaseEntity *pDriver = pEntity->GetServerVehicle()->GetPassenger();
  949. if ( pDriver != NULL )
  950. {
  951. pEntity = pDriver;
  952. }
  953. }
  954. */
  955. Vector attackDir = pEntity->WorldSpaceCenter() - m_dmgInfo->GetAttacker()->WorldSpaceCenter();
  956. VectorNormalize( attackDir );
  957. CTakeDamageInfo info = (*m_dmgInfo);
  958. CalculateMeleeDamageForce( &info, attackDir, info.GetAttacker()->WorldSpaceCenter(), m_flForceScale );
  959. CBaseCombatCharacter *pBCC = info.GetAttacker()->MyCombatCharacterPointer();
  960. CBaseCombatCharacter *pVictimBCC = pEntity->MyCombatCharacterPointer();
  961. // Only do these comparisons between NPCs
  962. if ( pBCC && pVictimBCC )
  963. {
  964. // Can only damage other NPCs that we hate
  965. if ( m_bDamageAnyNPC || pBCC->IRelationType( pEntity ) == D_HT )
  966. {
  967. if ( info.GetDamage() )
  968. {
  969. pEntity->TakeDamage( info );
  970. }
  971. // Put a combat sound in
  972. CSoundEnt::InsertSound( SOUND_COMBAT, info.GetDamagePosition(), 200, 0.2f, info.GetAttacker() );
  973. m_pHit = pEntity;
  974. return true;
  975. }
  976. }
  977. else
  978. {
  979. m_pHit = pEntity;
  980. // Make sure if the player is holding this, he drops it
  981. Pickup_ForcePlayerToDropThisObject( pEntity );
  982. // Otherwise just damage passive objects in our way
  983. if ( info.GetDamage() )
  984. {
  985. pEntity->TakeDamage( info );
  986. }
  987. }
  988. }
  989. return false;
  990. }
  991. //------------------------------------------------------------------------------
  992. // Purpose : start and end trace position, amount
  993. // of damage to do, and damage type. Returns a pointer to
  994. // the damaged entity in case the NPC wishes to do
  995. // other stuff to the victim (punchangle, etc)
  996. //
  997. // Used for many contact-range melee attacks. Bites, claws, etc.
  998. // Input :
  999. // Output :
  1000. //------------------------------------------------------------------------------
  1001. CBaseEntity *CBaseCombatCharacter::CheckTraceHullAttack( const Vector &vStart, const Vector &vEnd, const Vector &mins, const Vector &maxs, int iDamage, int iDmgType, float flForceScale, bool bDamageAnyNPC )
  1002. {
  1003. // Handy debuging tool to visualize HullAttack trace
  1004. if ( ai_show_hull_attacks.GetBool() )
  1005. {
  1006. float length = (vEnd - vStart ).Length();
  1007. Vector direction = (vEnd - vStart );
  1008. VectorNormalize( direction );
  1009. Vector hullMaxs = maxs;
  1010. hullMaxs.x = length + hullMaxs.x;
  1011. NDebugOverlay::BoxDirection(vStart, mins, hullMaxs, direction, 100,255,255,20,1.0);
  1012. NDebugOverlay::BoxDirection(vStart, mins, maxs, direction, 255,0,0,20,1.0);
  1013. }
  1014. #if 1
  1015. CTakeDamageInfo dmgInfo( this, this, iDamage, iDmgType );
  1016. // COLLISION_GROUP_PROJECTILE does some handy filtering that's very appropriate for this type of attack, as well. (sjb) 7/25/2007
  1017. CTraceFilterMelee traceFilter( this, COLLISION_GROUP_PROJECTILE, &dmgInfo, flForceScale, bDamageAnyNPC );
  1018. Ray_t ray;
  1019. ray.Init( vStart, vEnd, mins, maxs );
  1020. trace_t tr;
  1021. enginetrace->TraceRay( ray, MASK_SHOT_HULL, &traceFilter, &tr );
  1022. CBaseEntity *pEntity = traceFilter.m_pHit;
  1023. if ( pEntity == NULL )
  1024. {
  1025. // See if perhaps I'm trying to claw/bash someone who is standing on my head.
  1026. Vector vecTopCenter;
  1027. Vector vecEnd;
  1028. Vector vecMins, vecMaxs;
  1029. // Do a tracehull from the top center of my bounding box.
  1030. vecTopCenter = GetAbsOrigin();
  1031. CollisionProp()->WorldSpaceAABB( &vecMins, &vecMaxs );
  1032. vecTopCenter.z = vecMaxs.z + 1.0f;
  1033. vecEnd = vecTopCenter;
  1034. vecEnd.z += 2.0f;
  1035. ray.Init( vecTopCenter, vEnd, mins, maxs );
  1036. enginetrace->TraceRay( ray, MASK_SHOT_HULL, &traceFilter, &tr );
  1037. pEntity = traceFilter.m_pHit;
  1038. }
  1039. if( pEntity && !pEntity->CanBeHitByMeleeAttack(this) )
  1040. {
  1041. // If we touched something, but it shouldn't be hit, return nothing.
  1042. pEntity = NULL;
  1043. }
  1044. return pEntity;
  1045. #else
  1046. trace_t tr;
  1047. UTIL_TraceHull( vStart, vEnd, mins, maxs, MASK_SHOT_HULL, this, COLLISION_GROUP_NONE, &tr );
  1048. CBaseEntity *pEntity = tr.m_pEnt;
  1049. if ( !pEntity )
  1050. {
  1051. // See if perhaps I'm trying to claw/bash someone who is standing on my head.
  1052. Vector vecTopCenter;
  1053. Vector vecEnd;
  1054. Vector vecMins, vecMaxs;
  1055. // Do a tracehull from the top center of my bounding box.
  1056. vecTopCenter = GetAbsOrigin();
  1057. CollisionProp()->WorldSpaceAABB( &vecMins, &vecMaxs );
  1058. vecTopCenter.z = vecMaxs.z + 1.0f;
  1059. vecEnd = vecTopCenter;
  1060. vecEnd.z += 2.0f;
  1061. UTIL_TraceHull( vecTopCenter, vecEnd, mins, maxs, MASK_SHOT_HULL, this, COLLISION_GROUP_NONE, &tr );
  1062. pEntity = tr.m_pEnt;
  1063. }
  1064. if ( !pEntity || !pEntity->m_takedamage || !pEntity->IsAlive() )
  1065. return NULL;
  1066. // Translate the vehicle into its driver for damage
  1067. if ( pEntity->GetServerVehicle() != NULL )
  1068. {
  1069. CBaseEntity *pDriver = pEntity->GetServerVehicle()->GetPassenger();
  1070. if ( pDriver != NULL )
  1071. {
  1072. pEntity = pDriver;
  1073. //FIXME: Hook for damage scale in car here
  1074. }
  1075. }
  1076. // Must hate the hit entity
  1077. if ( IRelationType( pEntity ) == D_HT )
  1078. {
  1079. if ( iDamage > 0 )
  1080. {
  1081. CTakeDamageInfo info( this, this, iDamage, iDmgType );
  1082. CalculateMeleeDamageForce( &info, (vEnd - vStart), vStart, forceScale );
  1083. pEntity->TakeDamage( info );
  1084. }
  1085. }
  1086. return pEntity;
  1087. #endif
  1088. }
  1089. bool CBaseCombatCharacter::Event_Gibbed( const CTakeDamageInfo &info )
  1090. {
  1091. bool fade = false;
  1092. if ( HasHumanGibs() )
  1093. {
  1094. ConVarRef violence_hgibs( "violence_hgibs" );
  1095. if ( violence_hgibs.IsValid() && violence_hgibs.GetInt() == 0 )
  1096. {
  1097. fade = true;
  1098. }
  1099. }
  1100. else if ( HasAlienGibs() )
  1101. {
  1102. ConVarRef violence_agibs( "violence_agibs" );
  1103. if ( violence_agibs.IsValid() && violence_agibs.GetInt() == 0 )
  1104. {
  1105. fade = true;
  1106. }
  1107. }
  1108. m_takedamage = DAMAGE_NO;
  1109. AddSolidFlags( FSOLID_NOT_SOLID );
  1110. m_lifeState = LIFE_DEAD;
  1111. if ( fade )
  1112. {
  1113. CorpseFade();
  1114. return false;
  1115. }
  1116. else
  1117. {
  1118. AddEffects( EF_NODRAW ); // make the model invisible.
  1119. return CorpseGib( info );
  1120. }
  1121. }
  1122. Vector CBaseCombatCharacter::CalcDamageForceVector( const CTakeDamageInfo &info )
  1123. {
  1124. // Already have a damage force in the data, use that.
  1125. bool bNoPhysicsForceDamage = g_pGameRules->Damage_NoPhysicsForce( info.GetDamageType() );
  1126. if ( info.GetDamageForce() != vec3_origin || bNoPhysicsForceDamage )
  1127. {
  1128. if( info.GetDamageType() & DMG_BLAST )
  1129. {
  1130. // Fudge blast forces a little bit, so that each
  1131. // victim gets a slightly different trajectory.
  1132. // This simulates features that usually vary from
  1133. // person-to-person variables such as bodyweight,
  1134. // which are all indentical for characters using the same model.
  1135. float scale = random->RandomFloat( 0.85, 1.15 );
  1136. Vector force = info.GetDamageForce();
  1137. force.x *= scale;
  1138. force.y *= scale;
  1139. // Try to always exaggerate the upward force because we've got pretty harsh gravity
  1140. force.z *= (force.z > 0) ? 1.15 : scale;
  1141. return force;
  1142. }
  1143. return info.GetDamageForce();
  1144. }
  1145. CBaseEntity *pForce = info.GetInflictor();
  1146. if ( !pForce )
  1147. {
  1148. pForce = info.GetAttacker();
  1149. }
  1150. if ( pForce )
  1151. {
  1152. // Calculate an impulse large enough to push a 75kg man 4 in/sec per point of damage
  1153. float forceScale = info.GetDamage() * 75 * 4;
  1154. Vector forceVector;
  1155. // If the damage is a blast, point the force vector higher than usual, this gives
  1156. // the ragdolls a bodacious "really got blowed up" look.
  1157. if( info.GetDamageType() & DMG_BLAST )
  1158. {
  1159. // exaggerate the force from explosions a little (37.5%)
  1160. forceVector = (GetLocalOrigin() + Vector(0, 0, WorldAlignSize().z) ) - pForce->GetLocalOrigin();
  1161. VectorNormalize(forceVector);
  1162. forceVector *= 1.375f;
  1163. }
  1164. else
  1165. {
  1166. // taking damage from self? Take a little random force, but still try to collapse on the spot.
  1167. if ( this == pForce )
  1168. {
  1169. forceVector.x = random->RandomFloat( -1.0f, 1.0f );
  1170. forceVector.y = random->RandomFloat( -1.0f, 1.0f );
  1171. forceVector.z = 0.0;
  1172. forceScale = random->RandomFloat( 1000.0f, 2000.0f );
  1173. }
  1174. else
  1175. {
  1176. // UNDONE: Collision forces are baked in to CTakeDamageInfo now
  1177. // UNDONE: Is this MOVETYPE_VPHYSICS code still necessary?
  1178. if ( pForce->GetMoveType() == MOVETYPE_VPHYSICS )
  1179. {
  1180. // killed by a physics object
  1181. IPhysicsObject *pPhysics = VPhysicsGetObject();
  1182. if ( !pPhysics )
  1183. {
  1184. pPhysics = pForce->VPhysicsGetObject();
  1185. }
  1186. pPhysics->GetVelocity( &forceVector, NULL );
  1187. forceScale = pPhysics->GetMass();
  1188. }
  1189. else
  1190. {
  1191. forceVector = GetLocalOrigin() - pForce->GetLocalOrigin();
  1192. VectorNormalize(forceVector);
  1193. }
  1194. }
  1195. }
  1196. return forceVector * forceScale;
  1197. }
  1198. return vec3_origin;
  1199. }
  1200. //-----------------------------------------------------------------------------
  1201. // Purpose:
  1202. // Output : Returns true on success, false on failure.
  1203. //-----------------------------------------------------------------------------
  1204. void CBaseCombatCharacter::FixupBurningServerRagdoll( CBaseEntity *pRagdoll )
  1205. {
  1206. if ( !IsOnFire() )
  1207. return;
  1208. // Move the fire effects entity to the ragdoll
  1209. CEntityFlame *pFireChild = dynamic_cast<CEntityFlame *>( GetEffectEntity() );
  1210. if ( pFireChild )
  1211. {
  1212. SetEffectEntity( NULL );
  1213. pRagdoll->AddFlag( FL_ONFIRE );
  1214. pFireChild->SetAbsOrigin( pRagdoll->GetAbsOrigin() );
  1215. pFireChild->AttachToEntity( pRagdoll );
  1216. pFireChild->AddEFlags( EFL_FORCE_CHECK_TRANSMIT );
  1217. pRagdoll->SetEffectEntity( pFireChild );
  1218. color32 color = GetRenderColor();
  1219. pRagdoll->SetRenderColor( color.r, color.g, color.b );
  1220. }
  1221. }
  1222. bool CBaseCombatCharacter::BecomeRagdollBoogie( CBaseEntity *pKiller, const Vector &forceVector, float duration, int flags )
  1223. {
  1224. Assert( CanBecomeRagdoll() );
  1225. CTakeDamageInfo info( pKiller, pKiller, 1.0f, DMG_GENERIC );
  1226. info.SetDamageForce( forceVector );
  1227. CBaseEntity *pRagdoll = CreateServerRagdoll( this, 0, info, COLLISION_GROUP_INTERACTIVE_DEBRIS, true );
  1228. pRagdoll->SetCollisionBounds( CollisionProp()->OBBMins(), CollisionProp()->OBBMaxs() );
  1229. CRagdollBoogie::Create( pRagdoll, 200, gpGlobals->curtime, duration, flags );
  1230. CTakeDamageInfo ragdollInfo( pKiller, pKiller, 10000.0, DMG_GENERIC | DMG_REMOVENORAGDOLL );
  1231. ragdollInfo.SetDamagePosition(WorldSpaceCenter());
  1232. ragdollInfo.SetDamageForce( Vector( 0, 0, 1) );
  1233. TakeDamage( ragdollInfo );
  1234. return true;
  1235. }
  1236. //-----------------------------------------------------------------------------
  1237. // Purpose:
  1238. //-----------------------------------------------------------------------------
  1239. bool CBaseCombatCharacter::BecomeRagdoll( const CTakeDamageInfo &info, const Vector &forceVector )
  1240. {
  1241. if ( (info.GetDamageType() & DMG_VEHICLE) && !g_pGameRules->IsMultiplayer() )
  1242. {
  1243. CTakeDamageInfo info2 = info;
  1244. info2.SetDamageForce( forceVector );
  1245. Vector pos = info2.GetDamagePosition();
  1246. float flAbsMinsZ = GetAbsOrigin().z + WorldAlignMins().z;
  1247. if ( (pos.z - flAbsMinsZ) < 24 )
  1248. {
  1249. // HACKHACK: Make sure the vehicle impact is at least 2ft off the ground
  1250. pos.z = flAbsMinsZ + 24;
  1251. info2.SetDamagePosition( pos );
  1252. }
  1253. // UNDONE: Put in a real sound cue here, don't do this bogus hack anymore
  1254. #if 0
  1255. Vector soundOrigin = info.GetDamagePosition();
  1256. CPASAttenuationFilter filter( soundOrigin );
  1257. EmitSound_t ep;
  1258. ep.m_nChannel = CHAN_STATIC;
  1259. ep.m_pSoundName = "NPC_MetroPolice.HitByVehicle";
  1260. ep.m_flVolume = 1.0f;
  1261. ep.m_SoundLevel = SNDLVL_NORM;
  1262. ep.m_pOrigin = &soundOrigin;
  1263. EmitSound( filter, SOUND_FROM_WORLD, ep );
  1264. #endif
  1265. // in single player create ragdolls on the server when the player hits someone
  1266. // with their vehicle - for more dramatic death/collisions
  1267. CBaseEntity *pRagdoll = CreateServerRagdoll( this, m_nForceBone, info2, COLLISION_GROUP_INTERACTIVE_DEBRIS, true );
  1268. FixupBurningServerRagdoll( pRagdoll );
  1269. RemoveDeferred();
  1270. return true;
  1271. }
  1272. //Fix up the force applied to server side ragdolls. This fixes magnets not affecting them.
  1273. CTakeDamageInfo newinfo = info;
  1274. newinfo.SetDamageForce( forceVector );
  1275. #ifdef HL2_EPISODIC
  1276. // Burning corpses are server-side in episodic, if we're in darkness mode
  1277. if ( IsOnFire() && HL2GameRules()->IsAlyxInDarknessMode() )
  1278. {
  1279. CBaseEntity *pRagdoll = CreateServerRagdoll( this, m_nForceBone, newinfo, COLLISION_GROUP_DEBRIS );
  1280. FixupBurningServerRagdoll( pRagdoll );
  1281. RemoveDeferred();
  1282. return true;
  1283. }
  1284. #endif
  1285. #ifdef HL2_DLL
  1286. bool bMegaPhyscannonActive = false;
  1287. #if !defined( HL2MP )
  1288. bMegaPhyscannonActive = HL2GameRules()->MegaPhyscannonActive();
  1289. #endif // !HL2MP
  1290. // Mega physgun requires everything to be a server-side ragdoll
  1291. if ( m_bForceServerRagdoll == true || ( ( bMegaPhyscannonActive == true ) && !IsPlayer() && Classify() != CLASS_PLAYER_ALLY_VITAL && Classify() != CLASS_PLAYER_ALLY ) )
  1292. {
  1293. if ( CanBecomeServerRagdoll() == false )
  1294. return false;
  1295. //FIXME: This is fairly leafy to be here, but time is short!
  1296. CBaseEntity *pRagdoll = CreateServerRagdoll( this, m_nForceBone, newinfo, COLLISION_GROUP_INTERACTIVE_DEBRIS, true );
  1297. FixupBurningServerRagdoll( pRagdoll );
  1298. PhysSetEntityGameFlags( pRagdoll, FVPHYSICS_NO_SELF_COLLISIONS );
  1299. RemoveDeferred();
  1300. return true;
  1301. }
  1302. if( hl2_episodic.GetBool() && Classify() == CLASS_PLAYER_ALLY_VITAL )
  1303. {
  1304. CreateServerRagdoll( this, m_nForceBone, newinfo, COLLISION_GROUP_INTERACTIVE_DEBRIS, true );
  1305. RemoveDeferred();
  1306. return true;
  1307. }
  1308. #endif //HL2_DLL
  1309. return BecomeRagdollOnClient( forceVector );
  1310. }
  1311. /*
  1312. ============
  1313. Killed
  1314. ============
  1315. */
  1316. void CBaseCombatCharacter::Event_Killed( const CTakeDamageInfo &info )
  1317. {
  1318. extern ConVar npc_vphysics;
  1319. // Advance life state to dying
  1320. m_lifeState = LIFE_DYING;
  1321. // Calculate death force
  1322. Vector forceVector = CalcDamageForceVector( info );
  1323. // See if there's a ragdoll magnet that should influence our force.
  1324. CRagdollMagnet *pMagnet = CRagdollMagnet::FindBestMagnet( this );
  1325. if( pMagnet )
  1326. {
  1327. forceVector += pMagnet->GetForceVector( this );
  1328. }
  1329. CBaseCombatWeapon *pDroppedWeapon = m_hActiveWeapon.Get();
  1330. // Drop any weapon that I own
  1331. if ( VPhysicsGetObject() )
  1332. {
  1333. Vector weaponForce = forceVector * VPhysicsGetObject()->GetInvMass();
  1334. Weapon_Drop( m_hActiveWeapon, NULL, &weaponForce );
  1335. }
  1336. else
  1337. {
  1338. Weapon_Drop( m_hActiveWeapon );
  1339. }
  1340. // if flagged to drop a health kit
  1341. if (HasSpawnFlags(SF_NPC_DROP_HEALTHKIT))
  1342. {
  1343. CBaseEntity::Create( "item_healthvial", GetAbsOrigin(), GetAbsAngles() );
  1344. }
  1345. // clear the deceased's sound channels.(may have been firing or reloading when killed)
  1346. EmitSound( "BaseCombatCharacter.StopWeaponSounds" );
  1347. // Tell my killer that he got me!
  1348. if( info.GetAttacker() )
  1349. {
  1350. info.GetAttacker()->Event_KilledOther(this, info);
  1351. g_EventQueue.AddEvent( info.GetAttacker(), "KilledNPC", 0.3, this, this );
  1352. }
  1353. SendOnKilledGameEvent( info );
  1354. // Ragdoll unless we've gibbed
  1355. if ( ShouldGib( info ) == false )
  1356. {
  1357. bool bRagdollCreated = false;
  1358. if ( (info.GetDamageType() & DMG_DISSOLVE) && CanBecomeRagdoll() )
  1359. {
  1360. int nDissolveType = ENTITY_DISSOLVE_NORMAL;
  1361. if ( info.GetDamageType() & DMG_SHOCK )
  1362. {
  1363. nDissolveType = ENTITY_DISSOLVE_ELECTRICAL;
  1364. }
  1365. bRagdollCreated = Dissolve( NULL, gpGlobals->curtime, false, nDissolveType );
  1366. // Also dissolve any weapons we dropped
  1367. if ( pDroppedWeapon )
  1368. {
  1369. pDroppedWeapon->Dissolve( NULL, gpGlobals->curtime, false, nDissolveType );
  1370. }
  1371. }
  1372. #ifdef HL2_DLL
  1373. else if ( PlayerHasMegaPhysCannon() )
  1374. {
  1375. if ( pDroppedWeapon )
  1376. {
  1377. pDroppedWeapon->Dissolve( NULL, gpGlobals->curtime, false, ENTITY_DISSOLVE_NORMAL );
  1378. }
  1379. }
  1380. #endif
  1381. if ( !bRagdollCreated && ( info.GetDamageType() & DMG_REMOVENORAGDOLL ) == 0 )
  1382. {
  1383. BecomeRagdoll( info, forceVector );
  1384. }
  1385. }
  1386. // no longer standing on a nav area
  1387. ClearLastKnownArea();
  1388. #if 0
  1389. // L4D specific hack for zombie commentary mode
  1390. if( GetOwnerEntity() != NULL )
  1391. {
  1392. GetOwnerEntity()->DeathNotice( this );
  1393. }
  1394. #endif
  1395. #ifdef NEXT_BOT
  1396. // inform bots
  1397. TheNextBots().OnKilled( this, info );
  1398. #endif
  1399. #ifdef GLOWS_ENABLE
  1400. RemoveGlowEffect();
  1401. #endif // GLOWS_ENABLE
  1402. }
  1403. void CBaseCombatCharacter::Event_Dying( const CTakeDamageInfo &info )
  1404. {
  1405. }
  1406. void CBaseCombatCharacter::Event_Dying()
  1407. {
  1408. CTakeDamageInfo info;
  1409. Event_Dying( info );
  1410. }
  1411. // ===========================================================================
  1412. // > Weapons
  1413. // ===========================================================================
  1414. bool CBaseCombatCharacter::Weapon_Detach( CBaseCombatWeapon *pWeapon )
  1415. {
  1416. for ( int i = 0; i < MAX_WEAPONS; i++ )
  1417. {
  1418. if ( pWeapon == m_hMyWeapons[i] )
  1419. {
  1420. pWeapon->Detach();
  1421. if ( pWeapon->HolsterOnDetach() )
  1422. {
  1423. pWeapon->Holster();
  1424. }
  1425. m_hMyWeapons.Set( i, NULL );
  1426. pWeapon->SetOwner( NULL );
  1427. if ( pWeapon == m_hActiveWeapon )
  1428. ClearActiveWeapon();
  1429. return true;
  1430. }
  1431. }
  1432. return false;
  1433. }
  1434. //-----------------------------------------------------------------------------
  1435. // For weapon strip
  1436. //-----------------------------------------------------------------------------
  1437. void CBaseCombatCharacter::ThrowDirForWeaponStrip( CBaseCombatWeapon *pWeapon, const Vector &vecForward, Vector *pVecThrowDir )
  1438. {
  1439. // HACK! Always throw the physcannon directly in front of the player
  1440. // This is necessary for the physgun upgrade scene.
  1441. if ( FClassnameIs( pWeapon, "weapon_physcannon" ) )
  1442. {
  1443. if( hl2_episodic.GetBool() )
  1444. {
  1445. // It has been discovered that it's possible to throw the physcannon out of the world this way.
  1446. // So try to find a direction to throw the physcannon that's legal.
  1447. Vector vecOrigin = EyePosition();
  1448. Vector vecRight;
  1449. CrossProduct( vecForward, Vector( 0, 0, 1), vecRight );
  1450. Vector vecTest[ 4 ];
  1451. vecTest[0] = vecForward;
  1452. vecTest[1] = -vecForward;
  1453. vecTest[2] = vecRight;
  1454. vecTest[3] = -vecRight;
  1455. trace_t tr;
  1456. int i;
  1457. for( i = 0 ; i < 4 ; i++ )
  1458. {
  1459. UTIL_TraceLine( vecOrigin, vecOrigin + vecTest[ i ] * 48.0f, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr );
  1460. if ( !tr.startsolid && tr.fraction == 1.0f )
  1461. {
  1462. *pVecThrowDir = vecTest[ i ];
  1463. return;
  1464. }
  1465. }
  1466. }
  1467. // Well, fall through to what we did before we tried to make this a bit more robust.
  1468. *pVecThrowDir = vecForward;
  1469. }
  1470. else
  1471. {
  1472. // Nowhere in particular; just drop it.
  1473. VMatrix zRot;
  1474. MatrixBuildRotateZ( zRot, random->RandomFloat( -60.0f, 60.0f ) );
  1475. Vector vecThrow;
  1476. Vector3DMultiply( zRot, vecForward, *pVecThrowDir );
  1477. pVecThrowDir->z = random->RandomFloat( -0.5f, 0.5f );
  1478. VectorNormalize( *pVecThrowDir );
  1479. }
  1480. }
  1481. //-----------------------------------------------------------------------------
  1482. // For weapon strip
  1483. //-----------------------------------------------------------------------------
  1484. void CBaseCombatCharacter::DropWeaponForWeaponStrip( CBaseCombatWeapon *pWeapon,
  1485. const Vector &vecForward, const QAngle &vecAngles, float flDiameter )
  1486. {
  1487. Vector vecOrigin;
  1488. CollisionProp()->RandomPointInBounds( Vector( 0.5f, 0.5f, 0.5f ), Vector( 0.5f, 0.5f, 1.0f ), &vecOrigin );
  1489. // Nowhere in particular; just drop it.
  1490. Vector vecThrow;
  1491. ThrowDirForWeaponStrip( pWeapon, vecForward, &vecThrow );
  1492. Vector vecOffsetOrigin;
  1493. VectorMA( vecOrigin, flDiameter, vecThrow, vecOffsetOrigin );
  1494. trace_t tr;
  1495. UTIL_TraceLine( vecOrigin, vecOffsetOrigin, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr );
  1496. if ( tr.startsolid || tr.allsolid || ( tr.fraction < 1.0f && tr.m_pEnt != pWeapon ) )
  1497. {
  1498. //FIXME: Throw towards a known safe spot?
  1499. vecThrow.Negate();
  1500. VectorMA( vecOrigin, flDiameter, vecThrow, vecOffsetOrigin );
  1501. }
  1502. vecThrow *= random->RandomFloat( 400.0f, 600.0f );
  1503. pWeapon->SetAbsOrigin( vecOrigin );
  1504. pWeapon->SetAbsAngles( vecAngles );
  1505. pWeapon->Drop( vecThrow );
  1506. pWeapon->SetRemoveable( false );
  1507. Weapon_Detach( pWeapon );
  1508. }
  1509. //-----------------------------------------------------------------------------
  1510. // For weapon strip
  1511. //-----------------------------------------------------------------------------
  1512. void CBaseCombatCharacter::Weapon_DropAll( bool bDisallowWeaponPickup )
  1513. {
  1514. if ( GetFlags() & FL_NPC )
  1515. {
  1516. for (int i=0; i<MAX_WEAPONS; ++i)
  1517. {
  1518. CBaseCombatWeapon *pWeapon = m_hMyWeapons[i];
  1519. if (!pWeapon)
  1520. continue;
  1521. Weapon_Drop( pWeapon );
  1522. }
  1523. return;
  1524. }
  1525. QAngle gunAngles;
  1526. VectorAngles( BodyDirection2D(), gunAngles );
  1527. Vector vecForward;
  1528. AngleVectors( gunAngles, &vecForward, NULL, NULL );
  1529. float flDiameter = sqrt( CollisionProp()->OBBSize().x * CollisionProp()->OBBSize().x +
  1530. CollisionProp()->OBBSize().y * CollisionProp()->OBBSize().y );
  1531. CBaseCombatWeapon *pActiveWeapon = GetActiveWeapon();
  1532. for (int i=0; i<MAX_WEAPONS; ++i)
  1533. {
  1534. CBaseCombatWeapon *pWeapon = m_hMyWeapons[i];
  1535. if (!pWeapon)
  1536. continue;
  1537. // Have to drop this after we've dropped everything else, so autoswitch doesn't happen
  1538. if ( pWeapon == pActiveWeapon )
  1539. continue;
  1540. DropWeaponForWeaponStrip( pWeapon, vecForward, gunAngles, flDiameter );
  1541. // HACK: This hack is required to allow weapons to be disintegrated
  1542. // in the citadel weapon-strip scene
  1543. // Make them not pick-uppable again. This also has the effect of allowing weapons
  1544. // to collide with triggers.
  1545. if ( bDisallowWeaponPickup )
  1546. {
  1547. pWeapon->RemoveSolidFlags( FSOLID_TRIGGER );
  1548. IPhysicsObject *pObj = pWeapon->VPhysicsGetObject();
  1549. if ( pObj != NULL )
  1550. {
  1551. pObj->SetGameFlags( FVPHYSICS_NO_PLAYER_PICKUP );
  1552. }
  1553. }
  1554. }
  1555. // Drop the active weapon normally...
  1556. if ( pActiveWeapon )
  1557. {
  1558. // Nowhere in particular; just drop it.
  1559. Vector vecThrow;
  1560. ThrowDirForWeaponStrip( pActiveWeapon, vecForward, &vecThrow );
  1561. // Throw a little more vigorously; it starts closer to the player
  1562. vecThrow *= random->RandomFloat( 800.0f, 1000.0f );
  1563. Weapon_Drop( pActiveWeapon, NULL, &vecThrow );
  1564. pActiveWeapon->SetRemoveable( false );
  1565. // HACK: This hack is required to allow weapons to be disintegrated
  1566. // in the citadel weapon-strip scene
  1567. // Make them not pick-uppable again. This also has the effect of allowing weapons
  1568. // to collide with triggers.
  1569. if ( bDisallowWeaponPickup )
  1570. {
  1571. pActiveWeapon->RemoveSolidFlags( FSOLID_TRIGGER );
  1572. }
  1573. }
  1574. }
  1575. //-----------------------------------------------------------------------------
  1576. // Purpose: Drop the active weapon, optionally throwing it at the given target position.
  1577. // Input : pWeapon - Weapon to drop/throw.
  1578. // pvecTarget - Position to throw it at, NULL for none.
  1579. //-----------------------------------------------------------------------------
  1580. void CBaseCombatCharacter::Weapon_Drop( CBaseCombatWeapon *pWeapon, const Vector *pvecTarget /* = NULL */, const Vector *pVelocity /* = NULL */ )
  1581. {
  1582. if ( !pWeapon )
  1583. return;
  1584. // If I'm an NPC, fill the weapon with ammo before I drop it.
  1585. if ( GetFlags() & FL_NPC )
  1586. {
  1587. if ( pWeapon->UsesClipsForAmmo1() )
  1588. {
  1589. pWeapon->m_iClip1 = pWeapon->GetDefaultClip1();
  1590. if( FClassnameIs( pWeapon, "weapon_smg1" ) )
  1591. {
  1592. // Drop enough ammo to kill 2 of me.
  1593. // Figure out how much damage one piece of this type of ammo does to this type of enemy.
  1594. float flAmmoDamage = g_pGameRules->GetAmmoDamage( UTIL_PlayerByIndex(1), this, pWeapon->GetPrimaryAmmoType() );
  1595. pWeapon->m_iClip1 = (GetMaxHealth() / flAmmoDamage) * 2;
  1596. }
  1597. }
  1598. if ( pWeapon->UsesClipsForAmmo2() )
  1599. {
  1600. pWeapon->m_iClip2 = pWeapon->GetDefaultClip2();
  1601. }
  1602. if ( IsXbox() )
  1603. {
  1604. pWeapon->AddEffects( EF_ITEM_BLINK );
  1605. }
  1606. }
  1607. if ( IsPlayer() )
  1608. {
  1609. Vector vThrowPos = Weapon_ShootPosition() - Vector(0,0,12);
  1610. if( UTIL_PointContents(vThrowPos) & CONTENTS_SOLID )
  1611. {
  1612. Msg("Weapon spawning in solid!\n");
  1613. }
  1614. pWeapon->SetAbsOrigin( vThrowPos );
  1615. QAngle gunAngles;
  1616. VectorAngles( BodyDirection2D(), gunAngles );
  1617. pWeapon->SetAbsAngles( gunAngles );
  1618. }
  1619. else
  1620. {
  1621. int iBIndex = -1;
  1622. int iWeaponBoneIndex = -1;
  1623. CStudioHdr *hdr = pWeapon->GetModelPtr();
  1624. // If I have a hand, set the weapon position to my hand bone position.
  1625. if ( hdr && hdr->numbones() > 0 )
  1626. {
  1627. // Assume bone zero is the root
  1628. for ( iWeaponBoneIndex = 0; iWeaponBoneIndex < hdr->numbones(); ++iWeaponBoneIndex )
  1629. {
  1630. iBIndex = LookupBone( hdr->pBone( iWeaponBoneIndex )->pszName() );
  1631. // Found one!
  1632. if ( iBIndex != -1 )
  1633. {
  1634. break;
  1635. }
  1636. }
  1637. if ( iBIndex == -1 )
  1638. {
  1639. iBIndex = LookupBone( "ValveBiped.Weapon_bone" );
  1640. }
  1641. }
  1642. else
  1643. {
  1644. iBIndex = LookupBone( "ValveBiped.Weapon_bone" );
  1645. }
  1646. if ( iBIndex != -1)
  1647. {
  1648. Vector origin;
  1649. QAngle angles;
  1650. matrix3x4_t transform;
  1651. // Get the transform for the weapon bonetoworldspace in the NPC
  1652. GetBoneTransform( iBIndex, transform );
  1653. // find offset of root bone from origin in local space
  1654. // Make sure we're detached from hierarchy before doing this!!!
  1655. pWeapon->StopFollowingEntity();
  1656. pWeapon->SetAbsOrigin( Vector( 0, 0, 0 ) );
  1657. pWeapon->SetAbsAngles( QAngle( 0, 0, 0 ) );
  1658. pWeapon->InvalidateBoneCache();
  1659. matrix3x4_t rootLocal;
  1660. pWeapon->GetBoneTransform( iWeaponBoneIndex, rootLocal );
  1661. // invert it
  1662. matrix3x4_t rootInvLocal;
  1663. MatrixInvert( rootLocal, rootInvLocal );
  1664. matrix3x4_t weaponMatrix;
  1665. ConcatTransforms( transform, rootInvLocal, weaponMatrix );
  1666. MatrixAngles( weaponMatrix, angles, origin );
  1667. pWeapon->Teleport( &origin, &angles, NULL );
  1668. }
  1669. // Otherwise just set in front of me.
  1670. else
  1671. {
  1672. Vector vFacingDir = BodyDirection2D();
  1673. vFacingDir = vFacingDir * 10.0;
  1674. pWeapon->SetAbsOrigin( Weapon_ShootPosition() + vFacingDir );
  1675. }
  1676. }
  1677. Vector vecThrow;
  1678. if (pvecTarget)
  1679. {
  1680. // I've been told to throw it somewhere specific.
  1681. vecThrow = VecCheckToss( this, pWeapon->GetAbsOrigin(), *pvecTarget, 0.2, 1.0, false );
  1682. }
  1683. else
  1684. {
  1685. if ( pVelocity )
  1686. {
  1687. vecThrow = *pVelocity;
  1688. float flLen = vecThrow.Length();
  1689. if (flLen > 400)
  1690. {
  1691. VectorNormalize(vecThrow);
  1692. vecThrow *= 400;
  1693. }
  1694. }
  1695. else
  1696. {
  1697. // Nowhere in particular; just drop it.
  1698. float throwForce = ( IsPlayer() ) ? 400.0f : random->RandomInt( 64, 128 );
  1699. vecThrow = BodyDirection3D() * throwForce;
  1700. }
  1701. }
  1702. pWeapon->Drop( vecThrow );
  1703. Weapon_Detach( pWeapon );
  1704. if ( HasSpawnFlags( SF_NPC_NO_WEAPON_DROP ) )
  1705. {
  1706. // Don't drop weapons when the super physgun is happening.
  1707. UTIL_Remove( pWeapon );
  1708. }
  1709. }
  1710. //-----------------------------------------------------------------------------
  1711. // Lighting origin
  1712. //-----------------------------------------------------------------------------
  1713. void CBaseCombatCharacter::SetLightingOriginRelative( CBaseEntity *pLightingOrigin )
  1714. {
  1715. BaseClass::SetLightingOriginRelative( pLightingOrigin );
  1716. if ( GetActiveWeapon() )
  1717. {
  1718. GetActiveWeapon()->SetLightingOriginRelative( pLightingOrigin );
  1719. }
  1720. }
  1721. //-----------------------------------------------------------------------------
  1722. // Purpose: Add new weapon to the character
  1723. // Input : New weapon
  1724. //-----------------------------------------------------------------------------
  1725. void CBaseCombatCharacter::Weapon_Equip( CBaseCombatWeapon *pWeapon )
  1726. {
  1727. // Add the weapon to my weapon inventory
  1728. for (int i=0;i<MAX_WEAPONS;i++)
  1729. {
  1730. if (!m_hMyWeapons[i])
  1731. {
  1732. m_hMyWeapons.Set( i, pWeapon );
  1733. break;
  1734. }
  1735. }
  1736. // Weapon is now on my team
  1737. pWeapon->ChangeTeam( GetTeamNumber() );
  1738. // ----------------------
  1739. // Give Primary Ammo
  1740. // ----------------------
  1741. // If gun doesn't use clips, just give ammo
  1742. if (pWeapon->GetMaxClip1() == -1)
  1743. {
  1744. #ifdef HL2_DLL
  1745. if( FStrEq(STRING(gpGlobals->mapname), "d3_c17_09") && FClassnameIs(pWeapon, "weapon_rpg") && pWeapon->NameMatches("player_spawn_items") )
  1746. {
  1747. // !!!HACK - Don't give any ammo with the spawn equipment RPG in d3_c17_09. This is a chapter
  1748. // start and the map is way to easy if you start with 3 RPG rounds. It's fine if a player conserves
  1749. // them and uses them here, but it's not OK to start with enough ammo to bypass the snipers completely.
  1750. GiveAmmo( 0, pWeapon->m_iPrimaryAmmoType);
  1751. }
  1752. else
  1753. #endif // HL2_DLL
  1754. GiveAmmo(pWeapon->GetDefaultClip1(), pWeapon->m_iPrimaryAmmoType);
  1755. }
  1756. // If default ammo given is greater than clip
  1757. // size, fill clips and give extra ammo
  1758. else if (pWeapon->GetDefaultClip1() > pWeapon->GetMaxClip1() )
  1759. {
  1760. pWeapon->m_iClip1 = pWeapon->GetMaxClip1();
  1761. GiveAmmo( (pWeapon->GetDefaultClip1() - pWeapon->GetMaxClip1()), pWeapon->m_iPrimaryAmmoType);
  1762. }
  1763. // ----------------------
  1764. // Give Secondary Ammo
  1765. // ----------------------
  1766. // If gun doesn't use clips, just give ammo
  1767. if (pWeapon->GetMaxClip2() == -1)
  1768. {
  1769. GiveAmmo(pWeapon->GetDefaultClip2(), pWeapon->m_iSecondaryAmmoType);
  1770. }
  1771. // If default ammo given is greater than clip
  1772. // size, fill clips and give extra ammo
  1773. else if ( pWeapon->GetDefaultClip2() > pWeapon->GetMaxClip2() )
  1774. {
  1775. pWeapon->m_iClip2 = pWeapon->GetMaxClip2();
  1776. GiveAmmo( (pWeapon->GetDefaultClip2() - pWeapon->GetMaxClip2()), pWeapon->m_iSecondaryAmmoType);
  1777. }
  1778. pWeapon->Equip( this );
  1779. // Players don't automatically holster their current weapon
  1780. if ( IsPlayer() == false )
  1781. {
  1782. if ( m_hActiveWeapon )
  1783. {
  1784. m_hActiveWeapon->Holster();
  1785. // FIXME: isn't this handeled by the weapon?
  1786. m_hActiveWeapon->AddEffects( EF_NODRAW );
  1787. }
  1788. SetActiveWeapon( pWeapon );
  1789. m_hActiveWeapon->RemoveEffects( EF_NODRAW );
  1790. }
  1791. // Gotta do this *after* Equip because it may whack maxRange
  1792. if ( IsPlayer() == false )
  1793. {
  1794. // If SF_NPC_LONG_RANGE spawn flags is set let weapon work from any distance
  1795. if ( HasSpawnFlags(SF_NPC_LONG_RANGE) )
  1796. {
  1797. m_hActiveWeapon->m_fMaxRange1 = 999999999;
  1798. m_hActiveWeapon->m_fMaxRange2 = 999999999;
  1799. }
  1800. }
  1801. WeaponProficiency_t proficiency;
  1802. proficiency = CalcWeaponProficiency( pWeapon );
  1803. if( weapon_showproficiency.GetBool() != 0 )
  1804. {
  1805. Msg("%s equipped with %s, proficiency is %s\n", GetClassname(), pWeapon->GetClassname(), GetWeaponProficiencyName( proficiency ) );
  1806. }
  1807. SetCurrentWeaponProficiency( proficiency );
  1808. // Pass the lighting origin over to the weapon if we have one
  1809. pWeapon->SetLightingOriginRelative( GetLightingOriginRelative() );
  1810. }
  1811. //-----------------------------------------------------------------------------
  1812. // Purpose: Leaves weapon, giving only ammo to the character
  1813. // Input : Weapon
  1814. //-----------------------------------------------------------------------------
  1815. bool CBaseCombatCharacter::Weapon_EquipAmmoOnly( CBaseCombatWeapon *pWeapon )
  1816. {
  1817. // Check for duplicates
  1818. for (int i=0;i<MAX_WEAPONS;i++)
  1819. {
  1820. if ( m_hMyWeapons[i].Get() && FClassnameIs(m_hMyWeapons[i], pWeapon->GetClassname()) )
  1821. {
  1822. // Just give the ammo from the clip
  1823. int primaryGiven = (pWeapon->UsesClipsForAmmo1()) ? pWeapon->m_iClip1 : pWeapon->GetPrimaryAmmoCount();
  1824. int secondaryGiven = (pWeapon->UsesClipsForAmmo2()) ? pWeapon->m_iClip2 : pWeapon->GetSecondaryAmmoCount();
  1825. int takenPrimary = GiveAmmo( primaryGiven, pWeapon->m_iPrimaryAmmoType);
  1826. int takenSecondary = GiveAmmo( secondaryGiven, pWeapon->m_iSecondaryAmmoType);
  1827. if( pWeapon->UsesClipsForAmmo1() )
  1828. {
  1829. pWeapon->m_iClip1 -= takenPrimary;
  1830. }
  1831. else
  1832. {
  1833. pWeapon->SetPrimaryAmmoCount( pWeapon->GetPrimaryAmmoCount() - takenPrimary );
  1834. }
  1835. if( pWeapon->UsesClipsForAmmo2() )
  1836. {
  1837. pWeapon->m_iClip2 -= takenSecondary;
  1838. }
  1839. else
  1840. {
  1841. pWeapon->SetSecondaryAmmoCount( pWeapon->GetSecondaryAmmoCount() - takenSecondary );
  1842. }
  1843. //Only succeed if we've taken ammo from the weapon
  1844. if ( takenPrimary > 0 || takenSecondary > 0 )
  1845. return true;
  1846. return false;
  1847. }
  1848. }
  1849. return false;
  1850. }
  1851. //-----------------------------------------------------------------------------
  1852. // Purpose: Returns whether the weapon passed in would occupy a slot already occupied by the carrier
  1853. // Input : *pWeapon - weapon to test for
  1854. // Output : Returns true on success, false on failure.
  1855. //-----------------------------------------------------------------------------
  1856. bool CBaseCombatCharacter::Weapon_SlotOccupied( CBaseCombatWeapon *pWeapon )
  1857. {
  1858. if ( pWeapon == NULL )
  1859. return false;
  1860. //Check to see if there's a resident weapon already in this slot
  1861. if ( Weapon_GetSlot( pWeapon->GetSlot() ) == NULL )
  1862. return false;
  1863. return true;
  1864. }
  1865. //-----------------------------------------------------------------------------
  1866. // Purpose: Returns the weapon (if any) in the requested slot
  1867. // Input : slot - which slot to poll
  1868. //-----------------------------------------------------------------------------
  1869. CBaseCombatWeapon *CBaseCombatCharacter::Weapon_GetSlot( int slot ) const
  1870. {
  1871. int targetSlot = slot;
  1872. // Check for that slot being occupied already
  1873. for ( int i=0; i < MAX_WEAPONS; i++ )
  1874. {
  1875. if ( m_hMyWeapons[i].Get() != NULL )
  1876. {
  1877. // If the slots match, it's already occupied
  1878. if ( m_hMyWeapons[i]->GetSlot() == targetSlot )
  1879. return m_hMyWeapons[i];
  1880. }
  1881. }
  1882. return NULL;
  1883. }
  1884. //-----------------------------------------------------------------------------
  1885. // Purpose: Get a pointer to a weapon this character has that uses the specified ammo
  1886. //-----------------------------------------------------------------------------
  1887. CBaseCombatWeapon *CBaseCombatCharacter::Weapon_GetWpnForAmmo( int iAmmoIndex )
  1888. {
  1889. for ( int i = 0; i < MAX_WEAPONS; i++ )
  1890. {
  1891. CBaseCombatWeapon *weapon = GetWeapon( i );
  1892. if ( !weapon )
  1893. continue;
  1894. if ( weapon->GetPrimaryAmmoType() == iAmmoIndex )
  1895. return weapon;
  1896. if ( weapon->GetSecondaryAmmoType() == iAmmoIndex )
  1897. return weapon;
  1898. }
  1899. return NULL;
  1900. }
  1901. //-----------------------------------------------------------------------------
  1902. // Purpose: Can this character operate this weapon?
  1903. // Input : A weapon
  1904. // Output : true or false
  1905. //-----------------------------------------------------------------------------
  1906. bool CBaseCombatCharacter::Weapon_CanUse( CBaseCombatWeapon *pWeapon )
  1907. {
  1908. int actCount = 0;
  1909. acttable_t *pTable = pWeapon->ActivityList( actCount );
  1910. if( actCount < 1 )
  1911. {
  1912. // If the weapon has no activity table, it definitely cannot be used.
  1913. return false;
  1914. }
  1915. for ( int i = 0; i < actCount; i++, pTable++ )
  1916. {
  1917. if ( pTable->required )
  1918. {
  1919. // The NPC might translate the weapon activity into another activity
  1920. Activity translatedActivity = NPC_TranslateActivity( (Activity)(pTable->weaponAct) );
  1921. if ( SelectWeightedSequence(translatedActivity) == ACTIVITY_NOT_AVAILABLE )
  1922. {
  1923. return false;
  1924. }
  1925. }
  1926. }
  1927. return true;
  1928. }
  1929. //-----------------------------------------------------------------------------
  1930. // Purpose:
  1931. // Input :
  1932. // Output :
  1933. //-----------------------------------------------------------------------------
  1934. CBaseCombatWeapon *CBaseCombatCharacter::Weapon_Create( const char *pWeaponName )
  1935. {
  1936. CBaseCombatWeapon *pWeapon = static_cast<CBaseCombatWeapon *>( Create( pWeaponName, GetLocalOrigin(), GetLocalAngles(), this ) );
  1937. return pWeapon;
  1938. }
  1939. //-----------------------------------------------------------------------------
  1940. // Purpose:
  1941. // Input :
  1942. // Output :
  1943. //-----------------------------------------------------------------------------
  1944. void CBaseCombatCharacter::Weapon_HandleAnimEvent( animevent_t *pEvent )
  1945. {
  1946. // UNDONE: Some check to make sure that pEvent->pSource is a weapon I'm holding?
  1947. if ( m_hActiveWeapon )
  1948. {
  1949. // UNDONE: Pass to pEvent->pSource instead?
  1950. m_hActiveWeapon->Operator_HandleAnimEvent( pEvent, this );
  1951. }
  1952. }
  1953. void CBaseCombatCharacter::RemoveAllWeapons()
  1954. {
  1955. ClearActiveWeapon();
  1956. for (int i = 0; i < MAX_WEAPONS; i++)
  1957. {
  1958. if ( m_hMyWeapons[i] )
  1959. {
  1960. m_hMyWeapons[i]->Delete( );
  1961. m_hMyWeapons.Set( i, NULL );
  1962. }
  1963. }
  1964. }
  1965. // take health
  1966. int CBaseCombatCharacter::TakeHealth (float flHealth, int bitsDamageType)
  1967. {
  1968. if (!m_takedamage)
  1969. return 0;
  1970. return BaseClass::TakeHealth(flHealth, bitsDamageType);
  1971. }
  1972. /*
  1973. ============
  1974. OnTakeDamage
  1975. The damage is coming from inflictor, but get mad at attacker
  1976. This should be the only function that ever reduces health.
  1977. bitsDamageType indicates the type of damage sustained, ie: DMG_SHOCK
  1978. Time-based damage: only occurs while the NPC is within the trigger_hurt.
  1979. When a NPC is poisoned via an arrow etc it takes all the poison damage at once.
  1980. GLOBALS ASSUMED SET: g_iSkillLevel
  1981. ============
  1982. */
  1983. int CBaseCombatCharacter::OnTakeDamage( const CTakeDamageInfo &info )
  1984. {
  1985. int retVal = 0;
  1986. if (!m_takedamage)
  1987. return 0;
  1988. m_iDamageCount++;
  1989. if ( info.GetDamageType() & DMG_SHOCK )
  1990. {
  1991. g_pEffects->Sparks( info.GetDamagePosition(), 2, 2 );
  1992. UTIL_Smoke( info.GetDamagePosition(), random->RandomInt( 10, 15 ), 10 );
  1993. }
  1994. // track damage history
  1995. if ( info.GetAttacker() )
  1996. {
  1997. int attackerTeam = info.GetAttacker()->GetTeamNumber();
  1998. m_hasBeenInjured |= ( 1 << attackerTeam );
  1999. for( int i=0; i<MAX_DAMAGE_TEAMS; ++i )
  2000. {
  2001. if ( m_damageHistory[i].team == attackerTeam )
  2002. {
  2003. // restart the injury timer
  2004. m_damageHistory[i].interval.Start();
  2005. break;
  2006. }
  2007. if ( m_damageHistory[i].team == TEAM_INVALID )
  2008. {
  2009. // team not registered yet
  2010. m_damageHistory[i].team = attackerTeam;
  2011. m_damageHistory[i].interval.Start();
  2012. break;
  2013. }
  2014. }
  2015. }
  2016. switch( m_lifeState )
  2017. {
  2018. case LIFE_ALIVE:
  2019. retVal = OnTakeDamage_Alive( info );
  2020. if ( m_iHealth <= 0 )
  2021. {
  2022. IPhysicsObject *pPhysics = VPhysicsGetObject();
  2023. if ( pPhysics )
  2024. {
  2025. pPhysics->EnableCollisions( false );
  2026. }
  2027. bool bGibbed = false;
  2028. Event_Killed( info );
  2029. // Only classes that specifically request it are gibbed
  2030. if ( ShouldGib( info ) )
  2031. {
  2032. bGibbed = Event_Gibbed( info );
  2033. }
  2034. if ( bGibbed == false )
  2035. {
  2036. Event_Dying( info );
  2037. }
  2038. }
  2039. return retVal;
  2040. break;
  2041. case LIFE_DYING:
  2042. return OnTakeDamage_Dying( info );
  2043. default:
  2044. case LIFE_DEAD:
  2045. retVal = OnTakeDamage_Dead( info );
  2046. if ( m_iHealth <= 0 && g_pGameRules->Damage_ShouldGibCorpse( info.GetDamageType() ) && ShouldGib( info ) )
  2047. {
  2048. Event_Gibbed( info );
  2049. retVal = 0;
  2050. }
  2051. return retVal;
  2052. }
  2053. }
  2054. int CBaseCombatCharacter::OnTakeDamage_Alive( const CTakeDamageInfo &info )
  2055. {
  2056. // grab the vector of the incoming attack. ( pretend that the inflictor is a little lower than it really is, so the body will tend to fly upward a bit).
  2057. Vector vecDir = vec3_origin;
  2058. if (info.GetInflictor())
  2059. {
  2060. vecDir = info.GetInflictor()->WorldSpaceCenter() - Vector ( 0, 0, 10 ) - WorldSpaceCenter();
  2061. VectorNormalize(vecDir);
  2062. }
  2063. g_vecAttackDir = vecDir;
  2064. //!!!LATER - make armor consideration here!
  2065. // do the damage
  2066. if ( m_takedamage != DAMAGE_EVENTS_ONLY )
  2067. {
  2068. // Separate the fractional amount of damage from the whole
  2069. float flFractionalDamage = info.GetDamage() - floor( info.GetDamage() );
  2070. float flIntegerDamage = info.GetDamage() - flFractionalDamage;
  2071. // Add fractional damage to the accumulator
  2072. m_flDamageAccumulator += flFractionalDamage;
  2073. // If the accumulator is holding a full point of damage, move that point
  2074. // of damage into the damage we're about to inflict.
  2075. if( m_flDamageAccumulator >= 1.0 )
  2076. {
  2077. flIntegerDamage += 1.0;
  2078. m_flDamageAccumulator -= 1.0;
  2079. }
  2080. if ( flIntegerDamage <= 0 )
  2081. return 0;
  2082. m_iHealth -= flIntegerDamage;
  2083. }
  2084. return 1;
  2085. }
  2086. int CBaseCombatCharacter::OnTakeDamage_Dying( const CTakeDamageInfo &info )
  2087. {
  2088. return 1;
  2089. }
  2090. int CBaseCombatCharacter::OnTakeDamage_Dead( const CTakeDamageInfo &info )
  2091. {
  2092. // do the damage
  2093. if ( m_takedamage != DAMAGE_EVENTS_ONLY )
  2094. {
  2095. m_iHealth -= info.GetDamage();
  2096. }
  2097. return 1;
  2098. }
  2099. //-----------------------------------------------------------------------------
  2100. // Purpose: Sets vBodyDir to the body direction (2D) of the combat character.
  2101. // Used as NPC's and players extract facing direction differently
  2102. // Input :
  2103. // Output :
  2104. //-----------------------------------------------------------------------------
  2105. QAngle CBaseCombatCharacter::BodyAngles()
  2106. {
  2107. return GetAbsAngles();
  2108. }
  2109. Vector CBaseCombatCharacter::BodyDirection2D( void )
  2110. {
  2111. Vector vBodyDir = BodyDirection3D( );
  2112. vBodyDir.z = 0;
  2113. vBodyDir.AsVector2D().NormalizeInPlace();
  2114. return vBodyDir;
  2115. }
  2116. Vector CBaseCombatCharacter::BodyDirection3D( void )
  2117. {
  2118. QAngle angles = BodyAngles();
  2119. // FIXME: cache this
  2120. Vector vBodyDir;
  2121. AngleVectors( angles, &vBodyDir );
  2122. return vBodyDir;
  2123. }
  2124. void CBaseCombatCharacter::SetTransmit( CCheckTransmitInfo *pInfo, bool bAlways )
  2125. {
  2126. // Skip this work if we're already marked for transmission.
  2127. if ( pInfo->m_pTransmitEdict->Get( entindex() ) )
  2128. return;
  2129. BaseClass::SetTransmit( pInfo, bAlways );
  2130. bool bLocalPlayer = ( pInfo->m_pClientEnt == edict() );
  2131. if ( bLocalPlayer )
  2132. {
  2133. for ( int i=0; i < MAX_WEAPONS; i++ )
  2134. {
  2135. CBaseCombatWeapon *pWeapon = m_hMyWeapons[i];
  2136. if ( !pWeapon )
  2137. continue;
  2138. // The local player is sent all of his weapons.
  2139. pWeapon->SetTransmit( pInfo, bAlways );
  2140. }
  2141. }
  2142. else
  2143. {
  2144. // The check for EF_NODRAW is useless because the weapon will be networked anyway. In CBaseCombatWeapon::
  2145. // UpdateTransmitState all weapons with owners will transmit to clients in the PVS.
  2146. if ( m_hActiveWeapon && !m_hActiveWeapon->IsEffectActive( EF_NODRAW ) )
  2147. m_hActiveWeapon->SetTransmit( pInfo, bAlways );
  2148. }
  2149. }
  2150. //-----------------------------------------------------------------------------
  2151. // Purpose: Add or Change a class relationship for this entity
  2152. // Input :
  2153. // Output :
  2154. //-----------------------------------------------------------------------------
  2155. void CBaseCombatCharacter::AddClassRelationship ( Class_T class_type, Disposition_t disposition, int priority )
  2156. {
  2157. // First check to see if a relationship has already been declared for this class
  2158. // If so, update it with the new relationship
  2159. for (int i=m_Relationship.Count()-1;i >= 0;i--)
  2160. {
  2161. if (m_Relationship[i].classType == class_type)
  2162. {
  2163. m_Relationship[i].disposition = disposition;
  2164. if ( priority != DEF_RELATIONSHIP_PRIORITY )
  2165. m_Relationship[i].priority = priority;
  2166. return;
  2167. }
  2168. }
  2169. int index = m_Relationship.AddToTail();
  2170. // Add the new class relationship to our relationship table
  2171. m_Relationship[index].classType = class_type;
  2172. m_Relationship[index].entity = NULL;
  2173. m_Relationship[index].disposition = disposition;
  2174. m_Relationship[index].priority = ( priority != DEF_RELATIONSHIP_PRIORITY ) ? priority : 0;
  2175. }
  2176. //-----------------------------------------------------------------------------
  2177. // Purpose: Add or Change a entity relationship for this entity
  2178. // Input :
  2179. // Output :
  2180. //-----------------------------------------------------------------------------
  2181. void CBaseCombatCharacter::AddEntityRelationship ( CBaseEntity* pEntity, Disposition_t disposition, int priority )
  2182. {
  2183. // First check to see if a relationship has already been declared for this entity
  2184. // If so, update it with the new relationship
  2185. for (int i=m_Relationship.Count()-1;i >= 0;i--)
  2186. {
  2187. if (m_Relationship[i].entity == pEntity)
  2188. {
  2189. m_Relationship[i].disposition = disposition;
  2190. if ( priority != DEF_RELATIONSHIP_PRIORITY )
  2191. m_Relationship[i].priority = priority;
  2192. return;
  2193. }
  2194. }
  2195. int index = m_Relationship.AddToTail();
  2196. // Add the new class relationship to our relationship table
  2197. m_Relationship[index].classType = CLASS_NONE;
  2198. m_Relationship[index].entity = pEntity;
  2199. m_Relationship[index].disposition = disposition;
  2200. m_Relationship[index].priority = ( priority != DEF_RELATIONSHIP_PRIORITY ) ? priority : 0;
  2201. }
  2202. //-----------------------------------------------------------------------------
  2203. // Purpose: Removes an entity relationship from our list
  2204. // Input : *pEntity - Entity with whom the relationship should be ended
  2205. // Output : True is entity was removed, false if it was not found
  2206. //-----------------------------------------------------------------------------
  2207. bool CBaseCombatCharacter::RemoveEntityRelationship( CBaseEntity *pEntity )
  2208. {
  2209. // Find the entity in our list, if it exists
  2210. for ( int i = m_Relationship.Count()-1; i >= 0; i-- )
  2211. {
  2212. if ( m_Relationship[i].entity == pEntity )
  2213. {
  2214. // Done, remove it
  2215. m_Relationship.Remove( i );
  2216. return true;
  2217. }
  2218. }
  2219. return false;
  2220. }
  2221. //-----------------------------------------------------------------------------
  2222. // Allocates default relationships
  2223. //-----------------------------------------------------------------------------
  2224. void CBaseCombatCharacter::AllocateDefaultRelationships( )
  2225. {
  2226. if (!m_DefaultRelationship)
  2227. {
  2228. m_DefaultRelationship = new Relationship_t*[NUM_AI_CLASSES];
  2229. for (int i=0; i<NUM_AI_CLASSES; ++i)
  2230. {
  2231. // Be default all relationships are neutral of priority zero
  2232. m_DefaultRelationship[i] = new Relationship_t[NUM_AI_CLASSES];
  2233. }
  2234. }
  2235. }
  2236. //-----------------------------------------------------------------------------
  2237. // Purpose: Return an interaction ID (so we have no collisions)
  2238. // Input :
  2239. // Output :
  2240. //-----------------------------------------------------------------------------
  2241. void CBaseCombatCharacter::SetDefaultRelationship(Class_T nClass, Class_T nClassTarget, Disposition_t nDisposition, int nPriority)
  2242. {
  2243. if (m_DefaultRelationship)
  2244. {
  2245. m_DefaultRelationship[nClass][nClassTarget].disposition = nDisposition;
  2246. m_DefaultRelationship[nClass][nClassTarget].priority = nPriority;
  2247. }
  2248. }
  2249. //-----------------------------------------------------------------------------
  2250. // Purpose: Fetch the default (ignore ai_relationship changes) relationship
  2251. // Input :
  2252. // Output :
  2253. //-----------------------------------------------------------------------------
  2254. Disposition_t CBaseCombatCharacter::GetDefaultRelationshipDisposition( Class_T nClassTarget )
  2255. {
  2256. Assert( m_DefaultRelationship != NULL );
  2257. return m_DefaultRelationship[Classify()][nClassTarget].disposition;
  2258. }
  2259. //-----------------------------------------------------------------------------
  2260. // Purpose: describes the relationship between two types of NPC.
  2261. // Input :
  2262. // Output :
  2263. //-----------------------------------------------------------------------------
  2264. Relationship_t *CBaseCombatCharacter::FindEntityRelationship( CBaseEntity *pTarget )
  2265. {
  2266. if ( !pTarget )
  2267. {
  2268. static Relationship_t dummy;
  2269. return &dummy;
  2270. }
  2271. // First check for specific relationship with this edict
  2272. int i;
  2273. for (i=0;i<m_Relationship.Count();i++)
  2274. {
  2275. if (pTarget == (CBaseEntity *)m_Relationship[i].entity)
  2276. {
  2277. return &m_Relationship[i];
  2278. }
  2279. }
  2280. if (pTarget->Classify() != CLASS_NONE)
  2281. {
  2282. // Then check for relationship with this edict's class
  2283. for (i=0;i<m_Relationship.Count();i++)
  2284. {
  2285. if (pTarget->Classify() == m_Relationship[i].classType)
  2286. {
  2287. return &m_Relationship[i];
  2288. }
  2289. }
  2290. }
  2291. AllocateDefaultRelationships();
  2292. // If none found return the default
  2293. return &m_DefaultRelationship[ Classify() ][ pTarget->Classify() ];
  2294. }
  2295. Disposition_t CBaseCombatCharacter::IRelationType ( CBaseEntity *pTarget )
  2296. {
  2297. if ( pTarget )
  2298. return FindEntityRelationship( pTarget )->disposition;
  2299. return D_NU;
  2300. }
  2301. //-----------------------------------------------------------------------------
  2302. // Purpose: describes the relationship between two types of NPC.
  2303. // Input :
  2304. // Output :
  2305. //-----------------------------------------------------------------------------
  2306. int CBaseCombatCharacter::IRelationPriority( CBaseEntity *pTarget )
  2307. {
  2308. if ( pTarget )
  2309. return FindEntityRelationship( pTarget )->priority;
  2310. return 0;
  2311. }
  2312. //-----------------------------------------------------------------------------
  2313. // Purpose: Get shoot position of BCC at current position/orientation
  2314. // Input :
  2315. // Output :
  2316. //-----------------------------------------------------------------------------
  2317. Vector CBaseCombatCharacter::Weapon_ShootPosition( )
  2318. {
  2319. Vector forward, right, up;
  2320. AngleVectors( GetAbsAngles(), &forward, &right, &up );
  2321. Vector vecSrc = GetAbsOrigin()
  2322. + forward * m_HackedGunPos.y
  2323. + right * m_HackedGunPos.x
  2324. + up * m_HackedGunPos.z;
  2325. return vecSrc;
  2326. }
  2327. //-----------------------------------------------------------------------------
  2328. //-----------------------------------------------------------------------------
  2329. CBaseEntity *CBaseCombatCharacter::FindHealthItem( const Vector &vecPosition, const Vector &range )
  2330. {
  2331. CBaseEntity *list[1024];
  2332. int count = UTIL_EntitiesInBox( list, 1024, vecPosition - range, vecPosition + range, 0 );
  2333. for ( int i = 0; i < count; i++ )
  2334. {
  2335. CItem *pItem = dynamic_cast<CItem *>(list[ i ]);
  2336. if( pItem )
  2337. {
  2338. // Healthkits and healthvials
  2339. if( pItem->ClassMatches( "item_health*" ) && FVisible( pItem ) )
  2340. {
  2341. return pItem;
  2342. }
  2343. }
  2344. }
  2345. return NULL;
  2346. }
  2347. //-----------------------------------------------------------------------------
  2348. // Compares the weapon's center with this character's current origin, so it
  2349. // will not give reliable results for weapons that are visible to the NPC
  2350. // but are upstairs/downstairs, etc.
  2351. //
  2352. // A weapon is said to be on the ground if it is no more than 12 inches above
  2353. // or below the caller's feet.
  2354. //-----------------------------------------------------------------------------
  2355. bool CBaseCombatCharacter::Weapon_IsOnGround( CBaseCombatWeapon *pWeapon )
  2356. {
  2357. if( pWeapon->IsConstrained() )
  2358. {
  2359. // Constrained to a rack.
  2360. return false;
  2361. }
  2362. if( fabs(pWeapon->WorldSpaceCenter().z - GetAbsOrigin().z) >= 12.0f )
  2363. {
  2364. return false;
  2365. }
  2366. return true;
  2367. }
  2368. //-----------------------------------------------------------------------------
  2369. // Purpose:
  2370. // Input : &range -
  2371. // Output : CBaseEntity
  2372. //-----------------------------------------------------------------------------
  2373. CBaseEntity *CBaseCombatCharacter::Weapon_FindUsable( const Vector &range )
  2374. {
  2375. bool bConservative = false;
  2376. #ifdef HL2_DLL
  2377. if( hl2_episodic.GetBool() && !GetActiveWeapon() )
  2378. {
  2379. // Unarmed citizens are conservative in their weapon finding
  2380. if ( Classify() != CLASS_PLAYER_ALLY_VITAL )
  2381. {
  2382. bConservative = true;
  2383. }
  2384. }
  2385. #endif
  2386. CBaseCombatWeapon *weaponList[64];
  2387. CBaseCombatWeapon *pBestWeapon = NULL;
  2388. Vector mins = GetAbsOrigin() - range;
  2389. Vector maxs = GetAbsOrigin() + range;
  2390. int listCount = CBaseCombatWeapon::GetAvailableWeaponsInBox( weaponList, ARRAYSIZE(weaponList), mins, maxs );
  2391. float fBestDist = 1e6;
  2392. for ( int i = 0; i < listCount; i++ )
  2393. {
  2394. // Make sure not moving (ie flying through the air)
  2395. Vector velocity;
  2396. CBaseCombatWeapon *pWeapon = weaponList[i];
  2397. Assert(pWeapon);
  2398. pWeapon->GetVelocity( &velocity, NULL );
  2399. if ( pWeapon->CanBePickedUpByNPCs() == false )
  2400. continue;
  2401. if ( velocity.LengthSqr() > 1 || !Weapon_CanUse(pWeapon) )
  2402. continue;
  2403. if ( pWeapon->IsLocked(this) )
  2404. continue;
  2405. if ( GetActiveWeapon() )
  2406. {
  2407. // Already armed. Would picking up this weapon improve my situation?
  2408. if( GetActiveWeapon()->m_iClassname == pWeapon->m_iClassname )
  2409. {
  2410. // No, I'm already using this type of weapon.
  2411. continue;
  2412. }
  2413. if( FClassnameIs( pWeapon, "weapon_pistol" ) )
  2414. {
  2415. // No, it's a pistol.
  2416. continue;
  2417. }
  2418. }
  2419. float fCurDist = (pWeapon->GetLocalOrigin() - GetLocalOrigin()).Length();
  2420. // Give any reserved weapon a bonus
  2421. if( pWeapon->HasSpawnFlags( SF_WEAPON_NO_PLAYER_PICKUP ) )
  2422. {
  2423. fCurDist *= 0.5f;
  2424. }
  2425. if ( pBestWeapon )
  2426. {
  2427. // UNDONE: Better heuristic needed here
  2428. // Need to pick by power of weapons
  2429. // Don't want to pick a weapon right next to a NPC!
  2430. // Give the AR2 a bonus to be selected by making it seem closer.
  2431. if( FClassnameIs( pWeapon, "weapon_ar2" ) )
  2432. {
  2433. fCurDist *= 0.5;
  2434. }
  2435. // choose the last range attack weapon you find or the first available other weapon
  2436. if ( ! (pWeapon->CapabilitiesGet() & bits_CAP_RANGE_ATTACK_GROUP) )
  2437. {
  2438. continue;
  2439. }
  2440. else if (fCurDist > fBestDist )
  2441. {
  2442. continue;
  2443. }
  2444. }
  2445. if( Weapon_IsOnGround(pWeapon) )
  2446. {
  2447. // Weapon appears to be lying on the ground. Make sure this weapon is reachable
  2448. // by tracing out a human sized hull just above the weapon. If not, reject
  2449. trace_t tr;
  2450. Vector vAboveWeapon = pWeapon->GetAbsOrigin();
  2451. UTIL_TraceEntity( this, vAboveWeapon, vAboveWeapon + Vector( 0, 0, 1 ), MASK_SOLID, pWeapon, COLLISION_GROUP_NONE, &tr );
  2452. if ( tr.startsolid || (tr.fraction < 1.0) )
  2453. continue;
  2454. }
  2455. else if( bConservative )
  2456. {
  2457. // Skip it.
  2458. continue;
  2459. }
  2460. if( FVisible(pWeapon) )
  2461. {
  2462. fBestDist = fCurDist;
  2463. pBestWeapon = pWeapon;
  2464. }
  2465. }
  2466. if( pBestWeapon )
  2467. {
  2468. // Lock this weapon for my exclusive use. Lock it for just a couple of seconds because my AI
  2469. // might not actually be able to go pick it up right now.
  2470. pBestWeapon->Lock( 2.0, this );
  2471. }
  2472. return pBestWeapon;
  2473. }
  2474. //-----------------------------------------------------------------------------
  2475. // Purpose: Give the player some ammo.
  2476. // Input : iCount - Amount of ammo to give.
  2477. // iAmmoIndex - Index of the ammo into the AmmoInfoArray
  2478. // iMax - Max carrying capability of the player
  2479. // Output : Amount of ammo actually given
  2480. //-----------------------------------------------------------------------------
  2481. int CBaseCombatCharacter::GiveAmmo( int iCount, int iAmmoIndex, bool bSuppressSound)
  2482. {
  2483. if (iCount <= 0)
  2484. return 0;
  2485. if ( !g_pGameRules->CanHaveAmmo( this, iAmmoIndex ) )
  2486. {
  2487. // game rules say I can't have any more of this ammo type.
  2488. return 0;
  2489. }
  2490. if ( iAmmoIndex < 0 || iAmmoIndex >= MAX_AMMO_SLOTS )
  2491. return 0;
  2492. int iMax = GetAmmoDef()->MaxCarry(iAmmoIndex);
  2493. int iAdd = MIN( iCount, iMax - m_iAmmo[iAmmoIndex] );
  2494. if ( iAdd < 1 )
  2495. return 0;
  2496. // Ammo pickup sound
  2497. if ( !bSuppressSound )
  2498. {
  2499. EmitSound( "BaseCombatCharacter.AmmoPickup" );
  2500. }
  2501. m_iAmmo.Set( iAmmoIndex, m_iAmmo[iAmmoIndex] + iAdd );
  2502. return iAdd;
  2503. }
  2504. //-----------------------------------------------------------------------------
  2505. // Purpose: Give the player some ammo.
  2506. //-----------------------------------------------------------------------------
  2507. int CBaseCombatCharacter::GiveAmmo( int iCount, const char *szName, bool bSuppressSound )
  2508. {
  2509. int iAmmoType = GetAmmoDef()->Index(szName);
  2510. if (iAmmoType == -1)
  2511. {
  2512. Msg("ERROR: Attempting to give unknown ammo type (%s)\n",szName);
  2513. return 0;
  2514. }
  2515. return GiveAmmo( iCount, iAmmoType, bSuppressSound );
  2516. }
  2517. ConVar phys_stressbodyweights( "phys_stressbodyweights", "5.0" );
  2518. void CBaseCombatCharacter::VPhysicsUpdate( IPhysicsObject *pPhysics )
  2519. {
  2520. ApplyStressDamage( pPhysics, false );
  2521. BaseClass::VPhysicsUpdate( pPhysics );
  2522. }
  2523. float CBaseCombatCharacter::CalculatePhysicsStressDamage( vphysics_objectstress_t *pStressOut, IPhysicsObject *pPhysics )
  2524. {
  2525. // stress damage hack.
  2526. float mass = pPhysics->GetMass();
  2527. CalculateObjectStress( pPhysics, this, pStressOut );
  2528. float stress = (pStressOut->receivedStress * m_impactEnergyScale) / mass;
  2529. // Make sure the stress isn't from being stuck inside some static object.
  2530. // how many times your own weight can you hold up?
  2531. if ( pStressOut->hasNonStaticStress && stress > phys_stressbodyweights.GetFloat() )
  2532. {
  2533. // if stuck, don't do this!
  2534. if ( !(pPhysics->GetGameFlags() & FVPHYSICS_PENETRATING) )
  2535. return 200;
  2536. }
  2537. return 0;
  2538. }
  2539. void CBaseCombatCharacter::ApplyStressDamage( IPhysicsObject *pPhysics, bool bRequireLargeObject )
  2540. {
  2541. #ifdef HL2_DLL
  2542. if( Classify() == CLASS_PLAYER_ALLY || Classify() == CLASS_PLAYER_ALLY_VITAL )
  2543. {
  2544. // Bypass stress completely for allies and vitals.
  2545. if( hl2_episodic.GetBool() )
  2546. return;
  2547. }
  2548. #endif//HL2_DLL
  2549. vphysics_objectstress_t stressOut;
  2550. float damage = CalculatePhysicsStressDamage( &stressOut, pPhysics );
  2551. if ( damage > 0 )
  2552. {
  2553. if ( bRequireLargeObject && !stressOut.hasLargeObjectContact )
  2554. return;
  2555. //Msg("Stress! %.2f / %.2f\n", stressOut.exertedStress, stressOut.receivedStress );
  2556. CTakeDamageInfo dmgInfo( GetWorldEntity(), GetWorldEntity(), vec3_origin, vec3_origin, damage, DMG_CRUSH );
  2557. dmgInfo.SetDamageForce( Vector( 0, 0, -stressOut.receivedStress * GetCurrentGravity() * gpGlobals->frametime ) );
  2558. dmgInfo.SetDamagePosition( GetAbsOrigin() );
  2559. TakeDamage( dmgInfo );
  2560. }
  2561. }
  2562. //-----------------------------------------------------------------------------
  2563. // Purpose:
  2564. // Output : const impactdamagetable_t
  2565. //-----------------------------------------------------------------------------
  2566. const impactdamagetable_t &CBaseCombatCharacter::GetPhysicsImpactDamageTable( void )
  2567. {
  2568. return gDefaultNPCImpactDamageTable;
  2569. }
  2570. // how much to amplify impact forces
  2571. // This is to account for the ragdolls responding differently than
  2572. // the shadow objects. Also this makes the impacts more dramatic.
  2573. ConVar phys_impactforcescale( "phys_impactforcescale", "1.0" );
  2574. ConVar phys_upimpactforcescale( "phys_upimpactforcescale", "0.375" );
  2575. void CBaseCombatCharacter::VPhysicsShadowCollision( int index, gamevcollisionevent_t *pEvent )
  2576. {
  2577. int otherIndex = !index;
  2578. CBaseEntity *pOther = pEvent->pEntities[otherIndex];
  2579. IPhysicsObject *pOtherPhysics = pEvent->pObjects[otherIndex];
  2580. if ( !pOther )
  2581. return;
  2582. // Ragdolls are marked as dying.
  2583. if ( pOther->m_lifeState == LIFE_DYING )
  2584. return;
  2585. if ( pOther->GetMoveType() != MOVETYPE_VPHYSICS )
  2586. return;
  2587. if ( !pOtherPhysics->IsMoveable() )
  2588. return;
  2589. if ( pOther == GetGroundEntity() )
  2590. return;
  2591. // Player can't damage himself if he's was physics attacker *on this frame*
  2592. // which can occur owing to ordering issues it appears.
  2593. float flOtherAttackerTime = 0.0f;
  2594. #if defined( HL2_DLL ) && !defined( HL2MP )
  2595. if ( HL2GameRules()->MegaPhyscannonActive() == true )
  2596. {
  2597. flOtherAttackerTime = 1.0f;
  2598. }
  2599. #endif // HL2_DLL && !HL2MP
  2600. if ( this == pOther->HasPhysicsAttacker( flOtherAttackerTime ) )
  2601. return;
  2602. int damageType = 0;
  2603. float damage = 0;
  2604. damage = CalculatePhysicsImpactDamage( index, pEvent, GetPhysicsImpactDamageTable(), m_impactEnergyScale, false, damageType );
  2605. if ( damage <= 0 )
  2606. return;
  2607. // NOTE: We really need some rotational motion for some of these collisions.
  2608. // REVISIT: Maybe resolve this collision on death with a different (not approximately infinite like AABB tensor)
  2609. // inertia tensor to get torque?
  2610. Vector damageForce = pEvent->postVelocity[index] * pEvent->pObjects[index]->GetMass() * phys_impactforcescale.GetFloat();
  2611. IServerVehicle *vehicleOther = pOther->GetServerVehicle();
  2612. if ( vehicleOther )
  2613. {
  2614. CBaseCombatCharacter *pPassenger = vehicleOther->GetPassenger();
  2615. if ( pPassenger != NULL )
  2616. {
  2617. // flag as vehicle damage
  2618. damageType |= DMG_VEHICLE;
  2619. // if hit by vehicle driven by player, add some upward velocity to force
  2620. float len = damageForce.Length();
  2621. damageForce.z += len*phys_upimpactforcescale.GetFloat();
  2622. //Msg("Force %.1f / %.1f\n", damageForce.Length(), damageForce.z );
  2623. if ( pPassenger->IsPlayer() )
  2624. {
  2625. CBasePlayer *pPlayer = assert_cast<CBasePlayer *>(pPassenger);
  2626. if( damage >= GetMaxHealth() )
  2627. {
  2628. pPlayer->RumbleEffect( RUMBLE_357, 0, RUMBLE_FLAG_RESTART );
  2629. }
  2630. else
  2631. {
  2632. pPlayer->RumbleEffect( RUMBLE_PISTOL, 0, RUMBLE_FLAG_RESTART );
  2633. }
  2634. }
  2635. }
  2636. }
  2637. Vector damagePos;
  2638. pEvent->pInternalData->GetContactPoint( damagePos );
  2639. CTakeDamageInfo dmgInfo( pOther, pOther, damageForce, damagePos, damage, damageType );
  2640. // FIXME: is there a better way for physics objects to keep track of what root entity responsible for them moving?
  2641. CBasePlayer *pPlayer = pOther->HasPhysicsAttacker( 1.0 );
  2642. if (pPlayer)
  2643. {
  2644. dmgInfo.SetAttacker( pPlayer );
  2645. }
  2646. // UNDONE: Find one near damagePos?
  2647. m_nForceBone = 0;
  2648. PhysCallbackDamage( this, dmgInfo, *pEvent, index );
  2649. }
  2650. //-----------------------------------------------------------------------------
  2651. // Purpose: this entity is exploding, or otherwise needs to inflict damage upon
  2652. // entities within a certain range. only damage ents that can clearly
  2653. // be seen by the explosion!
  2654. // Input :
  2655. // Output :
  2656. //-----------------------------------------------------------------------------
  2657. void RadiusDamage( const CTakeDamageInfo &info, const Vector &vecSrc, float flRadius, int iClassIgnore, CBaseEntity *pEntityIgnore )
  2658. {
  2659. // NOTE: I did this this way so I wouldn't have to change a whole bunch of
  2660. // code unnecessarily. We need TF2 specific rules for RadiusDamage, so I moved
  2661. // the implementation of radius damage into gamerules. All existing code calls
  2662. // this method, which calls the game rules method
  2663. g_pGameRules->RadiusDamage( info, vecSrc, flRadius, iClassIgnore, pEntityIgnore );
  2664. // Let the world know if this was an explosion.
  2665. if( info.GetDamageType() & DMG_BLAST )
  2666. {
  2667. // Even the tiniest explosion gets attention. Don't let the radius
  2668. // be less than 128 units.
  2669. float soundRadius = MAX( 128.0f, flRadius * 1.5 );
  2670. CSoundEnt::InsertSound( SOUND_COMBAT | SOUND_CONTEXT_EXPLOSION, vecSrc, soundRadius, 0.25, info.GetInflictor() );
  2671. }
  2672. }
  2673. //-----------------------------------------------------------------------------
  2674. // Purpose: Change active weapon and notify derived classes
  2675. //
  2676. //-----------------------------------------------------------------------------
  2677. void CBaseCombatCharacter::SetActiveWeapon( CBaseCombatWeapon *pNewWeapon )
  2678. {
  2679. CBaseCombatWeapon *pOldWeapon = m_hActiveWeapon;
  2680. if ( pNewWeapon != pOldWeapon )
  2681. {
  2682. m_hActiveWeapon = pNewWeapon;
  2683. OnChangeActiveWeapon( pOldWeapon, pNewWeapon );
  2684. }
  2685. }
  2686. //-----------------------------------------------------------------------------
  2687. // Consider the weapon's built-in accuracy, this character's proficiency with
  2688. // the weapon, and the status of the target. Use this information to determine
  2689. // how accurately to shoot at the target.
  2690. //-----------------------------------------------------------------------------
  2691. Vector CBaseCombatCharacter::GetAttackSpread( CBaseCombatWeapon *pWeapon, CBaseEntity *pTarget )
  2692. {
  2693. if ( pWeapon )
  2694. return pWeapon->GetBulletSpread(GetCurrentWeaponProficiency());
  2695. return VECTOR_CONE_15DEGREES;
  2696. }
  2697. //-----------------------------------------------------------------------------
  2698. float CBaseCombatCharacter::GetSpreadBias( CBaseCombatWeapon *pWeapon, CBaseEntity *pTarget )
  2699. {
  2700. if ( pWeapon )
  2701. return pWeapon->GetSpreadBias(GetCurrentWeaponProficiency());
  2702. return 1.0;
  2703. }
  2704. #ifdef GLOWS_ENABLE
  2705. //-----------------------------------------------------------------------------
  2706. // Purpose:
  2707. //-----------------------------------------------------------------------------
  2708. void CBaseCombatCharacter::AddGlowEffect( void )
  2709. {
  2710. SetTransmitState( FL_EDICT_ALWAYS );
  2711. m_bGlowEnabled.Set( true );
  2712. }
  2713. //-----------------------------------------------------------------------------
  2714. // Purpose:
  2715. //-----------------------------------------------------------------------------
  2716. void CBaseCombatCharacter::RemoveGlowEffect( void )
  2717. {
  2718. m_bGlowEnabled.Set( false );
  2719. }
  2720. //-----------------------------------------------------------------------------
  2721. // Purpose:
  2722. //-----------------------------------------------------------------------------
  2723. bool CBaseCombatCharacter::IsGlowEffectActive( void )
  2724. {
  2725. return m_bGlowEnabled;
  2726. }
  2727. #endif // GLOWS_ENABLE
  2728. //-----------------------------------------------------------------------------
  2729. // Assume everyone is average with every weapon. Override this to make exceptions.
  2730. //-----------------------------------------------------------------------------
  2731. WeaponProficiency_t CBaseCombatCharacter::CalcWeaponProficiency( CBaseCombatWeapon *pWeapon )
  2732. {
  2733. return WEAPON_PROFICIENCY_AVERAGE;
  2734. }
  2735. //-----------------------------------------------------------------------------
  2736. // Purpose:
  2737. //-----------------------------------------------------------------------------
  2738. #define MAX_MISS_CANDIDATES 16
  2739. CBaseEntity *CBaseCombatCharacter::FindMissTarget( void )
  2740. {
  2741. CBaseEntity *pMissCandidates[ MAX_MISS_CANDIDATES ];
  2742. int numMissCandidates = 0;
  2743. CBasePlayer *pPlayer = UTIL_GetLocalPlayer();
  2744. CBaseEntity *pEnts[256];
  2745. Vector radius( 100, 100, 100);
  2746. Vector vecSource = GetAbsOrigin();
  2747. int numEnts = UTIL_EntitiesInBox( pEnts, 256, vecSource-radius, vecSource+radius, 0 );
  2748. for ( int i = 0; i < numEnts; i++ )
  2749. {
  2750. if ( pEnts[i] == NULL )
  2751. continue;
  2752. // New rule for this system. Don't shoot what the player won't see.
  2753. if ( pPlayer && !pPlayer->FInViewCone( pEnts[ i ] ) )
  2754. continue;
  2755. if ( numMissCandidates >= MAX_MISS_CANDIDATES )
  2756. break;
  2757. //See if it's a good target candidate
  2758. if ( FClassnameIs( pEnts[i], "prop_dynamic" ) ||
  2759. FClassnameIs( pEnts[i], "prop_physics" ) ||
  2760. FClassnameIs( pEnts[i], "physics_prop" ) )
  2761. {
  2762. pMissCandidates[numMissCandidates++] = pEnts[i];
  2763. continue;
  2764. }
  2765. }
  2766. if( numMissCandidates == 0 )
  2767. return NULL;
  2768. return pMissCandidates[ random->RandomInt( 0, numMissCandidates - 1 ) ];
  2769. }
  2770. //-----------------------------------------------------------------------------
  2771. //-----------------------------------------------------------------------------
  2772. bool CBaseCombatCharacter::ShouldShootMissTarget( CBaseCombatCharacter *pAttacker )
  2773. {
  2774. // Don't shoot at NPC's right now.
  2775. return false;
  2776. }
  2777. //-----------------------------------------------------------------------------
  2778. //-----------------------------------------------------------------------------
  2779. void CBaseCombatCharacter::InputKilledNPC( inputdata_t &inputdata )
  2780. {
  2781. OnKilledNPC( inputdata.pActivator ? inputdata.pActivator->MyCombatCharacterPointer() : NULL );
  2782. }
  2783. //-----------------------------------------------------------------------------
  2784. // Purpose: Overload our muzzle flash and send it to any actively held weapon
  2785. //-----------------------------------------------------------------------------
  2786. void CBaseCombatCharacter::DoMuzzleFlash()
  2787. {
  2788. // Our weapon takes our muzzle flash command
  2789. CBaseCombatWeapon *pWeapon = GetActiveWeapon();
  2790. if ( pWeapon )
  2791. {
  2792. pWeapon->DoMuzzleFlash();
  2793. //NOTENOTE: We do not chain to the base here
  2794. }
  2795. else
  2796. {
  2797. BaseClass::DoMuzzleFlash();
  2798. }
  2799. }
  2800. //-----------------------------------------------------------------------------
  2801. // Purpose: return true if given target cant be seen because of fog
  2802. //-----------------------------------------------------------------------------
  2803. bool CBaseCombatCharacter::IsHiddenByFog( const Vector &target ) const
  2804. {
  2805. float range = EyePosition().DistTo( target );
  2806. return IsHiddenByFog( range );
  2807. }
  2808. //-----------------------------------------------------------------------------
  2809. // Purpose: return true if given target cant be seen because of fog
  2810. //-----------------------------------------------------------------------------
  2811. bool CBaseCombatCharacter::IsHiddenByFog( CBaseEntity *target ) const
  2812. {
  2813. if ( !target )
  2814. return false;
  2815. float range = EyePosition().DistTo( target->WorldSpaceCenter() );
  2816. return IsHiddenByFog( range );
  2817. }
  2818. //-----------------------------------------------------------------------------
  2819. // Purpose: return true if given target cant be seen because of fog
  2820. //-----------------------------------------------------------------------------
  2821. bool CBaseCombatCharacter::IsHiddenByFog( float range ) const
  2822. {
  2823. if ( GetFogObscuredRatio( range ) >= 1.0f )
  2824. return true;
  2825. return false;
  2826. }
  2827. //-----------------------------------------------------------------------------
  2828. // Purpose: return 0-1 ratio where zero is not obscured, and 1 is completely obscured
  2829. //-----------------------------------------------------------------------------
  2830. float CBaseCombatCharacter::GetFogObscuredRatio( const Vector &target ) const
  2831. {
  2832. float range = EyePosition().DistTo( target );
  2833. return GetFogObscuredRatio( range );
  2834. }
  2835. //-----------------------------------------------------------------------------
  2836. // Purpose: return 0-1 ratio where zero is not obscured, and 1 is completely obscured
  2837. //-----------------------------------------------------------------------------
  2838. float CBaseCombatCharacter::GetFogObscuredRatio( CBaseEntity *target ) const
  2839. {
  2840. if ( !target )
  2841. return false;
  2842. float range = EyePosition().DistTo( target->WorldSpaceCenter() );
  2843. return GetFogObscuredRatio( range );
  2844. }
  2845. //-----------------------------------------------------------------------------
  2846. // Purpose: return 0-1 ratio where zero is not obscured, and 1 is completely obscured
  2847. //-----------------------------------------------------------------------------
  2848. float CBaseCombatCharacter::GetFogObscuredRatio( float range ) const
  2849. {
  2850. /* TODO: Get global fog from map somehow since nav mesh fog is gone
  2851. fogparams_t fog;
  2852. GetFogParams( &fog );
  2853. if ( !fog.enable )
  2854. return 0.0f;
  2855. if ( range <= fog.start )
  2856. return 0.0f;
  2857. if ( range >= fog.end )
  2858. return 1.0f;
  2859. float ratio = (range - fog.start) / (fog.end - fog.start);
  2860. ratio = MIN( ratio, fog.maxdensity );
  2861. return ratio;
  2862. */
  2863. return 0.0f;
  2864. }
  2865. //-----------------------------------------------------------------------------
  2866. // Purpose: Invoke this to update our last known nav area
  2867. // (since there is no think method chained to CBaseCombatCharacter)
  2868. //-----------------------------------------------------------------------------
  2869. void CBaseCombatCharacter::UpdateLastKnownArea( void )
  2870. {
  2871. #ifdef NEXT_BOT
  2872. if ( TheNavMesh->IsGenerating() )
  2873. {
  2874. ClearLastKnownArea();
  2875. return;
  2876. }
  2877. if ( nb_last_area_update_tolerance.GetFloat() > 0.0f )
  2878. {
  2879. // skip this test if we're not standing on the world (ie: elevators that move us)
  2880. if ( GetGroundEntity() == NULL || GetGroundEntity()->IsWorld() )
  2881. {
  2882. if ( m_lastNavArea && m_NavAreaUpdateMonitor.IsMarkSet() && !m_NavAreaUpdateMonitor.TargetMoved( this ) )
  2883. return;
  2884. m_NavAreaUpdateMonitor.SetMark( this, nb_last_area_update_tolerance.GetFloat() );
  2885. }
  2886. }
  2887. // find the area we are directly standing in
  2888. CNavArea *area = TheNavMesh->GetNearestNavArea( this, GETNAVAREA_CHECK_GROUND | GETNAVAREA_CHECK_LOS, 50.0f );
  2889. if ( !area )
  2890. return;
  2891. // make sure we can actually use this area - if not, consider ourselves off the mesh
  2892. if ( !IsAreaTraversable( area ) )
  2893. return;
  2894. if ( area != m_lastNavArea )
  2895. {
  2896. // player entered a new nav area
  2897. if ( m_lastNavArea )
  2898. {
  2899. m_lastNavArea->DecrementPlayerCount( m_registeredNavTeam, entindex() );
  2900. m_lastNavArea->OnExit( this, area );
  2901. }
  2902. m_registeredNavTeam = GetTeamNumber();
  2903. area->IncrementPlayerCount( m_registeredNavTeam, entindex() );
  2904. area->OnEnter( this, m_lastNavArea );
  2905. OnNavAreaChanged( area, m_lastNavArea );
  2906. m_lastNavArea = area;
  2907. }
  2908. #endif
  2909. }
  2910. //-----------------------------------------------------------------------------
  2911. // Purpose: Return true if we can use (walk through) the given area
  2912. //-----------------------------------------------------------------------------
  2913. bool CBaseCombatCharacter::IsAreaTraversable( const CNavArea *area ) const
  2914. {
  2915. return area ? !area->IsBlocked( GetTeamNumber() ) : false;
  2916. }
  2917. //-----------------------------------------------------------------------------
  2918. // Purpose: Leaving the nav mesh
  2919. //-----------------------------------------------------------------------------
  2920. void CBaseCombatCharacter::ClearLastKnownArea( void )
  2921. {
  2922. OnNavAreaChanged( NULL, m_lastNavArea );
  2923. if ( m_lastNavArea )
  2924. {
  2925. m_lastNavArea->DecrementPlayerCount( m_registeredNavTeam, entindex() );
  2926. m_lastNavArea->OnExit( this, NULL );
  2927. m_lastNavArea = NULL;
  2928. m_registeredNavTeam = TEAM_INVALID;
  2929. }
  2930. }
  2931. //-----------------------------------------------------------------------------
  2932. // Purpose: Handling editor removing the area we're standing upon
  2933. //-----------------------------------------------------------------------------
  2934. void CBaseCombatCharacter::OnNavAreaRemoved( CNavArea *removedArea )
  2935. {
  2936. if ( m_lastNavArea == removedArea )
  2937. {
  2938. ClearLastKnownArea();
  2939. }
  2940. }
  2941. //-----------------------------------------------------------------------------
  2942. // Purpose: Changing team, maintain associated data
  2943. //-----------------------------------------------------------------------------
  2944. void CBaseCombatCharacter::ChangeTeam( int iTeamNum )
  2945. {
  2946. // old team member no longer in the nav mesh
  2947. ClearLastKnownArea();
  2948. #ifdef GLOWS_ENABLE
  2949. RemoveGlowEffect();
  2950. #endif // GLOWS_ENABLE
  2951. BaseClass::ChangeTeam( iTeamNum );
  2952. }
  2953. //-----------------------------------------------------------------------------
  2954. // Return true if we have ever been injured by a member of the given team
  2955. //-----------------------------------------------------------------------------
  2956. bool CBaseCombatCharacter::HasEverBeenInjured( int team /*= TEAM_ANY */ ) const
  2957. {
  2958. if ( team == TEAM_ANY )
  2959. {
  2960. return ( m_hasBeenInjured == 0 ) ? false : true;
  2961. }
  2962. int teamMask = 1 << team;
  2963. if ( m_hasBeenInjured & teamMask )
  2964. {
  2965. return true;
  2966. }
  2967. return false;
  2968. }
  2969. //-----------------------------------------------------------------------------
  2970. // Return time since we were hurt by a member of the given team
  2971. //-----------------------------------------------------------------------------
  2972. float CBaseCombatCharacter::GetTimeSinceLastInjury( int team /*= TEAM_ANY */ ) const
  2973. {
  2974. const float never = 999999999999.9f;
  2975. if ( team == TEAM_ANY )
  2976. {
  2977. float time = never;
  2978. // find most recent injury time
  2979. for( int i=0; i<MAX_DAMAGE_TEAMS; ++i )
  2980. {
  2981. if ( m_damageHistory[i].team != TEAM_INVALID )
  2982. {
  2983. if ( m_damageHistory[i].interval.GetElapsedTime() < time )
  2984. {
  2985. time = m_damageHistory[i].interval.GetElapsedTime();
  2986. }
  2987. }
  2988. }
  2989. return time;
  2990. }
  2991. else
  2992. {
  2993. for( int i=0; i<MAX_DAMAGE_TEAMS; ++i )
  2994. {
  2995. if ( m_damageHistory[i].team == team )
  2996. {
  2997. return m_damageHistory[i].interval.GetElapsedTime();
  2998. }
  2999. }
  3000. }
  3001. return never;
  3002. }