]> git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
Organize system and host globals into structs. Implement host state tracking
[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 "thread.h"
34 #include "utf8lib.h"
35
36 /*
37
38 A server can always be started, even if the system started out as a client
39 to a remote system.
40
41 A client can NOT be started if the system started as a dedicated server.
42
43 Memory is cleared / released when a server or client begins, not when they end.
44
45 */
46
47 // current client
48 client_t *host_client;
49
50 host_t host;
51
52 // pretend frames take this amount of time (in seconds), 0 = realtime
53 cvar_t host_framerate = {CVAR_CLIENT | CVAR_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"};
54 cvar_t cl_maxphysicsframesperserverframe = {CVAR_CLIENT, "cl_maxphysicsframesperserverframe","10", "maximum number of physics frames per server frame"};
55 // shows time used by certain subsystems
56 cvar_t host_speeds = {CVAR_CLIENT | CVAR_SERVER, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
57 cvar_t host_maxwait = {CVAR_CLIENT | CVAR_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."};
58 cvar_t cl_minfps = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps", "40", "minimum fps target - while the rendering performance is below this, it will drift toward lower quality"};
59 cvar_t cl_minfps_fade = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_fade", "1", "how fast the quality adapts to varying framerate"};
60 cvar_t cl_minfps_qualitymax = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitymax", "1", "highest allowed drawdistance multiplier"};
61 cvar_t cl_minfps_qualitymin = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitymin", "0.25", "lowest allowed drawdistance multiplier"};
62 cvar_t cl_minfps_qualitymultiply = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitymultiply", "0.2", "multiplier for quality changes in quality change per second render time (1 assumes linearity of quality and render time)"};
63 cvar_t cl_minfps_qualityhysteresis = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualityhysteresis", "0.05", "reduce all quality increments by this to reduce flickering"};
64 cvar_t cl_minfps_qualitystepmax = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitystepmax", "0.1", "maximum quality change in a single frame"};
65 cvar_t cl_minfps_force = {CVAR_CLIENT, "cl_minfps_force", "0", "also apply quality reductions in timedemo/capturevideo"};
66 cvar_t cl_maxfps = {CVAR_CLIENT | CVAR_SAVE, "cl_maxfps", "0", "maximum fps cap, 0 = unlimited, if game is running faster than this it will wait before running another frame (useful to make cpu time available to other programs)"};
67 cvar_t cl_maxfps_alwayssleep = {CVAR_CLIENT, "cl_maxfps_alwayssleep","1", "gives up some processing time to other applications each frame, value in milliseconds, disabled if cl_maxfps is 0"};
68 cvar_t cl_maxidlefps = {CVAR_CLIENT | CVAR_SAVE, "cl_maxidlefps", "20", "maximum fps cap when the game is not the active window (makes cpu time available to other programs"};
69
70 cvar_t developer = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "developer","0", "shows debugging messages and information (recommended for all developers and level designers); the value -1 also suppresses buffering and logging these messages"};
71 cvar_t developer_extra = {CVAR_CLIENT | CVAR_SERVER, "developer_extra", "0", "prints additional debugging messages, often very verbose!"};
72 cvar_t developer_insane = {CVAR_CLIENT | CVAR_SERVER, "developer_insane", "0", "prints huge streams of information about internal workings, entire contents of files being read/written, etc.  Not recommended!"};
73 cvar_t developer_loadfile = {CVAR_CLIENT | CVAR_SERVER, "developer_loadfile","0", "prints name and size of every file loaded via the FS_LoadFile function (which is almost everything)"};
74 cvar_t developer_loading = {CVAR_CLIENT | CVAR_SERVER, "developer_loading","0", "prints information about files as they are loaded or unloaded successfully"};
75 cvar_t developer_entityparsing = {CVAR_CLIENT, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
76
77 cvar_t timestamps = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "timestamps", "0", "prints timestamps on console messages"};
78 cvar_t timeformat = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
79
80 cvar_t sessionid = {CVAR_CLIENT | CVAR_SERVER | CVAR_READONLY, "sessionid", "", "ID of the current session (use the -sessionid parameter to set it); this is always either empty or begins with a dot (.)"};
81 cvar_t locksession = {CVAR_CLIENT | CVAR_SERVER, "locksession", "0", "Lock the session? 0 = no, 1 = yes and abort on failure, 2 = yes and continue on failure"};
82
83 /*
84 ================
85 Host_AbortCurrentFrame
86
87 aborts the current host frame and goes on with the next one
88 ================
89 */
90 void Host_AbortCurrentFrame(void) DP_FUNC_NORETURN;
91 void Host_AbortCurrentFrame(void)
92 {
93         // in case we were previously nice, make us mean again
94         Sys_MakeProcessMean();
95
96         longjmp (host.abortframe, 1);
97 }
98
99 /*
100 ================
101 Host_Error
102
103 This shuts down both the client and server
104 ================
105 */
106 void Host_Error (const char *error, ...)
107 {
108         static char hosterrorstring1[MAX_INPUTLINE]; // THREAD UNSAFE
109         static char hosterrorstring2[MAX_INPUTLINE]; // THREAD UNSAFE
110         static qboolean hosterror = false;
111         va_list argptr;
112
113         // turn off rcon redirect if it was active when the crash occurred
114         // to prevent loops when it is a networking problem
115         Con_Rcon_Redirect_Abort();
116
117         va_start (argptr,error);
118         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
119         va_end (argptr);
120
121         Con_Errorf("Host_Error: %s\n", hosterrorstring1);
122
123         // LadyHavoc: if crashing very early, or currently shutting down, do
124         // Sys_Error instead
125         if (host.framecount < 3 || host.state == host_shutdown)
126                 Sys_Error ("Host_Error: %s", hosterrorstring1);
127
128         if (hosterror)
129                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
130         hosterror = true;
131
132         strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
133
134         CL_Parse_DumpPacket();
135
136         CL_Parse_ErrorCleanUp();
137
138         //PR_Crash();
139
140         // print out where the crash happened, if it was caused by QC (and do a cleanup)
141         PRVM_Crash(SVVM_prog);
142         PRVM_Crash(CLVM_prog);
143 #ifdef CONFIG_MENU
144         PRVM_Crash(MVM_prog);
145 #endif
146
147         cl.csqc_loaded = false;
148         Cvar_SetValueQuick(&csqc_progcrc, -1);
149         Cvar_SetValueQuick(&csqc_progsize, -1);
150
151         SV_LockThreadMutex();
152         Host_ShutdownServer ();
153         SV_UnlockThreadMutex();
154
155         if (cls.state == ca_dedicated)
156                 Sys_Error ("Host_Error: %s",hosterrorstring2);  // dedicated servers exit
157
158         CL_Disconnect ();
159         cls.demonum = -1;
160
161         hosterror = false;
162
163         Host_AbortCurrentFrame();
164 }
165
166 static void Host_ServerOptions (void)
167 {
168         int i;
169
170         // general default
171         svs.maxclients = 8;
172
173 // COMMANDLINEOPTION: Server: -dedicated [playerlimit] starts a dedicated server (with a command console), default playerlimit is 8
174 // COMMANDLINEOPTION: Server: -listen [playerlimit] starts a multiplayer server with graphical client, like singleplayer but other players can connect, default playerlimit is 8
175         // if no client is in the executable or -dedicated is specified on
176         // commandline, start a dedicated server
177         i = COM_CheckParm ("-dedicated");
178         if (i || !cl_available)
179         {
180                 cls.state = ca_dedicated;
181                 // check for -dedicated specifying how many players
182                 if (i && i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
183                         svs.maxclients = atoi (sys.argv[i+1]);
184                 if (COM_CheckParm ("-listen"))
185                         Con_Printf ("Only one of -dedicated or -listen can be specified\n");
186                 // default sv_public on for dedicated servers (often hosted by serious administrators), off for listen servers (often hosted by clueless users)
187                 Cvar_SetValue(&cvars_all, "sv_public", 1);
188         }
189         else if (cl_available)
190         {
191                 // client exists and not dedicated, check if -listen is specified
192                 cls.state = ca_disconnected;
193                 i = COM_CheckParm ("-listen");
194                 if (i)
195                 {
196                         // default players unless specified
197                         if (i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
198                                 svs.maxclients = atoi (sys.argv[i+1]);
199                 }
200                 else
201                 {
202                         // default players in some games, singleplayer in most
203                         if (gamemode != GAME_GOODVSBAD2 && !IS_NEXUIZ_DERIVED(gamemode) && gamemode != GAME_BATTLEMECH)
204                                 svs.maxclients = 1;
205                 }
206         }
207
208         svs.maxclients = svs.maxclients_next = bound(1, svs.maxclients, MAX_SCOREBOARD);
209
210         svs.clients = (client_t *)Mem_Alloc(sv_mempool, sizeof(client_t) * svs.maxclients);
211
212         if (svs.maxclients > 1 && !deathmatch.integer && !coop.integer)
213                 Cvar_SetValueQuick(&deathmatch, 1);
214 }
215
216 /*
217 =======================
218 Host_InitLocal
219 ======================
220 */
221 void Host_SaveConfig_f(cmd_state_t *cmd);
222 void Host_LoadConfig_f(cmd_state_t *cmd);
223 extern cvar_t sv_writepicture_quality;
224 extern cvar_t r_texture_jpeg_fastpicmip;
225 static void Host_InitLocal (void)
226 {
227         Cmd_AddCommand(CMD_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
228         Cmd_AddCommand(CMD_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
229         Cvar_RegisterVariable (&cl_maxphysicsframesperserverframe);
230         Cvar_RegisterVariable (&host_framerate);
231         Cvar_RegisterVariable (&host_speeds);
232         Cvar_RegisterVariable (&host_maxwait);
233         Cvar_RegisterVariable (&cl_minfps);
234         Cvar_RegisterVariable (&cl_minfps_fade);
235         Cvar_RegisterVariable (&cl_minfps_qualitymax);
236         Cvar_RegisterVariable (&cl_minfps_qualitymin);
237         Cvar_RegisterVariable (&cl_minfps_qualitystepmax);
238         Cvar_RegisterVariable (&cl_minfps_qualityhysteresis);
239         Cvar_RegisterVariable (&cl_minfps_qualitymultiply);
240         Cvar_RegisterVariable (&cl_minfps_force);
241         Cvar_RegisterVariable (&cl_maxfps);
242         Cvar_RegisterVariable (&cl_maxfps_alwayssleep);
243         Cvar_RegisterVariable (&cl_maxidlefps);
244
245         Cvar_RegisterVariable (&developer);
246         Cvar_RegisterVariable (&developer_extra);
247         Cvar_RegisterVariable (&developer_insane);
248         Cvar_RegisterVariable (&developer_loadfile);
249         Cvar_RegisterVariable (&developer_loading);
250         Cvar_RegisterVariable (&developer_entityparsing);
251
252         Cvar_RegisterVariable (&timestamps);
253         Cvar_RegisterVariable (&timeformat);
254
255         Cvar_RegisterVariable (&sv_writepicture_quality);
256         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
257 }
258
259
260 /*
261 ===============
262 Host_SaveConfig_f
263
264 Writes key bindings and archived cvars to config.cfg
265 ===============
266 */
267 static void Host_SaveConfig_to(const char *file)
268 {
269         qfile_t *f;
270
271 // dedicated servers initialize the host but don't parse and set the
272 // config.cfg cvars
273         // LadyHavoc: don't save a config if it crashed in startup
274         if (host.framecount >= 3 && cls.state != ca_dedicated && !COM_CheckParm("-benchmark") && !COM_CheckParm("-capturedemo"))
275         {
276                 f = FS_OpenRealFile(file, "wb", false);
277                 if (!f)
278                 {
279                         Con_Errorf("Couldn't write %s.\n", file);
280                         return;
281                 }
282
283                 Key_WriteBindings (f);
284                 Cvar_WriteVariables (&cvars_all, f);
285
286                 FS_Close (f);
287         }
288 }
289 void Host_SaveConfig(void)
290 {
291         Host_SaveConfig_to(CONFIGFILENAME);
292 }
293 void Host_SaveConfig_f(cmd_state_t *cmd)
294 {
295         const char *file = CONFIGFILENAME;
296
297         if(Cmd_Argc(cmd) >= 2) {
298                 file = Cmd_Argv(cmd, 1);
299                 Con_Printf("Saving to %s\n", file);
300         }
301
302         Host_SaveConfig_to(file);
303 }
304
305 static void Host_AddConfigText(cmd_state_t *cmd)
306 {
307         // set up the default startmap_sp and startmap_dm aliases (mods can
308         // override these) and then execute the quake.rc startup script
309         if (gamemode == GAME_NEHAHRA)
310                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
311         else if (gamemode == GAME_TRANSFUSION)
312                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
313         else if (gamemode == GAME_TEU)
314                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
315         else
316                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
317         Cbuf_Execute(cmd);
318 }
319
320 /*
321 ===============
322 Host_LoadConfig_f
323
324 Resets key bindings and cvars to defaults and then reloads scripts
325 ===============
326 */
327 void Host_LoadConfig_f(cmd_state_t *cmd)
328 {
329         // reset all cvars, commands and aliases to init values
330         Cmd_RestoreInitState();
331 #ifdef CONFIG_MENU
332         // prepend a menu restart command to execute after the config
333         Cbuf_InsertText(&cmd_client, "\nmenu_restart\n");
334 #endif
335         // reset cvars to their defaults, and then exec startup scripts again
336         Host_AddConfigText(&cmd_client);
337 }
338
339 /*
340 =================
341 SV_ClientPrint
342
343 Sends text across to be displayed
344 FIXME: make this just a stuffed echo?
345 =================
346 */
347 void SV_ClientPrint(const char *msg)
348 {
349         if (host_client->netconnection)
350         {
351                 MSG_WriteByte(&host_client->netconnection->message, svc_print);
352                 MSG_WriteString(&host_client->netconnection->message, msg);
353         }
354 }
355
356 /*
357 =================
358 SV_ClientPrintf
359
360 Sends text across to be displayed
361 FIXME: make this just a stuffed echo?
362 =================
363 */
364 void SV_ClientPrintf(const char *fmt, ...)
365 {
366         va_list argptr;
367         char msg[MAX_INPUTLINE];
368
369         va_start(argptr,fmt);
370         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
371         va_end(argptr);
372
373         SV_ClientPrint(msg);
374 }
375
376 /*
377 =================
378 SV_BroadcastPrint
379
380 Sends text to all active clients
381 =================
382 */
383 void SV_BroadcastPrint(const char *msg)
384 {
385         int i;
386         client_t *client;
387
388         for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
389         {
390                 if (client->active && client->netconnection)
391                 {
392                         MSG_WriteByte(&client->netconnection->message, svc_print);
393                         MSG_WriteString(&client->netconnection->message, msg);
394                 }
395         }
396
397         if (sv_echobprint.integer && cls.state == ca_dedicated)
398                 Con_Print(msg);
399 }
400
401 /*
402 =================
403 SV_BroadcastPrintf
404
405 Sends text to all active clients
406 =================
407 */
408 void SV_BroadcastPrintf(const char *fmt, ...)
409 {
410         va_list argptr;
411         char msg[MAX_INPUTLINE];
412
413         va_start(argptr,fmt);
414         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
415         va_end(argptr);
416
417         SV_BroadcastPrint(msg);
418 }
419
420 /*
421 =================
422 Host_ClientCommands
423
424 Send text over to the client to be executed
425 =================
426 */
427 void Host_ClientCommands(const char *fmt, ...)
428 {
429         va_list argptr;
430         char string[MAX_INPUTLINE];
431
432         if (!host_client->netconnection)
433                 return;
434
435         va_start(argptr,fmt);
436         dpvsnprintf(string, sizeof(string), fmt, argptr);
437         va_end(argptr);
438
439         MSG_WriteByte(&host_client->netconnection->message, svc_stufftext);
440         MSG_WriteString(&host_client->netconnection->message, string);
441 }
442
443 /*
444 =====================
445 SV_DropClient
446
447 Called when the player is getting totally kicked off the host
448 if (crash = true), don't bother sending signofs
449 =====================
450 */
451 void SV_DropClient(qboolean crash)
452 {
453         prvm_prog_t *prog = SVVM_prog;
454         int i;
455         Con_Printf("Client \"%s\" dropped\n", host_client->name);
456
457         SV_StopDemoRecording(host_client);
458
459         // make sure edict is not corrupt (from a level change for example)
460         host_client->edict = PRVM_EDICT_NUM(host_client - svs.clients + 1);
461
462         if (host_client->netconnection)
463         {
464                 // tell the client to be gone
465                 if (!crash)
466                 {
467                         // LadyHavoc: no opportunity for resending, so use unreliable 3 times
468                         unsigned char bufdata[8];
469                         sizebuf_t buf;
470                         memset(&buf, 0, sizeof(buf));
471                         buf.data = bufdata;
472                         buf.maxsize = sizeof(bufdata);
473                         MSG_WriteByte(&buf, svc_disconnect);
474                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
475                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
476                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, 0, false);
477                 }
478         }
479
480         // call qc ClientDisconnect function
481         // LadyHavoc: don't call QC if server is dead (avoids recursive
482         // Host_Error in some mods when they run out of edicts)
483         if (host_client->clientconnectcalled && sv.active && host_client->edict)
484         {
485                 // call the prog function for removing a client
486                 // this will set the body to a dead frame, among other things
487                 int saveSelf = PRVM_serverglobaledict(self);
488                 host_client->clientconnectcalled = false;
489                 PRVM_serverglobalfloat(time) = sv.time;
490                 PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
491                 prog->ExecuteProgram(prog, PRVM_serverfunction(ClientDisconnect), "QC function ClientDisconnect is missing");
492                 PRVM_serverglobaledict(self) = saveSelf;
493         }
494
495         if (host_client->netconnection)
496         {
497                 // break the net connection
498                 NetConn_Close(host_client->netconnection);
499                 host_client->netconnection = NULL;
500         }
501
502         // if a download is active, close it
503         if (host_client->download_file)
504         {
505                 Con_DPrintf("Download of %s aborted when %s dropped\n", host_client->download_name, host_client->name);
506                 FS_Close(host_client->download_file);
507                 host_client->download_file = NULL;
508                 host_client->download_name[0] = 0;
509                 host_client->download_expectedposition = 0;
510                 host_client->download_started = false;
511         }
512
513         // remove leaving player from scoreboard
514         host_client->name[0] = 0;
515         host_client->colors = 0;
516         host_client->frags = 0;
517         // send notification to all clients
518         // get number of client manually just to make sure we get it right...
519         i = host_client - svs.clients;
520         MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
521         MSG_WriteByte (&sv.reliable_datagram, i);
522         MSG_WriteString (&sv.reliable_datagram, host_client->name);
523         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
524         MSG_WriteByte (&sv.reliable_datagram, i);
525         MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
526         MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
527         MSG_WriteByte (&sv.reliable_datagram, i);
528         MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
529
530         // free the client now
531         if (host_client->entitydatabase)
532                 EntityFrame_FreeDatabase(host_client->entitydatabase);
533         if (host_client->entitydatabase4)
534                 EntityFrame4_FreeDatabase(host_client->entitydatabase4);
535         if (host_client->entitydatabase5)
536                 EntityFrame5_FreeDatabase(host_client->entitydatabase5);
537
538         if (sv.active)
539         {
540                 // clear a fields that matter to DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS, and also frags
541                 PRVM_ED_ClearEdict(prog, host_client->edict);
542         }
543
544         // clear the client struct (this sets active to false)
545         memset(host_client, 0, sizeof(*host_client));
546
547         // update server listing on the master because player count changed
548         // (which the master uses for filtering empty/full servers)
549         NetConn_Heartbeat(1);
550
551         if (sv.loadgame)
552         {
553                 for (i = 0;i < svs.maxclients;i++)
554                         if (svs.clients[i].active && !svs.clients[i].spawned)
555                                 break;
556                 if (i == svs.maxclients)
557                 {
558                         Con_Printf("Loaded game, everyone rejoined - unpausing\n");
559                         sv.paused = sv.loadgame = false; // we're basically done with loading now
560                 }
561         }
562 }
563
564 /*
565 ==================
566 Host_ShutdownServer
567
568 This only happens at the end of a game, not between levels
569 ==================
570 */
571 void Host_ShutdownServer(void)
572 {
573         prvm_prog_t *prog = SVVM_prog;
574         int i;
575
576         Con_DPrintf("Host_ShutdownServer\n");
577
578         if (!sv.active)
579                 return;
580
581         NetConn_Heartbeat(2);
582         NetConn_Heartbeat(2);
583
584 // make sure all the clients know we're disconnecting
585         World_End(&sv.world);
586         if(prog->loaded)
587         {
588                 if(PRVM_serverfunction(SV_Shutdown))
589                 {
590                         func_t s = PRVM_serverfunction(SV_Shutdown);
591                         PRVM_serverglobalfloat(time) = sv.time;
592                         PRVM_serverfunction(SV_Shutdown) = 0; // prevent it from getting called again
593                         prog->ExecuteProgram(prog, s,"SV_Shutdown() required");
594                 }
595         }
596         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
597                 if (host_client->active)
598                         SV_DropClient(false); // server shutdown
599
600         NetConn_CloseServerPorts();
601
602         sv.active = false;
603 //
604 // clear structures
605 //
606         memset(&sv, 0, sizeof(sv));
607         memset(svs.clients, 0, svs.maxclients*sizeof(client_t));
608
609         cl.islocalgame = false;
610 }
611
612
613 //============================================================================
614
615 /*
616 ===================
617 Host_GetConsoleCommands
618
619 Add them exactly as if they had been typed at the console
620 ===================
621 */
622 static void Host_GetConsoleCommands (void)
623 {
624         char *line;
625
626         while ((line = Sys_ConsoleInput()))
627         {
628                 if (cls.state == ca_dedicated)
629                         Cbuf_AddText(&cmd_server, line);
630                 else
631                         Cbuf_AddText(&cmd_client, line);
632         }
633 }
634
635 /*
636 ==================
637 Host_TimeReport
638
639 Returns a time report string, for example for
640 ==================
641 */
642 const char *Host_TimingReport(char *buf, size_t buflen)
643 {
644         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);
645 }
646
647 /*
648 ==================
649 Host_Frame
650
651 Runs all active servers
652 ==================
653 */
654 static void Host_Init(void);
655 void Host_Main(void)
656 {
657         double time1 = 0;
658         double time2 = 0;
659         double time3 = 0;
660         double cl_timer = 0, sv_timer = 0;
661         double clframetime, deltacleantime, olddirtytime, dirtytime;
662         double wait;
663         int pass1, pass2, pass3, i;
664         char vabuf[1024];
665         qboolean playing;
666
667         Host_Init();
668
669         host.realtime = 0;
670         host.dirtytime = Sys_DirtyTime();
671         for (;;)
672         {
673                 if (setjmp(host.abortframe))
674                 {
675                         SCR_ClearLoadingScreen(false);
676                         continue;                       // something bad happened, or the server disconnected
677                 }
678
679                 olddirtytime = host.dirtytime;
680                 dirtytime = Sys_DirtyTime();
681                 deltacleantime = dirtytime - olddirtytime;
682                 if (deltacleantime < 0)
683                 {
684                         // warn if it's significant
685                         if (deltacleantime < -0.01)
686                                 Con_Warnf("Host_Mingled: time stepped backwards (went from %f to %f, difference %f)\n", olddirtytime, dirtytime, deltacleantime);
687                         deltacleantime = 0;
688                 }
689                 else if (deltacleantime >= 1800)
690                 {
691                         Con_Warnf("Host_Mingled: time stepped forward (went from %f to %f, difference %f)\n", olddirtytime, dirtytime, deltacleantime);
692                         deltacleantime = 0;
693                 }
694                 host.realtime += deltacleantime;
695                 host.dirtytime = dirtytime;
696
697                 cl_timer += deltacleantime;
698                 sv_timer += deltacleantime;
699
700                 if (!svs.threaded)
701                 {
702                         svs.perf_acc_realtime += deltacleantime;
703
704                         // Look for clients who have spawned
705                         playing = false;
706                         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
707                                 if(host_client->begun)
708                                         if(host_client->netconnection)
709                                                 playing = true;
710                         if(sv.time < 10)
711                         {
712                                 // don't accumulate time for the first 10 seconds of a match
713                                 // so things can settle
714                                 svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
715                         }
716                         else if(svs.perf_acc_realtime > 5)
717                         {
718                                 svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
719                                 svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
720                                 if(svs.perf_acc_offset_samples > 0)
721                                 {
722                                         svs.perf_offset_max = svs.perf_acc_offset_max;
723                                         svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
724                                         svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
725                                 }
726                                 if(svs.perf_lost > 0 && developer_extra.integer)
727                                         if(playing) // only complain if anyone is looking
728                                                 Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport(vabuf, sizeof(vabuf)));
729                                 svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
730                         }
731                 }
732
733                 if (host_framerate.value < 0.00001 && host_framerate.value != 0)
734                         Cvar_SetValueQuick(&host_framerate, 0);
735
736                 TaskQueue_Frame(false);
737
738                 // keep the random time dependent, but not when playing demos/benchmarking
739                 if(!*sv_random_seed.string && !cls.demoplayback)
740                         rand();
741
742                 // get new key events
743                 Key_EventQueue_Unblock();
744                 SndSys_SendKeyEvents();
745                 Sys_SendKeyEvents();
746
747                 NetConn_UpdateSockets();
748
749                 Log_DestBuffer_Flush();
750
751                 // receive packets on each main loop iteration, as the main loop may
752                 // be undersleeping due to select() detecting a new packet
753                 if (sv.active && !svs.threaded)
754                         NetConn_ServerFrame();
755
756                 Curl_Run();
757
758                 // check for commands typed to the host
759                 Host_GetConsoleCommands();
760
761                 // when a server is running we only execute console commands on server frames
762                 // (this mainly allows frikbot .way config files to work properly by staying in sync with the server qc)
763                 // otherwise we execute them on client frames
764                 if (sv.active ? sv_timer > 0 : cl_timer > 0)
765                 {
766                         // process console commands
767 //                      R_TimeReport("preconsole");
768                         CL_VM_PreventInformationLeaks();
769                         Cbuf_Frame(&cmd_client);
770                         Cbuf_Frame(&cmd_server);
771
772                         if(sv.active)
773                         {
774                                 Cbuf_Frame(&cmd_serverfromclient);
775                         }
776
777 //                      R_TimeReport("console");
778                 }
779
780                 //Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);
781
782                 // if the accumulators haven't become positive yet, wait a while
783                 if (cls.state == ca_dedicated)
784                         wait = sv_timer * -1000000.0;
785                 else if (!sv.active || svs.threaded)
786                         wait = cl_timer * -1000000.0;
787                 else
788                         wait = max(cl_timer, sv_timer) * -1000000.0;
789
790                 if (!cls.timedemo && wait >= 1)
791                 {
792                         double time0, delta;
793
794                         if(host_maxwait.value <= 0)
795                                 wait = min(wait, 1000000.0);
796                         else
797                                 wait = min(wait, host_maxwait.value * 1000.0);
798                         if(wait < 1)
799                                 wait = 1; // because we cast to int
800
801                         time0 = Sys_DirtyTime();
802                         if (sv_checkforpacketsduringsleep.integer && !sys_usenoclockbutbenchmark.integer && !svs.threaded) {
803                                 NetConn_SleepMicroseconds((int)wait);
804                                 if (cls.state != ca_dedicated)
805                                         NetConn_ClientFrame(); // helps server browser get good ping values
806                                 // TODO can we do the same for ServerFrame? Probably not.
807                         }
808                         else
809                                 Sys_Sleep((int)wait);
810                         delta = Sys_DirtyTime() - time0;
811                         if (delta < 0 || delta >= 1800) delta = 0;
812                         if (!svs.threaded)
813                                 svs.perf_acc_sleeptime += delta;
814 //                      R_TimeReport("sleep");
815                         continue;
816                 }
817
818                 // limit the frametime steps to no more than 100ms each
819                 if (cl_timer > 0.1)
820                         cl_timer = 0.1;
821                 if (sv_timer > 0.1)
822                 {
823                         if (!svs.threaded)
824                                 svs.perf_acc_lost += (sv_timer - 0.1);
825                         sv_timer = 0.1;
826                 }
827
828                 R_TimeReport("---");
829
830         //-------------------
831         //
832         // server operations
833         //
834         //-------------------
835
836                 // limit the frametime steps to no more than 100ms each
837                 if (sv.active && sv_timer > 0 && !svs.threaded)
838                 {
839                         // execute one or more server frames, with an upper limit on how much
840                         // execution time to spend on server frames to avoid freezing the game if
841                         // the server is overloaded, this execution time limit means the game will
842                         // slow down if the server is taking too long.
843                         int framecount, framelimit = 1;
844                         double advancetime, aborttime = 0;
845                         float offset;
846                         prvm_prog_t *prog = SVVM_prog;
847
848                         // run the world state
849                         // don't allow simulation to run too fast or too slow or logic glitches can occur
850
851                         // stop running server frames if the wall time reaches this value
852                         if (sys_ticrate.value <= 0)
853                                 advancetime = sv_timer;
854                         else if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
855                         {
856                                 // synchronize to the client frametime, but no less than 10ms and no more than 100ms
857                                 advancetime = bound(0.01, cl_timer, 0.1);
858                         }
859                         else
860                         {
861                                 advancetime = sys_ticrate.value;
862                                 // listen servers can run multiple server frames per client frame
863                                 framelimit = cl_maxphysicsframesperserverframe.integer;
864                                 aborttime = Sys_DirtyTime() + 0.1;
865                         }
866                         if(host_timescale.value > 0 && host_timescale.value < 1)
867                                 advancetime = min(advancetime, 0.1 / host_timescale.value);
868                         else
869                                 advancetime = min(advancetime, 0.1);
870
871                         if(advancetime > 0)
872                         {
873                                 offset = Sys_DirtyTime() - dirtytime;if (offset < 0 || offset >= 1800) offset = 0;
874                                 offset += sv_timer;
875                                 ++svs.perf_acc_offset_samples;
876                                 svs.perf_acc_offset += offset;
877                                 svs.perf_acc_offset_squared += offset * offset;
878                                 if(svs.perf_acc_offset_max < offset)
879                                         svs.perf_acc_offset_max = offset;
880                         }
881
882                         // only advance time if not paused
883                         // the game also pauses in singleplayer when menu or console is used
884                         sv.frametime = advancetime * host_timescale.value;
885                         if (host_framerate.value)
886                                 sv.frametime = host_framerate.value;
887                         if (sv.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive || cl.csqc_paused)))
888                                 sv.frametime = 0;
889
890                         for (framecount = 0;framecount < framelimit && sv_timer > 0;framecount++)
891                         {
892                                 sv_timer -= advancetime;
893
894                                 // move things around and think unless paused
895                                 if (sv.frametime)
896                                         SV_Physics();
897
898                                 // if this server frame took too long, break out of the loop
899                                 if (framelimit > 1 && Sys_DirtyTime() >= aborttime)
900                                         break;
901                         }
902                         R_TimeReport("serverphysics");
903
904                         // send all messages to the clients
905                         SV_SendClientMessages();
906
907                         if (sv.paused == 1 && host.realtime > sv.pausedstart && sv.pausedstart > 0) {
908                                 prog->globals.fp[OFS_PARM0] = host.realtime - sv.pausedstart;
909                                 PRVM_serverglobalfloat(time) = sv.time;
910                                 prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
911                         }
912
913                         // send an heartbeat if enough time has passed since the last one
914                         NetConn_Heartbeat(0);
915                         R_TimeReport("servernetwork");
916                 }
917                 else if (!svs.threaded)
918                 {
919                         // don't let r_speeds display jump around
920                         R_TimeReport("serverphysics");
921                         R_TimeReport("servernetwork");
922                 }
923
924         //-------------------
925         //
926         // client operations
927         //
928         //-------------------
929
930                 if (cls.state != ca_dedicated && (cl_timer > 0 || cls.timedemo || ((vid_activewindow ? cl_maxfps : cl_maxidlefps).value < 1)))
931                 {
932                         R_TimeReport("---");
933                         Collision_Cache_NewFrame();
934                         R_TimeReport("photoncache");
935                         // decide the simulation time
936                         if (cls.capturevideo.active)
937                         {
938                                 //***
939                                 if (cls.capturevideo.realtime)
940                                         clframetime = cl.realframetime = max(cl_timer, 1.0 / cls.capturevideo.framerate);
941                                 else
942                                 {
943                                         clframetime = 1.0 / cls.capturevideo.framerate;
944                                         cl.realframetime = max(cl_timer, clframetime);
945                                 }
946                         }
947                         else if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
948                         {
949                                 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxfps.value);
950                                 // when running slow, we need to sleep to keep input responsive
951                                 wait = bound(0, cl_maxfps_alwayssleep.value * 1000, 100000);
952                                 if (wait > 0)
953                                         Sys_Sleep((int)wait);
954                         }
955                         else if (!vid_activewindow && cl_maxidlefps.value >= 1 && !cls.timedemo)
956                                 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxidlefps.value);
957                         else
958                                 clframetime = cl.realframetime = cl_timer;
959
960                         // apply slowmo scaling
961                         clframetime *= cl.movevars_timescale;
962                         // scale playback speed of demos by slowmo cvar
963                         if (cls.demoplayback)
964                         {
965                                 clframetime *= host_timescale.value;
966                                 // if demo playback is paused, don't advance time at all
967                                 if (cls.demopaused)
968                                         clframetime = 0;
969                         }
970                         else
971                         {
972                                 // host_framerate overrides all else
973                                 if (host_framerate.value)
974                                         clframetime = host_framerate.value;
975
976                                 if (cl.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive || cl.csqc_paused)))
977                                         clframetime = 0;
978                         }
979
980                         if (cls.timedemo)
981                                 clframetime = cl.realframetime = cl_timer;
982
983                         // deduct the frame time from the accumulator
984                         cl_timer -= cl.realframetime;
985
986                         cl.oldtime = cl.time;
987                         cl.time += clframetime;
988
989                         // update video
990                         if (host_speeds.integer)
991                                 time1 = Sys_DirtyTime();
992                         R_TimeReport("pre-input");
993
994                         // Collect input into cmd
995                         CL_Input();
996
997                         R_TimeReport("input");
998
999                         // check for new packets
1000                         NetConn_ClientFrame();
1001
1002                         // read a new frame from a demo if needed
1003                         CL_ReadDemoMessage();
1004                         R_TimeReport("clientnetwork");
1005
1006                         // now that packets have been read, send input to server
1007                         CL_SendMove();
1008                         R_TimeReport("sendmove");
1009
1010                         // update client world (interpolate entities, create trails, etc)
1011                         CL_UpdateWorld();
1012                         R_TimeReport("lerpworld");
1013
1014                         CL_Video_Frame();
1015
1016                         R_TimeReport("client");
1017
1018                         CL_UpdateScreen();
1019                         R_TimeReport("render");
1020
1021                         if (host_speeds.integer)
1022                                 time2 = Sys_DirtyTime();
1023
1024                         // update audio
1025                         if(cl.csqc_usecsqclistener)
1026                         {
1027                                 S_Update(&cl.csqc_listenermatrix);
1028                                 cl.csqc_usecsqclistener = false;
1029                         }
1030                         else
1031                                 S_Update(&r_refdef.view.matrix);
1032
1033                         CDAudio_Update();
1034                         R_TimeReport("audio");
1035
1036                         // reset gathering of mouse input
1037                         in_mouse_x = in_mouse_y = 0;
1038
1039                         if (host_speeds.integer)
1040                         {
1041                                 pass1 = (int)((time1 - time3)*1000000);
1042                                 time3 = Sys_DirtyTime();
1043                                 pass2 = (int)((time2 - time1)*1000000);
1044                                 pass3 = (int)((time3 - time2)*1000000);
1045                                 Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
1046                                                         pass1+pass2+pass3, pass1, pass2, pass3);
1047                         }
1048                 }
1049
1050 #if MEMPARANOIA
1051                 Mem_CheckSentinelsGlobal();
1052 #else
1053                 if (developer_memorydebug.integer)
1054                         Mem_CheckSentinelsGlobal();
1055 #endif
1056
1057                 // if there is some time remaining from this frame, reset the timers
1058                 if (cl_timer >= 0)
1059                         cl_timer = 0;
1060                 if (sv_timer >= 0)
1061                 {
1062                         if (!svs.threaded)
1063                                 svs.perf_acc_lost += sv_timer;
1064                         sv_timer = 0;
1065                 }
1066
1067                 host.framecount++;
1068         }
1069 }
1070
1071 //============================================================================
1072
1073 qboolean vid_opened = false;
1074 void Host_StartVideo(void)
1075 {
1076         if (!vid_opened && cls.state != ca_dedicated)
1077         {
1078                 vid_opened = true;
1079                 // make sure we open sockets before opening video because the Windows Firewall "unblock?" dialog can screw up the graphics context on some graphics drivers
1080                 NetConn_UpdateSockets();
1081                 VID_Start();
1082                 CDAudio_Startup();
1083         }
1084 }
1085
1086 char engineversion[128];
1087
1088 qboolean sys_nostdout = false;
1089
1090 static qfile_t *locksession_fh = NULL;
1091 static qboolean locksession_run = false;
1092 static void Host_InitSession(void)
1093 {
1094         int i;
1095         char *buf;
1096         Cvar_RegisterVariable(&sessionid);
1097         Cvar_RegisterVariable(&locksession);
1098
1099         // load the session ID into the read-only cvar
1100         if ((i = COM_CheckParm("-sessionid")) && (i + 1 < sys.argc))
1101         {
1102                 if(sys.argv[i+1][0] == '.')
1103                         Cvar_SetQuick(&sessionid, sys.argv[i+1]);
1104                 else
1105                 {
1106                         buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
1107                         dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
1108                         Cvar_SetQuick(&sessionid, buf);
1109                 }
1110         }
1111 }
1112 void Host_LockSession(void)
1113 {
1114         if(locksession_run)
1115                 return;
1116         locksession_run = true;
1117         if(locksession.integer != 0 && !COM_CheckParm("-readonly"))
1118         {
1119                 char vabuf[1024];
1120                 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
1121                 FS_CreatePath(p);
1122                 locksession_fh = FS_SysOpen(p, "wl", false);
1123                 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
1124                 if(!locksession_fh)
1125                 {
1126                         if(locksession.integer == 2)
1127                         {
1128                                 Con_Warnf("WARNING: session lock %s could not be acquired. Please run with -sessionid and an unique session name. Continuing anyway.\n", p);
1129                         }
1130                         else
1131                         {
1132                                 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
1133                         }
1134                 }
1135         }
1136 }
1137 void Host_UnlockSession(void)
1138 {
1139         if(!locksession_run)
1140                 return;
1141         locksession_run = false;
1142
1143         if(locksession_fh)
1144         {
1145                 FS_Close(locksession_fh);
1146                 // NOTE: we can NOT unlink the lock here, as doing so would
1147                 // create a race condition if another process created it
1148                 // between our close and our unlink
1149                 locksession_fh = NULL;
1150         }
1151 }
1152
1153 /*
1154 ====================
1155 Host_Init
1156 ====================
1157 */
1158 static void Host_Init (void)
1159 {
1160         int i;
1161         const char* os;
1162         char vabuf[1024];
1163         qboolean dedicated_server = COM_CheckParm("-dedicated") || !cl_available;
1164         cmd_state_t *cmd = &cmd_client;
1165
1166         host.state = host_init;
1167
1168         if (COM_CheckParm("-profilegameonly"))
1169                 Sys_AllowProfiling(false);
1170
1171         // LadyHavoc: quake never seeded the random number generator before... heh
1172         if (COM_CheckParm("-benchmark"))
1173                 srand(0); // predictable random sequence for -benchmark
1174         else
1175                 srand((unsigned int)time(NULL));
1176
1177         // FIXME: this is evil, but possibly temporary
1178         // LadyHavoc: doesn't seem very temporary...
1179         // LadyHavoc: made this a saved cvar
1180 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
1181         if (COM_CheckParm("-developer"))
1182         {
1183                 developer.value = developer.integer = 1;
1184                 developer.string = "1";
1185         }
1186
1187         if (COM_CheckParm("-developer2") || COM_CheckParm("-developer3"))
1188         {
1189                 developer.value = developer.integer = 1;
1190                 developer.string = "1";
1191                 developer_extra.value = developer_extra.integer = 1;
1192                 developer_extra.string = "1";
1193                 developer_insane.value = developer_insane.integer = 1;
1194                 developer_insane.string = "1";
1195                 developer_memory.value = developer_memory.integer = 1;
1196                 developer_memory.string = "1";
1197                 developer_memorydebug.value = developer_memorydebug.integer = 1;
1198                 developer_memorydebug.string = "1";
1199         }
1200
1201         if (COM_CheckParm("-developer3"))
1202         {
1203                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
1204                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
1205         }
1206
1207 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
1208         if (COM_CheckParm("-nostdout"))
1209                 sys_nostdout = 1;
1210
1211         // used by everything
1212         Memory_Init();
1213
1214         // initialize console command/cvar/alias/command execution systems
1215         Cmd_Init();
1216
1217         Cmd_Init_Commands(dedicated_server);
1218
1219         // initialize memory subsystem cvars/commands
1220         Memory_Init_Commands();
1221
1222         // initialize console and logging and its cvars/commands
1223         Con_Init();
1224
1225         // initialize various cvars that could not be initialized earlier
1226         u8_Init();
1227         Curl_Init_Commands();
1228         Sys_Init_Commands();
1229         COM_Init_Commands();
1230         FS_Init_Commands();
1231
1232         // initialize console window (only used by sys_win.c)
1233         Sys_InitConsole();
1234
1235         // initialize the self-pack (must be before COM_InitGameType as it may add command line options)
1236         FS_Init_SelfPack();
1237
1238         // detect gamemode from commandline options or executable name
1239         COM_InitGameType();
1240
1241         // construct a version string for the corner of the console
1242         os = DP_OS_NAME;
1243         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
1244         Con_Printf("%s\n", engineversion);
1245
1246         // initialize process nice level
1247         Sys_InitProcessNice();
1248
1249         // initialize ixtable
1250         Mathlib_Init();
1251
1252         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
1253         FS_Init();
1254
1255         // register the cvars for session locking
1256         Host_InitSession();
1257
1258         // must be after FS_Init
1259         Crypto_Init();
1260         Crypto_Init_Commands();
1261
1262         NetConn_Init();
1263         Curl_Init();
1264         //PR_Init();
1265         //PR_Cmd_Init();
1266         PRVM_Init();
1267         Mod_Init();
1268         World_Init();
1269         SV_Init();
1270         V_Init(); // some cvars needed by server player physics (cl_rollangle etc)
1271         Host_InitCommands();
1272         Host_InitLocal();
1273         Host_ServerOptions();
1274
1275         Thread_Init();
1276         TaskQueue_Init();
1277
1278         CL_Init();
1279
1280         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
1281         // NOTE: menu commands are freed by Cmd_RestoreInitState
1282         Cmd_SaveInitState();
1283
1284         // FIXME: put this into some neat design, but the menu should be allowed to crash
1285         // without crashing the whole game, so this should just be a short-time solution
1286
1287         // here comes the not so critical stuff
1288         if (setjmp(host.abortframe)) {
1289                 return;
1290         }
1291
1292         Host_AddConfigText(cmd);
1293
1294         Host_StartVideo();
1295
1296         // if quake.rc is missing, use default
1297         if (!FS_FileExists("quake.rc"))
1298         {
1299                 Cbuf_AddText(cmd, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
1300                 Cbuf_Execute(cmd);
1301         }
1302
1303         host.state = host_active;
1304
1305         // run stuffcmds now, deferred previously because it can crash if a server starts that early
1306         Cbuf_AddText(cmd,"stuffcmds\n");
1307         Cbuf_Execute(cmd);
1308
1309         Log_Start();
1310         
1311         // put up the loading image so the user doesn't stare at a black screen...
1312         SCR_BeginLoadingPlaque(true);
1313
1314 #ifdef CONFIG_MENU
1315         if (cls.state != ca_dedicated)
1316         {
1317                 MR_Init();
1318         }
1319 #endif
1320
1321         // check for special benchmark mode
1322 // 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)
1323         i = COM_CheckParm("-benchmark");
1324         if (i && i + 1 < sys.argc)
1325         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1326         {
1327                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
1328                 Cbuf_Execute(&cmd_client);
1329         }
1330
1331         // check for special demo mode
1332 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
1333         i = COM_CheckParm("-demo");
1334         if (i && i + 1 < sys.argc)
1335         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1336         {
1337                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
1338                 Cbuf_Execute(&cmd_client);
1339         }
1340
1341 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
1342         i = COM_CheckParm("-capturedemo");
1343         if (i && i + 1 < sys.argc)
1344         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1345         {
1346                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
1347                 Cbuf_Execute(&cmd_client);
1348         }
1349
1350         if (cls.state == ca_dedicated || COM_CheckParm("-listen"))
1351         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1352         {
1353                 Cbuf_AddText(&cmd_client, "startmap_dm\n");
1354                 Cbuf_Execute(&cmd_client);
1355         }
1356
1357         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1358         {
1359 #ifdef CONFIG_MENU
1360                 Cbuf_AddText(&cmd_client, "togglemenu 1\n");
1361 #endif
1362                 Cbuf_Execute(&cmd_client);
1363         }
1364
1365         Con_DPrint("========Initialized=========\n");
1366
1367         //Host_StartVideo();
1368
1369         if (cls.state != ca_dedicated)
1370                 SV_StartThread();
1371 }
1372
1373
1374 /*
1375 ===============
1376 Host_Shutdown
1377
1378 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
1379 to run quit through here before the final handoff to the sys code.
1380 ===============
1381 */
1382 void Host_Shutdown(void)
1383 {
1384         static qboolean isdown = false;
1385
1386         if (isdown)
1387         {
1388                 Con_Print("recursive shutdown\n");
1389                 return;
1390         }
1391         if (setjmp(host.abortframe))
1392         {
1393                 Con_Print("aborted the quitting frame?!?\n");
1394                 return;
1395         }
1396         isdown = true;
1397
1398         // be quiet while shutting down
1399         S_StopAllSounds();
1400
1401         // end the server thread
1402         if (svs.threaded)
1403                 SV_StopThread();
1404
1405         // disconnect client from server if active
1406         CL_Disconnect();
1407
1408         // shut down local server if active
1409         SV_LockThreadMutex();
1410         Host_ShutdownServer ();
1411         SV_UnlockThreadMutex();
1412
1413 #ifdef CONFIG_MENU
1414         // Shutdown menu
1415         if(MR_Shutdown)
1416                 MR_Shutdown();
1417 #endif
1418
1419         // AK shutdown PRVM
1420         // AK hmm, no PRVM_Shutdown(); yet
1421
1422         CL_Video_Shutdown();
1423
1424         Host_SaveConfig();
1425
1426         CDAudio_Shutdown ();
1427         S_Terminate ();
1428         Curl_Shutdown ();
1429         NetConn_Shutdown ();
1430         //PR_Shutdown ();
1431
1432         if (cls.state != ca_dedicated)
1433         {
1434                 R_Modules_Shutdown();
1435                 VID_Shutdown();
1436         }
1437
1438         SV_StopThread();
1439         TaskQueue_Shutdown();
1440         Thread_Shutdown();
1441         Cmd_Shutdown();
1442         Key_Shutdown();
1443         CL_Shutdown();
1444         Sys_Shutdown();
1445         Log_Close();
1446         Crypto_Shutdown();
1447
1448         Host_UnlockSession();
1449
1450         S_Shutdown();
1451         Con_Shutdown();
1452         Memory_Shutdown();
1453 }
1454