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