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
49 client_t *host_client; // current client
51 jmp_buf host_abortserver;
54 //byte *host_colormap;
56 cvar_t host_framerate = {"host_framerate","0"}; // set for slow motion
57 cvar_t host_speeds = {"host_speeds","0"}; // set for running times
58 cvar_t slowmo = {"slowmo", "1.0"}; // LordHavoc: framerate independent slowmo
60 cvar_t sys_ticrate = {"sys_ticrate","0.05"};
61 cvar_t serverprofile = {"serverprofile","0"};
63 cvar_t fraglimit = {"fraglimit","0",false,true};
64 cvar_t timelimit = {"timelimit","0",false,true};
65 cvar_t teamplay = {"teamplay","0",false,true};
67 cvar_t samelevel = {"samelevel","0"};
68 cvar_t noexit = {"noexit","0",false,true};
70 cvar_t developer = {"developer","0"};
72 cvar_t skill = {"skill","1"}; // 0 - 3
73 cvar_t deathmatch = {"deathmatch","0"}; // 0, 1, or 2
74 cvar_t coop = {"coop","0"}; // 0 or 1
76 cvar_t pausable = {"pausable","1"};
78 cvar_t temp1 = {"temp1","0"};
80 cvar_t timestamps = {"timestamps", "0", true};
81 cvar_t timeformat = {"timeformat", "[%b %e %X] ", true};
88 void Host_EndGame (char *message, ...)
93 va_start (argptr,message);
94 vsprintf (string,message,argptr);
96 Con_DPrintf ("Host_EndGame: %s\n",string);
99 Host_ShutdownServer (false);
101 if (cls.state == ca_dedicated)
102 Sys_Error ("Host_EndGame: %s\n",string); // dedicated servers exit
104 if (cls.demonum != -1)
109 longjmp (host_abortserver, 1);
116 This shuts down both the client and server
119 void Host_Error (char *error, ...)
123 static qboolean inerror = false;
126 Sys_Error ("Host_Error: recursively entered");
129 SCR_EndLoadingPlaque (); // reenable screen updates
131 va_start (argptr,error);
132 vsprintf (string,error,argptr);
134 Con_Printf ("Host_Error: %s\n",string);
137 Host_ShutdownServer (false);
139 if (cls.state == ca_dedicated)
140 Sys_Error ("Host_Error: %s\n",string); // dedicated servers exit
147 longjmp (host_abortserver, 1);
155 void Host_FindMaxClients (void)
161 i = COM_CheckParm ("-dedicated");
164 cls.state = ca_dedicated;
165 if (i != (com_argc - 1))
167 svs.maxclients = atoi (com_argv[i+1]);
173 cls.state = ca_disconnected;
175 i = COM_CheckParm ("-listen");
178 if (cls.state == ca_dedicated)
179 Sys_Error ("Only one of -dedicated or -listen can be specified");
180 if (i != (com_argc - 1))
181 svs.maxclients = atoi (com_argv[i+1]);
185 if (svs.maxclients < 1)
187 else if (svs.maxclients > MAX_SCOREBOARD)
188 svs.maxclients = MAX_SCOREBOARD;
190 svs.maxclientslimit = svs.maxclients;
191 if (svs.maxclientslimit < MAX_SCOREBOARD) // LordHavoc: upped listen mode limit from 4 to MAX_SCOREBOARD
192 svs.maxclientslimit = MAX_SCOREBOARD;
193 svs.clients = Hunk_AllocName (svs.maxclientslimit*sizeof(client_t), "clients");
195 if (svs.maxclients > 1)
196 Cvar_SetValue ("deathmatch", 1.0);
198 Cvar_SetValue ("deathmatch", 0.0);
203 =======================
205 ======================
207 void Host_InitLocal (void)
209 Host_InitCommands ();
211 Cvar_RegisterVariable (&host_framerate);
212 Cvar_RegisterVariable (&host_speeds);
213 Cvar_RegisterVariable (&slowmo);
215 Cvar_RegisterVariable (&sys_ticrate);
216 Cvar_RegisterVariable (&serverprofile);
218 Cvar_RegisterVariable (&fraglimit);
219 Cvar_RegisterVariable (&timelimit);
220 Cvar_RegisterVariable (&teamplay);
221 Cvar_RegisterVariable (&samelevel);
222 Cvar_RegisterVariable (&noexit);
223 Cvar_RegisterVariable (&skill);
224 Cvar_RegisterVariable (&developer);
225 Cvar_RegisterVariable (&deathmatch);
226 Cvar_RegisterVariable (&coop);
228 Cvar_RegisterVariable (&pausable);
230 Cvar_RegisterVariable (&temp1);
232 Cvar_RegisterVariable (×tamps);
233 Cvar_RegisterVariable (&timeformat);
235 Host_FindMaxClients ();
237 host_time = 1.0; // so a think at time 0 won't get called
243 Host_WriteConfiguration
245 Writes key bindings and archived cvars to config.cfg
248 void Host_WriteConfiguration (void)
252 // dedicated servers initialize the host but don't parse and set the
254 if (host_initialized & !isDedicated)
256 f = fopen (va("%s/config.cfg",com_gamedir), "w");
259 Con_Printf ("Couldn't write config.cfg.\n");
263 Key_WriteBindings (f);
264 Cvar_WriteVariables (f);
275 Sends text across to be displayed
276 FIXME: make this just a stuffed echo?
279 void SV_ClientPrintf (char *fmt, ...)
284 va_start (argptr,fmt);
285 vsprintf (string, fmt,argptr);
288 MSG_WriteByte (&host_client->message, svc_print);
289 MSG_WriteString (&host_client->message, string);
296 Sends text to all active clients
299 void SV_BroadcastPrintf (char *fmt, ...)
305 va_start (argptr,fmt);
306 vsprintf (string, fmt,argptr);
309 for (i=0 ; i<svs.maxclients ; i++)
310 if (svs.clients[i].active && svs.clients[i].spawned)
312 MSG_WriteByte (&svs.clients[i].message, svc_print);
313 MSG_WriteString (&svs.clients[i].message, string);
321 Send text over to the client to be executed
324 void Host_ClientCommands (char *fmt, ...)
329 va_start (argptr,fmt);
330 vsprintf (string, fmt,argptr);
333 MSG_WriteByte (&host_client->message, svc_stufftext);
334 MSG_WriteString (&host_client->message, string);
338 =====================
341 Called when the player is getting totally kicked off the host
342 if (crash = true), don't bother sending signofs
343 =====================
345 void SV_DropClient (qboolean crash)
353 // send any final messages (don't check for errors)
354 if (NET_CanSendMessage (host_client->netconnection))
356 MSG_WriteByte (&host_client->message, svc_disconnect);
357 NET_SendMessage (host_client->netconnection, &host_client->message);
360 if (host_client->edict && host_client->spawned)
362 // call the prog function for removing a client
363 // this will set the body to a dead frame, among other things
364 saveSelf = pr_global_struct->self;
365 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
366 PR_ExecuteProgram (pr_global_struct->ClientDisconnect);
367 pr_global_struct->self = saveSelf;
370 Sys_Printf ("Client %s removed\n",host_client->name);
373 // break the net connection
374 NET_Close (host_client->netconnection);
375 host_client->netconnection = NULL;
377 // free the client (the body stays around)
378 host_client->active = false;
379 host_client->name[0] = 0;
380 host_client->old_frags = -999999;
381 net_activeconnections--;
383 // send notification to all clients
384 for (i=0, client = svs.clients ; i<svs.maxclients ; i++, client++)
388 MSG_WriteByte (&client->message, svc_updatename);
389 MSG_WriteByte (&client->message, host_client - svs.clients);
390 MSG_WriteString (&client->message, "");
391 MSG_WriteByte (&client->message, svc_updatefrags);
392 MSG_WriteByte (&client->message, host_client - svs.clients);
393 MSG_WriteShort (&client->message, 0);
394 MSG_WriteByte (&client->message, svc_updatecolors);
395 MSG_WriteByte (&client->message, host_client - svs.clients);
396 MSG_WriteByte (&client->message, 0);
404 This only happens at the end of a game, not between levels
407 void Host_ShutdownServer(qboolean crash)
420 // stop all client sounds immediately
421 if (cls.state == ca_connected)
424 // flush any pending messages - like the score!!!
425 start = Sys_FloatTime();
429 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
431 if (host_client->active && host_client->message.cursize)
433 if (NET_CanSendMessage (host_client->netconnection))
435 NET_SendMessage(host_client->netconnection, &host_client->message);
436 SZ_Clear (&host_client->message);
440 NET_GetMessage(host_client->netconnection);
445 if ((Sys_FloatTime() - start) > 3.0)
450 // make sure all the clients know we're disconnecting
454 MSG_WriteByte(&buf, svc_disconnect);
455 count = NET_SendToAll(&buf, 5);
457 Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %u clients\n", count);
459 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
460 if (host_client->active)
461 SV_DropClient(crash);
466 memset (&sv, 0, sizeof(sv));
467 memset (svs.clients, 0, svs.maxclientslimit*sizeof(client_t));
475 This clears all the memory used by both the client and server, but does
476 not reinitialize anything.
479 void Host_ClearMemory (void)
481 Con_DPrintf ("Clearing memory\n");
485 Hunk_FreeToLowMark (host_hunklevel);
488 memset (&sv, 0, sizeof(sv));
489 memset (&cl, 0, sizeof(cl));
493 //============================================================================
499 Returns false if the time is too short to run a frame
502 qboolean Host_FilterTime (float time)
506 // if (!cls.timedemo && realtime - oldrealtime < (1.0 / 72.0))
507 // return false; // framerate is too high
509 host_frametime = (realtime - oldrealtime) * slowmo.value; // LordHavoc: slowmo cvar
510 oldrealtime = realtime;
512 if (host_framerate.value > 0)
513 host_frametime = host_framerate.value;
515 { // don't allow really long or short frames
516 if (host_frametime > 0.1)
517 host_frametime = 0.1;
518 if (host_frametime < 0.001)
519 host_frametime = 0.001;
528 Host_GetConsoleCommands
530 Add them exactly as if they had been typed at the console
533 void Host_GetConsoleCommands (void)
539 cmd = Sys_ConsoleInput ();
555 void _Host_ServerFrame (void)
557 // run the world state
558 pr_global_struct->frametime = host_frametime;
560 // read client messages
563 // move things around and think
564 // always pause in single player if in console or menus
565 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
569 void Host_ServerFrame (void)
571 float save_host_frametime;
572 float temp_host_frametime;
573 static float host_serverframe_timevalue;
575 // run the world state
576 pr_global_struct->frametime = host_frametime;
578 // set the time and clear the general datagram
581 // check for new clients
582 SV_CheckForNewClients ();
584 temp_host_frametime = save_host_frametime = host_frametime;
585 // LordHavoc: the results of my attempts to mangle this code to process no more than sys_ticrate,
586 // when I found that was too choppy, I changed it back to processing at least 20fps,
587 // I consider it a bit of a failure... because I felt a little out of control in singleplayer
589 //if (host_serverframe_timevalue < -0.2) // don't let it get way out of range
590 // host_serverframe_timevalue = -0.2;
591 //host_serverframe_timevalue += host_frametime;
592 // process frames (several if rendering is too slow to run well as a server)
593 while(temp_host_frametime > 0.0)
595 host_frametime = temp_host_frametime;
596 if (host_frametime > 0.05)
597 host_frametime = 0.05;
598 temp_host_frametime -= host_frametime;
599 // host_serverframe_timevalue -= host_frametime;
600 _Host_ServerFrame ();
602 host_frametime = save_host_frametime;
604 // send all messages to the clients
605 SV_SendClientMessages ();
606 // LordHavoc: sadly, this didn't look good to the person running the server in listen mode
608 // wait until enough time has built up when the framerate exceeds sys_ticrate
609 if (host_serverframe_timevalue >= sys_ticrate.value)
611 // while(host_serverframe_timevalue >= sys_ticrate.value)
612 // host_serverframe_timevalue -= sys_ticrate.value;
613 // send all messages to the clients
614 SV_SendClientMessages ();
621 double frametimetotal = 0, lastservertime = 0;
622 void Host_ServerFrame (void)
624 frametimetotal += host_frametime;
625 // LordHavoc: cap server at sys_ticrate in listen games
626 if (!isDedicated && svs.maxclients > 1 && ((realtime - lastservertime) < sys_ticrate.value))
628 // run the world state
629 pr_global_struct->frametime = frametimetotal;
631 // pr_global_struct->frametime = host_frametime;
633 // set the time and clear the general datagram
636 // check for new clients
637 SV_CheckForNewClients ();
639 // read client messages
642 // move things around and think
643 // always pause in single player if in console or menus
644 if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) )
647 // send all messages to the clients
648 SV_SendClientMessages ();
658 Runs all active servers
661 void _Host_Frame (float time)
663 static double time1 = 0;
664 static double time2 = 0;
665 static double time3 = 0;
666 int pass1, pass2, pass3;
668 if (setjmp (host_abortserver) )
669 return; // something bad happened, or the server disconnected
671 // keep the random time dependent
674 // decide the simulation time
675 if (!Host_FilterTime (time))
676 return; // don't run too fast, or packets will flood out
678 // get new key events
679 Sys_SendKeyEvents ();
681 // allow mice or other external controllers to add commands
684 // process console commands
689 // if running the server locally, make intentions now
693 //-------------------
697 //-------------------
699 // check for commands typed to the host
700 Host_GetConsoleCommands ();
705 //-------------------
709 //-------------------
711 // if running the server remotely, send intentions now after
712 // the incoming messages have been read
716 host_time += host_frametime;
718 // fetch results from server
719 if (cls.state == ca_connected)
721 CL_ReadFromServer ();
725 if (host_speeds.value)
726 time1 = Sys_FloatTime ();
730 if (host_speeds.value)
731 time2 = Sys_FloatTime ();
734 if (cls.signon == SIGNONS)
736 S_Update (r_origin, vpn, vright, vup);
740 S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin);
744 if (host_speeds.value)
746 pass1 = (time1 - time3)*1000;
747 time3 = Sys_FloatTime ();
748 pass2 = (time2 - time1)*1000;
749 pass3 = (time3 - time2)*1000;
750 Con_Printf ("%3i tot %3i server %3i gfx %3i snd\n",
751 pass1+pass2+pass3, pass1, pass2, pass3);
757 void Host_Frame (float time)
760 static double timetotal;
761 static int timecount;
764 if (!serverprofile.value)
770 time1 = Sys_FloatTime ();
772 time2 = Sys_FloatTime ();
774 timetotal += time2 - time1;
777 if (timecount < 1000)
780 m = timetotal*1000/timecount;
784 for (i=0 ; i<svs.maxclients ; i++)
786 if (svs.clients[i].active)
790 Con_Printf ("serverprofile: %2i clients %2i msec\n", c, m);
793 //============================================================================
797 #define VCR_SIGNATURE 0x56435231
800 void Host_InitVCR (quakeparms_t *parms)
805 if (COM_CheckParm("-playback"))
808 Sys_Error("No other parameters allowed with -playback\n");
810 Sys_FileOpenRead("quake.vcr", &vcrFile);
812 Sys_Error("playback file not found\n");
814 Sys_FileRead (vcrFile, &i, sizeof(int));
815 if (i != VCR_SIGNATURE)
816 Sys_Error("Invalid signature in vcr file\n");
818 Sys_FileRead (vcrFile, &com_argc, sizeof(int));
819 com_argv = malloc(com_argc * sizeof(char *));
820 com_argv[0] = parms->argv[0];
821 for (i = 0; i < com_argc; i++)
823 Sys_FileRead (vcrFile, &len, sizeof(int));
825 Sys_FileRead (vcrFile, p, len);
828 com_argc++; /* add one for arg[0] */
829 parms->argc = com_argc;
830 parms->argv = com_argv;
833 if ( (n = COM_CheckParm("-record")) != 0)
835 vcrFile = Sys_FileOpenWrite("quake.vcr");
838 Sys_FileWrite(vcrFile, &i, sizeof(int));
840 Sys_FileWrite(vcrFile, &i, sizeof(int));
841 for (i = 1; i < com_argc; i++)
846 Sys_FileWrite(vcrFile, &len, sizeof(int));
847 Sys_FileWrite(vcrFile, "-playback", len);
850 len = strlen(com_argv[i]) + 1;
851 Sys_FileWrite(vcrFile, &len, sizeof(int));
852 Sys_FileWrite(vcrFile, com_argv[i], len);
863 void Host_Init (quakeparms_t *parms)
867 minimum_memory = MINIMUM_MEMORY;
869 minimum_memory = MINIMUM_MEMORY_LEVELPAK;
871 if (COM_CheckParm ("-minmemory"))
872 parms->memsize = minimum_memory;
876 if (parms->memsize < minimum_memory)
877 Sys_Error ("Only %4.1f megs of memory available, can't execute game", parms->memsize / (float)0x100000);
879 com_argc = parms->argc;
880 com_argv = parms->argv;
882 Memory_Init (parms->membase, parms->memsize);
887 Host_InitVCR (parms);
888 COM_Init (parms->basedir);
890 W_LoadWadFile ("gfx.wad");
899 Con_Printf ("Exe: "__TIME__" "__DATE__"\n");
900 Con_Printf ("%4.1f megabyte heap\n",parms->memsize/ (1024*1024.0));
902 R_InitTextures (); // needed even for dedicated servers
904 if (cls.state != ca_dedicated)
906 host_basepal = (byte *)COM_LoadHunkFile ("gfx/palette.lmp", false);
908 Sys_Error ("Couldn't load gfx/palette.lmp");
909 host_basepal[765] = host_basepal[766] = host_basepal[767] = 0; // LordHavoc: force the transparent color to black
910 // host_colormap = (byte *)COM_LoadHunkFile ("gfx/colormap.lmp", false);
911 // if (!host_colormap)
912 // Sys_Error ("Couldn't load gfx/colormap.lmp");
914 #ifndef _WIN32 // on non win32, mouse comes before video for security reasons
917 VID_Init (host_basepal);
926 #ifdef _WIN32 // on non win32, mouse comes before video for security reasons
931 Cbuf_InsertText ("exec quake.rc\n");
933 Hunk_AllocName (0, "-HOST_HUNKLEVEL-");
934 host_hunklevel = Hunk_LowMark ();
936 host_initialized = true;
938 Sys_Printf ("========Quake Initialized=========\n");
946 FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better
947 to run quit through here before the final handoff to the sys code.
950 void Host_Shutdown(void)
952 static qboolean isdown = false;
956 printf ("recursive shutdown\n");
961 // keep Con_Printf from trying to update the screen
962 scr_disabled_for_loading = true;
964 Host_WriteConfiguration ();
971 if (cls.state != ca_dedicated)