2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // host.c -- coordinates spawning and killing of local servers
32 #include "taskqueue.h"
38 A server can always be started, even if the system started out as a client
41 A client can NOT be started if the system started as a dedicated server.
43 Memory is cleared / released when a server or client begins, not when they end.
49 // pretend frames take this amount of time (in seconds), 0 = realtime
50 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"};
51 cvar_t cl_maxphysicsframesperserverframe = {CVAR_CLIENT, "cl_maxphysicsframesperserverframe","10", "maximum number of physics frames per server frame"};
52 // shows time used by certain subsystems
53 cvar_t host_speeds = {CVAR_CLIENT | CVAR_SERVER, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
54 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."};
55 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"};
56 cvar_t cl_minfps_fade = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_fade", "1", "how fast the quality adapts to varying framerate"};
57 cvar_t cl_minfps_qualitymax = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitymax", "1", "highest allowed drawdistance multiplier"};
58 cvar_t cl_minfps_qualitymin = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitymin", "0.25", "lowest allowed drawdistance multiplier"};
59 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)"};
60 cvar_t cl_minfps_qualityhysteresis = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualityhysteresis", "0.05", "reduce all quality increments by this to reduce flickering"};
61 cvar_t cl_minfps_qualitystepmax = {CVAR_CLIENT | CVAR_SAVE, "cl_minfps_qualitystepmax", "0.1", "maximum quality change in a single frame"};
62 cvar_t cl_minfps_force = {CVAR_CLIENT, "cl_minfps_force", "0", "also apply quality reductions in timedemo/capturevideo"};
63 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)"};
64 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"};
65 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"};
67 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"};
68 cvar_t developer_extra = {CVAR_CLIENT | CVAR_SERVER, "developer_extra", "0", "prints additional debugging messages, often very verbose!"};
69 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!"};
70 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)"};
71 cvar_t developer_loading = {CVAR_CLIENT | CVAR_SERVER, "developer_loading","0", "prints information about files as they are loaded or unloaded successfully"};
72 cvar_t developer_entityparsing = {CVAR_CLIENT, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
74 cvar_t timestamps = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "timestamps", "0", "prints timestamps on console messages"};
75 cvar_t timeformat = {CVAR_CLIENT | CVAR_SERVER | CVAR_SAVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
77 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 (.)"};
78 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 Host_AbortCurrentFrame
84 aborts the current host frame and goes on with the next one
87 void Host_AbortCurrentFrame(void) DP_FUNC_NORETURN;
88 void Host_AbortCurrentFrame(void)
90 // in case we were previously nice, make us mean again
91 Sys_MakeProcessMean();
93 longjmp (host.abortframe, 1);
100 This shuts down both the client and server
103 void Host_Error (const char *error, ...)
105 static char hosterrorstring1[MAX_INPUTLINE]; // THREAD UNSAFE
106 static char hosterrorstring2[MAX_INPUTLINE]; // THREAD UNSAFE
107 static qboolean hosterror = false;
110 // turn off rcon redirect if it was active when the crash occurred
111 // to prevent loops when it is a networking problem
112 Con_Rcon_Redirect_Abort();
114 va_start (argptr,error);
115 dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
118 Con_Printf(CON_ERROR "Host_Error: %s\n", hosterrorstring1);
120 // LadyHavoc: if crashing very early, or currently shutting down, do
122 if (host.framecount < 3 || host.state == host_shutdown)
123 Sys_Error ("Host_Error: %s", hosterrorstring1);
126 Sys_Error ("Host_Error: recursively entered (original error was: %s new error is: %s)", hosterrorstring2, hosterrorstring1);
129 strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
131 CL_Parse_DumpPacket();
133 CL_Parse_ErrorCleanUp();
137 // print out where the crash happened, if it was caused by QC (and do a cleanup)
138 PRVM_Crash(SVVM_prog);
139 PRVM_Crash(CLVM_prog);
141 PRVM_Crash(MVM_prog);
144 cl.csqc_loaded = false;
145 Cvar_SetValueQuick(&csqc_progcrc, -1);
146 Cvar_SetValueQuick(&csqc_progsize, -1);
148 SV_LockThreadMutex();
150 SV_UnlockThreadMutex();
152 if (cls.state == ca_dedicated)
153 Sys_Error ("Host_Error: %s",hosterrorstring2); // dedicated servers exit
160 Host_AbortCurrentFrame();
163 static void Host_ServerOptions (void)
170 // COMMANDLINEOPTION: Server: -dedicated [playerlimit] starts a dedicated server (with a command console), default playerlimit is 8
171 // COMMANDLINEOPTION: Server: -listen [playerlimit] starts a multiplayer server with graphical client, like singleplayer but other players can connect, default playerlimit is 8
172 // if no client is in the executable or -dedicated is specified on
173 // commandline, start a dedicated server
174 i = COM_CheckParm ("-dedicated");
175 if (i || !cl_available)
177 cls.state = ca_dedicated;
178 // check for -dedicated specifying how many players
179 if (i && i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
180 svs.maxclients = atoi (sys.argv[i+1]);
181 if (COM_CheckParm ("-listen"))
182 Con_Printf ("Only one of -dedicated or -listen can be specified\n");
183 // default sv_public on for dedicated servers (often hosted by serious administrators), off for listen servers (often hosted by clueless users)
184 Cvar_SetValue(&cvars_all, "sv_public", 1);
186 else if (cl_available)
188 // client exists and not dedicated, check if -listen is specified
189 cls.state = ca_disconnected;
190 i = COM_CheckParm ("-listen");
193 // default players unless specified
194 if (i + 1 < sys.argc && atoi (sys.argv[i+1]) >= 1)
195 svs.maxclients = atoi (sys.argv[i+1]);
199 // default players in some games, singleplayer in most
200 if (gamemode != GAME_GOODVSBAD2 && !IS_NEXUIZ_DERIVED(gamemode) && gamemode != GAME_BATTLEMECH)
205 svs.maxclients = svs.maxclients_next = bound(1, svs.maxclients, MAX_SCOREBOARD);
207 svs.clients = (client_t *)Mem_Alloc(sv_mempool, sizeof(client_t) * svs.maxclients);
209 if (svs.maxclients > 1 && !deathmatch.integer && !coop.integer)
210 Cvar_SetValueQuick(&deathmatch, 1);
218 void Host_Quit_f(cmd_state_t *cmd)
220 if(host.state == host_shutdown)
221 Con_Printf("shutting down already!\n");
223 host.state = host_shutdown;
226 static void Host_Version_f(cmd_state_t *cmd)
228 Con_Printf("Version: %s build %s\n", gamename, buildstring);
232 =======================
234 ======================
236 void Host_SaveConfig_f(cmd_state_t *cmd);
237 void Host_LoadConfig_f(cmd_state_t *cmd);
238 extern cvar_t sv_writepicture_quality;
239 extern cvar_t r_texture_jpeg_fastpicmip;
240 static void Host_InitLocal (void)
242 Cmd_AddCommand(CMD_SHARED, "quit", Host_Quit_f, "quit the game");
243 Cmd_AddCommand(CMD_SHARED, "version", Host_Version_f, "print engine version");
244 Cmd_AddCommand(CMD_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
245 Cmd_AddCommand(CMD_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
246 Cvar_RegisterVariable (&cl_maxphysicsframesperserverframe);
247 Cvar_RegisterVariable (&host_framerate);
248 Cvar_RegisterVariable (&host_speeds);
249 Cvar_RegisterVariable (&host_maxwait);
250 Cvar_RegisterVariable (&cl_minfps);
251 Cvar_RegisterVariable (&cl_minfps_fade);
252 Cvar_RegisterVariable (&cl_minfps_qualitymax);
253 Cvar_RegisterVariable (&cl_minfps_qualitymin);
254 Cvar_RegisterVariable (&cl_minfps_qualitystepmax);
255 Cvar_RegisterVariable (&cl_minfps_qualityhysteresis);
256 Cvar_RegisterVariable (&cl_minfps_qualitymultiply);
257 Cvar_RegisterVariable (&cl_minfps_force);
258 Cvar_RegisterVariable (&cl_maxfps);
259 Cvar_RegisterVariable (&cl_maxfps_alwayssleep);
260 Cvar_RegisterVariable (&cl_maxidlefps);
262 Cvar_RegisterVariable (&developer);
263 Cvar_RegisterVariable (&developer_extra);
264 Cvar_RegisterVariable (&developer_insane);
265 Cvar_RegisterVariable (&developer_loadfile);
266 Cvar_RegisterVariable (&developer_loading);
267 Cvar_RegisterVariable (&developer_entityparsing);
269 Cvar_RegisterVariable (×tamps);
270 Cvar_RegisterVariable (&timeformat);
272 Cvar_RegisterVariable (&sv_writepicture_quality);
273 Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
281 Writes key bindings and archived cvars to config.cfg
284 static void Host_SaveConfig_to(const char *file)
288 // dedicated servers initialize the host but don't parse and set the
290 // LadyHavoc: don't save a config if it crashed in startup
291 if (host.framecount >= 3 && cls.state != ca_dedicated && !COM_CheckParm("-benchmark") && !COM_CheckParm("-capturedemo"))
293 f = FS_OpenRealFile(file, "wb", false);
296 Con_Printf(CON_ERROR "Couldn't write %s.\n", file);
300 Key_WriteBindings (f);
301 Cvar_WriteVariables (&cvars_all, f);
306 void Host_SaveConfig(void)
308 Host_SaveConfig_to(CONFIGFILENAME);
310 void Host_SaveConfig_f(cmd_state_t *cmd)
312 const char *file = CONFIGFILENAME;
314 if(Cmd_Argc(cmd) >= 2) {
315 file = Cmd_Argv(cmd, 1);
316 Con_Printf("Saving to %s\n", file);
319 Host_SaveConfig_to(file);
322 static void Host_AddConfigText(cmd_state_t *cmd)
324 // set up the default startmap_sp and startmap_dm aliases (mods can
325 // override these) and then execute the quake.rc startup script
326 if (gamemode == GAME_NEHAHRA)
327 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
328 else if (gamemode == GAME_TRANSFUSION)
329 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
330 else if (gamemode == GAME_TEU)
331 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
333 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
341 Resets key bindings and cvars to defaults and then reloads scripts
344 void Host_LoadConfig_f(cmd_state_t *cmd)
346 // reset all cvars, commands and aliases to init values
347 Cmd_RestoreInitState();
349 // prepend a menu restart command to execute after the config
350 Cbuf_InsertText(&cmd_client, "\nmenu_restart\n");
352 // reset cvars to their defaults, and then exec startup scripts again
353 Host_AddConfigText(&cmd_client);
356 //============================================================================
360 Host_GetConsoleCommands
362 Add them exactly as if they had been typed at the console
365 static void Host_GetConsoleCommands (void)
369 while ((line = Sys_ConsoleInput()))
371 if (cls.state == ca_dedicated)
372 Cbuf_AddText(&cmd_server, line);
374 Cbuf_AddText(&cmd_client, line);
382 Returns a time report string, for example for
385 const char *Host_TimingReport(char *buf, size_t buflen)
387 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);
394 Runs all active servers
397 static void Host_Init(void);
403 double cl_timer = 0, sv_timer = 0;
404 double clframetime, time, oldtime, newtime;
406 int pass1, pass2, pass3, i;
410 host.restless = false;
415 host.dirtytime = Sys_DirtyTime();
417 while(host.state != host_shutdown)
419 if (setjmp(host.abortframe))
421 SCR_ClearLoadingScreen(false);
422 continue; // something bad happened, or the server disconnected
425 oldtime = host.dirtytime;
426 newtime = Sys_DirtyTime();
427 time = newtime - oldtime;
430 // warn if it's significant
432 Con_Printf(CON_WARN "Host_Mingled: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
435 else if (time >= 1800)
437 Con_Printf(CON_WARN "Host_Mingled: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
440 host.realtime += time;
441 host.dirtytime = newtime;
448 svs.perf_acc_realtime += time;
450 // Look for clients who have spawned
452 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
453 if(host_client->begun)
454 if(host_client->netconnection)
458 // don't accumulate time for the first 10 seconds of a match
459 // so things can settle
460 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 else if(svs.perf_acc_realtime > 5)
464 svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
465 svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
466 if(svs.perf_acc_offset_samples > 0)
468 svs.perf_offset_max = svs.perf_acc_offset_max;
469 svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
470 svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
472 if(svs.perf_lost > 0 && developer_extra.integer)
473 if(playing) // only complain if anyone is looking
474 Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport(vabuf, sizeof(vabuf)));
475 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;
479 if (host_framerate.value < 0.00001 && host_framerate.value != 0)
480 Cvar_SetValueQuick(&host_framerate, 0);
482 TaskQueue_Frame(false);
484 // keep the random time dependent, but not when playing demos/benchmarking
485 if(!*sv_random_seed.string && !cls.demoplayback)
488 NetConn_UpdateSockets();
490 Log_DestBuffer_Flush();
492 // receive packets on each main loop iteration, as the main loop may
493 // be undersleeping due to select() detecting a new packet
494 if (sv.active && !svs.threaded)
495 NetConn_ServerFrame();
499 // check for commands typed to the host
500 Host_GetConsoleCommands();
502 // process console commands
503 // R_TimeReport("preconsole");
504 CL_VM_PreventInformationLeaks();
505 Cbuf_Frame(&cmd_client);
506 Cbuf_Frame(&cmd_server);
509 Cbuf_Frame(&cmd_serverfromclient);
511 // R_TimeReport("console");
513 //Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);
515 // if the accumulators haven't become positive yet, wait a while
516 if (cls.state == ca_dedicated)
517 wait = sv_timer * -1000000.0;
518 else if (!sv.active || svs.threaded)
519 wait = cl_timer * -1000000.0;
521 wait = max(cl_timer, sv_timer) * -1000000.0;
523 if (!host.restless && wait >= 1)
527 if(host_maxwait.value <= 0)
528 wait = min(wait, 1000000.0);
530 wait = min(wait, host_maxwait.value * 1000.0);
532 wait = 1; // because we cast to int
534 time0 = Sys_DirtyTime();
535 if (sv_checkforpacketsduringsleep.integer && !sys_usenoclockbutbenchmark.integer && !svs.threaded) {
536 NetConn_SleepMicroseconds((int)wait);
537 if (cls.state != ca_dedicated)
538 NetConn_ClientFrame(); // helps server browser get good ping values
539 // TODO can we do the same for ServerFrame? Probably not.
542 Sys_Sleep((int)wait);
543 delta = Sys_DirtyTime() - time0;
544 if (delta < 0 || delta >= 1800) delta = 0;
546 svs.perf_acc_sleeptime += delta;
547 // R_TimeReport("sleep");
551 // limit the frametime steps to no more than 100ms each
557 svs.perf_acc_lost += (sv_timer - 0.1);
563 //-------------------
567 //-------------------
569 // limit the frametime steps to no more than 100ms each
570 if (sv.active && sv_timer > 0 && !svs.threaded)
572 // execute one or more server frames, with an upper limit on how much
573 // execution time to spend on server frames to avoid freezing the game if
574 // the server is overloaded, this execution time limit means the game will
575 // slow down if the server is taking too long.
576 int framecount, framelimit = 1;
577 double advancetime, aborttime = 0;
579 prvm_prog_t *prog = SVVM_prog;
581 // run the world state
582 // don't allow simulation to run too fast or too slow or logic glitches can occur
584 // stop running server frames if the wall time reaches this value
585 if (sys_ticrate.value <= 0)
586 advancetime = sv_timer;
587 else if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
589 // synchronize to the client frametime, but no less than 10ms and no more than 100ms
590 advancetime = bound(0.01, cl_timer, 0.1);
594 advancetime = sys_ticrate.value;
595 // listen servers can run multiple server frames per client frame
596 framelimit = cl_maxphysicsframesperserverframe.integer;
597 aborttime = Sys_DirtyTime() + 0.1;
599 if(host_timescale.value > 0 && host_timescale.value < 1)
600 advancetime = min(advancetime, 0.1 / host_timescale.value);
602 advancetime = min(advancetime, 0.1);
606 offset = Sys_DirtyTime() - newtime;if (offset < 0 || offset >= 1800) offset = 0;
608 ++svs.perf_acc_offset_samples;
609 svs.perf_acc_offset += offset;
610 svs.perf_acc_offset_squared += offset * offset;
611 if(svs.perf_acc_offset_max < offset)
612 svs.perf_acc_offset_max = offset;
615 // only advance time if not paused
616 // the game also pauses in singleplayer when menu or console is used
617 sv.frametime = advancetime * host_timescale.value;
618 if (host_framerate.value)
619 sv.frametime = host_framerate.value;
620 if (sv.paused || host.paused)
623 for (framecount = 0;framecount < framelimit && sv_timer > 0;framecount++)
625 sv_timer -= advancetime;
627 // move things around and think unless paused
631 // if this server frame took too long, break out of the loop
632 if (framelimit > 1 && Sys_DirtyTime() >= aborttime)
635 R_TimeReport("serverphysics");
637 // send all messages to the clients
638 SV_SendClientMessages();
640 if (sv.paused == 1 && host.realtime > sv.pausedstart && sv.pausedstart > 0) {
641 prog->globals.fp[OFS_PARM0] = host.realtime - sv.pausedstart;
642 PRVM_serverglobalfloat(time) = sv.time;
643 prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
646 // send an heartbeat if enough time has passed since the last one
647 NetConn_Heartbeat(0);
648 R_TimeReport("servernetwork");
650 else if (!svs.threaded)
652 // don't let r_speeds display jump around
653 R_TimeReport("serverphysics");
654 R_TimeReport("servernetwork");
657 //-------------------
661 //-------------------
663 // get new key events
664 Key_EventQueue_Unblock();
665 SndSys_SendKeyEvents();
668 if (cls.state != ca_dedicated && (cl_timer > 0 || cls.timedemo || ((vid_activewindow ? cl_maxfps : cl_maxidlefps).value < 1)))
671 Collision_Cache_NewFrame();
672 R_TimeReport("photoncache");
673 #ifdef CONFIG_VIDEO_CAPTURE
674 // decide the simulation time
675 if (cls.capturevideo.active)
678 if (cls.capturevideo.realtime)
679 clframetime = cl.realframetime = max(cl_timer, 1.0 / cls.capturevideo.framerate);
682 clframetime = 1.0 / cls.capturevideo.framerate;
683 cl.realframetime = max(cl_timer, clframetime);
686 else if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
689 if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
692 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxfps.value);
693 // when running slow, we need to sleep to keep input responsive
694 wait = bound(0, cl_maxfps_alwayssleep.value * 1000, 100000);
696 Sys_Sleep((int)wait);
698 else if (!vid_activewindow && cl_maxidlefps.value >= 1 && !cls.timedemo)
699 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxidlefps.value);
701 clframetime = cl.realframetime = cl_timer;
703 // apply slowmo scaling
704 clframetime *= cl.movevars_timescale;
705 // scale playback speed of demos by slowmo cvar
706 if (cls.demoplayback)
708 clframetime *= host_timescale.value;
709 // if demo playback is paused, don't advance time at all
715 // host_framerate overrides all else
716 if (host_framerate.value)
717 clframetime = host_framerate.value;
719 if (cl.paused || host.paused)
724 clframetime = cl.realframetime = cl_timer;
726 // deduct the frame time from the accumulator
727 cl_timer -= cl.realframetime;
729 cl.oldtime = cl.time;
730 cl.time += clframetime;
733 if (host_speeds.integer)
734 time1 = Sys_DirtyTime();
735 R_TimeReport("pre-input");
737 // Collect input into cmd
740 R_TimeReport("input");
742 // check for new packets
743 NetConn_ClientFrame();
745 // read a new frame from a demo if needed
746 CL_ReadDemoMessage();
747 R_TimeReport("clientnetwork");
749 // now that packets have been read, send input to server
751 R_TimeReport("sendmove");
753 // update client world (interpolate entities, create trails, etc)
755 R_TimeReport("lerpworld");
759 R_TimeReport("client");
762 R_TimeReport("render");
764 if (host_speeds.integer)
765 time2 = Sys_DirtyTime();
768 if(cl.csqc_usecsqclistener)
770 S_Update(&cl.csqc_listenermatrix);
771 cl.csqc_usecsqclistener = false;
774 S_Update(&r_refdef.view.matrix);
777 R_TimeReport("audio");
779 // reset gathering of mouse input
780 in_mouse_x = in_mouse_y = 0;
782 if (host_speeds.integer)
784 pass1 = (int)((time1 - time3)*1000000);
785 time3 = Sys_DirtyTime();
786 pass2 = (int)((time2 - time1)*1000000);
787 pass3 = (int)((time3 - time2)*1000000);
788 Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
789 pass1+pass2+pass3, pass1, pass2, pass3);
794 Mem_CheckSentinelsGlobal();
796 if (developer_memorydebug.integer)
797 Mem_CheckSentinelsGlobal();
800 // if there is some time remaining from this frame, reset the timers
806 svs.perf_acc_lost += sv_timer;
816 //============================================================================
818 qboolean vid_opened = false;
819 void Host_StartVideo(void)
821 if (!vid_opened && cls.state != ca_dedicated)
824 // make sure we open sockets before opening video because the Windows Firewall "unblock?" dialog can screw up the graphics context on some graphics drivers
825 NetConn_UpdateSockets();
831 char engineversion[128];
833 qboolean sys_nostdout = false;
835 static qfile_t *locksession_fh = NULL;
836 static qboolean locksession_run = false;
837 static void Host_InitSession(void)
841 Cvar_RegisterVariable(&sessionid);
842 Cvar_RegisterVariable(&locksession);
844 // load the session ID into the read-only cvar
845 if ((i = COM_CheckParm("-sessionid")) && (i + 1 < sys.argc))
847 if(sys.argv[i+1][0] == '.')
848 Cvar_SetQuick(&sessionid, sys.argv[i+1]);
851 buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
852 dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
853 Cvar_SetQuick(&sessionid, buf);
857 void Host_LockSession(void)
861 locksession_run = true;
862 if(locksession.integer != 0 && !COM_CheckParm("-readonly"))
865 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
867 locksession_fh = FS_SysOpen(p, "wl", false);
868 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
871 if(locksession.integer == 2)
873 Con_Printf(CON_WARN "WARNING: session lock %s could not be acquired. Please run with -sessionid and an unique session name. Continuing anyway.\n", p);
877 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
882 void Host_UnlockSession(void)
886 locksession_run = false;
890 FS_Close(locksession_fh);
891 // NOTE: we can NOT unlink the lock here, as doing so would
892 // create a race condition if another process created it
893 // between our close and our unlink
894 locksession_fh = NULL;
903 static void Host_Init (void)
908 cmd_state_t *cmd = &cmd_client;
910 host.state = host_init;
912 if (COM_CheckParm("-profilegameonly"))
913 Sys_AllowProfiling(false);
915 // LadyHavoc: quake never seeded the random number generator before... heh
916 if (COM_CheckParm("-benchmark"))
917 srand(0); // predictable random sequence for -benchmark
919 srand((unsigned int)time(NULL));
921 // FIXME: this is evil, but possibly temporary
922 // LadyHavoc: doesn't seem very temporary...
923 // LadyHavoc: made this a saved cvar
924 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
925 if (COM_CheckParm("-developer"))
927 developer.value = developer.integer = 1;
928 developer.string = "1";
931 if (COM_CheckParm("-developer2") || COM_CheckParm("-developer3"))
933 developer.value = developer.integer = 1;
934 developer.string = "1";
935 developer_extra.value = developer_extra.integer = 1;
936 developer_extra.string = "1";
937 developer_insane.value = developer_insane.integer = 1;
938 developer_insane.string = "1";
939 developer_memory.value = developer_memory.integer = 1;
940 developer_memory.string = "1";
941 developer_memorydebug.value = developer_memorydebug.integer = 1;
942 developer_memorydebug.string = "1";
945 if (COM_CheckParm("-developer3"))
947 gl_paranoid.integer = 1;gl_paranoid.string = "1";
948 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
951 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
952 if (COM_CheckParm("-nostdout"))
955 // used by everything
958 // initialize console command/cvar/alias/command execution systems
961 // initialize memory subsystem cvars/commands
962 Memory_Init_Commands();
964 // initialize console and logging and its cvars/commands
967 // initialize various cvars that could not be initialized earlier
969 Curl_Init_Commands();
973 // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
976 // construct a version string for the corner of the console
978 dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
979 Con_Printf("%s\n", engineversion);
981 // initialize process nice level
982 Sys_InitProcessNice();
984 // initialize ixtable
987 // register the cvars for session locking
990 // must be after FS_Init
992 Crypto_Init_Commands();
1000 V_Init(); // some cvars needed by server player physics (cl_rollangle etc)
1002 Host_ServerOptions();
1009 // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
1010 // NOTE: menu commands are freed by Cmd_RestoreInitState
1011 Cmd_SaveInitState();
1013 // FIXME: put this into some neat design, but the menu should be allowed to crash
1014 // without crashing the whole game, so this should just be a short-time solution
1016 // here comes the not so critical stuff
1017 if (setjmp(host.abortframe)) {
1021 Host_AddConfigText(cmd);
1025 // if quake.rc is missing, use default
1026 if (!FS_FileExists("quake.rc"))
1028 Cbuf_InsertText(cmd, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
1032 host.state = host_active;
1034 // run stuffcmds now, deferred previously because it can crash if a server starts that early
1035 Cbuf_AddText(cmd,"stuffcmds\n");
1040 // put up the loading image so the user doesn't stare at a black screen...
1041 SCR_BeginLoadingPlaque(true);
1043 // check for special benchmark mode
1044 // 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)
1045 i = COM_CheckParm("-benchmark");
1046 if (i && i + 1 < sys.argc)
1047 if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1049 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
1050 Cbuf_Execute(&cmd_client);
1053 // check for special demo mode
1054 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
1055 i = COM_CheckParm("-demo");
1056 if (i && i + 1 < sys.argc)
1057 if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1059 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
1060 Cbuf_Execute(&cmd_client);
1063 #ifdef CONFIG_VIDEO_CAPTURE
1064 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
1065 i = COM_CheckParm("-capturedemo");
1066 if (i && i + 1 < sys.argc)
1067 if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1069 Cbuf_AddText(&cmd_client, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
1070 Cbuf_Execute(&cmd_client);
1074 if (cls.state == ca_dedicated || COM_CheckParm("-listen"))
1075 if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1077 Cbuf_AddText(&cmd_client, "startmap_dm\n");
1078 Cbuf_Execute(&cmd_client);
1081 if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1084 Cbuf_AddText(&cmd_client, "togglemenu 1\n");
1086 Cbuf_Execute(&cmd_client);
1089 Con_DPrint("========Initialized=========\n");
1091 if (cls.state != ca_dedicated)
1100 FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better
1101 to run quit through here before the final handoff to the sys code.
1104 void Host_Shutdown(void)
1106 static qboolean isdown = false;
1110 Con_Print("recursive shutdown\n");
1113 if (setjmp(host.abortframe))
1115 Con_Print("aborted the quitting frame?!?\n");
1120 // be quiet while shutting down
1123 // end the server thread
1127 // disconnect client from server if active
1130 // shut down local server if active
1131 SV_LockThreadMutex();
1133 SV_UnlockThreadMutex();
1142 // AK hmm, no PRVM_Shutdown(); yet
1144 CL_Video_Shutdown();
1148 CDAudio_Shutdown ();
1151 NetConn_Shutdown ();
1153 if (cls.state != ca_dedicated)
1155 R_Modules_Shutdown();
1160 TaskQueue_Shutdown();
1169 Host_UnlockSession();
1176 void Host_NoOperation_f(cmd_state_t *cmd)