Source:NetHack 3.6.2/src/restore.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to restore.c from the source code of NetHack 3.6.2. To link to a particular line, write [[Source:NetHack 3.6.2/src/restore.c#line12]], for example.

The NetHack General Public License applies to screenshots, source code and other content from NetHack.

This content was modified from the original NetHack source code distribution (by splitting up NetHack content between wiki pages, and possibly further editing). See the page history for a list of who changed it, and on what dates.

1. /* NetHack 3.6	restore.c	$NHDT-Date: 1555201698 2019/04/14 00:28:18 $  $NHDT-Branch: NetHack-3.6.2-beta01 $:$NHDT-Revision: 1.129 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Michael Allison, 2009. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. #include "lev.h"
8. #include "tcap.h" /* for TERMLIB and ASCIIGRAPH */
9. 
10. #if defined(MICRO)
11. extern int dotcnt; /* shared with save */
12. extern int dotrow; /* shared with save */
13. #endif
14. 
15. #ifdef USE_TILES
16. extern void FDECL(substitute_tiles, (d_level *)); /* from tile.c */
17. #endif
18. 
19. #ifdef ZEROCOMP
20. STATIC_DCL void NDECL(zerocomp_minit);
21. STATIC_DCL void FDECL(zerocomp_mread, (int, genericptr_t, unsigned int));
22. STATIC_DCL int NDECL(zerocomp_mgetc);
23. #endif
24. 
25. STATIC_DCL void NDECL(def_minit);
26. STATIC_DCL void FDECL(def_mread, (int, genericptr_t, unsigned int));
27. 
28. STATIC_DCL void NDECL(find_lev_obj);
29. STATIC_DCL void FDECL(restlevchn, (int));
30. STATIC_DCL void FDECL(restdamage, (int, BOOLEAN_P));
31. STATIC_DCL void FDECL(restobj, (int, struct obj *));
32. STATIC_DCL struct obj *FDECL(restobjchn, (int, BOOLEAN_P, BOOLEAN_P));
33. STATIC_OVL void FDECL(restmon, (int, struct monst *));
34. STATIC_DCL struct monst *FDECL(restmonchn, (int, BOOLEAN_P));
35. STATIC_DCL struct fruit *FDECL(loadfruitchn, (int));
36. STATIC_DCL void FDECL(freefruitchn, (struct fruit *));
37. STATIC_DCL void FDECL(ghostfruit, (struct obj *));
38. STATIC_DCL boolean FDECL(restgamestate, (int, unsigned int *, unsigned int *));
39. STATIC_DCL void FDECL(restlevelstate, (unsigned int, unsigned int));
40. STATIC_DCL int FDECL(restlevelfile, (int, XCHAR_P));
41. STATIC_OVL void FDECL(restore_msghistory, (int));
42. STATIC_DCL void FDECL(reset_oattached_mids, (BOOLEAN_P));
43. STATIC_DCL void FDECL(rest_levl, (int, BOOLEAN_P));
44. 
45. static struct restore_procs {
46.     const char *name;
47.     int mread_flags;
48.     void NDECL((*restore_minit));
49.     void FDECL((*restore_mread), (int, genericptr_t, unsigned int));
50.     void FDECL((*restore_bclose), (int));
51. } restoreprocs = {
52. #if !defined(ZEROCOMP) || (defined(COMPRESS) || defined(ZLIB_COMP))
53.     "externalcomp", 0, def_minit, def_mread, def_bclose,
54. #else
55.     "zerocomp", 0, zerocomp_minit, zerocomp_mread, zerocomp_bclose,
56. #endif
57. };
58. 
59. /*
60.  * Save a mapping of IDs from ghost levels to the current level.  This
61.  * map is used by the timer routines when restoring ghost levels.
62.  */
63. #define N_PER_BUCKET 64
64. struct bucket {
65.     struct bucket *next;
66.     struct {
67.         unsigned gid; /* ghost ID */
68.         unsigned nid; /* new ID */
69.     } map[N_PER_BUCKET];
70. };
71. 
72. STATIC_DCL void NDECL(clear_id_mapping);
73. STATIC_DCL void FDECL(add_id_mapping, (unsigned, unsigned));
74. 
75. static int n_ids_mapped = 0;
76. static struct bucket *id_map = 0;
77. 
78. #ifdef AMII_GRAPHICS
79. void FDECL(amii_setpens, (int)); /* use colors from save file */
80. extern int amii_numcolors;
81. #endif
82. 
83. #include "display.h"
84. 
85. boolean restoring = FALSE;
86. static NEARDATA struct fruit *oldfruit;
87. static NEARDATA long omoves;
88. 
89. #define Is_IceBox(o) ((o)->otyp == ICE_BOX ? TRUE : FALSE)
90. 
91. /* Recalculate level.objects[x][y], since this info was not saved. */
92. STATIC_OVL void
93. find_lev_obj()
94. {
95.     register struct obj *fobjtmp = (struct obj *) 0;
96.     register struct obj *otmp;
97.     int x, y;
98. 
99.     for (x = 0; x < COLNO; x++)
100.         for (y = 0; y < ROWNO; y++)
101.             level.objects[x][y] = (struct obj *) 0;
102. 
103.     /*
104.      * Reverse the entire fobj chain, which is necessary so that we can
105.      * place the objects in the proper order.  Make all obj in chain
106.      * OBJ_FREE so place_object will work correctly.
107.      */
108.     while ((otmp = fobj) != 0) {
109.         fobj = otmp->nobj;
110.         otmp->nobj = fobjtmp;
111.         otmp->where = OBJ_FREE;
112.         fobjtmp = otmp;
113.     }
114.     /* fobj should now be empty */
115. 
116.     /* Set level.objects (as well as reversing the chain back again) */
117.     while ((otmp = fobjtmp) != 0) {
118.         fobjtmp = otmp->nobj;
119.         place_object(otmp, otmp->ox, otmp->oy);
120.     }
121. }
122. 
123. /* Things that were marked "in_use" when the game was saved (ex. via the
124.  * infamous "HUP" cheat) get used up here.
125.  */
126. void
127. inven_inuse(quietly)
128. boolean quietly;
129. {
130.     register struct obj *otmp, *otmp2;
131. 
132.     for (otmp = invent; otmp; otmp = otmp2) {
133.         otmp2 = otmp->nobj;
134.         if (otmp->in_use) {
135.             if (!quietly)
136.                 pline("Finishing off %s...", xname(otmp));
137.             useup(otmp);
138.         }
139.     }
140. }
141. 
142. STATIC_OVL void
143. restlevchn(fd)
144. register int fd;
145. {
146.     int cnt;
147.     s_level *tmplev, *x;
148. 
149.     sp_levchn = (s_level *) 0;
150.     mread(fd, (genericptr_t) &cnt, sizeof(int));
151.     for (; cnt > 0; cnt--) {
152.         tmplev = (s_level *) alloc(sizeof(s_level));
153.         mread(fd, (genericptr_t) tmplev, sizeof(s_level));
154.         if (!sp_levchn)
155.             sp_levchn = tmplev;
156.         else {
157.             for (x = sp_levchn; x->next; x = x->next)
158.                 ;
159.             x->next = tmplev;
160.         }
161.         tmplev->next = (s_level *) 0;
162.     }
163. }
164. 
165. STATIC_OVL void
166. restdamage(fd, ghostly)
167. int fd;
168. boolean ghostly;
169. {
170.     int counter;
171.     struct damage *tmp_dam;
172. 
173.     mread(fd, (genericptr_t) &counter, sizeof(counter));
174.     if (!counter)
175.         return;
176.     tmp_dam = (struct damage *) alloc(sizeof(struct damage));
177.     while (--counter >= 0) {
178.         char damaged_shops[5], *shp = (char *) 0;
179. 
180.         mread(fd, (genericptr_t) tmp_dam, sizeof(*tmp_dam));
181.         if (ghostly)
182.             tmp_dam->when += (monstermoves - omoves);
183.         Strcpy(damaged_shops,
184.                in_rooms(tmp_dam->place.x, tmp_dam->place.y, SHOPBASE));
185.         if (u.uz.dlevel) {
186.             /* when restoring, there are two passes over the current
187.              * level.  the first time, u.uz isn't set, so neither is
188.              * shop_keeper().  just wait and process the damage on
189.              * the second pass.
190.              */
191.             for (shp = damaged_shops; *shp; shp++) {
192.                 struct monst *shkp = shop_keeper(*shp);
193. 
194.                 if (shkp && inhishop(shkp)
195.                     && repair_damage(shkp, tmp_dam, (int *) 0, TRUE))
196.                     break;
197.             }
198.         }
199.         if (!shp || !*shp) {
200.             tmp_dam->next = level.damagelist;
201.             level.damagelist = tmp_dam;
202.             tmp_dam = (struct damage *) alloc(sizeof(*tmp_dam));
203.         }
204.     }
205.     free((genericptr_t) tmp_dam);
206. }
207. 
208. /* restore one object */
209. STATIC_OVL void
210. restobj(fd, otmp)
211. int fd;
212. struct obj *otmp;
213. {
214.     int buflen;
215. 
216.     mread(fd, (genericptr_t) otmp, sizeof(struct obj));
217. 
218.     /* next object pointers are invalid; otmp->cobj needs to be left
219.        as is--being non-null is key to restoring container contents */
220.     otmp->nobj = otmp->nexthere = (struct obj *) 0;
221.     /* non-null oextra needs to be reconstructed */
222.     if (otmp->oextra) {
223.         otmp->oextra = newoextra();
224. 
225.         /* oname - object's name */
226.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
227.         if (buflen > 0) { /* includes terminating '\0' */
228.             new_oname(otmp, buflen);
229.             mread(fd, (genericptr_t) ONAME(otmp), buflen);
230.         }
231.         /* omonst - corpse or statue might retain full monster details */
232.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
233.         if (buflen > 0) {
234.             newomonst(otmp);
235.             /* this is actually a monst struct, so we
236.                can just defer to restmon() here */
237.             restmon(fd, OMONST(otmp));
238.         }
239.         /* omid - monster id number, connecting corpse to ghost */
240.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
241.         if (buflen > 0) {
242.             newomid(otmp);
243.             mread(fd, (genericptr_t) OMID(otmp), buflen);
244.         }
245.         /* olong - temporary gold */
246.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
247.         if (buflen > 0) {
248.             newolong(otmp);
249.             mread(fd, (genericptr_t) OLONG(otmp), buflen);
250.         }
251.         /* omailcmd - feedback mechanism for scroll of mail */
252.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
253.         if (buflen > 0) {
254.             char *omailcmd = (char *) alloc(buflen);
255. 
256.             mread(fd, (genericptr_t) omailcmd, buflen);
257.             new_omailcmd(otmp, omailcmd);
258.             free((genericptr_t) omailcmd);
259.         }
260.     }
261. }
262. 
263. STATIC_OVL struct obj *
264. restobjchn(fd, ghostly, frozen)
265. register int fd;
266. boolean ghostly, frozen;
267. {
268.     register struct obj *otmp, *otmp2 = 0;
269.     register struct obj *first = (struct obj *) 0;
270.     int buflen;
271. 
272.     while (1) {
273.         mread(fd, (genericptr_t) &buflen, sizeof buflen);
274.         if (buflen == -1)
275.             break;
276. 
277.         otmp = newobj();
278.         restobj(fd, otmp);
279.         if (!first)
280.             first = otmp;
281.         else
282.             otmp2->nobj = otmp;
283. 
284.         if (ghostly) {
285.             unsigned nid = context.ident++;
286.             add_id_mapping(otmp->o_id, nid);
287.             otmp->o_id = nid;
288.         }
289.         if (ghostly && otmp->otyp == SLIME_MOLD)
290.             ghostfruit(otmp);
291.         /* Ghost levels get object age shifted from old player's clock
292.          * to new player's clock.  Assumption: new player arrived
293.          * immediately after old player died.
294.          */
295.         if (ghostly && !frozen && !age_is_relative(otmp))
296.             otmp->age = monstermoves - omoves + otmp->age;
297. 
298.         /* get contents of a container or statue */
299.         if (Has_contents(otmp)) {
300.             struct obj *otmp3;
301. 
302.             otmp->cobj = restobjchn(fd, ghostly, Is_IceBox(otmp));
303.             /* restore container back pointers */
304.             for (otmp3 = otmp->cobj; otmp3; otmp3 = otmp3->nobj)
305.                 otmp3->ocontainer = otmp;
306.         } else if (SchroedingersBox(otmp)) {
307.             struct obj *catcorpse;
308. 
309.             /*
310.              * TODO:  Remove this after 3.6.x save compatibility is dropped.
311.              *
312.              * For 3.6.2, SchroedingersBox() always has a cat corpse in it.
313.              * For 3.6.[01], it was empty and its weight was falsified
314.              * to have the value it would have had if there was one inside.
315.              * Put a non-rotting cat corpse in this box to convert to 3.6.2.
316.              *
317.              * [Note: after this fix up, future save/restore of this object
318.              * will take the Has_contents() code path above.]
319.              */
320.             if ((catcorpse = mksobj(CORPSE, TRUE, FALSE)) != 0) {
321.                 otmp->spe = 1; /* flag for special SchroedingersBox */
322.                 set_corpsenm(catcorpse, PM_HOUSECAT);
323.                 (void) stop_timer(ROT_CORPSE, obj_to_any(catcorpse));
324.                 add_to_container(otmp, catcorpse);
325.                 otmp->owt = weight(otmp);
326.             }
327.         }
328.         if (otmp->bypass)
329.             otmp->bypass = 0;
330.         if (!ghostly) {
331.             /* fix the pointers */
332.             if (otmp->o_id == context.victual.o_id)
333.                 context.victual.piece = otmp;
334.             if (otmp->o_id == context.tin.o_id)
335.                 context.tin.tin = otmp;
336.             if (otmp->o_id == context.spbook.o_id)
337.                 context.spbook.book = otmp;
338.         }
339.         otmp2 = otmp;
340.     }
341.     if (first && otmp2->nobj) {
342.         impossible("Restobjchn: error reading objchn.");
343.         otmp2->nobj = 0;
344.     }
345. 
346.     return first;
347. }
348. 
349. /* restore one monster */
350. STATIC_OVL void
351. restmon(fd, mtmp)
352. int fd;
353. struct monst *mtmp;
354. {
355.     int buflen;
356. 
357.     mread(fd, (genericptr_t) mtmp, sizeof(struct monst));
358. 
359.     /* next monster pointer is invalid */
360.     mtmp->nmon = (struct monst *) 0;
361.     /* non-null mextra needs to be reconstructed */
362.     if (mtmp->mextra) {
363.         mtmp->mextra = newmextra();
364. 
365.         /* mname - monster's name */
366.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
367.         if (buflen > 0) { /* includes terminating '\0' */
368.             new_mname(mtmp, buflen);
369.             mread(fd, (genericptr_t) MNAME(mtmp), buflen);
370.         }
371.         /* egd - vault guard */
372.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
373.         if (buflen > 0) {
374.             newegd(mtmp);
375.             mread(fd, (genericptr_t) EGD(mtmp), sizeof(struct egd));
376.         }
377.         /* epri - temple priest */
378.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
379.         if (buflen > 0) {
380.             newepri(mtmp);
381.             mread(fd, (genericptr_t) EPRI(mtmp), sizeof(struct epri));
382.         }
383.         /* eshk - shopkeeper */
384.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
385.         if (buflen > 0) {
386.             neweshk(mtmp);
387.             mread(fd, (genericptr_t) ESHK(mtmp), sizeof(struct eshk));
388.         }
389.         /* emin - minion */
390.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
391.         if (buflen > 0) {
392.             newemin(mtmp);
393.             mread(fd, (genericptr_t) EMIN(mtmp), sizeof(struct emin));
394.         }
395.         /* edog - pet */
396.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
397.         if (buflen > 0) {
398.             newedog(mtmp);
399.             mread(fd, (genericptr_t) EDOG(mtmp), sizeof(struct edog));
400.         }
401.         /* mcorpsenm - obj->corpsenm for mimic posing as corpse or
402.            statue (inline int rather than pointer to something) */
403.         mread(fd, (genericptr_t) &MCORPSENM(mtmp), sizeof MCORPSENM(mtmp));
404.     } /* mextra */
405. }
406. 
407. STATIC_OVL struct monst *
408. restmonchn(fd, ghostly)
409. register int fd;
410. boolean ghostly;
411. {
412.     register struct monst *mtmp, *mtmp2 = 0;
413.     register struct monst *first = (struct monst *) 0;
414.     int offset, buflen;
415. 
416.     while (1) {
417.         mread(fd, (genericptr_t) &buflen, sizeof(buflen));
418.         if (buflen == -1)
419.             break;
420. 
421.         mtmp = newmonst();
422.         restmon(fd, mtmp);
423.         if (!first)
424.             first = mtmp;
425.         else
426.             mtmp2->nmon = mtmp;
427. 
428.         if (ghostly) {
429.             unsigned nid = context.ident++;
430.             add_id_mapping(mtmp->m_id, nid);
431.             mtmp->m_id = nid;
432.         }
433.         offset = mtmp->mnum;
434.         mtmp->data = &mons[offset];
435.         if (ghostly) {
436.             int mndx = monsndx(mtmp->data);
437.             if (propagate(mndx, TRUE, ghostly) == 0) {
438.                 /* cookie to trigger purge in getbones() */
439.                 mtmp->mhpmax = DEFUNCT_MONSTER;
440.             }
441.         }
442.         if (mtmp->minvent) {
443.             struct obj *obj;
444.             mtmp->minvent = restobjchn(fd, ghostly, FALSE);
445.             /* restore monster back pointer */
446.             for (obj = mtmp->minvent; obj; obj = obj->nobj)
447.                 obj->ocarry = mtmp;
448.         }
449.         if (mtmp->mw) {
450.             struct obj *obj;
451. 
452.             for (obj = mtmp->minvent; obj; obj = obj->nobj)
453.                 if (obj->owornmask & W_WEP)
454.                     break;
455.             if (obj)
456.                 mtmp->mw = obj;
457.             else {
458.                 MON_NOWEP(mtmp);
459.                 impossible("bad monster weapon restore");
460.             }
461.         }
462. 
463.         if (mtmp->isshk)
464.             restshk(mtmp, ghostly);
465.         if (mtmp->ispriest)
466.             restpriest(mtmp, ghostly);
467. 
468.         if (!ghostly) {
469.             if (mtmp->m_id == context.polearm.m_id)
470.                 context.polearm.hitmon = mtmp;
471.         }
472.         mtmp2 = mtmp;
473.     }
474.     if (first && mtmp2->nmon) {
475.         impossible("Restmonchn: error reading monchn.");
476.         mtmp2->nmon = 0;
477.     }
478.     return first;
479. }
480. 
481. STATIC_OVL struct fruit *
482. loadfruitchn(fd)
483. int fd;
484. {
485.     register struct fruit *flist, *fnext;
486. 
487.     flist = 0;
488.     while (fnext = newfruit(), mread(fd, (genericptr_t) fnext, sizeof *fnext),
489.            fnext->fid != 0) {
490.         fnext->nextf = flist;
491.         flist = fnext;
492.     }
493.     dealloc_fruit(fnext);
494.     return flist;
495. }
496. 
497. STATIC_OVL void
498. freefruitchn(flist)
499. register struct fruit *flist;
500. {
501.     register struct fruit *fnext;
502. 
503.     while (flist) {
504.         fnext = flist->nextf;
505.         dealloc_fruit(flist);
506.         flist = fnext;
507.     }
508. }
509. 
510. STATIC_OVL void
511. ghostfruit(otmp)
512. register struct obj *otmp;
513. {
514.     register struct fruit *oldf;
515. 
516.     for (oldf = oldfruit; oldf; oldf = oldf->nextf)
517.         if (oldf->fid == otmp->spe)
518.             break;
519. 
520.     if (!oldf)
521.         impossible("no old fruit?");
522.     else
523.         otmp->spe = fruitadd(oldf->fname, (struct fruit *) 0);
524. }
525. 
526. #ifdef SYSCF
527. #define SYSOPT_CHECK_SAVE_UID sysopt.check_save_uid
528. #else
529. #define SYSOPT_CHECK_SAVE_UID TRUE
530. #endif
531. 
532. STATIC_OVL
533. boolean
534. restgamestate(fd, stuckid, steedid)
535. register int fd;
536. unsigned int *stuckid, *steedid;
537. {
538.     struct flag newgameflags;
539. #ifdef SYSFLAGS
540.     struct sysflag newgamesysflags;
541. #endif
542.     struct context_info newgamecontext; /* all 0, but has some pointers */
543.     struct obj *otmp, *tmp_bc;
544.     char timebuf[15];
545.     unsigned long uid;
546.     boolean defer_perm_invent;
547. 
548.     mread(fd, (genericptr_t) &uid, sizeof uid);
549.     if (SYSOPT_CHECK_SAVE_UID
550.         && uid != (unsigned long) getuid()) { /* strange ... */
551.         /* for wizard mode, issue a reminder; for others, treat it
552.            as an attempt to cheat and refuse to restore this file */
553.         pline("Saved game was not yours.");
554.         if (!wizard)
555.             return FALSE;
556.     }
557. 
558.     newgamecontext = context; /* copy statically init'd context */
559.     mread(fd, (genericptr_t) &context, sizeof (struct context_info));
560.     context.warntype.species = (context.warntype.speciesidx >= LOW_PM)
561.                                   ? &mons[context.warntype.speciesidx]
562.                                   : (struct permonst *) 0;
563.     /* context.victual.piece, .tin.tin, .spellbook.book, and .polearm.hitmon
564.        are pointers which get set to Null during save and will be recovered
565.        via corresponding o_id or m_id while objs or mons are being restored */
566. 
567.     /* we want to be able to revert to command line/environment/config
568.        file option values instead of keeping old save file option values
569.        if partial restore fails and we resort to starting a new game */
570.     newgameflags = flags;
571.     mread(fd, (genericptr_t) &flags, sizeof (struct flag));
572.     /* avoid keeping permanent inventory window up to date during restore
573.        (setworn() calls update_inventory); attempting to include the cost
574.        of unpaid items before shopkeeper's bill is available is a no-no;
575.        named fruit names aren't accessible yet either
576.        [3.6.2: moved perm_invent from flags to iflags to keep it out of
577.        save files; retaining the override here is simpler than trying to
578.        to figure out where it really belongs now] */
579.     defer_perm_invent = iflags.perm_invent;
580.     iflags.perm_invent = FALSE;
581.     /* wizard and discover are actually flags.debug and flags.explore;
582.        player might be overriding the save file values for them;
583.        in the discover case, we don't want to set that for a normal
584.        game until after the save file has been removed */
585.     iflags.deferred_X = (newgameflags.explore && !discover);
586.     if (newgameflags.debug) {
587.         /* authorized by startup code; wizard mode exists and is allowed */
588.         wizard = TRUE, discover = iflags.deferred_X = FALSE;
589.     } else if (wizard) {
590.         /* specified by save file; check authorization now */
591.         set_playmode();
592.     }
593. #ifdef SYSFLAGS
594.     newgamesysflags = sysflags;
595.     mread(fd, (genericptr_t) &sysflags, sizeof(struct sysflag));
596. #endif
597. 
598.     role_init(); /* Reset the initial role, race, gender, and alignment */
599. #ifdef AMII_GRAPHICS
600.     amii_setpens(amii_numcolors); /* use colors from save file */
601. #endif
602.     mread(fd, (genericptr_t) &u, sizeof(struct you));
603. 
604. #define ReadTimebuf(foo)                   \
605.     mread(fd, (genericptr_t) timebuf, 14); \
606.     timebuf[14] = '\0';                    \
607.     foo = time_from_yyyymmddhhmmss(timebuf);
608. 
609.     ReadTimebuf(ubirthday);
610.     mread(fd, &urealtime.realtime, sizeof urealtime.realtime);
611.     ReadTimebuf(urealtime.start_timing); /** [not used] **/
612.     /* current time is the time to use for next urealtime.realtime update */
613.     urealtime.start_timing = getnow();
614. 
615.     set_uasmon();
616. #ifdef CLIPPING
617.     cliparound(u.ux, u.uy);
618. #endif
619.     if (u.uhp <= 0 && (!Upolyd || u.mh <= 0)) {
620.         u.ux = u.uy = 0; /* affects pline() [hence You()] */
621.         You("were not healthy enough to survive restoration.");
622.         /* wiz1_level.dlevel is used by mklev.c to see if lots of stuff is
623.          * uninitialized, so we only have to set it and not the other stuff.
624.          */
625.         wiz1_level.dlevel = 0;
626.         u.uz.dnum = 0;
627.         u.uz.dlevel = 1;
628.         /* revert to pre-restore option settings */
629.         iflags.deferred_X = FALSE;
630.         iflags.perm_invent = defer_perm_invent;
631.         flags = newgameflags;
632. #ifdef SYSFLAGS
633.         sysflags = newgamesysflags;
634. #endif
635.         context = newgamecontext;
636.         return FALSE;
637.     }
638.     /* in case hangup save occurred in midst of level change */
639.     assign_level(&u.uz0, &u.uz);
640. 
641.     /* this stuff comes after potential aborted restore attempts */
642.     restore_killers(fd);
643.     restore_timers(fd, RANGE_GLOBAL, FALSE, 0L);
644.     restore_light_sources(fd);
645.     invent = restobjchn(fd, FALSE, FALSE);
646.     /* tmp_bc only gets set here if the ball & chain were orphaned
647.        because you were swallowed; otherwise they will be on the floor
648.        or in your inventory */
649.     tmp_bc = restobjchn(fd, FALSE, FALSE);
650.     if (tmp_bc) {
651.         for (otmp = tmp_bc; otmp; otmp = otmp->nobj) {
652.             if (otmp->owornmask)
653.                 setworn(otmp, otmp->owornmask);
654.         }
655.         if (!uball || !uchain)
656.             impossible("restgamestate: lost ball & chain");
657.     }
658. 
659.     migrating_objs = restobjchn(fd, FALSE, FALSE);
660.     migrating_mons = restmonchn(fd, FALSE);
661.     mread(fd, (genericptr_t) mvitals, sizeof(mvitals));
662. 
663.     /*
664.      * There are some things after this that can have unintended display
665.      * side-effects too early in the game.
666.      * Disable see_monsters() here, re-enable it at the top of moveloop()
667.      */
668.     defer_see_monsters = TRUE;
669. 
670.     /* this comes after inventory has been loaded */
671.     for (otmp = invent; otmp; otmp = otmp->nobj)
672.         if (otmp->owornmask)
673.             setworn(otmp, otmp->owornmask);
674.     /* reset weapon so that player will get a reminder about "bashing"
675.        during next fight when bare-handed or wielding an unconventional
676.        item; for pick-axe, we aren't able to distinguish between having
677.        applied or wielded it, so be conservative and assume the former */
678.     otmp = uwep;   /* `uwep' usually init'd by setworn() in loop above */
679.     uwep = 0;      /* clear it and have setuwep() reinit */
680.     setuwep(otmp); /* (don't need any null check here) */
681.     if (!uwep || uwep->otyp == PICK_AXE || uwep->otyp == GRAPPLING_HOOK)
682.         unweapon = TRUE;
683. 
684.     restore_dungeon(fd);
685.     restlevchn(fd);
686.     mread(fd, (genericptr_t) &moves, sizeof moves);
687.     mread(fd, (genericptr_t) &monstermoves, sizeof monstermoves);
688.     mread(fd, (genericptr_t) &quest_status, sizeof (struct q_score));
689.     mread(fd, (genericptr_t) spl_book, (MAXSPELL + 1) * sizeof (struct spell));
690.     restore_artifacts(fd);
691.     restore_oracles(fd);
692.     if (u.ustuck)
693.         mread(fd, (genericptr_t) stuckid, sizeof *stuckid);
694.     if (u.usteed)
695.         mread(fd, (genericptr_t) steedid, sizeof *steedid);
696.     mread(fd, (genericptr_t) pl_character, sizeof pl_character);
697. 
698.     mread(fd, (genericptr_t) pl_fruit, sizeof pl_fruit);
699.     freefruitchn(ffruit); /* clean up fruit(s) made by initoptions() */
700.     ffruit = loadfruitchn(fd);
701. 
702.     restnames(fd);
703.     restore_waterlevel(fd);
704.     restore_msghistory(fd);
705.     /* must come after all mons & objs are restored */
706.     relink_timers(FALSE);
707.     relink_light_sources(FALSE);
708.     /* inventory display is now viable */
709.     iflags.perm_invent = defer_perm_invent;
710.     return TRUE;
711. }
712. 
713. /* update game state pointers to those valid for the current level (so we
714.  * don't dereference a wild u.ustuck when saving the game state, for instance)
715.  */
716. STATIC_OVL void
717. restlevelstate(stuckid, steedid)
718. unsigned int stuckid, steedid;
719. {
720.     register struct monst *mtmp;
721. 
722.     if (stuckid) {
723.         for (mtmp = fmon; mtmp; mtmp = mtmp->nmon)
724.             if (mtmp->m_id == stuckid)
725.                 break;
726.         if (!mtmp)
727.             panic("Cannot find the monster ustuck.");
728.         u.ustuck = mtmp;
729.     }
730.     if (steedid) {
731.         for (mtmp = fmon; mtmp; mtmp = mtmp->nmon)
732.             if (mtmp->m_id == steedid)
733.                 break;
734.         if (!mtmp)
735.             panic("Cannot find the monster usteed.");
736.         u.usteed = mtmp;
737.         remove_monster(mtmp->mx, mtmp->my);
738.     }
739. }
740. 
741. /*ARGSUSED*/
742. STATIC_OVL int
743. restlevelfile(fd, ltmp)
744. int fd; /* fd used in MFLOPPY only */
745. xchar ltmp;
746. {
747.     int nfd;
748.     char whynot[BUFSZ];
749. 
750. #ifndef MFLOPPY
751.     nhUse(fd);
752. #endif
753.     nfd = create_levelfile(ltmp, whynot);
754.     if (nfd < 0) {
755.         /* BUG: should suppress any attempt to write a panic
756.            save file if file creation is now failing... */
757.         panic("restlevelfile: %s", whynot);
758.     }
759. #ifdef MFLOPPY
760.     if (!savelev(nfd, ltmp, COUNT_SAVE)) {
761.         /* The savelev can't proceed because the size required
762.          * is greater than the available disk space.
763.          */
764.         pline("Not enough space on `%s' to restore your game.", levels);
765. 
766.         /* Remove levels and bones that may have been created.
767.          */
768.         (void) nhclose(nfd);
769. #ifdef AMIGA
770.         clearlocks();
771. #else /* !AMIGA */
772.         eraseall(levels, alllevels);
773.         eraseall(levels, allbones);
774. 
775.         /* Perhaps the person would like to play without a
776.          * RAMdisk.
777.          */
778.         if (ramdisk) {
779.             /* PlaywoRAMdisk may not return, but if it does
780.              * it is certain that ramdisk will be 0.
781.              */
782.             playwoRAMdisk();
783.             /* Rewind save file and try again */
784.             (void) lseek(fd, (off_t) 0, 0);
785.             (void) validate(fd, (char *) 0); /* skip version etc */
786.             return dorecover(fd);            /* 0 or 1 */
787.         }
788. #endif /* ?AMIGA */
789.         pline("Be seeing you...");
790.         nh_terminate(EXIT_SUCCESS);
791.     }
792. #endif /* MFLOPPY */
793.     bufon(nfd);
794.     savelev(nfd, ltmp, WRITE_SAVE | FREE_SAVE);
795.     bclose(nfd);
796.     return 2;
797. }
798. 
799. int
800. dorecover(fd)
801. register int fd;
802. {
803.     unsigned int stuckid = 0, steedid = 0; /* not a register */
804.     xchar ltmp;
805.     int rtmp;
806.     struct obj *otmp;
807. 
808.     restoring = TRUE;
809.     get_plname_from_file(fd, plname);
810.     getlev(fd, 0, (xchar) 0, FALSE);
811.     if (!restgamestate(fd, &stuckid, &steedid)) {
812.         display_nhwindow(WIN_MESSAGE, TRUE);
813.         savelev(-1, 0, FREE_SAVE); /* discard current level */
814.         (void) nhclose(fd);
815.         (void) delete_savefile();
816.         restoring = FALSE;
817.         return 0;
818.     }
819.     restlevelstate(stuckid, steedid);
820. #ifdef INSURANCE
821.     savestateinlock();
822. #endif
823.     rtmp = restlevelfile(fd, ledger_no(&u.uz));
824.     if (rtmp < 2)
825.         return rtmp; /* dorecover called recursively */
826. 
827.     /* these pointers won't be valid while we're processing the
828.      * other levels, but they'll be reset again by restlevelstate()
829.      * afterwards, and in the meantime at least u.usteed may mislead
830.      * place_monster() on other levels
831.      */
832.     u.ustuck = (struct monst *) 0;
833.     u.usteed = (struct monst *) 0;
834. 
835. #ifdef MICRO
836. #ifdef AMII_GRAPHICS
837.     {
838.         extern struct window_procs amii_procs;
839.         if (WINDOWPORT("amii") {
840.             extern winid WIN_BASE;
841.             clear_nhwindow(WIN_BASE); /* hack until there's a hook for this */
842.         }
843.     }
844. #else
845.         clear_nhwindow(WIN_MAP);
846. #endif
847.     clear_nhwindow(WIN_MESSAGE);
848.     You("return to level %d in %s%s.", depth(&u.uz),
849.         dungeons[u.uz.dnum].dname,
850.         flags.debug ? " while in debug mode"
851.                     : flags.explore ? " while in explore mode" : "");
852.     curs(WIN_MAP, 1, 1);
853.     dotcnt = 0;
854.     dotrow = 2;
855.     if (!WINDOWPORT("X11"))
856.         putstr(WIN_MAP, 0, "Restoring:");
857. #endif
858.     restoreprocs.mread_flags = 1; /* return despite error */
859.     while (1) {
860.         mread(fd, (genericptr_t) &ltmp, sizeof ltmp);
861.         if (restoreprocs.mread_flags == -1)
862.             break;
863.         getlev(fd, 0, ltmp, FALSE);
864. #ifdef MICRO
865.         curs(WIN_MAP, 1 + dotcnt++, dotrow);
866.         if (dotcnt >= (COLNO - 1)) {
867.             dotrow++;
868.             dotcnt = 0;
869.         }
870.         if (!WINDOWPORT("X11")) {
871.             putstr(WIN_MAP, 0, ".");
872.         }
873.         mark_synch();
874. #endif
875.         rtmp = restlevelfile(fd, ltmp);
876.         if (rtmp < 2)
877.             return rtmp; /* dorecover called recursively */
878.     }
879.     restoreprocs.mread_flags = 0;
880. 
881. #ifdef BSD
882.     (void) lseek(fd, 0L, 0);
883. #else
884.     (void) lseek(fd, (off_t) 0, 0);
885. #endif
886.     (void) validate(fd, (char *) 0); /* skip version and savefile info */
887.     get_plname_from_file(fd, plname);
888. 
889.     getlev(fd, 0, (xchar) 0, FALSE);
890.     (void) nhclose(fd);
891. 
892.     /* Now set the restore settings to match the
893.      * settings used by the save file output routines
894.      */
895.     reset_restpref();
896. 
897.     restlevelstate(stuckid, steedid);
898.     program_state.something_worth_saving = 1; /* useful data now exists */
899. 
900.     if (!wizard && !discover)
901.         (void) delete_savefile();
902.     if (Is_rogue_level(&u.uz))
903.         assign_graphics(ROGUESET);
904. #ifdef USE_TILES
905.     substitute_tiles(&u.uz);
906. #endif
907. #ifdef MFLOPPY
908.     gameDiskPrompt();
909. #endif
910.     max_rank_sz(); /* to recompute mrank_sz (botl.c) */
911.     /* take care of iron ball & chain */
912.     for (otmp = fobj; otmp; otmp = otmp->nobj)
913.         if (otmp->owornmask)
914.             setworn(otmp, otmp->owornmask);
915. 
916.     /* in_use processing must be after:
917.      *    + The inventory has been read so that freeinv() works.
918.      *    + The current level has been restored so billing information
919.      *      is available.
920.      */
921.     inven_inuse(FALSE);
922. 
923.     load_qtlist(); /* re-load the quest text info */
924.     /* Set up the vision internals, after levl[] data is loaded
925.        but before docrt(). */
926.     reglyph_darkroom();
927.     vision_reset();
928.     vision_full_recalc = 1; /* recompute vision (not saved) */
929. 
930.     run_timers(); /* expire all timers that have gone off while away */
931.     docrt();
932.     restoring = FALSE;
933.     clear_nhwindow(WIN_MESSAGE);
934. 
935.     /* Success! */
936.     welcome(FALSE);
937.     check_special_room(FALSE);
938.     return 1;
939. }
940. 
941. void
942. restcemetery(fd, cemeteryaddr)
943. int fd;
944. struct cemetery **cemeteryaddr;
945. {
946.     struct cemetery *bonesinfo, **bonesaddr;
947.     int flag;
948. 
949.     mread(fd, (genericptr_t) &flag, sizeof flag);
950.     if (flag == 0) {
951.         bonesaddr = cemeteryaddr;
952.         do {
953.             bonesinfo = (struct cemetery *) alloc(sizeof *bonesinfo);
954.             mread(fd, (genericptr_t) bonesinfo, sizeof *bonesinfo);
955.             *bonesaddr = bonesinfo;
956.             bonesaddr = &(*bonesaddr)->next;
957.         } while (*bonesaddr);
958.     } else {
959.         *cemeteryaddr = 0;
960.     }
961. }
962. 
963. /*ARGSUSED*/
964. STATIC_OVL void
965. rest_levl(fd, rlecomp)
966. int fd;
967. boolean rlecomp;
968. {
969. #ifdef RLECOMP
970.     short i, j;
971.     uchar len;
972.     struct rm r;
973. 
974.     if (rlecomp) {
975.         (void) memset((genericptr_t) &r, 0, sizeof(r));
976.         i = 0;
977.         j = 0;
978.         len = 0;
979.         while (i < ROWNO) {
980.             while (j < COLNO) {
981.                 if (len > 0) {
982.                     levl[j][i] = r;
983.                     len -= 1;
984.                     j += 1;
985.                 } else {
986.                     mread(fd, (genericptr_t) &len, sizeof(uchar));
987.                     mread(fd, (genericptr_t) &r, sizeof(struct rm));
988.                 }
989.             }
990.             j = 0;
991.             i += 1;
992.         }
993.         return;
994.     }
995. #else /* !RLECOMP */
996.     nhUse(rlecomp);
997. #endif /* ?RLECOMP */
998.     mread(fd, (genericptr_t) levl, sizeof levl);
999. }
1000. 
1001. void
1002. trickery(reason)
1003. char *reason;
1004. {
1005.     pline("Strange, this map is not as I remember it.");
1006.     pline("Somebody is trying some trickery here...");
1007.     pline("This game is void.");
1008.     Strcpy(killer.name, reason ? reason : "");
1009.     done(TRICKED);
1010. }
1011. 
1012. void
1013. getlev(fd, pid, lev, ghostly)
1014. int fd, pid;
1015. xchar lev;
1016. boolean ghostly;
1017. {
1018.     register struct trap *trap;
1019.     register struct monst *mtmp;
1020.     long elapsed;
1021.     branch *br;
1022.     int hpid;
1023.     xchar dlvl;
1024.     int x, y;
1025. #ifdef TOS
1026.     short tlev;
1027. #endif
1028. 
1029.     if (ghostly)
1030.         clear_id_mapping();
1031. 
1032. #if defined(MSDOS) || defined(OS2)
1033.     setmode(fd, O_BINARY);
1034. #endif
1035.     /* Load the old fruit info.  We have to do it first, so the
1036.      * information is available when restoring the objects.
1037.      */
1038.     if (ghostly)
1039.         oldfruit = loadfruitchn(fd);
1040. 
1041.     /* First some sanity checks */
1042.     mread(fd, (genericptr_t) &hpid, sizeof(hpid));
1043. /* CHECK:  This may prevent restoration */
1044. #ifdef TOS
1045.     mread(fd, (genericptr_t) &tlev, sizeof(tlev));
1046.     dlvl = tlev & 0x00ff;
1047. #else
1048.     mread(fd, (genericptr_t) &dlvl, sizeof(dlvl));
1049. #endif
1050.     if ((pid && pid != hpid) || (lev && dlvl != lev)) {
1051.         char trickbuf[BUFSZ];
1052. 
1053.         if (pid && pid != hpid)
1054.             Sprintf(trickbuf, "PID (%d) doesn't match saved PID (%d)!", hpid,
1055.                     pid);
1056.         else
1057.             Sprintf(trickbuf, "This is level %d, not %d!", dlvl, lev);
1058.         if (wizard)
1059.             pline1(trickbuf);
1060.         trickery(trickbuf);
1061.     }
1062.     restcemetery(fd, &level.bonesinfo);
1063.     rest_levl(fd,
1064.               (boolean) ((sfrestinfo.sfi1 & SFI1_RLECOMP) == SFI1_RLECOMP));
1065.     mread(fd, (genericptr_t) lastseentyp, sizeof(lastseentyp));
1066.     mread(fd, (genericptr_t) &omoves, sizeof(omoves));
1067.     elapsed = monstermoves - omoves;
1068.     mread(fd, (genericptr_t) &upstair, sizeof(stairway));
1069.     mread(fd, (genericptr_t) &dnstair, sizeof(stairway));
1070.     mread(fd, (genericptr_t) &upladder, sizeof(stairway));
1071.     mread(fd, (genericptr_t) &dnladder, sizeof(stairway));
1072.     mread(fd, (genericptr_t) &sstairs, sizeof(stairway));
1073.     mread(fd, (genericptr_t) &updest, sizeof(dest_area));
1074.     mread(fd, (genericptr_t) &dndest, sizeof(dest_area));
1075.     mread(fd, (genericptr_t) &level.flags, sizeof(level.flags));
1076.     mread(fd, (genericptr_t) doors, sizeof(doors));
1077.     rest_rooms(fd); /* No joke :-) */
1078.     if (nroom)
1079.         doorindex = rooms[nroom - 1].fdoor + rooms[nroom - 1].doorct;
1080.     else
1081.         doorindex = 0;
1082. 
1083.     restore_timers(fd, RANGE_LEVEL, ghostly, elapsed);
1084.     restore_light_sources(fd);
1085.     fmon = restmonchn(fd, ghostly);
1086. 
1087.     rest_worm(fd); /* restore worm information */
1088.     ftrap = 0;
1089.     while (trap = newtrap(),
1090.            mread(fd, (genericptr_t) trap, sizeof(struct trap)),
1091.            trap->tx != 0) { /* need "!= 0" to work around DICE 3.0 bug */
1092.         trap->ntrap = ftrap;
1093.         ftrap = trap;
1094.     }
1095.     dealloc_trap(trap);
1096.     fobj = restobjchn(fd, ghostly, FALSE);
1097.     find_lev_obj();
1098.     /* restobjchn()'s `frozen' argument probably ought to be a callback
1099.        routine so that we can check for objects being buried under ice */
1100.     level.buriedobjlist = restobjchn(fd, ghostly, FALSE);
1101.     billobjs = restobjchn(fd, ghostly, FALSE);
1102.     rest_engravings(fd);
1103. 
1104.     /* reset level.monsters for new level */
1105.     for (x = 0; x < COLNO; x++)
1106.         for (y = 0; y < ROWNO; y++)
1107.             level.monsters[x][y] = (struct monst *) 0;
1108.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
1109.         if (mtmp->isshk)
1110.             set_residency(mtmp, FALSE);
1111.         place_monster(mtmp, mtmp->mx, mtmp->my);
1112.         if (mtmp->wormno)
1113.             place_wsegs(mtmp, NULL);
1114. 
1115.         /* regenerate monsters while on another level */
1116.         if (!u.uz.dlevel)
1117.             continue;
1118.         if (ghostly) {
1119.             /* reset peaceful/malign relative to new character;
1120.                shopkeepers will reset based on name */
1121.             if (!mtmp->isshk)
1122.                 mtmp->mpeaceful =
1123.                     (is_unicorn(mtmp->data)
1124.                      && sgn(u.ualign.type) == sgn(mtmp->data->maligntyp))
1125.                         ? TRUE
1126.                         : peace_minded(mtmp->data);
1127.             set_malign(mtmp);
1128.         } else if (elapsed > 0L) {
1129.             mon_catchup_elapsed_time(mtmp, elapsed);
1130.         }
1131.         /* update shape-changers in case protection against
1132.            them is different now than when the level was saved */
1133.         restore_cham(mtmp);
1134.         /* give hiders a chance to hide before their next move */
1135.         if (ghostly || elapsed > (long) rnd(10))
1136.             hide_monst(mtmp);
1137.     }
1138. 
1139.     restdamage(fd, ghostly);
1140.     rest_regions(fd, ghostly);
1141.     if (ghostly) {
1142.         /* Now get rid of all the temp fruits... */
1143.         freefruitchn(oldfruit), oldfruit = 0;
1144. 
1145.         if (lev > ledger_no(&medusa_level)
1146.             && lev < ledger_no(&stronghold_level) && xdnstair == 0) {
1147.             coord cc;
1148. 
1149.             mazexy(&cc);
1150.             xdnstair = cc.x;
1151.             ydnstair = cc.y;
1152.             levl[cc.x][cc.y].typ = STAIRS;
1153.         }
1154. 
1155.         br = Is_branchlev(&u.uz);
1156.         if (br && u.uz.dlevel == 1) {
1157.             d_level ltmp;
1158. 
1159.             if (on_level(&u.uz, &br->end1))
1160.                 assign_level(&ltmp, &br->end2);
1161.             else
1162.                 assign_level(&ltmp, &br->end1);
1163. 
1164.             switch (br->type) {
1165.             case BR_STAIR:
1166.             case BR_NO_END1:
1167.             case BR_NO_END2: /* OK to assign to sstairs if it's not used */
1168.                 assign_level(&sstairs.tolev, &ltmp);
1169.                 break;
1170.             case BR_PORTAL: /* max of 1 portal per level */
1171.                 for (trap = ftrap; trap; trap = trap->ntrap)
1172.                     if (trap->ttyp == MAGIC_PORTAL)
1173.                         break;
1174.                 if (!trap)
1175.                     panic("getlev: need portal but none found");
1176.                 assign_level(&trap->dst, &ltmp);
1177.                 break;
1178.             }
1179.         } else if (!br) {
1180.             struct trap *ttmp = 0;
1181. 
1182.             /* Remove any dangling portals. */
1183.             for (trap = ftrap; trap; trap = ttmp) {
1184.                 ttmp = trap->ntrap;
1185.                 if (trap->ttyp == MAGIC_PORTAL)
1186.                     deltrap(trap);
1187.             }
1188.         }
1189.     }
1190. 
1191.     /* must come after all mons & objs are restored */
1192.     relink_timers(ghostly);
1193.     relink_light_sources(ghostly);
1194.     reset_oattached_mids(ghostly);
1195. 
1196.     if (ghostly)
1197.         clear_id_mapping();
1198. }
1199. 
1200. void
1201. get_plname_from_file(fd, plbuf)
1202. int fd;
1203. char *plbuf;
1204. {
1205.     int pltmpsiz = 0;
1206.     (void) read(fd, (genericptr_t) &pltmpsiz, sizeof(pltmpsiz));
1207.     (void) read(fd, (genericptr_t) plbuf, pltmpsiz);
1208.     return;
1209. }
1210. 
1211. STATIC_OVL void
1212. restore_msghistory(fd)
1213. register int fd;
1214. {
1215.     int msgsize, msgcount = 0;
1216.     char msg[BUFSZ];
1217. 
1218.     while (1) {
1219.         mread(fd, (genericptr_t) &msgsize, sizeof(msgsize));
1220.         if (msgsize == -1)
1221.             break;
1222.         if (msgsize > (BUFSZ - 1))
1223.             panic("restore_msghistory: msg too big (%d)", msgsize);
1224.         mread(fd, (genericptr_t) msg, msgsize);
1225.         msg[msgsize] = '\0';
1226.         putmsghistory(msg, TRUE);
1227.         ++msgcount;
1228.     }
1229.     if (msgcount)
1230.         putmsghistory((char *) 0, TRUE);
1231.     debugpline1("Read %d messages from savefile.", msgcount);
1232. }
1233. 
1234. /* Clear all structures for object and monster ID mapping. */
1235. STATIC_OVL void
1236. clear_id_mapping()
1237. {
1238.     struct bucket *curr;
1239. 
1240.     while ((curr = id_map) != 0) {
1241.         id_map = curr->next;
1242.         free((genericptr_t) curr);
1243.     }
1244.     n_ids_mapped = 0;
1245. }
1246. 
1247. /* Add a mapping to the ID map. */
1248. STATIC_OVL void
1249. add_id_mapping(gid, nid)
1250. unsigned gid, nid;
1251. {
1252.     int idx;
1253. 
1254.     idx = n_ids_mapped % N_PER_BUCKET;
1255.     /* idx is zero on first time through, as well as when a new bucket is */
1256.     /* needed */
1257.     if (idx == 0) {
1258.         struct bucket *gnu = (struct bucket *) alloc(sizeof(struct bucket));
1259.         gnu->next = id_map;
1260.         id_map = gnu;
1261.     }
1262. 
1263.     id_map->map[idx].gid = gid;
1264.     id_map->map[idx].nid = nid;
1265.     n_ids_mapped++;
1266. }
1267. 
1268. /*
1269.  * Global routine to look up a mapping.  If found, return TRUE and fill
1270.  * in the new ID value.  Otherwise, return false and return -1 in the new
1271.  * ID.
1272.  */
1273. boolean
1274. lookup_id_mapping(gid, nidp)
1275. unsigned gid, *nidp;
1276. {
1277.     int i;
1278.     struct bucket *curr;
1279. 
1280.     if (n_ids_mapped)
1281.         for (curr = id_map; curr; curr = curr->next) {
1282.             /* first bucket might not be totally full */
1283.             if (curr == id_map) {
1284.                 i = n_ids_mapped % N_PER_BUCKET;
1285.                 if (i == 0)
1286.                     i = N_PER_BUCKET;
1287.             } else
1288.                 i = N_PER_BUCKET;
1289. 
1290.             while (--i >= 0)
1291.                 if (gid == curr->map[i].gid) {
1292.                     *nidp = curr->map[i].nid;
1293.                     return TRUE;
1294.                 }
1295.         }
1296. 
1297.     return FALSE;
1298. }
1299. 
1300. STATIC_OVL void
1301. reset_oattached_mids(ghostly)
1302. boolean ghostly;
1303. {
1304.     struct obj *otmp;
1305.     unsigned oldid, nid;
1306.     for (otmp = fobj; otmp; otmp = otmp->nobj) {
1307.         if (ghostly && has_omonst(otmp)) {
1308.             struct monst *mtmp = OMONST(otmp);
1309. 
1310.             mtmp->m_id = 0;
1311.             mtmp->mpeaceful = mtmp->mtame = 0; /* pet's owner died! */
1312.         }
1313.         if (ghostly && has_omid(otmp)) {
1314.             (void) memcpy((genericptr_t) &oldid, (genericptr_t) OMID(otmp),
1315.                           sizeof(oldid));
1316.             if (lookup_id_mapping(oldid, &nid))
1317.                 (void) memcpy((genericptr_t) OMID(otmp), (genericptr_t) &nid,
1318.                               sizeof(nid));
1319.             else
1320.                 free_omid(otmp);
1321.         }
1322.     }
1323. }
1324. 
1325. #ifdef SELECTSAVED
1326. /* put up a menu listing each character from this player's saved games;
1327.    returns 1: use plname[], 0: new game, -1: quit */
1328. int
1329. restore_menu(bannerwin)
1330. winid bannerwin; /* if not WIN_ERR, clear window and show copyright in menu */
1331. {
1332.     winid tmpwin;
1333.     anything any;
1334.     char **saved;
1335.     menu_item *chosen_game = (menu_item *) 0;
1336.     int k, clet, ch = 0; /* ch: 0 => new game */
1337. 
1338.     *plname = '\0';
1339.     saved = get_saved_games(); /* array of character names */
1340.     if (saved && *saved) {
1341.         tmpwin = create_nhwindow(NHW_MENU);
1342.         start_menu(tmpwin);
1343.         any = zeroany; /* no selection */
1344.         if (bannerwin != WIN_ERR) {
1345.             /* for tty; erase copyright notice and redo it in the menu */
1346.             clear_nhwindow(bannerwin);
1347.             /* COPYRIGHT_BANNER_[ABCD] */
1348.             for (k = 1; k <= 4; ++k)
1349.                 add_menu(tmpwin, NO_GLYPH, &any, 0, 0, ATR_NONE,
1350.                          copyright_banner_line(k), MENU_UNSELECTED);
1351.             add_menu(tmpwin, NO_GLYPH, &any, 0, 0, ATR_NONE, "",
1352.                      MENU_UNSELECTED);
1353.         }
1354.         add_menu(tmpwin, NO_GLYPH, &any, 0, 0, ATR_NONE,
1355.                  "Select one of your saved games", MENU_UNSELECTED);
1356.         for (k = 0; saved[k]; ++k) {
1357.             any.a_int = k + 1;
1358.             add_menu(tmpwin, NO_GLYPH, &any, 0, 0, ATR_NONE, saved[k],
1359.                      MENU_UNSELECTED);
1360.         }
1361.         clet = (k <= 'n' - 'a') ? 'n' : 0; /* new game */
1362.         any.a_int = -1;                    /* not >= 0 */
1363.         add_menu(tmpwin, NO_GLYPH, &any, clet, 0, ATR_NONE,
1364.                  "Start a new character", MENU_UNSELECTED);
1365.         clet = (k + 1 <= 'q' - 'a') ? 'q' : 0; /* quit */
1366.         any.a_int = -2;
1367.         add_menu(tmpwin, NO_GLYPH, &any, clet, 0, ATR_NONE,
1368.                  "Never mind (quit)", MENU_SELECTED);
1369.         /* no prompt on end_menu, as we've done our own at the top */
1370.         end_menu(tmpwin, (char *) 0);
1371.         if (select_menu(tmpwin, PICK_ONE, &chosen_game) > 0) {
1372.             ch = chosen_game->item.a_int;
1373.             if (ch > 0)
1374.                 Strcpy(plname, saved[ch - 1]);
1375.             else if (ch < 0)
1376.                 ++ch; /* -1 -> 0 (new game), -2 -> -1 (quit) */
1377.             free((genericptr_t) chosen_game);
1378.         } else {
1379.             ch = -1; /* quit menu without making a selection => quit */
1380.         }
1381.         destroy_nhwindow(tmpwin);
1382.         if (bannerwin != WIN_ERR) {
1383.             /* for tty; clear the menu away and put subset of copyright back
1384.              */
1385.             clear_nhwindow(bannerwin);
1386.             /* COPYRIGHT_BANNER_A, preceding "Who are you?" prompt */
1387.             if (ch == 0)
1388.                 putstr(bannerwin, 0, copyright_banner_line(1));
1389.         }
1390.     }
1391.     free_saved_games(saved);
1392.     return (ch > 0) ? 1 : ch;
1393. }
1394. #endif /* SELECTSAVED */
1395. 
1396. void
1397. minit()
1398. {
1399.     (*restoreprocs.restore_minit)();
1400.     return;
1401. }
1402. 
1403. void
1404. mread(fd, buf, len)
1405. register int fd;
1406. register genericptr_t buf;
1407. register unsigned int len;
1408. {
1409.     (*restoreprocs.restore_mread)(fd, buf, len);
1410.     return;
1411. }
1412. 
1413. /* examine the version info and the savefile_info data
1414.    that immediately follows it.
1415.    Return 0 if it passed the checks.
1416.    Return 1 if it failed the version check.
1417.    Return 2 if it failed the savefile feature check.
1418.    Return -1 if it failed for some unknown reason.
1419.  */
1420. int
1421. validate(fd, name)
1422. int fd;
1423. const char *name;
1424. {
1425.     int rlen;
1426.     struct savefile_info sfi;
1427.     unsigned long compatible;
1428.     boolean verbose = name ? TRUE : FALSE, reslt = FALSE;
1429. 
1430.     if (!(reslt = uptodate(fd, name)))
1431.         return 1;
1432. 
1433.     rlen = read(fd, (genericptr_t) &sfi, sizeof sfi);
1434.     minit(); /* ZEROCOMP */
1435.     if (rlen == 0) {
1436.         if (verbose) {
1437.             pline("File \"%s\" is empty during save file feature check?",
1438.                   name);
1439.             wait_synch();
1440.         }
1441.         return -1;
1442.     }
1443. 
1444.     compatible = (sfi.sfi1 & sfcap.sfi1);
1445. 
1446.     if ((sfi.sfi1 & SFI1_ZEROCOMP) == SFI1_ZEROCOMP) {
1447.         if ((compatible & SFI1_ZEROCOMP) != SFI1_ZEROCOMP) {
1448.             if (verbose) {
1449.                 pline("File \"%s\" has incompatible ZEROCOMP compression.",
1450.                       name);
1451.                 wait_synch();
1452.             }
1453.             return 2;
1454.         } else if ((sfrestinfo.sfi1 & SFI1_ZEROCOMP) != SFI1_ZEROCOMP) {
1455.             set_restpref("zerocomp");
1456.         }
1457.     }
1458. 
1459.     if ((sfi.sfi1 & SFI1_EXTERNALCOMP) == SFI1_EXTERNALCOMP) {
1460.         if ((compatible & SFI1_EXTERNALCOMP) != SFI1_EXTERNALCOMP) {
1461.             if (verbose) {
1462.                 pline("File \"%s\" lacks required internal compression.",
1463.                       name);
1464.                 wait_synch();
1465.             }
1466.             return 2;
1467.         } else if ((sfrestinfo.sfi1 & SFI1_EXTERNALCOMP)
1468.                    != SFI1_EXTERNALCOMP) {
1469.             set_restpref("externalcomp");
1470.         }
1471.     }
1472. 
1473.     /* RLECOMP check must be last, after ZEROCOMP or INTERNALCOMP adjustments
1474.      */
1475.     if ((sfi.sfi1 & SFI1_RLECOMP) == SFI1_RLECOMP) {
1476.         if ((compatible & SFI1_RLECOMP) != SFI1_RLECOMP) {
1477.             if (verbose) {
1478.                 pline("File \"%s\" has incompatible run-length compression.",
1479.                       name);
1480.                 wait_synch();
1481.             }
1482.             return 2;
1483.         } else if ((sfrestinfo.sfi1 & SFI1_RLECOMP) != SFI1_RLECOMP) {
1484.             set_restpref("rlecomp");
1485.         }
1486.     }
1487.     /* savefile does not have RLECOMP level location compression, so adjust */
1488.     else
1489.         set_restpref("!rlecomp");
1490. 
1491.     return 0;
1492. }
1493. 
1494. void
1495. reset_restpref()
1496. {
1497. #ifdef ZEROCOMP
1498.     if (iflags.zerocomp)
1499.         set_restpref("zerocomp");
1500.     else
1501. #endif
1502.         set_restpref("externalcomp");
1503. #ifdef RLECOMP
1504.     if (iflags.rlecomp)
1505.         set_restpref("rlecomp");
1506.     else
1507. #endif
1508.         set_restpref("!rlecomp");
1509. }
1510. 
1511. void
1512. set_restpref(suitename)
1513. const char *suitename;
1514. {
1515.     if (!strcmpi(suitename, "externalcomp")) {
1516.         restoreprocs.name = "externalcomp";
1517.         restoreprocs.restore_mread = def_mread;
1518.         restoreprocs.restore_minit = def_minit;
1519.         sfrestinfo.sfi1 |= SFI1_EXTERNALCOMP;
1520.         sfrestinfo.sfi1 &= ~SFI1_ZEROCOMP;
1521.         def_minit();
1522.     }
1523.     if (!strcmpi(suitename, "!rlecomp")) {
1524.         sfrestinfo.sfi1 &= ~SFI1_RLECOMP;
1525.     }
1526. #ifdef ZEROCOMP
1527.     if (!strcmpi(suitename, "zerocomp")) {
1528.         restoreprocs.name = "zerocomp";
1529.         restoreprocs.restore_mread = zerocomp_mread;
1530.         restoreprocs.restore_minit = zerocomp_minit;
1531.         sfrestinfo.sfi1 |= SFI1_ZEROCOMP;
1532.         sfrestinfo.sfi1 &= ~SFI1_EXTERNALCOMP;
1533.         zerocomp_minit();
1534.     }
1535. #endif
1536. #ifdef RLECOMP
1537.     if (!strcmpi(suitename, "rlecomp")) {
1538.         sfrestinfo.sfi1 |= SFI1_RLECOMP;
1539.     }
1540. #endif
1541. }
1542. 
1543. #ifdef ZEROCOMP
1544. #define RLESC '\0' /* Leading character for run of RLESC's */
1545. 
1546. #ifndef ZEROCOMP_BUFSIZ
1547. #define ZEROCOMP_BUFSIZ BUFSZ
1548. #endif
1549. static NEARDATA unsigned char inbuf[ZEROCOMP_BUFSIZ];
1550. static NEARDATA unsigned short inbufp = 0;
1551. static NEARDATA unsigned short inbufsz = 0;
1552. static NEARDATA short inrunlength = -1;
1553. static NEARDATA int mreadfd;
1554. 
1555. STATIC_OVL int
1556. zerocomp_mgetc()
1557. {
1558.     if (inbufp >= inbufsz) {
1559.         inbufsz = read(mreadfd, (genericptr_t) inbuf, sizeof inbuf);
1560.         if (!inbufsz) {
1561.             if (inbufp > sizeof inbuf)
1562.                 error("EOF on file #%d.\n", mreadfd);
1563.             inbufp = 1 + sizeof inbuf; /* exactly one warning :-) */
1564.             return -1;
1565.         }
1566.         inbufp = 0;
1567.     }
1568.     return inbuf[inbufp++];
1569. }
1570. 
1571. STATIC_OVL void
1572. zerocomp_minit()
1573. {
1574.     inbufsz = 0;
1575.     inbufp = 0;
1576.     inrunlength = -1;
1577. }
1578. 
1579. STATIC_OVL void
1580. zerocomp_mread(fd, buf, len)
1581. int fd;
1582. genericptr_t buf;
1583. register unsigned len;
1584. {
1585.     /*register int readlen = 0;*/
1586.     if (fd < 0)
1587.         error("Restore error; mread attempting to read file %d.", fd);
1588.     mreadfd = fd;
1589.     while (len--) {
1590.         if (inrunlength > 0) {
1591.             inrunlength--;
1592.             *(*((char **) &buf))++ = '\0';
1593.         } else {
1594.             register short ch = zerocomp_mgetc();
1595.             if (ch < 0) {
1596.                 restoreprocs.mread_flags = -1;
1597.                 return;
1598.             }
1599.             if ((*(*(char **) &buf)++ = (char) ch) == RLESC) {
1600.                 inrunlength = zerocomp_mgetc();
1601.             }
1602.         }
1603.         /*readlen++;*/
1604.     }
1605. }
1606. #endif /* ZEROCOMP */
1607. 
1608. STATIC_OVL void
1609. def_minit()
1610. {
1611.     return;
1612. }
1613. 
1614. STATIC_OVL void
1615. def_mread(fd, buf, len)
1616. register int fd;
1617. register genericptr_t buf;
1618. register unsigned int len;
1619. {
1620.     register int rlen;
1621. #if defined(BSD) || defined(ULTRIX)
1622. #define readLenType int
1623. #else /* e.g. SYSV, __TURBOC__ */
1624. #define readLenType unsigned
1625. #endif
1626. 
1627.     rlen = read(fd, buf, (readLenType) len);
1628.     if ((readLenType) rlen != (readLenType) len) {
1629.         if (restoreprocs.mread_flags == 1) { /* means "return anyway" */
1630.             restoreprocs.mread_flags = -1;
1631.             return;
1632.         } else {
1633.             pline("Read %d instead of %u bytes.", rlen, len);
1634.             if (restoring) {
1635.                 (void) nhclose(fd);
1636.                 (void) delete_savefile();
1637.                 error("Error restoring old game.");
1638.             }
1639.             panic("Error reading level file.");
1640.         }
1641.     }
1642. }
1643. 
1644. /*restore.c*/