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