-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathphysics.cpp
2933 lines (2526 loc) · 83.9 KB
/
physics.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Interface layer for ipion IVP physics.
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//===========================================================================//
#include "cbase.h"
#include "coordsize.h"
#include "entitylist.h"
#include "vcollide_parse.h"
#include "soundenvelope.h"
#include "game.h"
#include "utlvector.h"
#include "init_factory.h"
#include "igamesystem.h"
#include "hierarchy.h"
#include "IEffects.h"
#include "engine/IEngineSound.h"
#include "world.h"
#include "decals.h"
#include "physics_fx.h"
#include "vphysics_sound.h"
#include "vphysics/vehicles.h"
#include "vehicle_sounds.h"
#include "movevars_shared.h"
#include "physics_saverestore.h"
#include "solidsetdefaults.h"
#include "tier0/vprof.h"
#include "engine/IStaticPropMgr.h"
#include "physics_prop_ragdoll.h"
#if HL2_EPISODIC
#include "particle_parse.h"
#endif
#include "vphysics/object_hash.h"
#include "vphysics/collision_set.h"
#include "vphysics/friction.h"
#include "fmtstr.h"
#include "physics_npc_solver.h"
#include "physics_collisionevent.h"
#include "vphysics/performance.h"
#include "positionwatcher.h"
#include "tier1/callqueue.h"
#include "vphysics/constraints.h"
#ifdef PORTAL
#include "portal_physics_collisionevent.h"
#include "physicsshadowclone.h"
#include "PortalSimulation.h"
void PortalPhysFrame( float deltaTime ); //small wrapper for PhysFrame that simulates all 3 environments at once
#endif
void PrecachePhysicsSounds( void );
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ConVar phys_speeds( "phys_speeds", "0" );
// defined in phys_constraint
extern IPhysicsConstraintEvent *g_pConstraintEvents;
CEntityList *g_pShadowEntities = NULL;
#ifdef PORTAL
CEntityList *g_pShadowEntities_Main = NULL;
#endif
// local variables
static float g_PhysAverageSimTime;
CCallQueue g_PostSimulationQueue;
// local routines
static IPhysicsObject *PhysCreateWorld( CBaseEntity *pWorld );
static void PhysFrame( float deltaTime );
static bool IsDebris( int collisionGroup );
void TimescaleChanged( IConVar *var, const char *pOldString, float flOldValue )
{
if ( physenv )
{
physenv->ResetSimulationClock();
}
}
ConVar phys_timescale( "phys_timescale", "1", 0, "Scale time for physics", TimescaleChanged );
#if _DEBUG
ConVar phys_dontprintint( "phys_dontprintint", "1", FCVAR_NONE, "Don't print inter-penetration warnings." );
#endif
#ifdef PORTAL
CPortal_CollisionEvent g_Collisions;
#else
CCollisionEvent g_Collisions;
#endif
IPhysicsCollisionSolver * const g_pCollisionSolver = &g_Collisions;
IPhysicsCollisionEvent * const g_pCollisionEventHandler = &g_Collisions;
IPhysicsObjectEvent * const g_pObjectEventHandler = &g_Collisions;
struct vehiclescript_t
{
string_t scriptName;
vehicleparams_t params;
vehiclesounds_t sounds;
};
class CPhysicsHook : public CBaseGameSystemPerFrame
{
public:
virtual const char *Name() { return "CPhysicsHook"; }
virtual bool Init();
virtual void LevelInitPreEntity();
virtual void LevelInitPostEntity();
virtual void LevelShutdownPreEntity();
virtual void LevelShutdownPostEntity();
virtual void FrameUpdatePostEntityThink();
virtual void PreClientUpdate();
bool FindOrAddVehicleScript( const char *pScriptName, vehicleparams_t *pVehicle, vehiclesounds_t *pSounds );
void FlushVehicleScripts()
{
m_vehicleScripts.RemoveAll();
}
bool ShouldSimulate()
{
return (physenv && !m_bPaused) ? true : false;
}
physicssound::soundlist_t m_impactSounds;
CUtlVector<physicssound::breaksound_t> m_breakSounds;
CUtlVector<masscenteroverride_t> m_massCenterOverrides;
CUtlVector<vehiclescript_t> m_vehicleScripts;
float m_impactSoundTime;
bool m_bPaused;
bool m_isFinalTick;
};
CPhysicsHook g_PhysicsHook;
//-----------------------------------------------------------------------------
// Singleton access
//-----------------------------------------------------------------------------
IGameSystem* PhysicsGameSystem()
{
return &g_PhysicsHook;
}
//-----------------------------------------------------------------------------
// Purpose: The physics hook callback implementations
//-----------------------------------------------------------------------------
bool CPhysicsHook::Init( void )
{
factorylist_t factories;
// Get the list of interface factories to extract the physics DLL's factory
FactoryList_Retrieve( factories );
if ( !factories.physicsFactory )
return false;
if ((physics = (IPhysics *)factories.physicsFactory( VPHYSICS_INTERFACE_VERSION, NULL )) == NULL ||
(physcollision = (IPhysicsCollision *)factories.physicsFactory( VPHYSICS_COLLISION_INTERFACE_VERSION, NULL )) == NULL ||
(physprops = (IPhysicsSurfaceProps *)factories.physicsFactory( VPHYSICS_SURFACEPROPS_INTERFACE_VERSION, NULL )) == NULL
)
return false;
PhysParseSurfaceData( physprops, filesystem );
m_isFinalTick = true;
m_impactSoundTime = 0;
m_vehicleScripts.EnsureCapacity(4);
return true;
}
// a little debug wrapper to help fix bugs when entity pointers get trashed
#if 0
struct physcheck_t
{
IPhysicsObject *pPhys;
char string[512];
};
CUtlVector< physcheck_t > physCheck;
void PhysCheckAdd( IPhysicsObject *pPhys, const char *pString )
{
physcheck_t tmp;
tmp.pPhys = pPhys;
Q_strncpy( tmp.string, pString ,sizeof(tmp.string));
physCheck.AddToTail( tmp );
}
const char *PhysCheck( IPhysicsObject *pPhys )
{
for ( int i = 0; i < physCheck.Size(); i++ )
{
if ( physCheck[i].pPhys == pPhys )
return physCheck[i].string;
}
return "unknown";
}
#endif
void CPhysicsHook::LevelInitPreEntity()
{
physenv = physics->CreateEnvironment();
physics_performanceparams_t params;
params.Defaults();
params.maxCollisionsPerObjectPerTimestep = 10;
physenv->SetPerformanceSettings( ¶ms );
#ifdef PORTAL
physenv_main = physenv;
#endif
{
g_EntityCollisionHash = physics->CreateObjectPairHash();
}
factorylist_t factories;
FactoryList_Retrieve( factories );
physenv->SetDebugOverlay( factories.engineFactory );
physenv->EnableDeleteQueue( true );
physenv->SetCollisionSolver( &g_Collisions );
physenv->SetCollisionEventHandler( &g_Collisions );
physenv->SetConstraintEventHandler( g_pConstraintEvents );
physenv->EnableConstraintNotify( true ); // callback when an object gets deleted that is attached to a constraint
physenv->SetObjectEventHandler( &g_Collisions );
physenv->SetSimulationTimestep( DEFAULT_TICK_INTERVAL ); // 15 ms per tick
// HL Game gravity, not real-world gravity
physenv->SetGravity( Vector( 0, 0, -GetCurrentGravity() ) );
g_PhysAverageSimTime = 0;
g_PhysWorldObject = PhysCreateWorld( GetWorldEntity() );
g_pShadowEntities = new CEntityList;
#ifdef PORTAL
g_pShadowEntities_Main = g_pShadowEntities;
#endif
PrecachePhysicsSounds();
m_bPaused = true;
}
void CPhysicsHook::LevelInitPostEntity()
{
m_bPaused = false;
}
void CPhysicsHook::LevelShutdownPreEntity()
{
if ( !physenv )
return;
physenv->SetQuickDelete( true );
}
void CPhysicsHook::LevelShutdownPostEntity()
{
if ( !physenv )
return;
g_pPhysSaveRestoreManager->ForgetAllModels();
g_Collisions.LevelShutdown();
physics->DestroyEnvironment( physenv );
physenv = NULL;
physics->DestroyObjectPairHash( g_EntityCollisionHash );
g_EntityCollisionHash = NULL;
physics->DestroyAllCollisionSets();
g_PhysWorldObject = NULL;
delete g_pShadowEntities;
g_pShadowEntities = NULL;
m_impactSounds.RemoveAll();
m_breakSounds.RemoveAll();
m_massCenterOverrides.Purge();
FlushVehicleScripts();
}
bool CPhysicsHook::FindOrAddVehicleScript( const char *pScriptName, vehicleparams_t *pVehicle, vehiclesounds_t *pSounds )
{
bool bLoadedSounds = false;
int index = -1;
for ( int i = 0; i < m_vehicleScripts.Count(); i++ )
{
if ( !Q_stricmp(m_vehicleScripts[i].scriptName.ToCStr(), pScriptName) )
{
index = i;
bLoadedSounds = true;
break;
}
}
if ( index < 0 )
{
byte *pFile = UTIL_LoadFileForMe( pScriptName, NULL );
if ( pFile )
{
// new script, parse it and write to the table
index = m_vehicleScripts.AddToTail();
m_vehicleScripts[index].scriptName = AllocPooledString(pScriptName);
m_vehicleScripts[index].sounds.Init();
IVPhysicsKeyParser *pParse = physcollision->VPhysicsKeyParserCreate( (char *)pFile );
while ( !pParse->Finished() )
{
const char *pBlock = pParse->GetCurrentBlockName();
if ( !strcmpi( pBlock, "vehicle" ) )
{
pParse->ParseVehicle( &m_vehicleScripts[index].params, NULL );
}
else if ( !Q_stricmp( pBlock, "vehicle_sounds" ) )
{
bLoadedSounds = true;
CVehicleSoundsParser soundParser;
pParse->ParseCustom( &m_vehicleScripts[index].sounds, &soundParser );
}
else
{
pParse->SkipBlock();
}
}
physcollision->VPhysicsKeyParserDestroy( pParse );
UTIL_FreeFile( pFile );
}
}
if ( index >= 0 )
{
if ( pVehicle )
{
*pVehicle = m_vehicleScripts[index].params;
}
if ( pSounds )
{
// We must pass back valid data here!
if ( bLoadedSounds == false )
return false;
*pSounds = m_vehicleScripts[index].sounds;
}
return true;
}
return false;
}
// called after entities think
void CPhysicsHook::FrameUpdatePostEntityThink( )
{
VPROF_BUDGET( "CPhysicsHook::FrameUpdatePostEntityThink", VPROF_BUDGETGROUP_PHYSICS );
// Tracker 24846: If game is paused, don't simulate vphysics
float interval = ( gpGlobals->frametime > 0.0f ) ? TICK_INTERVAL : 0.0f;
// update the physics simulation, not we don't use gpGlobals->frametime, since that can be 30 msec or 15 msec
// depending on whether IsSimulatingOnAlternateTicks is true or not
if ( CBaseEntity::IsSimulatingOnAlternateTicks() )
{
m_isFinalTick = false;
#ifdef PORTAL //slight detour if we're the portal mod
PortalPhysFrame( interval );
#else
PhysFrame( interval );
#endif
}
m_isFinalTick = true;
#ifdef PORTAL //slight detour if we're the portal mod
PortalPhysFrame( interval );
#else
PhysFrame( interval );
#endif
}
void CPhysicsHook::PreClientUpdate()
{
m_impactSoundTime += gpGlobals->frametime;
if ( m_impactSoundTime > 0.05f )
{
physicssound::PlayImpactSounds( m_impactSounds );
m_impactSoundTime = 0.0f;
physicssound::PlayBreakSounds( m_breakSounds );
}
}
bool PhysIsFinalTick()
{
return g_PhysicsHook.m_isFinalTick;
}
IPhysicsObject *PhysCreateWorld( CBaseEntity *pWorld )
{
staticpropmgr->CreateVPhysicsRepresentations( physenv, &g_SolidSetup, pWorld );
return PhysCreateWorld_Shared( pWorld, modelinfo->GetVCollide(1), g_PhysDefaultObjectParams );
}
// vehicle wheels can only collide with things that can't get stuck in them during game physics
// because they aren't in the game physics world at present
static bool WheelCollidesWith( IPhysicsObject *pObj, CBaseEntity *pEntity )
{
#if defined( INVASION_DLL )
if ( pEntity->GetCollisionGroup() == TFCOLLISION_GROUP_OBJECT )
return false;
#endif
// Cull against interactive debris
if ( pEntity->GetCollisionGroup() == COLLISION_GROUP_INTERACTIVE_DEBRIS )
return false;
// Hit physics ents
if ( pEntity->GetMoveType() == MOVETYPE_PUSH || pEntity->GetMoveType() == MOVETYPE_VPHYSICS || pObj->IsStatic() )
return true;
return false;
}
CCollisionEvent::CCollisionEvent()
{
m_inCallback = 0;
m_bBufferTouchEvents = false;
m_lastTickFrictionError = 0;
}
int CCollisionEvent::ShouldCollide( IPhysicsObject *pObj0, IPhysicsObject *pObj1, void *pGameData0, void *pGameData1 )
#if _DEBUG
{
int x0 = ShouldCollide_2(pObj0, pObj1, pGameData0, pGameData1);
int x1 = ShouldCollide_2(pObj1, pObj0, pGameData1, pGameData0);
Assert(x0==x1);
return x0;
}
int CCollisionEvent::ShouldCollide_2( IPhysicsObject *pObj0, IPhysicsObject *pObj1, void *pGameData0, void *pGameData1 )
#endif
{
CallbackContext check(this);
CBaseEntity *pEntity0 = static_cast<CBaseEntity *>(pGameData0);
CBaseEntity *pEntity1 = static_cast<CBaseEntity *>(pGameData1);
if ( !pEntity0 || !pEntity1 )
return 1;
unsigned short gameFlags0 = pObj0->GetGameFlags();
unsigned short gameFlags1 = pObj1->GetGameFlags();
if ( pEntity0 == pEntity1 )
{
// allow all-or-nothing per-entity disable
if ( (gameFlags0 | gameFlags1) & FVPHYSICS_NO_SELF_COLLISIONS )
return 0;
IPhysicsCollisionSet *pSet = physics->FindCollisionSet( pEntity0->GetModelIndex() );
if ( pSet )
return pSet->ShouldCollide( pObj0->GetGameIndex(), pObj1->GetGameIndex() );
return 1;
}
// objects that are both constrained to the world don't collide with each other
if ( (gameFlags0 & gameFlags1) & FVPHYSICS_CONSTRAINT_STATIC )
{
return 0;
}
// Special collision rules for vehicle wheels
// Their entity collides with stuff using the normal rules, but they
// have different rules than the vehicle body for various reasons.
// sort of a hack because we don't have spheres to represent them in the game
// world for speculative collisions.
if ( pObj0->GetCallbackFlags() & CALLBACK_IS_VEHICLE_WHEEL )
{
if ( !WheelCollidesWith( pObj1, pEntity1 ) )
return false;
}
if ( pObj1->GetCallbackFlags() & CALLBACK_IS_VEHICLE_WHEEL )
{
if ( !WheelCollidesWith( pObj0, pEntity0 ) )
return false;
}
if ( pEntity0->ForceVPhysicsCollide( pEntity1 ) || pEntity1->ForceVPhysicsCollide( pEntity0 ) )
return 1;
if ( pEntity0->edict() && pEntity1->edict() )
{
// don't collide with your owner
if ( pEntity0->GetOwnerEntity() == pEntity1 || pEntity1->GetOwnerEntity() == pEntity0 )
return 0;
}
if ( pEntity0->GetMoveParent() || pEntity1->GetMoveParent() )
{
CBaseEntity *pParent0 = pEntity0->GetRootMoveParent();
CBaseEntity *pParent1 = pEntity1->GetRootMoveParent();
// NOTE: Don't let siblings/parents collide. If you want this behavior, do it
// with constraints, not hierarchy!
if ( pParent0 == pParent1 )
return 0;
if ( g_EntityCollisionHash->IsObjectPairInHash( pParent0, pParent1 ) )
return 0;
IPhysicsObject *p0 = pParent0->VPhysicsGetObject();
IPhysicsObject *p1 = pParent1->VPhysicsGetObject();
if ( p0 && p1 )
{
if ( g_EntityCollisionHash->IsObjectPairInHash( p0, p1 ) )
return 0;
}
}
int solid0 = pEntity0->GetSolid();
int solid1 = pEntity1->GetSolid();
int nSolidFlags0 = pEntity0->GetSolidFlags();
int nSolidFlags1 = pEntity1->GetSolidFlags();
int movetype0 = pEntity0->GetMoveType();
int movetype1 = pEntity1->GetMoveType();
// entities with non-physical move parents or entities with MOVETYPE_PUSH
// are considered as "AI movers". They are unchanged by collision; they exert
// physics forces on the rest of the system.
bool aiMove0 = (movetype0==MOVETYPE_PUSH) ? true : false;
bool aiMove1 = (movetype1==MOVETYPE_PUSH) ? true : false;
if ( pEntity0->GetMoveParent() )
{
// if the object & its parent are both MOVETYPE_VPHYSICS, then this must be a special case
// like a prop_ragdoll_attached
if ( !(movetype0 == MOVETYPE_VPHYSICS && pEntity0->GetRootMoveParent()->GetMoveType() == MOVETYPE_VPHYSICS) )
{
aiMove0 = true;
}
}
if ( pEntity1->GetMoveParent() )
{
// if the object & its parent are both MOVETYPE_VPHYSICS, then this must be a special case.
if ( !(movetype1 == MOVETYPE_VPHYSICS && pEntity1->GetRootMoveParent()->GetMoveType() == MOVETYPE_VPHYSICS) )
{
aiMove1 = true;
}
}
// AI movers don't collide with the world/static/pinned objects or other AI movers
if ( (aiMove0 && !pObj1->IsMoveable()) ||
(aiMove1 && !pObj0->IsMoveable()) ||
(aiMove0 && aiMove1) )
return 0;
// two objects under shadow control should not collide. The AI will figure it out
if ( pObj0->GetShadowController() && pObj1->GetShadowController() )
return 0;
// BRJ 1/24/03
// You can remove the assert if it's problematic; I *believe* this condition
// should be met, but I'm not sure.
//Assert ( (solid0 != SOLID_NONE) && (solid1 != SOLID_NONE) );
if ( (solid0 == SOLID_NONE) || (solid1 == SOLID_NONE) )
return 0;
// not solid doesn't collide with anything
if ( (nSolidFlags0|nSolidFlags1) & FSOLID_NOT_SOLID )
{
// might be a vphysics trigger, collide with everything but "not solid"
if ( pObj0->IsTrigger() && !(nSolidFlags1 & FSOLID_NOT_SOLID) )
return 1;
if ( pObj1->IsTrigger() && !(nSolidFlags0 & FSOLID_NOT_SOLID) )
return 1;
return 0;
}
if ( (nSolidFlags0 & FSOLID_TRIGGER) &&
!(solid1 == SOLID_VPHYSICS || solid1 == SOLID_BSP || movetype1 == MOVETYPE_VPHYSICS) )
return 0;
if ( (nSolidFlags1 & FSOLID_TRIGGER) &&
!(solid0 == SOLID_VPHYSICS || solid0 == SOLID_BSP || movetype0 == MOVETYPE_VPHYSICS) )
return 0;
if ( !g_pGameRules->ShouldCollide( pEntity0->GetCollisionGroup(), pEntity1->GetCollisionGroup() ) )
return 0;
// check contents
if ( !(pObj0->GetContents() & pEntity1->PhysicsSolidMaskForEntity()) || !(pObj1->GetContents() & pEntity0->PhysicsSolidMaskForEntity()) )
return 0;
if ( g_EntityCollisionHash->IsObjectPairInHash( pGameData0, pGameData1 ) )
return 0;
if ( g_EntityCollisionHash->IsObjectPairInHash( pObj0, pObj1 ) )
return 0;
return 1;
}
bool FindMaxContact( IPhysicsObject *pObject, float minForce, IPhysicsObject **pOtherObject, Vector *contactPos, Vector *pForce )
{
float mass = pObject->GetMass();
float maxForce = minForce;
*pOtherObject = NULL;
IPhysicsFrictionSnapshot *pSnapshot = pObject->CreateFrictionSnapshot();
while ( pSnapshot->IsValid() )
{
IPhysicsObject *pOther = pSnapshot->GetObject(1);
if ( pOther->IsMoveable() && pOther->GetMass() > mass )
{
float force = pSnapshot->GetNormalForce();
if ( force > maxForce )
{
*pOtherObject = pOther;
pSnapshot->GetContactPoint( *contactPos );
pSnapshot->GetSurfaceNormal( *pForce );
*pForce *= force;
}
}
pSnapshot->NextFrictionData();
}
pObject->DestroyFrictionSnapshot( pSnapshot );
if ( *pOtherObject )
return true;
return false;
}
bool CCollisionEvent::ShouldFreezeObject( IPhysicsObject *pObject )
{
extern bool PropIsGib(CBaseEntity *pEntity);
// for now, don't apply a per-object limit to ai MOVETYPE_PUSH objects
// NOTE: If this becomes a problem (too many collision checks this tick) we should add a path
// to inform the logic in VPhysicsUpdatePusher() about the limit being applied so
// that it doesn't falsely block the object when it's simply been temporarily frozen
// for performance reasons
CBaseEntity *pEntity = static_cast<CBaseEntity *>(pObject->GetGameData());
if ( pEntity )
{
if (pEntity->GetMoveType() == MOVETYPE_PUSH )
return false;
// don't limit vehicle collisions either, limit can make breaking through a pile of breakable
// props very hitchy
if (pEntity->GetServerVehicle() && !(pObject->GetCallbackFlags() & CALLBACK_IS_VEHICLE_WHEEL))
return false;
}
// if we're freezing a debris object, then it's probably due to some kind of solver issue
// usually this is a large object resting on the debris object in question which is not
// very stable.
// After doing the experiment of constraining the dynamic range of mass while solving friction
// contacts, I like the results of this tradeoff better. So damage or remove the debris object
// wherever possible once we hit this case:
if ( IsDebris( pEntity->GetCollisionGroup()) && !pEntity->IsNPC() )
{
IPhysicsObject *pOtherObject = NULL;
Vector contactPos;
Vector force;
// find the contact with the moveable object applying the most contact force
if ( FindMaxContact( pObject, pObject->GetMass() * 10, &pOtherObject, &contactPos, &force ) )
{
CBaseEntity *pOther = static_cast<CBaseEntity *>(pOtherObject->GetGameData());
// this object can take damage, crush it
if ( pEntity->m_takedamage > DAMAGE_EVENTS_ONLY )
{
CTakeDamageInfo dmgInfo( pOther, pOther, force, contactPos, force.Length() * 0.1f, DMG_CRUSH );
PhysCallbackDamage( pEntity, dmgInfo );
}
else
{
// can't be damaged, so do something else:
if ( PropIsGib(pEntity) )
{
// it's always safe to delete gibs, so kill this one to avoid simulation problems
PhysCallbackRemove( pEntity->NetworkProp() );
}
else
{
// not a gib, create a solver:
// UNDONE: Add a property to override this in gameplay critical scenarios?
g_PostSimulationQueue.QueueCall( EntityPhysics_CreateSolver, pOther, pEntity, true, 1.0f );
}
}
}
}
return true;
}
bool CCollisionEvent::ShouldFreezeContacts( IPhysicsObject **pObjectList, int objectCount )
{
if ( m_lastTickFrictionError > gpGlobals->tickcount || m_lastTickFrictionError < (gpGlobals->tickcount-1) )
{
DevWarning("Performance Warning: large friction system (%d objects)!!!\n", objectCount );
#if _DEBUG
for ( int i = 0; i < objectCount; i++ )
{
CBaseEntity *pEntity = static_cast<CBaseEntity *>(pObjectList[i]->GetGameData());
pEntity->m_debugOverlays |= OVERLAY_ABSBOX_BIT | OVERLAY_PIVOT_BIT;
}
#endif
}
m_lastTickFrictionError = gpGlobals->tickcount;
return false;
}
// NOTE: these are fully edge triggered events
// called when an object wakes up (starts simulating)
void CCollisionEvent::ObjectWake( IPhysicsObject *pObject )
{
CBaseEntity *pEntity = static_cast<CBaseEntity *>(pObject->GetGameData());
if ( pEntity && pEntity->HasDataObjectType( VPHYSICSWATCHER ) )
{
ReportVPhysicsStateChanged( pObject, pEntity, true );
}
}
// called when an object goes to sleep (no longer simulating)
void CCollisionEvent::ObjectSleep( IPhysicsObject *pObject )
{
CBaseEntity *pEntity = static_cast<CBaseEntity *>(pObject->GetGameData());
if ( pEntity && pEntity->HasDataObjectType( VPHYSICSWATCHER ) )
{
ReportVPhysicsStateChanged( pObject, pEntity, false );
}
}
bool PhysShouldCollide( IPhysicsObject *pObj0, IPhysicsObject *pObj1 )
{
void *pGameData0 = pObj0->GetGameData();
void *pGameData1 = pObj1->GetGameData();
if ( !pGameData0 || !pGameData1 )
return false;
return g_Collisions.ShouldCollide( pObj0, pObj1, pGameData0, pGameData1 ) ? true : false;
}
bool PhysIsInCallback()
{
if ( (physenv && physenv->IsInSimulation()) || g_Collisions.IsInCallback() )
return true;
return false;
}
static void ReportPenetration( CBaseEntity *pEntity, float duration )
{
if ( pEntity->GetMoveType() == MOVETYPE_VPHYSICS )
{
if ( g_pDeveloper->GetInt() > 1 )
{
pEntity->m_debugOverlays |= OVERLAY_ABSBOX_BIT;
}
pEntity->AddTimedOverlay( UTIL_VarArgs("VPhysics Penetration Error (%s)!", pEntity->GetDebugName()), duration );
}
}
static bool IsDebris( int collisionGroup )
{
switch ( collisionGroup )
{
case COLLISION_GROUP_DEBRIS:
case COLLISION_GROUP_INTERACTIVE_DEBRIS:
case COLLISION_GROUP_DEBRIS_TRIGGER:
return true;
default:
break;
}
return false;
}
static void UpdateEntityPenetrationFlag( CBaseEntity *pEntity, bool isPenetrating )
{
if ( !pEntity )
return;
IPhysicsObject *pList[VPHYSICS_MAX_OBJECT_LIST_COUNT];
int count = pEntity->VPhysicsGetObjectList( pList, ARRAYSIZE(pList) );
for ( int i = 0; i < count; i++ )
{
if ( !pList[i]->IsStatic() )
{
if ( isPenetrating )
{
PhysSetGameFlags( pList[i], FVPHYSICS_PENETRATING );
}
else
{
PhysClearGameFlags( pList[i], FVPHYSICS_PENETRATING );
}
}
}
}
void CCollisionEvent::GetListOfPenetratingEntities( CBaseEntity *pSearch, CUtlVector<CBaseEntity *> &list )
{
for ( int i = m_penetrateEvents.Count()-1; i >= 0; --i )
{
if ( m_penetrateEvents[i].hEntity0 == pSearch && m_penetrateEvents[i].hEntity1.Get() != NULL )
{
list.AddToTail( m_penetrateEvents[i].hEntity1 );
}
else if ( m_penetrateEvents[i].hEntity1 == pSearch && m_penetrateEvents[i].hEntity0.Get() != NULL )
{
list.AddToTail( m_penetrateEvents[i].hEntity0 );
}
}
}
void CCollisionEvent::UpdatePenetrateEvents( void )
{
for ( int i = m_penetrateEvents.Count()-1; i >= 0; --i )
{
CBaseEntity *pEntity0 = m_penetrateEvents[i].hEntity0;
CBaseEntity *pEntity1 = m_penetrateEvents[i].hEntity1;
if ( m_penetrateEvents[i].collisionState == COLLSTATE_TRYDISABLE )
{
if ( pEntity0 && pEntity1 )
{
IPhysicsObject *pObj0 = pEntity0->VPhysicsGetObject();
if ( pObj0 )
{
PhysForceEntityToSleep( pEntity0, pObj0 );
}
IPhysicsObject *pObj1 = pEntity1->VPhysicsGetObject();
if ( pObj1 )
{
PhysForceEntityToSleep( pEntity1, pObj1 );
}
m_penetrateEvents[i].collisionState = COLLSTATE_DISABLED;
continue;
}
// missing entity or object, clear event
}
else if ( m_penetrateEvents[i].collisionState == COLLSTATE_TRYNPCSOLVER )
{
if ( pEntity0 && pEntity1 )
{
CAI_BaseNPC *pNPC = pEntity0->MyNPCPointer();
CBaseEntity *pBlocker = pEntity1;
if ( !pNPC )
{
pNPC = pEntity1->MyNPCPointer();
Assert(pNPC);
pBlocker = pEntity0;
}
NPCPhysics_CreateSolver( pNPC, pBlocker, true, 1.0f );
}
// transferred to solver, clear event
}
else if ( m_penetrateEvents[i].collisionState == COLLSTATE_TRYENTITYSOLVER )
{
if ( pEntity0 && pEntity1 )
{
if ( !IsDebris(pEntity1->GetCollisionGroup()) || pEntity1->GetMoveType() != MOVETYPE_VPHYSICS )
{
CBaseEntity *pTmp = pEntity0;
pEntity0 = pEntity1;
pEntity1 = pTmp;
}
EntityPhysics_CreateSolver( pEntity0, pEntity1, true, 1.0f );
}
// transferred to solver, clear event
}
else if ( gpGlobals->curtime - m_penetrateEvents[i].timeStamp > 1.0 )
{
if ( m_penetrateEvents[i].collisionState == COLLSTATE_DISABLED )
{
if ( pEntity0 && pEntity1 )
{
IPhysicsObject *pObj0 = pEntity0->VPhysicsGetObject();
IPhysicsObject *pObj1 = pEntity1->VPhysicsGetObject();
if ( pObj0 && pObj1 )
{
m_penetrateEvents[i].collisionState = COLLSTATE_ENABLED;
continue;
}
}
}
// haven't penetrated for 1 second, so remove
}
else
{
// recent timestamp, don't remove the event yet
continue;
}
// done, clear event
m_penetrateEvents.FastRemove(i);
UpdateEntityPenetrationFlag( pEntity0, false );
UpdateEntityPenetrationFlag( pEntity1, false );
}
}
penetrateevent_t &CCollisionEvent::FindOrAddPenetrateEvent( CBaseEntity *pEntity0, CBaseEntity *pEntity1 )
{
int index = -1;
for ( int i = m_penetrateEvents.Count()-1; i >= 0; --i )
{
if ( m_penetrateEvents[i].hEntity0.Get() == pEntity0 && m_penetrateEvents[i].hEntity1.Get() == pEntity1 )
{
index = i;
break;
}
}
if ( index < 0 )
{
index = m_penetrateEvents.AddToTail();
penetrateevent_t &event = m_penetrateEvents[index];
event.hEntity0 = pEntity0;
event.hEntity1 = pEntity1;
event.startTime = gpGlobals->curtime;
event.collisionState = COLLSTATE_ENABLED;
UpdateEntityPenetrationFlag( pEntity0, true );
UpdateEntityPenetrationFlag( pEntity1, true );
}
penetrateevent_t &event = m_penetrateEvents[index];
event.timeStamp = gpGlobals->curtime;
return event;
}
static ConVar phys_penetration_error_time( "phys_penetration_error_time", "10", 0, "Controls the duration of vphysics penetration error boxes." );
static bool CanResolvePenetrationWithNPC( CBaseEntity *pEntity, IPhysicsObject *pObject )
{
if ( pEntity->GetMoveType() == MOVETYPE_VPHYSICS )
{
// hinged objects won't be able to be pushed out anyway, so don't try the npc solver
if ( !pObject->IsHinged() && !pObject->IsAttachedToConstraint(true) )
{
if ( pObject->IsMoveable() || pEntity->GetServerVehicle() )
return true;
}
}
return false;
}
int CCollisionEvent::ShouldSolvePenetration( IPhysicsObject *pObj0, IPhysicsObject *pObj1, void *pGameData0, void *pGameData1, float dt )
{
CallbackContext check(this);
// Pointers to the entity for each physics object
CBaseEntity *pEntity0 = static_cast<CBaseEntity *>(pGameData0);
CBaseEntity *pEntity1 = static_cast<CBaseEntity *>(pGameData1);
// this can get called as entities are being constructed on the other side of a game load or level transition
// Some entities may not be fully constructed, so don't call into their code until the level is running
if ( g_PhysicsHook.m_bPaused )
return true;
// solve it yourself here and return 0, or have the default implementation do it
if ( pEntity0 > pEntity1 )
{
// swap sort
CBaseEntity *pTmp = pEntity0;
pEntity0 = pEntity1;
pEntity1 = pTmp;
IPhysicsObject *pTmpObj = pObj0;
pObj0 = pObj1;
pObj1 = pTmpObj;
}
if ( pEntity0 == pEntity1 )
{
if ( pObj0->GetGameFlags() & FVPHYSICS_PART_OF_RAGDOLL )
{
DevMsg(2, "Solving ragdoll self penetration! %s (%s) (%d v %d)\n", pObj0->GetName(), pEntity0->GetDebugName(), pObj0->GetGameIndex(), pObj1->GetGameIndex() );
ragdoll_t *pRagdoll = Ragdoll_GetRagdoll( pEntity0 );
pRagdoll->pGroup->SolvePenetration( pObj0, pObj1 );
return false;
}
}