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 void Host_Error (char *error, ...)
125 static qboolean inerror = false;
128 Sys_Error ("Host_Error: recursively entered");
131 SCR_EndLoadingPlaque (); // reenable screen updates
133 va_start (argptr,error);
134 vsprintf (string,error,argptr);
136 Con_Printf ("Host_Error: %s\n",string);
139 Host_ShutdownServer (false);
141 if (cls.state == ca_dedicated)
142 Sys_Error ("Host_Error: %s\n",string); // dedicated servers exit
149 longjmp (host_abortserver, 1);
157 void Host_FindMaxClients (void)
163 i = COM_CheckParm ("-dedicated");
166 cls.state = ca_dedicated;
167 if (i != (com_argc - 1))
169 svs.maxclients = atoi (com_argv[i+1]);
175 cls.state = ca_disconnected;
177 i = COM_CheckParm ("-listen");
180 if (cls.state == ca_dedicated)
181 Sys_Error ("Only one of -dedicated or -listen can be specified");
182 if (i != (com_argc - 1))
183 svs.maxclients = atoi (com_argv[i+1]);
187 if (svs.maxclients < 1)
189 else if (svs.maxclients > MAX_SCOREBOARD)
190 svs.maxclients = MAX_SCOREBOARD;
192 svs.maxclientslimit = svs.maxclients;
193 if (svs.maxclientslimit < MAX_SCOREBOARD) // LordHavoc: upped listen mode limit from 4 to MAX_SCOREBOARD
194 svs.maxclientslimit = MAX_SCOREBOARD;
195 svs.clients = Hunk_AllocName (svs.maxclientslimit*sizeof(client_t), "clients");
197 if (svs.maxclients > 1)
198 Cvar_SetValue ("deathmatch", 1.0);
200 Cvar_SetValue ("deathmatch", 0.0);
205 =======================
207 ======================
209 void Host_InitLocal (void)
211 Host_InitCommands ();
213 Cvar_RegisterVariable (&host_framerate);
214 Cvar_RegisterVariable (&host_speeds);
215 Cvar_RegisterVariable (&slowmo);
217 Cvar_RegisterVariable (&sys_ticrate);
218 Cvar_RegisterVariable (&serverprofile);
220 Cvar_RegisterVariable (&fraglimit);
221 Cvar_RegisterVariable (&timelimit);
222 Cvar_RegisterVariable (&teamplay);
223 Cvar_RegisterVariable (&samelevel);
224 Cvar_RegisterVariable (&noexit);
225 Cvar_RegisterVariable (&skill);
226 Cvar_RegisterVariable (&developer);
227 Cvar_RegisterVariable (&deathmatch);
228 Cvar_RegisterVariable (&coop);
230 Cvar_RegisterVariable (&pausable);
232 Cvar_RegisterVariable (&temp1);
234 Cvar_RegisterVariable (×tamps);
235 Cvar_RegisterVariable (&timeformat);
237 Host_FindMaxClients ();
239 host_time = 1.0; // so a think at time 0 won't get called
245 Host_WriteConfiguration
247 Writes key bindings and archived cvars to config.cfg
250 void Host_WriteConfiguration (void)
254 // dedicated servers initialize the host but don't parse and set the
256 if (host_initialized & !isDedicated)
258 f = fopen (va("%s/config.cfg",com_gamedir), "w");
261 Con_Printf ("Couldn't write config.cfg.\n");
265 Key_WriteBindings (f);
266 Cvar_WriteVariables (f);
277 Sends text across to be displayed
278 FIXME: make this just a stuffed echo?
281 void SV_ClientPrintf (char *fmt, ...)
286 va_start (argptr,fmt);
287 vsprintf (string, fmt,argptr);
290 MSG_WriteByte (&host_client->message, svc_print);
291 MSG_WriteString (&host_client->message, string);
298 Sends text to all active clients
301 void SV_BroadcastPrintf (char *fmt, ...)
307 va_start (argptr,fmt);
308 vsprintf (string, fmt,argptr);
311 for (i=0 ; i<svs.maxclients ; i++)
312 if (svs.clients[i].active && svs.clients[i].spawned)
314 MSG_WriteByte (&svs.clients[i].message, svc_print);
315 MSG_WriteString (&svs.clients[i].message, string);
323 Send text over to the client to be executed
326 void Host_ClientCommands (char *fmt, ...)
331 va_start (argptr,fmt);
332 vsprintf (string, fmt,argptr);
335 MSG_WriteByte (&host_client->message, svc_stufftext);
336 MSG_WriteString (&host_client->message, string);
340 =====================
343 Called when the player is getting totally kicked off the host
344 if (crash = true), don't bother sending signofs
345 =====================
347 void SV_DropClient (qboolean crash)
355 // send any final messages (don't check for errors)
356 if (NET_CanSendMessage (host_client->netconnection))
358 MSG_WriteByte (&host_client->message, svc_disconnect);
359 NET_SendMessage (host_client->netconnection, &host_client->message);
362 if (host_client->edict && host_client->spawned)
364 // call the prog function for removing a client
365 // this will set the body to a dead frame, among other things
366 saveSelf = pr_global_struct->self;
367 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
368 PR_ExecuteProgram (pr_global_struct->ClientDisconnect);
369 pr_global_struct->self = saveSelf;
372 Sys_Printf ("Client %s removed\n",host_client->name);
375 // break the net connection
376 NET_Close (host_client->netconnection);
377 host_client->netconnection = NULL;
379 // free the client (the body stays around)
380 host_client->active = false;
381 host_client->name[0] = 0;
382 host_client->old_frags = -999999;
383 net_activeconnections--;
385 // send notification to all clients
386 for (i=0, client = svs.clients ; i<svs.maxclients ; i++, client++)
390 MSG_WriteByte (&client->message, svc_updatename);
391 MSG_WriteByte (&client->message, host_client - svs.clients);
392 MSG_WriteString (&client->message, "");
393 MSG_WriteByte (&client->message, svc_updatefrags);
394 MSG_WriteByte (&client->message, host_client - svs.clients);
395 MSG_WriteShort (&client->message, 0);
396 MSG_WriteByte (&client->message, svc_updatecolors);
397 MSG_WriteByte (&client->message, host_client - svs.clients);
398 MSG_WriteByte (&client->message, 0);
406 This only happens at the end of a game, not between levels
409 void Host_ShutdownServer(qboolean crash)
422 // stop all client sounds immediately
423 if (cls.state == ca_connected)
426 // flush any pending messages - like the score!!!
427 start = Sys_FloatTime();
431 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
433 if (host_client->active && host_client->message.cursize)
435 if (NET_CanSendMessage (host_client->netconnection))
437 NET_SendMessage(host_client->netconnection, &host_client->message);
438 SZ_Clear (&host_client->message);
442 NET_GetMessage(host_client->netconnection);
447 if ((Sys_FloatTime() - start) > 3.0)
452 // make sure all the clients know we're disconnecting
456 MSG_WriteByte(&buf, svc_disconnect);
457 count = NET_SendToAll(&buf, 5);
459 Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %u clients\n", count);
461 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
462 if (host_client->active)
463 SV_DropClient(crash);
468 memset (&sv, 0, sizeof(sv));
469 memset (svs.clients, 0, svs.maxclientslimit*sizeof(client_t));
477 This clears all the memory used by both the client and server, but does
478 not reinitialize anything.
481 void Host_ClearMemory (void)
483 Con_DPrintf ("Clearing memory\n");
486 Hunk_FreeToLowMark (host_hunklevel);
489 memset (&sv, 0, sizeof(sv));
490 memset (&cl, 0, sizeof(cl));
494 //============================================================================
500 Returns false if the time is too short to run a frame
503 qboolean Host_FilterTime (float time)
507 // if (!cls.timedemo && realtime - oldrealtime < (1.0 / 72.0))
508 // return false; // framerate is too high
510 host_frametime = (realtime - oldrealtime) * slowmo.value; // LordHavoc: slowmo cvar
511 oldrealtime = realtime;
513 if (host_framerate.value > 0)
514 host_frametime = host_framerate.value;
516 { // don't allow really long or short frames
517 if (host_frametime > 0.1)
518 host_frametime = 0.1;
519 if (host_frametime < 0.001)
520 host_frametime = 0.001;
529 Host_GetConsoleCommands
531 Add them exactly as if they had been typed at the console
534 void Host_GetConsoleCommands (void)
540 cmd = Sys_ConsoleInput ();
556 void _Host_ServerFrame (void)
558 // run the world state
559 pr_global_struct->frametime = host_frametime;
561 // read client messages
564 // move things around and think
565 // always pause in single player if in console or menus
566 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
570 void Host_ServerFrame (void)
572 float save_host_frametime;
573 float temp_host_frametime;
574 static float host_serverframe_timevalue;
576 // run the world state
577 pr_global_struct->frametime = host_frametime;
579 // set the time and clear the general datagram
582 // check for new clients
583 SV_CheckForNewClients ();
585 temp_host_frametime = save_host_frametime = host_frametime;
586 // LordHavoc: the results of my attempts to mangle this code to process no more than sys_ticrate,
587 // when I found that was too choppy, I changed it back to processing at least 20fps,
588 // I consider it a bit of a failure... because I felt a little out of control in singleplayer
590 //if (host_serverframe_timevalue < -0.2) // don't let it get way out of range
591 // host_serverframe_timevalue = -0.2;
592 //host_serverframe_timevalue += host_frametime;
593 // process frames (several if rendering is too slow to run well as a server)
594 while(temp_host_frametime > 0.0)
596 host_frametime = temp_host_frametime;
597 if (host_frametime > 0.05)
598 host_frametime = 0.05;
599 temp_host_frametime -= host_frametime;
600 // host_serverframe_timevalue -= host_frametime;
601 _Host_ServerFrame ();
603 host_frametime = save_host_frametime;
605 // send all messages to the clients
606 SV_SendClientMessages ();
607 // LordHavoc: sadly, this didn't look good to the person running the server in listen mode
609 // wait until enough time has built up when the framerate exceeds sys_ticrate
610 if (host_serverframe_timevalue >= sys_ticrate.value)
612 // while(host_serverframe_timevalue >= sys_ticrate.value)
613 // host_serverframe_timevalue -= sys_ticrate.value;
614 // send all messages to the clients
615 SV_SendClientMessages ();
622 double frametimetotal = 0, lastservertime = 0;
623 void Host_ServerFrame (void)
625 frametimetotal += host_frametime;
626 // LordHavoc: cap server at sys_ticrate in listen games
627 if (!isDedicated && svs.maxclients > 1 && ((realtime - lastservertime) < sys_ticrate.value))
629 // run the world state
630 sv_frametime = pr_global_struct->frametime = frametimetotal;
632 // pr_global_struct->frametime = host_frametime;
634 // set the time and clear the general datagram
637 // check for new clients
638 SV_CheckForNewClients ();
640 // read client messages
643 // move things around and think
644 // always pause in single player if in console or menus
645 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
648 // send all messages to the clients
649 SV_SendClientMessages ();
659 Runs all active servers
662 void _Host_Frame (float time)
664 static double time1 = 0;
665 static double time2 = 0;
666 static double time3 = 0;
667 int pass1, pass2, pass3;
669 if (setjmp (host_abortserver) )
670 return; // something bad happened, or the server disconnected
672 // keep the random time dependent
675 // decide the simulation time
676 if (!Host_FilterTime (time))
677 return; // don't run too fast, or packets will flood out
679 // get new key events
680 Sys_SendKeyEvents ();
682 // allow mice or other external controllers to add commands
685 // process console commands
690 // if running the server locally, make intentions now
694 //-------------------
698 //-------------------
700 // check for commands typed to the host
701 Host_GetConsoleCommands ();
706 //-------------------
710 //-------------------
712 // if running the server remotely, send intentions now after
713 // the incoming messages have been read
717 host_time += host_frametime;
719 // fetch results from server
720 if (cls.state == ca_connected)
722 CL_ReadFromServer ();
726 if (host_speeds.value)
727 time1 = Sys_FloatTime ();
731 if (host_speeds.value)
732 time2 = Sys_FloatTime ();
735 if (cls.signon == SIGNONS)
737 S_Update (r_origin, vpn, vright, vup);
741 S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin);
745 if (host_speeds.value)
747 pass1 = (time1 - time3)*1000;
748 time3 = Sys_FloatTime ();
749 pass2 = (time2 - time1)*1000;
750 pass3 = (time3 - time2)*1000;
751 Con_Printf ("%3i tot %3i server %3i gfx %3i snd\n",
752 pass1+pass2+pass3, pass1, pass2, pass3);
758 void Host_Frame (float time)
761 static double timetotal;
762 static int timecount;
765 if (!serverprofile.value)
771 time1 = Sys_FloatTime ();
773 time2 = Sys_FloatTime ();
775 timetotal += time2 - time1;
778 if (timecount < 1000)
781 m = timetotal*1000/timecount;
785 for (i=0 ; i<svs.maxclients ; i++)
787 if (svs.clients[i].active)
791 Con_Printf ("serverprofile: %2i clients %2i msec\n", c, m);
794 //============================================================================
798 #define VCR_SIGNATURE 0x56435231
801 void Host_InitVCR (quakeparms_t *parms)
806 if (COM_CheckParm("-playback"))
809 Sys_Error("No other parameters allowed with -playback\n");
811 Sys_FileOpenRead("quake.vcr", &vcrFile);
813 Sys_Error("playback file not found\n");
815 Sys_FileRead (vcrFile, &i, sizeof(int));
816 if (i != VCR_SIGNATURE)
817 Sys_Error("Invalid signature in vcr file\n");
819 Sys_FileRead (vcrFile, &com_argc, sizeof(int));
820 com_argv = malloc(com_argc * sizeof(char *));
821 com_argv[0] = parms->argv[0];
822 for (i = 0; i < com_argc; i++)
824 Sys_FileRead (vcrFile, &len, sizeof(int));
826 Sys_FileRead (vcrFile, p, len);
829 com_argc++; /* add one for arg[0] */
830 parms->argc = com_argc;
831 parms->argv = com_argv;
834 if ( (n = COM_CheckParm("-record")) != 0)
836 vcrFile = Sys_FileOpenWrite("quake.vcr");
839 Sys_FileWrite(vcrFile, &i, sizeof(int));
841 Sys_FileWrite(vcrFile, &i, sizeof(int));
842 for (i = 1; i < com_argc; i++)
847 Sys_FileWrite(vcrFile, &len, sizeof(int));
848 Sys_FileWrite(vcrFile, "-playback", len);
851 len = strlen(com_argv[i]) + 1;
852 Sys_FileWrite(vcrFile, &len, sizeof(int));
853 Sys_FileWrite(vcrFile, com_argv[i], len);
864 void Host_Init (quakeparms_t *parms)
868 minimum_memory = MINIMUM_MEMORY;
870 minimum_memory = MINIMUM_MEMORY_LEVELPAK;
872 if (COM_CheckParm ("-minmemory"))
873 parms->memsize = minimum_memory;
877 if (parms->memsize < minimum_memory)
878 Sys_Error ("Only %4.1f megs of memory available, can't execute game", parms->memsize / (float)0x100000);
880 com_argc = parms->argc;
881 com_argv = parms->argv;
883 Memory_Init (parms->membase, parms->memsize);
888 Host_InitVCR (parms);
889 COM_Init (parms->basedir);
891 W_LoadWadFile ("gfx.wad");
900 Con_Printf ("Exe: "__TIME__" "__DATE__"\n");
901 Con_Printf ("%4.1f megabyte heap\n",parms->memsize/ (1024*1024.0));
903 R_InitTextures (); // needed even for dedicated servers
905 if (cls.state != ca_dedicated)
907 host_basepal = (byte *)COM_LoadHunkFile ("gfx/palette.lmp", false);
909 Sys_Error ("Couldn't load gfx/palette.lmp");
910 host_basepal[765] = host_basepal[766] = host_basepal[767] = 0; // LordHavoc: force the transparent color to black
911 // host_colormap = (byte *)COM_LoadHunkFile ("gfx/colormap.lmp", false);
912 // if (!host_colormap)
913 // Sys_Error ("Couldn't load gfx/colormap.lmp");
915 #ifndef _WIN32 // on non win32, mouse comes before video for security reasons
918 VID_Init (host_basepal);
927 #ifdef _WIN32 // on non win32, mouse comes before video for security reasons
932 Cbuf_InsertText ("exec quake.rc\n");
934 Hunk_AllocName (0, "-HOST_HUNKLEVEL-");
935 host_hunklevel = Hunk_LowMark ();
937 host_initialized = true;
939 Sys_Printf ("========Quake Initialized=========\n");
947 FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better
948 to run quit through here before the final handoff to the sys code.
951 void Host_Shutdown(void)
953 static qboolean isdown = false;
957 printf ("recursive shutdown\n");
962 // keep Con_Printf from trying to update the screen
963 scr_disabled_for_loading = true;
965 Host_WriteConfiguration ();
972 if (cls.state != ca_dedicated)