2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // host.c -- coordinates spawning and killing of local servers
26 A server can allways be started, even if the system started out as a client
29 A client can NOT be started if the system started as a dedicated server.
31 Memory is cleared / released when a server or client begins, not when they end.
35 quakeparms_t host_parms;
37 qboolean host_initialized; // true if into command execution
39 double host_frametime;
41 double realtime; // without any filtering or bounding
42 double oldrealtime; // last frame run
51 client_t *host_client; // current client
53 jmp_buf host_abortserver;
56 //byte *host_colormap;
58 cvar_t host_framerate = {"host_framerate","0"}; // set for slow motion
59 cvar_t host_speeds = {"host_speeds","0"}; // set for running times
60 cvar_t slowmo = {"slowmo", "1.0"}; // LordHavoc: framerate independent slowmo
62 cvar_t sys_ticrate = {"sys_ticrate","0.05"};
63 cvar_t serverprofile = {"serverprofile","0"};
65 cvar_t fraglimit = {"fraglimit","0",false,true};
66 cvar_t timelimit = {"timelimit","0",false,true};
67 cvar_t teamplay = {"teamplay","0",false,true};
69 cvar_t samelevel = {"samelevel","0"};
70 cvar_t noexit = {"noexit","0",false,true};
72 cvar_t developer = {"developer","0"};
74 cvar_t skill = {"skill","1"}; // 0 - 3
75 cvar_t deathmatch = {"deathmatch","0"}; // 0, 1, or 2
76 cvar_t coop = {"coop","0"}; // 0 or 1
78 cvar_t pausable = {"pausable","1"};
80 cvar_t temp1 = {"temp1","0"};
82 cvar_t timestamps = {"timestamps", "0", true};
83 cvar_t timeformat = {"timeformat", "[%b %e %X] ", true};
90 void Host_EndGame (char *message, ...)
95 va_start (argptr,message);
96 vsprintf (string,message,argptr);
98 Con_DPrintf ("Host_EndGame: %s\n",string);
101 Host_ShutdownServer (false);
103 if (cls.state == ca_dedicated)
104 Sys_Error ("Host_EndGame: %s\n",string); // dedicated servers exit
106 if (cls.demonum != -1)
111 longjmp (host_abortserver, 1);
118 This shuts down both the client and server
121 char hosterrorstring[1024];
122 void Host_Error (char *error, ...)
125 static qboolean inerror = false;
130 va_start (argptr,error);
131 vsprintf (string,error,argptr);
133 Sys_Error ("Host_Error: recursively entered (original error was: %s new error is: %s)", hosterrorstring, string);
137 SCR_EndLoadingPlaque (); // reenable screen updates
139 va_start (argptr,error);
140 vsprintf (hosterrorstring,error,argptr);
142 Con_Printf ("Host_Error: %s\n",hosterrorstring);
145 Host_ShutdownServer (false);
147 if (cls.state == ca_dedicated)
148 Sys_Error ("Host_Error: %s\n",hosterrorstring); // dedicated servers exit
155 longjmp (host_abortserver, 1);
163 void Host_FindMaxClients (void)
169 i = COM_CheckParm ("-dedicated");
172 cls.state = ca_dedicated;
173 if (i != (com_argc - 1))
175 svs.maxclients = atoi (com_argv[i+1]);
181 cls.state = ca_disconnected;
183 i = COM_CheckParm ("-listen");
186 if (cls.state == ca_dedicated)
187 Sys_Error ("Only one of -dedicated or -listen can be specified");
188 if (i != (com_argc - 1))
189 svs.maxclients = atoi (com_argv[i+1]);
193 if (svs.maxclients < 1)
195 else if (svs.maxclients > MAX_SCOREBOARD)
196 svs.maxclients = MAX_SCOREBOARD;
198 svs.maxclientslimit = svs.maxclients;
199 if (svs.maxclientslimit < MAX_SCOREBOARD) // LordHavoc: upped listen mode limit from 4 to MAX_SCOREBOARD
200 svs.maxclientslimit = MAX_SCOREBOARD;
201 svs.clients = Hunk_AllocName (svs.maxclientslimit*sizeof(client_t), "clients");
203 if (svs.maxclients > 1)
204 Cvar_SetValue ("deathmatch", 1.0);
206 Cvar_SetValue ("deathmatch", 0.0);
211 =======================
213 ======================
215 void Host_InitLocal (void)
217 Host_InitCommands ();
219 Cvar_RegisterVariable (&host_framerate);
220 Cvar_RegisterVariable (&host_speeds);
221 Cvar_RegisterVariable (&slowmo);
223 Cvar_RegisterVariable (&sys_ticrate);
224 Cvar_RegisterVariable (&serverprofile);
226 Cvar_RegisterVariable (&fraglimit);
227 Cvar_RegisterVariable (&timelimit);
228 Cvar_RegisterVariable (&teamplay);
229 Cvar_RegisterVariable (&samelevel);
230 Cvar_RegisterVariable (&noexit);
231 Cvar_RegisterVariable (&skill);
232 Cvar_RegisterVariable (&developer);
233 Cvar_RegisterVariable (&deathmatch);
234 Cvar_RegisterVariable (&coop);
236 Cvar_RegisterVariable (&pausable);
238 Cvar_RegisterVariable (&temp1);
240 Cvar_RegisterVariable (×tamps);
241 Cvar_RegisterVariable (&timeformat);
243 Host_FindMaxClients ();
245 host_time = 1.0; // so a think at time 0 won't get called
251 Host_WriteConfiguration
253 Writes key bindings and archived cvars to config.cfg
256 void Host_WriteConfiguration (void)
260 // dedicated servers initialize the host but don't parse and set the
262 if (host_initialized & !isDedicated)
264 f = fopen (va("%s/config.cfg",com_gamedir), "w");
267 Con_Printf ("Couldn't write config.cfg.\n");
271 Key_WriteBindings (f);
272 Cvar_WriteVariables (f);
283 Sends text across to be displayed
284 FIXME: make this just a stuffed echo?
287 void SV_ClientPrintf (char *fmt, ...)
292 va_start (argptr,fmt);
293 vsprintf (string, fmt,argptr);
296 MSG_WriteByte (&host_client->message, svc_print);
297 MSG_WriteString (&host_client->message, string);
304 Sends text to all active clients
307 void SV_BroadcastPrintf (char *fmt, ...)
313 va_start (argptr,fmt);
314 vsprintf (string, fmt,argptr);
317 for (i=0 ; i<svs.maxclients ; i++)
318 if (svs.clients[i].active && svs.clients[i].spawned)
320 MSG_WriteByte (&svs.clients[i].message, svc_print);
321 MSG_WriteString (&svs.clients[i].message, string);
329 Send text over to the client to be executed
332 void Host_ClientCommands (char *fmt, ...)
337 va_start (argptr,fmt);
338 vsprintf (string, fmt,argptr);
341 MSG_WriteByte (&host_client->message, svc_stufftext);
342 MSG_WriteString (&host_client->message, string);
346 =====================
349 Called when the player is getting totally kicked off the host
350 if (crash = true), don't bother sending signofs
351 =====================
353 void SV_DropClient (qboolean crash)
361 // send any final messages (don't check for errors)
362 if (NET_CanSendMessage (host_client->netconnection))
364 MSG_WriteByte (&host_client->message, svc_disconnect);
365 NET_SendMessage (host_client->netconnection, &host_client->message);
368 if (sv.active && host_client->edict && host_client->spawned) // LordHavoc: don't call QC if server is dead (avoids recursive Host_Error in some mods when they run out of edicts)
370 // call the prog function for removing a client
371 // this will set the body to a dead frame, among other things
372 saveSelf = pr_global_struct->self;
373 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
374 PR_ExecuteProgram (pr_global_struct->ClientDisconnect);
375 pr_global_struct->self = saveSelf;
378 Sys_Printf ("Client %s removed\n",host_client->name);
381 // break the net connection
382 NET_Close (host_client->netconnection);
383 host_client->netconnection = NULL;
385 // free the client (the body stays around)
386 host_client->active = false;
387 host_client->name[0] = 0;
388 host_client->old_frags = -999999;
389 net_activeconnections--;
391 // send notification to all clients
392 for (i=0, client = svs.clients ; i<svs.maxclients ; i++, client++)
396 MSG_WriteByte (&client->message, svc_updatename);
397 MSG_WriteByte (&client->message, host_client - svs.clients);
398 MSG_WriteString (&client->message, "");
399 MSG_WriteByte (&client->message, svc_updatefrags);
400 MSG_WriteByte (&client->message, host_client - svs.clients);
401 MSG_WriteShort (&client->message, 0);
402 MSG_WriteByte (&client->message, svc_updatecolors);
403 MSG_WriteByte (&client->message, host_client - svs.clients);
404 MSG_WriteByte (&client->message, 0);
412 This only happens at the end of a game, not between levels
415 void Host_ShutdownServer(qboolean crash)
428 // stop all client sounds immediately
429 if (cls.state == ca_connected)
432 // flush any pending messages - like the score!!!
433 start = Sys_FloatTime();
437 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
439 if (host_client->active && host_client->message.cursize)
441 if (NET_CanSendMessage (host_client->netconnection))
443 NET_SendMessage(host_client->netconnection, &host_client->message);
444 SZ_Clear (&host_client->message);
448 NET_GetMessage(host_client->netconnection);
453 if ((Sys_FloatTime() - start) > 3.0)
458 // make sure all the clients know we're disconnecting
462 MSG_WriteByte(&buf, svc_disconnect);
463 count = NET_SendToAll(&buf, 5);
465 Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %u clients\n", count);
467 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
468 if (host_client->active)
469 SV_DropClient(crash);
474 memset (&sv, 0, sizeof(sv));
475 memset (svs.clients, 0, svs.maxclientslimit*sizeof(client_t));
483 This clears all the memory used by both the client and server, but does
484 not reinitialize anything.
487 void Host_ClearMemory (void)
489 Con_DPrintf ("Clearing memory\n");
492 Hunk_FreeToLowMark (host_hunklevel);
495 memset (&sv, 0, sizeof(sv));
496 memset (&cl, 0, sizeof(cl));
500 //============================================================================
506 Returns false if the time is too short to run a frame
509 qboolean Host_FilterTime (float time)
513 // if (!cls.timedemo && realtime - oldrealtime < (1.0 / 72.0))
514 // return false; // framerate is too high
516 host_frametime = (realtime - oldrealtime) * slowmo.value; // LordHavoc: slowmo cvar
517 oldrealtime = realtime;
519 if (host_framerate.value > 0)
520 host_frametime = host_framerate.value;
522 { // don't allow really long or short frames
523 if (host_frametime > 0.1)
524 host_frametime = 0.1;
525 if (host_frametime < 0.001)
526 host_frametime = 0.001;
535 Host_GetConsoleCommands
537 Add them exactly as if they had been typed at the console
540 void Host_GetConsoleCommands (void)
546 cmd = Sys_ConsoleInput ();
562 void _Host_ServerFrame (void)
564 // run the world state
565 pr_global_struct->frametime = host_frametime;
567 // read client messages
570 // move things around and think
571 // always pause in single player if in console or menus
572 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
576 void Host_ServerFrame (void)
578 float save_host_frametime;
579 float temp_host_frametime;
580 static float host_serverframe_timevalue;
582 // run the world state
583 pr_global_struct->frametime = host_frametime;
585 // set the time and clear the general datagram
588 // check for new clients
589 SV_CheckForNewClients ();
591 temp_host_frametime = save_host_frametime = host_frametime;
592 // LordHavoc: the results of my attempts to mangle this code to process no more than sys_ticrate,
593 // when I found that was too choppy, I changed it back to processing at least 20fps,
594 // I consider it a bit of a failure... because I felt a little out of control in singleplayer
596 //if (host_serverframe_timevalue < -0.2) // don't let it get way out of range
597 // host_serverframe_timevalue = -0.2;
598 //host_serverframe_timevalue += host_frametime;
599 // process frames (several if rendering is too slow to run well as a server)
600 while(temp_host_frametime > 0.0)
602 host_frametime = temp_host_frametime;
603 if (host_frametime > 0.05)
604 host_frametime = 0.05;
605 temp_host_frametime -= host_frametime;
606 // host_serverframe_timevalue -= host_frametime;
607 _Host_ServerFrame ();
609 host_frametime = save_host_frametime;
611 // send all messages to the clients
612 SV_SendClientMessages ();
613 // LordHavoc: sadly, this didn't look good to the person running the server in listen mode
615 // wait until enough time has built up when the framerate exceeds sys_ticrate
616 if (host_serverframe_timevalue >= sys_ticrate.value)
618 // while(host_serverframe_timevalue >= sys_ticrate.value)
619 // host_serverframe_timevalue -= sys_ticrate.value;
620 // send all messages to the clients
621 SV_SendClientMessages ();
628 double frametimetotal = 0, lastservertime = 0;
629 void Host_ServerFrame (void)
631 frametimetotal += host_frametime;
632 // LordHavoc: cap server at sys_ticrate in listen games
633 if (!isDedicated && svs.maxclients > 1 && ((realtime - lastservertime) < sys_ticrate.value))
635 // run the world state
636 sv_frametime = pr_global_struct->frametime = frametimetotal;
638 // pr_global_struct->frametime = host_frametime;
640 // set the time and clear the general datagram
643 // check for new clients
644 SV_CheckForNewClients ();
646 // read client messages
649 // move things around and think
650 // always pause in single player if in console or menus
651 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
654 // send all messages to the clients
655 SV_SendClientMessages ();
665 Runs all active servers
668 void _Host_Frame (float time)
670 static double time1 = 0;
671 static double time2 = 0;
672 static double time3 = 0;
673 int pass1, pass2, pass3;
675 if (setjmp (host_abortserver) )
676 return; // something bad happened, or the server disconnected
678 // keep the random time dependent
681 // decide the simulation time
682 if (!Host_FilterTime (time))
683 return; // don't run too fast, or packets will flood out
685 // get new key events
686 Sys_SendKeyEvents ();
688 // allow mice or other external controllers to add commands
691 // process console commands
696 // if running the server locally, make intentions now
700 //-------------------
704 //-------------------
706 // check for commands typed to the host
707 Host_GetConsoleCommands ();
712 //-------------------
716 //-------------------
718 // if running the server remotely, send intentions now after
719 // the incoming messages have been read
723 host_time += host_frametime;
725 // fetch results from server
726 if (cls.state == ca_connected)
728 CL_ReadFromServer ();
732 if (host_speeds.value)
733 time1 = Sys_FloatTime ();
737 if (host_speeds.value)
738 time2 = Sys_FloatTime ();
741 if (cls.signon == SIGNONS)
743 S_Update (r_origin, vpn, vright, vup);
747 S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin);
751 if (host_speeds.value)
753 pass1 = (time1 - time3)*1000;
754 time3 = Sys_FloatTime ();
755 pass2 = (time2 - time1)*1000;
756 pass3 = (time3 - time2)*1000;
757 Con_Printf ("%3i tot %3i server %3i gfx %3i snd\n",
758 pass1+pass2+pass3, pass1, pass2, pass3);
764 void Host_Frame (float time)
767 static double timetotal;
768 static int timecount;
771 if (!serverprofile.value)
777 time1 = Sys_FloatTime ();
779 time2 = Sys_FloatTime ();
781 timetotal += time2 - time1;
784 if (timecount < 1000)
787 m = timetotal*1000/timecount;
791 for (i=0 ; i<svs.maxclients ; i++)
793 if (svs.clients[i].active)
797 Con_Printf ("serverprofile: %2i clients %2i msec\n", c, m);
800 //============================================================================
804 #define VCR_SIGNATURE 0x56435231
807 void Host_InitVCR (quakeparms_t *parms)
812 if (COM_CheckParm("-playback"))
815 Sys_Error("No other parameters allowed with -playback\n");
817 Sys_FileOpenRead("quake.vcr", &vcrFile);
819 Sys_Error("playback file not found\n");
821 Sys_FileRead (vcrFile, &i, sizeof(int));
822 if (i != VCR_SIGNATURE)
823 Sys_Error("Invalid signature in vcr file\n");
825 Sys_FileRead (vcrFile, &com_argc, sizeof(int));
826 com_argv = malloc(com_argc * sizeof(char *));
827 com_argv[0] = parms->argv[0];
828 for (i = 0; i < com_argc; i++)
830 Sys_FileRead (vcrFile, &len, sizeof(int));
832 Sys_FileRead (vcrFile, p, len);
835 com_argc++; /* add one for arg[0] */
836 parms->argc = com_argc;
837 parms->argv = com_argv;
840 if ( (n = COM_CheckParm("-record")) != 0)
842 vcrFile = Sys_FileOpenWrite("quake.vcr");
845 Sys_FileWrite(vcrFile, &i, sizeof(int));
847 Sys_FileWrite(vcrFile, &i, sizeof(int));
848 for (i = 1; i < com_argc; i++)
853 Sys_FileWrite(vcrFile, &len, sizeof(int));
854 Sys_FileWrite(vcrFile, "-playback", len);
857 len = strlen(com_argv[i]) + 1;
858 Sys_FileWrite(vcrFile, &len, sizeof(int));
859 Sys_FileWrite(vcrFile, com_argv[i], len);
870 void Host_Init (quakeparms_t *parms)
874 minimum_memory = MINIMUM_MEMORY;
876 minimum_memory = MINIMUM_MEMORY_LEVELPAK;
878 if (COM_CheckParm ("-minmemory"))
879 parms->memsize = minimum_memory;
883 if (parms->memsize < minimum_memory)
884 Sys_Error ("Only %4.1f megs of memory available, can't execute game", parms->memsize / (float)0x100000);
886 com_argc = parms->argc;
887 com_argv = parms->argv;
889 Memory_Init (parms->membase, parms->memsize);
894 Host_InitVCR (parms);
895 COM_Init (parms->basedir);
897 W_LoadWadFile ("gfx.wad");
906 Con_Printf ("Exe: "__TIME__" "__DATE__"\n");
907 Con_Printf ("%4.1f megabyte heap\n",parms->memsize/ (1024*1024.0));
909 R_InitTextures (); // needed even for dedicated servers
911 if (cls.state != ca_dedicated)
913 host_basepal = (byte *)COM_LoadHunkFile ("gfx/palette.lmp", false);
915 Sys_Error ("Couldn't load gfx/palette.lmp");
916 host_basepal[765] = host_basepal[766] = host_basepal[767] = 0; // LordHavoc: force the transparent color to black
917 // host_colormap = (byte *)COM_LoadHunkFile ("gfx/colormap.lmp", false);
918 // if (!host_colormap)
919 // Sys_Error ("Couldn't load gfx/colormap.lmp");
921 #ifndef _WIN32 // on non win32, mouse comes before video for security reasons
924 VID_Init (host_basepal);
933 #ifdef _WIN32 // on non win32, mouse comes before video for security reasons
938 Cbuf_InsertText ("exec quake.rc\n");
940 Hunk_AllocName (0, "-HOST_HUNKLEVEL-");
941 host_hunklevel = Hunk_LowMark ();
943 host_initialized = true;
945 Sys_Printf ("========Quake Initialized=========\n");
953 FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better
954 to run quit through here before the final handoff to the sys code.
957 void Host_Shutdown(void)
959 static qboolean isdown = false;
963 printf ("recursive shutdown\n");
968 // keep Con_Printf from trying to update the screen
969 scr_disabled_for_loading = true;
971 Host_WriteConfiguration ();
978 if (cls.state != ca_dedicated)