]> icculus.org git repositories - divverent/darkplaces.git/blob - host.c
added sv_clmovement_* cvars to disable movement prediction of players, or disable...
[divverent/darkplaces.git] / host.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // host.c -- coordinates spawning and killing of local servers
21
22 #include <time.h>
23 #include "quakedef.h"
24 #include "cdaudio.h"
25 #include "cl_video.h"
26 #include "progsvm.h"
27 #include "csprogs.h"
28
29 /*
30
31 A server can always be started, even if the system started out as a client
32 to a remote system.
33
34 A client can NOT be started if the system started as a dedicated server.
35
36 Memory is cleared / released when a server or client begins, not when they end.
37
38 */
39
40 // how many frames have occurred
41 // (checked by Host_Error and Host_SaveConfig_f)
42 int host_framecount = 0;
43 // LordHavoc: set when quit is executed
44 qboolean host_shuttingdown = false;
45
46 // the real time since application started, without any slowmo or clamping
47 double realtime;
48
49 // current client
50 client_t *host_client;
51
52 jmp_buf host_abortframe;
53
54 // pretend frames take this amount of time (in seconds), 0 = realtime
55 cvar_t host_framerate = {0, "host_framerate","0", "locks frame timing to this value in seconds, 0.05 is 20fps for example, note that this can easily run too fast, use host_maxfps if you want to limit your framerate instead, or sys_ticrate to limit server speed"};
56 // shows time used by certain subsystems
57 cvar_t host_speeds = {0, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
58 // LordHavoc: framerate independent slowmo
59 cvar_t slowmo = {0, "slowmo", "1.0", "controls game speed, 0.5 is half speed, 2 is double speed"};
60 // LordHavoc: framerate upper cap
61 cvar_t cl_maxfps = {CVAR_SAVE, "cl_maxfps", "1000", "maximum fps cap, if game is running faster than this it will wait before running another frame (useful to make cpu time available to other programs)"};
62
63 // print broadcast messages in dedicated mode
64 cvar_t sv_echobprint = {CVAR_SAVE, "sv_echobprint", "1", "prints gamecode bprint() calls to server console"};
65
66 cvar_t sys_ticrate = {CVAR_SAVE, "sys_ticrate","0.05", "how long a server frame is in seconds, 0.05 is 20fps server rate, 0.1 is 10fps (can not be set higher than 0.1), 0 runs as many server frames as possible (makes games against bots a little smoother, overwhelms network players)"};
67 cvar_t sv_fixedframeratesingleplayer = {0, "sv_fixedframeratesingleplayer", "0", "allows you to use server-style timing system in singleplayer (don't run faster than sys_ticrate)"};
68
69 cvar_t fraglimit = {CVAR_NOTIFY, "fraglimit","0", "ends level if this many frags is reached by any player"};
70 cvar_t timelimit = {CVAR_NOTIFY, "timelimit","0", "ends level at this time (in minutes)"};
71 cvar_t teamplay = {CVAR_NOTIFY, "teamplay","0", "teamplay mode, values depend on mod but typically 0 = no teams, 1 = no team damage no self damage, 2 = team damage and self damage, some mods support 3 = no team damage but can damage self"};
72
73 cvar_t samelevel = {CVAR_NOTIFY, "samelevel","0", "repeats same level if level ends (due to timelimit or someone hitting an exit)"};
74 cvar_t noexit = {CVAR_NOTIFY, "noexit","0", "kills anyone attempting to use an exit"};
75
76 cvar_t developer = {0, "developer","0", "prints additional debugging messages and information (recommended for modders and level designers)"};
77 cvar_t developer_entityparsing = {0, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
78
79 cvar_t skill = {0, "skill","1", "difficulty level of game, affects monster layouts in levels, 0 = easy, 1 = normal, 2 = hard, 3 = nightmare (same layout as hard but monsters fire twice)"};
80 cvar_t deathmatch = {0, "deathmatch","0", "deathmatch mode, values depend on mod but typically 0 = no deathmatch, 1 = normal deathmatch with respawning weapons, 2 = weapons stay (players can only pick up new weapons)"};
81 cvar_t coop = {0, "coop","0", "coop mode, 0 = no coop, 1 = coop mode, multiple players playing through the singleplayer game (coop mode also shuts off deathmatch)"};
82
83 cvar_t pausable = {0, "pausable","1", "allow players to pause or not"};
84
85 cvar_t temp1 = {0, "temp1","0", "general cvar for mods to use, in stock id1 this selects which death animation to use on players (0 = random death, other values select specific death scenes)"};
86
87 cvar_t timestamps = {CVAR_SAVE, "timestamps", "0", "prints timestamps on console messages"};
88 cvar_t timeformat = {CVAR_SAVE, "timeformat", "[%b %e %X] ", "time format to use on timestamped console messages"};
89
90 /*
91 ================
92 Host_AbortCurrentFrame
93
94 aborts the current host frame and goes on with the next one
95 ================
96 */
97 void Host_AbortCurrentFrame(void)
98 {
99         longjmp (host_abortframe, 1);
100 }
101
102 /*
103 ================
104 Host_Error
105
106 This shuts down both the client and server
107 ================
108 */
109 void Host_Error (const char *error, ...)
110 {
111         static char hosterrorstring1[MAX_INPUTLINE];
112         static char hosterrorstring2[MAX_INPUTLINE];
113         static qboolean hosterror = false;
114         va_list argptr;
115
116         // turn off rcon redirect if it was active when the crash occurred
117         rcon_redirect = false;
118
119         va_start (argptr,error);
120         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
121         va_end (argptr);
122
123         Con_Printf("Host_Error: %s\n", hosterrorstring1);
124
125         // LordHavoc: if crashing very early, or currently shutting down, do
126         // Sys_Error instead
127         if (host_framecount < 3 || host_shuttingdown)
128                 Sys_Error ("Host_Error: %s", hosterrorstring1);
129
130         if (hosterror)
131                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
132         hosterror = true;
133
134         strcpy(hosterrorstring2, hosterrorstring1);
135
136         CL_Parse_DumpPacket();
137
138         CL_Parse_ErrorCleanUp();
139
140         //PR_Crash();
141
142         // print out where the crash happened, if it was caused by QC (and do a cleanup)
143         PRVM_Crash();
144
145
146         Host_ShutdownServer ();
147
148         if (cls.state == ca_dedicated)
149                 Sys_Error ("Host_Error: %s",hosterrorstring2);  // dedicated servers exit
150
151         CL_Disconnect ();
152         cls.demonum = -1;
153
154         hosterror = false;
155
156         Host_AbortCurrentFrame();
157 }
158
159 void Host_ServerOptions (void)
160 {
161         int i;
162
163         // general default
164         svs.maxclients = 8;
165
166 // COMMANDLINEOPTION: Server: -dedicated [playerlimit] starts a dedicated server (with a command console), default playerlimit is 8
167 // COMMANDLINEOPTION: Server: -listen [playerlimit] starts a multiplayer server with graphical client, like singleplayer but other players can connect, default playerlimit is 8
168         // if no client is in the executable or -dedicated is specified on
169         // commandline, start a dedicated server
170         i = COM_CheckParm ("-dedicated");
171         if (i || !cl_available)
172         {
173                 cls.state = ca_dedicated;
174                 // check for -dedicated specifying how many players
175                 if (i && i + 1 < com_argc && atoi (com_argv[i+1]) >= 1)
176                         svs.maxclients = atoi (com_argv[i+1]);
177                 if (COM_CheckParm ("-listen"))
178                         Con_Printf ("Only one of -dedicated or -listen can be specified\n");
179                 // default sv_public on for dedicated servers (often hosted by serious administrators), off for listen servers (often hosted by clueless users)
180                 Cvar_SetValue("sv_public", 1);
181         }
182         else if (cl_available)
183         {
184                 // client exists and not dedicated, check if -listen is specified
185                 cls.state = ca_disconnected;
186                 i = COM_CheckParm ("-listen");
187                 if (i)
188                 {
189                         // default players unless specified
190                         if (i + 1 < com_argc && atoi (com_argv[i+1]) >= 1)
191                                 svs.maxclients = atoi (com_argv[i+1]);
192                 }
193                 else
194                 {
195                         // default players in some games, singleplayer in most
196                         if (gamemode != GAME_GOODVSBAD2 && gamemode != GAME_NEXUIZ && gamemode != GAME_BATTLEMECH)
197                                 svs.maxclients = 1;
198                 }
199         }
200
201         svs.maxclients = bound(1, svs.maxclients, MAX_SCOREBOARD);
202
203         svs.clients = (client_t *)Mem_Alloc(sv_mempool, sizeof(client_t) * svs.maxclients);
204
205         if (svs.maxclients > 1 && !deathmatch.integer && !coop.integer)
206                 Cvar_SetValueQuick(&deathmatch, 1);
207 }
208
209 /*
210 =======================
211 Host_InitLocal
212 ======================
213 */
214 void Host_SaveConfig_f(void);
215 static void Host_InitLocal (void)
216 {
217         Cmd_AddCommand("saveconfig", Host_SaveConfig_f, "save settings to config.cfg immediately (also automatic when quitting)");
218
219         Cvar_RegisterVariable (&host_framerate);
220         Cvar_RegisterVariable (&host_speeds);
221         Cvar_RegisterVariable (&slowmo);
222         Cvar_RegisterVariable (&cl_maxfps);
223
224         Cvar_RegisterVariable (&sv_echobprint);
225
226         Cvar_RegisterVariable (&sys_ticrate);
227         Cvar_RegisterVariable (&sv_fixedframeratesingleplayer);
228
229         Cvar_RegisterVariable (&fraglimit);
230         Cvar_RegisterVariable (&timelimit);
231         Cvar_RegisterVariable (&teamplay);
232         Cvar_RegisterVariable (&samelevel);
233         Cvar_RegisterVariable (&noexit);
234         Cvar_RegisterVariable (&skill);
235         Cvar_RegisterVariable (&developer);
236         Cvar_RegisterVariable (&developer_entityparsing);
237         Cvar_RegisterVariable (&deathmatch);
238         Cvar_RegisterVariable (&coop);
239
240         Cvar_RegisterVariable (&pausable);
241
242         Cvar_RegisterVariable (&temp1);
243
244         Cvar_RegisterVariable (&timestamps);
245         Cvar_RegisterVariable (&timeformat);
246 }
247
248
249 /*
250 ===============
251 Host_SaveConfig_f
252
253 Writes key bindings and archived cvars to config.cfg
254 ===============
255 */
256 void Host_SaveConfig_f(void)
257 {
258         qfile_t *f;
259
260 // dedicated servers initialize the host but don't parse and set the
261 // config.cfg cvars
262         // LordHavoc: don't save a config if it crashed in startup
263         if (host_framecount >= 3 && cls.state != ca_dedicated)
264         {
265                 f = FS_Open ("config.cfg", "wb", false, false);
266                 if (!f)
267                 {
268                         Con_Print("Couldn't write config.cfg.\n");
269                         return;
270                 }
271
272                 Key_WriteBindings (f);
273                 Cvar_WriteVariables (f);
274
275                 FS_Close (f);
276         }
277 }
278
279
280 /*
281 =================
282 SV_ClientPrint
283
284 Sends text across to be displayed
285 FIXME: make this just a stuffed echo?
286 =================
287 */
288 void SV_ClientPrint(const char *msg)
289 {
290         if (host_client->netconnection)
291         {
292                 MSG_WriteByte(&host_client->netconnection->message, svc_print);
293                 MSG_WriteString(&host_client->netconnection->message, msg);
294         }
295 }
296
297 /*
298 =================
299 SV_ClientPrintf
300
301 Sends text across to be displayed
302 FIXME: make this just a stuffed echo?
303 =================
304 */
305 void SV_ClientPrintf(const char *fmt, ...)
306 {
307         va_list argptr;
308         char msg[MAX_INPUTLINE];
309
310         va_start(argptr,fmt);
311         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
312         va_end(argptr);
313
314         SV_ClientPrint(msg);
315 }
316
317 /*
318 =================
319 SV_BroadcastPrint
320
321 Sends text to all active clients
322 =================
323 */
324 void SV_BroadcastPrint(const char *msg)
325 {
326         int i;
327         client_t *client;
328
329         for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
330         {
331                 if (client->spawned && client->netconnection)
332                 {
333                         MSG_WriteByte(&client->netconnection->message, svc_print);
334                         MSG_WriteString(&client->netconnection->message, msg);
335                 }
336         }
337
338         if (sv_echobprint.integer && cls.state == ca_dedicated)
339                 Con_Print(msg);
340 }
341
342 /*
343 =================
344 SV_BroadcastPrintf
345
346 Sends text to all active clients
347 =================
348 */
349 void SV_BroadcastPrintf(const char *fmt, ...)
350 {
351         va_list argptr;
352         char msg[MAX_INPUTLINE];
353
354         va_start(argptr,fmt);
355         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
356         va_end(argptr);
357
358         SV_BroadcastPrint(msg);
359 }
360
361 /*
362 =================
363 Host_ClientCommands
364
365 Send text over to the client to be executed
366 =================
367 */
368 void Host_ClientCommands(const char *fmt, ...)
369 {
370         va_list argptr;
371         char string[MAX_INPUTLINE];
372
373         if (!host_client->netconnection)
374                 return;
375
376         va_start(argptr,fmt);
377         dpvsnprintf(string, sizeof(string), fmt, argptr);
378         va_end(argptr);
379
380         MSG_WriteByte(&host_client->netconnection->message, svc_stufftext);
381         MSG_WriteString(&host_client->netconnection->message, string);
382 }
383
384 /*
385 =====================
386 SV_DropClient
387
388 Called when the player is getting totally kicked off the host
389 if (crash = true), don't bother sending signofs
390 =====================
391 */
392 void SV_DropClient(qboolean crash)
393 {
394         int i;
395         Con_Printf("Client \"%s\" dropped\n", host_client->name);
396
397         // make sure edict is not corrupt (from a level change for example)
398         host_client->edict = PRVM_EDICT_NUM(host_client - svs.clients + 1);
399
400         if (host_client->netconnection)
401         {
402                 // free the client (the body stays around)
403                 if (!crash)
404                 {
405                         // LordHavoc: no opportunity for resending, so use unreliable 3 times
406                         unsigned char bufdata[8];
407                         sizebuf_t buf;
408                         memset(&buf, 0, sizeof(buf));
409                         buf.data = bufdata;
410                         buf.maxsize = sizeof(bufdata);
411                         MSG_WriteByte(&buf, svc_disconnect);
412                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol);
413                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol);
414                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol);
415                 }
416                 // break the net connection
417                 NetConn_Close(host_client->netconnection);
418                 host_client->netconnection = NULL;
419         }
420
421         // call qc ClientDisconnect function
422         // LordHavoc: don't call QC if server is dead (avoids recursive
423         // Host_Error in some mods when they run out of edicts)
424         if (host_client->clientconnectcalled && sv.active && host_client->edict)
425         {
426                 // call the prog function for removing a client
427                 // this will set the body to a dead frame, among other things
428                 int saveSelf = prog->globals.server->self;
429                 host_client->clientconnectcalled = false;
430                 prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
431                 PRVM_ExecuteProgram(prog->globals.server->ClientDisconnect, "QC function ClientDisconnect is missing");
432                 prog->globals.server->self = saveSelf;
433         }
434
435         // remove leaving player from scoreboard
436         //host_client->edict->fields.server->netname = PRVM_SetEngineString(host_client->name);
437         //if ((val = PRVM_GETEDICTFIELDVALUE(host_client->edict, eval_clientcolors)))
438         //      val->_float = 0;
439         //host_client->edict->fields.server->frags = 0;
440         host_client->name[0] = 0;
441         host_client->colors = 0;
442         host_client->frags = 0;
443         // send notification to all clients
444         // get number of client manually just to make sure we get it right...
445         i = host_client - svs.clients;
446         MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
447         MSG_WriteByte (&sv.reliable_datagram, i);
448         MSG_WriteString (&sv.reliable_datagram, host_client->name);
449         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
450         MSG_WriteByte (&sv.reliable_datagram, i);
451         MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
452         MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
453         MSG_WriteByte (&sv.reliable_datagram, i);
454         MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
455
456         // free the client now
457         if (host_client->entitydatabase)
458                 EntityFrame_FreeDatabase(host_client->entitydatabase);
459         if (host_client->entitydatabase4)
460                 EntityFrame4_FreeDatabase(host_client->entitydatabase4);
461         if (host_client->entitydatabase5)
462                 EntityFrame5_FreeDatabase(host_client->entitydatabase5);
463
464         if (sv.active)
465         {
466                 // clear a fields that matter to DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS, and also frags
467                 PRVM_ED_ClearEdict(host_client->edict);
468         }
469
470         // clear the client struct (this sets active to false)
471         memset(host_client, 0, sizeof(*host_client));
472
473         // update server listing on the master because player count changed
474         // (which the master uses for filtering empty/full servers)
475         NetConn_Heartbeat(1);
476 }
477
478 /*
479 ==================
480 Host_ShutdownServer
481
482 This only happens at the end of a game, not between levels
483 ==================
484 */
485 void Host_ShutdownServer(void)
486 {
487         int i;
488
489         Con_DPrintf("Host_ShutdownServer\n");
490
491         if (!sv.active)
492                 return;
493
494         NetConn_Heartbeat(2);
495         NetConn_Heartbeat(2);
496
497 // make sure all the clients know we're disconnecting
498         SV_VM_Begin();
499         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
500                 if (host_client->active)
501                         SV_DropClient(false); // server shutdown
502         SV_VM_End();
503
504         NetConn_CloseServerPorts();
505
506         sv.active = false;
507 //
508 // clear structures
509 //
510         memset(&sv, 0, sizeof(sv));
511         memset(svs.clients, 0, svs.maxclients*sizeof(client_t));
512 }
513
514
515 //============================================================================
516
517 /*
518 ===================
519 Host_GetConsoleCommands
520
521 Add them exactly as if they had been typed at the console
522 ===================
523 */
524 void Host_GetConsoleCommands (void)
525 {
526         char *cmd;
527
528         while (1)
529         {
530                 cmd = Sys_ConsoleInput ();
531                 if (!cmd)
532                         break;
533                 Cbuf_AddText (cmd);
534         }
535 }
536
537 /*
538 ==================
539 Host_Frame
540
541 Runs all active servers
542 ==================
543 */
544 static void Host_Init(void);
545 void Host_Main(void)
546 {
547         static double time1 = 0;
548         static double time2 = 0;
549         static double time3 = 0;
550         // these are static because of setjmp/longjmp warnings in mingw32 gcc 2.95.3
551         static double frameoldtime, framenewtime, frametime, cl_timer, sv_timer;
552
553         Host_Init();
554
555         cl_timer = 0;
556         sv_timer = 0;
557
558         framenewtime = Sys_DoubleTime();
559         for (;;)
560         {
561                 if (setjmp(host_abortframe))
562                         continue;                       // something bad happened, or the server disconnected
563
564                 frameoldtime = framenewtime;
565                 framenewtime = Sys_DoubleTime();
566                 frametime = framenewtime - frameoldtime;
567                 realtime += frametime;
568
569                 // if there is some time remaining from last frame, rest the timers
570                 if (cl_timer >= 0)
571                         cl_timer = 0;
572                 if (sv_timer >= 0)
573                         sv_timer = 0;
574
575                 // accumulate the new frametime into the timers
576                 cl_timer += frametime;
577                 sv_timer += frametime;
578
579                 if (slowmo.value < 0)
580                         Cvar_SetValue("slowmo", 0);
581                 if (host_framerate.value < 0.00001 && host_framerate.value != 0)
582                         Cvar_SetValue("host_framerate", 0);
583                 if (cl_maxfps.value < 1)
584                         Cvar_SetValue("cl_maxfps", 1);
585
586                 // if the accumulators haven't become positive yet, keep waiting
587                 if (!cls.timedemo && cl_timer <= 0 && sv_timer <= 0)
588                 {
589                         double wait;
590                         int msleft;
591                         if (cls.state == ca_dedicated)
592                                 wait = sv_timer;
593                         else if (!sv.active)
594                                 wait = cl_timer;
595                         else
596                                 wait = max(cl_timer, sv_timer);
597                         msleft = (int)floor(wait * -1000.0);
598                         if (msleft >= 1)
599                                 Sys_Sleep(msleft);
600                         continue;
601                 }
602
603                 // keep the random time dependent
604                 rand();
605
606                 cl.islocalgame = NetConn_IsLocalGame();
607
608                 // get new key events
609                 Sys_SendKeyEvents();
610
611                 // when a server is running we only execute console commands on server frames
612                 // (this mainly allows frikbot .way config files to work properly by staying in sync with the server qc)
613                 // otherwise we execute them on all frames
614                 if (sv_timer > 0 || !sv.active)
615                 {
616                         // process console commands
617                         Cbuf_Execute();
618                 }
619
620                 NetConn_UpdateSockets();
621
622         //-------------------
623         //
624         // server operations
625         //
626         //-------------------
627
628                 if (sv_timer > 0)
629                 {
630                         if (!sv.active)
631                         {
632                                 // if there is no server, run server timing at 10fps
633                                 sv_timer -= 0.1;
634                         }
635                         else
636                         {
637                                 // execute one or more server frames, with an upper limit on how much
638                                 // execution time to spend on server frames to avoid freezing the game if
639                                 // the server is overloaded, this execution time limit means the game will
640                                 // slow down if the server is taking too long.
641                                 int framecount, framelimit = 1;
642                                 double advancetime, aborttime = 0;
643
644                                 // receive server packets now, which might contain rcon commands, which
645                                 // may change level or other such things we don't want to have happen in
646                                 // the middle of Host_Frame
647                                 NetConn_ServerFrame();
648
649                                 // check for commands typed to the host
650                                 Host_GetConsoleCommands();
651
652                                 // run the world state
653                                 // don't allow simulation to run too fast or too slow or logic glitches can occur
654
655                                 // stop running server frames if the wall time reaches this value
656                                 if (sys_ticrate.value <= 0)
657                                         advancetime = sv_timer;
658                                 else if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
659                                 {
660                                         // synchronize to the client frametime, but no less than 10ms and no more than sys_ticrate
661                                         advancetime = bound(0.01, cl_timer, sys_ticrate.value);
662                                         framelimit = 10;
663                                         aborttime = Sys_DoubleTime() + 0.1;
664                                 }
665                                 else
666                                 {
667                                         advancetime = sys_ticrate.value;
668                                         // listen servers can run multiple server frames per client frame
669                                         if (cls.state == ca_connected)
670                                         {
671                                                 framelimit = 10;
672                                                 aborttime = Sys_DoubleTime() + 0.1;
673                                         }
674                                 }
675                                 advancetime = min(advancetime, 0.1);
676
677                                 // only advance time if not paused
678                                 // the game also pauses in singleplayer when menu or console is used
679                                 sv.frametime = advancetime * slowmo.value;
680                                 if (host_framerate.value)
681                                         sv.frametime = host_framerate.value;
682                                 if (sv.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive)))
683                                         sv.frametime = 0;
684
685                                 // setup the VM frame
686                                 SV_VM_Begin();
687
688                                 for (framecount = 0;framecount < framelimit && sv_timer > 0;framecount++)
689                                 {
690                                         sv_timer -= advancetime;
691
692                                         // move things around and think unless paused
693                                         if (sv.frametime)
694                                                 SV_Physics();
695
696                                         // send all messages to the clients
697                                         SV_SendClientMessages();
698
699                                         // clear the general datagram
700                                         SV_ClearDatagram();
701
702                                         // if this server frame took too long, break out of the loop
703                                         if (framelimit > 1 && Sys_DoubleTime() >= aborttime)
704                                                 break;
705                                 }
706
707                                 // end the server VM frame
708                                 SV_VM_End();
709
710                                 // send an heartbeat if enough time has passed since the last one
711                                 NetConn_Heartbeat(0);
712                         }
713                 }
714
715         //-------------------
716         //
717         // client operations
718         //
719         //-------------------
720
721                 if (cl_timer > 0 || cls.timedemo)
722                 {
723                         if (cls.state == ca_dedicated)
724                         {
725                                 // if there is no client, run client timing at 10fps
726                                 cl_timer -= 0.1;
727                                 if (host_speeds.integer)
728                                         time1 = time2 = Sys_DoubleTime();
729                         }
730                         else
731                         {
732                                 double frametime;
733                                 frametime = cl.realframetime = min(cl_timer, 1);
734
735                                 // decide the simulation time
736                                 if (!cls.timedemo)
737                                 {
738                                         if (cls.capturevideo_active && !cls.capturevideo_soundfile)
739                                         {
740                                                 frametime = 1.0 / cls.capturevideo_framerate;
741                                                 cl.realframetime = max(cl.realframetime, frametime);
742                                         }
743                                         else if (vid_activewindow)
744                                                 frametime = cl.realframetime = max(cl.realframetime, 1.0 / cl_maxfps.value);
745                                         else
746                                                 frametime = cl.realframetime = 0.1;
747
748                                         // deduct the frame time from the accumulator
749                                         cl_timer -= cl.realframetime;
750
751                                         // apply slowmo scaling
752                                         frametime *= slowmo.value;
753
754                                         // host_framerate overrides all else
755                                         if (host_framerate.value)
756                                                 frametime = host_framerate.value;
757                                 }
758
759                                 cl.oldtime = cl.time;
760                                 cl.time += frametime;
761
762                                 // Collect input into cmd
763                                 CL_Move();
764
765                                 NetConn_ClientFrame();
766
767                                 if (cls.state == ca_connected)
768                                 {
769                                         CL_ReadFromServer();
770                                         // if running the server remotely, send intentions now after
771                                         // the incoming messages have been read
772                                         //if (!cl.islocalgame)
773                                         //      CL_SendCmd();
774                                 }
775
776                                 // update video
777                                 if (host_speeds.integer)
778                                         time1 = Sys_DoubleTime();
779
780                                 //ui_update();
781
782                                 CL_VideoFrame();
783
784                                 CL_UpdateScreen();
785
786                                 if (host_speeds.integer)
787                                         time2 = Sys_DoubleTime();
788
789                                 // update audio
790                                 if(csqc_usecsqclistener)
791                                 {
792                                         S_Update(&csqc_listenermatrix);
793                                         csqc_usecsqclistener = false;
794                                 }
795                                 else
796                                         S_Update(&r_view.matrix);
797
798                                 CDAudio_Update();
799                         }
800
801                         if (host_speeds.integer)
802                         {
803                                 int pass1, pass2, pass3;
804                                 pass1 = (int)((time1 - time3)*1000000);
805                                 time3 = Sys_DoubleTime();
806                                 pass2 = (int)((time2 - time1)*1000000);
807                                 pass3 = (int)((time3 - time2)*1000000);
808                                 Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
809                                                         pass1+pass2+pass3, pass1, pass2, pass3);
810                         }
811                 }
812
813                 host_framecount++;
814         }
815 }
816
817 //============================================================================
818
819 qboolean vid_opened = false;
820 void Host_StartVideo(void)
821 {
822         if (!vid_opened && cls.state != ca_dedicated)
823         {
824                 vid_opened = true;
825                 VID_Start();
826                 CDAudio_Startup();
827         }
828 }
829
830 char engineversion[128];
831
832 qboolean sys_nostdout = false;
833
834 extern void Render_Init(void);
835 extern void Mathlib_Init(void);
836 extern void FS_Init(void);
837 extern void FS_Shutdown(void);
838 extern void PR_Cmd_Init(void);
839 extern void COM_Init_Commands(void);
840 extern void FS_Init_Commands(void);
841 extern void COM_CheckRegistered(void);
842 extern qboolean host_stuffcmdsrun;
843
844 /*
845 ====================
846 Host_Init
847 ====================
848 */
849 static void Host_Init (void)
850 {
851         int i;
852         const char* os;
853
854         // FIXME: this is evil, but possibly temporary
855 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
856         if (COM_CheckParm("-developer"))
857         {
858                 developer.value = developer.integer = 100;
859                 developer.string = "100";
860         }
861
862         if (COM_CheckParm("-developer2"))
863         {
864                 developer.value = developer.integer = 100;
865                 developer.string = "100";
866                 developer_memory.value = developer_memory.integer = 100;
867                 developer.string = "100";
868                 developer_memorydebug.value = developer_memorydebug.integer = 100;
869                 developer_memorydebug.string = "100";
870         }
871
872         // LordHavoc: quake never seeded the random number generator before... heh
873         srand(time(NULL));
874
875         // used by everything
876         Memory_Init();
877
878         // initialize console and logging
879         Con_Init();
880
881         // initialize console command/cvar/alias/command execution systems
882         Cmd_Init();
883
884         // parse commandline
885         COM_InitArgv();
886
887         // initialize console window (only used by sys_win.c)
888         Sys_InitConsole();
889
890         // detect gamemode from commandline options or executable name
891         COM_InitGameType();
892
893         // construct a version string for the corner of the console
894 #if defined(__linux__)
895         os = "Linux";
896 #elif defined(WIN32)
897         os = "Windows";
898 #elif defined(__FreeBSD__)
899         os = "FreeBSD";
900 #elif defined(__NetBSD__)
901         os = "NetBSD";
902 #elif defined(__OpenBSD__)
903         os = "OpenBSD";
904 #elif defined(MACOSX)
905         os = "Mac OS X";
906 #elif defined(__MORPHOS__)
907         os = "MorphOS";
908 #else
909         os = "Unknown";
910 #endif
911         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
912
913 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
914         if (COM_CheckParm("-nostdout"))
915                 sys_nostdout = 1;
916         else
917                 Con_Printf("%s\n", engineversion);
918
919         // initialize filesystem (including fs_basedir, fs_gamedir, -path, -game, scr_screenshot_name)
920         FS_Init();
921
922         // initialize various cvars that could not be initialized earlier
923         Memory_Init_Commands();
924         Con_Init_Commands();
925         Cmd_Init_Commands();
926         Sys_Init_Commands();
927         COM_Init_Commands();
928         FS_Init_Commands();
929         COM_CheckRegistered();
930
931         // initialize ixtable
932         Mathlib_Init();
933
934         NetConn_Init();
935         //PR_Init();
936         //PR_Cmd_Init();
937         PRVM_Init();
938         Mod_Init();
939         SV_Init();
940         Host_InitCommands();
941         Host_InitLocal();
942         Host_ServerOptions();
943
944         if (cls.state != ca_dedicated)
945         {
946                 Con_Printf("Initializing client\n");
947
948                 R_Modules_Init();
949                 Palette_Init();
950                 MR_Init_Commands();
951                 VID_Shared_Init();
952                 VID_Init();
953                 Render_Init();
954                 S_Init();
955                 CDAudio_Init();
956                 Key_Init();
957                 V_Init();
958                 CL_Init();
959         }
960
961         // set up the default startmap_sp and startmap_dm aliases (mods can
962         // override these) and then execute the quake.rc startup script
963         if (gamemode == GAME_NEHAHRA)
964                 Cbuf_AddText("alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec quake.rc\n");
965         else if (gamemode == GAME_TRANSFUSION)
966                 Cbuf_AddText("alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec quake.rc\n");
967         else if (gamemode == GAME_TEU)
968                 Cbuf_AddText("alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
969         else
970                 Cbuf_AddText("alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec quake.rc\n");
971         Cbuf_Execute();
972
973         // if stuffcmds wasn't run, then quake.rc is probably missing, use default
974         if (!host_stuffcmdsrun)
975         {
976                 Cbuf_AddText("exec default.cfg\nexec config.cfg\nexec autoexec.cfg\nstuffcmds\n");
977                 Cbuf_Execute();
978         }
979
980         // put up the loading image so the user doesn't stare at a black screen...
981         SCR_BeginLoadingPlaque();
982
983         // FIXME: put this into some neat design, but the menu should be allowed to crash
984         // without crashing the whole game, so this should just be a short-time solution
985
986         // here comes the not so critical stuff
987         if (setjmp(host_abortframe)) {
988                 return;
989         }
990
991         if (cls.state != ca_dedicated)
992         {
993                 MR_Init();
994         }
995
996         // check for special benchmark mode
997 // COMMANDLINEOPTION: Client: -benchmark <demoname> runs a timedemo and quits, results of any timedemo can be found in gamedir/benchmark.log (for example id1/benchmark.log)
998         i = COM_CheckParm("-benchmark");
999         if (i && i + 1 < com_argc)
1000         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1001         {
1002                 Cbuf_AddText(va("timedemo %s\n", com_argv[i + 1]));
1003                 Cbuf_Execute();
1004         }
1005
1006         // check for special demo mode
1007 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
1008         i = COM_CheckParm("-demo");
1009         if (i && i + 1 < com_argc)
1010         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1011         {
1012                 Cbuf_AddText(va("playdemo %s\n", com_argv[i + 1]));
1013                 Cbuf_Execute();
1014         }
1015
1016         // check for special demolooponly mode
1017 // COMMANDLINEOPTION: Client: -demolooponly <demoname> runs a playdemo and quits
1018         i = COM_CheckParm("-demolooponly");
1019         if (i && i + 1 < com_argc)
1020         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1021         {
1022                 Cbuf_AddText(va("playdemo %s\n", com_argv[i + 1]));
1023                 Cbuf_Execute();
1024         }
1025
1026         if (cls.state == ca_dedicated || COM_CheckParm("-listen"))
1027         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1028         {
1029                 Cbuf_AddText("startmap_dm\n");
1030                 Cbuf_Execute();
1031         }
1032
1033         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1034         {
1035                 if (gamemode == GAME_NEXUIZ)
1036                         Cbuf_AddText("togglemenu\nplayvideo logo\ncd loop 1\n");
1037                 else
1038                         Cbuf_AddText("togglemenu\n");
1039                 Cbuf_Execute();
1040         }
1041
1042         Con_DPrint("========Initialized=========\n");
1043
1044         //Host_StartVideo();
1045 }
1046
1047
1048 /*
1049 ===============
1050 Host_Shutdown
1051
1052 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
1053 to run quit through here before the final handoff to the sys code.
1054 ===============
1055 */
1056 void Host_Shutdown(void)
1057 {
1058         static qboolean isdown = false;
1059
1060         if (isdown)
1061         {
1062                 Con_Print("recursive shutdown\n");
1063                 return;
1064         }
1065         isdown = true;
1066
1067         // be quiet while shutting down
1068         S_StopAllSounds();
1069
1070         // disconnect client from server if active
1071         CL_Disconnect();
1072
1073         // shut down local server if active
1074         Host_ShutdownServer ();
1075
1076         // Shutdown menu
1077         if(MR_Shutdown)
1078                 MR_Shutdown();
1079
1080         // AK shutdown PRVM
1081         // AK hmm, no PRVM_Shutdown(); yet
1082
1083         CL_Video_Shutdown();
1084
1085         Host_SaveConfig_f();
1086
1087         CDAudio_Shutdown ();
1088         S_Terminate ();
1089         NetConn_Shutdown ();
1090         //PR_Shutdown ();
1091
1092         if (cls.state != ca_dedicated)
1093         {
1094                 R_Modules_Shutdown();
1095                 VID_Shutdown();
1096         }
1097
1098         Cmd_Shutdown();
1099         CL_Shutdown();
1100         Sys_Shutdown();
1101         Log_Close();
1102         FS_Shutdown();
1103         Memory_Shutdown();
1104 }
1105