]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - host.c
Gigantic commit - dlight system rewritten
[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 "quakedef.h"
23
24 /*
25
26 A server can allways be started, even if the system started out as a client
27 to a remote system.
28
29 A client can NOT be started if the system started as a dedicated server.
30
31 Memory is cleared / released when a server or client begins, not when they end.
32
33 */
34
35 quakeparms_t host_parms;
36
37 qboolean        host_initialized;               // true if into command execution
38
39 double          host_frametime;
40 double          host_time;
41 double          realtime;                               // without any filtering or bounding
42 double          oldrealtime;                    // last frame run
43 int                     host_framecount;
44
45 double          sv_frametime;
46
47 int                     host_hunklevel;
48
49 int                     minimum_memory;
50
51 client_t        *host_client;                   // current client
52
53 jmp_buf         host_abortserver;
54
55 byte            *host_basepal;
56 //byte          *host_colormap;
57
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
61
62 cvar_t  sys_ticrate = {"sys_ticrate","0.05"};
63 cvar_t  serverprofile = {"serverprofile","0"};
64
65 cvar_t  fraglimit = {"fraglimit","0",false,true};
66 cvar_t  timelimit = {"timelimit","0",false,true};
67 cvar_t  teamplay = {"teamplay","0",false,true};
68
69 cvar_t  samelevel = {"samelevel","0"};
70 cvar_t  noexit = {"noexit","0",false,true};
71
72 cvar_t  developer = {"developer","0"};
73
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
77
78 cvar_t  pausable = {"pausable","1"};
79
80 cvar_t  temp1 = {"temp1","0"};
81
82 cvar_t  timestamps = {"timestamps", "0", true};
83 cvar_t  timeformat = {"timeformat", "[%b %e %X] ", true};
84
85 /*
86 ================
87 Host_EndGame
88 ================
89 */
90 void Host_EndGame (char *message, ...)
91 {
92         va_list         argptr;
93         char            string[1024];
94         
95         va_start (argptr,message);
96         vsprintf (string,message,argptr);
97         va_end (argptr);
98         Con_DPrintf ("Host_EndGame: %s\n",string);
99         
100         if (sv.active)
101                 Host_ShutdownServer (false);
102
103         if (cls.state == ca_dedicated)
104                 Sys_Error ("Host_EndGame: %s\n",string);        // dedicated servers exit
105         
106         if (cls.demonum != -1)
107                 CL_NextDemo ();
108         else
109                 CL_Disconnect ();
110
111         longjmp (host_abortserver, 1);
112 }
113
114 /*
115 ================
116 Host_Error
117
118 This shuts down both the client and server
119 ================
120 */
121 void Host_Error (char *error, ...)
122 {
123         va_list         argptr;
124         char            string[1024];
125         static  qboolean inerror = false;
126         
127         if (inerror)
128                 Sys_Error ("Host_Error: recursively entered");
129         inerror = true;
130         
131         SCR_EndLoadingPlaque ();                // reenable screen updates
132
133         va_start (argptr,error);
134         vsprintf (string,error,argptr);
135         va_end (argptr);
136         Con_Printf ("Host_Error: %s\n",string);
137         
138         if (sv.active)
139                 Host_ShutdownServer (false);
140
141         if (cls.state == ca_dedicated)
142                 Sys_Error ("Host_Error: %s\n",string);  // dedicated servers exit
143
144         CL_Disconnect ();
145         cls.demonum = -1;
146
147         inerror = false;
148
149         longjmp (host_abortserver, 1);
150 }
151
152 /*
153 ================
154 Host_FindMaxClients
155 ================
156 */
157 void    Host_FindMaxClients (void)
158 {
159         int             i;
160
161         svs.maxclients = 1;
162                 
163         i = COM_CheckParm ("-dedicated");
164         if (i)
165         {
166                 cls.state = ca_dedicated;
167                 if (i != (com_argc - 1))
168                 {
169                         svs.maxclients = atoi (com_argv[i+1]);
170                 }
171                 else
172                         svs.maxclients = 8;
173         }
174         else
175                 cls.state = ca_disconnected;
176
177         i = COM_CheckParm ("-listen");
178         if (i)
179         {
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]);
184                 else
185                         svs.maxclients = 8;
186         }
187         if (svs.maxclients < 1)
188                 svs.maxclients = 8;
189         else if (svs.maxclients > MAX_SCOREBOARD)
190                 svs.maxclients = MAX_SCOREBOARD;
191
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");
196
197         if (svs.maxclients > 1)
198                 Cvar_SetValue ("deathmatch", 1.0);
199         else
200                 Cvar_SetValue ("deathmatch", 0.0);
201 }
202
203
204 /*
205 =======================
206 Host_InitLocal
207 ======================
208 */
209 void Host_InitLocal (void)
210 {
211         Host_InitCommands ();
212         
213         Cvar_RegisterVariable (&host_framerate);
214         Cvar_RegisterVariable (&host_speeds);
215         Cvar_RegisterVariable (&slowmo);
216
217         Cvar_RegisterVariable (&sys_ticrate);
218         Cvar_RegisterVariable (&serverprofile);
219
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);
229
230         Cvar_RegisterVariable (&pausable);
231
232         Cvar_RegisterVariable (&temp1);
233
234         Cvar_RegisterVariable (&timestamps);
235         Cvar_RegisterVariable (&timeformat);
236
237         Host_FindMaxClients ();
238         
239         host_time = 1.0;                // so a think at time 0 won't get called
240 }
241
242
243 /*
244 ===============
245 Host_WriteConfiguration
246
247 Writes key bindings and archived cvars to config.cfg
248 ===============
249 */
250 void Host_WriteConfiguration (void)
251 {
252         FILE    *f;
253
254 // dedicated servers initialize the host but don't parse and set the
255 // config.cfg cvars
256         if (host_initialized & !isDedicated)
257         {
258                 f = fopen (va("%s/config.cfg",com_gamedir), "w");
259                 if (!f)
260                 {
261                         Con_Printf ("Couldn't write config.cfg.\n");
262                         return;
263                 }
264                 
265                 Key_WriteBindings (f);
266                 Cvar_WriteVariables (f);
267
268                 fclose (f);
269         }
270 }
271
272
273 /*
274 =================
275 SV_ClientPrintf
276
277 Sends text across to be displayed 
278 FIXME: make this just a stuffed echo?
279 =================
280 */
281 void SV_ClientPrintf (char *fmt, ...)
282 {
283         va_list         argptr;
284         char            string[1024];
285         
286         va_start (argptr,fmt);
287         vsprintf (string, fmt,argptr);
288         va_end (argptr);
289         
290         MSG_WriteByte (&host_client->message, svc_print);
291         MSG_WriteString (&host_client->message, string);
292 }
293
294 /*
295 =================
296 SV_BroadcastPrintf
297
298 Sends text to all active clients
299 =================
300 */
301 void SV_BroadcastPrintf (char *fmt, ...)
302 {
303         va_list         argptr;
304         char            string[1024];
305         int                     i;
306         
307         va_start (argptr,fmt);
308         vsprintf (string, fmt,argptr);
309         va_end (argptr);
310         
311         for (i=0 ; i<svs.maxclients ; i++)
312                 if (svs.clients[i].active && svs.clients[i].spawned)
313                 {
314                         MSG_WriteByte (&svs.clients[i].message, svc_print);
315                         MSG_WriteString (&svs.clients[i].message, string);
316                 }
317 }
318
319 /*
320 =================
321 Host_ClientCommands
322
323 Send text over to the client to be executed
324 =================
325 */
326 void Host_ClientCommands (char *fmt, ...)
327 {
328         va_list         argptr;
329         char            string[1024];
330         
331         va_start (argptr,fmt);
332         vsprintf (string, fmt,argptr);
333         va_end (argptr);
334         
335         MSG_WriteByte (&host_client->message, svc_stufftext);
336         MSG_WriteString (&host_client->message, string);
337 }
338
339 /*
340 =====================
341 SV_DropClient
342
343 Called when the player is getting totally kicked off the host
344 if (crash = true), don't bother sending signofs
345 =====================
346 */
347 void SV_DropClient (qboolean crash)
348 {
349         int             saveSelf;
350         int             i;
351         client_t *client;
352
353         if (!crash)
354         {
355                 // send any final messages (don't check for errors)
356                 if (NET_CanSendMessage (host_client->netconnection))
357                 {
358                         MSG_WriteByte (&host_client->message, svc_disconnect);
359                         NET_SendMessage (host_client->netconnection, &host_client->message);
360                 }
361         
362                 if (host_client->edict && host_client->spawned)
363                 {
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;
370                 }
371
372                 Sys_Printf ("Client %s removed\n",host_client->name);
373         }
374
375 // break the net connection
376         NET_Close (host_client->netconnection);
377         host_client->netconnection = NULL;
378
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--;
384
385 // send notification to all clients
386         for (i=0, client = svs.clients ; i<svs.maxclients ; i++, client++)
387         {
388                 if (!client->active)
389                         continue;
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);
399         }
400 }
401
402 /*
403 ==================
404 Host_ShutdownServer
405
406 This only happens at the end of a game, not between levels
407 ==================
408 */
409 void Host_ShutdownServer(qboolean crash)
410 {
411         int             i;
412         int             count;
413         sizebuf_t       buf;
414         char            message[4];
415         double  start;
416
417         if (!sv.active)
418                 return;
419
420         sv.active = false;
421
422 // stop all client sounds immediately
423         if (cls.state == ca_connected)
424                 CL_Disconnect ();
425
426 // flush any pending messages - like the score!!!
427         start = Sys_FloatTime();
428         do
429         {
430                 count = 0;
431                 for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
432                 {
433                         if (host_client->active && host_client->message.cursize)
434                         {
435                                 if (NET_CanSendMessage (host_client->netconnection))
436                                 {
437                                         NET_SendMessage(host_client->netconnection, &host_client->message);
438                                         SZ_Clear (&host_client->message);
439                                 }
440                                 else
441                                 {
442                                         NET_GetMessage(host_client->netconnection);
443                                         count++;
444                                 }
445                         }
446                 }
447                 if ((Sys_FloatTime() - start) > 3.0)
448                         break;
449         }
450         while (count);
451
452 // make sure all the clients know we're disconnecting
453         buf.data = message;
454         buf.maxsize = 4;
455         buf.cursize = 0;
456         MSG_WriteByte(&buf, svc_disconnect);
457         count = NET_SendToAll(&buf, 5);
458         if (count)
459                 Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %u clients\n", count);
460
461         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
462                 if (host_client->active)
463                         SV_DropClient(crash);
464
465 //
466 // clear structures
467 //
468         memset (&sv, 0, sizeof(sv));
469         memset (svs.clients, 0, svs.maxclientslimit*sizeof(client_t));
470 }
471
472
473 /*
474 ================
475 Host_ClearMemory
476
477 This clears all the memory used by both the client and server, but does
478 not reinitialize anything.
479 ================
480 */
481 void Host_ClearMemory (void)
482 {
483         Con_DPrintf ("Clearing memory\n");
484         Mod_ClearAll ();
485         if (host_hunklevel)
486                 Hunk_FreeToLowMark (host_hunklevel);
487
488         cls.signon = 0;
489         memset (&sv, 0, sizeof(sv));
490         memset (&cl, 0, sizeof(cl));
491 }
492
493
494 //============================================================================
495
496 /*
497 ===================
498 Host_FilterTime
499
500 Returns false if the time is too short to run a frame
501 ===================
502 */
503 qboolean Host_FilterTime (float time)
504 {
505         realtime += time;
506
507 //      if (!cls.timedemo && realtime - oldrealtime < (1.0 / 72.0))
508 //              return false;           // framerate is too high
509
510         host_frametime = (realtime - oldrealtime) * slowmo.value; // LordHavoc: slowmo cvar
511         oldrealtime = realtime;
512
513         if (host_framerate.value > 0)
514                 host_frametime = host_framerate.value;
515         else
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;
521         }
522         
523         return true;
524 }
525
526
527 /*
528 ===================
529 Host_GetConsoleCommands
530
531 Add them exactly as if they had been typed at the console
532 ===================
533 */
534 void Host_GetConsoleCommands (void)
535 {
536         char    *cmd;
537
538         while (1)
539         {
540                 cmd = Sys_ConsoleInput ();
541                 if (!cmd)
542                         break;
543                 Cbuf_AddText (cmd);
544         }
545 }
546
547
548 /*
549 ==================
550 Host_ServerFrame
551
552 ==================
553 */
554 #ifdef FPS_20
555
556 void _Host_ServerFrame (void)
557 {
558 // run the world state  
559         pr_global_struct->frametime = host_frametime;
560
561 // read client messages
562         SV_RunClients ();
563         
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) )
567                 SV_Physics ();
568 }
569
570 void Host_ServerFrame (void)
571 {
572         float   save_host_frametime;
573         float   temp_host_frametime;
574         static float    host_serverframe_timevalue;
575
576 // run the world state  
577         pr_global_struct->frametime = host_frametime;
578
579 // set the time and clear the general datagram
580         SV_ClearDatagram ();
581                 
582 // check for new clients
583         SV_CheckForNewClients ();
584
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
589         // (sliding around)
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)
595         {
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 ();
602         }
603         host_frametime = save_host_frametime;
604
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
608         /*
609 // wait until enough time has built up when the framerate exceeds sys_ticrate
610         if (host_serverframe_timevalue >= sys_ticrate.value)
611         //{
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 ();
616         }
617         */
618 }
619
620 #else
621
622 double frametimetotal = 0, lastservertime = 0;
623 void Host_ServerFrame (void)
624 {
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))
628                 return;
629 // run the world state
630         sv_frametime = pr_global_struct->frametime = frametimetotal;
631         frametimetotal = 0;
632 //      pr_global_struct->frametime = host_frametime;
633
634 // set the time and clear the general datagram
635         SV_ClearDatagram ();
636         
637 // check for new clients
638         SV_CheckForNewClients ();
639
640 // read client messages
641         SV_RunClients ();
642         
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) )
646                 SV_Physics ();
647
648 // send all messages to the clients
649         SV_SendClientMessages ();
650 }
651
652 #endif
653
654
655 /*
656 ==================
657 Host_Frame
658
659 Runs all active servers
660 ==================
661 */
662 void _Host_Frame (float time)
663 {
664         static double           time1 = 0;
665         static double           time2 = 0;
666         static double           time3 = 0;
667         int                     pass1, pass2, pass3;
668
669         if (setjmp (host_abortserver) )
670                 return;                 // something bad happened, or the server disconnected
671
672 // keep the random time dependent
673         rand ();
674         
675 // decide the simulation time
676         if (!Host_FilterTime (time))
677                 return;                 // don't run too fast, or packets will flood out
678                 
679 // get new key events
680         Sys_SendKeyEvents ();
681
682 // allow mice or other external controllers to add commands
683         IN_Commands ();
684
685 // process console commands
686         Cbuf_Execute ();
687
688         NET_Poll();
689
690 // if running the server locally, make intentions now
691         if (sv.active)
692                 CL_SendCmd ();
693         
694 //-------------------
695 //
696 // server operations
697 //
698 //-------------------
699
700 // check for commands typed to the host
701         Host_GetConsoleCommands ();
702         
703         if (sv.active)
704                 Host_ServerFrame ();
705
706 //-------------------
707 //
708 // client operations
709 //
710 //-------------------
711
712 // if running the server remotely, send intentions now after
713 // the incoming messages have been read
714         if (!sv.active)
715                 CL_SendCmd ();
716
717         host_time += host_frametime;
718
719 // fetch results from server
720         if (cls.state == ca_connected)
721         {
722                 CL_ReadFromServer ();
723         }
724
725 // update video
726         if (host_speeds.value)
727                 time1 = Sys_FloatTime ();
728                 
729         SCR_UpdateScreen ();
730
731         if (host_speeds.value)
732                 time2 = Sys_FloatTime ();
733                 
734 // update audio
735         if (cls.signon == SIGNONS)
736         {
737                 S_Update (r_origin, vpn, vright, vup);
738                 CL_DecayLights ();
739         }
740         else
741                 S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin);
742         
743         CDAudio_Update();
744
745         if (host_speeds.value)
746         {
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);
753         }
754         
755         host_framecount++;
756 }
757
758 void Host_Frame (float time)
759 {
760         double  time1, time2;
761         static double   timetotal;
762         static int              timecount;
763         int             i, c, m;
764
765         if (!serverprofile.value)
766         {
767                 _Host_Frame (time);
768                 return;
769         }
770         
771         time1 = Sys_FloatTime ();
772         _Host_Frame (time);
773         time2 = Sys_FloatTime ();       
774         
775         timetotal += time2 - time1;
776         timecount++;
777         
778         if (timecount < 1000)
779                 return;
780
781         m = timetotal*1000/timecount;
782         timecount = 0;
783         timetotal = 0;
784         c = 0;
785         for (i=0 ; i<svs.maxclients ; i++)
786         {
787                 if (svs.clients[i].active)
788                         c++;
789         }
790
791         Con_Printf ("serverprofile: %2i clients %2i msec\n",  c,  m);
792 }
793
794 //============================================================================
795
796
797 extern int vcrFile;
798 #define VCR_SIGNATURE   0x56435231
799 // "VCR1"
800
801 void Host_InitVCR (quakeparms_t *parms)
802 {
803         int             i, len, n;
804         char    *p;
805         
806         if (COM_CheckParm("-playback"))
807         {
808                 if (com_argc != 2)
809                         Sys_Error("No other parameters allowed with -playback\n");
810
811                 Sys_FileOpenRead("quake.vcr", &vcrFile);
812                 if (vcrFile == -1)
813                         Sys_Error("playback file not found\n");
814
815                 Sys_FileRead (vcrFile, &i, sizeof(int));
816                 if (i != VCR_SIGNATURE)
817                         Sys_Error("Invalid signature in vcr file\n");
818
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++)
823                 {
824                         Sys_FileRead (vcrFile, &len, sizeof(int));
825                         p = malloc(len);
826                         Sys_FileRead (vcrFile, p, len);
827                         com_argv[i+1] = p;
828                 }
829                 com_argc++; /* add one for arg[0] */
830                 parms->argc = com_argc;
831                 parms->argv = com_argv;
832         }
833
834         if ( (n = COM_CheckParm("-record")) != 0)
835         {
836                 vcrFile = Sys_FileOpenWrite("quake.vcr");
837
838                 i = VCR_SIGNATURE;
839                 Sys_FileWrite(vcrFile, &i, sizeof(int));
840                 i = com_argc - 1;
841                 Sys_FileWrite(vcrFile, &i, sizeof(int));
842                 for (i = 1; i < com_argc; i++)
843                 {
844                         if (i == n)
845                         {
846                                 len = 10;
847                                 Sys_FileWrite(vcrFile, &len, sizeof(int));
848                                 Sys_FileWrite(vcrFile, "-playback", len);
849                                 continue;
850                         }
851                         len = strlen(com_argv[i]) + 1;
852                         Sys_FileWrite(vcrFile, &len, sizeof(int));
853                         Sys_FileWrite(vcrFile, com_argv[i], len);
854                 }
855         }
856         
857 }
858
859 /*
860 ====================
861 Host_Init
862 ====================
863 */
864 void Host_Init (quakeparms_t *parms)
865 {
866
867         if (standard_quake)
868                 minimum_memory = MINIMUM_MEMORY;
869         else
870                 minimum_memory = MINIMUM_MEMORY_LEVELPAK;
871
872         if (COM_CheckParm ("-minmemory"))
873                 parms->memsize = minimum_memory;
874
875         host_parms = *parms;
876
877         if (parms->memsize < minimum_memory)
878                 Sys_Error ("Only %4.1f megs of memory available, can't execute game", parms->memsize / (float)0x100000);
879
880         com_argc = parms->argc;
881         com_argv = parms->argv;
882
883         Memory_Init (parms->membase, parms->memsize);
884         Cbuf_Init ();
885         Cmd_Init ();    
886         V_Init ();
887         Chase_Init ();
888         Host_InitVCR (parms);
889         COM_Init (parms->basedir);
890         Host_InitLocal ();
891         W_LoadWadFile ("gfx.wad");
892         Key_Init ();
893         Con_Init ();    
894         M_Init ();      
895         PR_Init ();
896         Mod_Init ();
897         NET_Init ();
898         SV_Init ();
899
900         Con_Printf ("Exe: "__TIME__" "__DATE__"\n");
901         Con_Printf ("%4.1f megabyte heap\n",parms->memsize/ (1024*1024.0));
902         
903         R_InitTextures ();              // needed even for dedicated servers
904  
905         if (cls.state != ca_dedicated)
906         {
907                 host_basepal = (byte *)COM_LoadHunkFile ("gfx/palette.lmp", false);
908                 if (!host_basepal)
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");
914
915 #ifndef _WIN32 // on non win32, mouse comes before video for security reasons
916                 IN_Init ();
917 #endif
918                 VID_Init (host_basepal);
919
920                 Draw_Init ();
921                 SCR_Init ();
922                 R_Init ();
923                 S_Init ();
924                 CDAudio_Init ();
925                 Sbar_Init ();
926                 CL_Init ();
927 #ifdef _WIN32 // on non win32, mouse comes before video for security reasons
928                 IN_Init ();
929 #endif
930         }
931
932         Cbuf_InsertText ("exec quake.rc\n");
933
934         Hunk_AllocName (0, "-HOST_HUNKLEVEL-");
935         host_hunklevel = Hunk_LowMark ();
936
937         host_initialized = true;
938         
939         Sys_Printf ("========Quake Initialized=========\n");    
940 }
941
942
943 /*
944 ===============
945 Host_Shutdown
946
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.
949 ===============
950 */
951 void Host_Shutdown(void)
952 {
953         static qboolean isdown = false;
954         
955         if (isdown)
956         {
957                 printf ("recursive shutdown\n");
958                 return;
959         }
960         isdown = true;
961
962 // keep Con_Printf from trying to update the screen
963         scr_disabled_for_loading = true;
964
965         Host_WriteConfiguration (); 
966
967         CDAudio_Shutdown ();
968         NET_Shutdown ();
969         S_Shutdown();
970         IN_Shutdown ();
971
972         if (cls.state != ca_dedicated)
973         {
974                 VID_Shutdown();
975         }
976 }
977