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