]> git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
host: Remove unneeded includes
[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 /*
171 =======================
172 Host_InitLocal
173 ======================
174 */
175 void Host_SaveConfig_f(cmd_state_t *cmd);
176 void Host_LoadConfig_f(cmd_state_t *cmd);
177 extern cvar_t sv_writepicture_quality;
178 extern cvar_t r_texture_jpeg_fastpicmip;
179 static void Host_InitLocal (void)
180 {
181         Cmd_AddCommand(CF_SHARED, "quit", Host_Quit_f, "quit the game");
182         Cmd_AddCommand(CF_SHARED, "version", Host_Version_f, "print engine version");
183         Cmd_AddCommand(CF_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
184         Cmd_AddCommand(CF_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
185         Cvar_RegisterVariable (&cl_maxphysicsframesperserverframe);
186         Cvar_RegisterVariable (&host_framerate);
187         Cvar_RegisterCallback (&host_framerate, Host_Framerate_c);
188         Cvar_RegisterVariable (&host_speeds);
189         Cvar_RegisterVariable (&host_maxwait);
190         Cvar_RegisterVariable (&host_isclient);
191
192         Cvar_RegisterVariable (&developer);
193         Cvar_RegisterVariable (&developer_extra);
194         Cvar_RegisterVariable (&developer_insane);
195         Cvar_RegisterVariable (&developer_loadfile);
196         Cvar_RegisterVariable (&developer_loading);
197         Cvar_RegisterVariable (&developer_entityparsing);
198
199         Cvar_RegisterVariable (&timestamps);
200         Cvar_RegisterVariable (&timeformat);
201
202         Cvar_RegisterVariable (&sv_writepicture_quality);
203         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
204 }
205
206
207 /*
208 ===============
209 Host_SaveConfig_f
210
211 Writes key bindings and archived cvars to config.cfg
212 ===============
213 */
214 static void Host_SaveConfig_to(const char *file)
215 {
216         qfile_t *f;
217
218 // dedicated servers initialize the host but don't parse and set the
219 // config.cfg cvars
220         // LadyHavoc: don't save a config if it crashed in startup
221         if (host.framecount >= 3 && cls.state != ca_dedicated && !Sys_CheckParm("-benchmark") && !Sys_CheckParm("-capturedemo"))
222         {
223                 f = FS_OpenRealFile(file, "wb", false);
224                 if (!f)
225                 {
226                         Con_Printf(CON_ERROR "Couldn't write %s.\n", file);
227                         return;
228                 }
229
230                 Key_WriteBindings (f);
231                 Cvar_WriteVariables (&cvars_all, f);
232
233                 FS_Close (f);
234         }
235 }
236 void Host_SaveConfig(void)
237 {
238         Host_SaveConfig_to(CONFIGFILENAME);
239 }
240 void Host_SaveConfig_f(cmd_state_t *cmd)
241 {
242         const char *file = CONFIGFILENAME;
243
244         if(Cmd_Argc(cmd) >= 2) {
245                 file = Cmd_Argv(cmd, 1);
246                 Con_Printf("Saving to %s\n", file);
247         }
248
249         Host_SaveConfig_to(file);
250 }
251
252 static void Host_AddConfigText(cmd_state_t *cmd)
253 {
254         // set up the default startmap_sp and startmap_dm aliases (mods can
255         // override these) and then execute the quake.rc startup script
256         if (gamemode == GAME_NEHAHRA)
257                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
258         else if (gamemode == GAME_TRANSFUSION)
259                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
260         else if (gamemode == GAME_TEU)
261                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
262         else
263                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
264         Cbuf_Execute(cmd->cbuf);
265 }
266
267 /*
268 ===============
269 Host_LoadConfig_f
270
271 Resets key bindings and cvars to defaults and then reloads scripts
272 ===============
273 */
274 void Host_LoadConfig_f(cmd_state_t *cmd)
275 {
276         // reset all cvars, commands and aliases to init values
277         Cmd_RestoreInitState();
278 #ifdef CONFIG_MENU
279         // prepend a menu restart command to execute after the config
280         Cbuf_InsertText(&cmd_client, "\nmenu_restart\n");
281 #endif
282         // reset cvars to their defaults, and then exec startup scripts again
283         Host_AddConfigText(&cmd_client);
284 }
285
286 //============================================================================
287
288 /*
289 ===================
290 Host_GetConsoleCommands
291
292 Add them exactly as if they had been typed at the console
293 ===================
294 */
295 static void Host_GetConsoleCommands (void)
296 {
297         char *line;
298
299         while ((line = Sys_ConsoleInput()))
300         {
301                 if (cls.state == ca_dedicated)
302                         Cbuf_AddText(&cmd_server, line);
303                 else
304                         Cbuf_AddText(&cmd_client, line);
305         }
306 }
307
308 /*
309 ==================
310 Host_TimeReport
311
312 Returns a time report string, for example for
313 ==================
314 */
315 const char *Host_TimingReport(char *buf, size_t buflen)
316 {
317         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);
318 }
319
320 /*
321 ==================
322 Host_Frame
323
324 Runs all active servers
325 ==================
326 */
327 static void Host_Init(void);
328 double Host_Frame(double time)
329 {
330         double cl_timer = 0;
331         double sv_timer = 0;
332         static double wait;
333
334         TaskQueue_Frame(false);
335
336         // keep the random time dependent, but not when playing demos/benchmarking
337         if(!*sv_random_seed.string && !host.restless)
338                 rand();
339
340         NetConn_UpdateSockets();
341
342         Log_DestBuffer_Flush();
343
344         Curl_Run();
345
346         // check for commands typed to the host
347         Host_GetConsoleCommands();
348
349         // process console commands
350 //              R_TimeReport("preconsole");
351
352         Cbuf_Frame(host.cbuf);
353
354 //              R_TimeReport("console");
355
356         //Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);
357
358         R_TimeReport("---");
359
360         sv_timer = SV_Frame(time);
361         cl_timer = CL_Frame(time);
362
363         Mem_CheckSentinelsGlobal();
364
365         // if the accumulators haven't become positive yet, wait a while
366         if (cls.state == ca_dedicated)
367                 wait = sv_timer * -1000000.0; // dedicated
368         else if (!sv.active || svs.threaded)
369                 wait = cl_timer * -1000000.0; // connected to server, main menu, or server is on different thread
370         else
371                 wait = max(cl_timer, sv_timer) * -1000000.0; // listen server or singleplayer
372
373         if (!host.restless && wait >= 1)
374                 return wait;
375         else
376                 return 0;
377 }
378
379 static inline void Host_Sleep(double time)
380 {
381         static double delta;
382         double time0;
383
384         if(host_maxwait.value <= 0)
385                 time = min(time, 1000000.0);
386         else
387                 time = min(time, host_maxwait.value * 1000.0);
388         if(time < 1)
389                 time = 1; // because we cast to int
390
391         time0 = Sys_DirtyTime();
392         if (sv_checkforpacketsduringsleep.integer && !sys_usenoclockbutbenchmark.integer && !svs.threaded) {
393                 NetConn_SleepMicroseconds((int)time);
394                 if (cls.state != ca_dedicated)
395                         NetConn_ClientFrame(); // helps server browser get good ping values
396                 // TODO can we do the same for ServerFrame? Probably not.
397         }
398         else
399                 Sys_Sleep((int)time);
400         delta = Sys_DirtyTime() - time0;
401         if (delta < 0 || delta >= 1800) 
402                 delta = 0;
403         host.sleeptime += delta;
404 //                      R_TimeReport("sleep");
405         return;
406 }
407
408 // Cloudwalk: Most overpowered function declaration...
409 static inline double Host_UpdateTime (double newtime, double oldtime)
410 {
411         double time = newtime - oldtime;
412
413         if (time < 0)
414         {
415                 // warn if it's significant
416                 if (time < -0.01)
417                         Con_Printf(CON_WARN "Host_UpdateTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
418                 time = 0;
419         }
420         else if (time >= 1800)
421         {
422                 Con_Printf(CON_WARN "Host_UpdateTime: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
423                 time = 0;
424         }
425
426         return time;
427 }
428
429 void Host_Main(void)
430 {
431         double time, newtime, oldtime, sleeptime;
432
433         Host_Init(); // Start!
434
435         host.realtime = 0;
436         oldtime = Sys_DirtyTime();
437
438         // Main event loop
439         while(host.state != host_shutdown)
440         {
441                 // Something bad happened, or the server disconnected
442                 if (setjmp(host.abortframe))
443                 {
444                         host.state = host_active; // In case we were loading
445                         continue;
446                 }
447
448                 newtime = host.dirtytime = Sys_DirtyTime();
449                 host.realtime += time = Host_UpdateTime(newtime, oldtime);
450
451                 sleeptime = Host_Frame(time);
452                 oldtime = newtime;
453
454                 if (sleeptime)
455                 {
456                         Host_Sleep(sleeptime);
457                         continue;
458                 }
459
460                 host.framecount++;
461         }
462
463         return;
464 }
465
466 //============================================================================
467
468 char engineversion[128];
469
470 qbool sys_nostdout = false;
471
472 static qfile_t *locksession_fh = NULL;
473 static qbool locksession_run = false;
474 static void Host_InitSession(void)
475 {
476         int i;
477         char *buf;
478         Cvar_RegisterVariable(&sessionid);
479         Cvar_RegisterVariable(&locksession);
480
481         // load the session ID into the read-only cvar
482         if ((i = Sys_CheckParm("-sessionid")) && (i + 1 < sys.argc))
483         {
484                 if(sys.argv[i+1][0] == '.')
485                         Cvar_SetQuick(&sessionid, sys.argv[i+1]);
486                 else
487                 {
488                         buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
489                         dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
490                         Cvar_SetQuick(&sessionid, buf);
491                 }
492         }
493 }
494 void Host_LockSession(void)
495 {
496         if(locksession_run)
497                 return;
498         locksession_run = true;
499         if(locksession.integer != 0 && !Sys_CheckParm("-readonly"))
500         {
501                 char vabuf[1024];
502                 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
503                 FS_CreatePath(p);
504                 locksession_fh = FS_SysOpen(p, "wl", false);
505                 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
506                 if(!locksession_fh)
507                 {
508                         if(locksession.integer == 2)
509                         {
510                                 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);
511                         }
512                         else
513                         {
514                                 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
515                         }
516                 }
517         }
518 }
519 void Host_UnlockSession(void)
520 {
521         if(!locksession_run)
522                 return;
523         locksession_run = false;
524
525         if(locksession_fh)
526         {
527                 FS_Close(locksession_fh);
528                 // NOTE: we can NOT unlink the lock here, as doing so would
529                 // create a race condition if another process created it
530                 // between our close and our unlink
531                 locksession_fh = NULL;
532         }
533 }
534
535 /*
536 ====================
537 Host_Init
538 ====================
539 */
540 static void Host_Init (void)
541 {
542         int i;
543         const char* os;
544         char vabuf[1024];
545         cmd_state_t *cmd = &cmd_client;
546
547         host.hook.ConnectLocal = NULL;
548         host.hook.Disconnect = NULL;
549         host.hook.ToggleMenu = NULL;
550         host.hook.CL_Intermission = NULL;
551         host.hook.SV_CanSave = NULL;
552
553         host.state = host_init;
554
555         if (setjmp(host.abortframe)) // Huh?!
556                 Sys_Error("Engine initialization failed. Check the console (if available) for additional information.\n");
557
558         if (Sys_CheckParm("-profilegameonly"))
559                 Sys_AllowProfiling(false);
560
561         // LadyHavoc: quake never seeded the random number generator before... heh
562         if (Sys_CheckParm("-benchmark"))
563                 srand(0); // predictable random sequence for -benchmark
564         else
565                 srand((unsigned int)time(NULL));
566
567         // FIXME: this is evil, but possibly temporary
568         // LadyHavoc: doesn't seem very temporary...
569         // LadyHavoc: made this a saved cvar
570 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
571         if (Sys_CheckParm("-developer"))
572         {
573                 developer.value = developer.integer = 1;
574                 developer.string = "1";
575         }
576
577         if (Sys_CheckParm("-developer2") || Sys_CheckParm("-developer3"))
578         {
579                 developer.value = developer.integer = 1;
580                 developer.string = "1";
581                 developer_extra.value = developer_extra.integer = 1;
582                 developer_extra.string = "1";
583                 developer_insane.value = developer_insane.integer = 1;
584                 developer_insane.string = "1";
585                 developer_memory.value = developer_memory.integer = 1;
586                 developer_memory.string = "1";
587                 developer_memorydebug.value = developer_memorydebug.integer = 1;
588                 developer_memorydebug.string = "1";
589         }
590
591         if (Sys_CheckParm("-developer3"))
592         {
593                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
594                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
595         }
596
597 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
598         if (Sys_CheckParm("-nostdout"))
599                 sys_nostdout = 1;
600
601         // initialize console command/cvar/alias/command execution systems
602         Cmd_Init();
603
604         // initialize memory subsystem cvars/commands
605         Memory_Init_Commands();
606
607         // initialize console and logging and its cvars/commands
608         Con_Init();
609
610         // initialize various cvars that could not be initialized earlier
611         u8_Init();
612         Curl_Init_Commands();
613         Sys_Init_Commands();
614         COM_Init_Commands();
615
616         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
617         FS_Init();
618
619         // construct a version string for the corner of the console
620         os = DP_OS_NAME;
621         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
622         Con_Printf("%s\n", engineversion);
623
624         // initialize process nice level
625         Sys_InitProcessNice();
626
627         // initialize ixtable
628         Mathlib_Init();
629
630         // register the cvars for session locking
631         Host_InitSession();
632
633         // must be after FS_Init
634         Crypto_Init();
635         Crypto_Init_Commands();
636
637         NetConn_Init();
638         Curl_Init();
639         PRVM_Init();
640         Mod_Init();
641         World_Init();
642         SV_Init();
643         Host_InitLocal();
644
645         Thread_Init();
646         TaskQueue_Init();
647
648         CL_Init();
649
650         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
651         // NOTE: menu commands are freed by Cmd_RestoreInitState
652         Cmd_SaveInitState();
653
654         // FIXME: put this into some neat design, but the menu should be allowed to crash
655         // without crashing the whole game, so this should just be a short-time solution
656
657         // here comes the not so critical stuff
658
659         Host_AddConfigText(cmd);
660
661         // if quake.rc is missing, use default
662         if (!FS_FileExists("quake.rc"))
663         {
664                 Cbuf_AddText(cmd, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
665                 Cbuf_Execute(cmd->cbuf);
666         }
667
668         host.state = host_active;
669
670         CL_StartVideo();
671
672         Log_Start();
673
674         // put up the loading image so the user doesn't stare at a black screen...
675         SCR_BeginLoadingPlaque(true);
676 #ifdef CONFIG_MENU
677         if (cls.state != ca_dedicated)
678                 MR_Init();
679 #endif
680         // check for special benchmark mode
681 // 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)
682         i = Sys_CheckParm("-benchmark");
683         if (i && i + 1 < sys.argc)
684         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
685         {
686                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
687                 Cbuf_Execute((&cmd_client)->cbuf);
688         }
689
690         // check for special demo mode
691 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
692         i = Sys_CheckParm("-demo");
693         if (i && i + 1 < sys.argc)
694         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
695         {
696                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
697                 Cbuf_Execute((&cmd_client)->cbuf);
698         }
699
700 #ifdef CONFIG_VIDEO_CAPTURE
701 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
702         i = Sys_CheckParm("-capturedemo");
703         if (i && i + 1 < sys.argc)
704         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
705         {
706                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
707                 Cbuf_Execute((&cmd_client)->cbuf);
708         }
709 #endif
710
711         if (cls.state == ca_dedicated || Sys_CheckParm("-listen"))
712         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
713         {
714                 Cbuf_AddText(&cmd_client, "startmap_dm\n");
715                 Cbuf_Execute((&cmd_client)->cbuf);
716         }
717
718         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
719         {
720 #ifdef CONFIG_MENU
721                 Cbuf_AddText(&cmd_client, "togglemenu 1\n");
722 #endif
723                 Cbuf_Execute((&cmd_client)->cbuf);
724         }
725
726         Con_DPrint("========Initialized=========\n");
727
728         if (cls.state != ca_dedicated)
729                 SV_StartThread();
730 }
731
732
733 /*
734 ===============
735 Host_Shutdown
736
737 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
738 to run quit through here before the final handoff to the sys code.
739 ===============
740 */
741 void Host_Shutdown(void)
742 {
743         static qbool isdown = false;
744
745         if (isdown)
746         {
747                 Con_Print("recursive shutdown\n");
748                 return;
749         }
750         if (setjmp(host.abortframe))
751         {
752                 Con_Print("aborted the quitting frame?!?\n");
753                 return;
754         }
755         isdown = true;
756
757         if(cls.state != ca_dedicated)
758                 CL_Shutdown();
759
760         // end the server thread
761         if (svs.threaded)
762                 SV_StopThread();
763
764         // shut down local server if active
765         SV_LockThreadMutex();
766         SV_Shutdown ();
767         SV_UnlockThreadMutex();
768
769         // AK shutdown PRVM
770         // AK hmm, no PRVM_Shutdown(); yet
771
772         Host_SaveConfig();
773
774         Curl_Shutdown ();
775         NetConn_Shutdown ();
776
777         SV_StopThread();
778         TaskQueue_Shutdown();
779         Thread_Shutdown();
780         Cmd_Shutdown();
781         Sys_Shutdown();
782         Log_Close();
783         Crypto_Shutdown();
784
785         Host_UnlockSession();
786
787         Con_Shutdown();
788         Memory_Shutdown();
789 }
790
791 void Host_NoOperation_f(cmd_state_t *cmd)
792 {
793 }