]> git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
Parser is now tail recursive. Implemented parse tree, self-cleaning on failure
[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 cvar_t cl_maxphysicsframesperserverframe = {CF_CLIENT, "cl_maxphysicsframesperserverframe","10", "maximum number of physics frames per server frame"};
46 // shows time used by certain subsystems
47 cvar_t host_speeds = {CF_CLIENT | CF_SERVER, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
48 cvar_t host_maxwait = {CF_CLIENT | CF_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."};
49
50 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"};
51 cvar_t developer_extra = {CF_CLIENT | CF_SERVER, "developer_extra", "0", "prints additional debugging messages, often very verbose!"};
52 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!"};
53 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)"};
54 cvar_t developer_loading = {CF_CLIENT | CF_SERVER, "developer_loading","0", "prints information about files as they are loaded or unloaded successfully"};
55 cvar_t developer_entityparsing = {CF_CLIENT, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
56
57 cvar_t timestamps = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "timestamps", "0", "prints timestamps on console messages"};
58 cvar_t timeformat = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
59
60 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 (.)"};
61 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"};
62
63 cvar_t host_isclient = {CF_SHARED | CF_READONLY, "_host_isclient", "0", "If 1, clientside is active."};
64
65 /*
66 ================
67 Host_AbortCurrentFrame
68
69 aborts the current host frame and goes on with the next one
70 ================
71 */
72 void Host_AbortCurrentFrame(void)
73 {
74         // in case we were previously nice, make us mean again
75         Sys_MakeProcessMean();
76
77         longjmp (host.abortframe, 1);
78 }
79
80 /*
81 ================
82 Host_Error
83
84 This shuts down both the client and server
85 ================
86 */
87 void Host_Error (const char *error, ...)
88 {
89         static char hosterrorstring1[MAX_INPUTLINE]; // THREAD UNSAFE
90         static char hosterrorstring2[MAX_INPUTLINE]; // THREAD UNSAFE
91         static qbool hosterror = false;
92         va_list argptr;
93
94         // turn off rcon redirect if it was active when the crash occurred
95         // to prevent loops when it is a networking problem
96         Con_Rcon_Redirect_Abort();
97
98         va_start (argptr,error);
99         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
100         va_end (argptr);
101
102         Con_Printf(CON_ERROR "Host_Error: %s\n", hosterrorstring1);
103
104         // LadyHavoc: if crashing very early, or currently shutting down, do
105         // Sys_Error instead
106         if (host.framecount < 3 || host.state == host_shutdown)
107                 Sys_Error ("Host_Error: %s", hosterrorstring1);
108
109         if (hosterror)
110                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
111         hosterror = true;
112
113         strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
114
115         CL_Parse_DumpPacket();
116
117         CL_Parse_ErrorCleanUp();
118
119         //PR_Crash();
120
121         // print out where the crash happened, if it was caused by QC (and do a cleanup)
122         PRVM_Crash(SVVM_prog);
123         PRVM_Crash(CLVM_prog);
124 #ifdef CONFIG_MENU
125         PRVM_Crash(MVM_prog);
126 #endif
127
128         Cvar_SetValueQuick(&csqc_progcrc, -1);
129         Cvar_SetValueQuick(&csqc_progsize, -1);
130
131         if(host.hook.SV_Shutdown)
132                 host.hook.SV_Shutdown();
133
134         if (cls.state == ca_dedicated)
135                 Sys_Error ("Host_Error: %s",hosterrorstring2);  // dedicated servers exit
136
137         CL_Disconnect();
138         cls.demonum = -1;
139
140         hosterror = false;
141
142         Host_AbortCurrentFrame();
143 }
144
145 /*
146 ==================
147 Host_Quit_f
148 ==================
149 */
150 static void Host_Quit_f(cmd_state_t *cmd)
151 {
152         if(host.state == host_shutdown)
153                 Con_Printf("shutting down already!\n");
154         else
155                 host.state = host_shutdown;
156 }
157
158 static void Host_Version_f(cmd_state_t *cmd)
159 {
160         Con_Printf("Version: %s build %s\n", gamename, buildstring);
161 }
162
163 static void Host_Framerate_c(cvar_t *var)
164 {
165         if (var->value < 0.00001 && var->value != 0)
166                 Cvar_SetValueQuick(var, 0);
167 }
168
169 // TODO: Find a better home for this.
170 static void SendCvar_f(cmd_state_t *cmd)
171 {
172         if(cmd->source == src_local && host.hook.SV_SendCvar)
173         {
174                 host.hook.SV_SendCvar(cmd);
175                 return;
176         }
177         if(cmd->source == src_client && host.hook.CL_SendCvar)
178         {
179                 host.hook.CL_SendCvar(cmd);
180                 return;
181         }
182 }
183
184 /*
185 ===============
186 Host_SaveConfig_f
187
188 Writes key bindings and archived cvars to config.cfg
189 ===============
190 */
191 void Host_SaveConfig(const char *file)
192 {
193         qfile_t *f;
194
195 // dedicated servers initialize the host but don't parse and set the
196 // config.cfg cvars
197         // LadyHavoc: don't save a config if it crashed in startup
198         if (host.framecount >= 3 && cls.state != ca_dedicated && !Sys_CheckParm("-benchmark") && !Sys_CheckParm("-capturedemo"))
199         {
200                 f = FS_OpenRealFile(file, "wb", false);
201                 if (!f)
202                 {
203                         Con_Printf(CON_ERROR "Couldn't write %s.\n", file);
204                         return;
205                 }
206
207                 Key_WriteBindings (f);
208                 Cvar_WriteVariables (&cvars_all, f);
209
210                 FS_Close (f);
211         }
212 }
213
214 static void Host_SaveConfig_f(cmd_state_t *cmd)
215 {
216         const char *file = CONFIGFILENAME;
217
218         if(Cmd_Argc(cmd) >= 2) {
219                 file = Cmd_Argv(cmd, 1);
220                 Con_Printf("Saving to %s\n", file);
221         }
222
223         Host_SaveConfig(file);
224 }
225
226 static void Host_AddConfigText(cmd_state_t *cmd)
227 {
228         // set up the default startmap_sp and startmap_dm aliases (mods can
229         // override these) and then execute the quake.rc startup script
230         if (gamemode == GAME_NEHAHRA)
231                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
232         else if (gamemode == GAME_TRANSFUSION)
233                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
234         else if (gamemode == GAME_TEU)
235                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
236         else
237                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
238         Cbuf_Execute(cmd->cbuf);
239 }
240
241 /*
242 ===============
243 Host_LoadConfig_f
244
245 Resets key bindings and cvars to defaults and then reloads scripts
246 ===============
247 */
248 static void Host_LoadConfig_f(cmd_state_t *cmd)
249 {
250         // reset all cvars, commands and aliases to init values
251         Cmd_RestoreInitState();
252 #ifdef CONFIG_MENU
253         // prepend a menu restart command to execute after the config
254         Cbuf_InsertText(cmd_local, "\nmenu_restart\n");
255 #endif
256         // reset cvars to their defaults, and then exec startup scripts again
257         Host_AddConfigText(cmd_local);
258 }
259
260 /*
261 =======================
262 Host_InitLocal
263 ======================
264 */
265 void Json_Test_f(cmd_state_t *cmd);
266 extern cvar_t r_texture_jpeg_fastpicmip;
267 static void Host_InitLocal (void)
268 {
269         Cmd_AddCommand(CF_SHARED, "quit", Host_Quit_f, "quit the game");
270         Cmd_AddCommand(CF_SHARED, "version", Host_Version_f, "print engine version");
271         Cmd_AddCommand(CF_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
272         Cmd_AddCommand(CF_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
273         Cmd_AddCommand(CF_SHARED, "sendcvar", SendCvar_f, "sends the value of a cvar to the server as a sentcvar command, for use by QuakeC");
274         Cmd_AddCommand(CF_SHARED, "json_test", Json_Test_f, "test the json parser");
275         Cvar_RegisterVariable (&cl_maxphysicsframesperserverframe);
276         Cvar_RegisterVariable (&host_framerate);
277         Cvar_RegisterCallback (&host_framerate, Host_Framerate_c);
278         Cvar_RegisterVariable (&host_speeds);
279         Cvar_RegisterVariable (&host_maxwait);
280         Cvar_RegisterVariable (&host_isclient);
281
282         Cvar_RegisterVariable (&developer);
283         Cvar_RegisterVariable (&developer_extra);
284         Cvar_RegisterVariable (&developer_insane);
285         Cvar_RegisterVariable (&developer_loadfile);
286         Cvar_RegisterVariable (&developer_loading);
287         Cvar_RegisterVariable (&developer_entityparsing);
288
289         Cvar_RegisterVariable (&timestamps);
290         Cvar_RegisterVariable (&timeformat);
291
292         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
293 }
294
295 char engineversion[128];
296
297 qbool sys_nostdout = false;
298
299 static qfile_t *locksession_fh = NULL;
300 static qbool locksession_run = false;
301 static void Host_InitSession(void)
302 {
303         int i;
304         char *buf;
305         Cvar_RegisterVariable(&sessionid);
306         Cvar_RegisterVariable(&locksession);
307
308         // load the session ID into the read-only cvar
309         if ((i = Sys_CheckParm("-sessionid")) && (i + 1 < sys.argc))
310         {
311                 if(sys.argv[i+1][0] == '.')
312                         Cvar_SetQuick(&sessionid, sys.argv[i+1]);
313                 else
314                 {
315                         buf = (char *)Z_Malloc(strlen(sys.argv[i+1]) + 2);
316                         dpsnprintf(buf, sizeof(buf), ".%s", sys.argv[i+1]);
317                         Cvar_SetQuick(&sessionid, buf);
318                 }
319         }
320 }
321
322 void Host_LockSession(void)
323 {
324         if(locksession_run)
325                 return;
326         locksession_run = true;
327         if(locksession.integer != 0 && !Sys_CheckParm("-readonly"))
328         {
329                 char vabuf[1024];
330                 char *p = va(vabuf, sizeof(vabuf), "%slock%s", *fs_userdir ? fs_userdir : fs_basedir, sessionid.string);
331                 FS_CreatePath(p);
332                 locksession_fh = FS_SysOpen(p, "wl", false);
333                 // TODO maybe write the pid into the lockfile, while we are at it? may help server management tools
334                 if(!locksession_fh)
335                 {
336                         if(locksession.integer == 2)
337                         {
338                                 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);
339                         }
340                         else
341                         {
342                                 Sys_Error("session lock %s could not be acquired. Please run with -sessionid and an unique session name.\n", p);
343                         }
344                 }
345         }
346 }
347
348 void Host_UnlockSession(void)
349 {
350         if(!locksession_run)
351                 return;
352         locksession_run = false;
353
354         if(locksession_fh)
355         {
356                 FS_Close(locksession_fh);
357                 // NOTE: we can NOT unlink the lock here, as doing so would
358                 // create a race condition if another process created it
359                 // between our close and our unlink
360                 locksession_fh = NULL;
361         }
362 }
363
364 /*
365 ====================
366 Host_Init
367 ====================
368 */
369 static void Host_Init (void)
370 {
371         int i;
372         const char* os;
373         char vabuf[1024];
374
375         host.hook.ConnectLocal = NULL;
376         host.hook.Disconnect = NULL;
377         host.hook.ToggleMenu = NULL;
378         host.hook.CL_Intermission = NULL;
379         host.hook.SV_Shutdown = NULL;
380
381         host.state = host_init;
382
383         if (setjmp(host.abortframe)) // Huh?!
384                 Sys_Error("Engine initialization failed. Check the console (if available) for additional information.\n");
385
386         if (Sys_CheckParm("-profilegameonly"))
387                 Sys_AllowProfiling(false);
388
389         // LadyHavoc: quake never seeded the random number generator before... heh
390         if (Sys_CheckParm("-benchmark"))
391                 srand(0); // predictable random sequence for -benchmark
392         else
393                 srand((unsigned int)time(NULL));
394
395         // FIXME: this is evil, but possibly temporary
396         // LadyHavoc: doesn't seem very temporary...
397         // LadyHavoc: made this a saved cvar
398 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
399         if (Sys_CheckParm("-developer"))
400         {
401                 developer.value = developer.integer = 1;
402                 developer.string = "1";
403         }
404
405         if (Sys_CheckParm("-developer2") || Sys_CheckParm("-developer3"))
406         {
407                 developer.value = developer.integer = 1;
408                 developer.string = "1";
409                 developer_extra.value = developer_extra.integer = 1;
410                 developer_extra.string = "1";
411                 developer_insane.value = developer_insane.integer = 1;
412                 developer_insane.string = "1";
413                 developer_memory.value = developer_memory.integer = 1;
414                 developer_memory.string = "1";
415                 developer_memorydebug.value = developer_memorydebug.integer = 1;
416                 developer_memorydebug.string = "1";
417         }
418
419         if (Sys_CheckParm("-developer3"))
420         {
421                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
422                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
423         }
424
425 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
426         if (Sys_CheckParm("-nostdout"))
427                 sys_nostdout = 1;
428
429         // initialize console command/cvar/alias/command execution systems
430         Cmd_Init();
431
432         // initialize memory subsystem cvars/commands
433         Memory_Init_Commands();
434
435         // initialize console and logging and its cvars/commands
436         Con_Init();
437
438         // initialize various cvars that could not be initialized earlier
439         u8_Init();
440         Curl_Init_Commands();
441         Sys_Init_Commands();
442         COM_Init_Commands();
443
444         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
445         FS_Init();
446
447         // construct a version string for the corner of the console
448         os = DP_OS_NAME;
449         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
450         Con_Printf("%s\n", engineversion);
451
452         // initialize process nice level
453         Sys_InitProcessNice();
454
455         // initialize ixtable
456         Mathlib_Init();
457
458         // register the cvars for session locking
459         Host_InitSession();
460
461         // must be after FS_Init
462         Crypto_Init();
463         Crypto_Init_Commands();
464
465         NetConn_Init();
466         Curl_Init();
467         PRVM_Init();
468         Mod_Init();
469         World_Init();
470         SV_Init();
471         Host_InitLocal();
472
473         Thread_Init();
474         TaskQueue_Init();
475
476         CL_Init();
477
478         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
479         // NOTE: menu commands are freed by Cmd_RestoreInitState
480         Cmd_SaveInitState();
481
482         // FIXME: put this into some neat design, but the menu should be allowed to crash
483         // without crashing the whole game, so this should just be a short-time solution
484
485         // here comes the not so critical stuff
486
487         Host_AddConfigText(cmd_local);
488
489         // if quake.rc is missing, use default
490         if (!FS_FileExists("quake.rc"))
491         {
492                 Cbuf_AddText(cmd_local, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
493                 Cbuf_Execute(cmd_local->cbuf);
494         }
495
496         host.state = host_active;
497
498         CL_StartVideo();
499
500         Log_Start();
501
502         // put up the loading image so the user doesn't stare at a black screen...
503         SCR_BeginLoadingPlaque(true);
504 #ifdef CONFIG_MENU
505         if (cls.state != ca_dedicated)
506                 MR_Init();
507 #endif
508         // check for special benchmark mode
509 // 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)
510         i = Sys_CheckParm("-benchmark");
511         if (i && i + 1 < sys.argc)
512         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
513         {
514                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
515                 Cbuf_Execute(cmd_local->cbuf);
516         }
517
518         // check for special demo mode
519 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
520         i = Sys_CheckParm("-demo");
521         if (i && i + 1 < sys.argc)
522         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
523         {
524                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
525                 Cbuf_Execute(cmd_local->cbuf);
526         }
527
528 #ifdef CONFIG_VIDEO_CAPTURE
529 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
530         i = Sys_CheckParm("-capturedemo");
531         if (i && i + 1 < sys.argc)
532         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
533         {
534                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
535                 Cbuf_Execute((cmd_local)->cbuf);
536         }
537 #endif
538
539         if (cls.state == ca_dedicated || Sys_CheckParm("-listen"))
540         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
541         {
542                 Cbuf_AddText(cmd_local, "startmap_dm\n");
543                 Cbuf_Execute(cmd_local->cbuf);
544         }
545
546         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
547         {
548 #ifdef CONFIG_MENU
549                 Cbuf_AddText(cmd_local, "togglemenu 1\n");
550 #endif
551                 Cbuf_Execute(cmd_local->cbuf);
552         }
553
554         Con_DPrint("========Initialized=========\n");
555
556         if (cls.state != ca_dedicated)
557                 SV_StartThread();
558 }
559
560 /*
561 ===============
562 Host_Shutdown
563
564 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
565 to run quit through here before the final handoff to the sys code.
566 ===============
567 */
568 void Host_Shutdown(void)
569 {
570         static qbool isdown = false;
571
572         if (isdown)
573         {
574                 Con_Print("recursive shutdown\n");
575                 return;
576         }
577         if (setjmp(host.abortframe))
578         {
579                 Con_Print("aborted the quitting frame?!?\n");
580                 return;
581         }
582         isdown = true;
583
584         if(cls.state != ca_dedicated)
585                 CL_Shutdown();
586
587         // end the server thread
588         if (svs.threaded)
589                 SV_StopThread();
590
591         // shut down local server if active
592         if(host.hook.SV_Shutdown)
593                 host.hook.SV_Shutdown();
594
595         // AK shutdown PRVM
596         // AK hmm, no PRVM_Shutdown(); yet
597
598         Host_SaveConfig(CONFIGFILENAME);
599
600         Curl_Shutdown ();
601         NetConn_Shutdown ();
602
603         SV_StopThread();
604         TaskQueue_Shutdown();
605         Thread_Shutdown();
606         Cmd_Shutdown();
607         Sys_Shutdown();
608         Log_Close();
609         Crypto_Shutdown();
610
611         Host_UnlockSession();
612
613         Con_Shutdown();
614         Memory_Shutdown();
615 }
616
617 //============================================================================
618
619 /*
620 ==================
621 Host_Frame
622
623 Runs all active servers
624 ==================
625 */
626 static double Host_Frame(double time)
627 {
628         double cl_wait, sv_wait;
629
630         TaskQueue_Frame(false);
631
632         // keep the random time dependent, but not when playing demos/benchmarking
633         if(!*sv_random_seed.string && !host.restless)
634                 rand();
635
636         NetConn_UpdateSockets();
637
638         Log_DestBuffer_Flush();
639
640         // Run any downloads
641         Curl_Frame();
642
643         // process console commands
644         Cbuf_Frame(host.cbuf);
645
646         R_TimeReport("---");
647
648         sv_wait = SV_Frame(time);
649         cl_wait = CL_Frame(time);
650
651 //      Con_Printf("%6.0f %6.0f\n", cl_wait * 1000000.0, sv_wait * 1000000.0);
652
653         Mem_CheckSentinelsGlobal();
654
655         if(host.restless)
656                 return 0;
657
658         // if the accumulators haven't become positive yet, wait a while
659         if (cls.state == ca_dedicated)
660                 return sv_wait * -1000000.0; // dedicated
661         else if (!sv.active || svs.threaded)
662                 return cl_wait * -1000000.0; // connected to server, main menu, or server is on different thread
663         else
664                 return max(cl_wait, sv_wait) * -1000000.0; // listen server or singleplayer
665 }
666
667 static inline void Host_Sleep(double time)
668 {
669         double delta, time0;
670
671         if(host_maxwait.value <= 0)
672                 time = min(time, 1000000.0);
673         else
674                 time = min(time, host_maxwait.value * 1000.0);
675         if(time < 1)
676                 time = 1; // because we cast to int
677
678         time0 = Sys_DirtyTime();
679         if (sv_checkforpacketsduringsleep.integer && !sys_usenoclockbutbenchmark.integer && !svs.threaded) {
680                 NetConn_SleepMicroseconds((int)time);
681                 if (cls.state != ca_dedicated)
682                         NetConn_ClientFrame(); // helps server browser get good ping values
683                 // TODO can we do the same for ServerFrame? Probably not.
684         }
685         else
686                 Sys_Sleep((int)time);
687         delta = Sys_DirtyTime() - time0;
688         if (delta < 0 || delta >= 1800)
689                 delta = 0;
690         host.sleeptime += delta;
691 //                      R_TimeReport("sleep");
692         return;
693 }
694
695 // Cloudwalk: Most overpowered function declaration...
696 static inline double Host_UpdateTime (double newtime, double oldtime)
697 {
698         double time = newtime - oldtime;
699
700         if (time < 0)
701         {
702                 // warn if it's significant
703                 if (time < -0.01)
704                         Con_Printf(CON_WARN "Host_UpdateTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
705                 time = 0;
706         }
707         else if (time >= 1800)
708         {
709                 Con_Printf(CON_WARN "Host_UpdateTime: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
710                 time = 0;
711         }
712
713         return time;
714 }
715
716 void Host_Main(void)
717 {
718         double time, newtime, oldtime, sleeptime;
719
720         Host_Init(); // Start!
721
722         host.realtime = 0;
723         oldtime = Sys_DirtyTime();
724
725         // Main event loop
726         while(host.state != host_shutdown)
727         {
728                 // Something bad happened, or the server disconnected
729                 if (setjmp(host.abortframe))
730                 {
731                         host.state = host_active; // In case we were loading
732                         continue;
733                 }
734
735                 newtime = host.dirtytime = Sys_DirtyTime();
736                 host.realtime += time = Host_UpdateTime(newtime, oldtime);
737
738                 sleeptime = Host_Frame(time);
739                 oldtime = newtime;
740
741                 if (sleeptime >= 1)
742                 {
743                         Host_Sleep(sleeptime);
744                         continue;
745                 }
746
747                 host.framecount++;
748         }
749
750         return;
751 }