Source:NetHack 5.0.0/src/timeout.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to timeout.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/timeout.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 5.0	timeout.c	$NHDT-Date: 1776080125 2026/04/13 03:35:25 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.207 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Robert Patrick Rankin, 2018. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. 
8. #ifndef SFCTOOL
9. staticfn void stoned_dialogue(void);
10. staticfn void vomiting_dialogue(void);
11. staticfn void sleep_dialogue(void);
12. staticfn void choke_dialogue(void);
13. staticfn void levitation_dialogue(void);
14. staticfn void slime_dialogue(void);
15. staticfn void slimed_to_death(struct kinfo *) NO_NNARGS;
16. staticfn void sickness_dialogue(void);
17. staticfn void phaze_dialogue(void);
18. staticfn void region_dialogue(void);
19. staticfn void done_timeout(int, int);
20. staticfn void slip_or_trip(void);
21. staticfn void see_lamp_flicker(struct obj *, const char *) NONNULLPTRS;
22. staticfn void lantern_message(struct obj *) NONNULLARG1;
23. staticfn void cleanup_burn(ANY_P *, long) NONNULLARG1;
24. 
25. /* used by wizard mode #timeout and #wizintrinsic; order by 'interest'
26.    for timeout countdown, where most won't occur in normal play */
27. static const struct propname {
28.     int prop_num;
29.     const char *prop_name;
30. } propertynames[] = {
31.     { INVULNERABLE, "invulnerable" },
32.     { STONED, "petrifying" },
33.     { SLIMED, "becoming slime" },
34.     { STRANGLED, "strangling" },
35.     { SICK, "fatally sick" },
36.     { STUNNED, "stunned" },
37.     { CONFUSION, "confused" },
38.     { HALLUC, "hallucinating" },
39.     { BLINDED, "blinded" },
40.     { DEAF, "deafness" },
41.     { VOMITING, "vomiting" },
42.     { GLIB, "slippery fingers" },
43.     { WOUNDED_LEGS, "wounded legs" },
44.     { SLEEPY, "sleepy" },
45.     { TELEPORT, "teleporting" },
46.     { POLYMORPH, "polymorphing" },
47.     { LEVITATION, "levitating" },
48.     { FAST, "very fast" }, /* timed 'FAST' is very fast */
49.     { CLAIRVOYANT, "clairvoyant" },
50.     { DETECT_MONSTERS, "monster detection" },
51.     { SEE_INVIS, "see invisible" },
52.     { INVIS, "invisible" },
53.     /* temporary acid resistance and stone resistance can come from eating */
54.     { ACID_RES, "acid resistance" },
55.     { STONE_RES, "stoning resistance" },
56.     /* timed displacement is possible via eating a displacer beast corpse */
57.     { DISPLACED, "displaced" },
58.     /* timed pass-walls is a potential prayer result if surrounded by stone
59.        with nowhere to be safely teleported to */
60.     { PASSES_WALLS, "pass thru walls" },
61.     /* likewise for magical breathing vs poison gas regions */
62.     { MAGICAL_BREATHING, "magical breathing" },
63.     /* timed fire resistance and water walking are possible in explore mode
64.        (as well as in wizard mode) after life-saving in lava if it fails to
65.        teleport the hero to safety and player declines to die */
66.     { WWALKING, "water walking" },
67.     { FIRE_RES, "fire resistance" },
68.     /*
69.      * Properties beyond here don't have timed values during normal play,
70.      * so there's not much point in trying to order them sensibly.
71.      * They're either on or off based on equipment, role, actions, &c,
72.      * but in wizard mode, #wizintrinsic can give them as timed effects.
73.      */
74.     { COLD_RES, "cold resistance" },
75.     { SLEEP_RES, "sleep resistance" },
76.     { DISINT_RES, "disintegration resistance" },
77.     { SHOCK_RES, "shock resistance" },
78.     { POISON_RES, "poison resistance" },
79.     { DRAIN_RES, "drain resistance" },
80.     { SICK_RES, "sickness resistance" },
81.     { ANTIMAGIC, "magic resistance" },
82.     { HALLUC_RES, "hallucination resistance" },
83.     { BLND_RES, "light-induced blindness resistance" },
84.     { FUMBLING, "fumbling" },
85.     { HUNGER, "voracious hunger" },
86.     { TELEPAT, "telepathic" },
87.     { WARNING, "warning" },
88.     { WARN_OF_MON, "warn: monster type or class" },
89.     { WARN_UNDEAD, "warn: undead" },
90.     { SEARCHING, "searching" },
91.     { INFRAVISION, "infravision" },
92.     { ADORNED, "adorned (+/- Cha)" },
93.     { STEALTH, "stealthy" },
94.     { AGGRAVATE_MONSTER, "monster aggravation" },
95.     { CONFLICT, "conflict" },
96.     { JUMPING, "jumping" },
97.     { TELEPORT_CONTROL, "teleport control" },
98.     { FLYING, "flying" },
99.     { SWIMMING, "swimming" },
100.     { SLOW_DIGESTION, "slow digestion" },
101.     { HALF_SPDAM, "half spell damage" },
102.     { HALF_PHDAM, "half physical damage" },
103.     { REGENERATION, "HP regeneration" },
104.     { ENERGY_REGENERATION, "energy regeneration" },
105.     { PROTECTION, "extra protection" },
106.     { PROT_FROM_SHAPE_CHANGERS, "protection from shape changers" },
107.     { POLYMORPH_CONTROL, "polymorph control" },
108.     { UNCHANGING, "unchanging" },
109.     { REFLECTING, "reflecting" },
110.     { FREE_ACTION, "free action" },
111.     { FIXED_ABIL, "fixed abilities" },
112.     { LIFESAVED, "life will be saved" },
113.     {  0, 0 },
114. };
115. 
116. const char *
117. property_by_index(int idx, int *propertynum)
118. {
119.     if (!IndexOkT(idx, propertynames))
120.         idx = SIZE(propertynames) - 1;
121. 
122.     if (propertynum)
123.         *propertynum = propertynames[idx].prop_num;
124.     return propertynames[idx].prop_name;
125. }
126. 
127. /* He is being petrified - dialogue by inmet!tower */
128. static NEARDATA const char *const stoned_texts[] = {
129.     "You are slowing down.",            /* 5 */
130.     "Your limbs are stiffening.",       /* 4 */
131.     "Your limbs have turned to stone.", /* 3 */
132.     "You have turned to stone.",        /* 2 */
133.     "You are a statue."                 /* 1 */
134. };
135. 
136. staticfn void
137. stoned_dialogue(void)
138. {
139.     long i = (Stoned & TIMEOUT);
140. 
141.     if (i > 0L && i <= SIZE(stoned_texts)) {
142.         char buf[BUFSZ];
143. 
144.         Strcpy(buf, stoned_texts[SIZE(stoned_texts) - i]);
145.         if (nolimbs(gy.youmonst.data) && strstri(buf, "limbs"))
146.             (void) strsubst(buf, "limbs", "extremities");
147.         urgent_pline("%s", buf);
148.     }
149.     switch ((int) i) {
150.     case 5: /* slowing down */
151.         HFast = 0L;
152.         if (gm.multi > 0)
153.             nomul(0);
154.         break;
155.     case 4: /* limbs stiffening */
156.         /* just one move left to save oneself so quit fiddling around;
157.            don't stop attempt to eat tin--might be lizard or acidic */
158.         if (!Popeye(STONED))
159.             stop_occupation();
160.         if (gm.multi > 0)
161.             nomul(0);
162.         break;
163.     case 3: /* limbs turned to stone */
164.         stop_occupation();
165.         nomul(-3); /* can't move anymore */
166.         gm.multi_reason = "getting stoned";
167.         gn.nomovemsg = You_can_move_again; /* not unconscious */
168.         /* "your limbs have turned to stone" so terminate wounded legs */
169.         if (Wounded_legs && !u.usteed)
170.             heal_legs(2);
171.         break;
172.     case 2: /* turned to stone */
173.         if ((HDeaf & TIMEOUT) > 0L && (HDeaf & TIMEOUT) < 5L)
174.             set_itimeout(&HDeaf, 5L); /* avoid Hear_again at tail end */
175.         /* if also vomiting or turning into slime, stop those (no messages) */
176.         if (Vomiting)
177.             make_vomiting(0L, FALSE);
178.         if (Slimed)
179.             make_slimed(0L, (char *) 0);
180.         break;
181.     default:
182.         break;
183.     }
184.     exercise(A_DEX, FALSE);
185. }
186. 
187. /* hero is getting sicker and sicker prior to vomiting */
188. static NEARDATA const char *const vomiting_texts[] = {
189.     "are feeling mildly nauseated.", /* 14 */
190.     "feel slightly confused.",       /* 11 */
191.     "can't seem to think straight.", /* 8 */
192.     "feel incredibly sick.",         /* 5 */
193.     "are about to vomit."            /* 2 */
194. };
195. 
196. staticfn void
197. vomiting_dialogue(void)
198. {
199.     const char *txt = 0;
200.     char buf[BUFSZ];
201.     long v = (Vomiting & TIMEOUT);
202. 
203.     /* note: nhtimeout() hasn't decremented timed properties for the
204.        current turn yet, so we use Vomiting-1 here */
205.     switch ((int) (v - 1L)) {
206.     case 14:
207.         txt = vomiting_texts[0];
208.         break;
209.     case 11:
210.         txt = vomiting_texts[1];
211.         if (strstri(txt, " confused") && Confusion)
212.             txt = strsubst(strcpy(buf, txt), " confused", " more confused");
213.         break;
214.     case 6:
215.         make_stunned((HStun & TIMEOUT) + (long) d(2, 4), FALSE);
216.         if (!Popeye(VOMITING))
217.             stop_occupation();
218.         FALLTHROUGH;
219.     /*FALLTHRU*/
220.     case 9:
221.         make_confused((HConfusion & TIMEOUT) + (long) d(2, 4), FALSE);
222.         if (gm.multi > 0)
223.             nomul(0);
224.         break;
225.     case 8:
226.         txt = vomiting_texts[2];
227.         if (strstri(txt, " think") && Stunned)
228.             txt = strsubst(strcpy(buf, txt), "can't seem to ", "can't ");
229.         break;
230.     case 5:
231.         txt = vomiting_texts[3];
232.         break;
233.     case 2:
234.         txt = vomiting_texts[4];
235.         if (cantvomit(gy.youmonst.data))
236.             txt = "gag uncontrollably.";
237.         else if (Hallucination)
238.             /* "hurl" is short for "hurl chunks" which is slang for
239.                relatively violent vomiting... */
240.             txt = "are about to hurl!";
241.         break;
242.     case 0:
243.         stop_occupation();
244.         if (!cantvomit(gy.youmonst.data)) {
245.             morehungry(20);
246.             /* case 2 used to be "You suddenly vomit!" but it wasn't sudden
247.                since you've just been through the earlier messages of the
248.                countdown, and it was still possible to move around between
249.                that message and "You can move again." (from vomit()'s
250.                nomul(-2)) with no intervening message; give one here to
251.                have more specific point at which hero became unable to move
252.                [vomit() issues its own message for the cantvomit() case
253.                and for the FAINTING-or-worse case where stomach is empty] */
254.             if (u.uhs < FAINTING)
255.                 You("%s!", !Hallucination ? "vomit" : "hurl chunks");
256.         }
257.         vomit();
258.         break;
259.     default:
260.         break;
261.     }
262.     if (txt)
263.         You1(txt);
264.     exercise(A_CON, FALSE);
265. }
266. 
267. staticfn void
268. sleep_dialogue(void)
269. {
270.     long i = (HSleepy & TIMEOUT);
271. 
272.     if (i == 4)
273.         You("yawn.");
274. }
275. 
276. DISABLE_WARNING_FORMAT_NONLITERAL   /* RESTORE is after slime_dialogue */
277. 
278. static NEARDATA const char *const choke_texts[] = {
279.     "You find it hard to breathe.",
280.     "You're gasping for air.",
281.     "You can no longer breathe.",
282.     "You're turning %s.",
283.     "You suffocate."
284. };
285. 
286. static NEARDATA const char *const choke_texts2[] = {
287.     "Your %s is becoming constricted.",
288.     "Your blood is having trouble reaching your brain.",
289.     "The pressure on your %s increases.",
290.     "Your consciousness is fading.",
291.     "You suffocate."
292. };
293. 
294. staticfn void
295. choke_dialogue(void)
296. {
297.     long i = (Strangled & TIMEOUT);
298. 
299.     if (i > 0 && i <= SIZE(choke_texts)) {
300.         if (Breathless || !rn2(50)) {
301.             urgent_pline(choke_texts2[SIZE(choke_texts2) - i],
302.                          body_part(NECK));
303.         } else {
304.             const char *str = choke_texts[SIZE(choke_texts) - i];
305. 
306.             if (strchr(str, '%'))
307.                 urgent_pline(str, hcolor(NH_BLUE));
308.             else
309.                 urgent_pline("%s", str);
310.             stop_occupation();
311.         }
312.     }
313.     exercise(A_STR, FALSE);
314. }
315. 
316. static NEARDATA const char *const sickness_texts[] = {
317.     "Your illness feels worse.",
318.     "Your illness is severe.",
319.     "You are at Death's door.",
320. };
321. 
322. staticfn void
323. sickness_dialogue(void)
324. {
325.     long j = (Sick & TIMEOUT), i = j / 2L;
326. 
327.     if (i > 0L && i <= SIZE(sickness_texts) && (j % 2) != 0) {
328.         char buf[BUFSZ], pronounbuf[40];
329. 
330.         Strcpy(buf, sickness_texts[SIZE(sickness_texts) - i]);
331.         /* change the message slightly for food poisoning */
332.         if ((u.usick_type & SICK_NONVOMITABLE) == 0)
333.             (void) strsubst(buf, "illness", "sickness");
334.         if (Hallucination && strstri(buf, "Death's door")) {
335.             /* youmonst: for Hallucination, mhe()'s mon argument isn't used */
336.             Strcpy(pronounbuf, mhe(&gy.youmonst));
337.             Sprintf(eos(buf), "  %s %s inviting you in.",
338.                     /* upstart() modifies its argument but vtense() doesn't
339.                        care whether or not that has already happened */
340.                     upstart(pronounbuf), vtense(pronounbuf, "are"));
341.         }
342.         urgent_pline("%s", buf);
343.     }
344.     exercise(A_CON, FALSE);
345. }
346. 
347. static NEARDATA const char *const levi_texts[] = {
348.     "You float slightly lower.",
349.     "You wobble unsteadily %s the %s."
350. };
351. 
352. staticfn void
353. levitation_dialogue(void)
354. {
355.     /* -1 because the last message comes via float_down() */
356.     long i = (((HLevitation & TIMEOUT) - 1L) / 2L);
357. 
358.     if (ELevitation)
359.         return;
360. 
361.     if (!ACCESSIBLE(levl[u.ux][u.uy].typ)
362.         && !is_pool_or_lava(u.ux,u.uy))
363.         return;
364. 
365.     if (((HLevitation & TIMEOUT) % 2L) && i > 0L && i <= SIZE(levi_texts)) {
366.         const char *s = levi_texts[SIZE(levi_texts) - i];
367. 
368.         if (strchr(s, '%')) {
369.             boolean danger = (is_pool_or_lava(u.ux, u.uy)
370.                               && !Is_waterlevel(&u.uz));
371. 
372.             urgent_pline(s, danger ? "over" : "in",
373.                          danger ? surface(u.ux, u.uy) : "air");
374.         } else
375.             pline1(s);
376.         stop_occupation();
377.     }
378. }
379. 
380. static NEARDATA const char *const slime_texts[] = {
381.     "You are turning a little %s.",   /* 5 */
382.     "Your limbs are getting oozy.",   /* 4 */
383.     "Your skin begins to peel away.", /* 3 */
384.     "You are turning into %s.",       /* 2 */
385.     "You have become %s."             /* 1 */
386. };
387. 
388. staticfn void
389. slime_dialogue(void)
390. {
391.     long t = (Slimed & TIMEOUT), i = t / 2L;
392. 
393.     if (t == 1L) {
394.         /* display as green slime during "You have become green slime."
395.            but don't worry about not being able to see self; if already
396.            mimicking something else at the time, implicitly be revealed */
397.         gy.youmonst.m_ap_type = M_AP_MONSTER;
398.         gy.youmonst.mappearance = PM_GREEN_SLIME;
399.         /* no message given when 't' is odd, so no automatic update of
400.            self; force one */
401.         newsym(u.ux, u.uy);
402.     }
403. 
404.     if ((t % 2L) != 0L && i >= 0L && i < SIZE(slime_texts)) {
405.         char buf[BUFSZ];
406. 
407.         Strcpy(buf, slime_texts[SIZE(slime_texts) - i - 1L]);
408.         if (nolimbs(gy.youmonst.data) && strstri(buf, "limbs"))
409.             (void) strsubst(buf, "limbs", "extremities");
410. 
411.         if (strchr(buf, '%')) {
412.             if (i == 4L) {  /* "you are turning green" */
413.                 if (!Blind) /* [what if you're already green?] */
414.                     urgent_pline(buf, hcolor(NH_GREEN));
415.             } else {
416.                 urgent_pline(buf, an(Hallucination ? rndmonnam(NULL)
417.                                                    : "green slime"));
418.             }
419.         } else {
420.             urgent_pline("%s", buf);
421.         }
422.     }
423. 
424.     switch (i) {
425.     case 3L:  /* limbs becoming oozy */
426.         HFast = 0L; /* lose intrinsic speed */
427.         if (!Popeye(SLIMED))
428.             stop_occupation();
429.         if (gm.multi > 0)
430.             nomul(0);
431.         break;
432.     case 2L: /* skin begins to peel */
433.         if ((HDeaf & TIMEOUT) > 0L && (HDeaf & TIMEOUT) < 5L)
434.             set_itimeout(&HDeaf, 5L); /* avoid Hear_again at tail end */
435.         break;
436.     case 1L: /* turning into slime */
437.         /* if also turning to stone, stop doing that (no message) */
438.         if (Stoned)
439.             make_stoned(0L, (char *) 0, KILLED_BY_AN, (char *) 0);
440.         break;
441.     }
442.     exercise(A_DEX, FALSE);
443. }
444. 
445. RESTORE_WARNING_FORMAT_NONLITERAL
446. 
447. void
448. burn_away_slime(void)
449. {
450.     if (Slimed) {
451.         make_slimed(0L, "The slime that covers you is burned away!");
452.     }
453. }
454. 
455. /* countdown timer for turning into green slime has run out; kill our hero */
456. staticfn void
457. slimed_to_death(struct kinfo *kptr)
458. {
459.     uchar save_mvflags;
460. 
461.     /* redundant: polymon() cures sliming when polying into green slime */
462.     if (Upolyd && gy.youmonst.data == &mons[PM_GREEN_SLIME]) {
463.         dealloc_killer(kptr);
464.         return;
465.     }
466.     /* more sure killer reason is set up */
467.     if (kptr && kptr->name[0]) {
468.         svk.killer.format = kptr->format;
469.         Strcpy(svk.killer.name, kptr->name);
470.     } else {
471.         svk.killer.format = NO_KILLER_PREFIX;
472.         Strcpy(svk.killer.name, "turned into green slime");
473.     }
474.     dealloc_killer(kptr);
475. 
476.     /*
477.      * Polymorph into a green slime, which might destroy some worn armor
478.      * (potentially affecting bones) and dismount from steed.
479.      * Can't be Unchanging; wouldn't have turned into slime if we were.
480.      * Despite lack of Unchanging, neither done() nor savelife() calls
481.      * rehumanize() if hero dies while polymorphed.
482.      * polymon() undoes the slime countdown's mimick-green-slime hack
483.      * but does not perform polyself()'s light source bookkeeping.
484.      * No longer need to manually increment uconduct.polyselfs to reflect
485.      * [formerly implicit] change of form; polymon() takes care of that.
486.      * Temporarily ungenocide if necessary.
487.      */
488.     if (emits_light(gy.youmonst.data))
489.         del_light_source(LS_MONSTER, monst_to_any(&gy.youmonst));
490.     save_mvflags = svm.mvitals[PM_GREEN_SLIME].mvflags;
491.     svm.mvitals[PM_GREEN_SLIME].mvflags = save_mvflags & ~G_GENOD;
492.     /* become a green slime; also resets youmonst.m_ap_type+.mappearance */
493.     (void) polymon(PM_GREEN_SLIME);
494.     svm.mvitals[PM_GREEN_SLIME].mvflags = save_mvflags;
495.     done_timeout(TURNED_SLIME, SLIMED);
496. 
497.     /* life-saved; even so, hero still has turned into green slime;
498.        player may have genocided green slimes after being infected */
499.     if ((svm.mvitals[PM_GREEN_SLIME].mvflags & G_GENOD) != 0) {
500.         char slimebuf[BUFSZ];
501. 
502.         svk.killer.format = KILLED_BY;
503.         Strcpy(svk.killer.name, "slimicide");
504.         /* vary the message depending upon whether life-save was due to
505.            amulet or due to declining to die in explore or wizard mode */
506.         Strcpy(slimebuf, "green slime has been genocided...");
507.         if (iflags.last_msg == PLNMSG_OK_DONT_DIE)
508.             /* follows "OK, so you don't die." and arg is second sentence */
509.             urgent_pline("Yes, you do.  %s", upstart(slimebuf));
510.         else
511.             /* follows "The medallion crumbles to dust." */
512.             urgent_pline("Unfortunately, %s", slimebuf);
513.         /* die again; no possibility of amulet this time */
514.         done(GENOCIDED); /* [should it be done_timeout(GENOCIDED, SLIMED)?] */
515.         /* could be life-saved again (only in explore or wizard mode)
516.            but green slimes are gone; just stay in current form */
517.     }
518.     return;
519. }
520. 
521. /* Intrinsic Passes_walls is temporary when your god is trying to fix
522.    all troubles and then TROUBLE_STUCK_IN_WALL calls safe_teleds() but
523.    it can't find anywhere to place you.  If that happens you get a small
524.    value for (HPasses_walls & TIMEOUT) to move somewhere yourself.
525.    Message given is "you feel much slimmer" as a joke hint that you can
526.    move between things which are closely packed--like the substance of
527.    solid rock! */
528. static NEARDATA const char *const phaze_texts[] = {
529.     "You start to feel bloated.",
530.     "You are feeling rather flabby.",
531. };
532. 
533. staticfn void
534. phaze_dialogue(void)
535. {
536.     long i = ((HPasses_walls & TIMEOUT) / 2L);
537. 
538.     if (EPasses_walls || (HPasses_walls & ~TIMEOUT))
539.         return;
540. 
541.     if (((HPasses_walls & TIMEOUT) % 2L) && i > 0L && i <= SIZE(phaze_texts))
542.         pline("%s", phaze_texts[SIZE(phaze_texts) - i]);
543. }
544. 
545. /* Similar to Passes_walls, if prayer tries to save hero from a poison
546.    gas region but can't, (HMagical_breathing & TIMEOUT) will be set to
547.    a small value.  Unlike Passes_walls, there's no joke message. */
548. static NEARDATA const char *const region_texts[] = {
549.     "You seem to have some trouble breathing.",
550.     "The air here seems foul.",
551. };
552. 
553. staticfn void
554. region_dialogue(void)
555. {
556.     boolean no_need_to_breathe, in_poison_gas_cloud;
557.     long r = (HMagical_breathing & TIMEOUT), i = r / 2L;
558. 
559.     /* might have poly'd into non-breather or moved out of gas cloud */
560.     HMagical_breathing &= ~TIMEOUT;
561.     no_need_to_breathe = Breathless;
562.     in_poison_gas_cloud = region_danger();
563.     HMagical_breathing |= r;
564.     if (no_need_to_breathe || !in_poison_gas_cloud)
565.         return;
566. 
567.     if ((r % 2L) && i > 0L && i <= SIZE(region_texts))
568.         pline("%s", region_texts[SIZE(region_texts) - i]);
569. }
570. 
571. /* when a status timeout is fatal, keep the status line indicator shown
572.    during end of game rundown (and potential dumplog);
573.    timeout has already counted down to 0 by the time we get here */
574. staticfn void
575. done_timeout(int how, int which)
576. {
577.     long *intrinsic_p = &u.uprops[which].intrinsic;
578. 
579.     *intrinsic_p |= I_SPECIAL; /* affects final disclosure */
580.     done(how);
581. 
582.     /* life-saved */
583.     *intrinsic_p &= ~I_SPECIAL;
584.     disp.botl = TRUE;
585. }
586. 
587. void
588. nh_timeout(void)
589. {
590.     struct prop *upp;
591.     struct kinfo *kptr;
592.     boolean was_flying;
593.     int sleeptime;
594.     int m_idx;
595.     int baseluck = (flags.moonphase == FULL_MOON) ? 1 : 0;
596. 
597.     if (flags.friday13)
598.         baseluck -= 1;
599. 
600.     if (svq.quest_status.killed_leader)
601.         baseluck -= 4;
602. 
603.     if (Role_if(PM_ARCHEOLOGIST) && uarmh && uarmh->otyp == FEDORA)
604.         baseluck += 1;
605. 
606.     if (u.uluck != baseluck
607.         && svm.moves % ((u.uhave.amulet || u.ugangr) ? 300 : 600) == 0) {
608.         /* Cursed luckstones stop bad luck from timing out; blessed luckstones
609.          * stop good luck from timing out; normal luckstones stop both;
610.          * neither is stopped if you don't have a luckstone.
611.          * Luck is based at 0 usually, +1 if a full moon and -1 on Friday 13th
612.          */
613.         int time_luck = stone_luck(FALSE);
614.         boolean nostone = !carrying(LUCKSTONE) && !stone_luck(TRUE);
615. 
616.         if (u.uluck > baseluck && (nostone || time_luck < 0))
617.             u.uluck--;
618.         else if (u.uluck < baseluck && (nostone || time_luck > 0))
619.             u.uluck++;
620.     }
621.     if (u.uinvulnerable)
622.         return; /* things past this point could kill you */
623.     if (Stoned)
624.         stoned_dialogue();
625.     if (Slimed)
626.         slime_dialogue();
627.     if (Vomiting)
628.         vomiting_dialogue();
629.     if (Strangled)
630.         choke_dialogue();
631.     if (Sick)
632.         sickness_dialogue();
633.     if (HLevitation & TIMEOUT)
634.         levitation_dialogue();
635.     if (HPasses_walls & TIMEOUT)
636.         phaze_dialogue();
637.     if (HMagical_breathing & TIMEOUT)
638.         region_dialogue();
639.     if (HSleepy & TIMEOUT)
640.         sleep_dialogue();
641.     if (u.mtimedone && !--u.mtimedone) {
642.         if (Unchanging)
643.             u.mtimedone = rnd(100 * gy.youmonst.data->mlevel + 1);
644.         else if (is_were(gy.youmonst.data))
645.             you_unwere(FALSE); /* if polycontrl, asks whether to rehumanize */
646.         else
647.             rehumanize();
648.     }
649.     if (u.ucreamed)
650.         u.ucreamed--;
651. 
652.     /* Dissipate spell-based protection. */
653.     if (u.usptime) {
654.         if (--u.usptime == 0 && u.uspellprot) {
655.             u.usptime = u.uspmtime;
656.             u.uspellprot--;
657.             find_ac();
658.             if (!Blind)
659.                 Norep("The %s haze around you %s.", hcolor(NH_GOLDEN),
660.                       u.uspellprot ? "becomes less dense" : "disappears");
661.         }
662.     }
663. 
664.     if (u.ugallop) {
665.         if (--u.ugallop == 0L && u.usteed)
666.             pline("%s stops galloping.", Monnam(u.usteed));
667.     }
668. 
669.     was_flying = Flying;
670.     for (upp = u.uprops; upp < u.uprops + SIZE(u.uprops); upp++)
671.         if ((upp->intrinsic & TIMEOUT) && !(--upp->intrinsic & TIMEOUT)) {
672.             kptr = find_delayed_killer((int) (upp - u.uprops));
673.             switch (upp - u.uprops) {
674.             case STONED:
675.                 if (kptr && kptr->name[0]) {
676.                     svk.killer.format = kptr->format;
677.                     Strcpy(svk.killer.name, kptr->name);
678.                 } else {
679.                     svk.killer.format = NO_KILLER_PREFIX;
680.                     Strcpy(svk.killer.name, "killed by petrification");
681.                 }
682.                 dealloc_killer(kptr);
683.                 /* (unlike sliming, you aren't changing form here) */
684.                 done_timeout(STONING, STONED);
685.                 break;
686.             case SLIMED:
687.                 slimed_to_death(kptr); /* done_timeout(TURNED_SLIME,SLIMED) */
688.                 break;
689.             case VOMITING:
690.                 make_vomiting(0L, TRUE);
691.                 break;
692.             case SICK:
693.                 /* hero might be able to bounce back from food poisoning,
694.                    but not other forms of illness */
695.                 if ((u.usick_type & SICK_NONVOMITABLE) == 0
696.                     && rn2(100) < ACURR(A_CON)) {
697.                     You("have recovered from your illness.");
698.                     make_sick(0, NULL, FALSE, SICK_ALL);
699.                     exercise(A_CON, FALSE);
700.                     adjattrib(A_CON, -1, 1);
701.                     break;
702.                 }
703.                 urgent_pline("You die from your illness.");
704.                 if (kptr && kptr->name[0]) {
705.                     svk.killer.format = kptr->format;
706.                     Strcpy(svk.killer.name, kptr->name);
707.                 } else {
708.                     svk.killer.format = KILLED_BY_AN;
709.                     svk.killer.name[0] = 0; /* take the default */
710.                 }
711.                 dealloc_killer(kptr);
712. 
713.                 if ((m_idx = name_to_mon(svk.killer.name,
714.                                          (int *) 0)) >= LOW_PM) {
715.                     if (type_is_pname(&mons[m_idx])) {
716.                         svk.killer.format = KILLED_BY;
717.                     } else if (mons[m_idx].geno & G_UNIQ) {
718.                         Strcpy(svk.killer.name, the(svk.killer.name));
719.                         svk.killer.format = KILLED_BY;
720.                     }
721.                 }
722.                 done_timeout(POISONING, SICK);
723.                 u.usick_type = 0;
724.                 break;
725.             case FAST:
726.                 if (!Very_fast)
727.                     You_feel("yourself slow down%s.",
728.                              Fast ? " a bit" : "");
729.                 break;
730.             case CONFUSION:
731.                 /* So make_confused works properly */
732.                 set_itimeout(&HConfusion, 1L);
733.                 make_confused(0L, TRUE);
734.                 if (!Confusion)
735.                     stop_occupation();
736.                 break;
737.             case STUNNED:
738.                 set_itimeout(&HStun, 1L);
739.                 make_stunned(0L, TRUE);
740.                 if (!Stunned)
741.                     stop_occupation();
742.                 break;
743.             case BLINDED: {
744.                 boolean was_blind = !!Blind;
745. 
746.                 set_itimeout(&HBlinded, 1L);
747.                 make_blinded(0L, TRUE);
748.                 if (was_blind && !Blind)
749.                     stop_occupation();
750.                 break;
751.             }
752.             case DEAF:
753.                 set_itimeout(&HDeaf, 1L);
754.                 make_deaf(0L, TRUE);
755.                 disp.botl = TRUE;
756.                 if (!Deaf)
757.                     stop_occupation();
758.                 break;
759.             case INVIS:
760.                 newsym(u.ux, u.uy);
761.                 if (!Invis && !BInvis && !Blind) {
762.                     You(!See_invisible
763.                             ? "are no longer invisible."
764.                             : "can no longer see through yourself.");
765.                     stop_occupation();
766.                 }
767.                 break;
768.             case SEE_INVIS:
769.                 set_mimic_blocking(); /* do special mimic handling */
770.                 see_monsters();       /* make invis mons appear */
771.                 newsym(u.ux, u.uy);   /* make self appear */
772.                 stop_occupation();
773.                 break;
774.             case WOUNDED_LEGS:
775.                 heal_legs(0);
776.                 stop_occupation();
777.                 break;
778.             case HALLUC:
779.                 set_itimeout(&HHallucination, 1L);
780.                 (void) make_hallucinated(0L, TRUE, 0L);
781.                 if (!Hallucination)
782.                     stop_occupation();
783.                 break;
784.             case SLEEPY:
785.                 if (unconscious() || Sleep_resistance) {
786.                     incr_itimeout(&HSleepy, rnd(100));
787.                 } else if (Sleepy) {
788.                     You("fall asleep.");
789.                     sleeptime = rnd(20);
790.                     fall_asleep(-sleeptime, TRUE);
791.                     incr_itimeout(&HSleepy, sleeptime + rnd(100));
792.                 }
793.                 break;
794.             case LEVITATION:
795.                 /* timed Levitation is ordinary, timed Flying is via
796.                    #wizintrinsic only; still, we want to avoid float_down()
797.                    reporting "you have stopped levitating and are now flying"
798.                    when both are timing out together; if that is about to
799.                    happen, end Flying early to skip feedback about it;
800.                    assumes Levitation is handled before Flying */
801.                 if ((HFlying & TIMEOUT) == 1L)
802.                     set_itimeout(&HFlying, 0L); /* bypass 'case FLYING' */
803.                 (void) float_down(I_SPECIAL | TIMEOUT, 0L);
804.                 break;
805.             case FLYING:
806.                 /* timed Flying is via #wizintrinsic only */
807.                 if (was_flying && !Flying) {
808.                     disp.botl = TRUE;
809.                     You("land.");
810.                     spoteffects(TRUE);
811.                 }
812.                 break;
813.             case ACID_RES:
814.                 if (!Acid_resistance) {
815.                     if (eating_dangerous_corpse(ACID_RES)) {
816.                         /* extend temporary acid resistance if in midst
817.                            of eating an acidic corpse; this will repeat
818.                            until eating is finished or interrupted */
819.                         set_itimeout(&u.uprops[ACID_RES].intrinsic, 1L);
820.                         break;
821.                     }
822.                     if (!Unaware)
823.                         You("no longer feel safe from acid.");
824.                 }
825.                 break;
826.             case STONE_RES:
827.                 if (!Stone_resistance) {
828.                     if (eating_dangerous_corpse(STONE_RES)) {
829.                         /* extend temporary stoning resistance if in midst
830.                            of eating a stoning corpse; this will repeat
831.                            until eating is finished or interrupted */
832.                         set_itimeout(&u.uprops[STONE_RES].intrinsic, 1L);
833.                         break;
834.                     }
835.                     if (!Unaware)
836.                         You("no longer feel secure from petrification.");
837.                     /* no-op if not wielding a cockatrice corpse;
838.                        uswapwep case is always a no-op because two-weapon
839.                        combat is only possible with two one-handed weapons
840.                        or weapon tools, not corpses */
841.                     wielding_corpse(uwep, (struct obj *) 0, FALSE);
842.                     wielding_corpse(uswapwep, (struct obj *) 0, FALSE);
843.                 }
844.                 break;
845.             case FIRE_RES:
846.                 /* timed fire resistance and timed water walking combine
847.                    as a way to survive lava after multiple life-saving
848.                    attempts fail to relocate hero; skip timeout message
849.                    if hero has acquired fire resistance in the meantime */
850.                 if (!Fire_resistance)
851.                     Your("temporary ability to survive burning has ended.");
852.                 break;
853.             case WWALKING:
854.                 /* [see fire resistance] */
855.                 if (!Wwalking)
856.                     Your("temporary ability to walk on liquid has ended.");
857.                 break;
858.             case DISPLACED:
859.                 if (!Displaced) /* give a message */
860.                     toggle_displacement((struct obj *) 0, 0L, FALSE);
861.                 break;
862.             case WARN_OF_MON:
863.                 /* timed Warn_of_mon is via #wizintrinsic only */
864.                 if (!Warn_of_mon) {
865.                     struct permonst *wptr = svc.context.warntype.species;
866. 
867.                     svc.context.warntype.species = (struct permonst *) 0;
868.                     svc.context.warntype.speciesidx = NON_PM;
869.                     if (wptr)
870.                         You("are no longer warned about %s.",
871.                             makeplural(wptr->pmnames[NEUTRAL]));
872.                 }
873.                 break;
874.             case PASSES_WALLS:
875.                 if (!Passes_walls) {
876.                     if (stuck_in_wall())
877.                         You_feel("hemmed in again.");
878.                     else
879.                         pline("You're back to your %s self again.",
880.                               !Upolyd ? "normal" : "unusual");
881.                 }
882.                 break;
883.             case MAGICAL_BREATHING:
884.                 if (!Breathless) {
885.                     if (region_danger())
886.                         You("cough%s",
887.                             Poison_resistance ? "." : " and spit blood!");
888.                 }
889.                 break;
890.             case STRANGLED:
891.                 svk.killer.format = KILLED_BY;
892.                 Strcpy(svk.killer.name,
893.                        (u.uburied) ? "suffocation" : "strangulation");
894.                 done_timeout(DIED, STRANGLED);
895.                 /* must be declining to die in explore|wizard mode;
896.                    treat like being cured of strangulation by prayer */
897.                 if (uamul && uamul->otyp == AMULET_OF_STRANGULATION) {
898.                     Your("amulet vanishes!");
899.                     useup(uamul);
900.                 }
901.                 break;
902.             case FUMBLING:
903.                 /* call this only when a move took place.  */
904.                 /* otherwise handle fumbling msgs locally. */
905.                 if (u.umoved && !(Levitation || Flying)) {
906.                     slip_or_trip();
907.                     nomul(-2);
908.                     gm.multi_reason = "fumbling";
909.                     gn.nomovemsg = "";
910.                     /* The more you are carrying the more likely you
911.                      * are to make noise when you fumble.  Adjustments
912.                      * to this number must be thoroughly play tested.
913.                      */
914.                     if ((inv_weight() > (WT_NOISY_INV * -1))) {
915.                         if (!Deaf)
916.                             You("make a lot of noise!");
917.                         wake_nearby(FALSE);
918.                     }
919.                 }
920.                 /* from outside means slippery ice; don't reset
921.                    counter if that's the only fumble reason */
922.                 HFumbling &= ~FROMOUTSIDE;
923.                 if (Fumbling)
924.                     incr_itimeout(&HFumbling, rnd(20));
925. 
926.                 if (iflags.defer_decor) {
927.                     /* 'mention_decor' was deferred for message sequencing
928.                        reasons; catch up now */
929.                     deferred_decor(FALSE);
930.                 }
931.                 break;
932.             case DETECT_MONSTERS:
933.                 see_monsters();
934.                 break;
935.             case GLIB:
936.                 make_glib(0); /* might update persistent inventory */
937.                 break;
938.             case PROT_FROM_SHAPE_CHANGERS:
939.                 /* timed Protection_from_shape_changers is via
940.                    #wizintrinsic only */
941.                 if (!Protection_from_shape_changers)
942.                     restartcham();
943.                 break;
944.             }
945.         }
946. 
947.     run_timers();
948. }
949. 
950. void
951. fall_asleep(int how_long, boolean wakeup_msg)
952. {
953.     stop_occupation();
954.     nomul(how_long);
955.     gm.multi_reason = "sleeping";
956. #if 0   /* this was broken; the fix for 'how_long' will result in changed
957.          * behavior for sounds that don't go through You_hear() so needs
958.          * testing */
959.     /* You_hear() produces "You dream that you hear ..." when sleeping;
960.        other sound messages will either honor or ignore Deaf */
961.     if (wakeup_msg && gm.multi == how_long) {
962.         /* caller can follow with a direct call to Hear_again() if
963.            there's a need to override this when wakeup_msg is true */
964.         /* 5.0: how_long is negative so wasn't actually incrementing the
965.            deafness timeout when it used to be passed as-is */
966.         incr_itimeout(&HDeaf, abs(how_long));
967.         disp.botl = TRUE;
968.         ga.afternmv = Hear_again; /* this won't give any messages */
969.     }
970. #endif
971.     /* early wakeup from combat won't be possible until next monster turn */
972.     u.usleep = svm.moves;
973.     gn.nomovemsg = wakeup_msg ? "You wake up." : You_can_move_again;
974. }
975. 
976. /* Attach an egg hatch timeout to the given egg.
977.  *      when = Time to hatch, usually only passed if re-creating an
978.  *             existing hatch timer. Pass 0L for random hatch time.
979.  */
980. void
981. attach_egg_hatch_timeout(struct obj *egg, long when)
982. {
983.     int i;
984. 
985.     /* stop previous timer, if any */
986.     (void) stop_timer(HATCH_EGG, obj_to_any(egg));
987. 
988.     /*
989.      * Decide if and when to hatch the egg.  The old hatch_it() code tried
990.      * once a turn from age 151 to 200 (inclusive), hatching if it rolled
991.      * a number x, 1<=x<=age, where x>150.  This yields a chance of
992.      * hatching > 99.9993%.  Mimic that here.
993.      */
994.     if (!when) {
995.         for (i = (MAX_EGG_HATCH_TIME - 50) + 1; i <= MAX_EGG_HATCH_TIME; i++)
996.             if (rnd(i) > 150) {
997.                 /* egg will hatch */
998.                 when = (long) i;
999.                 break;
1000.             }
1001.     }
1002.     if (when) {
1003.         (void) start_timer(when, TIMER_OBJECT, HATCH_EGG, obj_to_any(egg));
1004.     }
1005. }
1006. 
1007. /* prevent an egg from ever hatching */
1008. void
1009. kill_egg(struct obj *egg)
1010. {
1011.     /* stop previous timer, if any */
1012.     (void) stop_timer(HATCH_EGG, obj_to_any(egg));
1013. }
1014. 
1015. /* timer callback routine: hatch the given egg */
1016. void
1017. hatch_egg(anything *arg, long timeout)
1018. {
1019.     struct obj *egg;
1020.     struct monst *mon, *mon2;
1021.     coord cc;
1022.     coordxy x, y;
1023.     boolean yours, silent, knows_egg = FALSE;
1024.     boolean cansee_hatchspot = FALSE;
1025.     int i, mnum, hatchcount = 0;
1026. 
1027.     egg = arg->a_obj;
1028.     /* sterilized while waiting */
1029.     if (egg->corpsenm == NON_PM)
1030.         return;
1031. 
1032.     mon = mon2 = (struct monst *) 0;
1033.     mnum = big_to_little(egg->corpsenm);
1034.     /* The identity of one's father is learned, not innate */
1035.     yours = (egg->spe || (!flags.female && carried(egg) && !rn2(2)));
1036.     silent = (timeout != svm.moves); /* hatched while away */
1037. 
1038.     /* only can hatch when in INVENT, FLOOR, MINVENT;
1039.        get_obj_location() will fail for MIGRATING, also for CONTAINED
1040.        and BURIED when the flags for those aren't included in the call */
1041.     if (get_obj_location(egg, &x, &y, 0)) {
1042.         hatchcount = rnd((int) egg->quan);
1043.         cansee_hatchspot = cansee(x, y) && !silent;
1044.         if (!(mons[mnum].geno & G_UNIQ)
1045.             && !(svm.mvitals[mnum].mvflags & (G_GENOD | G_EXTINCT))) {
1046.             for (i = hatchcount; i > 0; i--) {
1047.                 if (!enexto(&cc, x, y, &mons[mnum])
1048.                     || !(mon = makemon(&mons[mnum], cc.x, cc.y,
1049.                                        NO_MINVENT | MM_NOMSG)))
1050.                     break;
1051.                 /* tame if your own egg hatches while you're on the
1052.                    same dungeon level, or any dragon egg which hatches
1053.                    while it's in your inventory */
1054.                 if ((yours && !silent)
1055.                     || (carried(egg) && mon->data->mlet == S_DRAGON)) {
1056.                     if (tamedog(mon, (struct obj *) 0, FALSE)) {
1057.                         if (carried(egg) && mon->data->mlet != S_DRAGON)
1058.                             mon->mtame = 20;
1059.                     }
1060.                 }
1061.                 if (svm.mvitals[mnum].mvflags & G_EXTINCT)
1062.                     break;  /* just made last one */
1063.                 mon2 = mon; /* in case makemon() fails on 2nd egg */
1064.             }
1065.             if (!mon)
1066.                 mon = mon2;
1067.             hatchcount -= i;
1068.             egg->quan -= (long) hatchcount;
1069.         }
1070. #if 0
1071.     /*
1072.      * We could possibly hatch while migrating, but the code isn't
1073.      * set up for it...
1074.      */
1075.     } else if (obj->where == OBJ_MIGRATING) {
1076.         /*
1077.          * We can do several things.  The first ones that come to
1078.          * mind are:
1079.          * + Create the hatched monster then place it on the migrating
1080.          *   mons list.  This is tough because all makemon() is made
1081.          *   to place the monster as well. Makemon() also doesn't lend
1082.          *   itself well to splitting off a "not yet placed" subroutine.
1083.          * + Mark the egg as hatched, then place the monster when we
1084.          *   place the migrating objects.
1085.          * + Or just kill any egg which gets sent to another level.
1086.          *   Falling is the usual reason such transportation occurs.
1087.          */
1088.         cansee_hatchspot = FALSE;
1089.         mon = ???;
1090. #endif
1091.     }
1092. 
1093.     if (mon) {
1094.         char monnambuf[BUFSZ], carriedby[BUFSZ];
1095.         boolean siblings = (hatchcount > 1), redraw = FALSE;
1096. 
1097.         if (cansee_hatchspot) {
1098.             /* [bug?  m_monnam() yields accurate monster type
1099.                regardless of hallucination] */
1100.             Sprintf(monnambuf, "%s%s", siblings ? "some " : "",
1101.                     siblings ? makeplural(m_monnam(mon)) : an(m_monnam(mon)));
1102.             /* we don't learn the egg type here because learning
1103.                an egg type requires either seeing the egg hatch
1104.                or being familiar with the egg already,
1105.                as well as being able to see the resulting
1106.                monster, checked below
1107.             */
1108.         }
1109.         switch (egg->where) {
1110.         case OBJ_INVENT:
1111.             knows_egg = TRUE; /* true even if you are blind */
1112.             if (!cansee_hatchspot)
1113.                 You_feel("%s %s from your pack!", something,
1114.                          locomotion(mon->data, "drop"));
1115.             else
1116.                 You_see("%s %s out of your pack!", monnambuf,
1117.                         locomotion(mon->data, "drop"));
1118.             if (yours) {
1119.                 pline("%s %s %s like \"%s%s\"",
1120.                       siblings ? "Their" : "Its",
1121.                       ing_suffix(cry_sound(mon)),
1122.                       (is_silent(mon->data) || Deaf) ? "seems" : "sounds",
1123.                       flags.female ? "mommy" : "daddy", egg->spe ? "." : "?");
1124.             } else if (mon->data->mlet == S_DRAGON && !Deaf) {
1125.                 SetVoice(mon, 0, 80, 0);
1126.                 verbalize("Gleep!"); /* Mything eggs :-) */
1127.             }
1128.             break;
1129. 
1130.         case OBJ_FLOOR:
1131.             if (cansee_hatchspot) {
1132.                 knows_egg = TRUE;
1133.                 You_see("%s hatch.", monnambuf);
1134.                 redraw = TRUE; /* update egg's map location */
1135.             }
1136.             break;
1137. 
1138.         case OBJ_MINVENT:
1139.             if (cansee_hatchspot) {
1140.                 /* egg carrying monster might be invisible */
1141.                 mon2 = egg->ocarry;
1142.                 if (canseemon(mon2)
1143.                     && (!mon2->wormno || cansee(mon2->mx, mon2->my))) {
1144.                     Sprintf(carriedby, "%s pack",
1145.                             s_suffix(a_monnam(mon2)));
1146.                     knows_egg = TRUE;
1147.                 } else if (is_pool(mon->mx, mon->my)) {
1148.                     Strcpy(carriedby, "empty water");
1149.                 } else {
1150.                     Strcpy(carriedby, "thin air");
1151.                 }
1152.                 You_see("%s %s out of %s!", monnambuf,
1153.                         locomotion(mon->data, "drop"), carriedby);
1154.             }
1155.             break;
1156. #if 0
1157.         case OBJ_MIGRATING:
1158.             break;
1159. #endif
1160.         default:
1161.             impossible("egg hatched where? (%d)", (int) egg->where);
1162.             break;
1163.         }
1164. 
1165.         if (cansee_hatchspot && knows_egg)
1166.             learn_egg_type(mnum);
1167. 
1168.         if (egg->quan > 0) {
1169.             /* still some eggs left; we didn't split the stack, just
1170.                subtracted from quantity so weight needs to be updated;
1171.                for remainder of stack, add a new, short hatch timer */
1172.             attach_egg_hatch_timeout(egg, (long) rnd(12));
1173.             /* container_weight(arg) updates arg->owt, and if contained,
1174.                its enclosing container arg->ocontainer (recursively)
1175.                [egg won't be contained due to conditions imposed above] */
1176.             container_weight(egg);
1177.         } else if (carried(egg)) {
1178.             useup(egg);
1179.         } else {
1180.             /* free egg here because we use it above */
1181.             obj_extract_self(egg);
1182.             obfree(egg, (struct obj *) 0);
1183.             if ((mon = m_at(x,y)) && !hideunder(mon) && cansee(x, y))
1184.                 redraw = TRUE;
1185.         }
1186.         if (redraw)
1187.             newsym(x, y);
1188.     }
1189. }
1190. 
1191. /* Learn to recognize eggs of the given type. */
1192. void
1193. learn_egg_type(int mnum)
1194. {
1195.     /* baby monsters hatch from grown-up eggs */
1196.     mnum = little_to_big(mnum);
1197.     svm.mvitals[mnum].mvflags |= MV_KNOWS_EGG;
1198.     /* we might have just learned about other eggs being carried */
1199.     update_inventory();
1200. }
1201. 
1202. /* Attach a fig_transform timeout to the given figurine. */
1203. void
1204. attach_fig_transform_timeout(struct obj *figurine)
1205. {
1206.     int i;
1207. 
1208.     /* stop previous timer, if any */
1209.     (void) stop_timer(FIG_TRANSFORM, obj_to_any(figurine));
1210. 
1211.     /*
1212.      * Decide when to transform the figurine.
1213.      */
1214.     i = rnd(9000) + 200;
1215.     /* figurine will transform */
1216.     (void) start_timer((long) i, TIMER_OBJECT, FIG_TRANSFORM,
1217.                        obj_to_any(figurine));
1218. }
1219. 
1220. /* give a fumble message */
1221. staticfn void
1222. slip_or_trip(void)
1223. {
1224.     struct obj *otmp = vobj_at(u.ux, u.uy), *otmp2, *saddle;
1225.     const char *what;
1226.     char buf[BUFSZ];
1227.     boolean on_foot = !u.usteed;
1228. 
1229.     if (otmp && on_foot && !u.uinwater && is_pool(u.ux, u.uy))
1230.         otmp = 0;
1231. 
1232.     if (otmp && on_foot) { /* trip over something in particular */
1233.         /*
1234.           If there is only one item, it will have just been named
1235.           during the move, so refer to it by pronoun; otherwise,
1236.           if the top item has been or can be seen, refer to it by
1237.           name; if not, look for rocks to trip over; trip over
1238.           anonymous "something" if there aren't any rocks.
1239.         */
1240.         what = (iflags.last_msg == PLNMSG_ONE_ITEM_HERE)
1241.                 ? ((otmp->quan == 1L) ? "it"
1242.                       : Hallucination ? "they" : "them")
1243.                 : (otmp->dknown || !Blind)
1244.                       ? doname(otmp)
1245.                       : ((otmp2 = sobj_at(ROCK, u.ux, u.uy)) == 0
1246.                              ? something
1247.                              : (otmp2->quan == 1L ? "a rock" : "some rocks"));
1248.         if (Hallucination) {
1249.             what = strcpy(buf, what);
1250.             buf[0] = highc(buf[0]);
1251.             pline("Egads!  %s bite%s your %s!", what,
1252.                   (!otmp || otmp->quan == 1L) ? "s" : "", body_part(FOOT));
1253.         } else {
1254.             You("trip over %s.", what);
1255.         }
1256.         if (!uarmf && otmp->otyp == CORPSE
1257.             && touch_petrifies(&mons[otmp->corpsenm]) && !Stone_resistance) {
1258.             Sprintf(svk.killer.name, "tripping over %s corpse",
1259.                     an(mons[otmp->corpsenm].pmnames[NEUTRAL]));
1260.             instapetrify(svk.killer.name);
1261.         }
1262.     } else if ((HFumbling & FROMOUTSIDE) || (is_ice(u.ux, u.uy) && !rn2(3))) {
1263.         /* is fumbling from ice alone? */
1264.         boolean ice_only = !(EFumbling || (HFumbling & ~FROMOUTSIDE));
1265. 
1266.         pline("%s %s %s the ice.",
1267.               u.usteed ? upstart(x_monnam(u.usteed, ARTICLE_THE, (char *) 0,
1268.                                           SUPPRESS_SADDLE, FALSE))
1269.                        : "You",
1270.               /* "steed": arbitrary value that will use third person verb
1271.                  regardless of what u.usteed might be named, as opposed to
1272.                  "you" (second person, which won't have final 's' added) */
1273.               vtense(u.usteed ? "steed" : "you", rn2(2) ? "slip" : "slide"),
1274.               /* sometimes slipping due to ice occurs during turn that hero
1275.                  has just moved off the ice; phrase things differently then */
1276.               is_ice(u.ux, u.uy) ? "on" : "off");
1277.         /* fumbling outside of ice while mounted always causes the hero to
1278.            fall from the saddle (unless it is cursed), so to avoid a
1279.            counterintuitive effect where ice makes riding _less_ hazardous,
1280.            unconditionally dismount if fumbling is from a non-ice source */
1281.         if (!on_foot
1282.             && ((saddle = which_armor(u.usteed, W_SADDLE)) == 0
1283.                 || !saddle->cursed)
1284.             && (!ice_only || !rn2(3))) {
1285.             You("lose your balance.");
1286.             dismount_steed(DISMOUNT_FELL);
1287.         } else if (!rn2(10 + ACURR(A_DEX))) {
1288.             /* Maybe slip in a random direction.  This takes place after
1289.                the hero has already changed location.  If the hero is
1290.                in grid bug form, only allow forward hurtle, otherwise a
1291.                90 degree orthogonal one after the step would make the
1292.                combined move appear to be a single diagonal step. */
1293.             if (!NODIAG(u.umonnum))
1294.                 confdir(TRUE); /* sets u.dx and u.dy */
1295.             /* Only hurtle if the random direction won't move hero back
1296.                to same spot where this move started. */
1297.             if (u.ux + u.dx != u.ux0 || u.uy + u.dy != u.uy0)
1298.                 hurtle(u.dx, u.dy, 1, FALSE);
1299.         }
1300.     } else {
1301.         if (on_foot) {
1302.             switch (rn2(4)) {
1303.             case 1:
1304.                 You("trip over your own %s.",
1305.                     Hallucination ? "elbow" : makeplural(body_part(FOOT)));
1306.                 break;
1307.             case 2:
1308.                 You("slip %s.",
1309.                     Hallucination ? "on a banana peel" : "and nearly fall");
1310.                 break;
1311.             case 3:
1312.                 You("flounder.");
1313.                 break;
1314.             default:
1315.                 You("stumble.");
1316.                 break;
1317.             }
1318. 
1319.         /* mounted; saddle should never end up being Null here;
1320.            don't fall off when it happens to be cursed */
1321.         } else if ((saddle = which_armor(u.usteed, W_SADDLE)) == 0
1322.                    || !saddle->cursed) {
1323.             switch (rn2(4)) {
1324.             case 1:
1325.                 Your("%s slip out of the stirrups.",
1326.                      makeplural(body_part(FOOT)));
1327.                 break;
1328.             case 2:
1329.                 You("let go of the reins.");
1330.                 break;
1331.             case 3:
1332.                 You("bang into the saddle-horn.");
1333.                 break;
1334.             default:
1335.                 You("slide to one side of the saddle.");
1336.                 break;
1337.             }
1338.             dismount_steed(DISMOUNT_FELL);
1339.         }
1340.     }
1341. }
1342. 
1343. /* Print a lamp flicker message with tailer.  Only called if seen. */
1344. staticfn void
1345. see_lamp_flicker(struct obj *obj, const char *tailer)
1346. {
1347.     switch (obj->where) {
1348.     case OBJ_INVENT:
1349.     case OBJ_MINVENT:
1350.         pline("%s flickers%s.", Yname2(obj), tailer);
1351.         break;
1352.     case OBJ_FLOOR:
1353.         You_see("%s flicker%s.", an(xname(obj)), tailer);
1354.         break;
1355.     }
1356. }
1357. 
1358. /* Print a dimming message for brass lanterns.  Only called if seen. */
1359. staticfn void
1360. lantern_message(struct obj *obj)
1361. {
1362.     /* from adventure */
1363.     switch (obj->where) {
1364.     case OBJ_INVENT:
1365.         Your("lantern is getting dim.");
1366.         if (Hallucination)
1367.             pline("Batteries have not been invented yet.");
1368.         break;
1369.     case OBJ_FLOOR:
1370.         You_see("a lantern getting dim.");
1371.         break;
1372.     case OBJ_MINVENT:
1373.         pline("%s lantern is getting dim.", s_suffix(Monnam(obj->ocarry)));
1374.         break;
1375.     }
1376. }
1377. 
1378. /*
1379.  * Timeout callback for objects that are burning. E.g. lamps, candles.
1380.  * See begin_burn() for meanings of obj->age and obj->spe.
1381.  */
1382. void
1383. burn_object(anything *arg, long timeout)
1384. {
1385.     struct obj *obj = arg->a_obj;
1386.     boolean canseeit, many, menorah, need_newsym, need_invupdate, bytouch;
1387.     coordxy x, y;
1388.     char whose[BUFSZ];
1389. 
1390.     menorah = obj->otyp == CANDELABRUM_OF_INVOCATION;
1391.     many = menorah ? obj->spe > 1 : obj->quan > 1L;
1392. 
1393.     /* timeout while away */
1394.     if (timeout != svm.moves) {
1395.         long how_long = svm.moves - timeout;
1396. 
1397.         if (how_long >= obj->age) {
1398.             obj->age = 0;
1399.             end_burn(obj, FALSE);
1400. 
1401.             if (menorah) {
1402.                 obj->spe = 0; /* no more candles */
1403.                 obj->owt = weight(obj);
1404.             } else if (Is_candle(obj) || obj->otyp == POT_OIL) {
1405.                 struct monst *mtmp = NULL;
1406. 
1407.                 if (obj->where == OBJ_FLOOR)
1408.                     mtmp = m_at(obj->ox, obj->oy);
1409.                 /* get rid of candles and burning oil potions;
1410.                    we know this object isn't carried by hero,
1411.                    nor is it migrating */
1412.                 obj_extract_self(obj);
1413.                 obfree(obj, (struct obj *) 0);
1414.                 obj = (struct obj *) 0;
1415.                 if (mtmp)
1416.                     maybe_unhide_at(mtmp->mx, mtmp->my);
1417.             }
1418. 
1419.         } else {
1420.             obj->age -= how_long;
1421.             begin_burn(obj, TRUE);
1422.         }
1423.         return;
1424.     }
1425. 
1426.     /* only interested in INVENT, FLOOR, and MINVENT */
1427.     if (get_obj_location(obj, &x, &y, 0)) {
1428.         canseeit = !Blind && cansee(x, y);
1429.         /* set `whose[]' to be "Your " or "Fred's " or "The goblin's " */
1430.         (void) Shk_Your(whose, obj);
1431.     } else {
1432.         canseeit = FALSE;
1433.     }
1434.     /* when carrying the light source, you can feel the heat from lit lamp
1435.        or candle so you'll be notified when it burns out even if blind at
1436.        the time; brass lantern doesn't radiate sufficient heat for that
1437.        (however, inventory formatting drops "(lit)" so player can tell) */
1438.     bytouch = (obj->where == OBJ_INVENT && obj->otyp != BRASS_LANTERN);
1439.     need_newsym = need_invupdate = FALSE;
1440. 
1441.     /* obj->age is the age remaining at this point.  */
1442.     switch (obj->otyp) {
1443.     case POT_OIL:
1444.         /* this should only be called when we run out */
1445.         if (canseeit) {
1446.             switch (obj->where) {
1447.             case OBJ_INVENT:
1448.                 need_invupdate = TRUE;
1449.                 FALLTHROUGH;
1450.                 /*FALLTHRU*/
1451.             case OBJ_MINVENT:
1452.                 pline("%spotion of oil has burnt away.", whose);
1453.                 break;
1454.             case OBJ_FLOOR:
1455.                 You_see("a burning potion of oil go out.");
1456.                 need_newsym = TRUE;
1457.                 break;
1458.             }
1459.         }
1460.         end_burn(obj, FALSE); /* turn off light source */
1461.         if (carried(obj)) {
1462.             useupall(obj);
1463.         } else {
1464.             /* clear migrating obj's destination code before obfree
1465.                to avoid false complaint of deleting worn item */
1466.             if (obj->where == OBJ_MIGRATING)
1467.                 obj->owornmask = 0L;
1468.             obj_extract_self(obj);
1469.             obfree(obj, (struct obj *) 0);
1470.         }
1471.         obj = (struct obj *) 0;
1472.         break;
1473. 
1474.     case BRASS_LANTERN:
1475.     case OIL_LAMP:
1476.         switch ((int) obj->age) {
1477.         case 150:
1478.         case 100:
1479.         case 50:
1480.             if (canseeit) {
1481.                 if (obj->otyp == BRASS_LANTERN)
1482.                     lantern_message(obj);
1483.                 else
1484.                     see_lamp_flicker(obj,
1485.                                      obj->age == 50L ? " considerably" : "");
1486.             }
1487.             break;
1488. 
1489.         case 25:
1490.             if (canseeit) {
1491.                 if (obj->otyp == BRASS_LANTERN) {
1492.                     lantern_message(obj);
1493.                 } else {
1494.                     switch (obj->where) {
1495.                     case OBJ_INVENT:
1496.                     case OBJ_MINVENT:
1497.                         pline("%s seems about to go out.", Yname2(obj));
1498.                         break;
1499.                     case OBJ_FLOOR:
1500.                         You_see("%s about to go out.", an(xname(obj)));
1501.                         break;
1502.                     }
1503.                 }
1504.             }
1505.             break;
1506. 
1507.         case 0:
1508.             /* even if blind you'll know if holding it */
1509.             if (canseeit || bytouch) {
1510.                 switch (obj->where) {
1511.                 case OBJ_INVENT:
1512.                     need_invupdate = TRUE;
1513.                     FALLTHROUGH;
1514.                     /*FALLTHRU*/
1515.                 case OBJ_MINVENT:
1516.                     if (obj->otyp == BRASS_LANTERN)
1517.                         pline("%slantern has run out of power.", whose);
1518.                     else
1519.                         pline("%s has gone out.", Yname2(obj));
1520.                     break;
1521.                 case OBJ_FLOOR:
1522.                     if (obj->otyp == BRASS_LANTERN)
1523.                         You_see("a lantern run out of power.");
1524.                     else
1525.                         You_see("%s go out.", an(xname(obj)));
1526.                     break;
1527.                 }
1528.             }
1529.             end_burn(obj, FALSE);
1530.             break;
1531. 
1532.         default:
1533.             /*
1534.              * Someone added fuel to the lamp while it was
1535.              * lit. Just fall through and let begin_burn()
1536.              * handle the new age.
1537.              */
1538.             break;
1539.         }
1540. 
1541.         if (obj->age)
1542.             begin_burn(obj, TRUE);
1543. 
1544.         break;
1545. 
1546.     case CANDELABRUM_OF_INVOCATION:
1547.     case TALLOW_CANDLE:
1548.     case WAX_CANDLE:
1549.         switch (obj->age) {
1550.         case 75:
1551.             if (canseeit)
1552.                 switch (obj->where) {
1553.                 case OBJ_INVENT:
1554.                 case OBJ_MINVENT:
1555.                     pline("%s%scandle%s getting short.", whose,
1556.                           menorah ? "candelabrum's " : "",
1557.                           many ? "s are" : " is");
1558.                     break;
1559.                 case OBJ_FLOOR:
1560.                     You_see("%scandle%s getting short.",
1561.                             menorah ? "a candelabrum's " : many ? "some "
1562.                                                                 : "a ",
1563.                             many ? "s" : "");
1564.                     break;
1565.                 }
1566.             break;
1567. 
1568.         case 15:
1569.             if (canseeit)
1570.                 switch (obj->where) {
1571.                 case OBJ_INVENT:
1572.                 case OBJ_MINVENT:
1573.                     pline("%s%scandle%s flame%s flicker%s low!", whose,
1574.                           menorah ? "candelabrum's " : "", many ? "s'" : "'s",
1575.                           many ? "s" : "", many ? "" : "s");
1576.                     break;
1577.                 case OBJ_FLOOR:
1578.                     You_see("%scandle%s flame%s flicker low!",
1579.                             menorah ? "a candelabrum's " : many ? "some "
1580.                                                                 : "a ",
1581.                             many ? "s'" : "'s", many ? "s" : "");
1582.                     break;
1583.                 }
1584.             break;
1585. 
1586.         case 0:
1587.             /* we know even if blind and in our inventory */
1588.             if (canseeit || bytouch) {
1589.                 if (menorah) {
1590.                     switch (obj->where) {
1591.                     case OBJ_INVENT:
1592.                         need_invupdate = TRUE;
1593.                         FALLTHROUGH;
1594.                         /*FALLTHRU*/
1595.                     case OBJ_MINVENT:
1596.                         pline("%scandelabrum's flame%s.", whose,
1597.                               many ? "s die" : " dies");
1598.                         break;
1599.                     case OBJ_FLOOR:
1600.                         You_see("a candelabrum's flame%s die.",
1601.                                 many ? "s" : "");
1602.                         break;
1603.                     }
1604.                 } else {
1605.                     switch (obj->where) {
1606.                     case OBJ_INVENT:
1607.                         /* no need_invupdate for update_inventory() necessary;
1608.                            useupall() -> freeinv() handles it */
1609.                            FALLTHROUGH;
1610.                         /*FALLTHRU*/
1611.                     case OBJ_MINVENT:
1612.                         pline("%s %s consumed!", Yname2(obj),
1613.                               many ? "are" : "is");
1614.                         break;
1615.                     case OBJ_FLOOR:
1616.                         /*
1617.                           You see some wax candles consumed!
1618.                           You see a wax candle consumed!
1619.                          */
1620.                         You_see("%s%s consumed!", many ? "some " : "",
1621.                                 many ? xname(obj) : an(xname(obj)));
1622.                         need_newsym = TRUE;
1623.                         break;
1624.                     }
1625. 
1626.                     /* post message */
1627.                     pline(Hallucination
1628.                               ? (many ? "They shriek!" : "It shrieks!")
1629.                               : Blind ? "" : (many ? "Their flames die."
1630.                                                    : "Its flame dies."));
1631.                 }
1632.             }
1633.             end_burn(obj, FALSE);
1634. 
1635.             if (menorah) {
1636.                 obj->spe = 0; /* no candles */
1637.                 obj->owt = weight(obj);
1638.                 if (carried(obj))
1639.                     need_invupdate = TRUE;
1640.             } else {
1641.                 if (carried(obj)) {
1642.                     useupall(obj);
1643.                 } else {
1644.                     boolean onfloor = (obj->where == OBJ_FLOOR);
1645. 
1646.                     /* clear migrating obj's destination code
1647.                        so obfree won't think this item is worn */
1648.                     if (obj->where == OBJ_MIGRATING)
1649.                         obj->owornmask = 0L;
1650.                     obj_extract_self(obj);
1651.                     if (onfloor)
1652.                         maybe_unhide_at(x, y);
1653.                     obfree(obj, (struct obj *) 0);
1654.                 }
1655.                 obj = (struct obj *) 0;
1656.             }
1657.             break; /* case [age ==] 0 */
1658. 
1659.         default:
1660.             /*
1661.              * Someone added fuel (candles) to the menorah while
1662.              * it was lit. Just fall through and let begin_burn()
1663.              * handle the new age.
1664.              */
1665.             break;
1666.         }
1667. 
1668.         if (obj && obj->age)
1669.             begin_burn(obj, TRUE);
1670.         break; /* case [otyp ==] candelabrum|tallow_candle|wax_candle */
1671. 
1672.     default:
1673.         impossible("burn_object: unexpected obj %s", xname(obj));
1674.         break;
1675.     }
1676.     if (need_newsym)
1677.         newsym(x, y);
1678.     if (need_invupdate)
1679.         update_inventory();
1680. }
1681. 
1682. /*
1683.  * Start a burn timeout on the given object. If not "already lit" then
1684.  * create a light source for the vision system.  There had better not
1685.  * be a burn already running on the object.
1686.  *
1687.  * Magic lamps stay lit as long as there's a genie inside, so don't start
1688.  * a timer.
1689.  *
1690.  * Burn rules:
1691.  *      potions of oil, lamps & candles:
1692.  *              age = # of turns of fuel left
1693.  *              spe = <unused>
1694.  *      magic lamps:
1695.  *              age = <unused>
1696.  *              spe = 0 not lightable, 1 lightable forever
1697.  *      candelabrum:
1698.  *              age = # of turns of fuel left
1699.  *              spe = # of candles
1700.  *
1701.  * Once the burn begins, the age will be set to the amount of fuel
1702.  * remaining _once_the_burn_finishes_.  If the burn is terminated
1703.  * early then fuel is added back.
1704.  *
1705.  * This use of age differs from the use of age for corpses and eggs.
1706.  * For the latter items, age is when the object was created, so we
1707.  * know when it becomes "bad".
1708.  *
1709.  * This is a "silent" routine - it should not print anything out.
1710.  */
1711. void
1712. begin_burn(struct obj *obj, boolean already_lit)
1713. {
1714.     int radius = 3;
1715.     long turns = 0;
1716.     boolean do_timer = TRUE;
1717. 
1718.     if (obj->age == 0 && obj->otyp != MAGIC_LAMP && !artifact_light(obj))
1719.         return;
1720. 
1721.     switch (obj->otyp) {
1722.     case MAGIC_LAMP:
1723.         obj->lamplit = 1;
1724.         do_timer = FALSE;
1725.         break;
1726. 
1727.     case POT_OIL:
1728.         turns = obj->age;
1729.         if (obj->odiluted)
1730.             turns = (3L * turns + 2L) / 4L;
1731.         radius = 1; /* very dim light */
1732.         break;
1733. 
1734.     case BRASS_LANTERN:
1735.     case OIL_LAMP:
1736.         /* magic times are 150, 100, 50, 25, and 0 */
1737.         if (obj->age > 150L)
1738.             turns = obj->age - 150L;
1739.         else if (obj->age > 100L)
1740.             turns = obj->age - 100L;
1741.         else if (obj->age > 50L)
1742.             turns = obj->age - 50L;
1743.         else if (obj->age > 25L)
1744.             turns = obj->age - 25L;
1745.         else
1746.             turns = obj->age;
1747.         break;
1748. 
1749.     case CANDELABRUM_OF_INVOCATION:
1750.     case TALLOW_CANDLE:
1751.     case WAX_CANDLE:
1752.         /* magic times are 75, 15, and 0 */
1753.         if (obj->age > 75L)
1754.             turns = obj->age - 75L;
1755.         else if (obj->age > 15L)
1756.             turns = obj->age - 15L;
1757.         else
1758.             turns = obj->age;
1759.         radius = candle_light_range(obj);
1760.         break;
1761. 
1762.     default:
1763.         /* [ALI] Support artifact light sources */
1764.         if (artifact_light(obj)) {
1765.             obj->lamplit = 1;
1766.             do_timer = FALSE;
1767.             radius = arti_light_radius(obj);
1768.         } else {
1769.             impossible("begin burn: unexpected %s", xname(obj));
1770.             turns = obj->age;
1771.         }
1772.         break;
1773.     }
1774. 
1775.     if (do_timer) {
1776.         if (start_timer(turns, TIMER_OBJECT, BURN_OBJECT, obj_to_any(obj))) {
1777.             obj->lamplit = 1;
1778.             obj->age -= turns;
1779.             if (carried(obj) && !already_lit)
1780.                 update_inventory();
1781.         } else {
1782.             obj->lamplit = 0;
1783.         }
1784.     } else {
1785.         if (carried(obj) && !already_lit)
1786.             update_inventory();
1787.     }
1788. 
1789.     if (obj->lamplit && !already_lit) {
1790.         coordxy x, y;
1791. 
1792.         if (get_obj_location(obj, &x, &y, CONTAINED_TOO | BURIED_TOO))
1793.             new_light_source(x, y, radius, LS_OBJECT, obj_to_any(obj));
1794.         else
1795.             impossible("begin_burn: can't get obj position");
1796.     }
1797. }
1798. 
1799. /*
1800.  * Stop a burn timeout on the given object if timer attached.  Darken
1801.  * light source.
1802.  */
1803. void
1804. end_burn(struct obj *obj, boolean timer_attached)
1805. {
1806.     if (!obj->lamplit) {
1807.         impossible("end_burn: obj %s not lit", xname(obj));
1808.         return;
1809.     }
1810. 
1811.     if (obj->otyp == MAGIC_LAMP || artifact_light(obj))
1812.         timer_attached = FALSE;
1813. 
1814.     if (!timer_attached) {
1815.         /* [DS] Cleanup explicitly, since timer cleanup won't happen */
1816.         del_light_source(LS_OBJECT, obj_to_any(obj));
1817.         obj->lamplit = 0;
1818.         if (obj->where == OBJ_INVENT)
1819.             update_inventory();
1820.     } else if (!stop_timer(BURN_OBJECT, obj_to_any(obj)))
1821.         impossible("end_burn: obj %s not timed!", xname(obj));
1822. }
1823. 
1824. /*
1825.  * Cleanup a burning object if timer stopped.
1826.  */
1827. staticfn void
1828. cleanup_burn(anything *arg, long expire_time)
1829. {
1830.     struct obj *obj = arg->a_obj;
1831. 
1832.     if (!obj->lamplit) {
1833.         impossible("cleanup_burn: obj %s not lit", xname(obj));
1834.         return;
1835.     }
1836. 
1837.     del_light_source(LS_OBJECT, obj_to_any(obj));
1838.     /* restore unused time */
1839.     obj->age += expire_time - svm.moves;
1840.     obj->lamplit = 0;
1841. 
1842.     if (obj->where == OBJ_INVENT)
1843.         update_inventory();
1844. }
1845. 
1846. void
1847. do_storms(void)
1848. {
1849.     int nstrike;
1850.     int x, y;
1851.     int dirx, diry;
1852.     int count;
1853. 
1854.     /* no lightning if not stormy level or too often, even then */
1855.     if (!svl.level.flags.stormy || rn2(8))
1856.         return;
1857. 
1858.     /* the number of strikes is 8-log2(nstrike) */
1859.     for (nstrike = rnd(64); nstrike <= 64; nstrike *= 2) {
1860.         count = 0;
1861.         do {
1862.             x = rnd(COLNO - 1);
1863.             y = rn2(ROWNO);
1864.         } while (++count < 100 && levl[x][y].typ != CLOUD);
1865. 
1866.         if (count < 100) {
1867.             dirx = rn2(3) - 1;
1868.             diry = rn2(3) - 1;
1869.             if (dirx != 0 || diry != 0) {
1870.                 /* BZ_M_SPELL(BZ_OFS_AD(AD_ELEC)): monster LIGHTNING spell */
1871.                 gb.buzzer = 0; /* unspecified attacker */
1872.                 buzz(BZ_M_SPELL(BZ_OFS_AD(AD_ELEC)), 8, x, y, dirx, diry);
1873.             }
1874.         }
1875.     }
1876. 
1877.     if (levl[u.ux][u.uy].typ == CLOUD) {
1878.         /* Inside a cloud during a thunderstorm is deafening. */
1879.         /* Even if already deaf, we sense the thunder's vibrations. */
1880.         Soundeffect(se_kaboom_boom_boom, 80);
1881.         pline("Kaboom!!!  Boom!!  Boom!!");
1882.         incr_itimeout(&HDeaf, rn1(20, 30));
1883.         disp.botl = TRUE;
1884.         if (!u.uinvulnerable) {
1885.             stop_occupation();
1886.             nomul(-3);
1887.             gm.multi_reason = "hiding from thunderstorm";
1888.             gn.nomovemsg = 0;
1889.         }
1890.     } else
1891.         You_hear("a rumbling noise.");
1892. }
1893. 
1894. /* -------------------------------------------------------------------------
1895.  */
1896. /*
1897.  * Generic Timeout Functions.
1898.  *
1899.  * Interface:
1900.  *
1901.  * General:
1902.  *  boolean start_timer(long timeout,short kind,short func_index,
1903.  *                      anything *arg)
1904.  *      Start a timer of kind 'kind' that will expire at time
1905.  *      svm.moves+'timeout'.  Call the function at 'func_index'
1906.  *      in the timeout table using argument 'arg'.  Return TRUE if
1907.  *      a timer was started.  This places the timer on a list ordered
1908.  *      "sooner" to "later".  If an object, increment the object's
1909.  *      timer count.
1910.  *
1911.  *  long stop_timer(short func_index, anything *arg)
1912.  *      Stop a timer specified by the (func_index, arg) pair.  This
1913.  *      assumes that such a pair is unique.  Return the time the
1914.  *      timer would have gone off.  If no timer is found, return 0.
1915.  *      If an object, decrement the object's timer count.
1916.  *
1917.  *  long peek_timer(short func_index, anything *arg)
1918.  *      Return time specified timer will go off (0 if no such timer).
1919.  *
1920.  *  void run_timers(void)
1921.  *      Call timers that have timed out.
1922.  *
1923.  * Save/Restore:
1924.  *  void save_timers(NHFILE *, int range)
1925.  *      Save all timers of range 'range'.  Range is either global
1926.  *      or local.  Global timers follow game play, local timers
1927.  *      are saved with a level.  Object and monster timers are
1928.  *      saved using their respective ids instead of pointers.
1929.  *
1930.  *  void restore_timers(NHFILE *, int range, long adjust)
1931.  *      Restore timers of range 'range'.  If from a ghost pile,
1932.  *      adjust the timeout by 'adjust'.  The object and monster
1933.  *      ids are not restored until later.
1934.  *
1935.  *  void relink_timers(boolean ghostly)
1936.  *      Relink all object and monster timers that had been saved
1937.  *      using their object's or monster's id number.
1938.  *
1939.  * Object Specific:
1940.  *  void obj_move_timers(struct obj *src, struct obj *dest)
1941.  *      Reassign all timers from src to dest.
1942.  *
1943.  *  void obj_split_timers(struct obj *src, struct obj *dest)
1944.  *      Duplicate all timers assigned to src and attach them to dest.
1945.  *
1946.  *  void obj_stop_timers(struct obj *obj)
1947.  *      Stop all timers attached to obj.
1948.  *
1949.  *  boolean obj_has_timer(struct obj *object, short timer_type)
1950.  *      Check whether object has a timer of type timer_type.
1951.  */
1952. 
1953. staticfn const char *kind_name(short);
1954. staticfn void print_queue(winid, timer_element *);
1955. staticfn void insert_timer(timer_element *);
1956. staticfn timer_element *remove_timer(timer_element **, short, ANY_P *);
1957. staticfn void write_timer(NHFILE *, timer_element *);
1958. staticfn boolean mon_is_local(struct monst *);
1959. staticfn boolean timer_is_local(timer_element *);
1960. staticfn int maybe_write_timer(NHFILE *, int, boolean);
1961. 
1962. /* If defined, then include names when printing out the timer queue */
1963. #define VERBOSE_TIMER
1964. 
1965. typedef struct {
1966.     timeout_proc f, cleanup;
1967. #ifdef VERBOSE_TIMER
1968.     const char *name;
1969. #define TTAB(a, b, c) { a, b, c }
1970. #else
1971. #define TTAB(a, b, c) { a, b } /* ignore c for !VERBOSE_TIMER */
1972. #endif
1973. } ttable;
1974. 
1975. /*
1976.  * Table of timeout functions, listed in order of enum timeout_types:
1977.  */
1978. static const ttable timeout_funcs[NUM_TIME_FUNCS] = {
1979.     /* object timers */
1980.     TTAB(rot_organic, (timeout_proc) 0, "rot_organic"),
1981.     TTAB(rot_corpse, (timeout_proc) 0, "rot_corpse"),
1982.     TTAB(revive_mon, (timeout_proc) 0, "revive_mon"),
1983.     TTAB(zombify_mon, (timeout_proc) 0, "zombify_mon"),
1984.     TTAB(burn_object, cleanup_burn, "burn_object"),
1985.     TTAB(hatch_egg, (timeout_proc) 0, "hatch_egg"),
1986.     TTAB(fig_transform, (timeout_proc) 0, "fig_transform"),
1987.     TTAB(shrink_glob, (timeout_proc) 0, "shrink_glob"),
1988.     /* level timers */
1989.     TTAB(melt_ice_away, (timeout_proc) 0, "melt_ice_away"),
1990.     /* currently no monster or global timers */
1991. };
1992. #undef TTAB
1993. 
1994. staticfn const char *
1995. kind_name(short kind)
1996. {
1997.     switch (kind) {
1998.     case TIMER_NONE:
1999.         impossible("no timer type");
2000.         return "none";
2001.     case TIMER_LEVEL:
2002.         return "level";
2003.     case TIMER_GLOBAL:
2004.         return "global";
2005.     case TIMER_OBJECT:
2006.         return "object";
2007.     case TIMER_MONSTER:
2008.         return "monster";
2009.     }
2010.     return "unknown";
2011. }
2012. 
2013. staticfn void
2014. print_queue(winid win, timer_element *base)
2015. {
2016.     timer_element *curr;
2017.     char buf[BUFSZ];
2018. 
2019.     if (!base) {
2020.         putstr(win, 0, " <empty>");
2021.     } else {
2022.         putstr(win, 0, "timeout  id   kind   call");
2023.         for (curr = base; curr; curr = curr->next) {
2024. #ifdef VERBOSE_TIMER
2025.             Sprintf(buf, " %4ld   %4ld  %-6s %s(%s)", curr->timeout,
2026.                     (long) curr->tid, kind_name(curr->kind),
2027.                     timeout_funcs[curr->func_index].name,
2028.                     fmt_ptr((genericptr_t) curr->arg.a_void));
2029. #else
2030.             Sprintf(buf, " %4ld   %4ld  %-6s #%d(%s)", curr->timeout,
2031.                     curr->tid, kind_name(curr->kind), curr->func_index,
2032.                     fmt_ptr((genericptr_t) curr->arg.a_void));
2033. #endif
2034.             putstr(win, 0, buf);
2035.         }
2036.     }
2037. }
2038. 
2039. /* the #timeout command */
2040. int
2041. wiz_timeout_queue(void)
2042. {
2043.     winid win;
2044.     char buf[BUFSZ];
2045.     const char *propname;
2046.     long intrinsic;
2047.     int i, p, count, longestlen, ln, specindx = 0;
2048. 
2049.     win = create_nhwindow(NHW_MENU); /* corner text window */
2050.     if (win == WIN_ERR)
2051.         return ECMD_OK;
2052. 
2053.     Sprintf(buf, "Current time = %ld.", svm.moves);
2054.     putstr(win, 0, buf);
2055.     putstr(win, 0, "");
2056.     putstr(win, 0, "Active timeout queue:");
2057.     putstr(win, 0, "");
2058.     print_queue(win, gt.timer_base);
2059. 
2060.     /* Timed properties:
2061.      * check every one; the majority can't obtain temporary timeouts in
2062.      * normal play but those can be forced via the #wizintrinsic command.
2063.      */
2064.     count = longestlen = 0;
2065.     for (i = 0; (propname = propertynames[i].prop_name) != 0; ++i) {
2066.         p = propertynames[i].prop_num;
2067.         intrinsic = u.uprops[p].intrinsic;
2068.         if (intrinsic & TIMEOUT) {
2069.             ++count;
2070.             if ((ln = (int) strlen(propname)) > longestlen)
2071.                 longestlen = ln;
2072.         }
2073.         if (specindx == 0 && p == COLD_RES) /* was FIRE_RES but has changed */
2074.             specindx = i;
2075.     }
2076.     putstr(win, 0, "");
2077.     if (!count) {
2078.         putstr(win, 0, "No timed properties.");
2079.     } else {
2080.         putstr(win, 0, "Timed properties:");
2081.         putstr(win, 0, "");
2082.         for (i = 0; (propname = propertynames[i].prop_name) != 0; ++i) {
2083.             p = propertynames[i].prop_num;
2084.             intrinsic = u.uprops[p].intrinsic;
2085.             if (intrinsic & TIMEOUT) {
2086.                 if (specindx > 0 && i >= specindx) {
2087.                     putstr(win, 0, " -- settable via #wizintrinsic only --");
2088.                     specindx = 0;
2089.                 }
2090.                 /* timeout value can be up to 16777215 (0x00ffffff) but
2091.                    width of 4 digits should result in values lining up
2092.                    almost all the time (if/when they don't, it won't
2093.                    look nice but the information will still be accurate) */
2094.                 Sprintf(buf, " %*s %4ld", -longestlen, propname,
2095.                         (intrinsic & TIMEOUT));
2096.                 putstr(win, 0, buf);
2097.             }
2098.         }
2099.     }
2100.     if (u.uswldtim) {
2101.         putstr(win, 0, "");
2102.         /* decremented when engulfer makes a move, so can last longer than
2103.            the number of turns reported if engulfer is slow */
2104.         Sprintf(buf, "Swallow countdown is %u.", u.uswldtim);
2105.         putstr(win, 0, buf);
2106.     }
2107.     if (u.uinvault) {
2108.         putstr(win, 0, "");
2109.         Sprintf(buf, "Vault counter is %d.", u.uinvault);
2110.         putstr(win, 0, buf);
2111.     }
2112.     if (any_visible_region()) {
2113.         visible_region_summary(win);
2114.     }
2115.     if (svl.level.flags.stasis_until >= svm.moves) {
2116.         putstr(win, 0, "");
2117.         Sprintf(buf, "Level is no-teleport for %ld %s.",
2118.                 svl.level.flags.stasis_until - svm.moves + 1L,
2119.                 (svl.level.flags.stasis_until - svm.moves > 0L)
2120.                   ? "turns" : "more turn");
2121.         putstr(win, 0, buf);
2122.     }
2123.     display_nhwindow(win, FALSE);
2124.     destroy_nhwindow(win);
2125. 
2126.     return ECMD_OK;
2127. }
2128. 
2129. void
2130. timer_sanity_check(void)
2131. {
2132.     timer_element *curr;
2133.     unsigned long t_id;
2134.     coordxy x, y;
2135. 
2136.     for (curr = gt.timer_base; curr; curr = curr->next) {
2137.         t_id = curr->tid;
2138.         switch (curr->kind) {
2139.         case TIMER_OBJECT: {
2140.             /* TODO? verify that the timer type is attached to applicable
2141.                object (egg for hatch, glob for shrink, and so forth) */
2142.             struct obj *obj = curr->arg.a_obj, *top;
2143.             char *obj_adr = fmt_ptr((genericptr_t) obj);
2144.             int owhere = obj->where;
2145. 
2146.             if (obj->timed == 0) {
2147.                 impossible("timer sanity: untimed obj %s, timer %lu",
2148.                            obj_adr, t_id);
2149.             }
2150.             x = y = 0;
2151.             /* if obj is in a container, possibly a nested one, figure out
2152.                where the outermost container is */
2153.             for (top = obj; top; top = top->ocontainer)
2154.                 if ((owhere = top->where) != OBJ_CONTAINED)
2155.                     break;
2156.             assert(top != NULL);
2157.             if (owhere == OBJ_MIGRATING
2158.                 || (owhere == OBJ_MINVENT && !mon_is_local(top->ocarry))) {
2159.                 /* migrating directly or carried by migrating monster */
2160.                 ; /* not able to validate location so skip checks */
2161.             } else if (!get_obj_location(obj, &x, &y,
2162.                                          CONTAINED_TOO | BURIED_TOO)) {
2163.                 /* free? or on a shop's used-up bill? */
2164.                 impossible(
2165.                     "timer sanity: can't locate obj %s [where=%d], timer %lu",
2166.                            obj_adr, obj->where, t_id);
2167.             } else if (!isok(x, y)) {
2168.                 impossible(
2169.               "timer sanity: obj %s [where=%d] located at <%d,%d>, timer %lu",
2170.                            obj_adr, obj->where, x, y, t_id);
2171.             }
2172.             break;
2173.         }
2174.         case TIMER_MONSTER:
2175.             impossible("timer sanity: unexpected monster timer %lu", t_id);
2176.             break;
2177.         case TIMER_LEVEL: {
2178.             long lwhere = curr->arg.a_long;
2179. 
2180.             x = (coordxy) ((lwhere >> 16) & 0xFFFF);
2181.             y = (coordxy) (lwhere & 0xFFFF);
2182.             if (isok(x, y)) {
2183.                 /* replicate isok() in order to convince static analysis
2184.                    that the decoding via '& 0xFFFF' hasn't produced a value
2185.                    too big for levl[][] and that the cast to a narrower type
2186.                    hasn't intruded on the sign bit to yield a negative value;
2187.                    the analyzer isn't aware that isok() filters such things */
2188.                 assert(x > 0 && x < COLNO && y >= 0 && y < ROWNO);
2189. 
2190.                 if (curr->func_index == MELT_ICE_AWAY && !is_ice(x, y)
2191.                     /* the terrain under the span of an open drawbridge might
2192.                        be frozen moat; is_ice() only checks for that when
2193.                        the drawbridge is closed (and terrain here would be
2194.                        DRAWBRIGE_UP) */
2195.                     && !(levl[x][y].typ == DRAWBRIDGE_DOWN
2196.                          && (levl[x][y].drawbridgemask & DB_UNDER) == DB_ICE))
2197.                     impossible(
2198.                          "timer sanity: melt timer %lu on non-ice %d <%d,%d>",
2199.                                t_id, levl[x][y].typ, x, y);
2200.             } else {
2201.                 impossible("timer sanity: spot timer %lu at <%d,%d>",
2202.                            t_id, x, y);
2203.             }
2204.             break;
2205.         }
2206.         case TIMER_GLOBAL:
2207.             impossible("timer sanity: unexpected global timer %lu", t_id);
2208.             break;
2209.         default:
2210.             impossible("timer sanity: unknown timer %lu, type: %d",
2211.                        t_id, curr->kind);
2212.             break;
2213.         }
2214.     }
2215. }
2216. 
2217. /*
2218.  * Pick off timeout elements from the global queue and call their functions.
2219.  * Do this until their time is less than or equal to the move count.
2220.  */
2221. void
2222. run_timers(void)
2223. {
2224.     timer_element *curr;
2225. 
2226.     /*
2227.      * Always use the first element.  Elements may be added or deleted at
2228.      * any time.  The list is ordered; we are done when the first element
2229.      * is in the future.
2230.      */
2231.     while (gt.timer_base && gt.timer_base->timeout <= svm.moves) {
2232.         curr = gt.timer_base;
2233.         gt.timer_base = curr->next;
2234. 
2235.         if (curr->kind == TIMER_OBJECT)
2236.             (curr->arg.a_obj)->timed--;
2237.         (*timeout_funcs[curr->func_index].f)(&curr->arg, curr->timeout);
2238.         (void) memset((genericptr_t) curr, 0, sizeof(timer_element));
2239.         free((genericptr_t) curr);
2240.     }
2241. }
2242. 
2243. /*
2244.  * Start a timer.  Return TRUE if successful.
2245.  */
2246. boolean
2247. start_timer(
2248.     long when,
2249.     short kind,
2250.     short func_index,
2251.     anything *arg)
2252. {
2253.     timer_element *gnu, *dup;
2254. 
2255.     if (kind <= TIMER_NONE || kind >= NUM_TIMER_KINDS
2256.         || func_index < 0 || func_index >= NUM_TIME_FUNCS)
2257.         panic("start_timer (%s: %d)", kind_name(kind), (int) func_index);
2258. 
2259.     /* fail if <arg> already has a <func_index> timer running */
2260.     for (dup = gt.timer_base; dup; dup = dup->next)
2261.         if (dup->kind == kind
2262.             && dup->func_index == func_index
2263.             && dup->arg.a_void == arg->a_void)
2264.             break;
2265.     if (dup) {
2266.         char idbuf[QBUFSZ];
2267. 
2268. #ifdef VERBOSE_TIMER
2269.         Sprintf(idbuf, "%s timer", timeout_funcs[func_index].name);
2270. #else
2271.         Sprintf(idbuf, "%s timer (%d)", kind_name(kind), (int) func_index);
2272. #endif
2273.         impossible("Attempted to start duplicate %s, aborted.", idbuf);
2274.         return FALSE;
2275.     }
2276. 
2277.     gnu = (timer_element *) alloc(sizeof *gnu);
2278.     (void) memset((genericptr_t) gnu, 0, sizeof *gnu);
2279.     gnu->next = 0;
2280.     gnu->tid = svt.timer_id++;
2281.     gnu->timeout = svm.moves + when;
2282.     gnu->kind = kind;
2283.     gnu->needs_fixup = 0;
2284.     gnu->func_index = func_index;
2285.     gnu->arg = *arg;
2286.     insert_timer(gnu);
2287. 
2288.     if (kind == TIMER_OBJECT) /* increment object's timed count */
2289.         (arg->a_obj)->timed++;
2290. 
2291.     return TRUE;
2292. }
2293. 
2294. /*
2295.  * Remove the timer from the current list and free it up.  Return the time
2296.  * remaining until it would have gone off, 0 if not found.
2297.  */
2298. long
2299. stop_timer(short func_index, anything *arg)
2300. {
2301.     timeout_proc cleanup_func;
2302.     timer_element *doomed;
2303.     long timeout;
2304. 
2305.     doomed = remove_timer(&gt.timer_base, func_index, arg);
2306. 
2307.     if (doomed) {
2308.         timeout = doomed->timeout;
2309.         if (doomed->kind == TIMER_OBJECT)
2310.             (arg->a_obj)->timed--;
2311.         if ((cleanup_func = timeout_funcs[doomed->func_index].cleanup) != 0)
2312.             (*cleanup_func)(arg, timeout);
2313.         (void) memset((genericptr_t) doomed, 0, sizeof(timer_element));
2314.         free((genericptr_t) doomed);
2315.         return (timeout - svm.moves);
2316.     }
2317.     return 0L;
2318. }
2319. 
2320. /*
2321.  * Find the timeout of specified timer; return 0 if none.
2322.  */
2323. long
2324. peek_timer(short type, anything *arg)
2325. {
2326.     timer_element *curr;
2327. 
2328.     for (curr = gt.timer_base; curr; curr = curr->next) {
2329.         if (curr->func_index == type && curr->arg.a_void == arg->a_void)
2330.             return curr->timeout;
2331.     }
2332.     return 0L;
2333. }
2334. 
2335. /*
2336.  * Move all object timers from src to dest, leaving src untimed.
2337.  */
2338. void
2339. obj_move_timers(struct obj *src, struct obj *dest)
2340. {
2341.     int count;
2342.     timer_element *curr;
2343. 
2344.     for (count = 0, curr = gt.timer_base; curr; curr = curr->next)
2345.         if (curr->kind == TIMER_OBJECT && curr->arg.a_obj == src) {
2346.             curr->arg.a_obj = dest;
2347.             dest->timed++;
2348.             count++;
2349.         }
2350.     if (count != src->timed)
2351.         panic("obj_move_timers");
2352.     src->timed = 0;
2353. }
2354. 
2355. /*
2356.  * Find all object timers and duplicate them for the new object "dest".
2357.  */
2358. void
2359. obj_split_timers(struct obj *src, struct obj *dest)
2360. {
2361.     timer_element *curr, *next_timer = 0;
2362. 
2363.     for (curr = gt.timer_base; curr; curr = next_timer) {
2364.         next_timer = curr->next; /* things may be inserted */
2365.         if (curr->kind == TIMER_OBJECT && curr->arg.a_obj == src) {
2366.             (void) start_timer(curr->timeout - svm.moves, TIMER_OBJECT,
2367.                                curr->func_index, obj_to_any(dest));
2368.         }
2369.     }
2370. }
2371. 
2372. /*
2373.  * Stop all timers attached to this object.  We can get away with this because
2374.  * all object pointers are unique.
2375.  */
2376. void
2377. obj_stop_timers(struct obj *obj)
2378. {
2379.     timeout_proc cleanup_func;
2380.     timer_element *curr, *prev, *next_timer = 0;
2381. 
2382.     for (prev = 0, curr = gt.timer_base; curr; curr = next_timer) {
2383.         next_timer = curr->next;
2384.         if (curr->kind == TIMER_OBJECT && curr->arg.a_obj == obj) {
2385.             if (prev)
2386.                 prev->next = curr->next;
2387.             else
2388.                 gt.timer_base = curr->next;
2389.             if ((cleanup_func = timeout_funcs[curr->func_index].cleanup) != 0)
2390.                 (*cleanup_func)(&curr->arg, curr->timeout);
2391.             (void) memset((genericptr_t) curr, 0, sizeof(timer_element));
2392.             free((genericptr_t) curr);
2393.         } else {
2394.             prev = curr;
2395.         }
2396.     }
2397.     obj->timed = 0;
2398. }
2399. 
2400. /*
2401.  * Check whether object has a timer of type timer_type.
2402.  */
2403. boolean
2404. obj_has_timer(struct obj *object, short timer_type)
2405. {
2406.     long timeout = peek_timer(timer_type, obj_to_any(object));
2407. 
2408.     return (boolean) (timeout != 0L);
2409. }
2410. 
2411. /*
2412.  * Stop all timers of index func_index at this spot.
2413.  *
2414.  */
2415. void
2416. spot_stop_timers(coordxy x, coordxy y, short func_index)
2417. {
2418.     timeout_proc cleanup_func;
2419.     timer_element *curr, *prev, *next_timer = 0;
2420.     long where = (((long) x << 16) | ((long) y));
2421. 
2422.     for (prev = 0, curr = gt.timer_base; curr; curr = next_timer) {
2423.         next_timer = curr->next;
2424.         if (curr->kind == TIMER_LEVEL && curr->func_index == func_index
2425.             && curr->arg.a_long == where) {
2426.             if (prev)
2427.                 prev->next = curr->next;
2428.             else
2429.                 gt.timer_base = curr->next;
2430.             if ((cleanup_func = timeout_funcs[curr->func_index].cleanup) != 0)
2431.                 (*cleanup_func)(&curr->arg, curr->timeout);
2432.             (void) memset((genericptr_t) curr, 0, sizeof(timer_element));
2433.             free((genericptr_t) curr);
2434.         } else {
2435.             prev = curr;
2436.         }
2437.     }
2438. }
2439. 
2440. /*
2441.  * When is the spot timer of type func_index going to expire?
2442.  * Returns 0L if no such timer.
2443.  */
2444. long
2445. spot_time_expires(coordxy x, coordxy y, short func_index)
2446. {
2447.     timer_element *curr;
2448.     long where = (((long) x << 16) | ((long) y));
2449. 
2450.     for (curr = gt.timer_base; curr; curr = curr->next) {
2451.         if (curr->kind == TIMER_LEVEL && curr->func_index == func_index
2452.             && curr->arg.a_long == where)
2453.             return curr->timeout;
2454.     }
2455.     return 0L;
2456. }
2457. 
2458. long
2459. spot_time_left(coordxy x, coordxy y, short func_index)
2460. {
2461.     long expires = spot_time_expires(x, y, func_index);
2462.     return (expires > 0L) ? expires - svm.moves : 0L;
2463. }
2464. 
2465. /* Insert timer into the global queue */
2466. staticfn void
2467. insert_timer(timer_element *gnu)
2468. {
2469.     timer_element *curr, *prev;
2470. 
2471.     for (prev = 0, curr = gt.timer_base; curr; prev = curr, curr = curr->next)
2472.         if (curr->timeout >= gnu->timeout)
2473.             break;
2474. 
2475.     gnu->next = curr;
2476.     if (prev)
2477.         prev->next = gnu;
2478.     else
2479.         gt.timer_base = gnu;
2480. }
2481. 
2482. staticfn timer_element *
2483. remove_timer(
2484.     timer_element **base,
2485.     short func_index,
2486.     anything *arg)
2487. {
2488.     timer_element *prev, *curr;
2489. 
2490.     for (prev = 0, curr = *base; curr; prev = curr, curr = curr->next)
2491.         if (curr->func_index == func_index && curr->arg.a_void == arg->a_void)
2492.             break;
2493. 
2494.     if (curr) {
2495.         if (prev)
2496.             prev->next = curr->next;
2497.         else
2498.             *base = curr->next;
2499.     }
2500. 
2501.     return curr;
2502. }
2503. 
2504. staticfn void
2505. write_timer(NHFILE *nhfp, timer_element *timer)
2506. {
2507.     anything arg_save;
2508. 
2509.     arg_save = cg.zeroany;
2510.     switch (timer->kind) {
2511.     case TIMER_GLOBAL:
2512.     case TIMER_LEVEL:
2513.         /* assume no pointers in arg */
2514.         Sfo_fe(nhfp, timer, "timer");
2515.         break;
2516. 
2517.     case TIMER_OBJECT:
2518.         if (timer->needs_fixup) {
2519.             Sfo_fe(nhfp, timer, "timer");
2520.         } else {
2521.             /* replace object pointer with id */
2522.             arg_save.a_obj = timer->arg.a_obj;
2523.             timer->arg = cg.zeroany;
2524.             timer->arg.a_uint = (arg_save.a_obj)->o_id;
2525.             timer->needs_fixup = 1;
2526.             Sfo_fe(nhfp, timer, "timer");
2527.             timer->arg.a_obj = arg_save.a_obj;
2528.             timer->needs_fixup = 0;
2529.         }
2530.         break;
2531. 
2532.     case TIMER_MONSTER:
2533.         if (timer->needs_fixup) {
2534.             Sfo_fe(nhfp, timer, "timer");
2535.         } else {
2536.             /* replace monster pointer with id */
2537.             arg_save.a_monst = timer->arg.a_monst;
2538.             timer->arg = cg.zeroany;
2539.             timer->arg.a_uint = (arg_save.a_monst)->m_id;
2540.             timer->needs_fixup = 1;
2541.             Sfo_fe(nhfp, timer, "timer");
2542.             timer->arg.a_monst = arg_save.a_monst;
2543.             timer->needs_fixup = 0;
2544.         }
2545.         break;
2546. 
2547.     default:
2548.         panic("write_timer");
2549.         break;
2550.     }
2551. }
2552. 
2553. DISABLE_WARNING_UNREACHABLE_CODE
2554. 
2555. /*
2556.  * Return TRUE if the object will stay on the level when the level is
2557.  * saved.
2558.  */
2559. boolean
2560. obj_is_local(struct obj *obj)
2561. {
2562.     switch (obj->where) {
2563.     case OBJ_INVENT:
2564.     case OBJ_MIGRATING:
2565.         return FALSE;
2566.     case OBJ_FLOOR:
2567.     case OBJ_BURIED:
2568.         return TRUE;
2569.     case OBJ_CONTAINED:
2570.         return obj_is_local(obj->ocontainer);
2571.     case OBJ_MINVENT:
2572.         return mon_is_local(obj->ocarry);
2573.     }
2574.     panic("obj_is_local");
2575.     /*NOTREACHED*/
2576.     return FALSE;
2577. }
2578. 
2579. /*
2580.  * Return TRUE if the given monster will stay on the level when the
2581.  * level is saved.
2582.  */
2583. staticfn boolean
2584. mon_is_local(struct monst *mon)
2585. {
2586.     struct monst *curr;
2587. 
2588.     for (curr = gm.migrating_mons; curr; curr = curr->nmon)
2589.         if (curr == mon)
2590.             return FALSE;
2591.     /* `gm.mydogs' is used during level changes, never saved and restored */
2592.     for (curr = gm.mydogs; curr; curr = curr->nmon)
2593.         if (curr == mon)
2594.             return FALSE;
2595.     return TRUE;
2596. }
2597. 
2598. /*
2599.  * Return TRUE if the timer is attached to something that will stay on the
2600.  * level when the level is saved.
2601.  */
2602. staticfn boolean
2603. timer_is_local(timer_element *timer)
2604. {
2605.     switch (timer->kind) {
2606.     case TIMER_LEVEL:
2607.         return TRUE;
2608.     case TIMER_GLOBAL:
2609.         return FALSE;
2610.     case TIMER_OBJECT:
2611.         return obj_is_local(timer->arg.a_obj);
2612.     case TIMER_MONSTER:
2613.         return mon_is_local(timer->arg.a_monst);
2614.     }
2615.     panic("timer_is_local");
2616.     /*NOTREACHED*/
2617.     return FALSE;
2618. }
2619. 
2620. RESTORE_WARNING_UNREACHABLE_CODE
2621. 
2622. /*
2623.  * Part of the save routine.  Count up the number of timers that would
2624.  * be written.  If write_it is true, actually write the timer.
2625.  */
2626. staticfn int
2627. maybe_write_timer(NHFILE *nhfp, int range, boolean write_it)
2628. {
2629.     int count = 0;
2630.     timer_element *curr;
2631. 
2632.     for (curr = gt.timer_base; curr; curr = curr->next) {
2633.         if (range == RANGE_GLOBAL) {
2634.             /* global timers */
2635. 
2636.             if (!timer_is_local(curr)) {
2637.                 count++;
2638.                 if (write_it) write_timer(nhfp, curr);
2639.             }
2640.         } else {
2641.             /* local timers */
2642. 
2643.             if (timer_is_local(curr)) {
2644.                 count++;
2645.                 if (write_it) write_timer(nhfp, curr);
2646.             }
2647.         }
2648.     }
2649. 
2650.     return count;
2651. }
2652. 
2653. 
2654. /*
2655.  * Save part of the timer list.  The parameter 'range' specifies either
2656.  * global or level timers to save.  The timer ID is saved with the global
2657.  * timers.
2658.  *
2659.  * Global range:
2660.  *      + timeouts that follow the hero (global)
2661.  *      + timeouts that follow obj & monst that are migrating
2662.  *
2663.  * Level range:
2664.  *      + timeouts that are level-specific (e.g. storms)
2665.  *      + timeouts that stay with the level (obj & monst)
2666.  */
2667. void
2668. save_timers(NHFILE *nhfp, int range)
2669. {
2670.     timer_element *curr, *prev, *next_timer = 0;
2671.     int count;
2672. 
2673.     if (update_file(nhfp)) {
2674.         if (range == RANGE_GLOBAL) {
2675.             Sfo_ulong(nhfp, &svt.timer_id, "timer-timer_id");
2676.         }
2677.         count = maybe_write_timer(nhfp, range, FALSE);
2678.         Sfo_int(nhfp, &count, "timer-timer_count");
2679.         (void) maybe_write_timer(nhfp, range, TRUE);
2680.     }
2681. 
2682.     if (release_data(nhfp)) {
2683.         for (prev = 0, curr = gt.timer_base; curr; curr = next_timer) {
2684.             next_timer = curr->next; /* in case curr is removed */
2685. 
2686.             if (!(!!(range == RANGE_LEVEL) ^ !!timer_is_local(curr))) {
2687.                 if (prev)
2688.                     prev->next = curr->next;
2689.                 else
2690.                     gt.timer_base = curr->next;
2691.                 (void) memset((genericptr_t) curr, 0, sizeof(timer_element));
2692.                 free((genericptr_t) curr);
2693.                 /* prev stays the same */
2694.             } else {
2695.                 prev = curr;
2696.             }
2697.         }
2698.     }
2699. }
2700. #endif /* !SFCTOOL */
2701. 
2702. /*
2703.  * Pull in the structures from disk, but don't recalculate the object and
2704.  * monster pointers.
2705.  */
2706. void
2707. restore_timers(NHFILE *nhfp, int range, long adjust)
2708. {
2709.     int count = 0;
2710.     timer_element *curr;
2711.     boolean ghostly = (nhfp->ftype == NHF_BONESFILE); /* from a ghost level */
2712. 
2713.     if (range == RANGE_GLOBAL) {
2714.         Sfi_ulong(nhfp, &svt.timer_id, "timer-timer_id");
2715.     }
2716. 
2717.     /* restore elements */
2718.     Sfi_int(nhfp, &count, "timer-timer_count");
2719.     while (count-- > 0) {
2720.         curr = (timer_element *) alloc(sizeof(timer_element));
2721.         Sfi_fe(nhfp, curr, "timer");
2722.         if (ghostly)
2723.             curr->timeout += adjust;
2724. #ifndef SFCTOOL
2725.         insert_timer(curr);
2726. #endif
2727.     }
2728. }
2729. 
2730. #ifndef SFCTOOL
2731. DISABLE_WARNING_FORMAT_NONLITERAL
2732. 
2733. /* to support '#stats' wizard-mode command */
2734. void
2735. timer_stats(const char *hdrfmt, char *hdrbuf, long *count, long *size)
2736. {
2737.     timer_element *te;
2738. 
2739.     Sprintf(hdrbuf, hdrfmt, (long) sizeof (timer_element));
2740.     *count = *size = 0L;
2741.     for (te = gt.timer_base; te; te = te->next) {
2742.         ++*count;
2743.         *size += (long) sizeof *te;
2744.     }
2745. }
2746. 
2747. RESTORE_WARNING_FORMAT_NONLITERAL
2748. 
2749. /* reset all timers that are marked for resetting */
2750. void
2751. relink_timers(boolean ghostly)
2752. {
2753.     timer_element *curr;
2754.     unsigned nid;
2755. 
2756.     for (curr = gt.timer_base; curr; curr = curr->next) {
2757.         if (curr->needs_fixup) {
2758.             if (curr->kind == TIMER_OBJECT) {
2759.                 if (ghostly) {
2760.                     if (!lookup_id_mapping(curr->arg.a_uint, &nid))
2761.                         panic("relink_timers 1");
2762.                 } else
2763.                     nid = curr->arg.a_uint;
2764.                 curr->arg.a_obj = find_oid(nid);
2765.                 if (!curr->arg.a_obj)
2766.                     panic("can't find o_id %d", nid);
2767.                 curr->needs_fixup = 0;
2768.             } else if (curr->kind == TIMER_MONSTER) {
2769.                 panic("relink_timers: no monster timer implemented");
2770.             } else
2771.                 panic("relink_timers 2");
2772.         }
2773.     }
2774. }
2775. #endif /* !SFCTOOL */
2776. 
2777. /*timeout.c*/