]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
sys: work around incomplete POSIX support in MacOS
[xonotic/darkplaces.git] / host.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2000-2021 DarkPlaces contributors
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 See the GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 */
21 // host.c -- coordinates spawning and killing of local servers
22
23 #include "quakedef.h"
24
25 #include <time.h>
26 #include "libcurl.h"
27 #include "taskqueue.h"
28 #include "utf8lib.h"
29
30 /*
31
32 A server can always be started, even if the system started out as a client
33 to a remote system.
34
35 A client can NOT be started if the system started as a dedicated server.
36
37 Memory is cleared / released when a server or client begins, not when they end.
38
39 */
40
41 host_static_t host;
42
43 // pretend frames take this amount of time (in seconds), 0 = realtime
44 cvar_t host_framerate = {CF_CLIENT | CF_SERVER, "host_framerate","0", "locks frame timing to this value in seconds, 0.05 is 20fps for example, note that this can easily run too fast, use cl_maxfps if you want to limit your framerate instead, or sys_ticrate to limit server speed"};
45 // shows time used by certain subsystems
46 cvar_t host_speeds = {CF_CLIENT | CF_SERVER, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
47
48 cvar_t developer = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "developer","0", "shows debugging messages and information (recommended for all developers and level designers); the value -1 also suppresses buffering and logging these messages"};
49 cvar_t developer_extra = {CF_CLIENT | CF_SERVER, "developer_extra", "0", "prints additional debugging messages, often very verbose!"};
50 cvar_t developer_insane = {CF_CLIENT | CF_SERVER, "developer_insane", "0", "prints huge streams of information about internal workings, entire contents of files being read/written, etc.  Not recommended!"};
51 cvar_t developer_loadfile = {CF_CLIENT | CF_SERVER, "developer_loadfile","0", "prints name and size of every file loaded via the FS_LoadFile function (which is almost everything)"};
52 cvar_t developer_loading = {CF_CLIENT | CF_SERVER, "developer_loading","0", "prints information about files as they are loaded or unloaded successfully"};
53 cvar_t developer_entityparsing = {CF_CLIENT, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
54
55 cvar_t timestamps = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "timestamps", "0", "prints timestamps on console messages"};
56 cvar_t timeformat = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
57
58 cvar_t sessionid = {CF_CLIENT | CF_SERVER | CF_READONLY, "sessionid", "", "ID of the current session (use the -sessionid parameter to set it); this is always either empty or begins with a dot (.)"};
59 cvar_t locksession = {CF_CLIENT | CF_SERVER, "locksession", "0", "Lock the session? 0 = no, 1 = yes and abort on failure, 2 = yes and continue on failure"};
60
61 cvar_t host_isclient = {CF_SHARED | CF_READONLY, "_host_isclient", "0", "If 1, clientside is active."};
62
63 /*
64 ================
65 Host_AbortCurrentFrame
66
67 aborts the current host frame and goes on with the next one
68 ================
69 */
70 void Host_AbortCurrentFrame(void)
71 {
72         // in case we were previously nice, make us mean again
73         Sys_MakeProcessMean();
74
75         longjmp (host.abortframe, 1);
76 }
77
78 /*
79 ================
80 Host_Error
81
82 This shuts down both the client and server
83 ================
84 */
85 void Host_Error (const char *error, ...)
86 {
87         static char hosterrorstring1[MAX_INPUTLINE]; // THREAD UNSAFE
88         static char hosterrorstring2[MAX_INPUTLINE]; // THREAD UNSAFE
89         static qbool hosterror = false;
90         va_list argptr;
91         int outfd = sys.outfd;
92
93         // set output to stderr
94         sys.outfd = fileno(stderr);
95
96         // turn off rcon redirect if it was active when the crash occurred
97         // to prevent loops when it is a networking problem
98         Con_Rcon_Redirect_Abort();
99
100         va_start (argptr,error);
101         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
102         va_end (argptr);
103
104         Con_Printf(CON_ERROR "Host_Error: %s\n", hosterrorstring1);
105
106         // LadyHavoc: if crashing very early, or currently shutting down, do
107         // Sys_Error instead
108         if (host.framecount < 3 || host.state == host_shutdown)
109                 Sys_Error ("Host_Error during %s: %s", host.framecount < 3 ? "startup" : "shutdown", hosterrorstring1);
110
111         if (hosterror)
112                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
113         hosterror = true;
114
115         dp_strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
116
117         CL_Parse_DumpPacket();
118         CL_Parse_ErrorCleanUp();
119
120         // print out where the crash happened, if it was caused by QC (and do a cleanup)
121         PRVM_Crash();
122
123         if(host.hook.SV_Shutdown)
124                 host.hook.SV_Shutdown();
125
126         if (cls.state == ca_dedicated)
127                 Sys_Error("Host_Error: %s", hosterrorstring1);        // dedicated servers exit
128
129         // prevent an endless loop if the error was triggered by a command
130         Cbuf_Clear(cmd_local->cbuf);
131
132         CL_DisconnectEx(false, "Host_Error: %s", hosterrorstring1);
133         cls.demonum = -1; // stop demo loop
134
135         hosterror = false;
136
137         // restore configured outfd
138         sys.outfd = outfd;
139
140         Host_AbortCurrentFrame();
141 }
142
143 /*
144 ==================
145 Host_Quit_f
146 ==================
147 */
148 static void Host_Quit_f(cmd_state_t *cmd)
149 {
150         if(host.state == host_shutdown)
151                 Con_Printf("shutting down already!\n");
152         else
153                 host.state = host_shutdown;
154 }
155
156 static void Host_Version_f(cmd_state_t *cmd)
157 {
158         Con_Printf("Version: %s\n", engineversion);
159 }
160
161 void Host_UpdateVersion(void)
162 {
163         dpsnprintf(engineversion, sizeof(engineversion), "%s %s%s %s", gamename ? gamename : "DarkPlaces", DP_OS_NAME, cls.state == ca_dedicated ? " dedicated" : "", buildstring);
164 }
165
166 static void Host_Framerate_c(cvar_t *var)
167 {
168         if (var->value < 0.00001 && var->value != 0)
169                 Cvar_SetValueQuick(var, 0);
170 }
171
172 // TODO: Find a better home for this.
173 static void SendCvar_f(cmd_state_t *cmd)
174 {
175         if(cmd->source == src_local && host.hook.SV_SendCvar)
176         {
177                 host.hook.SV_SendCvar(cmd);
178                 return;
179         }
180         if(cmd->source == src_client && host.hook.CL_SendCvar)
181         {
182                 host.hook.CL_SendCvar(cmd);
183                 return;
184         }
185 }
186
187 /*
188 ===============
189 Host_SaveConfig_f
190
191 Writes key bindings and archived cvars to config.cfg
192 ===============
193 */
194 void Host_SaveConfig(const char *file)
195 {
196         qfile_t *f;
197
198 // dedicated servers initialize the host but don't parse and set the
199 // config.cfg cvars
200         // LadyHavoc: don't save a config if it crashed in startup
201         if (host.framecount >= 3 && cls.state != ca_dedicated && !Sys_CheckParm("-benchmark") && !Sys_CheckParm("-capturedemo"))
202         {
203                 f = FS_OpenRealFile(file, "wb", false);
204                 if (!f)
205                 {
206                         Con_Printf(CON_ERROR "Couldn't write %s\n", file);
207                         return;
208                 }
209                 else
210                         Con_Printf("Saving config to %s ...\n", file);
211
212                 Key_WriteBindings (f);
213                 Cvar_WriteVariables (&cvars_all, f);
214
215                 FS_Close (f);
216         }
217 }
218
219 static void Host_SaveConfig_f(cmd_state_t *cmd)
220 {
221         const char *file = CONFIGFILENAME;
222
223         if(Cmd_Argc(cmd) >= 2)
224                 file = Cmd_Argv(cmd, 1);
225
226         Host_SaveConfig(file);
227 }
228
229 static void Host_AddConfigText(cmd_state_t *cmd)
230 {
231         // set up the default startmap_sp and startmap_dm aliases (mods can
232         // override these) and then execute the quake.rc startup script
233         if (gamemode == GAME_NEHAHRA)
234                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
235         else if (gamemode == GAME_TRANSFUSION)
236                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
237         else if (gamemode == GAME_TEU)
238                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
239         else
240                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
241
242         // if quake.rc is missing, use default
243         if (!FS_FileExists(STARTCONFIGFILENAME))
244                 Cbuf_InsertText(cmd, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
245 }
246
247 /*
248 ===============
249 Host_LoadConfig_f
250
251 Resets key bindings and cvars to defaults and then reloads scripts
252 ===============
253 */
254 static void Host_LoadConfig_f(cmd_state_t *cmd)
255 {
256 #ifdef CONFIG_MENU
257         // Xonotic QC complains/breaks if its cvars are deleted before its m_shutdown() is called
258         if(MR_Shutdown)
259                 MR_Shutdown();
260 #endif
261         Cmd_RestoreInitState();
262 #ifdef CONFIG_MENU
263         // Must re-add menu.c commands or load menu.dat before executing quake.rc or handling events
264         MR_Init();
265 #endif
266         // exec startup scripts again
267         Host_AddConfigText(cmd);
268 }
269
270 /*
271 =======================
272 Host_InitLocal
273 ======================
274 */
275 extern cvar_t r_texture_jpeg_fastpicmip;
276 static void Host_InitLocal (void)
277 {
278         Cmd_AddCommand(CF_SHARED, "quit", Host_Quit_f, "quit the game");
279         Cmd_AddCommand(CF_SHARED, "version", Host_Version_f, "print engine version");
280         Cmd_AddCommand(CF_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
281         Cmd_AddCommand(CF_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
282         Cmd_AddCommand(CF_SHARED, "sendcvar", SendCvar_f, "sends the value of a cvar to the server as a sentcvar command, for use by QuakeC");
283         Cvar_RegisterVariable (&host_framerate);
284         Cvar_RegisterCallback (&host_framerate, Host_Framerate_c);
285         Cvar_RegisterVariable (&host_speeds);
286         Cvar_RegisterVariable (&host_isclient);
287
288         Cvar_RegisterVariable (&developer);
289         Cvar_RegisterVariable (&developer_extra);
290         Cvar_RegisterVariable (&developer_insane);
291         Cvar_RegisterVariable (&developer_loadfile);
292         Cvar_RegisterVariable (&developer_loading);
293         Cvar_RegisterVariable (&developer_entityparsing);
294
295         Cvar_RegisterVariable (&timestamps);
296         Cvar_RegisterVariable (&timeformat);
297
298         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
299 }
300
301 char engineversion[128]; ///< version string for the corner of the console, crash messages, status command, etc
302
303
304 static qfile_t *locksession_fh = NULL;
305 static qbool locksession_run = false;
306 static void Host_InitSession(void)
307 {
308         int i;
309         char *buf;
310         Cvar_RegisterVariable(&sessionid);
311         Cvar_RegisterVariable(&locksession);
312
313         // load the session ID into the read-only cvar
314         if ((i = Sys_CheckParm("-sessionid")) && (i + 1 < sys.argc))
315         {
316                 if(sys.argv[i+1][0] == '.')
317                         Cvar_SetQuick(&sessionid, sys.argv[i+1]);
318                 else
319                 {
320                         buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
321                         dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
322                         Cvar_SetQuick(&sessionid, buf);
323                 }
324         }
325 }
326
327 void Host_LockSession(void)
328 {
329         if(locksession_run)
330                 return;
331         locksession_run = true;
332         if(locksession.integer != 0 && !Sys_CheckParm("-readonly"))
333         {
334                 char vabuf[1024];
335                 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
336                 FS_CreatePath(p);
337                 locksession_fh = FS_SysOpen(p, "wl", false);
338                 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
339                 if(!locksession_fh)
340                 {
341                         if(locksession.integer == 2)
342                         {
343                                 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);
344                         }
345                         else
346                         {
347                                 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
348                         }
349                 }
350         }
351 }
352
353 void Host_UnlockSession(void)
354 {
355         if(!locksession_run)
356                 return;
357         locksession_run = false;
358
359         if(locksession_fh)
360         {
361                 FS_Close(locksession_fh);
362                 // NOTE: we can NOT unlink the lock here, as doing so would
363                 // create a race condition if another process created it
364                 // between our close and our unlink
365                 locksession_fh = NULL;
366         }
367 }
368
369 /*
370 ====================
371 Host_Init
372 ====================
373 */
374 static void Host_Init (void)
375 {
376         int i;
377         char vabuf[1024];
378
379         Sys_SDL_Init();
380
381         Memory_Init();
382
383         host.hook.ConnectLocal = NULL;
384         host.hook.Disconnect = NULL;
385         host.hook.ToggleMenu = NULL;
386         host.hook.CL_Intermission = NULL;
387         host.hook.SV_Shutdown = NULL;
388
389         host.state = host_init;
390
391         if (setjmp(host.abortframe)) // Huh?!
392                 Sys_Error("Engine initialization failed. Check the console (if available) for additional information.\n");
393
394         if (Sys_CheckParm("-profilegameonly"))
395                 Sys_AllowProfiling(false);
396
397         // LadyHavoc: quake never seeded the random number generator before... heh
398         if (Sys_CheckParm("-benchmark"))
399                 srand(0); // predictable random sequence for -benchmark
400         else
401                 srand((unsigned int)time(NULL));
402
403         // FIXME: this is evil, but possibly temporary
404         // LadyHavoc: doesn't seem very temporary...
405         // LadyHavoc: made this a saved cvar
406 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
407         if (Sys_CheckParm("-developer"))
408         {
409                 developer.value = developer.integer = 1;
410                 developer.string = "1";
411         }
412
413         if (Sys_CheckParm("-developer2") || Sys_CheckParm("-developer3"))
414         {
415                 developer.value = developer.integer = 1;
416                 developer.string = "1";
417                 developer_extra.value = developer_extra.integer = 1;
418                 developer_extra.string = "1";
419                 developer_insane.value = developer_insane.integer = 1;
420                 developer_insane.string = "1";
421                 developer_memory.value = developer_memory.integer = 1;
422                 developer_memory.string = "1";
423                 developer_memorydebug.value = developer_memorydebug.integer = 1;
424                 developer_memorydebug.string = "1";
425         }
426
427         if (Sys_CheckParm("-developer3"))
428         {
429                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
430                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
431         }
432
433         // -dedicated is checked in SV_ServerOptions() but that's too late for Cvar_RegisterVariable() to skip all the client-only cvars
434         if (Sys_CheckParm ("-dedicated") || !cl_available)
435                 cls.state = ca_dedicated;
436
437         // set and print initial version string (will be updated when gamename is changed)
438         Host_UpdateVersion(); // checks for cls.state == ca_dedicated
439         Con_Printf("%s\n", engineversion);
440
441         // initialize console command/cvar/alias/command execution systems
442         Cmd_Init();
443
444         // initialize memory subsystem cvars/commands
445         Memory_Init_Commands();
446
447         // initialize console and logging and its cvars/commands
448         // this enables Con_Printf() messages to be coloured
449         Con_Init();
450
451         // initialize various cvars that could not be initialized earlier
452         u8_Init();
453         Curl_Init_Commands();
454         Sys_Init_Commands();
455         COM_Init_Commands();
456
457         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name, gamename)
458         FS_Init();
459
460         // initialize process nice level
461         Sys_InitProcessNice();
462
463         // initialize ixtable
464         Mathlib_Init();
465
466         // register the cvars for session locking
467         Host_InitSession();
468
469         // must be after FS_Init
470         Crypto_Init();
471         Crypto_Init_Commands();
472
473         NetConn_Init();
474         Curl_Init();
475         PRVM_Init();
476         Mod_Init();
477         World_Init();
478         SV_Init();
479         Host_InitLocal();
480
481         Thread_Init();
482         TaskQueue_Init();
483
484         CL_Init();
485
486         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
487         // NOTE: menu commands are freed by Cmd_RestoreInitState
488         Cmd_SaveInitState();
489
490         // FIXME: put this into some neat design, but the menu should be allowed to crash
491         // without crashing the whole game, so this should just be a short-time solution
492
493         // here comes the not so critical stuff
494
495         Host_AddConfigText(cmd_local);
496         Cbuf_Execute(cmd_local->cbuf); // cannot be in Host_AddConfigText as that would cause Host_LoadConfig_f to loop!
497
498         host.state = host_active;
499
500         CL_StartVideo();
501
502         Log_Start();
503
504         if (cls.state != ca_dedicated)
505         {
506                 // put up the loading image so the user doesn't stare at a black screen...
507                 SCR_BeginLoadingPlaque(true);
508                 S_Startup();
509 #ifdef CONFIG_MENU
510                 MR_Init();
511 #endif
512         }
513
514         // check for special benchmark mode
515 // 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)
516         i = Sys_CheckParm("-benchmark");
517         if (i && i + 1 < sys.argc)
518         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
519         {
520                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
521                 Cbuf_Execute(cmd_local->cbuf);
522         }
523
524         // check for special demo mode
525 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
526         i = Sys_CheckParm("-demo");
527         if (i && i + 1 < sys.argc)
528         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
529         {
530                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
531                 Cbuf_Execute(cmd_local->cbuf);
532         }
533
534 #ifdef CONFIG_VIDEO_CAPTURE
535 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
536         i = Sys_CheckParm("-capturedemo");
537         if (i && i + 1 < sys.argc)
538         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
539         {
540                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
541                 Cbuf_Execute((cmd_local)->cbuf);
542         }
543 #endif
544
545         if (cls.state == ca_dedicated || Sys_CheckParm("-listen"))
546         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
547         {
548                 Cbuf_AddText(cmd_local, "startmap_dm\n");
549                 Cbuf_Execute(cmd_local->cbuf);
550         }
551
552         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
553         {
554 #ifdef CONFIG_MENU
555                 Cbuf_AddText(cmd_local, "togglemenu 1\n");
556 #endif
557                 Cbuf_Execute(cmd_local->cbuf);
558         }
559
560         Con_DPrint("========Initialized=========\n");
561
562         if (cls.state != ca_dedicated)
563                 SV_StartThread();
564 }
565
566 /*
567 ===============
568 Host_Shutdown
569
570 Cleanly shuts down after the main loop exits.
571 ===============
572 */
573 static void Host_Shutdown(void)
574 {
575         if (Sys_CheckParm("-profilegameonly"))
576                 Sys_AllowProfiling(false);
577
578         if(cls.state != ca_dedicated)
579                 CL_Shutdown();
580
581         // end the server thread
582         if (svs.threaded)
583                 SV_StopThread();
584
585         // shut down local server if active
586         if(host.hook.SV_Shutdown)
587                 host.hook.SV_Shutdown();
588
589         // AK shutdown PRVM
590         // AK hmm, no PRVM_Shutdown(); yet
591
592         Host_SaveConfig(CONFIGFILENAME);
593
594         Curl_Shutdown ();
595         NetConn_Shutdown ();
596
597         SV_StopThread();
598         TaskQueue_Shutdown();
599         Thread_Shutdown();
600         Cmd_Shutdown();
601         Sys_SDL_Shutdown();
602         Log_Close();
603         Crypto_Shutdown();
604
605         Host_UnlockSession();
606
607         Con_Shutdown();
608         Memory_Shutdown();
609 }
610
611 //============================================================================
612
613 /*
614 ==================
615 Host_Frame
616
617 Runs all active servers
618 ==================
619 */
620 static double Host_Frame(double time)
621 {
622         double cl_wait, sv_wait;
623
624         TaskQueue_Frame(false);
625
626         // keep the random time dependent, but not when playing demos/benchmarking
627         if(!*sv_random_seed.string && !host.restless)
628                 rand();
629
630         NetConn_UpdateSockets();
631
632         Log_DestBuffer_Flush();
633
634         // Run any downloads
635         Curl_Frame();
636
637         // get new SDL events and add commands from keybindings to the cbuf
638         Sys_SDL_HandleEvents();
639
640         // process console commands
641         Cbuf_Frame(host.cbuf);
642
643         R_TimeReport("---");
644
645         // if the accumulators haven't become positive yet, wait a while
646         sv_wait = - SV_Frame(time);
647         cl_wait = - CL_Frame(time);
648
649         Mem_CheckSentinelsGlobal();
650
651         if (cls.state == ca_dedicated)
652                 return sv_wait; // dedicated
653         else if (!sv.active || svs.threaded)
654                 return cl_wait; // connected to server, main menu, or server is on different thread
655         else
656                 return min(cl_wait, sv_wait); // listen server or singleplayer
657 }
658
659 // Cloudwalk: Most overpowered function declaration...
660 static inline double Host_UpdateTime (double newtime, double oldtime)
661 {
662         double time = newtime - oldtime;
663
664         if (time < 0)
665         {
666                 // warn if it's significant
667                 if (time < -0.01)
668                         Con_Printf(CON_WARN "Host_UpdateTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
669                 time = 0;
670         }
671         else if (time >= 1800)
672         {
673                 Con_Printf(CON_WARN "Host_UpdateTime: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
674                 time = 0;
675         }
676
677         return time;
678 }
679
680 void Host_Main(void)
681 {
682         double time, oldtime, sleeptime;
683
684         Host_Init(); // Start!
685
686         host.realtime = 0;
687         oldtime = Sys_DirtyTime();
688
689         // Main event loop
690         while(host.state < host_shutdown) // see Sys_HandleCrash() comments
691         {
692                 // Something bad happened, or the server disconnected
693                 if (setjmp(host.abortframe))
694                 {
695                         host.state = host_active; // In case we were loading
696                         continue;
697                 }
698
699                 host.dirtytime = Sys_DirtyTime();
700                 host.realtime += time = Host_UpdateTime(host.dirtytime, oldtime);
701                 oldtime = host.dirtytime;
702
703                 sleeptime = Host_Frame(time);
704                 ++host.framecount;
705                 sleeptime -= Sys_DirtyTime() - host.dirtytime; // execution time
706                 host.sleeptime = Sys_Sleep(sleeptime);
707         }
708
709         Host_Shutdown();
710 }