]> git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
(Round 3) Break up host_cmd.c
[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         SV_Shutdown ();
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_Quit_f
219 ==================
220 */
221 void Host_Quit_f(cmd_state_t *cmd)
222 {
223         if(host.state == host_shutdown)
224                 Con_Printf("shutting down already!\n");
225         else
226                 host.state = host_shutdown;
227 }
228
229 static void Host_Version_f(cmd_state_t *cmd)
230 {
231         Con_Printf("Version: %s build %s\n", gamename, buildstring);
232 }
233
234 /*
235 =======================
236 Host_InitLocal
237 ======================
238 */
239 void Host_SaveConfig_f(cmd_state_t *cmd);
240 void Host_LoadConfig_f(cmd_state_t *cmd);
241 extern cvar_t sv_writepicture_quality;
242 extern cvar_t r_texture_jpeg_fastpicmip;
243 static void Host_InitLocal (void)
244 {
245         Cmd_AddCommand(CMD_SHARED, "quit", Host_Quit_f, "quit the game");
246         Cmd_AddCommand(CMD_SHARED, "version", Host_Version_f, "print engine version");
247         Cmd_AddCommand(CMD_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
248         Cmd_AddCommand(CMD_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
249         Cvar_RegisterVariable (&cl_maxphysicsframesperserverframe);
250         Cvar_RegisterVariable (&host_framerate);
251         Cvar_RegisterVariable (&host_speeds);
252         Cvar_RegisterVariable (&host_maxwait);
253         Cvar_RegisterVariable (&cl_minfps);
254         Cvar_RegisterVariable (&cl_minfps_fade);
255         Cvar_RegisterVariable (&cl_minfps_qualitymax);
256         Cvar_RegisterVariable (&cl_minfps_qualitymin);
257         Cvar_RegisterVariable (&cl_minfps_qualitystepmax);
258         Cvar_RegisterVariable (&cl_minfps_qualityhysteresis);
259         Cvar_RegisterVariable (&cl_minfps_qualitymultiply);
260         Cvar_RegisterVariable (&cl_minfps_force);
261         Cvar_RegisterVariable (&cl_maxfps);
262         Cvar_RegisterVariable (&cl_maxfps_alwayssleep);
263         Cvar_RegisterVariable (&cl_maxidlefps);
264
265         Cvar_RegisterVariable (&developer);
266         Cvar_RegisterVariable (&developer_extra);
267         Cvar_RegisterVariable (&developer_insane);
268         Cvar_RegisterVariable (&developer_loadfile);
269         Cvar_RegisterVariable (&developer_loading);
270         Cvar_RegisterVariable (&developer_entityparsing);
271
272         Cvar_RegisterVariable (&timestamps);
273         Cvar_RegisterVariable (&timeformat);
274
275         Cvar_RegisterVariable (&sv_writepicture_quality);
276         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
277 }
278
279
280 /*
281 ===============
282 Host_SaveConfig_f
283
284 Writes key bindings and archived cvars to config.cfg
285 ===============
286 */
287 static void Host_SaveConfig_to(const char *file)
288 {
289         qfile_t *f;
290
291 // dedicated servers initialize the host but don't parse and set the
292 // config.cfg cvars
293         // LadyHavoc: don't save a config if it crashed in startup
294         if (host.framecount >= 3 && cls.state != ca_dedicated && !COM_CheckParm("-benchmark") && !COM_CheckParm("-capturedemo"))
295         {
296                 f = FS_OpenRealFile(file, "wb", false);
297                 if (!f)
298                 {
299                         Con_Errorf("Couldn't write %s.\n", file);
300                         return;
301                 }
302
303                 Key_WriteBindings (f);
304                 Cvar_WriteVariables (&cvars_all, f);
305
306                 FS_Close (f);
307         }
308 }
309 void Host_SaveConfig(void)
310 {
311         Host_SaveConfig_to(CONFIGFILENAME);
312 }
313 void Host_SaveConfig_f(cmd_state_t *cmd)
314 {
315         const char *file = CONFIGFILENAME;
316
317         if(Cmd_Argc(cmd) >= 2) {
318                 file = Cmd_Argv(cmd, 1);
319                 Con_Printf("Saving to %s\n", file);
320         }
321
322         Host_SaveConfig_to(file);
323 }
324
325 static void Host_AddConfigText(cmd_state_t *cmd)
326 {
327         // set up the default startmap_sp and startmap_dm aliases (mods can
328         // override these) and then execute the quake.rc startup script
329         if (gamemode == GAME_NEHAHRA)
330                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
331         else if (gamemode == GAME_TRANSFUSION)
332                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
333         else if (gamemode == GAME_TEU)
334                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
335         else
336                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
337         Cbuf_Execute(cmd);
338 }
339
340 /*
341 ===============
342 Host_LoadConfig_f
343
344 Resets key bindings and cvars to defaults and then reloads scripts
345 ===============
346 */
347 void Host_LoadConfig_f(cmd_state_t *cmd)
348 {
349         // reset all cvars, commands and aliases to init values
350         Cmd_RestoreInitState();
351 #ifdef CONFIG_MENU
352         // prepend a menu restart command to execute after the config
353         Cbuf_InsertText(&cmd_client, "\nmenu_restart\n");
354 #endif
355         // reset cvars to their defaults, and then exec startup scripts again
356         Host_AddConfigText(&cmd_client);
357 }
358
359 //============================================================================
360
361 /*
362 ===================
363 Host_GetConsoleCommands
364
365 Add them exactly as if they had been typed at the console
366 ===================
367 */
368 static void Host_GetConsoleCommands (void)
369 {
370         char *line;
371
372         while ((line = Sys_ConsoleInput()))
373         {
374                 if (cls.state == ca_dedicated)
375                         Cbuf_AddText(&cmd_server, line);
376                 else
377                         Cbuf_AddText(&cmd_client, line);
378         }
379 }
380
381 /*
382 ==================
383 Host_TimeReport
384
385 Returns a time report string, for example for
386 ==================
387 */
388 const char *Host_TimingReport(char *buf, size_t buflen)
389 {
390         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);
391 }
392
393 /*
394 ==================
395 Host_Frame
396
397 Runs all active servers
398 ==================
399 */
400 static void Host_Init(void);
401 void Host_Main(void)
402 {
403         double time1 = 0;
404         double time2 = 0;
405         double time3 = 0;
406         double cl_timer = 0, sv_timer = 0;
407         double clframetime, time, oldtime, newtime;
408         double wait;
409         int pass1, pass2, pass3, i;
410         char vabuf[1024];
411         qboolean playing;
412
413         Host_Init();
414
415         host.realtime = 0;
416         host.dirtytime = Sys_DirtyTime();
417
418         while(host.state != host_shutdown)
419         {
420                 if (setjmp(host.abortframe))
421                 {
422                         SCR_ClearLoadingScreen(false);
423                         continue;                       // something bad happened, or the server disconnected
424                 }
425
426                 oldtime = host.dirtytime;
427                 newtime = Sys_DirtyTime();
428                 time = newtime - oldtime;
429                 if (time < 0)
430                 {
431                         // warn if it's significant
432                         if (time < -0.01)
433                                 Con_Warnf("Host_Mingled: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
434                         time = 0;
435                 }
436                 else if (time >= 1800)
437                 {
438                         Con_Warnf("Host_Mingled: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
439                         time = 0;
440                 }
441                 host.realtime += time;
442                 host.dirtytime = newtime;
443
444                 cl_timer += time;
445                 sv_timer += time;
446
447                 if (!svs.threaded)
448                 {
449                         svs.perf_acc_realtime += time;
450
451                         // Look for clients who have spawned
452                         playing = false;
453                         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
454                                 if(host_client->begun)
455                                         if(host_client->netconnection)
456                                                 playing = true;
457                         if(sv.time < 10)
458                         {
459                                 // don't accumulate time for the first 10 seconds of a match
460                                 // so things can settle
461                                 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;
462                         }
463                         else if(svs.perf_acc_realtime > 5)
464                         {
465                                 svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
466                                 svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
467                                 if(svs.perf_acc_offset_samples > 0)
468                                 {
469                                         svs.perf_offset_max = svs.perf_acc_offset_max;
470                                         svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
471                                         svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
472                                 }
473                                 if(svs.perf_lost > 0 && developer_extra.integer)
474                                         if(playing) // only complain if anyone is looking
475                                                 Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport(vabuf, sizeof(vabuf)));
476                                 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;
477                         }
478                 }
479
480                 if (host_framerate.value < 0.00001 && host_framerate.value != 0)
481                         Cvar_SetValueQuick(&host_framerate, 0);
482
483                 TaskQueue_Frame(false);
484
485                 // keep the random time dependent, but not when playing demos/benchmarking
486                 if(!*sv_random_seed.string && !cls.demoplayback)
487                         rand();
488
489                 // get new key events
490                 Key_EventQueue_Unblock();
491                 SndSys_SendKeyEvents();
492                 Sys_SendKeyEvents();
493
494                 NetConn_UpdateSockets();
495
496                 Log_DestBuffer_Flush();
497
498                 // receive packets on each main loop iteration, as the main loop may
499                 // be undersleeping due to select() detecting a new packet
500                 if (sv.active && !svs.threaded)
501                         NetConn_ServerFrame();
502
503                 Curl_Run();
504
505                 // check for commands typed to the host
506                 Host_GetConsoleCommands();
507
508                 // process console commands
509 //              R_TimeReport("preconsole");
510                 CL_VM_PreventInformationLeaks();
511                 Cbuf_Frame(&cmd_client);
512                 Cbuf_Frame(&cmd_server);
513
514                 if(sv.active)
515                         Cbuf_Frame(&cmd_serverfromclient);
516
517 //              R_TimeReport("console");
518
519                 //Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);
520
521                 // if the accumulators haven't become positive yet, wait a while
522                 if (cls.state == ca_dedicated)
523                         wait = sv_timer * -1000000.0;
524                 else if (!sv.active || svs.threaded)
525                         wait = cl_timer * -1000000.0;
526                 else
527                         wait = max(cl_timer, sv_timer) * -1000000.0;
528
529                 if (!cls.timedemo && wait >= 1)
530                 {
531                         double time0, delta;
532
533                         if(host_maxwait.value <= 0)
534                                 wait = min(wait, 1000000.0);
535                         else
536                                 wait = min(wait, host_maxwait.value * 1000.0);
537                         if(wait < 1)
538                                 wait = 1; // because we cast to int
539
540                         time0 = Sys_DirtyTime();
541                         if (sv_checkforpacketsduringsleep.integer && !sys_usenoclockbutbenchmark.integer && !svs.threaded) {
542                                 NetConn_SleepMicroseconds((int)wait);
543                                 if (cls.state != ca_dedicated)
544                                         NetConn_ClientFrame(); // helps server browser get good ping values
545                                 // TODO can we do the same for ServerFrame? Probably not.
546                         }
547                         else
548                                 Sys_Sleep((int)wait);
549                         delta = Sys_DirtyTime() - time0;
550                         if (delta < 0 || delta >= 1800) delta = 0;
551                         if (!svs.threaded)
552                                 svs.perf_acc_sleeptime += delta;
553 //                      R_TimeReport("sleep");
554                         continue;
555                 }
556
557                 // limit the frametime steps to no more than 100ms each
558                 if (cl_timer > 0.1)
559                         cl_timer = 0.1;
560                 if (sv_timer > 0.1)
561                 {
562                         if (!svs.threaded)
563                                 svs.perf_acc_lost += (sv_timer - 0.1);
564                         sv_timer = 0.1;
565                 }
566
567                 R_TimeReport("---");
568
569         //-------------------
570         //
571         // server operations
572         //
573         //-------------------
574
575                 // limit the frametime steps to no more than 100ms each
576                 if (sv.active && sv_timer > 0 && !svs.threaded)
577                 {
578                         // execute one or more server frames, with an upper limit on how much
579                         // execution time to spend on server frames to avoid freezing the game if
580                         // the server is overloaded, this execution time limit means the game will
581                         // slow down if the server is taking too long.
582                         int framecount, framelimit = 1;
583                         double advancetime, aborttime = 0;
584                         float offset;
585                         prvm_prog_t *prog = SVVM_prog;
586
587                         // run the world state
588                         // don't allow simulation to run too fast or too slow or logic glitches can occur
589
590                         // stop running server frames if the wall time reaches this value
591                         if (sys_ticrate.value <= 0)
592                                 advancetime = sv_timer;
593                         else if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
594                         {
595                                 // synchronize to the client frametime, but no less than 10ms and no more than 100ms
596                                 advancetime = bound(0.01, cl_timer, 0.1);
597                         }
598                         else
599                         {
600                                 advancetime = sys_ticrate.value;
601                                 // listen servers can run multiple server frames per client frame
602                                 framelimit = cl_maxphysicsframesperserverframe.integer;
603                                 aborttime = Sys_DirtyTime() + 0.1;
604                         }
605                         if(host_timescale.value > 0 && host_timescale.value < 1)
606                                 advancetime = min(advancetime, 0.1 / host_timescale.value);
607                         else
608                                 advancetime = min(advancetime, 0.1);
609
610                         if(advancetime > 0)
611                         {
612                                 offset = Sys_DirtyTime() - newtime;if (offset < 0 || offset >= 1800) offset = 0;
613                                 offset += sv_timer;
614                                 ++svs.perf_acc_offset_samples;
615                                 svs.perf_acc_offset += offset;
616                                 svs.perf_acc_offset_squared += offset * offset;
617                                 if(svs.perf_acc_offset_max < offset)
618                                         svs.perf_acc_offset_max = offset;
619                         }
620
621                         // only advance time if not paused
622                         // the game also pauses in singleplayer when menu or console is used
623                         sv.frametime = advancetime * host_timescale.value;
624                         if (host_framerate.value)
625                                 sv.frametime = host_framerate.value;
626                         if (sv.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive || cl.csqc_paused)))
627                                 sv.frametime = 0;
628
629                         for (framecount = 0;framecount < framelimit && sv_timer > 0;framecount++)
630                         {
631                                 sv_timer -= advancetime;
632
633                                 // move things around and think unless paused
634                                 if (sv.frametime)
635                                         SV_Physics();
636
637                                 // if this server frame took too long, break out of the loop
638                                 if (framelimit > 1 && Sys_DirtyTime() >= aborttime)
639                                         break;
640                         }
641                         R_TimeReport("serverphysics");
642
643                         // send all messages to the clients
644                         SV_SendClientMessages();
645
646                         if (sv.paused == 1 && host.realtime > sv.pausedstart && sv.pausedstart > 0) {
647                                 prog->globals.fp[OFS_PARM0] = host.realtime - sv.pausedstart;
648                                 PRVM_serverglobalfloat(time) = sv.time;
649                                 prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
650                         }
651
652                         // send an heartbeat if enough time has passed since the last one
653                         NetConn_Heartbeat(0);
654                         R_TimeReport("servernetwork");
655                 }
656                 else if (!svs.threaded)
657                 {
658                         // don't let r_speeds display jump around
659                         R_TimeReport("serverphysics");
660                         R_TimeReport("servernetwork");
661                 }
662
663         //-------------------
664         //
665         // client operations
666         //
667         //-------------------
668
669                 if (cls.state != ca_dedicated && (cl_timer > 0 || cls.timedemo || ((vid_activewindow ? cl_maxfps : cl_maxidlefps).value < 1)))
670                 {
671                         R_TimeReport("---");
672                         Collision_Cache_NewFrame();
673                         R_TimeReport("photoncache");
674 #ifdef CONFIG_VIDEO_CAPTURE
675                         // decide the simulation time
676                         if (cls.capturevideo.active)
677                         {
678                                 //***
679                                 if (cls.capturevideo.realtime)
680                                         clframetime = cl.realframetime = max(cl_timer, 1.0 / cls.capturevideo.framerate);
681                                 else
682                                 {
683                                         clframetime = 1.0 / cls.capturevideo.framerate;
684                                         cl.realframetime = max(cl_timer, clframetime);
685                                 }
686                         }
687                         else if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
688
689 #else
690                         if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
691 #endif
692                         {
693                                 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxfps.value);
694                                 // when running slow, we need to sleep to keep input responsive
695                                 wait = bound(0, cl_maxfps_alwayssleep.value * 1000, 100000);
696                                 if (wait > 0)
697                                         Sys_Sleep((int)wait);
698                         }
699                         else if (!vid_activewindow && cl_maxidlefps.value >= 1 && !cls.timedemo)
700                                 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxidlefps.value);
701                         else
702                                 clframetime = cl.realframetime = cl_timer;
703
704                         // apply slowmo scaling
705                         clframetime *= cl.movevars_timescale;
706                         // scale playback speed of demos by slowmo cvar
707                         if (cls.demoplayback)
708                         {
709                                 clframetime *= host_timescale.value;
710                                 // if demo playback is paused, don't advance time at all
711                                 if (cls.demopaused)
712                                         clframetime = 0;
713                         }
714                         else
715                         {
716                                 // host_framerate overrides all else
717                                 if (host_framerate.value)
718                                         clframetime = host_framerate.value;
719
720                                 if (cl.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive || cl.csqc_paused)))
721                                         clframetime = 0;
722                         }
723
724                         if (cls.timedemo)
725                                 clframetime = cl.realframetime = cl_timer;
726
727                         // deduct the frame time from the accumulator
728                         cl_timer -= cl.realframetime;
729
730                         cl.oldtime = cl.time;
731                         cl.time += clframetime;
732
733                         // update video
734                         if (host_speeds.integer)
735                                 time1 = Sys_DirtyTime();
736                         R_TimeReport("pre-input");
737
738                         // Collect input into cmd
739                         CL_Input();
740
741                         R_TimeReport("input");
742
743                         // check for new packets
744                         NetConn_ClientFrame();
745
746                         // read a new frame from a demo if needed
747                         CL_ReadDemoMessage();
748                         R_TimeReport("clientnetwork");
749
750                         // now that packets have been read, send input to server
751                         CL_SendMove();
752                         R_TimeReport("sendmove");
753
754                         // update client world (interpolate entities, create trails, etc)
755                         CL_UpdateWorld();
756                         R_TimeReport("lerpworld");
757
758                         CL_Video_Frame();
759
760                         R_TimeReport("client");
761
762                         CL_UpdateScreen();
763                         R_TimeReport("render");
764
765                         if (host_speeds.integer)
766                                 time2 = Sys_DirtyTime();
767
768                         // update audio
769                         if(cl.csqc_usecsqclistener)
770                         {
771                                 S_Update(&cl.csqc_listenermatrix);
772                                 cl.csqc_usecsqclistener = false;
773                         }
774                         else
775                                 S_Update(&r_refdef.view.matrix);
776
777                         CDAudio_Update();
778                         R_TimeReport("audio");
779
780                         // reset gathering of mouse input
781                         in_mouse_x = in_mouse_y = 0;
782
783                         if (host_speeds.integer)
784                         {
785                                 pass1 = (int)((time1 - time3)*1000000);
786                                 time3 = Sys_DirtyTime();
787                                 pass2 = (int)((time2 - time1)*1000000);
788                                 pass3 = (int)((time3 - time2)*1000000);
789                                 Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
790                                                         pass1+pass2+pass3, pass1, pass2, pass3);
791                         }
792                 }
793
794 #if MEMPARANOIA
795                 Mem_CheckSentinelsGlobal();
796 #else
797                 if (developer_memorydebug.integer)
798                         Mem_CheckSentinelsGlobal();
799 #endif
800
801                 // if there is some time remaining from this frame, reset the timers
802                 if (cl_timer >= 0)
803                         cl_timer = 0;
804                 if (sv_timer >= 0)
805                 {
806                         if (!svs.threaded)
807                                 svs.perf_acc_lost += sv_timer;
808                         sv_timer = 0;
809                 }
810
811                 host.framecount++;
812         }
813
814         Sys_Quit(0);
815 }
816
817 //============================================================================
818
819 qboolean vid_opened = false;
820 void Host_StartVideo(void)
821 {
822         if (!vid_opened && cls.state != ca_dedicated)
823         {
824                 vid_opened = true;
825                 // make sure we open sockets before opening video because the Windows Firewall "unblock?" dialog can screw up the graphics context on some graphics drivers
826                 NetConn_UpdateSockets();
827                 VID_Start();
828                 CDAudio_Startup();
829         }
830 }
831
832 char engineversion[128];
833
834 qboolean sys_nostdout = false;
835
836 static qfile_t *locksession_fh = NULL;
837 static qboolean locksession_run = false;
838 static void Host_InitSession(void)
839 {
840         int i;
841         char *buf;
842         Cvar_RegisterVariable(&sessionid);
843         Cvar_RegisterVariable(&locksession);
844
845         // load the session ID into the read-only cvar
846         if ((i = COM_CheckParm("-sessionid")) && (i + 1 < sys.argc))
847         {
848                 if(sys.argv[i+1][0] == '.')
849                         Cvar_SetQuick(&sessionid, sys.argv[i+1]);
850                 else
851                 {
852                         buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
853                         dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
854                         Cvar_SetQuick(&sessionid, buf);
855                 }
856         }
857 }
858 void Host_LockSession(void)
859 {
860         if(locksession_run)
861                 return;
862         locksession_run = true;
863         if(locksession.integer != 0 && !COM_CheckParm("-readonly"))
864         {
865                 char vabuf[1024];
866                 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
867                 FS_CreatePath(p);
868                 locksession_fh = FS_SysOpen(p, "wl", false);
869                 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
870                 if(!locksession_fh)
871                 {
872                         if(locksession.integer == 2)
873                         {
874                                 Con_Warnf("WARNING: session lock %s could not be acquired. Please run with -sessionid and an unique session name. Continuing anyway.\n", p);
875                         }
876                         else
877                         {
878                                 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
879                         }
880                 }
881         }
882 }
883 void Host_UnlockSession(void)
884 {
885         if(!locksession_run)
886                 return;
887         locksession_run = false;
888
889         if(locksession_fh)
890         {
891                 FS_Close(locksession_fh);
892                 // NOTE: we can NOT unlink the lock here, as doing so would
893                 // create a race condition if another process created it
894                 // between our close and our unlink
895                 locksession_fh = NULL;
896         }
897 }
898
899 /*
900 ====================
901 Host_Init
902 ====================
903 */
904 static void Host_Init (void)
905 {
906         int i;
907         const char* os;
908         char vabuf[1024];
909         cmd_state_t *cmd = &cmd_client;
910
911         host.state = host_init;
912
913         if (COM_CheckParm("-profilegameonly"))
914                 Sys_AllowProfiling(false);
915
916         // LadyHavoc: quake never seeded the random number generator before... heh
917         if (COM_CheckParm("-benchmark"))
918                 srand(0); // predictable random sequence for -benchmark
919         else
920                 srand((unsigned int)time(NULL));
921
922         // FIXME: this is evil, but possibly temporary
923         // LadyHavoc: doesn't seem very temporary...
924         // LadyHavoc: made this a saved cvar
925 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
926         if (COM_CheckParm("-developer"))
927         {
928                 developer.value = developer.integer = 1;
929                 developer.string = "1";
930         }
931
932         if (COM_CheckParm("-developer2") || COM_CheckParm("-developer3"))
933         {
934                 developer.value = developer.integer = 1;
935                 developer.string = "1";
936                 developer_extra.value = developer_extra.integer = 1;
937                 developer_extra.string = "1";
938                 developer_insane.value = developer_insane.integer = 1;
939                 developer_insane.string = "1";
940                 developer_memory.value = developer_memory.integer = 1;
941                 developer_memory.string = "1";
942                 developer_memorydebug.value = developer_memorydebug.integer = 1;
943                 developer_memorydebug.string = "1";
944         }
945
946         if (COM_CheckParm("-developer3"))
947         {
948                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
949                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
950         }
951
952 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
953         if (COM_CheckParm("-nostdout"))
954                 sys_nostdout = 1;
955
956         // used by everything
957         Memory_Init();
958
959         // initialize console command/cvar/alias/command execution systems
960         Cmd_Init();
961
962         // initialize memory subsystem cvars/commands
963         Memory_Init_Commands();
964
965         // initialize console and logging and its cvars/commands
966         Con_Init();
967
968         // initialize various cvars that could not be initialized earlier
969         u8_Init();
970         Curl_Init_Commands();
971         Sys_Init_Commands();
972         COM_Init_Commands();
973
974         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
975         FS_Init();
976
977         // construct a version string for the corner of the console
978         os = DP_OS_NAME;
979         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
980         Con_Printf("%s\n", engineversion);
981
982         // initialize process nice level
983         Sys_InitProcessNice();
984
985         // initialize ixtable
986         Mathlib_Init();
987
988         // register the cvars for session locking
989         Host_InitSession();
990
991         // must be after FS_Init
992         Crypto_Init();
993         Crypto_Init_Commands();
994
995         NetConn_Init();
996         Curl_Init();
997         PRVM_Init();
998         Mod_Init();
999         World_Init();
1000         SV_Init();
1001         V_Init(); // some cvars needed by server player physics (cl_rollangle etc)
1002         Host_InitCommands();
1003         Host_InitLocal();
1004         Host_ServerOptions();
1005
1006         Thread_Init();
1007         TaskQueue_Init();
1008
1009         CL_Init();
1010
1011         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
1012         // NOTE: menu commands are freed by Cmd_RestoreInitState
1013         Cmd_SaveInitState();
1014
1015         // FIXME: put this into some neat design, but the menu should be allowed to crash
1016         // without crashing the whole game, so this should just be a short-time solution
1017
1018         // here comes the not so critical stuff
1019         if (setjmp(host.abortframe)) {
1020                 return;
1021         }
1022
1023         Host_AddConfigText(cmd);
1024
1025         Host_StartVideo();
1026
1027         // if quake.rc is missing, use default
1028         if (!FS_FileExists("quake.rc"))
1029         {
1030                 Cbuf_InsertText(cmd, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
1031                 Cbuf_Execute(cmd);
1032         }
1033
1034         host.state = host_active;
1035
1036         // run stuffcmds now, deferred previously because it can crash if a server starts that early
1037         Cbuf_AddText(cmd,"stuffcmds\n");
1038         Cbuf_Execute(cmd);
1039
1040         Log_Start();
1041
1042         // put up the loading image so the user doesn't stare at a black screen...
1043         SCR_BeginLoadingPlaque(true);
1044         
1045         // check for special benchmark mode
1046 // 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)
1047         i = COM_CheckParm("-benchmark");
1048         if (i && i + 1 < sys.argc)
1049         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1050         {
1051                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
1052                 Cbuf_Execute(&cmd_client);
1053         }
1054
1055         // check for special demo mode
1056 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
1057         i = COM_CheckParm("-demo");
1058         if (i && i + 1 < sys.argc)
1059         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1060         {
1061                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
1062                 Cbuf_Execute(&cmd_client);
1063         }
1064
1065 #ifdef CONFIG_VIDEO_CAPTURE
1066 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
1067         i = COM_CheckParm("-capturedemo");
1068         if (i && i + 1 < sys.argc)
1069         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1070         {
1071                 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
1072                 Cbuf_Execute(&cmd_client);
1073         }
1074 #endif
1075
1076         if (cls.state == ca_dedicated || COM_CheckParm("-listen"))
1077         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1078         {
1079                 Cbuf_AddText(&cmd_client, "startmap_dm\n");
1080                 Cbuf_Execute(&cmd_client);
1081         }
1082
1083         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1084         {
1085 #ifdef CONFIG_MENU
1086                 Cbuf_AddText(&cmd_client, "togglemenu 1\n");
1087 #endif
1088                 Cbuf_Execute(&cmd_client);
1089         }
1090
1091         Con_DPrint("========Initialized=========\n");
1092
1093         if (cls.state != ca_dedicated)
1094                 SV_StartThread();
1095 }
1096
1097
1098 /*
1099 ===============
1100 Host_Shutdown
1101
1102 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
1103 to run quit through here before the final handoff to the sys code.
1104 ===============
1105 */
1106 void Host_Shutdown(void)
1107 {
1108         static qboolean isdown = false;
1109
1110         if (isdown)
1111         {
1112                 Con_Print("recursive shutdown\n");
1113                 return;
1114         }
1115         if (setjmp(host.abortframe))
1116         {
1117                 Con_Print("aborted the quitting frame?!?\n");
1118                 return;
1119         }
1120         isdown = true;
1121
1122         // be quiet while shutting down
1123         S_StopAllSounds();
1124
1125         // end the server thread
1126         if (svs.threaded)
1127                 SV_StopThread();
1128
1129         // disconnect client from server if active
1130         CL_Disconnect();
1131
1132         // shut down local server if active
1133         SV_LockThreadMutex();
1134         SV_Shutdown ();
1135         SV_UnlockThreadMutex();
1136
1137 #ifdef CONFIG_MENU
1138         // Shutdown menu
1139         if(MR_Shutdown)
1140                 MR_Shutdown();
1141 #endif
1142
1143         // AK shutdown PRVM
1144         // AK hmm, no PRVM_Shutdown(); yet
1145
1146         CL_Video_Shutdown();
1147
1148         Host_SaveConfig();
1149
1150         CDAudio_Shutdown ();
1151         S_Terminate ();
1152         Curl_Shutdown ();
1153         NetConn_Shutdown ();
1154
1155         if (cls.state != ca_dedicated)
1156         {
1157                 R_Modules_Shutdown();
1158                 VID_Shutdown();
1159         }
1160
1161         SV_StopThread();
1162         TaskQueue_Shutdown();
1163         Thread_Shutdown();
1164         Cmd_Shutdown();
1165         Key_Shutdown();
1166         CL_Shutdown();
1167         Sys_Shutdown();
1168         Log_Close();
1169         Crypto_Shutdown();
1170
1171         Host_UnlockSession();
1172
1173         S_Shutdown();
1174         Con_Shutdown();
1175         Memory_Shutdown();
1176 }
1177