Refactoring step - change some visibilities.
[open-adventure.git] / saveresume.c
1 /*
2  * Saving and resuming.
3  *
4  * (ESR) This replaces  a bunch of particularly nasty FORTRAN-derived code;
5  * see the history.adoc file in the source distribution for discussion.
6  *
7  * SPDX-FileCopyrightText: 1977, 2005 by Will Crowther and Don Woods
8  * SPDX-FileCopyrightText: 2017 by Eric S. Raymond
9  * SPDX-License-Identifier: BSD-2-Clause
10  */
11
12 #include <stdlib.h>
13 #include <string.h>
14 #include <ctype.h>
15 #include <time.h>
16 #include <inttypes.h>
17
18 #include "advent.h"
19 #include "dungeon.h"
20
21 struct save_t save;
22
23 #define IGNORE(r) do{if (r){}}while(0)
24
25 int savefile(FILE *fp, int32_t version)
26 /* Save game to file. No input or output from user. */
27 {
28     save.savetime = time(NULL);
29     save.mode = -1;
30     save.version = (version == 0) ? SAVE_VERSION : version;
31
32     save.game = game;
33     IGNORE(fwrite(&save, sizeof(struct save_t), 1, fp));
34     return (0);
35 }
36
37 /* Suspend and resume */
38
39 static char *strip(char *name)
40 {
41     // Trim leading whitespace
42     while(isspace((unsigned char)*name))
43         name++; // LCOV_EXCL_LINE
44     if(*name != '\0') {
45         // Trim trailing whitespace;
46         // might be left there by autocomplete
47         char *end = name + strlen(name) - 1;
48         while(end > name && isspace((unsigned char)*end))
49             end--;
50         // Write new null terminator character
51         end[1] = '\0';
52     }
53
54     return name;
55 }
56
57 int suspend(void)
58 {
59     /*  Suspend.  Offer to save things in a file, but charging
60      *  some points (so can't win by using saved games to retry
61      *  battles or to start over after learning zzword).
62      *  If ADVENT_NOSAVE is defined, gripe instead. */
63
64 #if defined ADVENT_NOSAVE || defined ADVENT_AUTOSAVE
65     rspeak(SAVERESUME_DISABLED);
66     return GO_TOP;
67 #endif
68     FILE *fp = NULL;
69
70     rspeak(SUSPEND_WARNING);
71     if (!yes_or_no(arbitrary_messages[THIS_ACCEPTABLE], arbitrary_messages[OK_MAN], arbitrary_messages[OK_MAN]))
72         return GO_CLEAROBJ;
73     game.saved = game.saved + 5;
74
75     while (fp == NULL) {
76         char* name = myreadline("\nFile name: ");
77         if (name == NULL)
78             return GO_TOP;
79         name = strip(name);
80         if (strlen(name) == 0)
81             return GO_TOP;      // LCOV_EXCL_LINE
82         fp = fopen(strip(name), WRITE_MODE);
83         if (fp == NULL)
84             printf("Can't open file %s, try again.\n", name);
85         free(name);
86     }
87
88     savefile(fp, SAVE_VERSION);
89     fclose(fp);
90     rspeak(RESUME_HELP);
91     exit(EXIT_SUCCESS);
92 }
93
94 int resume(void)
95 {
96     /*  Resume.  Read a suspended game back from a file.
97      *  If ADVENT_NOSAVE is defined, gripe instead. */
98
99 #if defined ADVENT_NOSAVE || defined ADVENT_AUTOSAVE
100     rspeak(SAVERESUME_DISABLED);
101     return GO_TOP;
102 #endif
103     FILE *fp = NULL;
104
105     if (game.loc != LOC_START || game.abbrev[LOC_START] != 1) {
106         rspeak(RESUME_ABANDON);
107         if (!yes_or_no(arbitrary_messages[THIS_ACCEPTABLE], arbitrary_messages[OK_MAN], arbitrary_messages[OK_MAN]))
108             return GO_CLEAROBJ;
109     }
110
111     while (fp == NULL) {
112         char* name = myreadline("\nFile name: ");
113         if (name == NULL)
114             return GO_TOP;
115         name = strip(name);
116         if (strlen(name) == 0)
117             return GO_TOP;      // LCOV_EXCL_LINE
118         fp = fopen(name, READ_MODE);
119         if (fp == NULL)
120             printf("Can't open file %s, try again.\n", name);
121         free(name);
122     }
123
124     return restore(fp);
125 }
126
127 int restore(FILE* fp)
128 {
129     /*  Read and restore game state from file, assuming
130      *  sane initial state.
131      *  If ADVENT_NOSAVE is defined, gripe instead. */
132 #ifdef ADVENT_NOSAVE
133     rspeak(SAVERESUME_DISABLED)
134     return GO_TOP;
135 #endif
136
137     IGNORE(fread(&save, sizeof(struct save_t), 1, fp));
138     fclose(fp);
139     if (save.version != SAVE_VERSION) {
140         rspeak(VERSION_SKEW, save.version / 10, MOD(save.version, 10), SAVE_VERSION / 10, MOD(SAVE_VERSION, 10));
141     } else if (!is_valid(save.game)) {
142         rspeak(SAVE_TAMPERING);
143         exit(EXIT_SUCCESS);
144     } else {
145         game = save.game;
146     }
147     return GO_TOP;
148 }
149
150 bool is_valid(struct game_t valgame)
151 {
152     /*  Save files can be roughly grouped into three groups:
153      *  With valid, reachable state, with valid, but unreachable
154      *  state and with invalid state. We check that state is
155      *  valid: no states are outside minimal or maximal value
156      */
157
158     /* Prevent division by zero */
159     if (valgame.abbnum == 0) {
160         return false;   // LCOV_EXCL_LINE
161     }
162
163     /* Check for RNG overflow. Truncate */
164     if (valgame.lcg_x >= LCG_M) {
165         valgame.lcg_x %= LCG_M; // LCOV_EXCL_LINE
166     }
167
168     /* Check for RNG underflow. Transpose */
169     if (valgame.lcg_x < LCG_M) {
170         valgame.lcg_x = LCG_M + (valgame.lcg_x % LCG_M);
171     }
172
173     /*  Bounds check for locations */
174     if ( valgame.chloc  < -1 || valgame.chloc  > NLOCATIONS ||
175          valgame.chloc2 < -1 || valgame.chloc2 > NLOCATIONS ||
176          valgame.loc    <  0 || valgame.loc    > NLOCATIONS ||
177          valgame.newloc <  0 || valgame.newloc > NLOCATIONS ||
178          valgame.oldloc <  0 || valgame.oldloc > NLOCATIONS ||
179          valgame.oldlc2 <  0 || valgame.oldlc2 > NLOCATIONS) {
180         return false;   // LCOV_EXCL_LINE
181     }
182     /*  Bounds check for location arrays */
183     for (int i = 0; i <= NDWARVES; i++) {
184         if (valgame.dloc[i]  < -1 || valgame.dloc[i]  > NLOCATIONS  ||
185             valgame.odloc[i] < -1 || valgame.odloc[i] > NLOCATIONS) {
186             return false;       // LCOV_EXCL_LINE
187         }
188     }
189
190     for (int i = 0; i <= NOBJECTS; i++) {
191         if (valgame.place[i] < -1 || valgame.place[i] > NLOCATIONS  ||
192             valgame.fixed[i] < -1 || valgame.fixed[i] > NLOCATIONS) {
193             return false;       // LCOV_EXCL_LINE
194         }
195     }
196
197     /*  Bounds check for dwarves */
198     if (valgame.dtotal < 0 || valgame.dtotal > NDWARVES ||
199         valgame.dkill < 0  || valgame.dkill  > NDWARVES) {
200         return false;   // LCOV_EXCL_LINE
201     }
202
203     /*  Validate that we didn't die too many times in save */
204     if (valgame.numdie >= NDEATHS) {
205         return false;   // LCOV_EXCL_LINE
206     }
207
208     /* Recalculate tally, throw the towel if in disagreement */
209     int temp_tally = 0;
210     for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
211         if (objects[treasure].is_treasure) {
212             if (valgame.prop[treasure] == STATE_NOTFOUND) {
213                 ++temp_tally;
214             }
215         }
216     }
217     if (temp_tally != valgame.tally) {
218         return false;   // LCOV_EXCL_LINE
219     }
220
221     /* Check that properties of objects aren't beyond expected */
222     for (obj_t obj = 0; obj <= NOBJECTS; obj++) {
223         /* Magic number -2 allows a STASHED version of state 1 */
224         if (valgame.prop[obj] < -2 || valgame.prop[obj] > 1) {
225             switch (obj) {
226             case RUG:
227             case DRAGON:
228             case BIRD:
229             case BOTTLE:
230             case PLANT:
231             case PLANT2:
232             case TROLL:
233             case URN:
234             case EGGS:
235             case VASE:
236             case CHAIN:
237                 if (valgame.prop[obj] == 2) // There are multiple different states, but it's convenient to clump them together
238                     continue;   // LCOV_EXCL_LINE
239             /* FALLTHRU */
240             case BEAR:
241                 if (valgame.prop[BEAR] == CONTENTED_BEAR || valgame.prop[BEAR] == BEAR_DEAD)
242                     continue;
243             /* FALLTHRU */
244             default:
245                 return false;   // LCOV_EXCL_LINE
246             }
247         }
248     }
249
250     /* Check that values in linked lists for objects in locations are inside bounds */
251     for (loc_t loc = LOC_NOWHERE; loc <= NLOCATIONS; loc++) {
252         if (valgame.atloc[loc] < NO_OBJECT || valgame.atloc[loc] > NOBJECTS * 2) {
253             return false;       // LCOV_EXCL_LINE
254         }
255     }
256     for (obj_t obj = 0; obj <= NOBJECTS * 2; obj++ ) {
257         if (valgame.link[obj] < NO_OBJECT || valgame.link[obj] > NOBJECTS * 2) {
258             return false;       // LCOV_EXCL_LINE
259         }
260     }
261
262     return true;
263 }
264
265 /* end */