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