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