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