-
Notifications
You must be signed in to change notification settings - Fork 12
/
gameinterface.cpp
3535 lines (2950 loc) · 104 KB
/
gameinterface.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: encapsulates and implements all the accessing of the game dll from external
// sources (only the engine at the time of writing)
// This files ONLY contains functions and data necessary to build an interface
// to external modules
//===========================================================================//
#include "cbase.h"
#include "gamestringpool.h"
#include "mapentities_shared.h"
#include "game.h"
#include "entityapi.h"
#include "client.h"
#include "saverestore.h"
#include "entitylist.h"
#include "gamerules.h"
#include "soundent.h"
#include "player.h"
#include "server_class.h"
#include "ai_node.h"
#include "ai_link.h"
#include "ai_saverestore.h"
#include "ai_networkmanager.h"
#include "ndebugoverlay.h"
#include "ivoiceserver.h"
#include <stdarg.h>
#include "movehelper_server.h"
#include "networkstringtable_gamedll.h"
#include "filesystem.h"
#include "func_areaportalwindow.h"
#include "igamesystem.h"
#include "init_factory.h"
#include "vstdlib/random.h"
#include "env_wind_shared.h"
#include "engine/IEngineSound.h"
#include "ispatialpartition.h"
#include "textstatsmgr.h"
#include "bitbuf.h"
#include "saverestoretypes.h"
#include "physics_saverestore.h"
#include "achievement_saverestore.h"
#include "tier0/vprof.h"
#include "effect_dispatch_data.h"
#include "engine/IStaticPropMgr.h"
#include "TemplateEntities.h"
#include "ai_speech.h"
#include "soundenvelope.h"
#include "usermessages.h"
#include "physics.h"
#include "igameevents.h"
#include "EventLog.h"
#include "datacache/idatacache.h"
#include "engine/ivdebugoverlay.h"
#include "shareddefs.h"
#include "props.h"
#include "timedeventmgr.h"
#include "gameinterface.h"
#include "eventqueue.h"
#include "hltvdirector.h"
#if defined( REPLAY_ENABLED )
#include "replay/iserverreplaycontext.h"
#endif
#include "SoundEmitterSystem/isoundemittersystembase.h"
#include "AI_ResponseSystem.h"
#include "saverestore_stringtable.h"
#include "util.h"
#include "tier0/icommandline.h"
#include "datacache/imdlcache.h"
#include "engine/iserverplugin.h"
#ifdef _WIN32
#include "ienginevgui.h"
#endif
#include "ragdoll_shared.h"
#include "toolframework/iserverenginetools.h"
#include "sceneentity.h"
#include "appframework/IAppSystemGroup.h"
#include "scenefilecache/ISceneFileCache.h"
#include "tier2/tier2.h"
#include "particles/particles.h"
#include "gamestats.h"
#include "ixboxsystem.h"
#include "engine/imatchmaking.h"
#include "hl2orange.spa.h"
#include "particle_parse.h"
#ifndef NO_STEAM
#include "steam/steam_gameserver.h"
#endif
#include "tier3/tier3.h"
#include "serverbenchmark_base.h"
#include "querycache.h"
#ifdef TF_DLL
#include "gc_clientsystem.h"
#include "econ_item_inventory.h"
#include "steamworks_gamestats.h"
#include "tf/tf_gc_server.h"
#include "tf_gamerules.h"
#include "tf_lobby.h"
#include "player_vs_environment/tf_population_manager.h"
#include "workshop/maps_workshop.h"
extern ConVar tf_mm_trusted;
extern ConVar tf_mm_servermode;
#endif
#ifdef USE_NAV_MESH
#include "nav_mesh.h"
#endif
#ifdef NEXT_BOT
#include "NextBotManager.h"
#endif
#ifdef USES_ECON_ITEMS
#include "econ_item_system.h"
#endif // USES_ECON_ITEMS
#ifdef CSTRIKE_DLL // BOTPORT: TODO: move these ifdefs out
#include "bot/bot.h"
#endif
#ifdef PORTAL
#include "prop_portal_shared.h"
#include "portal_player.h"
#endif
#if defined( REPLAY_ENABLED )
#include "replay/ireplaysystem.h"
#endif
#ifdef NEO
#include "neo_mount_original.h"
#include "neo_version.h"
#include "neo_player_shared.h"
#endif
extern IToolFrameworkServer *g_pToolFrameworkServer;
extern IParticleSystemQuery *g_pParticleSystemQuery;
extern ConVar commentary;
#ifndef NO_STEAM
// this context is not available on dedicated servers
// WARNING! always check if interfaces are available before using
static CSteamAPIContext s_SteamAPIContext;
CSteamAPIContext *steamapicontext = &s_SteamAPIContext;
// this context is not available on a pure client connected to a remote server.
// WARNING! always check if interfaces are available before using
static CSteamGameServerAPIContext s_SteamGameServerAPIContext;
CSteamGameServerAPIContext *steamgameserverapicontext = &s_SteamGameServerAPIContext;
#endif
IUploadGameStats *gamestatsuploader = NULL;
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
CTimedEventMgr g_NetworkPropertyEventMgr;
ISaveRestoreBlockHandler *GetEventQueueSaveRestoreBlockHandler();
ISaveRestoreBlockHandler *GetCommentarySaveRestoreBlockHandler();
CUtlLinkedList<CMapEntityRef, unsigned short> g_MapEntityRefs;
// Engine interfaces.
IVEngineServer *engine = NULL;
IVoiceServer *g_pVoiceServer = NULL;
#if !defined(_STATIC_LINKED)
IFileSystem *filesystem = NULL;
#else
extern IFileSystem *filesystem;
#endif
INetworkStringTableContainer *networkstringtable = NULL;
IStaticPropMgrServer *staticpropmgr = NULL;
IUniformRandomStream *random = NULL;
IEngineSound *enginesound = NULL;
ISpatialPartition *partition = NULL;
IVModelInfo *modelinfo = NULL;
IEngineTrace *enginetrace = NULL;
IGameEventManager2 *gameeventmanager = NULL;
IDataCache *datacache = NULL;
IVDebugOverlay * debugoverlay = NULL;
ISoundEmitterSystemBase *soundemitterbase = NULL;
IServerPluginHelpers *serverpluginhelpers = NULL;
IServerEngineTools *serverenginetools = NULL;
ISceneFileCache *scenefilecache = NULL;
IXboxSystem *xboxsystem = NULL; // Xbox 360 only
IMatchmaking *matchmaking = NULL; // Xbox 360 only
#if defined( REPLAY_ENABLED )
IReplaySystem *g_pReplay = NULL;
IServerReplayContext *g_pReplayServerContext = NULL;
#endif
IGameSystem *SoundEmitterSystem();
bool ModelSoundsCacheInit();
void ModelSoundsCacheShutdown();
void SceneManager_ClientActive( CBasePlayer *player );
class IMaterialSystem;
class IStudioRender;
#ifdef _DEBUG
static ConVar s_UseNetworkVars( "UseNetworkVars", "1", FCVAR_CHEAT, "For profiling, toggle network vars." );
#endif
extern ConVar sv_noclipduringpause;
ConVar sv_massreport( "sv_massreport", "0" );
ConVar sv_force_transmit_ents( "sv_force_transmit_ents", "0", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "Will transmit all entities to client, regardless of PVS conditions (will still skip based on transmit flags, however)." );
ConVar sv_autosave( "sv_autosave", "1", 0, "Set to 1 to autosave game on level transition. Does not affect autosave triggers." );
ConVar *sv_maxreplay = NULL;
static ConVar *g_pcv_commentary = NULL;
static ConVar *g_pcv_ThreadMode = NULL;
static ConVar *g_pcv_hideServer = NULL;
// String tables
INetworkStringTable *g_pStringTableParticleEffectNames = NULL;
INetworkStringTable *g_pStringTableEffectDispatch = NULL;
INetworkStringTable *g_pStringTableVguiScreen = NULL;
INetworkStringTable *g_pStringTableMaterials = NULL;
INetworkStringTable *g_pStringTableInfoPanel = NULL;
INetworkStringTable *g_pStringTableClientSideChoreoScenes = NULL;
INetworkStringTable *g_pStringTableServerMapCycle = NULL;
#ifdef TF_DLL
INetworkStringTable *g_pStringTableServerPopFiles = NULL;
INetworkStringTable *g_pStringTableServerMapCycleMvM = NULL;
#endif
CStringTableSaveRestoreOps g_VguiScreenStringOps;
// Holds global variables shared between engine and game.
CGlobalVars *gpGlobals;
edict_t *g_pDebugEdictBase = 0;
static int g_nCommandClientIndex = 0;
// The chapter number of the current
static int g_nCurrentChapterIndex = -1;
#ifdef _DEBUG
static ConVar sv_showhitboxes( "sv_showhitboxes", "-1", FCVAR_CHEAT, "Send server-side hitboxes for specified entity to client (NOTE: this uses lots of bandwidth, use on listen server only)." );
#endif
void PrecachePointTemplates();
static ClientPutInServerOverrideFn g_pClientPutInServerOverride = NULL;
static void UpdateChapterRestrictions( const char *mapname );
static void UpdateRichPresence ( void );
#if !defined( _XBOX ) // Don't doubly define this symbol.
CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
#endif
IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
{
return engine->GetChangeAccessor( (const edict_t *)this );
}
const IChangeInfoAccessor *CBaseEdict::GetChangeAccessor() const
{
return engine->GetChangeAccessor( (const edict_t *)this );
}
const char *GetHintTypeDescription( CAI_Hint *pHint );
void ClientPutInServerOverride( ClientPutInServerOverrideFn fn )
{
g_pClientPutInServerOverride = fn;
}
ConVar ai_post_frame_navigation( "ai_post_frame_navigation", "0" );
class CPostFrameNavigationHook;
extern CPostFrameNavigationHook *PostFrameNavigationSystem( void );
//-----------------------------------------------------------------------------
// Purpose:
// Output : int
//-----------------------------------------------------------------------------
int UTIL_GetCommandClientIndex( void )
{
// -1 == unknown,dedicated server console
// 0 == player 1
// Convert to 1 based offset
return (g_nCommandClientIndex+1);
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : CBasePlayer
//-----------------------------------------------------------------------------
CBasePlayer *UTIL_GetCommandClient( void )
{
int idx = UTIL_GetCommandClientIndex();
if ( idx > 0 )
{
return UTIL_PlayerByIndex( idx );
}
// HLDS console issued command
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Retrieves the MOD directory for the active game (ie. "hl2")
//-----------------------------------------------------------------------------
bool UTIL_GetModDir( char *lpszTextOut, unsigned int nSize )
{
// Must pass in a buffer at least large enough to hold the desired string
const char *pGameDir = CommandLine()->ParmValue( "-game", "hl2" );
Assert( strlen(pGameDir) <= nSize );
if ( strlen(pGameDir) > nSize )
return false;
Q_strncpy( lpszTextOut, pGameDir, nSize );
if ( Q_strnchr( lpszTextOut, '/', nSize ) || Q_strnchr( lpszTextOut, '\\', nSize ) )
{
// Strip the last directory off (which will be our game dir)
Q_StripLastDir( lpszTextOut, nSize );
// Find the difference in string lengths and take that difference from the original string as the mod dir
int dirlen = Q_strlen( lpszTextOut );
Q_strncpy( lpszTextOut, pGameDir + dirlen, Q_strlen( pGameDir ) - dirlen + 1 );
}
return true;
}
extern void InitializeCvars( void );
CBaseEntity* FindPickerEntity( CBasePlayer* pPlayer );
CAI_Node* FindPickerAINode( CBasePlayer* pPlayer, NodeType_e nNodeType );
CAI_Link* FindPickerAILink( CBasePlayer* pPlayer );
float GetFloorZ(const Vector &origin);
void UpdateAllClientData( void );
void DrawMessageEntities();
#include "ai_network.h"
// For now just using one big AI network
extern ConVar think_limit;
#if 0
//-----------------------------------------------------------------------------
// Purpose: Draw output overlays for any measure sections
// Input :
//-----------------------------------------------------------------------------
void DrawMeasuredSections(void)
{
int row = 1;
float rowheight = 0.025;
CMeasureSection *p = CMeasureSection::GetList();
while ( p )
{
char str[256];
Q_snprintf(str,sizeof(str),"%s",p->GetName());
NDebugOverlay::ScreenText( 0.01,0.51+(row*rowheight),str, 255,255,255,255, 0.0 );
Q_snprintf(str,sizeof(str),"%5.2f\n",p->GetTime().GetMillisecondsF());
//Q_snprintf(str,sizeof(str),"%3.3f\n",p->GetTime().GetSeconds() * 100.0 / engine->Time());
NDebugOverlay::ScreenText( 0.28,0.51+(row*rowheight),str, 255,255,255,255, 0.0 );
Q_snprintf(str,sizeof(str),"%5.2f\n",p->GetMaxTime().GetMillisecondsF());
//Q_snprintf(str,sizeof(str),"%3.3f\n",p->GetTime().GetSeconds() * 100.0 / engine->Time());
NDebugOverlay::ScreenText( 0.34,0.51+(row*rowheight),str, 255,255,255,255, 0.0 );
row++;
p = p->GetNext();
}
bool sort_reset = false;
// Time to redo sort?
if ( measure_resort.GetFloat() > 0.0 &&
engine->Time() >= CMeasureSection::m_dNextResort )
{
// Redo it
CMeasureSection::SortSections();
// Set next time
CMeasureSection::m_dNextResort = engine->Time() + measure_resort.GetFloat();
// Flag to reset sort accumulator, too
sort_reset = true;
}
// Iterate through the sections now
p = CMeasureSection::GetList();
while ( p )
{
// Update max
p->UpdateMax();
// Reset regular accum.
p->Reset();
// Reset sort accum less often
if ( sort_reset )
{
p->SortReset();
}
p = p->GetNext();
}
}
#endif
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void DrawAllDebugOverlays( void )
{
// If in debug select mode print the selection entities name or classname
if (CBaseEntity::m_bInDebugSelect)
{
CBasePlayer* pPlayer = UTIL_PlayerByIndex( CBaseEntity::m_nDebugPlayer );
if (pPlayer)
{
// First try to trace a hull to an entity
CBaseEntity *pEntity = FindPickerEntity( pPlayer );
if ( pEntity )
{
pEntity->DrawDebugTextOverlays();
pEntity->DrawBBoxOverlay();
pEntity->SendDebugPivotOverlay();
}
}
}
// --------------------------------------------------------
// Draw debug overlay lines
// --------------------------------------------------------
UTIL_DrawOverlayLines();
// ------------------------------------------------------------------------
// If in wc_edit mode draw a box to highlight which node I'm looking at
// ------------------------------------------------------------------------
if (engine->IsInEditMode())
{
CBasePlayer* pPlayer = UTIL_PlayerByIndex( CBaseEntity::m_nDebugPlayer );
if (pPlayer)
{
if (g_pAINetworkManager->GetEditOps()->m_bLinkEditMode)
{
CAI_Link* pAILink = FindPickerAILink(pPlayer);
if (pAILink)
{
// For now just using one big AI network
Vector startPos = g_pBigAINet->GetNode(pAILink->m_iSrcID)->GetPosition(g_pAINetworkManager->GetEditOps()->m_iHullDrawNum);
Vector endPos = g_pBigAINet->GetNode(pAILink->m_iDestID)->GetPosition(g_pAINetworkManager->GetEditOps()->m_iHullDrawNum);
Vector linkDir = startPos-endPos;
float linkLen = VectorNormalize( linkDir );
// Draw in green if link that's been turned off
if (pAILink->m_LinkInfo & bits_LINK_OFF)
{
NDebugOverlay::BoxDirection(startPos, Vector(-4,-4,-4), Vector(-linkLen,4,4), linkDir, 0,255,0,40,0);
}
else
{
NDebugOverlay::BoxDirection(startPos, Vector(-4,-4,-4), Vector(-linkLen,4,4), linkDir, 255,0,0,40,0);
}
}
}
else
{
CAI_Node* pAINode;
if (g_pAINetworkManager->GetEditOps()->m_bAirEditMode)
{
pAINode = FindPickerAINode(pPlayer,NODE_AIR);
}
else
{
pAINode = FindPickerAINode(pPlayer,NODE_GROUND);
}
if (pAINode)
{
Vector vecPos = pAINode->GetPosition(g_pAINetworkManager->GetEditOps()->m_iHullDrawNum);
NDebugOverlay::Box( vecPos, Vector(-8,-8,-8), Vector(8,8,8), 255,0,0,40,0);
if ( pAINode->GetHint() )
{
CBaseEntity *pEnt = (CBaseEntity *)pAINode->GetHint();
if ( pEnt->GetEntityName() != NULL_STRING )
{
NDebugOverlay::Text( vecPos + Vector(0,0,6), STRING(pEnt->GetEntityName()), false, 0 );
}
NDebugOverlay::Text( vecPos, GetHintTypeDescription( pAINode->GetHint() ), false, 0 );
}
}
}
// ------------------------------------
// If in air edit mode draw guide line
// ------------------------------------
if (g_pAINetworkManager->GetEditOps()->m_bAirEditMode)
{
UTIL_DrawPositioningOverlay(g_pAINetworkManager->GetEditOps()->m_flAirEditDistance);
}
else
{
NDebugOverlay::DrawGroundCrossHairOverlay();
}
}
}
// For not just using one big AI Network
if ( g_pAINetworkManager )
{
g_pAINetworkManager->GetEditOps()->DrawAINetworkOverlay();
}
// PERFORMANCE: only do this in developer mode
if ( g_pDeveloper->GetInt() && !engine->IsDedicatedServer() )
{
// iterate through all objects for debug overlays
const CEntInfo *pInfo = gEntList.FirstEntInfo();
for ( ;pInfo; pInfo = pInfo->m_pNext )
{
CBaseEntity *ent = (CBaseEntity *)pInfo->m_pEntity;
// HACKHACK: to flag off these calls
if ( ent->m_debugOverlays || ent->m_pTimedOverlay )
{
MDLCACHE_CRITICAL_SECTION();
ent->DrawDebugGeometryOverlays();
}
}
}
if ( sv_massreport.GetInt() )
{
// iterate through all objects for debug overlays
const CEntInfo *pInfo = gEntList.FirstEntInfo();
for ( ;pInfo; pInfo = pInfo->m_pNext )
{
CBaseEntity *ent = (CBaseEntity *)pInfo->m_pEntity;
if (!ent->VPhysicsGetObject())
continue;
char tempstr[512];
Q_snprintf(tempstr, sizeof(tempstr),"%s: Mass: %.2f kg / %.2f lb (%s)",
STRING( ent->GetModelName() ), ent->VPhysicsGetObject()->GetMass(),
kg2lbs(ent->VPhysicsGetObject()->GetMass()),
GetMassEquivalent(ent->VPhysicsGetObject()->GetMass()));
ent->EntityText(0, tempstr, 0);
}
}
// A hack to draw point_message entities w/o developer required
DrawMessageEntities();
}
CServerGameDLL g_ServerGameDLL;
// INTERFACEVERSION_SERVERGAMEDLL_VERSION_8 is compatible with the latest since we're only adding things to the end, so expose that as well.
//EXPOSE_SINGLE_INTERFACE_GLOBALVAR(CServerGameDLL, IServerGameDLL008, INTERFACEVERSION_SERVERGAMEDLL_VERSION_8, g_ServerGameDLL );
EXPOSE_SINGLE_INTERFACE_GLOBALVAR(CServerGameDLL, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL, g_ServerGameDLL);
// When bumping the version to this interface, check that our assumption is still valid and expose the older version in the same way
COMPILE_TIME_ASSERT( INTERFACEVERSION_SERVERGAMEDLL_INT == 10 );
bool CServerGameDLL::DLLInit( CreateInterfaceFn appSystemFactory,
CreateInterfaceFn physicsFactory, CreateInterfaceFn fileSystemFactory,
CGlobalVars *pGlobals)
{
ConnectTier1Libraries( &appSystemFactory, 1 );
ConnectTier2Libraries( &appSystemFactory, 1 );
ConnectTier3Libraries( &appSystemFactory, 1 );
// Connected in ConnectTier1Libraries
if ( cvar == NULL )
return false;
#ifndef _X360
s_SteamAPIContext.Init();
s_SteamGameServerAPIContext.Init();
#endif
// init each (seperated for ease of debugging)
if ( (engine = (IVEngineServer*)appSystemFactory(INTERFACEVERSION_VENGINESERVER, NULL)) == NULL )
return false;
if ( (g_pVoiceServer = (IVoiceServer*)appSystemFactory(INTERFACEVERSION_VOICESERVER, NULL)) == NULL )
return false;
if ( (networkstringtable = (INetworkStringTableContainer *)appSystemFactory(INTERFACENAME_NETWORKSTRINGTABLESERVER,NULL)) == NULL )
return false;
if ( (staticpropmgr = (IStaticPropMgrServer *)appSystemFactory(INTERFACEVERSION_STATICPROPMGR_SERVER,NULL)) == NULL )
return false;
if ( (random = (IUniformRandomStream *)appSystemFactory(VENGINE_SERVER_RANDOM_INTERFACE_VERSION, NULL)) == NULL )
return false;
if ( (enginesound = (IEngineSound *)appSystemFactory(IENGINESOUND_SERVER_INTERFACE_VERSION, NULL)) == NULL )
return false;
if ( (partition = (ISpatialPartition *)appSystemFactory(INTERFACEVERSION_SPATIALPARTITION, NULL)) == NULL )
return false;
if ( (modelinfo = (IVModelInfo *)appSystemFactory(VMODELINFO_SERVER_INTERFACE_VERSION, NULL)) == NULL )
return false;
if ( (enginetrace = (IEngineTrace *)appSystemFactory(INTERFACEVERSION_ENGINETRACE_SERVER,NULL)) == NULL )
return false;
if ( (filesystem = (IFileSystem *)fileSystemFactory(FILESYSTEM_INTERFACE_VERSION,NULL)) == NULL )
return false;
if ( (gameeventmanager = (IGameEventManager2 *)appSystemFactory(INTERFACEVERSION_GAMEEVENTSMANAGER2,NULL)) == NULL )
return false;
if ( (datacache = (IDataCache*)appSystemFactory(DATACACHE_INTERFACE_VERSION, NULL )) == NULL )
return false;
if ( (soundemitterbase = (ISoundEmitterSystemBase *)appSystemFactory(SOUNDEMITTERSYSTEM_INTERFACE_VERSION, NULL)) == NULL )
return false;
#ifndef _XBOX
if ( (gamestatsuploader = (IUploadGameStats *)appSystemFactory( INTERFACEVERSION_UPLOADGAMESTATS, NULL )) == NULL )
return false;
#endif
if ( !mdlcache )
return false;
if ( (serverpluginhelpers = (IServerPluginHelpers *)appSystemFactory(INTERFACEVERSION_ISERVERPLUGINHELPERS, NULL)) == NULL )
return false;
if ( (scenefilecache = (ISceneFileCache *)appSystemFactory( SCENE_FILE_CACHE_INTERFACE_VERSION, NULL )) == NULL )
return false;
if ( IsX360() && (xboxsystem = (IXboxSystem *)appSystemFactory( XBOXSYSTEM_INTERFACE_VERSION, NULL )) == NULL )
return false;
if ( IsX360() && (matchmaking = (IMatchmaking *)appSystemFactory( VENGINE_MATCHMAKING_VERSION, NULL )) == NULL )
return false;
// If not running dedicated, grab the engine vgui interface
if ( !engine->IsDedicatedServer() )
{
#ifdef _WIN32
// This interface is optional, and is only valid when running with -tools
serverenginetools = ( IServerEngineTools * )appSystemFactory( VSERVERENGINETOOLS_INTERFACE_VERSION, NULL );
#endif
}
#ifdef NEO
if (!FindOriginalNeotokyoAssets(filesystem, false))
{
return false;
}
NeoVersionPrint();
#endif
// Yes, both the client and game .dlls will try to Connect, the soundemittersystem.dll will handle this gracefully
if ( !soundemitterbase->Connect( appSystemFactory ) )
return false;
// cache the globals
gpGlobals = pGlobals;
g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
MathLib_Init( 2.2f, 2.2f, 0.0f, 2.0f );
// save these in case other system inits need them
factorylist_t factories;
factories.engineFactory = appSystemFactory;
factories.fileSystemFactory = fileSystemFactory;
factories.physicsFactory = physicsFactory;
FactoryList_Store( factories );
// load used game events
gameeventmanager->LoadEventsFromFile("resource/gameevents.res");
// init the cvar list first in case inits want to reference them
InitializeCvars();
// Initialize the particle system
if ( !g_pParticleSystemMgr->Init( g_pParticleSystemQuery ) )
{
return false;
}
sv_cheats = g_pCVar->FindVar( "sv_cheats" );
if ( !sv_cheats )
return false;
g_pcv_commentary = g_pCVar->FindVar( "commentary" );
g_pcv_ThreadMode = g_pCVar->FindVar( "host_thread_mode" );
g_pcv_hideServer = g_pCVar->FindVar( "hide_server" );
sv_maxreplay = g_pCVar->FindVar( "sv_maxreplay" );
g_pGameSaveRestoreBlockSet->AddBlockHandler( GetEntitySaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->AddBlockHandler( GetPhysSaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->AddBlockHandler( GetAISaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->AddBlockHandler( GetTemplateSaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->AddBlockHandler( GetDefaultResponseSystemSaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->AddBlockHandler( GetCommentarySaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->AddBlockHandler( GetEventQueueSaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->AddBlockHandler( GetAchievementSaveRestoreBlockHandler() );
// The string system must init first + shutdown last
IGameSystem::Add( GameStringSystem() );
// Physics must occur before the sound envelope manager
IGameSystem::Add( PhysicsGameSystem() );
// Used to service deferred navigation queries for NPCs
IGameSystem::Add( (IGameSystem *) PostFrameNavigationSystem() );
// Add game log system
IGameSystem::Add( GameLogSystem() );
#ifndef _XBOX
// Add HLTV director
IGameSystem::Add( HLTVDirectorSystem() );
#endif
// Add sound emitter
IGameSystem::Add( SoundEmitterSystem() );
// load Mod specific game events ( MUST be before InitAllSystems() so it can pickup the mod specific events)
#ifdef NEO
// Because the base-game override is overriding our nod events, use a separate one
gameeventmanager->LoadEventsFromFile("resource/NeoModEvents.res");
#else
gameeventmanager->LoadEventsFromFile("resource/ModEvents.res");
#endif
#ifdef CSTRIKE_DLL // BOTPORT: TODO: move these ifdefs out
InstallBotControl();
#endif
if ( !IGameSystem::InitAllSystems() )
return false;
#if defined( REPLAY_ENABLED )
if ( gameeventmanager->LoadEventsFromFile( "resource/replayevents.res" ) <= 0 )
{
Warning( "\n*\n* replayevents.res MISSING.\n*\n\n" );
return false;
}
#endif
// Due to dependencies, these are not autogamesystems
if ( !ModelSoundsCacheInit() )
{
return false;
}
InvalidateQueryCache();
// Parse the particle manifest file & register the effects within it
ParseParticleEffects( false, false );
// try to get debug overlay, may be NULL if on HLDS
debugoverlay = (IVDebugOverlay *)appSystemFactory( VDEBUG_OVERLAY_INTERFACE_VERSION, NULL );
#ifndef _XBOX
#ifdef USE_NAV_MESH
// create the Navigation Mesh interface
TheNavMesh = NavMeshFactory();
#endif
// init the gamestatsupload connection
gamestatsuploader->InitConnection();
#endif
return true;
}
void CServerGameDLL::PostInit()
{
IGameSystem::PostInitAllSystems();
#ifdef NEO
// Initialize streamer mode names
for (int i = 0; i < MAX_PLAYERS + 1; ++i)
{
V_memset(gStreamerModeNames[i], '.', 5);
}
#endif
}
void CServerGameDLL::DLLShutdown( void )
{
// Due to dependencies, these are not autogamesystems
ModelSoundsCacheShutdown();
g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetAchievementSaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetCommentarySaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetEventQueueSaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetDefaultResponseSystemSaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetTemplateSaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetAISaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetPhysSaveRestoreBlockHandler() );
g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetEntitySaveRestoreBlockHandler() );
char *pFilename = g_TextStatsMgr.GetStatsFilename();
if ( !pFilename || !pFilename[0] )
{
g_TextStatsMgr.SetStatsFilename( "stats.txt" );
}
g_TextStatsMgr.WriteFile( filesystem );
IGameSystem::ShutdownAllSystems();
#ifdef CSTRIKE_DLL // BOTPORT: TODO: move these ifdefs out
RemoveBotControl();
#endif
#ifndef _XBOX
#ifdef USE_NAV_MESH
// destroy the Navigation Mesh interface
if ( TheNavMesh )
{
delete TheNavMesh;
TheNavMesh = NULL;
}
#endif
// reset (shutdown) the gamestatsupload connection
gamestatsuploader->InitConnection();
#endif
#ifndef _X360
s_SteamAPIContext.Clear(); // Steam API context shutdown
s_SteamGameServerAPIContext.Clear();
#endif
gameeventmanager = NULL;
DisconnectTier3Libraries();
DisconnectTier2Libraries();
ConVar_Unregister();
DisconnectTier1Libraries();
}
bool CServerGameDLL::ReplayInit( CreateInterfaceFn fnReplayFactory )
{
#if defined( REPLAY_ENABLED )
if ( !IsPC() )
return false;
if ( (g_pReplay = ( IReplaySystem *)fnReplayFactory( REPLAY_INTERFACE_VERSION, NULL )) == NULL )
return false;
if ( (g_pReplayServerContext = g_pReplay->SV_GetContext()) == NULL )
return false;
return true;
#else
return false;
#endif
}
//-----------------------------------------------------------------------------
// Purpose: See shareddefs.h for redefining this. Don't even think about it, though, for HL2. Or you will pay. ywb 9/22/03
// Output : float
//-----------------------------------------------------------------------------
float CServerGameDLL::GetTickInterval( void ) const
{
float tickinterval = DEFAULT_TICK_INTERVAL;
//=============================================================================
// HPE_BEGIN:
// [Forrest] For Counter-Strike, set default tick rate of 66 and removed -tickrate command line parameter.
//=============================================================================
// Ignoring this for now, server ops are abusing it
#if !defined( TF_DLL ) && !defined( CSTRIKE_DLL ) && !defined( DOD_DLL )
//=============================================================================
// HPE_END
//=============================================================================
// override if tick rate specified in command line
if ( CommandLine()->CheckParm( "-tickrate" ) )
{
#ifdef NEO
const int tickrateAsInt = CommandLine()->ParmValue("-tickrate", 0);
Warning("WARNING: Setting -tickrate is not recommended. Server is only recommended to run at the default ~66.67 tickrate. Current tickrate: %d\n", tickrateAsInt);
const float tickrate = static_cast<float>(tickrateAsInt);
#else
float tickrate = CommandLine()->ParmValue("-tickrate", 0);
#endif
if ( tickrate > 10 )
tickinterval = 1.0f / tickrate;
}
#endif
return tickinterval;
}
// This is called when a new game is started. (restart, map)
bool CServerGameDLL::GameInit( void )
{
ResetGlobalState();
engine->ServerCommand( "exec game.cfg\n" );
engine->ServerExecute( );
CBaseEntity::sm_bAccurateTriggerBboxChecks = true;
IGameEvent *event = gameeventmanager->CreateEvent( "game_init" );
if ( event )
{
gameeventmanager->FireEvent( event );
}
return true;
}
// This is called when a game ends (server disconnect, death, restart, load)
// NOT on level transitions within a game
void CServerGameDLL::GameShutdown( void )
{
ResetGlobalState();
}
static bool g_OneWayTransition = false;
void Game_SetOneWayTransition( void )
{
g_OneWayTransition = true;
}
static CUtlVector<EHANDLE> g_RestoredEntities;
// just for debugging, assert that this is the only time this function is called
static bool g_InRestore = false;
void AddRestoredEntity( CBaseEntity *pEntity )
{
Assert(g_InRestore);
if ( !pEntity )
return;
g_RestoredEntities.AddToTail( EHANDLE(pEntity) );
}
void EndRestoreEntities()
{
if ( !g_InRestore )
return;
// The entire hierarchy is restored, so we can call GetAbsOrigin again.
//CBaseEntity::SetAbsQueriesValid( true );
// Call all entities' OnRestore handlers
for ( int i = g_RestoredEntities.Count()-1; i >=0; --i )
{
CBaseEntity *pEntity = g_RestoredEntities[i].Get();
if ( pEntity && !pEntity->IsDormant() )
{
MDLCACHE_CRITICAL_SECTION();
pEntity->OnRestore();
}
}
g_RestoredEntities.Purge();
IGameSystem::OnRestoreAllSystems();
g_InRestore = false;
gEntList.CleanupDeleteList();
// HACKHACK: UNDONE: We need to redesign the main loop with respect to save/load/server activate
g_ServerGameDLL.ServerActivate( NULL, 0, 0 );
CBaseEntity::SetAllowPrecache( false );
}
void BeginRestoreEntities()
{
if ( g_InRestore )
{
DevMsg( "BeginRestoreEntities without previous EndRestoreEntities.\n" );
gEntList.CleanupDeleteList();
}
g_RestoredEntities.Purge();
g_InRestore = true;
CBaseEntity::SetAllowPrecache( true );
// No calls to GetAbsOrigin until the entire hierarchy is restored!
//CBaseEntity::SetAbsQueriesValid( false );
}
//-----------------------------------------------------------------------------
// Purpose: This prevents sv.tickcount/gpGlobals->tickcount from advancing during restore which
// would cause a lot of the NPCs to fast forward their think times to the same
// tick due to some ticks being elapsed during restore where there was no simulation going on
//-----------------------------------------------------------------------------
bool CServerGameDLL::IsRestoring()
{
return g_InRestore;
}
// Called any time a new level is started (after GameInit() also on level transitions within a game)
bool CServerGameDLL::LevelInit( const char *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background )
{
VPROF("CServerGameDLL::LevelInit");
#ifdef USES_ECON_ITEMS
GameItemSchema_t *pItemSchema = ItemSystem()->GetItemSchema();
if ( pItemSchema )
{
pItemSchema->BInitFromDelayedBuffer();
}
#endif // USES_ECON_ITEMS
ResetWindspeed();
UpdateChapterRestrictions( pMapName );