]> git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
7ce6406d21faeee15b6749d5b9ba9b0431b8d565
[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 static void Host_Framerate_c(cvar_t *var)
162 {
163         if (var->value < 0.00001 && var->value != 0)
164                 Cvar_SetValueQuick(var, 0);
165 }
166
167 // TODO: Find a better home for this.
168 static void SendCvar_f(cmd_state_t *cmd)
169 {
170         if(cmd->source == src_local && host.hook.SV_SendCvar)
171         {
172                 host.hook.SV_SendCvar(cmd);
173                 return;
174         }
175         if(cmd->source == src_client && host.hook.CL_SendCvar)
176         {
177                 host.hook.CL_SendCvar(cmd);
178                 return;
179         }
180 }
181
182 /*
183 ===============
184 Host_SaveConfig_f
185
186 Writes key bindings and archived cvars to config.cfg
187 ===============
188 */
189 void Host_SaveConfig(const char *file)
190 {
191         qfile_t *f;
192
193 // dedicated servers initialize the host but don't parse and set the
194 // config.cfg cvars
195         // LadyHavoc: don't save a config if it crashed in startup
196         if (host.framecount >= 3 && cls.state != ca_dedicated && !Sys_CheckParm("-benchmark") && !Sys_CheckParm("-capturedemo"))
197         {
198                 f = FS_OpenRealFile(file, "wb", false);
199                 if (!f)
200                 {
201                         Con_Printf(CON_ERROR "Couldn't write %s\n", file);
202                         return;
203                 }
204                 else
205                         Con_Printf("Saving config to %s ...\n", file);
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
221         Host_SaveConfig(file);
222 }
223
224 static void Host_AddConfigText(cmd_state_t *cmd)
225 {
226         // set up the default startmap_sp and startmap_dm aliases (mods can
227         // override these) and then execute the quake.rc startup script
228         if (gamemode == GAME_NEHAHRA)
229                 Cbuf_InsertText(cmd, "alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec " STARTCONFIGFILENAME "\n");
230         else if (gamemode == GAME_TRANSFUSION)
231                 Cbuf_InsertText(cmd, "alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec " STARTCONFIGFILENAME "\n");
232         else if (gamemode == GAME_TEU)
233                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
234         else
235                 Cbuf_InsertText(cmd, "alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec " STARTCONFIGFILENAME "\n");
236
237         // if quake.rc is missing, use default
238         if (!FS_FileExists(STARTCONFIGFILENAME))
239                 Cbuf_InsertText(cmd, "exec default.cfg\nexec " CONFIGFILENAME "\nexec autoexec.cfg\n");
240 }
241
242 /*
243 ===============
244 Host_LoadConfig_f
245
246 Resets key bindings and cvars to defaults and then reloads scripts
247 ===============
248 */
249 static void Host_LoadConfig_f(cmd_state_t *cmd)
250 {
251 #ifdef CONFIG_MENU
252         // Xonotic QC complains/breaks if its cvars are deleted before its m_shutdown() is called
253         if(MR_Shutdown)
254                 MR_Shutdown();
255 #endif
256         Cmd_RestoreInitState();
257 #ifdef CONFIG_MENU
258         // Must re-add menu.c commands or load menu.dat before executing quake.rc or handling events
259         MR_Init();
260 #endif
261         // exec startup scripts again
262         Host_AddConfigText(cmd);
263 }
264
265 /*
266 =======================
267 Host_InitLocal
268 ======================
269 */
270 extern cvar_t r_texture_jpeg_fastpicmip;
271 static void Host_InitLocal (void)
272 {
273         Cmd_AddCommand(CF_SHARED, "quit", Host_Quit_f, "quit the game");
274         Cmd_AddCommand(CF_SHARED, "version", Host_Version_f, "print engine version");
275         Cmd_AddCommand(CF_SHARED, "saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
276         Cmd_AddCommand(CF_SHARED, "loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
277         Cmd_AddCommand(CF_SHARED, "sendcvar", SendCvar_f, "sends the value of a cvar to the server as a sentcvar command, for use by QuakeC");
278         Cvar_RegisterVariable (&host_framerate);
279         Cvar_RegisterCallback (&host_framerate, Host_Framerate_c);
280         Cvar_RegisterVariable (&host_speeds);
281         Cvar_RegisterVariable (&host_isclient);
282
283         Cvar_RegisterVariable (&developer);
284         Cvar_RegisterVariable (&developer_extra);
285         Cvar_RegisterVariable (&developer_insane);
286         Cvar_RegisterVariable (&developer_loadfile);
287         Cvar_RegisterVariable (&developer_loading);
288         Cvar_RegisterVariable (&developer_entityparsing);
289
290         Cvar_RegisterVariable (&timestamps);
291         Cvar_RegisterVariable (&timeformat);
292
293         Cvar_RegisterVariable (&r_texture_jpeg_fastpicmip);
294 }
295
296 char engineversion[128];
297
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         char vabuf[1024];
373
374         Sys_SDL_Init();
375
376         Memory_Init();
377
378         host.hook.ConnectLocal = NULL;
379         host.hook.Disconnect = NULL;
380         host.hook.ToggleMenu = NULL;
381         host.hook.CL_Intermission = NULL;
382         host.hook.SV_Shutdown = NULL;
383
384         host.state = host_init;
385
386         if (setjmp(host.abortframe)) // Huh?!
387                 Sys_Error("Engine initialization failed. Check the console (if available) for additional information.\n");
388
389         if (Sys_CheckParm("-profilegameonly"))
390                 Sys_AllowProfiling(false);
391
392         // LadyHavoc: quake never seeded the random number generator before... heh
393         if (Sys_CheckParm("-benchmark"))
394                 srand(0); // predictable random sequence for -benchmark
395         else
396                 srand((unsigned int)time(NULL));
397
398         // FIXME: this is evil, but possibly temporary
399         // LadyHavoc: doesn't seem very temporary...
400         // LadyHavoc: made this a saved cvar
401 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
402         if (Sys_CheckParm("-developer"))
403         {
404                 developer.value = developer.integer = 1;
405                 developer.string = "1";
406         }
407
408         if (Sys_CheckParm("-developer2") || Sys_CheckParm("-developer3"))
409         {
410                 developer.value = developer.integer = 1;
411                 developer.string = "1";
412                 developer_extra.value = developer_extra.integer = 1;
413                 developer_extra.string = "1";
414                 developer_insane.value = developer_insane.integer = 1;
415                 developer_insane.string = "1";
416                 developer_memory.value = developer_memory.integer = 1;
417                 developer_memory.string = "1";
418                 developer_memorydebug.value = developer_memorydebug.integer = 1;
419                 developer_memorydebug.string = "1";
420         }
421
422         if (Sys_CheckParm("-developer3"))
423         {
424                 gl_paranoid.integer = 1;gl_paranoid.string = "1";
425                 gl_printcheckerror.integer = 1;gl_printcheckerror.string = "1";
426         }
427
428         // -dedicated is checked in SV_ServerOptions() but that's too late for Cvar_RegisterVariable() to skip all the client-only cvars
429         if (Sys_CheckParm ("-dedicated") || !cl_available)
430                 cls.state = ca_dedicated;
431
432         // initialize console command/cvar/alias/command execution systems
433         Cmd_Init();
434
435         // initialize memory subsystem cvars/commands
436         Memory_Init_Commands();
437
438         // initialize console and logging and its cvars/commands
439         // this enables Con_Printf() messages to be coloured
440         Con_Init();
441
442         // initialize various cvars that could not be initialized earlier
443         u8_Init();
444         Curl_Init_Commands();
445         Sys_Init_Commands();
446         COM_Init_Commands();
447
448         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name, gamename)
449         FS_Init();
450
451         // ASAP! construct a version string for the corner of the console and for crash messages
452         dpsnprintf (engineversion, sizeof (engineversion), "%s %s%s, buildstring: %s", gamename, DP_OS_NAME, cls.state == ca_dedicated ? " dedicated" : "", buildstring);
453         Con_Printf("%s\n", engineversion);
454
455         // initialize process nice level
456         Sys_InitProcessNice();
457
458         // initialize ixtable
459         Mathlib_Init();
460
461         // register the cvars for session locking
462         Host_InitSession();
463
464         // must be after FS_Init
465         Crypto_Init();
466         Crypto_Init_Commands();
467
468         NetConn_Init();
469         Curl_Init();
470         PRVM_Init();
471         Mod_Init();
472         World_Init();
473         SV_Init();
474         Host_InitLocal();
475
476         Thread_Init();
477         TaskQueue_Init();
478
479         CL_Init();
480
481         // save off current state of aliases, commands and cvars for later restore if FS_GameDir_f is called
482         // NOTE: menu commands are freed by Cmd_RestoreInitState
483         Cmd_SaveInitState();
484
485         // FIXME: put this into some neat design, but the menu should be allowed to crash
486         // without crashing the whole game, so this should just be a short-time solution
487
488         // here comes the not so critical stuff
489
490         Host_AddConfigText(cmd_local);
491         Cbuf_Execute(cmd_local->cbuf); // cannot be in Host_AddConfigText as that would cause Host_LoadConfig_f to loop!
492
493         host.state = host_active;
494
495         CL_StartVideo();
496
497         Log_Start();
498
499         if (cls.state != ca_dedicated)
500         {
501                 // put up the loading image so the user doesn't stare at a black screen...
502                 SCR_BeginLoadingPlaque(true);
503                 S_Startup();
504 #ifdef CONFIG_MENU
505                 MR_Init();
506 #endif
507         }
508
509         // check for special benchmark mode
510 // 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)
511         i = Sys_CheckParm("-benchmark");
512         if (i && i + 1 < sys.argc)
513         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
514         {
515                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "timedemo %s\n", sys.argv[i + 1]));
516                 Cbuf_Execute(cmd_local->cbuf);
517         }
518
519         // check for special demo mode
520 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
521         i = Sys_CheckParm("-demo");
522         if (i && i + 1 < sys.argc)
523         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
524         {
525                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "playdemo %s\n", sys.argv[i + 1]));
526                 Cbuf_Execute(cmd_local->cbuf);
527         }
528
529 #ifdef CONFIG_VIDEO_CAPTURE
530 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
531         i = Sys_CheckParm("-capturedemo");
532         if (i && i + 1 < sys.argc)
533         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
534         {
535                 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "playdemo %s\ncl_capturevideo 1\n", sys.argv[i + 1]));
536                 Cbuf_Execute((cmd_local)->cbuf);
537         }
538 #endif
539
540         if (cls.state == ca_dedicated || Sys_CheckParm("-listen"))
541         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
542         {
543                 Cbuf_AddText(cmd_local, "startmap_dm\n");
544                 Cbuf_Execute(cmd_local->cbuf);
545         }
546
547         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
548         {
549 #ifdef CONFIG_MENU
550                 Cbuf_AddText(cmd_local, "togglemenu 1\n");
551 #endif
552                 Cbuf_Execute(cmd_local->cbuf);
553         }
554
555         Con_DPrint("========Initialized=========\n");
556
557         if (cls.state != ca_dedicated)
558                 SV_StartThread();
559 }
560
561 /*
562 ===============
563 Host_Shutdown
564
565 Cleanly shuts down after the main loop exits.
566 ===============
567 */
568 static void Host_Shutdown(void)
569 {
570         if (Sys_CheckParm("-profilegameonly"))
571                 Sys_AllowProfiling(false);
572
573         if(cls.state != ca_dedicated)
574                 CL_Shutdown();
575
576         // end the server thread
577         if (svs.threaded)
578                 SV_StopThread();
579
580         // shut down local server if active
581         if(host.hook.SV_Shutdown)
582                 host.hook.SV_Shutdown();
583
584         // AK shutdown PRVM
585         // AK hmm, no PRVM_Shutdown(); yet
586
587         Host_SaveConfig(CONFIGFILENAME);
588
589         Curl_Shutdown ();
590         NetConn_Shutdown ();
591
592         SV_StopThread();
593         TaskQueue_Shutdown();
594         Thread_Shutdown();
595         Cmd_Shutdown();
596         Sys_SDL_Shutdown();
597         Log_Close();
598         Crypto_Shutdown();
599
600         Host_UnlockSession();
601
602         Con_Shutdown();
603         Memory_Shutdown();
604 }
605
606 //============================================================================
607
608 /*
609 ==================
610 Host_Frame
611
612 Runs all active servers
613 ==================
614 */
615 static double Host_Frame(double time)
616 {
617         double cl_wait, sv_wait;
618
619         TaskQueue_Frame(false);
620
621         // keep the random time dependent, but not when playing demos/benchmarking
622         if(!*sv_random_seed.string && !host.restless)
623                 rand();
624
625         NetConn_UpdateSockets();
626
627         Log_DestBuffer_Flush();
628
629         // Run any downloads
630         Curl_Frame();
631
632         // get new SDL events and add commands from keybindings to the cbuf
633         Sys_SDL_HandleEvents();
634
635         // process console commands
636         Cbuf_Frame(host.cbuf);
637
638         R_TimeReport("---");
639
640         // if the accumulators haven't become positive yet, wait a while
641         sv_wait = - SV_Frame(time);
642         cl_wait = - CL_Frame(time);
643
644         Mem_CheckSentinelsGlobal();
645
646         if (cls.state == ca_dedicated)
647                 return sv_wait; // dedicated
648         else if (!sv.active || svs.threaded)
649                 return cl_wait; // connected to server, main menu, or server is on different thread
650         else
651                 return min(cl_wait, sv_wait); // listen server or singleplayer
652 }
653
654 // Cloudwalk: Most overpowered function declaration...
655 static inline double Host_UpdateTime (double newtime, double oldtime)
656 {
657         double time = newtime - oldtime;
658
659         if (time < 0)
660         {
661                 // warn if it's significant
662                 if (time < -0.01)
663                         Con_Printf(CON_WARN "Host_UpdateTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, time);
664                 time = 0;
665         }
666         else if (time >= 1800)
667         {
668                 Con_Printf(CON_WARN "Host_UpdateTime: time stepped forward (went from %f to %f, difference %f)\n", oldtime, newtime, time);
669                 time = 0;
670         }
671
672         return time;
673 }
674
675 void Host_Main(void)
676 {
677         double time, oldtime, sleeptime;
678
679         Host_Init(); // Start!
680
681         host.realtime = 0;
682         oldtime = Sys_DirtyTime();
683
684         // Main event loop
685         while(host.state < host_shutdown) // see Sys_HandleCrash() comments
686         {
687                 // Something bad happened, or the server disconnected
688                 if (setjmp(host.abortframe))
689                 {
690                         host.state = host_active; // In case we were loading
691                         continue;
692                 }
693
694                 host.dirtytime = Sys_DirtyTime();
695                 host.realtime += time = Host_UpdateTime(host.dirtytime, oldtime);
696                 oldtime = host.dirtytime;
697
698                 sleeptime = Host_Frame(time);
699                 ++host.framecount;
700                 sleeptime -= Sys_DirtyTime() - host.dirtytime; // execution time
701                 host.sleeptime = Sys_Sleep(sleeptime);
702         }
703
704         Host_Shutdown();
705 }