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