]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
Removed all calls to strcpy; most of them are now calls to strlcpy or memcpy.
[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 <time.h>
23 #include "quakedef.h"
24 #include "libcurl.h"
25 #include "cdaudio.h"
26 #include "cl_video.h"
27 #include "progsvm.h"
28 #include "csprogs.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 // how many frames have occurred
42 // (checked by Host_Error and Host_SaveConfig_f)
43 int host_framecount = 0;
44 // LordHavoc: set when quit is executed
45 qboolean host_shuttingdown = false;
46
47 // the real time since application started, without any slowmo or clamping
48 double realtime;
49
50 // current client
51 client_t *host_client;
52
53 jmp_buf host_abortframe;
54
55 // pretend frames take this amount of time (in seconds), 0 = realtime
56 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 host_maxfps if you want to limit your framerate instead, or sys_ticrate to limit server speed"};
57 // shows time used by certain subsystems
58 cvar_t host_speeds = {0, "host_speeds","0", "reports how much time is used in server/graphics/sound"};
59 // LordHavoc: framerate independent slowmo
60 cvar_t slowmo = {0, "slowmo", "1.0", "controls game speed, 0.5 is half speed, 2 is double speed"};
61 // LordHavoc: framerate upper cap
62 cvar_t cl_maxfps = {CVAR_SAVE, "cl_maxfps", "1000", "maximum fps cap, if game is running faster than this it will wait before running another frame (useful to make cpu time available to other programs)"};
63
64 // print broadcast messages in dedicated mode
65 cvar_t sv_echobprint = {CVAR_SAVE, "sv_echobprint", "1", "prints gamecode bprint() calls to server console"};
66
67 cvar_t sys_ticrate = {CVAR_SAVE, "sys_ticrate","0.05", "how long a server frame is in seconds, 0.05 is 20fps server rate, 0.1 is 10fps (can not be set higher than 0.1), 0 runs as many server frames as possible (makes games against bots a little smoother, overwhelms network players)"};
68 cvar_t sv_fixedframeratesingleplayer = {0, "sv_fixedframeratesingleplayer", "0", "allows you to use server-style timing system in singleplayer (don't run faster than sys_ticrate)"};
69
70 cvar_t fraglimit = {CVAR_NOTIFY, "fraglimit","0", "ends level if this many frags is reached by any player"};
71 cvar_t timelimit = {CVAR_NOTIFY, "timelimit","0", "ends level at this time (in minutes)"};
72 cvar_t teamplay = {CVAR_NOTIFY, "teamplay","0", "teamplay mode, values depend on mod but typically 0 = no teams, 1 = no team damage no self damage, 2 = team damage and self damage, some mods support 3 = no team damage but can damage self"};
73
74 cvar_t samelevel = {CVAR_NOTIFY, "samelevel","0", "repeats same level if level ends (due to timelimit or someone hitting an exit)"};
75 cvar_t noexit = {CVAR_NOTIFY, "noexit","0", "kills anyone attempting to use an exit"};
76
77 cvar_t developer = {0, "developer","0", "prints additional debugging messages and information (recommended for modders and level designers)"};
78 cvar_t developer_entityparsing = {0, "developer_entityparsing", "0", "prints detailed network entities information each time a packet is received"};
79
80 cvar_t skill = {0, "skill","1", "difficulty level of game, affects monster layouts in levels, 0 = easy, 1 = normal, 2 = hard, 3 = nightmare (same layout as hard but monsters fire twice)"};
81 cvar_t deathmatch = {0, "deathmatch","0", "deathmatch mode, values depend on mod but typically 0 = no deathmatch, 1 = normal deathmatch with respawning weapons, 2 = weapons stay (players can only pick up new weapons)"};
82 cvar_t coop = {0, "coop","0", "coop mode, 0 = no coop, 1 = coop mode, multiple players playing through the singleplayer game (coop mode also shuts off deathmatch)"};
83
84 cvar_t pausable = {0, "pausable","1", "allow players to pause or not"};
85
86 cvar_t temp1 = {0, "temp1","0", "general cvar for mods to use, in stock id1 this selects which death animation to use on players (0 = random death, other values select specific death scenes)"};
87
88 cvar_t timestamps = {CVAR_SAVE, "timestamps", "0", "prints timestamps on console messages"};
89 cvar_t timeformat = {CVAR_SAVE, "timeformat", "[%b %e %X] ", "time format to use on timestamped console messages"};
90
91 /*
92 ================
93 Host_AbortCurrentFrame
94
95 aborts the current host frame and goes on with the next one
96 ================
97 */
98 void Host_AbortCurrentFrame(void)
99 {
100         longjmp (host_abortframe, 1);
101 }
102
103 /*
104 ================
105 Host_Error
106
107 This shuts down both the client and server
108 ================
109 */
110 void Host_Error (const char *error, ...)
111 {
112         static char hosterrorstring1[MAX_INPUTLINE];
113         static char hosterrorstring2[MAX_INPUTLINE];
114         static qboolean hosterror = false;
115         va_list argptr;
116
117         // turn off rcon redirect if it was active when the crash occurred
118         rcon_redirect = false;
119
120         va_start (argptr,error);
121         dpvsnprintf (hosterrorstring1,sizeof(hosterrorstring1),error,argptr);
122         va_end (argptr);
123
124         Con_Printf("Host_Error: %s\n", hosterrorstring1);
125
126         // LordHavoc: if crashing very early, or currently shutting down, do
127         // Sys_Error instead
128         if (host_framecount < 3 || host_shuttingdown)
129                 Sys_Error ("Host_Error: %s", hosterrorstring1);
130
131         if (hosterror)
132                 Sys_Error ("Host_Error: recursively entered (original error was: %s    new error is: %s)", hosterrorstring2, hosterrorstring1);
133         hosterror = true;
134
135         strlcpy(hosterrorstring2, hosterrorstring1, sizeof(hosterrorstring2));
136
137         CL_Parse_DumpPacket();
138
139         CL_Parse_ErrorCleanUp();
140
141         //PR_Crash();
142
143         // print out where the crash happened, if it was caused by QC (and do a cleanup)
144         PRVM_Crash();
145
146
147         Host_ShutdownServer ();
148
149         if (cls.state == ca_dedicated)
150                 Sys_Error ("Host_Error: %s",hosterrorstring2);  // dedicated servers exit
151
152         CL_Disconnect ();
153         cls.demonum = -1;
154
155         hosterror = false;
156
157         Host_AbortCurrentFrame();
158 }
159
160 void Host_ServerOptions (void)
161 {
162         int i;
163
164         // general default
165         svs.maxclients = 8;
166
167 // COMMANDLINEOPTION: Server: -dedicated [playerlimit] starts a dedicated server (with a command console), default playerlimit is 8
168 // COMMANDLINEOPTION: Server: -listen [playerlimit] starts a multiplayer server with graphical client, like singleplayer but other players can connect, default playerlimit is 8
169         // if no client is in the executable or -dedicated is specified on
170         // commandline, start a dedicated server
171         i = COM_CheckParm ("-dedicated");
172         if (i || !cl_available)
173         {
174                 cls.state = ca_dedicated;
175                 // check for -dedicated specifying how many players
176                 if (i && i + 1 < com_argc && atoi (com_argv[i+1]) >= 1)
177                         svs.maxclients = atoi (com_argv[i+1]);
178                 if (COM_CheckParm ("-listen"))
179                         Con_Printf ("Only one of -dedicated or -listen can be specified\n");
180                 // default sv_public on for dedicated servers (often hosted by serious administrators), off for listen servers (often hosted by clueless users)
181                 Cvar_SetValue("sv_public", 1);
182         }
183         else if (cl_available)
184         {
185                 // client exists and not dedicated, check if -listen is specified
186                 cls.state = ca_disconnected;
187                 i = COM_CheckParm ("-listen");
188                 if (i)
189                 {
190                         // default players unless specified
191                         if (i + 1 < com_argc && atoi (com_argv[i+1]) >= 1)
192                                 svs.maxclients = atoi (com_argv[i+1]);
193                 }
194                 else
195                 {
196                         // default players in some games, singleplayer in most
197                         if (gamemode != GAME_GOODVSBAD2 && gamemode != GAME_NEXUIZ && gamemode != GAME_BATTLEMECH)
198                                 svs.maxclients = 1;
199                 }
200         }
201
202         svs.maxclients = bound(1, svs.maxclients, MAX_SCOREBOARD);
203
204         svs.clients = (client_t *)Mem_Alloc(sv_mempool, sizeof(client_t) * svs.maxclients);
205
206         if (svs.maxclients > 1 && !deathmatch.integer && !coop.integer)
207                 Cvar_SetValueQuick(&deathmatch, 1);
208 }
209
210 /*
211 =======================
212 Host_InitLocal
213 ======================
214 */
215 void Host_SaveConfig_f(void);
216 static void Host_InitLocal (void)
217 {
218         Cmd_AddCommand("saveconfig", Host_SaveConfig_f, "save settings to config.cfg immediately (also automatic when quitting)");
219
220         Cvar_RegisterVariable (&host_framerate);
221         Cvar_RegisterVariable (&host_speeds);
222         Cvar_RegisterVariable (&slowmo);
223         Cvar_RegisterVariable (&cl_maxfps);
224
225         Cvar_RegisterVariable (&sv_echobprint);
226
227         Cvar_RegisterVariable (&sys_ticrate);
228         Cvar_RegisterVariable (&sv_fixedframeratesingleplayer);
229
230         Cvar_RegisterVariable (&fraglimit);
231         Cvar_RegisterVariable (&timelimit);
232         Cvar_RegisterVariable (&teamplay);
233         Cvar_RegisterVariable (&samelevel);
234         Cvar_RegisterVariable (&noexit);
235         Cvar_RegisterVariable (&skill);
236         Cvar_RegisterVariable (&developer);
237         Cvar_RegisterVariable (&developer_entityparsing);
238         Cvar_RegisterVariable (&deathmatch);
239         Cvar_RegisterVariable (&coop);
240
241         Cvar_RegisterVariable (&pausable);
242
243         Cvar_RegisterVariable (&temp1);
244
245         Cvar_RegisterVariable (&timestamps);
246         Cvar_RegisterVariable (&timeformat);
247 }
248
249
250 /*
251 ===============
252 Host_SaveConfig_f
253
254 Writes key bindings and archived cvars to config.cfg
255 ===============
256 */
257 void Host_SaveConfig_f(void)
258 {
259         qfile_t *f;
260
261 // dedicated servers initialize the host but don't parse and set the
262 // config.cfg cvars
263         // LordHavoc: don't save a config if it crashed in startup
264         if (host_framecount >= 3 && cls.state != ca_dedicated)
265         {
266                 f = FS_Open ("config.cfg", "wb", false, false);
267                 if (!f)
268                 {
269                         Con_Print("Couldn't write config.cfg.\n");
270                         return;
271                 }
272
273                 Key_WriteBindings (f);
274                 Cvar_WriteVariables (f);
275
276                 FS_Close (f);
277         }
278 }
279
280
281 /*
282 =================
283 SV_ClientPrint
284
285 Sends text across to be displayed
286 FIXME: make this just a stuffed echo?
287 =================
288 */
289 void SV_ClientPrint(const char *msg)
290 {
291         if (host_client->netconnection)
292         {
293                 MSG_WriteByte(&host_client->netconnection->message, svc_print);
294                 MSG_WriteString(&host_client->netconnection->message, msg);
295         }
296 }
297
298 /*
299 =================
300 SV_ClientPrintf
301
302 Sends text across to be displayed
303 FIXME: make this just a stuffed echo?
304 =================
305 */
306 void SV_ClientPrintf(const char *fmt, ...)
307 {
308         va_list argptr;
309         char msg[MAX_INPUTLINE];
310
311         va_start(argptr,fmt);
312         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
313         va_end(argptr);
314
315         SV_ClientPrint(msg);
316 }
317
318 /*
319 =================
320 SV_BroadcastPrint
321
322 Sends text to all active clients
323 =================
324 */
325 void SV_BroadcastPrint(const char *msg)
326 {
327         int i;
328         client_t *client;
329
330         for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
331         {
332                 if (client->spawned && client->netconnection)
333                 {
334                         MSG_WriteByte(&client->netconnection->message, svc_print);
335                         MSG_WriteString(&client->netconnection->message, msg);
336                 }
337         }
338
339         if (sv_echobprint.integer && cls.state == ca_dedicated)
340                 Con_Print(msg);
341 }
342
343 /*
344 =================
345 SV_BroadcastPrintf
346
347 Sends text to all active clients
348 =================
349 */
350 void SV_BroadcastPrintf(const char *fmt, ...)
351 {
352         va_list argptr;
353         char msg[MAX_INPUTLINE];
354
355         va_start(argptr,fmt);
356         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
357         va_end(argptr);
358
359         SV_BroadcastPrint(msg);
360 }
361
362 /*
363 =================
364 Host_ClientCommands
365
366 Send text over to the client to be executed
367 =================
368 */
369 void Host_ClientCommands(const char *fmt, ...)
370 {
371         va_list argptr;
372         char string[MAX_INPUTLINE];
373
374         if (!host_client->netconnection)
375                 return;
376
377         va_start(argptr,fmt);
378         dpvsnprintf(string, sizeof(string), fmt, argptr);
379         va_end(argptr);
380
381         MSG_WriteByte(&host_client->netconnection->message, svc_stufftext);
382         MSG_WriteString(&host_client->netconnection->message, string);
383 }
384
385 /*
386 =====================
387 SV_DropClient
388
389 Called when the player is getting totally kicked off the host
390 if (crash = true), don't bother sending signofs
391 =====================
392 */
393 void SV_DropClient(qboolean crash)
394 {
395         int i;
396         Con_Printf("Client \"%s\" dropped\n", host_client->name);
397
398         // make sure edict is not corrupt (from a level change for example)
399         host_client->edict = PRVM_EDICT_NUM(host_client - svs.clients + 1);
400
401         if (host_client->netconnection)
402         {
403                 // free the client (the body stays around)
404                 if (!crash)
405                 {
406                         // LordHavoc: no opportunity for resending, so use unreliable 3 times
407                         unsigned char bufdata[8];
408                         sizebuf_t buf;
409                         memset(&buf, 0, sizeof(buf));
410                         buf.data = bufdata;
411                         buf.maxsize = sizeof(bufdata);
412                         MSG_WriteByte(&buf, svc_disconnect);
413                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol);
414                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol);
415                         NetConn_SendUnreliableMessage(host_client->netconnection, &buf, sv.protocol);
416                 }
417                 // break the net connection
418                 NetConn_Close(host_client->netconnection);
419                 host_client->netconnection = NULL;
420         }
421
422         // call qc ClientDisconnect function
423         // LordHavoc: don't call QC if server is dead (avoids recursive
424         // Host_Error in some mods when they run out of edicts)
425         if (host_client->clientconnectcalled && sv.active && host_client->edict)
426         {
427                 // call the prog function for removing a client
428                 // this will set the body to a dead frame, among other things
429                 int saveSelf = prog->globals.server->self;
430                 host_client->clientconnectcalled = false;
431                 prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
432                 PRVM_ExecuteProgram(prog->globals.server->ClientDisconnect, "QC function ClientDisconnect is missing");
433                 prog->globals.server->self = saveSelf;
434         }
435
436         // remove leaving player from scoreboard
437         //host_client->edict->fields.server->netname = PRVM_SetEngineString(host_client->name);
438         //if ((val = PRVM_GETEDICTFIELDVALUE(host_client->edict, eval_clientcolors)))
439         //      val->_float = 0;
440         //host_client->edict->fields.server->frags = 0;
441         host_client->name[0] = 0;
442         host_client->colors = 0;
443         host_client->frags = 0;
444         // send notification to all clients
445         // get number of client manually just to make sure we get it right...
446         i = host_client - svs.clients;
447         MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
448         MSG_WriteByte (&sv.reliable_datagram, i);
449         MSG_WriteString (&sv.reliable_datagram, host_client->name);
450         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
451         MSG_WriteByte (&sv.reliable_datagram, i);
452         MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
453         MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
454         MSG_WriteByte (&sv.reliable_datagram, i);
455         MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
456
457         // free the client now
458         if (host_client->entitydatabase)
459                 EntityFrame_FreeDatabase(host_client->entitydatabase);
460         if (host_client->entitydatabase4)
461                 EntityFrame4_FreeDatabase(host_client->entitydatabase4);
462         if (host_client->entitydatabase5)
463                 EntityFrame5_FreeDatabase(host_client->entitydatabase5);
464
465         if (sv.active)
466         {
467                 // clear a fields that matter to DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS, and also frags
468                 PRVM_ED_ClearEdict(host_client->edict);
469         }
470
471         // clear the client struct (this sets active to false)
472         memset(host_client, 0, sizeof(*host_client));
473
474         // update server listing on the master because player count changed
475         // (which the master uses for filtering empty/full servers)
476         NetConn_Heartbeat(1);
477 }
478
479 /*
480 ==================
481 Host_ShutdownServer
482
483 This only happens at the end of a game, not between levels
484 ==================
485 */
486 void Host_ShutdownServer(void)
487 {
488         int i;
489
490         Con_DPrintf("Host_ShutdownServer\n");
491
492         if (!sv.active)
493                 return;
494
495         NetConn_Heartbeat(2);
496         NetConn_Heartbeat(2);
497
498 // make sure all the clients know we're disconnecting
499         SV_VM_Begin();
500         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
501                 if (host_client->active)
502                         SV_DropClient(false); // server shutdown
503         SV_VM_End();
504
505         NetConn_CloseServerPorts();
506
507         sv.active = false;
508 //
509 // clear structures
510 //
511         memset(&sv, 0, sizeof(sv));
512         memset(svs.clients, 0, svs.maxclients*sizeof(client_t));
513 }
514
515
516 //============================================================================
517
518 /*
519 ===================
520 Host_GetConsoleCommands
521
522 Add them exactly as if they had been typed at the console
523 ===================
524 */
525 void Host_GetConsoleCommands (void)
526 {
527         char *cmd;
528
529         while (1)
530         {
531                 cmd = Sys_ConsoleInput ();
532                 if (!cmd)
533                         break;
534                 Cbuf_AddText (cmd);
535         }
536 }
537
538 /*
539 ==================
540 Host_Frame
541
542 Runs all active servers
543 ==================
544 */
545 static void Host_Init(void);
546 void Host_Main(void)
547 {
548         static double time1 = 0;
549         static double time2 = 0;
550         static double time3 = 0;
551         // these are static because of setjmp/longjmp warnings in mingw32 gcc 2.95.3
552         static double frameoldtime, framenewtime, frametime, cl_timer, sv_timer;
553
554         Host_Init();
555
556         cl_timer = 0;
557         sv_timer = 0;
558
559         framenewtime = Sys_DoubleTime();
560         for (;;)
561         {
562                 if (setjmp(host_abortframe))
563                         continue;                       // something bad happened, or the server disconnected
564
565                 frameoldtime = framenewtime;
566                 framenewtime = Sys_DoubleTime();
567                 frametime = framenewtime - frameoldtime;
568                 realtime += frametime;
569
570                 // if there is some time remaining from last frame, rest the timers
571                 if (cl_timer >= 0)
572                         cl_timer = 0;
573                 if (sv_timer >= 0)
574                         sv_timer = 0;
575
576                 // accumulate the new frametime into the timers
577                 cl_timer += frametime;
578                 sv_timer += frametime;
579
580                 if (slowmo.value < 0)
581                         Cvar_SetValue("slowmo", 0);
582                 if (host_framerate.value < 0.00001 && host_framerate.value != 0)
583                         Cvar_SetValue("host_framerate", 0);
584                 if (cl_maxfps.value < 1)
585                         Cvar_SetValue("cl_maxfps", 1);
586
587                 // if the accumulators haven't become positive yet, keep waiting
588                 if (!cls.timedemo && cl_timer <= 0 && sv_timer <= 0)
589                 {
590                         double wait;
591                         int msleft;
592                         if (cls.state == ca_dedicated)
593                                 wait = sv_timer;
594                         else if (!sv.active)
595                                 wait = cl_timer;
596                         else
597                                 wait = max(cl_timer, sv_timer);
598                         msleft = (int)floor(wait * -1000.0);
599                         if (msleft >= 1)
600                                 Sys_Sleep(msleft);
601                         continue;
602                 }
603
604                 // keep the random time dependent
605                 rand();
606
607                 cl.islocalgame = NetConn_IsLocalGame();
608
609                 // get new key events
610                 Sys_SendKeyEvents();
611
612                 // when a server is running we only execute console commands on server frames
613                 // (this mainly allows frikbot .way config files to work properly by staying in sync with the server qc)
614                 // otherwise we execute them on all frames
615                 if (sv_timer > 0 || !sv.active)
616                 {
617                         // process console commands
618                         Cbuf_Execute();
619                 }
620
621                 NetConn_UpdateSockets();
622
623                 Curl_Run();
624
625         //-------------------
626         //
627         // server operations
628         //
629         //-------------------
630
631                 // check for commands typed to the host
632                 Host_GetConsoleCommands();
633
634                 if (sv_timer > 0)
635                 {
636                         if (!sv.active)
637                         {
638                                 // if there is no server, run server timing at 10fps
639                                 sv_timer -= 0.1;
640                         }
641                         else
642                         {
643                                 // execute one or more server frames, with an upper limit on how much
644                                 // execution time to spend on server frames to avoid freezing the game if
645                                 // the server is overloaded, this execution time limit means the game will
646                                 // slow down if the server is taking too long.
647                                 int framecount, framelimit = 1;
648                                 double advancetime, aborttime = 0;
649
650                                 // receive server packets now, which might contain rcon commands, which
651                                 // may change level or other such things we don't want to have happen in
652                                 // the middle of Host_Frame
653                                 NetConn_ServerFrame();
654
655                                 // run the world state
656                                 // don't allow simulation to run too fast or too slow or logic glitches can occur
657
658                                 // stop running server frames if the wall time reaches this value
659                                 if (sys_ticrate.value <= 0)
660                                         advancetime = sv_timer;
661                                 else if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
662                                 {
663                                         // synchronize to the client frametime, but no less than 10ms and no more than sys_ticrate
664                                         advancetime = bound(0.01, cl_timer, sys_ticrate.value);
665                                         framelimit = 10;
666                                         aborttime = Sys_DoubleTime() + 0.1;
667                                 }
668                                 else
669                                 {
670                                         advancetime = sys_ticrate.value;
671                                         // listen servers can run multiple server frames per client frame
672                                         if (cls.state == ca_connected)
673                                         {
674                                                 framelimit = 10;
675                                                 aborttime = Sys_DoubleTime() + 0.1;
676                                         }
677                                 }
678                                 advancetime = min(advancetime, 0.1);
679
680                                 // only advance time if not paused
681                                 // the game also pauses in singleplayer when menu or console is used
682                                 sv.frametime = advancetime * slowmo.value;
683                                 if (host_framerate.value)
684                                         sv.frametime = host_framerate.value;
685                                 if (sv.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive)))
686                                         sv.frametime = 0;
687
688                                 // setup the VM frame
689                                 SV_VM_Begin();
690
691                                 for (framecount = 0;framecount < framelimit && sv_timer > 0;framecount++)
692                                 {
693                                         sv_timer -= advancetime;
694
695                                         // move things around and think unless paused
696                                         if (sv.frametime)
697                                                 SV_Physics();
698
699                                         // send all messages to the clients
700                                         SV_SendClientMessages();
701
702                                         // clear the general datagram
703                                         SV_ClearDatagram();
704
705                                         // if this server frame took too long, break out of the loop
706                                         if (framelimit > 1 && Sys_DoubleTime() >= aborttime)
707                                                 break;
708                                 }
709
710                                 // end the server VM frame
711                                 SV_VM_End();
712
713                                 // send an heartbeat if enough time has passed since the last one
714                                 NetConn_Heartbeat(0);
715                         }
716                 }
717
718         //-------------------
719         //
720         // client operations
721         //
722         //-------------------
723
724                 if (cl_timer > 0 || cls.timedemo)
725                 {
726                         if (cls.state == ca_dedicated)
727                         {
728                                 // if there is no client, run client timing at 10fps
729                                 cl_timer -= 0.1;
730                                 if (host_speeds.integer)
731                                         time1 = time2 = Sys_DoubleTime();
732                         }
733                         else
734                         {
735                                 double frametime;
736                                 frametime = cl.realframetime = min(cl_timer, 1);
737
738                                 // decide the simulation time
739                                 if (!cls.timedemo)
740                                 {
741                                         if (cls.capturevideo_active)// && !cls.capturevideo_soundfile)
742                                         {
743                                                 frametime = 1.0 / cls.capturevideo_framerate;
744                                                 cl.realframetime = max(cl.realframetime, frametime);
745                                         }
746                                         else if (vid_activewindow)
747                                                 frametime = cl.realframetime = max(cl.realframetime, 1.0 / cl_maxfps.value);
748                                         else
749                                                 frametime = cl.realframetime = 0.1;
750
751                                         // deduct the frame time from the accumulator
752                                         cl_timer -= cl.realframetime;
753
754                                         // apply slowmo scaling
755                                         frametime *= slowmo.value;
756
757                                         // host_framerate overrides all else
758                                         if (host_framerate.value)
759                                                 frametime = host_framerate.value;
760                                 }
761
762                                 cl.oldtime = cl.time;
763                                 cl.time += frametime;
764
765                                 // Collect input into cmd
766                                 CL_Move();
767
768                                 NetConn_ClientFrame();
769
770                                 if (cls.state == ca_connected)
771                                 {
772                                         CL_ReadFromServer();
773                                         // if running the server remotely, send intentions now after
774                                         // the incoming messages have been read
775                                         //if (!cl.islocalgame)
776                                         //      CL_SendCmd();
777                                 }
778
779                                 // update video
780                                 if (host_speeds.integer)
781                                         time1 = Sys_DoubleTime();
782
783                                 //ui_update();
784
785                                 CL_VideoFrame();
786
787                                 CL_UpdateScreen();
788
789                                 if (host_speeds.integer)
790                                         time2 = Sys_DoubleTime();
791
792                                 // update audio
793                                 if(csqc_usecsqclistener)
794                                 {
795                                         S_Update(&csqc_listenermatrix);
796                                         csqc_usecsqclistener = false;
797                                 }
798                                 else
799                                         S_Update(&r_view.matrix);
800
801                                 CDAudio_Update();
802                         }
803
804                         if (host_speeds.integer)
805                         {
806                                 int pass1, pass2, pass3;
807                                 pass1 = (int)((time1 - time3)*1000000);
808                                 time3 = Sys_DoubleTime();
809                                 pass2 = (int)((time2 - time1)*1000000);
810                                 pass3 = (int)((time3 - time2)*1000000);
811                                 Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
812                                                         pass1+pass2+pass3, pass1, pass2, pass3);
813                         }
814                 }
815
816                 host_framecount++;
817         }
818 }
819
820 //============================================================================
821
822 qboolean vid_opened = false;
823 void Host_StartVideo(void)
824 {
825         if (!vid_opened && cls.state != ca_dedicated)
826         {
827                 vid_opened = true;
828                 VID_Start();
829                 CDAudio_Startup();
830         }
831 }
832
833 char engineversion[128];
834
835 qboolean sys_nostdout = false;
836
837 extern void Render_Init(void);
838 extern void Mathlib_Init(void);
839 extern void FS_Init(void);
840 extern void FS_Shutdown(void);
841 extern void PR_Cmd_Init(void);
842 extern void COM_Init_Commands(void);
843 extern void FS_Init_Commands(void);
844 extern void COM_CheckRegistered(void);
845 extern qboolean host_stuffcmdsrun;
846
847 /*
848 ====================
849 Host_Init
850 ====================
851 */
852 static void Host_Init (void)
853 {
854         int i;
855         const char* os;
856
857         // FIXME: this is evil, but possibly temporary
858 // COMMANDLINEOPTION: Console: -developer enables warnings and other notices (RECOMMENDED for mod developers)
859         if (COM_CheckParm("-developer"))
860         {
861                 developer.value = developer.integer = 100;
862                 developer.string = "100";
863         }
864
865         if (COM_CheckParm("-developer2"))
866         {
867                 developer.value = developer.integer = 100;
868                 developer.string = "100";
869                 developer_memory.value = developer_memory.integer = 100;
870                 developer.string = "100";
871                 developer_memorydebug.value = developer_memorydebug.integer = 100;
872                 developer_memorydebug.string = "100";
873         }
874
875         // LordHavoc: quake never seeded the random number generator before... heh
876         srand(time(NULL));
877
878         // used by everything
879         Memory_Init();
880
881         // initialize console and logging
882         Con_Init();
883
884         // initialize console command/cvar/alias/command execution systems
885         Cmd_Init();
886
887         // parse commandline
888         COM_InitArgv();
889
890         // initialize console window (only used by sys_win.c)
891         Sys_InitConsole();
892
893         // detect gamemode from commandline options or executable name
894         COM_InitGameType();
895
896         // construct a version string for the corner of the console
897 #if defined(__linux__)
898         os = "Linux";
899 #elif defined(WIN32)
900         os = "Windows";
901 #elif defined(__FreeBSD__)
902         os = "FreeBSD";
903 #elif defined(__NetBSD__)
904         os = "NetBSD";
905 #elif defined(__OpenBSD__)
906         os = "OpenBSD";
907 #elif defined(MACOSX)
908         os = "Mac OS X";
909 #elif defined(__MORPHOS__)
910         os = "MorphOS";
911 #else
912         os = "Unknown";
913 #endif
914         dpsnprintf (engineversion, sizeof (engineversion), "%s %s %s", gamename, os, buildstring);
915
916 // COMMANDLINEOPTION: Console: -nostdout disables text output to the terminal the game was launched from
917         if (COM_CheckParm("-nostdout"))
918                 sys_nostdout = 1;
919         else
920                 Con_Printf("%s\n", engineversion);
921
922         // initialize filesystem (including fs_basedir, fs_gamedir, -path, -game, scr_screenshot_name)
923         FS_Init();
924
925         // initialize various cvars that could not be initialized earlier
926         Memory_Init_Commands();
927         Con_Init_Commands();
928         Curl_Init_Commands();
929         Cmd_Init_Commands();
930         Sys_Init_Commands();
931         COM_Init_Commands();
932         FS_Init_Commands();
933         COM_CheckRegistered();
934
935         // initialize ixtable
936         Mathlib_Init();
937
938         NetConn_Init();
939         Curl_Init();
940         //PR_Init();
941         //PR_Cmd_Init();
942         PRVM_Init();
943         Mod_Init();
944         SV_Init();
945         Host_InitCommands();
946         Host_InitLocal();
947         Host_ServerOptions();
948
949         if (cls.state != ca_dedicated)
950         {
951                 Con_Printf("Initializing client\n");
952
953                 R_Modules_Init();
954                 Palette_Init();
955                 MR_Init_Commands();
956                 VID_Shared_Init();
957                 VID_Init();
958                 Render_Init();
959                 S_Init();
960                 CDAudio_Init();
961                 Key_Init();
962                 V_Init();
963                 CL_Init();
964         }
965
966         // set up the default startmap_sp and startmap_dm aliases (mods can
967         // override these) and then execute the quake.rc startup script
968         if (gamemode == GAME_NEHAHRA)
969                 Cbuf_AddText("alias startmap_sp \"map nehstart\"\nalias startmap_dm \"map nehstart\"\nexec quake.rc\n");
970         else if (gamemode == GAME_TRANSFUSION)
971                 Cbuf_AddText("alias startmap_sp \"map e1m1\"\n""alias startmap_dm \"map bb1\"\nexec quake.rc\n");
972         else if (gamemode == GAME_TEU)
973                 Cbuf_AddText("alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec teu.rc\n");
974         else
975                 Cbuf_AddText("alias startmap_sp \"map start\"\nalias startmap_dm \"map start\"\nexec quake.rc\n");
976         Cbuf_Execute();
977
978         // if stuffcmds wasn't run, then quake.rc is probably missing, use default
979         if (!host_stuffcmdsrun)
980         {
981                 Cbuf_AddText("exec default.cfg\nexec config.cfg\nexec autoexec.cfg\nstuffcmds\n");
982                 Cbuf_Execute();
983         }
984
985         // put up the loading image so the user doesn't stare at a black screen...
986         SCR_BeginLoadingPlaque();
987
988         // FIXME: put this into some neat design, but the menu should be allowed to crash
989         // without crashing the whole game, so this should just be a short-time solution
990
991         // here comes the not so critical stuff
992         if (setjmp(host_abortframe)) {
993                 return;
994         }
995
996         if (cls.state != ca_dedicated)
997         {
998                 MR_Init();
999         }
1000
1001         // check for special benchmark mode
1002 // 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)
1003         i = COM_CheckParm("-benchmark");
1004         if (i && i + 1 < com_argc)
1005         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1006         {
1007                 Cbuf_AddText(va("timedemo %s\n", com_argv[i + 1]));
1008                 Cbuf_Execute();
1009         }
1010
1011         // check for special demo mode
1012 // COMMANDLINEOPTION: Client: -demo <demoname> runs a playdemo and quits
1013         i = COM_CheckParm("-demo");
1014         if (i && i + 1 < com_argc)
1015         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1016         {
1017                 Cbuf_AddText(va("playdemo %s\n", com_argv[i + 1]));
1018                 Cbuf_Execute();
1019         }
1020
1021         // check for special demolooponly mode
1022 // COMMANDLINEOPTION: Client: -demolooponly <demoname> runs a playdemo and quits
1023         i = COM_CheckParm("-demolooponly");
1024         if (i && i + 1 < com_argc)
1025         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1026         {
1027                 Cbuf_AddText(va("playdemo %s\n", com_argv[i + 1]));
1028                 Cbuf_Execute();
1029         }
1030
1031         if (cls.state == ca_dedicated || COM_CheckParm("-listen"))
1032         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1033         {
1034                 Cbuf_AddText("startmap_dm\n");
1035                 Cbuf_Execute();
1036         }
1037
1038         if (!sv.active && !cls.demoplayback && !cls.connect_trying)
1039         {
1040                 if (gamemode == GAME_NEXUIZ)
1041                         Cbuf_AddText("togglemenu\nplayvideo logo\ncd loop 1\n");
1042                 else
1043                         Cbuf_AddText("togglemenu\n");
1044                 Cbuf_Execute();
1045         }
1046
1047         Con_DPrint("========Initialized=========\n");
1048
1049         //Host_StartVideo();
1050 }
1051
1052
1053 /*
1054 ===============
1055 Host_Shutdown
1056
1057 FIXME: this is a callback from Sys_Quit and Sys_Error.  It would be better
1058 to run quit through here before the final handoff to the sys code.
1059 ===============
1060 */
1061 void Host_Shutdown(void)
1062 {
1063         static qboolean isdown = false;
1064
1065         if (isdown)
1066         {
1067                 Con_Print("recursive shutdown\n");
1068                 return;
1069         }
1070         isdown = true;
1071
1072         // be quiet while shutting down
1073         S_StopAllSounds();
1074
1075         // disconnect client from server if active
1076         CL_Disconnect();
1077
1078         // shut down local server if active
1079         Host_ShutdownServer ();
1080
1081         // Shutdown menu
1082         if(MR_Shutdown)
1083                 MR_Shutdown();
1084
1085         // AK shutdown PRVM
1086         // AK hmm, no PRVM_Shutdown(); yet
1087
1088         CL_Video_Shutdown();
1089
1090         Host_SaveConfig_f();
1091
1092         CDAudio_Shutdown ();
1093         S_Terminate ();
1094         Curl_Shutdown ();
1095         NetConn_Shutdown ();
1096         //PR_Shutdown ();
1097
1098         if (cls.state != ca_dedicated)
1099         {
1100                 R_Modules_Shutdown();
1101                 VID_Shutdown();
1102         }
1103
1104         Cmd_Shutdown();
1105         CL_Shutdown();
1106         Sys_Shutdown();
1107         Log_Close();
1108         FS_Shutdown();
1109         Memory_Shutdown();
1110 }
1111