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