]> git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
host: Move out some client and server code
[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 "quakedef.h"
23
24 #include <time.h>
25 #include "libcurl.h"
26 #include "cdaudio.h"
27 #include "cl_video.h"
28 #include "progsvm.h"
29 #include "csprogs.h"
30 #include "sv_demo.h"
31 #include "snd_main.h"
32 #include "taskqueue.h"
33 #include "utf8lib.h"
34
35 /*
36
37 A server can always be started, even if the system started out as a client
38 to a remote system.
39
40 A client can NOT be started if the system started as a dedicated server.
41
42 Memory is cleared / released when a server or client begins, not when they end.
43
44 */
45
46 host_t host;
47
48 // pretend frames take this amount of time (in seconds), 0 = realtime
49 cvar_t host_framerate = {CF_CLIENT | CF_SERVER, "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 cl_maxfps if you want to limit your framerate instead, or sys_ticrate to limit server speed"};
50 cvar_t cl_maxphysicsframesperserverframe = {CF_CLIENT, "cl_maxphysicsframesperserverframe","10", "maximum number of physics frames per server frame"};
51 // shows time used by certain subsystems
52 cvar_t host_speeds = {CF_CLIENT | CF_SERVER, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
53 cvar_t host_maxwait = {CF_CLIENT | CF_SERVER, "host_maxwait","1000", "maximum sleep time requested from the operating system in millisecond. Larger sleeps will be done using multiple host_maxwait length sleeps. Lowering this value will increase CPU load, but may help working around problems with accuracy of sleep times."};
54
55 cvar_t developer = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "developer","0", "shows debugging messages and information (recommended for all developers and level designers); the value -1 also suppresses buffering and logging these messages"};
56 cvar_t developer_extra = {CF_CLIENT | CF_SERVER, "developer_extra", "0", "prints additional debugging messages, often very verbose!"};
57 cvar_t developer_insane = {CF_CLIENT | CF_SERVER, "developer_insane", "0", "prints huge streams of information about internal workings, entire contents of files being read/written, etc.  Not recommended!"};
58 cvar_t developer_loadfile = {CF_CLIENT | CF_SERVER, "developer_loadfile","0", "prints name and size of every file loaded via the FS_LoadFile function (which is almost everything)"};
59 cvar_t developer_loading = {CF_CLIENT | CF_SERVER, "developer_loading","0", "prints information about files as they are loaded or unloaded successfully"};
60 cvar_t developer_entityparsing = {CF_CLIENT, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
61
62 cvar_t timestamps = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "timestamps", "0", "prints timestamps on console messages"};
63 cvar_t timeformat = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
64
65 cvar_t sessionid = {CF_CLIENT | CF_SERVER | CF_READONLY, "sessionid", "", "ID of the current session (use the -sessionid parameter to set it); this is always either empty or begins with a dot (.)"};
66 cvar_t locksession = {CF_CLIENT | CF_SERVER, "locksession", "0", "Lock the session? 0 = no, 1 = yes and abort on failure, 2 = yes and continue on failure"};
67
68 cvar_t host_isclient = {CF_SHARED | CF_READONLY, "_host_isclient", "0", "If 1, clientside is active."};
69
70 /*
71 ================
72 Host_AbortCurrentFrame
73
74 aborts the current host frame and goes on with the next one
75 ================
76 */
77 void Host_AbortCurrentFrame(void) DP_FUNC_NORETURN;
78 void Host_AbortCurrentFrame(void)
79 {
80         // in case we were previously nice, make us mean again
81         Sys_MakeProcessMean();
82
83         longjmp (host.abortframe, 1);
84 }
85
86 /*
87 ================
88 Host_Error
89
90 This shuts down both the client and server
91 ================
92 */
93 void Host_Error (const char *error, ...)
94 {
95         static char hosterrorstring1[MAX_INPUTLINE]; // THREAD UNSAFE
96         static char hosterrorstring2[MAX_INPUTLINE]; // THREAD UNSAFE
97         static qbool hosterror = false;
98         va_list argptr;
99
100         // turn off rcon redirect if it was active when the crash occurred
101         // to prevent loops when it is a networking problem
102         Con_Rcon_Redirect_Abort();
103
104         va_start (argptr,error);
105         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
106         va_end (argptr);
107
108         Con_Printf(CON_ERROR "Host_Error: %s\n", hosterrorstring1);
109
110         // LadyHavoc: if crashing very early, or currently shutting down, do
111         // Sys_Error instead
112         if (host.framecount < 3 || host.state == host_shutdown)
113                 Sys_Error ("Host_Error: %s", hosterrorstring1);
114
115         if (hosterror)
116                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
117         hosterror = true;
118
119         strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
120
121         CL_Parse_DumpPacket();
122
123         CL_Parse_ErrorCleanUp();
124
125         //PR_Crash();
126
127         // print out where the crash happened, if it was caused by QC (and do a cleanup)
128         PRVM_Crash(SVVM_prog);
129         PRVM_Crash(CLVM_prog);
130 #ifdef CONFIG_MENU
131         PRVM_Crash(MVM_prog);
132 #endif
133
134         Cvar_SetValueQuick(&csqc_progcrc, -1);
135         Cvar_SetValueQuick(&csqc_progsize, -1);
136
137         SV_LockThreadMutex();
138         SV_Shutdown ();
139         SV_UnlockThreadMutex();
140
141         if (cls.state == ca_dedicated)
142                 Sys_Error ("Host_Error: %s",hosterrorstring2);  // dedicated servers exit
143
144         CL_Disconnect ();
145         cls.demonum = -1;
146
147         hosterror = false;
148
149         Host_AbortCurrentFrame();
150 }
151
152 /*
153 ==================
154 Host_Quit_f
155 ==================
156 */
157 static void Host_Quit_f(cmd_state_t *cmd)
158 {
159         if(host.state == host_shutdown)
160                 Con_Printf("shutting down already!\n");
161         else
162                 host.state = host_shutdown;
163 }
164
165 static void Host_Version_f(cmd_state_t *cmd)
166 {
167         Con_Printf("Version: %s build %s\n", gamename, buildstring);
168 }
169
170 static void Host_Framerate_c(cvar_t *var)
171 {
172         if (var->value < 0.00001 && var->value != 0)
173                 Cvar_SetValueQuick(var, 0);
174 }
175
176 /*
177 =======================
178 Host_InitLocal
179 ======================
180 */
181 void Host_SaveConfig_f(cmd_state_t *cmd);
182 void Host_LoadConfig_f(cmd_state_t *cmd);
183 extern cvar_t sv_writepicture_quality;
184 extern cvar_t r_texture_jpeg_fastpicmip;
185 static void Host_InitLocal (void)
186 {
187         Cmd_AddCommand(CF_SHARED, "quit", Host_Quit_f, "quit the game");
188         Cmd_AddCommand(CF_SHARED, "version", Host_Version_f, "print engine version");
189         Cmd_AddCommand(CF_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
190         Cmd_AddCommand(CF_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
191         Cvar_RegisterVariable (&cl_maxphysicsframesperserverframe);
192         Cvar_RegisterVariable (&host_framerate);
193         Cvar_RegisterCallback (&host_framerate, Host_Framerate_c);
194         Cvar_RegisterVariable (&host_speeds);
195         Cvar_RegisterVariable (&host_maxwait);
196         Cvar_RegisterVariable (&host_isclient);
197
198         Cvar_RegisterVariable (&developer);
199         Cvar_RegisterVariable (&developer_extra);
200         Cvar_RegisterVariable (&developer_insane);
201         Cvar_RegisterVariable (&developer_loadfile);
202         Cvar_RegisterVariable (&developer_loading);
203         Cvar_RegisterVariable (&developer_entityparsing);
204
205         Cvar_RegisterVariable (&timestamps);
206         Cvar_RegisterVariable (&timeformat);
207
208         Cvar_RegisterVariable (&sv_writepicture_quality);
209         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
210 }
211
212
213 /*
214 ===============
215 Host_SaveConfig_f
216
217 Writes key bindings and archived cvars to config.cfg
218 ===============
219 */
220 static void Host_SaveConfig_to(const char *file)
221 {
222         qfile_t *f;
223
224 // dedicated servers initialize the host but don't parse and set the
225 // config.cfg cvars
226         // LadyHavoc: don't save a config if it crashed in startup
227         if (host.framecount >= 3 && cls.state != ca_dedicated && !Sys_CheckParm("-benchmark") && !Sys_CheckParm("-capturedemo"))
228         {
229                 f = FS_OpenRealFile(file, "wb", false);
230                 if (!f)
231                 {
232                         Con_Printf(CON_ERROR "Couldn't write %s.\n", file);
233                         return;
234                 }
235
236                 Key_WriteBindings (f);
237                 Cvar_WriteVariables (&cvars_all, f);
238
239                 FS_Close (f);
240         }
241 }
242 void Host_SaveConfig(void)
243 {
244         Host_SaveConfig_to(CONFIGFILENAME);
245 }
246 void Host_SaveConfig_f(cmd_state_t *cmd)
247 {
248         const char *file = CONFIGFILENAME;
249
250         if(Cmd_Argc(cmd) >= 2) {
251                 file = Cmd_Argv(cmd, 1);
252                 Con_Printf("Saving to %s\n", file);
253         }
254
255         Host_SaveConfig_to(file);
256 }
257
258 static void Host_AddConfigText(cmd_state_t *cmd)
259 {
260         // set up the default startmap_sp and startmap_dm aliases (mods can
261         // override these) and then execute the quake.rc startup script
262         if (gamemode == GAME_NEHAHRA)
263                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
264         else if (gamemode == GAME_TRANSFUSION)
265                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
266         else if (gamemode == GAME_TEU)
267                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
268         else
269                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
270         Cbuf_Execute(cmd->cbuf);
271 }
272
273 /*
274 ===============
275 Host_LoadConfig_f
276
277 Resets key bindings and cvars to defaults and then reloads scripts
278 ===============
279 */
280 void Host_LoadConfig_f(cmd_state_t *cmd)
281 {
282         // reset all cvars, commands and aliases to init values
283         Cmd_RestoreInitState();
284 #ifdef CONFIG_MENU
285         // prepend a menu restart command to execute after the config
286         Cbuf_InsertText(&cmd_client, "\nmenu_restart\n");
287 #endif
288         // reset cvars to their defaults, and then exec startup scripts again
289         Host_AddConfigText(&cmd_client);
290 }
291
292 //============================================================================
293
294 /*
295 ===================
296 Host_GetConsoleCommands
297
298 Add them exactly as if they had been typed at the console
299 ===================
300 */
301 static void Host_GetConsoleCommands (void)
302 {
303         char *line;
304
305         while ((line = Sys_ConsoleInput()))
306         {
307                 if (cls.state == ca_dedicated)
308                         Cbuf_AddText(&cmd_server, line);
309                 else
310                         Cbuf_AddText(&cmd_client, line);
311         }
312 }
313
314 /*
315 ==================
316 Host_TimeReport
317
318 Returns a time report string, for example for
319 ==================
320 */
321 const char *Host_TimingReport(char *buf, size_t buflen)
322 {
323         return va(buf, buflen, "%.1f%% CPU, %.2f%% lost, offset avg %.1fms, max %.1fms, sdev %.1fms", svs.perf_cpuload * 100, svs.perf_lost * 100, svs.perf_offset_avg * 1000, svs.perf_offset_max * 1000, svs.perf_offset_sdev * 1000);
324 }
325
326 /*
327 ==================
328 Host_Frame
329
330 Runs all active servers
331 ==================
332 */
333 static void Host_Init(void);
334 double Host_Frame(double time)
335 {
336         double cl_timer = 0;
337         double sv_timer = 0;
338         static double wait;
339
340         TaskQueue_Frame(false);
341
342         // keep the random time dependent, but not when playing demos/benchmarking
343         if(!*sv_random_seed.string && !host.restless)
344                 rand();
345
346         NetConn_UpdateSockets();
347
348         Log_DestBuffer_Flush();
349
350         Curl_Run();
351
352         // check for commands typed to the host
353         Host_GetConsoleCommands();
354
355         // process console commands
356 //              R_TimeReport("preconsole");
357
358         Cbuf_Frame(host.cbuf);
359
360 //              R_TimeReport("console");
361
362         //Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);
363
364         R_TimeReport("---");
365
366         sv_timer = SV_Frame(time);
367         cl_timer = CL_Frame(time);
368
369         Mem_CheckSentinelsGlobal();
370
371         // if the accumulators haven't become positive yet, wait a while
372         if (cls.state == ca_dedicated)
373                 wait = sv_timer * -1000000.0; // dedicated
374         else if (!sv.active || svs.threaded)
375                 wait = cl_timer * -1000000.0; // connected to server, main menu, or server is on different thread
376         else
377                 wait = max(cl_timer, sv_timer) * -1000000.0; // listen server or singleplayer
378
379         if (!host.restless && wait >= 1)
380                 return wait;
381         else
382                 return 0;
383 }
384
385 static inline void Host_Sleep(double time)
386 {
387         static double delta;
388         double time0;
389
390         if(host_maxwait.value <= 0)
391                 time = min(time, 1000000.0);
392         else
393                 time = min(time, host_maxwait.value * 1000.0);
394         if(time < 1)
395                 time = 1; // because we cast to int
396
397         time0 = Sys_DirtyTime();
398         if (sv_checkforpacketsduringsleep.integer && !sys_usenoclockbutbenchmark.integer && !svs.threaded) {
399                 NetConn_SleepMicroseconds((int)time);
400                 if (cls.state != ca_dedicated)
401                         NetConn_ClientFrame(); // helps server browser get good ping values
402                 // TODO can we do the same for ServerFrame? Probably not.
403         }
404         else
405                 Sys_Sleep((int)time);
406         delta = Sys_DirtyTime() - time0;
407         if (delta < 0 || delta >= 1800) 
408                 delta = 0;
409         host.sleeptime += delta;
410 //                      R_TimeReport("sleep");
411         return;
412 }
413
414 // Cloudwalk: Most overpowered function declaration...
415 static inline double Host_UpdateTime (double newtime, double oldtime)
416 {
417         double time = newtime - oldtime;
418
419         if (time < 0)
420         {
421                 // warn if it's significant
422                 if (time < -0.01)
423                         Con_Printf(CON_WARN "Host_UpdateTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
424                 time = 0;
425         }
426         else if (time >= 1800)
427         {
428                 Con_Printf(CON_WARN "Host_UpdateTime: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
429                 time = 0;
430         }
431
432         return time;
433 }
434
435 void Host_Main(void)
436 {
437         double time, newtime, oldtime, sleeptime;
438
439         Host_Init(); // Start!
440
441         host.realtime = 0;
442         oldtime = Sys_DirtyTime();
443
444         // Main event loop
445         while(host.state != host_shutdown)
446         {
447                 // Something bad happened, or the server disconnected
448                 if (setjmp(host.abortframe))
449                 {
450                         host.state = host_active; // In case we were loading
451                         continue;
452                 }
453
454                 newtime = host.dirtytime = Sys_DirtyTime();
455                 host.realtime += time = Host_UpdateTime(newtime, oldtime);
456
457                 sleeptime = Host_Frame(time);
458                 oldtime = newtime;
459
460                 if (sleeptime)
461                 {
462                         Host_Sleep(sleeptime);
463                         continue;
464                 }
465
466                 host.framecount++;
467         }
468
469         return;
470 }
471
472 //============================================================================
473
474 char engineversion[128];
475
476 qbool sys_nostdout = false;
477
478 static qfile_t *locksession_fh = NULL;
479 static qbool locksession_run = false;
480 static void Host_InitSession(void)
481 {
482         int i;
483         char *buf;
484         Cvar_RegisterVariable(&sessionid);
485         Cvar_RegisterVariable(&locksession);
486
487         // load the session ID into the read-only cvar
488         if ((i = Sys_CheckParm("-sessionid")) && (i + 1 < sys.argc))
489         {
490                 if(sys.argv[i+1][0] == '.')
491                         Cvar_SetQuick(&sessionid, sys.argv[i+1]);
492                 else
493                 {
494                         buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
495                         dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
496                         Cvar_SetQuick(&sessionid, buf);
497                 }
498         }
499 }
500 void Host_LockSession(void)
501 {
502         if(locksession_run)
503                 return;
504         locksession_run = true;
505         if(locksession.integer != 0 && !Sys_CheckParm("-readonly"))
506         {
507                 char vabuf[1024];
508                 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
509                 FS_CreatePath(p);
510                 locksession_fh = FS_SysOpen(p, "wl", false);
511                 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
512                 if(!locksession_fh)
513                 {
514                         if(locksession.integer == 2)
515                         {
516                                 Con_Printf(CON_WARN "WARNING: session lock %s could not be acquired. Please run with -sessionid and an unique session name. Continuing anyway.\n", p);
517                         }
518                         else
519                         {
520                                 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
521                         }
522                 }
523         }
524 }
525 void Host_UnlockSession(void)
526 {
527         if(!locksession_run)
528                 return;
529         locksession_run = false;
530
531         if(locksession_fh)
532         {
533                 FS_Close(locksession_fh);
534                 // NOTE: we can NOT unlink the lock here, as doing so would
535                 // create a race condition if another process created it
536                 // between our close and our unlink
537                 locksession_fh = NULL;
538         }
539 }
540
541 /*
542 ====================
543 Host_Init
544 ====================
545 */
546 static void Host_Init (void)
547 {
548         int i;
549         const char* os;
550         char vabuf[1024];
551         cmd_state_t *cmd = &cmd_client;
552
553         host.hook.ConnectLocal = NULL;
554         host.hook.Disconnect = NULL;
555         host.hook.ToggleMenu = NULL;
556         host.hook.CL_Intermission = NULL;
557         host.hook.SV_CanSave = NULL;
558
559         host.state = host_init;
560
561         if (setjmp(host.abortframe)) // Huh?!
562                 Sys_Error("Engine initialization failed. Check the console (if available) for additional information.\n");
563
564         if (Sys_CheckParm("-profilegameonly"))
565                 Sys_AllowProfiling(false);
566
567         // LadyHavoc: quake never seeded the random number generator before... heh
568         if (Sys_CheckParm("-benchmark"))
569                 srand(0); // predictable random sequence for -benchmark
570         else
571                 srand((unsigned int)time(NULL));
572
573         // FIXME: this is evil, but possibly temporary
574         // LadyHavoc: doesn't seem very temporary...
575         // LadyHavoc: made this a saved cvar
576 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
577         if (Sys_CheckParm("-developer"))
578         {
579                 developer.value = developer.integer = 1;
580                 developer.string = "1";
581         }
582
583         if (Sys_CheckParm("-developer2") || Sys_CheckParm("-developer3"))
584         {
585                 developer.value = developer.integer = 1;
586                 developer.string = "1";
587                 developer_extra.value = developer_extra.integer = 1;
588                 developer_extra.string = "1";
589                 developer_insane.value = developer_insane.integer = 1;
590                 developer_insane.string = "1";
591                 developer_memory.value = developer_memory.integer = 1;
592                 developer_memory.string = "1";
593                 developer_memorydebug.value = developer_memorydebug.integer = 1;
594                 developer_memorydebug.string = "1";
595         }
596
597         if (Sys_CheckParm("-developer3"))
598         {
599                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
600                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
601         }
602
603 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
604         if (Sys_CheckParm("-nostdout"))
605                 sys_nostdout = 1;
606
607         // initialize console command/cvar/alias/command execution systems
608         Cmd_Init();
609
610         // initialize memory subsystem cvars/commands
611         Memory_Init_Commands();
612
613         // initialize console and logging and its cvars/commands
614         Con_Init();
615
616         // initialize various cvars that could not be initialized earlier
617         u8_Init();
618         Curl_Init_Commands();
619         Sys_Init_Commands();
620         COM_Init_Commands();
621
622         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
623         FS_Init();
624
625         // construct a version string for the corner of the console
626         os = DP_OS_NAME;
627         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
628         Con_Printf("%s\n", engineversion);
629
630         // initialize process nice level
631         Sys_InitProcessNice();
632
633         // initialize ixtable
634         Mathlib_Init();
635
636         // register the cvars for session locking
637         Host_InitSession();
638
639         // must be after FS_Init
640         Crypto_Init();
641         Crypto_Init_Commands();
642
643         NetConn_Init();
644         Curl_Init();
645         PRVM_Init();
646         Mod_Init();
647         World_Init();
648         SV_Init();
649         Host_InitLocal();
650
651         Thread_Init();
652         TaskQueue_Init();
653
654         CL_Init();
655
656         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
657         // NOTE: menu commands are freed by Cmd_RestoreInitState
658         Cmd_SaveInitState();
659
660         // FIXME: put this into some neat design, but the menu should be allowed to crash
661         // without crashing the whole game, so this should just be a short-time solution
662
663         // here comes the not so critical stuff
664
665         Host_AddConfigText(cmd);
666
667         // if quake.rc is missing, use default
668         if (!FS_FileExists("quake.rc"))
669         {
670                 Cbuf_AddText(cmd, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
671                 Cbuf_Execute(cmd->cbuf);
672         }
673
674         host.state = host_active;
675
676         CL_StartVideo();
677
678         Log_Start();
679
680         // put up the loading image so the user doesn't stare at a black screen...
681         SCR_BeginLoadingPlaque(true);
682 #ifdef CONFIG_MENU
683         if (cls.state != ca_dedicated)
684                 MR_Init();
685 #endif
686         // check for special benchmark mode
687 // 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)
688         i = Sys_CheckParm("-benchmark");
689         if (i && i + 1 < sys.argc)
690         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
691         {
692                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
693                 Cbuf_Execute((&cmd_client)->cbuf);
694         }
695
696         // check for special demo mode
697 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
698         i = Sys_CheckParm("-demo");
699         if (i && i + 1 < sys.argc)
700         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
701         {
702                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
703                 Cbuf_Execute((&cmd_client)->cbuf);
704         }
705
706 #ifdef CONFIG_VIDEO_CAPTURE
707 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
708         i = Sys_CheckParm("-capturedemo");
709         if (i && i + 1 < sys.argc)
710         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
711         {
712                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
713                 Cbuf_Execute((&cmd_client)->cbuf);
714         }
715 #endif
716
717         if (cls.state == ca_dedicated || Sys_CheckParm("-listen"))
718         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
719         {
720                 Cbuf_AddText(&cmd_client, "startmap_dm\n");
721                 Cbuf_Execute((&cmd_client)->cbuf);
722         }
723
724         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
725         {
726 #ifdef CONFIG_MENU
727                 Cbuf_AddText(&cmd_client, "togglemenu 1\n");
728 #endif
729                 Cbuf_Execute((&cmd_client)->cbuf);
730         }
731
732         Con_DPrint("========Initialized=========\n");
733
734         if (cls.state != ca_dedicated)
735                 SV_StartThread();
736 }
737
738
739 /*
740 ===============
741 Host_Shutdown
742
743 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
744 to run quit through here before the final handoff to the sys code.
745 ===============
746 */
747 void Host_Shutdown(void)
748 {
749         static qbool isdown = false;
750
751         if (isdown)
752         {
753                 Con_Print("recursive shutdown\n");
754                 return;
755         }
756         if (setjmp(host.abortframe))
757         {
758                 Con_Print("aborted the quitting frame?!?\n");
759                 return;
760         }
761         isdown = true;
762
763         if(cls.state != ca_dedicated)
764                 CL_Shutdown();
765
766         // end the server thread
767         if (svs.threaded)
768                 SV_StopThread();
769
770         // shut down local server if active
771         SV_LockThreadMutex();
772         SV_Shutdown ();
773         SV_UnlockThreadMutex();
774
775         // AK shutdown PRVM
776         // AK hmm, no PRVM_Shutdown(); yet
777
778         Host_SaveConfig();
779
780         Curl_Shutdown ();
781         NetConn_Shutdown ();
782
783         SV_StopThread();
784         TaskQueue_Shutdown();
785         Thread_Shutdown();
786         Cmd_Shutdown();
787         Sys_Shutdown();
788         Log_Close();
789         Crypto_Shutdown();
790
791         Host_UnlockSession();
792
793         Con_Shutdown();
794         Memory_Shutdown();
795 }
796
797 void Host_NoOperation_f(cmd_state_t *cmd)
798 {
799 }