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