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