]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
fix memory leaks in server csqc
[xonotic/darkplaces.git] / host.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // host.c -- coordinates spawning and killing of local servers
21
22 #include "quakedef.h"
23
24 #include <time.h>
25 #include "libcurl.h"
26 #include "cdaudio.h"
27 #include "cl_gecko.h"
28 #include "cl_video.h"
29 #include "progsvm.h"
30 #include "csprogs.h"
31 #include "sv_demo.h"
32
33 /*
34
35 A server can always be started, even if the system started out as a client
36 to a remote system.
37
38 A client can NOT be started if the system started as a dedicated server.
39
40 Memory is cleared / released when a server or client begins, not when they end.
41
42 */
43
44 // how many frames have occurred
45 // (checked by Host_Error and Host_SaveConfig_f)
46 int host_framecount = 0;
47 // LordHavoc: set when quit is executed
48 qboolean host_shuttingdown = false;
49
50 // the real time since application started, without any slowmo or clamping
51 double realtime;
52
53 // current client
54 client_t *host_client;
55
56 jmp_buf host_abortframe;
57 double host_starttime = 0;
58
59 // pretend frames take this amount of time (in seconds), 0 = realtime
60 cvar_t host_framerate = {0, "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"};
61 // shows time used by certain subsystems
62 cvar_t host_speeds = {0, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
63 cvar_t host_sleep = {0, "host_sleep","1", "gives up some processing time to other applications each frame, value in milliseconds"};
64 cvar_t cl_minfps = {CVAR_SAVE, "cl_minfps", "40", "minimum fps target - while the rendering performance is below this, it will drift toward lower quality"};
65 cvar_t cl_minfps_fade = {CVAR_SAVE, "cl_minfps_fade", "0.2", "how fast the quality adapts to varying framerate"};
66 cvar_t cl_minfps_qualitymax = {CVAR_SAVE, "cl_minfps_qualitymax", "1", "highest allowed drawdistance multiplier"};
67 cvar_t cl_minfps_qualitymin = {CVAR_SAVE, "cl_minfps_qualitymin", "0.25", "lowest allowed drawdistance multiplier"};
68 cvar_t cl_minfps_qualitypower = {CVAR_SAVE, "cl_minfps_qualitypower", "4", "raises quality value to a power of itself, higher values make quality drop more sharply in relation to framerate"};
69 cvar_t cl_minfps_qualityscale = {CVAR_SAVE, "cl_minfps_qualityscale", "0.5", "multiplier for quality"};
70 cvar_t cl_maxfps = {CVAR_SAVE, "cl_maxfps", "0", "maximum fps cap, 0 = unlimited, if game is running faster than this it will wait before running another frame (useful to make cpu time available to other programs)"};
71 cvar_t cl_maxidlefps = {CVAR_SAVE, "cl_maxidlefps", "20", "maximum fps cap when the game is not the active window (makes cpu time available to other programs"};
72
73 cvar_t developer = {0, "developer","0", "prints additional debugging messages and information (recommended for modders and level designers)"};
74 cvar_t developer_loadfile = {0, "developer_loadfile","0", "prints name and size of every file loaded via the FS_LoadFile function (which is almost everything)"};
75 cvar_t developer_loading = {0, "developer_loading","0", "prints information about files as they are loaded or unloaded successfully"};
76 cvar_t developer_entityparsing = {0, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
77
78 cvar_t timestamps = {CVAR_SAVE, "timestamps", "0", "prints timestamps on console messages"};
79 cvar_t timeformat = {CVAR_SAVE, "timeformat", "[%Y-%m-%d %H:%M:%S] ", "time format to use on timestamped console messages"};
80
81 /*
82 ================
83 Host_AbortCurrentFrame
84
85 aborts the current host frame and goes on with the next one
86 ================
87 */
88 void Host_AbortCurrentFrame(void)
89 {
90         longjmp (host_abortframe, 1);
91 }
92
93 /*
94 ================
95 Host_Error
96
97 This shuts down both the client and server
98 ================
99 */
100 void Host_Error (const char *error, ...)
101 {
102         static char hosterrorstring1[MAX_INPUTLINE];
103         static char hosterrorstring2[MAX_INPUTLINE];
104         static qboolean hosterror = false;
105         va_list argptr;
106
107         // turn off rcon redirect if it was active when the crash occurred
108         // to prevent loops when it is a networking problem
109         Con_Rcon_Redirect_Abort();
110
111         va_start (argptr,error);
112         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
113         va_end (argptr);
114
115         Con_Printf("Host_Error: %s\n", hosterrorstring1);
116
117         // LordHavoc: if crashing very early, or currently shutting down, do
118         // Sys_Error instead
119         if (host_framecount < 3 || host_shuttingdown)
120                 Sys_Error ("Host_Error: %s", hosterrorstring1);
121
122         if (hosterror)
123                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
124         hosterror = true;
125
126         strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
127
128         CL_Parse_DumpPacket();
129
130         CL_Parse_ErrorCleanUp();
131
132         //PR_Crash();
133
134         // print out where the crash happened, if it was caused by QC (and do a cleanup)
135         PRVM_Crash();
136
137
138         Host_ShutdownServer ();
139
140         if (cls.state == ca_dedicated)
141                 Sys_Error ("Host_Error: %s",hosterrorstring2);  // dedicated servers exit
142
143         CL_Disconnect ();
144         cls.demonum = -1;
145
146         hosterror = false;
147
148         Host_AbortCurrentFrame();
149 }
150
151 void Host_ServerOptions (void)
152 {
153         int i;
154
155         // general default
156         svs.maxclients = 8;
157
158 // COMMANDLINEOPTION: Server: -dedicated [playerlimit] starts a dedicated server (with a command console), default playerlimit is 8
159 // COMMANDLINEOPTION: Server: -listen [playerlimit] starts a multiplayer server with graphical client, like singleplayer but other players can connect, default playerlimit is 8
160         // if no client is in the executable or -dedicated is specified on
161         // commandline, start a dedicated server
162         i = COM_CheckParm ("-dedicated");
163         if (i || !cl_available)
164         {
165                 cls.state = ca_dedicated;
166                 // check for -dedicated specifying how many players
167                 if (i && i + 1 < com_argc && atoi (com_argv[i+1]) >= 1)
168                         svs.maxclients = atoi (com_argv[i+1]);
169                 if (COM_CheckParm ("-listen"))
170                         Con_Printf ("Only one of -dedicated or -listen can be specified\n");
171                 // default sv_public on for dedicated servers (often hosted by serious administrators), off for listen servers (often hosted by clueless users)
172                 Cvar_SetValue("sv_public", 1);
173         }
174         else if (cl_available)
175         {
176                 // client exists and not dedicated, check if -listen is specified
177                 cls.state = ca_disconnected;
178                 i = COM_CheckParm ("-listen");
179                 if (i)
180                 {
181                         // default players unless specified
182                         if (i + 1 < com_argc && atoi (com_argv[i+1]) >= 1)
183                                 svs.maxclients = atoi (com_argv[i+1]);
184                 }
185                 else
186                 {
187                         // default players in some games, singleplayer in most
188                         if (gamemode != GAME_GOODVSBAD2 && gamemode != GAME_NEXUIZ && gamemode != GAME_BATTLEMECH)
189                                 svs.maxclients = 1;
190                 }
191         }
192
193         svs.maxclients = svs.maxclients_next = bound(1, svs.maxclients, MAX_SCOREBOARD);
194
195         svs.clients = (client_t *)Mem_Alloc(sv_mempool, sizeof(client_t) * svs.maxclients);
196
197         if (svs.maxclients > 1 && !deathmatch.integer && !coop.integer)
198                 Cvar_SetValueQuick(&deathmatch, 1);
199 }
200
201 /*
202 =======================
203 Host_InitLocal
204 ======================
205 */
206 void Host_SaveConfig_f(void);
207 void Host_LoadConfig_f(void);
208 extern cvar_t sv_writepicture_quality;
209 static void Host_InitLocal (void)
210 {
211         Cmd_AddCommand("saveconfig", Host_SaveConfig_f, "save settings to config.cfg (or a specified filename) immediately (also automatic when quitting)");
212         Cmd_AddCommand("loadconfig", Host_LoadConfig_f, "reset everything and reload configs");
213
214         Cvar_RegisterVariable (&host_framerate);
215         Cvar_RegisterVariable (&host_speeds);
216         Cvar_RegisterVariable (&host_sleep);
217         Cvar_RegisterVariable (&cl_minfps);
218         Cvar_RegisterVariable (&cl_minfps_fade);
219         Cvar_RegisterVariable (&cl_minfps_qualitymax);
220         Cvar_RegisterVariable (&cl_minfps_qualitymin);
221         Cvar_RegisterVariable (&cl_minfps_qualitypower);
222         Cvar_RegisterVariable (&cl_minfps_qualityscale);
223         Cvar_RegisterVariable (&cl_maxfps);
224         Cvar_RegisterVariable (&cl_maxidlefps);
225
226         Cvar_RegisterVariable (&developer);
227         Cvar_RegisterVariable (&developer_loadfile);
228         Cvar_RegisterVariable (&developer_loading);
229         Cvar_RegisterVariable (&developer_entityparsing);
230
231         Cvar_RegisterVariable (&timestamps);
232         Cvar_RegisterVariable (&timeformat);
233
234         Cvar_RegisterVariable (&sv_writepicture_quality);
235 }
236
237
238 /*
239 ===============
240 Host_SaveConfig_f
241
242 Writes key bindings and archived cvars to config.cfg
243 ===============
244 */
245 void Host_SaveConfig_to(const char *file)
246 {
247         qfile_t *f;
248
249 // dedicated servers initialize the host but don't parse and set the
250 // config.cfg cvars
251         // LordHavoc: don't save a config if it crashed in startup
252         if (host_framecount >= 3 && cls.state != ca_dedicated && !COM_CheckParm("-benchmark") && !COM_CheckParm("-capturedemo"))
253         {
254                 f = FS_OpenRealFile(file, "wb", false);
255                 if (!f)
256                 {
257                         Con_Printf("Couldn't write %s.\n", file);
258                         return;
259                 }
260
261                 Key_WriteBindings (f);
262                 Cvar_WriteVariables (f);
263
264                 FS_Close (f);
265         }
266 }
267 void Host_SaveConfig(void)
268 {
269         Host_SaveConfig_to("config.cfg");
270 }
271 void Host_SaveConfig_f(void)
272 {
273         const char *file = "config.cfg";
274
275         if(Cmd_Argc() >= 2) {
276                 file = Cmd_Argv(1);
277                 Con_Printf("Saving to %s\n", file);
278         }
279
280         Host_SaveConfig_to(file);
281 }
282
283 /*
284 ===============
285 Host_LoadConfig_f
286
287 Resets key bindings and cvars to defaults and then reloads scripts
288 ===============
289 */
290 void Host_LoadConfig_f(void)
291 {
292         // unlock the cvar default strings so they can be updated by the new default.cfg
293         Cvar_UnlockDefaults();
294         // reset cvars to their defaults, and then exec startup scripts again
295         Cbuf_InsertText("cvar_resettodefaults_all;exec quake.rc\n");
296 }
297
298 /*
299 =================
300 SV_ClientPrint
301
302 Sends text across to be displayed
303 FIXME: make this just a stuffed echo?
304 =================
305 */
306 void SV_ClientPrint(const char *msg)
307 {
308         if (host_client->netconnection)
309         {
310                 MSG_WriteByte(&host_client->netconnection->message, svc_print);
311                 MSG_WriteString(&host_client->netconnection->message, msg);
312         }
313 }
314
315 /*
316 =================
317 SV_ClientPrintf
318
319 Sends text across to be displayed
320 FIXME: make this just a stuffed echo?
321 =================
322 */
323 void SV_ClientPrintf(const char *fmt, ...)
324 {
325         va_list argptr;
326         char msg[MAX_INPUTLINE];
327
328         va_start(argptr,fmt);
329         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
330         va_end(argptr);
331
332         SV_ClientPrint(msg);
333 }
334
335 /*
336 =================
337 SV_BroadcastPrint
338
339 Sends text to all active clients
340 =================
341 */
342 void SV_BroadcastPrint(const char *msg)
343 {
344         int i;
345         client_t *client;
346
347         for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
348         {
349                 if (client->active && client->netconnection)
350                 {
351                         MSG_WriteByte(&client->netconnection->message, svc_print);
352                         MSG_WriteString(&client->netconnection->message, msg);
353                 }
354         }
355
356         if (sv_echobprint.integer && cls.state == ca_dedicated)
357                 Con_Print(msg);
358 }
359
360 /*
361 =================
362 SV_BroadcastPrintf
363
364 Sends text to all active clients
365 =================
366 */
367 void SV_BroadcastPrintf(const char *fmt, ...)
368 {
369         va_list argptr;
370         char msg[MAX_INPUTLINE];
371
372         va_start(argptr,fmt);
373         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
374         va_end(argptr);
375
376         SV_BroadcastPrint(msg);
377 }
378
379 /*
380 =================
381 Host_ClientCommands
382
383 Send text over to the client to be executed
384 =================
385 */
386 void Host_ClientCommands(const char *fmt, ...)
387 {
388         va_list argptr;
389         char string[MAX_INPUTLINE];
390
391         if (!host_client->netconnection)
392                 return;
393
394         va_start(argptr,fmt);
395         dpvsnprintf(string, sizeof(string), fmt, argptr);
396         va_end(argptr);
397
398         MSG_WriteByte(&host_client->netconnection->message, svc_stufftext);
399         MSG_WriteString(&host_client->netconnection->message, string);
400 }
401
402 /*
403 =====================
404 SV_DropClient
405
406 Called when the player is getting totally kicked off the host
407 if (crash = true), don't bother sending signofs
408 =====================
409 */
410 void SV_DropClient(qboolean crash)
411 {
412         int i;
413         Con_Printf("Client \"%s\" dropped\n", host_client->name);
414
415         SV_StopDemoRecording(host_client);
416
417         // make sure edict is not corrupt (from a level change for example)
418         host_client->edict = PRVM_EDICT_NUM(host_client - svs.clients + 1);
419
420         if (host_client->netconnection)
421         {
422                 // free the client (the body stays around)
423                 if (!crash)
424                 {
425                         // LordHavoc: no opportunity for resending, so use unreliable 3 times
426                         unsigned char bufdata[8];
427                         sizebuf_t buf;
428                         memset(&buf, 0, sizeof(buf));
429                         buf.data = bufdata;
430                         buf.maxsize = sizeof(bufdata);
431                         MSG_WriteByte(&buf, svc_disconnect);
432                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, false);
433                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, false);
434                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol, 10000, false);
435                 }
436                 // break the net connection
437                 NetConn_Close(host_client->netconnection);
438                 host_client->netconnection = NULL;
439         }
440
441         // call qc ClientDisconnect function
442         // LordHavoc: don't call QC if server is dead (avoids recursive
443         // Host_Error in some mods when they run out of edicts)
444         if (host_client->clientconnectcalled && sv.active && host_client->edict)
445         {
446                 // call the prog function for removing a client
447                 // this will set the body to a dead frame, among other things
448                 int saveSelf = prog->globals.server->self;
449                 host_client->clientconnectcalled = false;
450                 prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
451                 PRVM_ExecuteProgram(prog->globals.server->ClientDisconnect, "QC function ClientDisconnect is missing");
452                 prog->globals.server->self = saveSelf;
453         }
454
455         // if a download is active, close it
456         if (host_client->download_file)
457         {
458                 Con_DPrintf("Download of %s aborted when %s dropped\n", host_client->download_name, host_client->name);
459                 FS_Close(host_client->download_file);
460                 host_client->download_file = NULL;
461                 host_client->download_name[0] = 0;
462                 host_client->download_expectedposition = 0;
463                 host_client->download_started = false;
464         }
465
466         // remove leaving player from scoreboard
467         host_client->name[0] = 0;
468         host_client->colors = 0;
469         host_client->frags = 0;
470         // send notification to all clients
471         // get number of client manually just to make sure we get it right...
472         i = host_client - svs.clients;
473         MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
474         MSG_WriteByte (&sv.reliable_datagram, i);
475         MSG_WriteString (&sv.reliable_datagram, host_client->name);
476         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
477         MSG_WriteByte (&sv.reliable_datagram, i);
478         MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
479         MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
480         MSG_WriteByte (&sv.reliable_datagram, i);
481         MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
482
483         // free the client now
484         if (host_client->entitydatabase)
485                 EntityFrame_FreeDatabase(host_client->entitydatabase);
486         if (host_client->entitydatabase4)
487                 EntityFrame4_FreeDatabase(host_client->entitydatabase4);
488         if (host_client->entitydatabase5)
489                 EntityFrame5_FreeDatabase(host_client->entitydatabase5);
490
491         if (sv.active)
492         {
493                 // clear a fields that matter to DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS, and also frags
494                 PRVM_ED_ClearEdict(host_client->edict);
495         }
496
497         // clear the client struct (this sets active to false)
498         memset(host_client, 0, sizeof(*host_client));
499
500         // update server listing on the master because player count changed
501         // (which the master uses for filtering empty/full servers)
502         NetConn_Heartbeat(1);
503
504         if (sv.loadgame)
505         {
506                 for (i = 0;i < svs.maxclients;i++)
507                         if (svs.clients[i].active && !svs.clients[i].spawned)
508                                 break;
509                 if (i == svs.maxclients)
510                 {
511                         Con_Printf("Loaded game, everyone rejoined - unpausing\n");
512                         sv.paused = sv.loadgame = false; // we're basically done with loading now
513                 }
514         }
515 }
516
517 /*
518 ==================
519 Host_ShutdownServer
520
521 This only happens at the end of a game, not between levels
522 ==================
523 */
524 void Host_ShutdownServer(void)
525 {
526         int i;
527
528         Con_DPrintf("Host_ShutdownServer\n");
529
530         if (!sv.active)
531                 return;
532
533         NetConn_Heartbeat(2);
534         NetConn_Heartbeat(2);
535
536 // make sure all the clients know we're disconnecting
537         SV_VM_Begin();
538         if(prog->loaded)
539                 if(prog->funcoffsets.SV_Shutdown)
540                 {
541                         func_t s = prog->funcoffsets.SV_Shutdown;
542                         prog->funcoffsets.SV_Shutdown = 0; // prevent it from getting called again
543                         PRVM_ExecuteProgram(s,"SV_Shutdown() required");
544                 }
545         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
546                 if (host_client->active)
547                         SV_DropClient(false); // server shutdown
548         SV_VM_End();
549
550         NetConn_CloseServerPorts();
551
552         if(sv.csqc_progdata)
553         {
554                 Con_DPrintf("Unloading CSQC data.\n");
555                 Mem_Free(sv.csqc_progdata);
556                 if(sv.csqc_progdata_deflated)
557                         Mem_Free(sv.csqc_progdata_deflated);
558         }
559
560         sv.active = false;
561 //
562 // clear structures
563 //
564         memset(&sv, 0, sizeof(sv));
565         memset(svs.clients, 0, svs.maxclients*sizeof(client_t));
566 }
567
568
569 //============================================================================
570
571 /*
572 ===================
573 Host_GetConsoleCommands
574
575 Add them exactly as if they had been typed at the console
576 ===================
577 */
578 void Host_GetConsoleCommands (void)
579 {
580         char *cmd;
581
582         while (1)
583         {
584                 cmd = Sys_ConsoleInput ();
585                 if (!cmd)
586                         break;
587                 Cbuf_AddText (cmd);
588         }
589 }
590
591 /*
592 ==================
593 Host_TimeReport
594
595 Returns a time report string, for example for
596 ==================
597 */
598 const char *Host_TimingReport()
599 {
600         return va("%.1f%% CPU, %.2f%% lost, offset avg %.1fms, max %.1fms, sdev %.1fms", svs.perf_cpuload * 100, svs.perf_lost * 100, svs.perf_offset_avg * 1000, svs.perf_offset_max * 1000, svs.perf_offset_sdev * 1000);
601 }
602
603 /*
604 ==================
605 Host_Frame
606
607 Runs all active servers
608 ==================
609 */
610 static void Host_Init(void);
611 void Host_Main(void)
612 {
613         double time1 = 0;
614         double time2 = 0;
615         double time3 = 0;
616         double cl_timer, sv_timer;
617         double clframetime, deltarealtime, oldrealtime;
618         double wait;
619         int pass1, pass2, pass3, i;
620
621         Host_Init();
622
623         cl_timer = 0;
624         sv_timer = 0;
625
626         realtime = host_starttime = Sys_DoubleTime();
627         for (;;)
628         {
629                 if (setjmp(host_abortframe))
630                         continue;                       // something bad happened, or the server disconnected
631
632                 oldrealtime = realtime;
633                 realtime = Sys_DoubleTime();
634
635                 deltarealtime = realtime - oldrealtime;
636                 cl_timer += deltarealtime;
637                 sv_timer += deltarealtime;
638
639                 svs.perf_acc_realtime += deltarealtime;
640
641                 // Look for clients who have spawned
642                 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
643                         if(host_client->spawned)
644                                 if(host_client->netconnection)
645                                         break;
646                 if(i == svs.maxclients)
647                 {
648                         // Nobody is looking? Then we won't do timing...
649                         // Instead, reset it to zero
650                         svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
651                 }
652                 else if(svs.perf_acc_realtime > 5)
653                 {
654                         svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
655                         svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
656                         if(svs.perf_acc_offset_samples > 0)
657                         {
658                                 svs.perf_offset_max = svs.perf_acc_offset_max;
659                                 svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
660                                 svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
661                         }
662                         if(svs.perf_lost > 0)
663                                 Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport());
664                         svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
665                 }
666
667                 if (slowmo.value < 0.00001 && slowmo.value != 0)
668                         Cvar_SetValue("slowmo", 0);
669                 if (host_framerate.value < 0.00001 && host_framerate.value != 0)
670                         Cvar_SetValue("host_framerate", 0);
671
672                 // keep the random time dependent, but not when playing demos/benchmarking
673                 if(!*sv_random_seed.string && !cls.demoplayback)
674                         rand();
675
676                 cl.islocalgame = NetConn_IsLocalGame();
677
678                 // begin gathering mouse input
679                 in_mouse_x = in_mouse_y = 0;
680
681                 // get new key events
682                 Sys_SendKeyEvents();
683
684                 NetConn_UpdateSockets();
685
686                 Log_DestBuffer_Flush();
687
688                 // receive packets on each main loop iteration, as the main loop may
689                 // be undersleeping due to select() detecting a new packet
690                 if (sv.active)
691                         NetConn_ServerFrame();
692
693                 Curl_Run();
694
695                 // check for commands typed to the host
696                 Host_GetConsoleCommands();
697
698                 // when a server is running we only execute console commands on server frames
699                 // (this mainly allows frikbot .way config files to work properly by staying in sync with the server qc)
700                 // otherwise we execute them on client frames
701                 if (sv.active ? sv_timer > 0 : cl_timer > 0)
702                 {
703                         // process console commands
704                         Cbuf_Execute();
705                 }
706
707                 //Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);
708
709                 // if the accumulators haven't become positive yet, wait a while
710                 if (cls.state == ca_dedicated)
711                         wait = sv_timer * -1000000.0;
712                 else if (!sv.active)
713                         wait = cl_timer * -1000000.0;
714                 else
715                         wait = max(cl_timer, sv_timer) * -1000000.0;
716                 wait = bound(0, wait, 100000);
717
718                 if (!cls.timedemo && wait >= 1)
719                 {
720                         double time0 = Sys_DoubleTime();
721                         if (sv_checkforpacketsduringsleep.integer)
722                                 NetConn_SleepMicroseconds((int)wait);
723                         else
724                                 Sys_Sleep((int)wait);
725                         svs.perf_acc_sleeptime += Sys_DoubleTime() - time0;
726                         continue;
727                 }
728
729         //-------------------
730         //
731         // server operations
732         //
733         //-------------------
734
735                 // limit the frametime steps to no more than 100ms each
736                 if (cl_timer > 0.1)
737                         cl_timer = 0.1;
738                 if (sv_timer > 0.1)
739                 {
740                         svs.perf_acc_lost += (sv_timer - 0.1);
741                         sv_timer = 0.1;
742                 }
743
744                 if (sv.active && sv_timer > 0)
745                 {
746                         // execute one or more server frames, with an upper limit on how much
747                         // execution time to spend on server frames to avoid freezing the game if
748                         // the server is overloaded, this execution time limit means the game will
749                         // slow down if the server is taking too long.
750                         int framecount, framelimit = 1;
751                         double advancetime, aborttime = 0;
752                         float offset;
753
754                         // run the world state
755                         // don't allow simulation to run too fast or too slow or logic glitches can occur
756
757                         // stop running server frames if the wall time reaches this value
758                         if (sys_ticrate.value <= 0)
759                                 advancetime = sv_timer;
760                         else if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
761                         {
762                                 // synchronize to the client frametime, but no less than 10ms and no more than sys_ticrate
763                                 advancetime = bound(0.01, cl_timer, sys_ticrate.value);
764                                 framelimit = 10;
765                                 aborttime = realtime + 0.1;
766                         }
767                         else
768                         {
769                                 advancetime = sys_ticrate.value;
770                                 // listen servers can run multiple server frames per client frame
771                                 if (cls.state == ca_connected)
772                                 {
773                                         framelimit = 10;
774                                         aborttime = realtime + 0.1;
775                                 }
776                         }
777                         advancetime = min(advancetime, 0.1);
778
779                         if(advancetime > 0)
780                         {
781                                 offset = sv_timer + (Sys_DoubleTime() - realtime);
782                                 ++svs.perf_acc_offset_samples;
783                                 svs.perf_acc_offset += offset;
784                                 svs.perf_acc_offset_squared += offset * offset;
785                                 if(svs.perf_acc_offset_max < offset)
786                                         svs.perf_acc_offset_max = offset;
787                         }
788
789                         // only advance time if not paused
790                         // the game also pauses in singleplayer when menu or console is used
791                         sv.frametime = advancetime * slowmo.value;
792                         if (host_framerate.value)
793                                 sv.frametime = host_framerate.value;
794                         if (sv.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive)))
795                                 sv.frametime = 0;
796
797                         // setup the VM frame
798                         SV_VM_Begin();
799
800                         for (framecount = 0;framecount < framelimit && sv_timer > 0;framecount++)
801                         {
802                                 sv_timer -= advancetime;
803
804                                 // move things around and think unless paused
805                                 if (sv.frametime)
806                                         SV_Physics();
807
808                                 // if this server frame took too long, break out of the loop
809                                 if (framelimit > 1 && Sys_DoubleTime() >= aborttime)
810                                         break;
811                         }
812
813                         // send all messages to the clients
814                         SV_SendClientMessages();
815                         
816                         if (sv.paused == 1 && realtime > sv.pausedstart && sv.pausedstart > 0) {
817                                 prog->globals.generic[OFS_PARM0] = realtime - sv.pausedstart;
818                                 PRVM_ExecuteProgram(prog->funcoffsets.SV_PausedTic, "QC function SV_PausedTic is missing");
819                         }
820
821                         // end the server VM frame
822                         SV_VM_End();
823
824                         // send an heartbeat if enough time has passed since the last one
825                         NetConn_Heartbeat(0);
826                 }
827
828         //-------------------
829         //
830         // client operations
831         //
832         //-------------------
833
834                 if (cls.state != ca_dedicated && (cl_timer > 0 || cls.timedemo))
835                 {
836                         // decide the simulation time
837                         if (cls.capturevideo.active)
838                         {
839                                 if (cls.capturevideo.realtime)
840                                         clframetime = cl.realframetime = max(cl_timer, 1.0 / cls.capturevideo.framerate);
841                                 else
842                                 {
843                                         clframetime = 1.0 / cls.capturevideo.framerate;
844                                         cl.realframetime = max(cl_timer, clframetime);
845                                 }
846                         }
847                         else if (vid_activewindow && cl_maxfps.value >= 1)
848                                 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxfps.value);
849                         else if (!vid_activewindow && cl_maxidlefps.value >= 1)
850                                 clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxidlefps.value);
851                         else
852                                 clframetime = cl.realframetime = cl_timer;
853
854                         // apply slowmo scaling
855                         clframetime *= cl.movevars_timescale;
856                         // scale playback speed of demos by slowmo cvar
857                         if (cls.demoplayback)
858                         {
859                                 clframetime *= slowmo.value;
860                                 // if demo playback is paused, don't advance time at all
861                                 if (cls.demopaused)
862                                         clframetime = 0;
863                         }
864
865                         // host_framerate overrides all else
866                         if (host_framerate.value)
867                                 clframetime = host_framerate.value;
868
869                         if (cls.timedemo)
870                                 clframetime = cl.realframetime = cl_timer;
871
872                         // deduct the frame time from the accumulator
873                         cl_timer -= cl.realframetime;
874
875                         cl.oldtime = cl.time;
876                         cl.time += clframetime;
877
878                         // Collect input into cmd
879                         CL_Input();
880
881                         // check for new packets
882                         NetConn_ClientFrame();
883
884                         // read a new frame from a demo if needed
885                         CL_ReadDemoMessage();
886
887                         // now that packets have been read, send input to server
888                         CL_SendMove();
889
890                         // update client world (interpolate entities, create trails, etc)
891                         CL_UpdateWorld();
892
893                         // update video
894                         if (host_speeds.integer)
895                                 time1 = Sys_DoubleTime();
896
897                         CL_Video_Frame();
898                         CL_Gecko_Frame();
899
900                         CL_UpdateScreen();
901
902                         if (host_speeds.integer)
903                                 time2 = Sys_DoubleTime();
904
905                         // update audio
906                         if(cl.csqc_usecsqclistener)
907                         {
908                                 S_Update(&cl.csqc_listenermatrix);
909                                 cl.csqc_usecsqclistener = false;
910                         }
911                         else
912                                 S_Update(&r_refdef.view.matrix);
913
914                         CDAudio_Update();
915
916                         if (host_speeds.integer)
917                         {
918                                 pass1 = (int)((time1 - time3)*1000000);
919                                 time3 = Sys_DoubleTime();
920                                 pass2 = (int)((time2 - time1)*1000000);
921                                 pass3 = (int)((time3 - time2)*1000000);
922                                 Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
923                                                         pass1+pass2+pass3, pass1, pass2, pass3);
924                         }
925                         wait = bound(0, host_sleep.value * 1000, 100000);
926                         if (!cls.timedemo && wait >= 1)
927                                 Sys_Sleep((int)wait);
928                 }
929
930                 // if there is some time remaining from this frame, reset the timers
931                 if (cl_timer >= 0)
932                         cl_timer = 0;
933                 if (sv_timer >= 0)
934                 {
935                         svs.perf_acc_lost += sv_timer;
936                         sv_timer = 0;
937                 }
938
939                 host_framecount++;
940         }
941 }
942
943 //============================================================================
944
945 qboolean vid_opened = false;
946 void Host_StartVideo(void)
947 {
948         if (!vid_opened && cls.state != ca_dedicated)
949         {
950                 vid_opened = true;
951                 // make sure we open sockets before opening video because the Windows Firewall "unblock?" dialog can screw up the graphics context on some graphics drivers
952                 NetConn_UpdateSockets();
953                 VID_Start();
954                 CDAudio_Startup();
955         }
956 }
957
958 char engineversion[128];
959
960 qboolean sys_nostdout = false;
961
962 extern void Render_Init(void);
963 extern void Mathlib_Init(void);
964 extern void FS_Init(void);
965 extern void FS_Shutdown(void);
966 extern void PR_Cmd_Init(void);
967 extern void COM_Init_Commands(void);
968 extern void FS_Init_Commands(void);
969 extern qboolean host_stuffcmdsrun;
970
971 /*
972 ====================
973 Host_Init
974 ====================
975 */
976 static void Host_Init (void)
977 {
978         int i;
979         const char* os;
980
981         if (COM_CheckParm("-profilegameonly"))
982                 Sys_AllowProfiling(false);
983
984         // LordHavoc: quake never seeded the random number generator before... heh
985         if (COM_CheckParm("-benchmark"))
986                 srand(0); // predictable random sequence for -benchmark
987         else
988                 srand(time(NULL));
989
990         // FIXME: this is evil, but possibly temporary
991 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
992         if (COM_CheckParm("-developer"))
993         {
994                 developer.value = developer.integer = 1;
995                 developer.string = "1";
996         }
997
998         if (COM_CheckParm("-developer2"))
999         {
1000                 developer.value = developer.integer = 100;
1001                 developer.string = "100";
1002                 developer_memory.value = developer_memory.integer = 100;
1003                 developer.string = "100";
1004                 developer_memorydebug.value = developer_memorydebug.integer = 100;
1005                 developer_memorydebug.string = "100";
1006         }
1007
1008 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
1009         if (COM_CheckParm("-nostdout"))
1010                 sys_nostdout = 1;
1011
1012         // used by everything
1013         Memory_Init();
1014
1015         // initialize console command/cvar/alias/command execution systems
1016         Cmd_Init();
1017
1018         // initialize memory subsystem cvars/commands
1019         Memory_Init_Commands();
1020
1021         // initialize console and logging and its cvars/commands
1022         Con_Init();
1023
1024         // initialize various cvars that could not be initialized earlier
1025         Curl_Init_Commands();
1026         Cmd_Init_Commands();
1027         Sys_Init_Commands();
1028         COM_Init_Commands();
1029         FS_Init_Commands();
1030
1031         // initialize console window (only used by sys_win.c)
1032         Sys_InitConsole();
1033
1034         // detect gamemode from commandline options or executable name
1035         COM_InitGameType();
1036
1037         // construct a version string for the corner of the console
1038         os = DP_OS_NAME;
1039         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
1040         Con_Printf("%s\n", engineversion);
1041
1042         // initialize ixtable
1043         Mathlib_Init();
1044
1045         // initialize filesystem (including fs_basedir, fs_gamedir, -game, scr_screenshot_name)
1046         FS_Init();
1047
1048         NetConn_Init();
1049         Curl_Init();
1050         //PR_Init();
1051         //PR_Cmd_Init();
1052         PRVM_Init();
1053         Mod_Init();
1054         World_Init();
1055         SV_Init();
1056         Host_InitCommands();
1057         Host_InitLocal();
1058         Host_ServerOptions();
1059
1060         if (cls.state == ca_dedicated)
1061                 Cmd_AddCommand ("disconnect", CL_Disconnect_f, "disconnect from server (or disconnect all clients if running a server)");
1062         else
1063         {
1064                 Con_DPrintf("Initializing client\n");
1065
1066                 R_Modules_Init();
1067                 Palette_Init();
1068                 MR_Init_Commands();
1069                 VID_Shared_Init();
1070                 VID_Init();
1071                 Render_Init();
1072                 S_Init();
1073                 CDAudio_Init();
1074                 Key_Init();
1075                 V_Init();
1076                 CL_Init();
1077         }
1078
1079         // set up the default startmap_sp and startmap_dm aliases (mods can
1080         // override these) and then execute the quake.rc startup script
1081         if (gamemode == GAME_NEHAHRA)
1082                 Cbuf_AddText("alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec quake.rc\n");
1083         else if (gamemode == GAME_TRANSFUSION)
1084                 Cbuf_AddText("alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec quake.rc\n");
1085         else if (gamemode == GAME_TEU)
1086                 Cbuf_AddText("alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
1087         else
1088                 Cbuf_AddText("alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec quake.rc\n");
1089         Cbuf_Execute();
1090
1091         // if stuffcmds wasn't run, then quake.rc is probably missing, use default
1092         if (!host_stuffcmdsrun)
1093         {
1094                 Cbuf_AddText("exec default.cfg\nexec config.cfg\nexec autoexec.cfg\nstuffcmds\n");
1095                 Cbuf_Execute();
1096         }
1097
1098         // put up the loading image so the user doesn't stare at a black screen...
1099         SCR_BeginLoadingPlaque();
1100
1101         // FIXME: put this into some neat design, but the menu should be allowed to crash
1102         // without crashing the whole game, so this should just be a short-time solution
1103
1104         // here comes the not so critical stuff
1105         if (setjmp(host_abortframe)) {
1106                 return;
1107         }
1108
1109         if (cls.state != ca_dedicated)
1110         {
1111                 MR_Init();
1112         }
1113
1114         // check for special benchmark mode
1115 // 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)
1116         i = COM_CheckParm("-benchmark");
1117         if (i && i + 1 < com_argc)
1118         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1119         {
1120                 Cbuf_AddText(va("timedemo %s\n", com_argv[i + 1]));
1121                 Cbuf_Execute();
1122         }
1123
1124         // check for special demo mode
1125 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
1126         i = COM_CheckParm("-demo");
1127         if (i && i + 1 < com_argc)
1128         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1129         {
1130                 Cbuf_AddText(va("playdemo %s\n", com_argv[i + 1]));
1131                 Cbuf_Execute();
1132         }
1133
1134 // COMMANDLINEOPTION: Client: -capturedemo <demoname> captures a playdemo and quits
1135         i = COM_CheckParm("-capturedemo");
1136         if (i && i + 1 < com_argc)
1137         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1138         {
1139                 Cbuf_AddText(va("playdemo %s\ncl_capturevideo 1\n", com_argv[i + 1]));
1140                 Cbuf_Execute();
1141         }
1142
1143         if (cls.state == ca_dedicated || COM_CheckParm("-listen"))
1144         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1145         {
1146                 Cbuf_AddText("startmap_dm\n");
1147                 Cbuf_Execute();
1148         }
1149
1150         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1151         {
1152                 Cbuf_AddText("togglemenu\n");
1153                 Cbuf_Execute();
1154         }
1155
1156         Con_DPrint("========Initialized=========\n");
1157
1158         //Host_StartVideo();
1159 }
1160
1161
1162 /*
1163 ===============
1164 Host_Shutdown
1165
1166 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
1167 to run quit through here before the final handoff to the sys code.
1168 ===============
1169 */
1170 void Host_Shutdown(void)
1171 {
1172         static qboolean isdown = false;
1173
1174         if (isdown)
1175         {
1176                 Con_Print("recursive shutdown\n");
1177                 return;
1178         }
1179         if (setjmp(host_abortframe))
1180         {
1181                 Con_Print("aborted the quitting frame?!?\n");
1182                 return;
1183         }
1184         isdown = true;
1185
1186         // be quiet while shutting down
1187         S_StopAllSounds();
1188
1189         // disconnect client from server if active
1190         CL_Disconnect();
1191
1192         // shut down local server if active
1193         Host_ShutdownServer ();
1194
1195         // Shutdown menu
1196         if(MR_Shutdown)
1197                 MR_Shutdown();
1198
1199         // AK shutdown PRVM
1200         // AK hmm, no PRVM_Shutdown(); yet
1201
1202         CL_Gecko_Shutdown();
1203         CL_Video_Shutdown();
1204
1205         Host_SaveConfig();
1206
1207         CDAudio_Shutdown ();
1208         S_Terminate ();
1209         Curl_Shutdown ();
1210         NetConn_Shutdown ();
1211         //PR_Shutdown ();
1212
1213         if (cls.state != ca_dedicated)
1214         {
1215                 R_Modules_Shutdown();
1216                 VID_Shutdown();
1217         }
1218
1219         Cmd_Shutdown();
1220         CL_Shutdown();
1221         Sys_Shutdown();
1222         Log_Close();
1223         FS_Shutdown();
1224         Memory_Shutdown();
1225 }
1226