]> icculus.org git repositories - icculus/iodoom3.git/blob - neo/d3xp/Game_local.h
hello world
[icculus/iodoom3.git] / neo / d3xp / Game_local.h
1 /*
2 ===========================================================================
3
4 Doom 3 GPL Source Code
5 Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. 
6
7 This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).  
8
9 Doom 3 Source Code is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 Doom 3 Source Code is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with Doom 3 Source Code.  If not, see <http://www.gnu.org/licenses/>.
21
22 In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code.  If not, please request a copy in writing from id Software at the address below.
23
24 If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
25
26 ===========================================================================
27 */
28
29 #ifndef __GAME_LOCAL_H__
30 #define __GAME_LOCAL_H__
31
32 /*
33 ===============================================================================
34
35         Local implementation of the public game interface.
36
37 ===============================================================================
38 */
39
40 #define LAGO_IMG_WIDTH 64
41 #define LAGO_IMG_HEIGHT 64
42 #define LAGO_WIDTH      64
43 #define LAGO_HEIGHT     44
44 #define LAGO_MATERIAL   "textures/sfx/lagometer"
45 #define LAGO_IMAGE              "textures/sfx/lagometer.tga"
46
47 // if set to 1 the server sends the client PVS with snapshots and the client compares against what it sees
48 #ifndef ASYNC_WRITE_PVS
49         #define ASYNC_WRITE_PVS 0
50 #endif
51
52 #ifdef ID_DEBUG_UNINITIALIZED_MEMORY
53 // This is real evil but allows the code to inspect arbitrary class variables.
54 #define private         public
55 #define protected       public
56 #endif
57
58 extern idRenderWorld *                          gameRenderWorld;
59 extern idSoundWorld *                           gameSoundWorld;
60
61 // the "gameversion" client command will print this plus compile date
62 #define GAME_VERSION            "baseDOOM-1"
63
64 // classes used by idGameLocal
65 class idEntity;
66 class idActor;
67 class idPlayer;
68 class idCamera;
69 class idWorldspawn;
70 class idTestModel;
71 class idAAS;
72 class idAI;
73 class idSmokeParticles;
74 class idEntityFx;
75 class idTypeInfo;
76 class idProgram;
77 class idThread;
78 class idEditEntities;
79 class idLocationEntity;
80
81 #define MAX_CLIENTS                             32
82 #define GENTITYNUM_BITS                 12
83 #define MAX_GENTITIES                   (1<<GENTITYNUM_BITS)
84 #define ENTITYNUM_NONE                  (MAX_GENTITIES-1)
85 #define ENTITYNUM_WORLD                 (MAX_GENTITIES-2)
86 #define ENTITYNUM_MAX_NORMAL    (MAX_GENTITIES-2)
87
88 //============================================================================
89
90 void gameError( const char *fmt, ... );
91
92 #include "gamesys/Event.h"
93 #include "gamesys/Class.h"
94 #include "gamesys/SysCvar.h"
95 #include "gamesys/SysCmds.h"
96 #include "gamesys/SaveGame.h"
97 #include "gamesys/DebugGraph.h"
98
99 #include "script/Script_Program.h"
100
101 #include "anim/Anim.h"
102
103 #include "ai/AAS.h"
104
105 #include "physics/Clip.h"
106 #include "physics/Push.h"
107
108 #include "Pvs.h"
109 #include "MultiplayerGame.h"
110
111 //============================================================================
112
113 const int MAX_GAME_MESSAGE_SIZE         = 8192;
114 const int MAX_ENTITY_STATE_SIZE         = 512;
115 const int ENTITY_PVS_SIZE                       = ((MAX_GENTITIES+31)>>5);
116 const int NUM_RENDER_PORTAL_BITS        = idMath::BitsForInteger( PS_BLOCK_ALL );
117
118 typedef struct entityState_s {
119         int                                             entityNumber;
120         idBitMsg                                state;
121         byte                                    stateBuf[MAX_ENTITY_STATE_SIZE];
122         struct entityState_s *  next;
123 } entityState_t;
124
125 typedef struct snapshot_s {
126         int                                             sequence;
127         entityState_t *                 firstEntityState;
128         int                                             pvs[ENTITY_PVS_SIZE];
129         struct snapshot_s *             next;
130 } snapshot_t;
131
132 const int MAX_EVENT_PARAM_SIZE          = 128;
133
134 typedef struct entityNetEvent_s {
135         int                                             spawnId;
136         int                                             event;
137         int                                             time;
138         int                                             paramsSize;
139         byte                                    paramsBuf[MAX_EVENT_PARAM_SIZE];
140         struct entityNetEvent_s *next;
141         struct entityNetEvent_s *prev;
142 } entityNetEvent_t;
143
144 enum {
145         GAME_RELIABLE_MESSAGE_INIT_DECL_REMAP,
146         GAME_RELIABLE_MESSAGE_REMAP_DECL,
147         GAME_RELIABLE_MESSAGE_SPAWN_PLAYER,
148         GAME_RELIABLE_MESSAGE_DELETE_ENT,
149         GAME_RELIABLE_MESSAGE_CHAT,
150         GAME_RELIABLE_MESSAGE_TCHAT,
151         GAME_RELIABLE_MESSAGE_SOUND_EVENT,
152         GAME_RELIABLE_MESSAGE_SOUND_INDEX,
153         GAME_RELIABLE_MESSAGE_DB,
154         GAME_RELIABLE_MESSAGE_KILL,
155         GAME_RELIABLE_MESSAGE_DROPWEAPON,
156         GAME_RELIABLE_MESSAGE_RESTART,
157         GAME_RELIABLE_MESSAGE_SERVERINFO,
158         GAME_RELIABLE_MESSAGE_TOURNEYLINE,
159         GAME_RELIABLE_MESSAGE_CALLVOTE,
160         GAME_RELIABLE_MESSAGE_CASTVOTE,
161         GAME_RELIABLE_MESSAGE_STARTVOTE,
162         GAME_RELIABLE_MESSAGE_UPDATEVOTE,
163         GAME_RELIABLE_MESSAGE_PORTALSTATES,
164         GAME_RELIABLE_MESSAGE_PORTAL,
165         GAME_RELIABLE_MESSAGE_VCHAT,
166         GAME_RELIABLE_MESSAGE_STARTSTATE,
167         GAME_RELIABLE_MESSAGE_MENU,
168         GAME_RELIABLE_MESSAGE_WARMUPTIME,
169         GAME_RELIABLE_MESSAGE_EVENT
170 };
171
172 typedef enum {
173         GAMESTATE_UNINITIALIZED,                // prior to Init being called
174         GAMESTATE_NOMAP,                                // no map loaded
175         GAMESTATE_STARTUP,                              // inside InitFromNewMap().  spawning map entities.
176         GAMESTATE_ACTIVE,                               // normal gameplay
177         GAMESTATE_SHUTDOWN                              // inside MapShutdown().  clearing memory.
178 } gameState_t;
179
180 typedef struct {
181         idEntity        *ent;
182         int                     dist;
183 #ifdef CTF
184         int                     team;                   
185 #endif    
186 } spawnSpot_t;
187
188 //============================================================================
189
190 class idEventQueue {
191 public:
192         typedef enum {
193                 OUTOFORDER_IGNORE,
194                 OUTOFORDER_DROP,
195                 OUTOFORDER_SORT
196         } outOfOrderBehaviour_t;
197
198                                                         idEventQueue() : start( NULL ), end( NULL ) {}
199
200         entityNetEvent_t *              Alloc();
201         void                                    Free( entityNetEvent_t *event );
202         void                                    Shutdown();
203
204         void                                    Init();
205         void                                    Enqueue( entityNetEvent_t* event, outOfOrderBehaviour_t oooBehaviour );
206         entityNetEvent_t *              Dequeue( void );
207         entityNetEvent_t *              RemoveLast( void );
208
209         entityNetEvent_t *              Start( void ) { return start; }
210
211 private:
212         entityNetEvent_t *                                      start;
213         entityNetEvent_t *                                      end;
214         idBlockAlloc<entityNetEvent_t,32>       eventAllocator;
215 };
216
217 //============================================================================
218
219 template< class type >
220 class idEntityPtr {
221 public:
222                                                         idEntityPtr();
223
224         // save games
225         void                                    Save( idSaveGame *savefile ) const;                                     // archives object for save game file
226         void                                    Restore( idRestoreGame *savefile );                                     // unarchives object from save game file
227
228         idEntityPtr<type> &             operator=( type *ent );
229
230         // synchronize entity pointers over the network
231         int                                             GetSpawnId( void ) const { return spawnId; }
232         bool                                    SetSpawnId( int id );
233         bool                                    UpdateSpawnId( void );
234
235         bool                                    IsValid( void ) const;
236         type *                                  GetEntity( void ) const;
237         int                                             GetEntityNum( void ) const;
238
239 private:
240         int                                             spawnId;
241 };
242
243 #ifdef _D3XP
244 struct timeState_t {
245         int                                     time;
246         int                                     previousTime;
247         int                                     msec;
248         int                                     framenum;
249         int                                     realClientTime;
250
251         void                            Set( int t, int pt, int ms, int f, int rct )            { time = t; previousTime = pt; msec = ms; framenum = f; realClientTime = rct; };
252         void                            Get( int& t, int& pt, int& ms, int& f, int& rct )       { t = time; pt = previousTime; ms = msec; f = framenum; rct = realClientTime; };
253         void                            Save( idSaveGame *savefile ) const      { savefile->WriteInt( time ); savefile->WriteInt( previousTime ); savefile->WriteInt( msec ); savefile->WriteInt( framenum ); savefile->WriteInt( realClientTime ); }
254         void                            Restore( idRestoreGame *savefile )      { savefile->ReadInt( time ); savefile->ReadInt( previousTime ); savefile->ReadInt( msec ); savefile->ReadInt( framenum ); savefile->ReadInt( realClientTime ); }
255         void                            Increment()                                                                                     { framenum++; previousTime = time; time += msec; realClientTime = time; };
256 };
257
258 enum slowmoState_t {
259         SLOWMO_STATE_OFF,
260         SLOWMO_STATE_RAMPUP,
261         SLOWMO_STATE_ON,
262         SLOWMO_STATE_RAMPDOWN
263 };
264 #endif
265
266 //============================================================================
267
268 class idGameLocal : public idGame {
269 public:
270         idDict                                  serverInfo;                             // all the tunable parameters, like numclients, etc
271         int                                             numClients;                             // pulled from serverInfo and verified
272         idDict                                  userInfo[MAX_CLIENTS];  // client specific settings
273         usercmd_t                               usercmds[MAX_CLIENTS];  // client input commands
274         idDict                                  persistentPlayerInfo[MAX_CLIENTS];
275         idEntity *                              entities[MAX_GENTITIES];// index to entities
276         int                                             spawnIds[MAX_GENTITIES];// for use in idEntityPtr
277         int                                             firstFreeIndex;                 // first free index in the entities array
278         int                                             num_entities;                   // current number <= MAX_GENTITIES
279         idHashIndex                             entityHash;                             // hash table to quickly find entities by name
280         idWorldspawn *                  world;                                  // world entity
281         idLinkList<idEntity>    spawnedEntities;                // all spawned entities
282         idLinkList<idEntity>    activeEntities;                 // all thinking entities (idEntity::thinkFlags != 0)
283         int                                             numEntitiesToDeactivate;// number of entities that became inactive in current frame
284         bool                                    sortPushers;                    // true if active lists needs to be reordered to place pushers at the front
285         bool                                    sortTeamMasters;                // true if active lists needs to be reordered to place physics team masters before their slaves
286         idDict                                  persistentLevelInfo;    // contains args that are kept around between levels
287
288         // can be used to automatically effect every material in the world that references globalParms
289         float                                   globalShaderParms[ MAX_GLOBAL_SHADER_PARMS ];   
290
291         idRandom                                random;                                 // random number generator used throughout the game
292
293         idProgram                               program;                                // currently loaded script and data space
294         idThread *                              frameCommandThread;
295
296         idClip                                  clip;                                   // collision detection
297         idPush                                  push;                                   // geometric pushing
298         idPVS                                   pvs;                                    // potential visible set
299
300         idTestModel *                   testmodel;                              // for development testing of models
301         idEntityFx *                    testFx;                                 // for development testing of fx
302
303         idStr                                   sessionCommand;                 // a target_sessionCommand can set this to return something to the session 
304
305         idMultiplayerGame               mpGame;                                 // handles rules for standard dm
306
307         idSmokeParticles *              smokeParticles;                 // global smoke trails
308         idEditEntities *                editEntities;                   // in game editing
309
310         int                                             cinematicSkipTime;              // don't allow skipping cinemetics until this time has passed so player doesn't skip out accidently from a firefight
311         int                                             cinematicStopTime;              // cinematics have several camera changes, so keep track of when we stop them so that we don't reset cinematicSkipTime unnecessarily
312         int                                             cinematicMaxSkipTime;   // time to end cinematic when skipping.  there's a possibility of an infinite loop if the map isn't set up right.
313         bool                                    inCinematic;                    // game is playing cinematic (player controls frozen)
314         bool                                    skipCinematic;
315
316                                                                                                         // are kept up to date with changes to serverInfo
317         int                                             framenum;
318         int                                             previousTime;                   // time in msec of last frame
319         int                                             time;                                   // in msec
320         int                                             msec;                                   // time since last update in milliseconds
321
322         int                                             vacuumAreaNum;                  // -1 if level doesn't have any outside areas
323
324         gameType_t                              gameType;
325         bool                                    isMultiplayer;                  // set if the game is run in multiplayer mode
326         bool                                    isServer;                               // set if the game is run for a dedicated or listen server
327         bool                                    isClient;                               // set if the game is run for a client
328                                                                                                         // discriminates between the RunFrame path and the ClientPrediction path
329                                                                                                         // NOTE: on a listen server, isClient is false
330         int                                             localClientNum;                 // number of the local client. MP: -1 on a dedicated
331         idLinkList<idEntity>    snapshotEntities;               // entities from the last snapshot
332         int                                             realClientTime;                 // real client time
333         bool                                    isNewFrame;                             // true if this is a new game frame, not a rerun due to prediction
334         float                                   clientSmoothing;                // smoothing of other clients in the view
335         int                                             entityDefBits;                  // bits required to store an entity def number
336
337         static const char *             sufaceTypeNames[ MAX_SURFACE_TYPES ];   // text names for surface types
338
339         idEntityPtr<idEntity>   lastGUIEnt;                             // last entity with a GUI, used by Cmd_NextGUI_f
340         int                                             lastGUI;                                // last GUI on the lastGUIEnt
341
342 #ifdef _D3XP
343         idEntityPtr<idEntity>   portalSkyEnt;
344         bool                                    portalSkyActive;
345
346         void                                    SetPortalSkyEnt( idEntity *ent );
347         bool                                    IsPortalSkyAcive();
348
349         timeState_t                             fast;
350         timeState_t                             slow;
351
352         slowmoState_t                   slowmoState;
353         float                                   slowmoMsec;
354
355         bool                                    quickSlowmoReset;
356
357         virtual void                    SelectTimeGroup( int timeGroup );
358         virtual int                             GetTimeGroupTime( int timeGroup );
359
360         virtual void                    GetBestGameType( const char* map, const char* gametype, char buf[ MAX_STRING_CHARS ] );
361
362         void                                    ComputeSlowMsec();
363         void                                    RunTimeGroup2();
364
365         void                                    ResetSlowTimeVars();
366         void                                    QuickSlowmoReset();
367
368         bool                                    NeedRestart();
369 #endif
370
371         void                                    Tokenize( idStrList &out, const char *in );
372
373         // ---------------------- Public idGame Interface -------------------
374
375                                                         idGameLocal();
376
377         virtual void                    Init( void );
378         virtual void                    Shutdown( void );
379         virtual void                    SetLocalClient( int clientNum );
380         virtual void                    ThrottleUserInfo( void );
381         virtual const idDict *  SetUserInfo( int clientNum, const idDict &userInfo, bool isClient, bool canModify );
382         virtual const idDict *  GetUserInfo( int clientNum );
383         virtual void                    SetServerInfo( const idDict &serverInfo );
384
385         virtual const idDict &  GetPersistentPlayerInfo( int clientNum );
386         virtual void                    SetPersistentPlayerInfo( int clientNum, const idDict &playerInfo );
387         virtual void                    InitFromNewMap( const char *mapName, idRenderWorld *renderWorld, idSoundWorld *soundWorld, bool isServer, bool isClient, int randSeed );
388         virtual bool                    InitFromSaveGame( const char *mapName, idRenderWorld *renderWorld, idSoundWorld *soundWorld, idFile *saveGameFile );
389         virtual void                    SaveGame( idFile *saveGameFile );
390         virtual void                    MapShutdown( void );
391         virtual void                    CacheDictionaryMedia( const idDict *dict );
392         virtual void                    SpawnPlayer( int clientNum );
393         virtual gameReturn_t    RunFrame( const usercmd_t *clientCmds );
394         virtual bool                    Draw( int clientNum );
395         virtual escReply_t              HandleESC( idUserInterface **gui );
396         virtual idUserInterface *StartMenu( void );
397         virtual const char *    HandleGuiCommands( const char *menuCommand );
398         virtual void                    HandleMainMenuCommands( const char *menuCommand, idUserInterface *gui );
399         virtual allowReply_t    ServerAllowClient( int numClients, const char *IP, const char *guid, const char *password, char reason[MAX_STRING_CHARS] );
400         virtual void                    ServerClientConnect( int clientNum, const char *guid );
401         virtual void                    ServerClientBegin( int clientNum );
402         virtual void                    ServerClientDisconnect( int clientNum );
403         virtual void                    ServerWriteInitialReliableMessages( int clientNum );
404         virtual void                    ServerWriteSnapshot( int clientNum, int sequence, idBitMsg &msg, byte *clientInPVS, int numPVSClients );
405         virtual bool                    ServerApplySnapshot( int clientNum, int sequence );
406         virtual void                    ServerProcessReliableMessage( int clientNum, const idBitMsg &msg );
407         virtual void                    ClientReadSnapshot( int clientNum, int sequence, const int gameFrame, const int gameTime, const int dupeUsercmds, const int aheadOfServer, const idBitMsg &msg );
408         virtual bool                    ClientApplySnapshot( int clientNum, int sequence );
409         virtual void                    ClientProcessReliableMessage( int clientNum, const idBitMsg &msg );
410         virtual gameReturn_t    ClientPrediction( int clientNum, const usercmd_t *clientCmds, bool lastPredictFrame );
411
412         virtual void                    GetClientStats( int clientNum, char *data, const int len );
413         virtual void                    SwitchTeam( int clientNum, int team );
414
415         virtual bool                    DownloadRequest( const char *IP, const char *guid, const char *paks, char urls[ MAX_STRING_CHARS ] );
416
417         virtual void                            GetMapLoadingGUI( char gui[ MAX_STRING_CHARS ] );
418
419         // ---------------------- Public idGameLocal Interface -------------------
420
421         void                                    Printf( const char *fmt, ... ) const id_attribute((format(printf,2,3)));
422         void                                    DPrintf( const char *fmt, ... ) const id_attribute((format(printf,2,3)));
423         void                                    Warning( const char *fmt, ... ) const id_attribute((format(printf,2,3)));
424         void                                    DWarning( const char *fmt, ... ) const id_attribute((format(printf,2,3)));
425         void                                    Error( const char *fmt, ... ) const id_attribute((format(printf,2,3)));
426
427                                                         // Initializes all map variables common to both save games and spawned games
428         void                                    LoadMap( const char *mapName, int randseed );
429
430         void                                    LocalMapRestart( void );
431         void                                    MapRestart( void );
432         static void                             MapRestart_f( const idCmdArgs &args );
433         bool                                    NextMap( void );        // returns wether serverinfo settings have been modified
434         static void                             NextMap_f( const idCmdArgs &args );
435
436         idMapFile *                             GetLevelMap( void );
437         const char *                    GetMapName( void ) const;
438
439         int                                             NumAAS( void ) const;
440         idAAS *                                 GetAAS( int num ) const;
441         idAAS *                                 GetAAS( const char *name ) const;
442         void                                    SetAASAreaState( const idBounds &bounds, const int areaContents, bool closed );
443         aasHandle_t                             AddAASObstacle( const idBounds &bounds );
444         void                                    RemoveAASObstacle( const aasHandle_t handle );
445         void                                    RemoveAllAASObstacles( void );
446
447         bool                                    CheatsOk( bool requirePlayer = true );
448         void                                    SetSkill( int value );
449         gameState_t                             GameState( void ) const;
450         idEntity *                              SpawnEntityType( const idTypeInfo &classdef, const idDict *args = NULL, bool bIsClientReadSnapshot = false );
451         bool                                    SpawnEntityDef( const idDict &args, idEntity **ent = NULL, bool setDefaults = true );
452         int                                             GetSpawnId( const idEntity *ent ) const;
453
454         const idDeclEntityDef * FindEntityDef( const char *name, bool makeDefault = true ) const;
455         const idDict *                  FindEntityDefDict( const char *name, bool makeDefault = true ) const;
456
457         void                                    RegisterEntity( idEntity *ent );
458         void                                    UnregisterEntity( idEntity *ent );
459
460         bool                                    RequirementMet( idEntity *activator, const idStr &requires, int removeItem );
461
462         void                                    AlertAI( idEntity *ent );
463         idActor *                               GetAlertEntity( void );
464
465         bool                                    InPlayerPVS( idEntity *ent ) const;
466         bool                                    InPlayerConnectedArea( idEntity *ent ) const;
467 #ifdef _D3XP
468         pvsHandle_t                             GetPlayerPVS()                  { return playerPVS; };
469 #endif
470
471         void                                    SetCamera( idCamera *cam );
472         idCamera *                              GetCamera( void ) const;
473         bool                                    SkipCinematic( void );
474         void                                    CalcFov( float base_fov, float &fov_x, float &fov_y ) const;
475
476         void                                    AddEntityToHash( const char *name, idEntity *ent );
477         bool                                    RemoveEntityFromHash( const char *name, idEntity *ent );
478         int                                             GetTargets( const idDict &args, idList< idEntityPtr<idEntity> > &list, const char *ref ) const;
479
480                                                         // returns the master entity of a trace.  for example, if the trace entity is the player's head, it will return the player.
481         idEntity *                              GetTraceEntity( const trace_t &trace ) const;
482
483         static void                             ArgCompletion_EntityName( const idCmdArgs &args, void(*callback)( const char *s ) );
484         idEntity *                              FindTraceEntity( idVec3 start, idVec3 end, const idTypeInfo &c, const idEntity *skip ) const;
485         idEntity *                              FindEntity( const char *name ) const;
486         idEntity *                              FindEntityUsingDef( idEntity *from, const char *match ) const;
487         int                                             EntitiesWithinRadius( const idVec3 org, float radius, idEntity **entityList, int maxCount ) const;
488
489         void                                    KillBox( idEntity *ent, bool catch_teleport = false );
490         void                                    RadiusDamage( const idVec3 &origin, idEntity *inflictor, idEntity *attacker, idEntity *ignoreDamage, idEntity *ignorePush, const char *damageDefName, float dmgPower = 1.0f );
491         void                                    RadiusPush( const idVec3 &origin, const float radius, const float push, const idEntity *inflictor, const idEntity *ignore, float inflictorScale, const bool quake );
492         void                                    RadiusPushClipModel( const idVec3 &origin, const float push, const idClipModel *clipModel );
493
494         void                                    ProjectDecal( const idVec3 &origin, const idVec3 &dir, float depth, bool parallel, float size, const char *material, float angle = 0 );
495         void                                    BloodSplat( const idVec3 &origin, const idVec3 &dir, float size, const char *material );
496
497         void                                    CallFrameCommand( idEntity *ent, const function_t *frameCommand );
498         void                                    CallObjectFrameCommand( idEntity *ent, const char *frameCommand );
499
500         const idVec3 &                  GetGravity( void ) const;
501
502         // added the following to assist licensees with merge issues
503         int                                             GetFrameNum() const { return framenum; };
504         int                                             GetTime() const { return time; };
505         int                                             GetMSec() const { return msec; };
506
507         int                                             GetNextClientNum( int current ) const;
508         idPlayer *                              GetClientByNum( int current ) const;
509         idPlayer *                              GetClientByName( const char *name ) const;
510         idPlayer *                              GetClientByCmdArgs( const idCmdArgs &args ) const;
511
512         idPlayer *                              GetLocalPlayer() const;
513
514         void                                    SpreadLocations();
515         idLocationEntity *              LocationForPoint( const idVec3 &point );        // May return NULL
516         idEntity *                              SelectInitialSpawnPoint( idPlayer *player );
517
518         void                                    SetPortalState( qhandle_t portal, int blockingBits );
519         void                                    SaveEntityNetworkEvent( const idEntity *ent, int event, const idBitMsg *msg );
520         void                                    ServerSendChatMessage( int to, const char *name, const char *text );
521         int                                             ServerRemapDecl( int clientNum, declType_t type, int index );
522         int                                             ClientRemapDecl( declType_t type, int index );
523
524         void                                    SetGlobalMaterial( const idMaterial *mat );
525         const idMaterial *              GetGlobalMaterial();
526
527         void                                    SetGibTime( int _time ) { nextGibTime = _time; };
528         int                                             GetGibTime() { return nextGibTime; };
529
530
531
532 private:
533         const static int                INITIAL_SPAWN_COUNT = 1;
534
535         idStr                                   mapFileName;                    // name of the map, empty string if no map loaded
536         idMapFile *                             mapFile;                                // will be NULL during the game unless in-game editing is used
537         bool                                    mapCycleLoaded;
538
539         int                                             spawnCount;
540         int                                             mapSpawnCount;                  // it's handy to know which entities are part of the map
541
542         idLocationEntity **             locationEntities;               // for location names, etc
543
544         idCamera *                              camera;
545         const idMaterial *              globalMaterial;         // for overriding everything
546
547         idList<idAAS *>                 aasList;                                // area system
548         idStrList                               aasNames;
549
550         idEntityPtr<idActor>    lastAIAlertEntity;
551         int                                             lastAIAlertTime;
552
553         idDict                                  spawnArgs;                              // spawn args used during entity spawning  FIXME: shouldn't be necessary anymore
554
555         pvsHandle_t                             playerPVS;                              // merged pvs of all players
556         pvsHandle_t                             playerConnectedAreas;   // all areas connected to any player area
557
558         idVec3                                  gravity;                                // global gravity vector
559         gameState_t                             gamestate;                              // keeps track of whether we're spawning, shutting down, or normal gameplay
560         bool                                    influenceActive;                // true when a phantasm is happening
561         int                                             nextGibTime;
562
563         idList<int>                             clientDeclRemap[MAX_CLIENTS][DECL_MAX_TYPES];
564
565         entityState_t *                 clientEntityStates[MAX_CLIENTS][MAX_GENTITIES];
566         int                                             clientPVS[MAX_CLIENTS][ENTITY_PVS_SIZE];
567         snapshot_t *                    clientSnapshots[MAX_CLIENTS];
568         idBlockAlloc<entityState_t,256>entityStateAllocator;
569         idBlockAlloc<snapshot_t,64>snapshotAllocator;
570
571         idEventQueue                    eventQueue;
572         idEventQueue                    savedEventQueue;
573
574         idStaticList<spawnSpot_t, MAX_GENTITIES> spawnSpots;
575         idStaticList<idEntity *, MAX_GENTITIES> initialSpots;
576         int                                             currentInitialSpot;
577
578 #ifdef CTF
579         idStaticList<spawnSpot_t, MAX_GENTITIES> teamSpawnSpots[2];
580         idStaticList<idEntity *, MAX_GENTITIES> teamInitialSpots[2];
581         int                                             teamCurrentInitialSpot[2];
582 #endif
583
584         idDict                                  newInfo;
585
586         idStrList                               shakeSounds;
587
588         byte                                    lagometer[ LAGO_IMG_HEIGHT ][ LAGO_IMG_WIDTH ][ 4 ];
589
590         void                                    Clear( void );
591                                                         // returns true if the entity shouldn't be spawned at all in this game type or difficulty level
592         bool                                    InhibitEntitySpawn( idDict &spawnArgs );
593                                                         // spawn entities from the map file
594         void                                    SpawnMapEntities( void );
595                                                         // commons used by init, shutdown, and restart
596         void                                    MapPopulate( void );
597         void                                    MapClear( bool clearClients );
598
599         pvsHandle_t                             GetClientPVS( idPlayer *player, pvsType_t type );
600         void                                    SetupPlayerPVS( void );
601         void                                    FreePlayerPVS( void );
602         void                                    UpdateGravity( void );
603         void                                    SortActiveEntityList( void );
604         void                                    ShowTargets( void );
605         void                                    RunDebugInfo( void );
606
607         void                                    InitScriptForMap( void );
608
609         void                                    InitConsoleCommands( void );
610         void                                    ShutdownConsoleCommands( void );
611
612         void                                    InitAsyncNetwork( void );
613         void                                    ShutdownAsyncNetwork( void );
614         void                                    InitLocalClient( int clientNum );
615         void                                    InitClientDeclRemap( int clientNum );
616         void                                    ServerSendDeclRemapToClient( int clientNum, declType_t type, int index );
617         void                                    FreeSnapshotsOlderThanSequence( int clientNum, int sequence );
618         bool                                    ApplySnapshot( int clientNum, int sequence );
619         void                                    WriteGameStateToSnapshot( idBitMsgDelta &msg ) const;
620         void                                    ReadGameStateFromSnapshot( const idBitMsgDelta &msg );
621         void                                    NetworkEventWarning( const entityNetEvent_t *event, const char *fmt, ... ) id_attribute((format(printf,3,4)));
622         void                                    ServerProcessEntityNetworkEventQueue( void );
623         void                                    ClientProcessEntityNetworkEventQueue( void );
624         void                                    ClientShowSnapshot( int clientNum ) const;
625                                                         // call after any change to serverInfo. Will update various quick-access flags
626         void                                    UpdateServerInfoFlags( void );
627         void                                    RandomizeInitialSpawns( void );
628         static int                              sortSpawnPoints( const void *ptr1, const void *ptr2 );
629
630         void                                    DumpOggSounds( void );
631         void                                    GetShakeSounds( const idDict *dict );
632
633         void                                    UpdateLagometer( int aheadOfServer, int dupeUsercmds );
634 };
635
636 //============================================================================
637
638 extern idGameLocal                      gameLocal;
639 extern idAnimManager            animationLib;
640
641 //============================================================================
642
643 class idGameError : public idException {
644 public:
645         idGameError( const char *text ) : idException( text ) {}
646 };
647
648 //============================================================================
649
650 template< class type >
651 ID_INLINE idEntityPtr<type>::idEntityPtr() {
652         spawnId = 0;
653 }
654
655 template< class type >
656 ID_INLINE void idEntityPtr<type>::Save( idSaveGame *savefile ) const {
657         savefile->WriteInt( spawnId );
658 }
659
660 template< class type >
661 ID_INLINE void idEntityPtr<type>::Restore( idRestoreGame *savefile ) {
662         savefile->ReadInt( spawnId );
663 }
664
665 template< class type >
666 ID_INLINE idEntityPtr<type> &idEntityPtr<type>::operator=( type *ent ) {
667         if ( ent == NULL ) {
668                 spawnId = 0;
669         } else {
670                 spawnId = ( gameLocal.spawnIds[ent->entityNumber] << GENTITYNUM_BITS ) | ent->entityNumber;
671         }
672         return *this;
673 }
674
675 template< class type >
676 ID_INLINE bool idEntityPtr<type>::SetSpawnId( int id ) {
677         // the reason for this first check is unclear:
678         // the function returning false may mean the spawnId is already set right, or the entity is missing
679         if ( id == spawnId ) {
680                 return false;
681         }
682         if ( ( id >> GENTITYNUM_BITS ) == gameLocal.spawnIds[ id & ( ( 1 << GENTITYNUM_BITS ) - 1 ) ] ) {
683                 spawnId = id;
684                 return true;
685         }
686         return false;
687 }
688
689 template< class type >
690 ID_INLINE bool idEntityPtr<type>::IsValid( void ) const {
691         return ( gameLocal.spawnIds[ spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 ) ] == ( spawnId >> GENTITYNUM_BITS ) );
692 }
693
694 template< class type >
695 ID_INLINE type *idEntityPtr<type>::GetEntity( void ) const {
696         int entityNum = spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 );
697         if ( ( gameLocal.spawnIds[ entityNum ] == ( spawnId >> GENTITYNUM_BITS ) ) ) {
698                 return static_cast<type *>( gameLocal.entities[ entityNum ] );
699         }
700         return NULL;
701 }
702
703 template< class type >
704 ID_INLINE int idEntityPtr<type>::GetEntityNum( void ) const {
705         return ( spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 ) );
706 }
707
708 //  ===========================================================================
709
710 //
711 // these defines work for all startsounds from all entity types
712 // make sure to change script/doom_defs.script if you add any channels, or change their order
713 //
714 typedef enum {
715         SND_CHANNEL_ANY = SCHANNEL_ANY,
716         SND_CHANNEL_VOICE = SCHANNEL_ONE,
717         SND_CHANNEL_VOICE2,
718         SND_CHANNEL_BODY,
719         SND_CHANNEL_BODY2,
720         SND_CHANNEL_BODY3,
721         SND_CHANNEL_WEAPON,
722         SND_CHANNEL_ITEM,
723         SND_CHANNEL_HEART,
724         SND_CHANNEL_PDA,
725         SND_CHANNEL_DEMONIC,
726         SND_CHANNEL_RADIO,
727
728         // internal use only.  not exposed to script or framecommands.
729         SND_CHANNEL_AMBIENT,
730         SND_CHANNEL_DAMAGE
731 } gameSoundChannel_t;
732
733 // content masks
734 #define MASK_ALL                                        (-1)
735 #define MASK_SOLID                                      (CONTENTS_SOLID)
736 #define MASK_MONSTERSOLID                       (CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BODY)
737 #define MASK_PLAYERSOLID                        (CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_BODY)
738 #define MASK_DEADSOLID                          (CONTENTS_SOLID|CONTENTS_PLAYERCLIP)
739 #define MASK_WATER                                      (CONTENTS_WATER)
740 #define MASK_OPAQUE                                     (CONTENTS_OPAQUE)
741 #define MASK_SHOT_RENDERMODEL           (CONTENTS_SOLID|CONTENTS_RENDERMODEL)
742 #define MASK_SHOT_BOUNDINGBOX           (CONTENTS_SOLID|CONTENTS_BODY)
743
744 const float DEFAULT_GRAVITY                     = 1066.0f;
745 #define DEFAULT_GRAVITY_STRING          "1066"
746 const idVec3 DEFAULT_GRAVITY_VEC3( 0, 0, -DEFAULT_GRAVITY );
747
748 const int       CINEMATIC_SKIP_DELAY    = SEC2MS( 2.0f );
749
750 //============================================================================
751
752 #include "physics/Force.h"
753 #include "physics/Force_Constant.h"
754 #include "physics/Force_Drag.h"
755 #ifdef _D3XP
756 #include "physics/Force_Grab.h"
757 #endif
758 #include "physics/Force_Field.h"
759 #include "physics/Force_Spring.h"
760 #include "physics/Physics.h"
761 #include "physics/Physics_Static.h"
762 #include "physics/Physics_StaticMulti.h"
763 #include "physics/Physics_Base.h"
764 #include "physics/Physics_Actor.h"
765 #include "physics/Physics_Monster.h"
766 #include "physics/Physics_Player.h"
767 #include "physics/Physics_Parametric.h"
768 #include "physics/Physics_RigidBody.h"
769 #include "physics/Physics_AF.h"
770
771 #include "SmokeParticles.h"
772
773 #include "Entity.h"
774 #include "GameEdit.h"
775 #ifdef _D3XP
776 #include "Grabber.h"
777 #endif
778 #include "AF.h"
779 #include "IK.h"
780 #include "AFEntity.h"
781 #include "Misc.h"
782 #include "Actor.h"
783 #include "Projectile.h"
784 #include "Weapon.h"
785 #include "Light.h"
786 #include "WorldSpawn.h"
787 #include "Item.h"
788 #include "PlayerView.h"
789 #include "PlayerIcon.h"
790 #include "Player.h"
791 #include "Mover.h"
792 #include "Camera.h"
793 #include "Moveable.h"
794 #include "Target.h"
795 #include "Trigger.h"
796 #include "Sound.h"
797 #include "Fx.h"
798 #include "SecurityCamera.h"
799 #include "BrittleFracture.h"
800
801 #include "ai/AI.h"
802 #include "anim/Anim_Testmodel.h"
803
804 #include "script/Script_Compiler.h"
805 #include "script/Script_Interpreter.h"
806 #include "script/Script_Thread.h"
807
808 #endif  /* !__GAME_LOCAL_H__ */