sv_save: Call CL_Disconnect and ToggleMenu via hook
[xonotic/darkplaces.git] / sv_save.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
21 #include "quakedef.h"
22 #include "prvm_cmds.h"
23
24 /*
25 ===============================================================================
26
27 LOAD / SAVE GAME
28
29 ===============================================================================
30 */
31
32 #define SAVEGAME_VERSION        5
33
34 void SV_Savegame_to(prvm_prog_t *prog, const char *name)
35 {
36         qfile_t *f;
37         int             i, k, l, numbuffers, lightstyles = 64;
38         char    comment[SAVEGAME_COMMENT_LENGTH+1];
39         char    line[MAX_INPUTLINE];
40         qbool isserver;
41         char    *s;
42
43         // first we have to figure out if this can be saved in 64 lightstyles
44         // (for Quake compatibility)
45         for (i=64 ; i<MAX_LIGHTSTYLES ; i++)
46                 if (sv.lightstyles[i][0])
47                         lightstyles = i+1;
48
49         isserver = prog == SVVM_prog;
50
51         Con_Printf("Saving game to %s...\n", name);
52         f = FS_OpenRealFile(name, "wb", false);
53         if (!f)
54         {
55                 Con_Print("ERROR: couldn't open.\n");
56                 return;
57         }
58
59         FS_Printf(f, "%i\n", SAVEGAME_VERSION);
60
61         memset(comment, 0, sizeof(comment));
62         if(isserver)
63                 dpsnprintf(comment, sizeof(comment), "%-21.21s kills:%3i/%3i", PRVM_GetString(prog, PRVM_serveredictstring(prog->edicts, message)), (int)PRVM_serverglobalfloat(killed_monsters), (int)PRVM_serverglobalfloat(total_monsters));
64         else
65                 dpsnprintf(comment, sizeof(comment), "(crash dump of %s progs)", prog->name);
66         // convert space to _ to make stdio happy
67         // LadyHavoc: convert control characters to _ as well
68         for (i=0 ; i<SAVEGAME_COMMENT_LENGTH ; i++)
69                 if (ISWHITESPACEORCONTROL(comment[i]))
70                         comment[i] = '_';
71         comment[SAVEGAME_COMMENT_LENGTH] = '\0';
72
73         FS_Printf(f, "%s\n", comment);
74         if(isserver)
75         {
76                 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
77                         FS_Printf(f, "%f\n", svs.clients[0].spawn_parms[i]);
78                 FS_Printf(f, "%d\n", current_skill);
79                 FS_Printf(f, "%s\n", sv.name);
80                 FS_Printf(f, "%f\n",sv.time);
81         }
82         else
83         {
84                 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
85                         FS_Printf(f, "(dummy)\n");
86                 FS_Printf(f, "%d\n", 0);
87                 FS_Printf(f, "%s\n", "(dummy)");
88                 FS_Printf(f, "%f\n", host.realtime);
89         }
90
91         // write the light styles
92         for (i=0 ; i<lightstyles ; i++)
93         {
94                 if (isserver && sv.lightstyles[i][0])
95                         FS_Printf(f, "%s\n", sv.lightstyles[i]);
96                 else
97                         FS_Print(f,"m\n");
98         }
99
100         PRVM_ED_WriteGlobals (prog, f);
101         for (i=0 ; i<prog->num_edicts ; i++)
102         {
103                 FS_Printf(f,"// edict %d\n", i);
104                 //Con_Printf("edict %d...\n", i);
105                 PRVM_ED_Write (prog, f, PRVM_EDICT_NUM(i));
106         }
107
108 #if 1
109         FS_Printf(f,"/*\n");
110         FS_Printf(f,"// DarkPlaces extended savegame\n");
111         // darkplaces extension - extra lightstyles, support for color lightstyles
112         for (i=0 ; i<MAX_LIGHTSTYLES ; i++)
113                 if (isserver && sv.lightstyles[i][0])
114                         FS_Printf(f, "sv.lightstyles %i %s\n", i, sv.lightstyles[i]);
115
116         // darkplaces extension - model precaches
117         for (i=1 ; i<MAX_MODELS ; i++)
118                 if (sv.model_precache[i][0])
119                         FS_Printf(f,"sv.model_precache %i %s\n", i, sv.model_precache[i]);
120
121         // darkplaces extension - sound precaches
122         for (i=1 ; i<MAX_SOUNDS ; i++)
123                 if (sv.sound_precache[i][0])
124                         FS_Printf(f,"sv.sound_precache %i %s\n", i, sv.sound_precache[i]);
125
126         // darkplaces extension - save buffers
127         numbuffers = (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray);
128         for (i = 0; i < numbuffers; i++)
129         {
130                 prvm_stringbuffer_t *stringbuffer = (prvm_stringbuffer_t*) Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);
131                 if(stringbuffer && (stringbuffer->flags & STRINGBUFFER_SAVED))
132                 {
133                         FS_Printf(f,"sv.buffer %i %i \"string\"\n", i, stringbuffer->flags & STRINGBUFFER_QCFLAGS);
134                         for(k = 0; k < stringbuffer->num_strings; k++)
135                         {
136                                 if (!stringbuffer->strings[k])
137                                         continue;
138                                 // Parse the string a bit to turn special characters
139                                 // (like newline, specifically) into escape codes
140                                 s = stringbuffer->strings[k];
141                                 for (l = 0;l < (int)sizeof(line) - 2 && *s;)
142                                 {       
143                                         if (*s == '\n')
144                                         {
145                                                 line[l++] = '\\';
146                                                 line[l++] = 'n';
147                                         }
148                                         else if (*s == '\r')
149                                         {
150                                                 line[l++] = '\\';
151                                                 line[l++] = 'r';
152                                         }
153                                         else if (*s == '\\')
154                                         {
155                                                 line[l++] = '\\';
156                                                 line[l++] = '\\';
157                                         }
158                                         else if (*s == '"')
159                                         {
160                                                 line[l++] = '\\';
161                                                 line[l++] = '"';
162                                         }
163                                         else
164                                                 line[l++] = *s;
165                                         s++;
166                                 }
167                                 line[l] = '\0';
168                                 FS_Printf(f,"sv.bufstr %i %i \"%s\"\n", i, k, line);
169                         }
170                 }
171         }
172         FS_Printf(f,"*/\n");
173 #endif
174
175         FS_Close (f);
176         Con_Print("done.\n");
177 }
178
179 static qbool SV_CanSave(void)
180 {
181         prvm_prog_t *prog = SVVM_prog;
182         if(SV_IsLocalServer() == 1)
183         {
184                 // singleplayer checks
185                 // FIXME: This only checks if the first player is dead?
186                 if ((svs.clients[0].active && PRVM_serveredictfloat(svs.clients[0].edict, deadflag)))
187                 {
188                         Con_Print("Can't savegame with a dead player\n");
189                         return false;
190                 }
191
192                 if(host.hook.CL_Intermission && host.hook.CL_Intermission())
193                 {
194                         Con_Print("Can't save in intermission.\n");
195                         return false;
196                 }
197         }
198         else
199                 Con_Print(CON_WARN "Warning: saving a multiplayer game may have strange results when restored (to properly resume, all players must join in the same player slots and then the game can be reloaded).\n");
200         return true;
201 }
202
203 /*
204 ===============
205 SV_Savegame_f
206 ===============
207 */
208 void SV_Savegame_f(cmd_state_t *cmd)
209 {
210         prvm_prog_t *prog = SVVM_prog;
211         char    name[MAX_QPATH];
212
213         if (!sv.active)
214         {
215                 Con_Print("Can't save - no server running.\n");
216                 return;
217         }
218
219         if(!SV_CanSave())
220                 return;
221
222         if (Cmd_Argc(cmd) != 2)
223         {
224                 Con_Print("save <savename> : save a game\n");
225                 return;
226         }
227
228         if (strstr(Cmd_Argv(cmd, 1), ".."))
229         {
230                 Con_Print("Relative pathnames are not allowed.\n");
231                 return;
232         }
233
234         strlcpy (name, Cmd_Argv(cmd, 1), sizeof (name));
235         FS_DefaultExtension (name, ".sav", sizeof (name));
236
237         SV_Savegame_to(prog, name);
238 }
239
240 /*
241 ===============
242 SV_Loadgame_f
243 ===============
244 */
245 void SV_Loadgame_f(cmd_state_t *cmd)
246 {
247         prvm_prog_t *prog = SVVM_prog;
248         char filename[MAX_QPATH];
249         char mapname[MAX_QPATH];
250         float time;
251         const char *start;
252         const char *end;
253         const char *t;
254         char *text;
255         prvm_edict_t *ent;
256         int i, k, numbuffers;
257         int entnum;
258         int version;
259         float spawn_parms[NUM_SPAWN_PARMS];
260         prvm_stringbuffer_t *stringbuffer;
261
262         if (Cmd_Argc(cmd) != 2)
263         {
264                 Con_Print("load <savename> : load a game\n");
265                 return;
266         }
267
268         strlcpy (filename, Cmd_Argv(cmd, 1), sizeof(filename));
269         FS_DefaultExtension (filename, ".sav", sizeof (filename));
270
271         Con_Printf("Loading game from %s...\n", filename);
272
273         if(host.hook.Disconnect)
274                 host.hook.Disconnect(false, NULL);
275
276         if(host.hook.ToggleMenu)
277                 host.hook.ToggleMenu();
278
279         cls.demonum = -1;               // stop demo loop in case this fails
280
281         t = text = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
282         if (!text)
283         {
284                 Con_Print("ERROR: couldn't open.\n");
285                 return;
286         }
287
288         if(developer_entityparsing.integer)
289                 Con_Printf("SV_Loadgame_f: loading version\n");
290
291         // version
292         COM_ParseToken_Simple(&t, false, false, true);
293         version = atoi(com_token);
294         if (version != SAVEGAME_VERSION)
295         {
296                 Mem_Free(text);
297                 Con_Printf("Savegame is version %i, not %i\n", version, SAVEGAME_VERSION);
298                 return;
299         }
300
301         if(developer_entityparsing.integer)
302                 Con_Printf("SV_Loadgame_f: loading description\n");
303
304         // description
305         COM_ParseToken_Simple(&t, false, false, true);
306
307         for (i = 0;i < NUM_SPAWN_PARMS;i++)
308         {
309                 COM_ParseToken_Simple(&t, false, false, true);
310                 spawn_parms[i] = atof(com_token);
311         }
312         // skill
313         COM_ParseToken_Simple(&t, false, false, true);
314 // this silliness is so we can load 1.06 save files, which have float skill values
315         current_skill = (int)(atof(com_token) + 0.5);
316         Cvar_SetValue (&cvars_all, "skill", (float)current_skill);
317
318         if(developer_entityparsing.integer)
319                 Con_Printf("SV_Loadgame_f: loading mapname\n");
320
321         // mapname
322         COM_ParseToken_Simple(&t, false, false, true);
323         strlcpy (mapname, com_token, sizeof(mapname));
324
325         if(developer_entityparsing.integer)
326                 Con_Printf("SV_Loadgame_f: loading time\n");
327
328         // time
329         COM_ParseToken_Simple(&t, false, false, true);
330         time = atof(com_token);
331
332         if(developer_entityparsing.integer)
333                 Con_Printf("SV_Loadgame_f: spawning server\n");
334
335         SV_SpawnServer (mapname);
336         if (!sv.active)
337         {
338                 Mem_Free(text);
339                 Con_Print("Couldn't load map\n");
340                 return;
341         }
342         sv.paused = true;               // pause until all clients connect
343         sv.loadgame = true;
344
345         if(developer_entityparsing.integer)
346                 Con_Printf("SV_Loadgame_f: loading light styles\n");
347
348 // load the light styles
349
350         // -1 is the globals
351         entnum = -1;
352
353         for (i = 0;i < MAX_LIGHTSTYLES;i++)
354         {
355                 // light style
356                 start = t;
357                 COM_ParseToken_Simple(&t, false, false, true);
358                 // if this is a 64 lightstyle savegame produced by Quake, stop now
359                 // we have to check this because darkplaces may save more than 64
360                 if (com_token[0] == '{')
361                 {
362                         t = start;
363                         break;
364                 }
365                 strlcpy(sv.lightstyles[i], com_token, sizeof(sv.lightstyles[i]));
366         }
367
368         if(developer_entityparsing.integer)
369                 Con_Printf("SV_Loadgame_f: skipping until globals\n");
370
371         // now skip everything before the first opening brace
372         // (this is for forward compatibility, so that older versions (at
373         // least ones with this fix) can load savegames with extra data before the
374         // first brace, as might be produced by a later engine version)
375         for (;;)
376         {
377                 start = t;
378                 if (!COM_ParseToken_Simple(&t, false, false, true))
379                         break;
380                 if (com_token[0] == '{')
381                 {
382                         t = start;
383                         break;
384                 }
385         }
386
387         // unlink all entities
388         World_UnlinkAll(&sv.world);
389
390 // load the edicts out of the savegame file
391         end = t;
392         for (;;)
393         {
394                 start = t;
395                 while (COM_ParseToken_Simple(&t, false, false, true))
396                         if (!strcmp(com_token, "}"))
397                                 break;
398                 if (!COM_ParseToken_Simple(&start, false, false, true))
399                 {
400                         // end of file
401                         break;
402                 }
403                 if (strcmp(com_token,"{"))
404                 {
405                         Mem_Free(text);
406                         Host_Error ("First token isn't a brace");
407                 }
408
409                 if (entnum == -1)
410                 {
411                         if(developer_entityparsing.integer)
412                                 Con_Printf("SV_Loadgame_f: loading globals\n");
413
414                         // parse the global vars
415                         PRVM_ED_ParseGlobals (prog, start);
416
417                         // restore the autocvar globals
418                         Cvar_UpdateAllAutoCvars(prog->console_cmd->cvars);
419                 }
420                 else
421                 {
422                         // parse an edict
423                         if (entnum >= MAX_EDICTS)
424                         {
425                                 Mem_Free(text);
426                                 Host_Error("Host_PerformLoadGame: too many edicts in save file (reached MAX_EDICTS %i)", MAX_EDICTS);
427                         }
428                         while (entnum >= prog->max_edicts)
429                                 PRVM_MEM_IncreaseEdicts(prog);
430                         ent = PRVM_EDICT_NUM(entnum);
431                         memset(ent->fields.fp, 0, prog->entityfields * sizeof(prvm_vec_t));
432                         ent->free = false;
433
434                         if(developer_entityparsing.integer)
435                                 Con_Printf("SV_Loadgame_f: loading edict %d\n", entnum);
436
437                         PRVM_ED_ParseEdict (prog, start, ent);
438
439                         // link it into the bsp tree
440                         if (!ent->free && !VectorCompare(PRVM_serveredictvector(ent, absmin), PRVM_serveredictvector(ent, absmax)))
441                                 SV_LinkEdict(ent);
442                 }
443
444                 end = t;
445                 entnum++;
446         }
447
448         prog->num_edicts = entnum;
449         sv.time = time;
450
451         for (i = 0;i < NUM_SPAWN_PARMS;i++)
452                 svs.clients[0].spawn_parms[i] = spawn_parms[i];
453
454         if(developer_entityparsing.integer)
455                 Con_Printf("SV_Loadgame_f: skipping until extended data\n");
456
457         // read extended data if present
458         // the extended data is stored inside a /* */ comment block, which the
459         // parser intentionally skips, so we have to check for it manually here
460         if(end)
461         {
462                 while (*end == '\r' || *end == '\n')
463                         end++;
464                 if (end[0] == '/' && end[1] == '*' && (end[2] == '\r' || end[2] == '\n'))
465                 {
466                         if(developer_entityparsing.integer)
467                                 Con_Printf("SV_Loadgame_f: loading extended data\n");
468
469                         Con_Printf("Loading extended DarkPlaces savegame\n");
470                         t = end + 2;
471                         memset(sv.lightstyles[0], 0, sizeof(sv.lightstyles));
472                         memset(sv.model_precache[0], 0, sizeof(sv.model_precache));
473                         memset(sv.sound_precache[0], 0, sizeof(sv.sound_precache));
474                         BufStr_Flush(prog);
475
476                         while (COM_ParseToken_Simple(&t, false, false, true))
477                         {
478                                 if (!strcmp(com_token, "sv.lightstyles"))
479                                 {
480                                         COM_ParseToken_Simple(&t, false, false, true);
481                                         i = atoi(com_token);
482                                         COM_ParseToken_Simple(&t, false, false, true);
483                                         if (i >= 0 && i < MAX_LIGHTSTYLES)
484                                                 strlcpy(sv.lightstyles[i], com_token, sizeof(sv.lightstyles[i]));
485                                         else
486                                                 Con_Printf("unsupported lightstyle %i \"%s\"\n", i, com_token);
487                                 }
488                                 else if (!strcmp(com_token, "sv.model_precache"))
489                                 {
490                                         COM_ParseToken_Simple(&t, false, false, true);
491                                         i = atoi(com_token);
492                                         COM_ParseToken_Simple(&t, false, false, true);
493                                         if (i >= 0 && i < MAX_MODELS)
494                                         {
495                                                 strlcpy(sv.model_precache[i], com_token, sizeof(sv.model_precache[i]));
496                                                 sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, sv.model_precache[i][0] == '*' ? sv.worldname : NULL);
497                                         }
498                                         else
499                                                 Con_Printf("unsupported model %i \"%s\"\n", i, com_token);
500                                 }
501                                 else if (!strcmp(com_token, "sv.sound_precache"))
502                                 {
503                                         COM_ParseToken_Simple(&t, false, false, true);
504                                         i = atoi(com_token);
505                                         COM_ParseToken_Simple(&t, false, false, true);
506                                         if (i >= 0 && i < MAX_SOUNDS)
507                                                 strlcpy(sv.sound_precache[i], com_token, sizeof(sv.sound_precache[i]));
508                                         else
509                                                 Con_Printf("unsupported sound %i \"%s\"\n", i, com_token);
510                                 }
511                                 else if (!strcmp(com_token, "sv.buffer"))
512                                 {
513                                         if (COM_ParseToken_Simple(&t, false, false, true))
514                                         {
515                                                 i = atoi(com_token);
516                                                 if (i >= 0)
517                                                 {
518                                                         k = STRINGBUFFER_SAVED;
519                                                         if (COM_ParseToken_Simple(&t, false, false, true))
520                                                                 k |= atoi(com_token);
521                                                         if (!BufStr_FindCreateReplace(prog, i, k, "string"))
522                                                                 Con_Printf(CON_ERROR "failed to create stringbuffer %i\n", i);
523                                                 }
524                                                 else
525                                                         Con_Printf("unsupported stringbuffer index %i \"%s\"\n", i, com_token);
526                                         }
527                                         else
528                                                 Con_Printf("unexpected end of line when parsing sv.buffer (expected buffer index)\n");
529                                 }
530                                 else if (!strcmp(com_token, "sv.bufstr"))
531                                 {
532                                         if (!COM_ParseToken_Simple(&t, false, false, true))
533                                                 Con_Printf("unexpected end of line when parsing sv.bufstr\n");
534                                         else
535                                         {
536                                                 i = atoi(com_token);
537                                                 stringbuffer = BufStr_FindCreateReplace(prog, i, STRINGBUFFER_SAVED, "string");
538                                                 if (stringbuffer)
539                                                 {
540                                                         if (COM_ParseToken_Simple(&t, false, false, true))
541                                                         {
542                                                                 k = atoi(com_token);
543                                                                 if (COM_ParseToken_Simple(&t, false, false, true))
544                                                                         BufStr_Set(prog, stringbuffer, k, com_token);
545                                                                 else
546                                                                         Con_Printf("unexpected end of line when parsing sv.bufstr (expected string)\n");
547                                                         }
548                                                         else
549                                                                 Con_Printf("unexpected end of line when parsing sv.bufstr (expected strindex)\n");
550                                                 }
551                                                 else
552                                                         Con_Printf(CON_ERROR "failed to create stringbuffer %i \"%s\"\n", i, com_token);
553                                         }
554                                 }       
555                                 // skip any trailing text or unrecognized commands
556                                 while (COM_ParseToken_Simple(&t, true, false, true) && strcmp(com_token, "\n"))
557                                         ;
558                         }
559                 }
560         }
561         Mem_Free(text);
562
563         // remove all temporary flagged string buffers (ones created with BufStr_FindCreateReplace)
564         numbuffers = (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray);
565         for (i = 0; i < numbuffers; i++)
566         {
567                 if ( (stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i)) )
568                         if (stringbuffer->flags & STRINGBUFFER_TEMP)
569                                 BufStr_Del(prog, stringbuffer);
570         }
571
572         if(developer_entityparsing.integer)
573                 Con_Printf("SV_Loadgame_f: finished\n");
574
575         // make sure we're connected to loopback
576         if(sv.active && host.hook.ConnectLocal)
577                 host.hook.ConnectLocal();
578 }