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