Removed unused code, reindented
[open-adventure.git] / misc.c
1 #include <unistd.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <stdarg.h>
6 #include <sys/time.h>
7 #include <ctype.h>
8 #include <editline/readline.h>
9
10 #include "advent.h"
11 #include "dungeon.h"
12
13 static void* xmalloc(size_t size)
14 {
15     void* ptr = malloc(size);
16     if (ptr == NULL) {
17         // LCOV_EXCL_START
18         // exclude from coverage analysis because we can't simulate an out of memory error in testing
19         fprintf(stderr, "Out of memory!\n");
20         exit(EXIT_FAILURE);
21         // LCOV_EXCL_STOP
22     }
23     return (ptr);
24 }
25
26 void packed_to_token(long packed, char token[TOKLEN + 1])
27 {
28     // The advent->ascii mapping.
29     const char advent_to_ascii[] = {
30         ' ', '!', '"', '#', '$', '%', '&', '\'',
31         '(', ')', '*', '+', ',', '-', '.', '/',
32         '0', '1', '2', '3', '4', '5', '6', '7',
33         '8', '9', ':', ';', '<', '=', '>', '?',
34         '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
35         'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
36         'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
37         'X', 'Y', 'Z', '\0', '\0', '\0', '\0', '\0',
38     };
39
40     // Unpack and map back to ASCII.
41     for (int i = 0; i < 5; ++i) {
42         char advent = (packed >> i * 6) & 63;
43         token[i] = advent_to_ascii[(int) advent];
44     }
45
46     // Ensure the last character is \0.
47     token[5] = '\0';
48
49     // Replace trailing whitespace with \0.
50     for (int i = 4; i >= 0; --i) {
51         if (token[i] == ' ' ||
52             token[i] == '\t')
53             token[i] = '\0';
54         else
55             break;
56     }
57 }
58
59 long token_to_packed(const char token[])
60 {
61     const char ascii_to_advent[] = {
62         63, 63, 63, 63, 63, 63, 63, 63,
63         63, 63, 63, 63, 63, 63, 63, 63,
64         63, 63, 63, 63, 63, 63, 63, 63,
65         63, 63, 63, 63, 63, 63, 63, 63,
66
67         0, 1, 2, 3, 4, 5, 6, 7,
68         8, 9, 10, 11, 12, 13, 14, 15,
69         16, 17, 18, 19, 20, 21, 22, 23,
70         24, 25, 26, 27, 28, 29, 30, 31,
71         32, 33, 34, 35, 36, 37, 38, 39,
72         40, 41, 42, 43, 44, 45, 46, 47,
73         48, 49, 50, 51, 52, 53, 54, 55,
74         56, 57, 58, 59, 60, 61, 62, 63,
75
76         63, 63, 63, 63, 63, 63, 63, 63,
77         63, 63, 63, 63, 63, 63, 63, 63,
78         63, 63, 63, 63, 63, 63, 63, 63,
79         63, 63, 63, 63, 63, 63, 63, 63,
80     };
81
82     size_t t_len = strlen(token);
83     if (t_len > TOKLEN)
84         t_len = TOKLEN;
85     long packed = 0;
86     for (size_t i = 0; i < t_len; ++i) {
87         char mapped = ascii_to_advent[(int) toupper(token[i])];
88         packed |= (mapped << (6 * i));
89     }
90     return (packed);
91 }
92
93 void tokenize(char* raw, struct command_t *cmd)
94 {
95     memset(cmd, '\0', sizeof(struct command_t));
96
97     /* Bound prefix on the %s would be needed to prevent buffer
98      * overflow.  but we shortstop this more simply by making each
99      * raw-input buffer as long as the enrire inout buffer. */
100     sscanf(raw, "%s%s", cmd->raw1, cmd->raw2);
101
102     // pack the substrings
103     cmd->wd1  = token_to_packed(cmd->raw1);
104     cmd->wd2  = token_to_packed(cmd->raw2);
105
106     /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
107      * effect on raw tokens of packing them into sixbit characters, 5
108      * to a 32-bit word.  This is something the FORTRAN version did
109      * becuse archaic FORTRAN had no string types.  Don Wood's
110      * mechanical translation of 2.5 to C retained the packing and
111      * thus this misfeature.
112      *
113      * It's philosophically questionable whether this is the right
114      * thing to do even in oldstyle mode.  On one hand, the text
115      * mangling was not authorial intent, but a result of limitations
116      * in their tools. On the other, not simulating this misbehavior
117      * goes against the goal of making oldstyle as accurate as
118      * possible an emulation of the original UI.
119      */
120     if (settings.oldstyle) {
121         cmd->raw1[TOKLEN + TOKLEN] = cmd->raw2[TOKLEN + TOKLEN] = '\0';
122         for (size_t i = 0; i < strlen(cmd->raw1); i++)
123             cmd->raw1[i] = toupper(cmd->raw1[i]);
124         for (size_t i = 0; i < strlen(cmd->raw2); i++)
125             cmd->raw2[i] = toupper(cmd->raw2[i]);
126     }
127 }
128
129 /* Hide the fact that wods are corrently packed longs */
130
131 bool wordempty(token_t a)
132 {
133     return a == 0;
134 }
135
136 void wordclear(token_t *v)
137 {
138     *v = 0;
139 }
140
141 /*  I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
142
143 void vspeak(const char* msg, bool blank, va_list ap)
144 {
145     // Do nothing if we got a null pointer.
146     if (msg == NULL)
147         return;
148
149     // Do nothing if we got an empty string.
150     if (strlen(msg) == 0)
151         return;
152
153     if (blank == true)
154         printf("\n");
155
156     int msglen = strlen(msg);
157
158     // Rendered string
159     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
160     char* rendered = xmalloc(size);
161     char* renderp = rendered;
162
163     // Handle format specifiers (including the custom %C, %L, %S) by
164     // adjusting the parameter accordingly, and replacing the
165     // specifier with %s.
166     long previous_arg = 0;
167     for (int i = 0; i < msglen; i++) {
168         if (msg[i] != '%') {
169             /* Ugh.  Least obtrusive way to deal with artifacts "on the floor"
170              * being dropped outside of both cave and building. */
171             if (strncmp(msg + i, "floor", 5) == 0 && strchr(" .", msg[i + 5]) && !INSIDE(game.loc)) {
172                 strcpy(renderp, "ground");
173                 renderp += 6;
174                 i += 4;
175                 size -= 5;
176             } else {
177                 *renderp++ = msg[i];
178                 size--;
179             }
180         } else {
181             long arg = va_arg(ap, long);
182             if (arg == -1)
183                 arg = 0; // LCOV_EXCL_LINE - don't think we can get here.
184             i++;
185             // Integer specifier. In order to accommodate the fact
186             // that PARMS can have both legitimate integers *and*
187             // packed tokens, stringify everything. Future work may
188             // eliminate the need for this.
189             if (msg[i] == 'd') {
190                 int ret = snprintf(renderp, size, "%ld", arg);
191                 if (ret < size) {
192                     renderp += ret;
193                     size -= ret;
194                 }
195             }
196
197             // Unmodified string specifier.
198             if (msg[i] == 's') {
199                 packed_to_token(arg, renderp); /* unpack directly to destination */
200                 size_t len = strlen(renderp);
201                 renderp += len;
202                 size -= len;
203             }
204
205             // Singular/plural specifier.
206             if (msg[i] == 'S') {
207                 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
208                     *renderp++ = 's';
209                     size--;
210                 }
211             }
212
213             /* Version specifier */
214             if (msg[i] == 'V') {
215                 strcpy(renderp, VERSION);
216                 size_t len = strlen(VERSION);
217                 renderp += len;
218                 size -= len;
219             }
220
221             previous_arg = arg;
222         }
223     }
224     *renderp = 0;
225
226     // Print the message.
227     printf("%s\n", rendered);
228
229     free(rendered);
230 }
231
232 void speak(const char* msg, ...)
233 {
234     va_list ap;
235     va_start(ap, msg);
236     vspeak(msg, true, ap);
237     va_end(ap);
238 }
239
240 void sspeak(const long msg, ...)
241 {
242     va_list ap;
243     va_start(ap, msg);
244     fputc('\n', stdout);
245     vprintf(arbitrary_messages[msg], ap);
246     fputc('\n', stdout);
247     va_end(ap);
248 }
249
250 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
251 /* Find the skip+1st message from msg and print it.  Modes are:
252  * feel = for inventory, what you can touch
253  * look = the long description for the state the object is in
254  * listen = the sound for the state the object is in
255  * study = text on the object. */
256 {
257     va_list ap;
258     va_start(ap, blank);
259     switch (mode) {
260     case touch:
261         vspeak(objects[msg].inventory, blank, ap);
262         break;
263     case look:
264         vspeak(objects[msg].descriptions[skip], blank, ap);
265         break;
266     case hear:
267         vspeak(objects[msg].sounds[skip], blank, ap);
268         break;
269     case study:
270         vspeak(objects[msg].texts[skip], blank, ap);
271         break;
272     case change:
273         vspeak(objects[msg].changes[skip], blank, ap);
274         break;
275     }
276     va_end(ap);
277 }
278
279 void rspeak(vocab_t i, ...)
280 /* Print the i-th "random" message (section 6 of database). */
281 {
282     va_list ap;
283     va_start(ap, i);
284     vspeak(arbitrary_messages[i], true, ap);
285     va_end(ap);
286 }
287
288 void echo_input(FILE* destination, const char* input_prompt, const char* input)
289 {
290     size_t len = strlen(input_prompt) + strlen(input) + 1;
291     char* prompt_and_input = (char*) xmalloc(len);
292     strcpy(prompt_and_input, input_prompt);
293     strcat(prompt_and_input, input);
294     fprintf(destination, "%s\n", prompt_and_input);
295     free(prompt_and_input);
296 }
297
298 int word_count(char* str)
299 {
300     char delims[] = " \t";
301     int count = 0;
302     int inblanks = true;
303
304     for (char *s = str; *s; s++)
305         if (inblanks) {
306             if (strchr(delims, *s) == 0) {
307                 ++count;
308                 inblanks = false;
309             }
310         } else {
311             if (strchr(delims, *s) != 0) {
312                 inblanks = true;
313             }
314         }
315
316     return (count);
317 }
318
319 char* get_input()
320 {
321     // Set up the prompt
322     char input_prompt[] = "> ";
323     if (!settings.prompt)
324         input_prompt[0] = '\0';
325
326     // Print a blank line
327     printf("\n");
328
329     char* input;
330     while (true) {
331         input = readline(input_prompt);
332
333         if (input == NULL) // Got EOF; return with it.
334             return (input);
335         if (input[0] == '#') { // Ignore comments.
336             free(input);
337             continue;
338         }
339         // We have a 'normal' line; leave the loop.
340         break;
341     }
342
343     // Strip trailing newlines from the input
344     input[strcspn(input, "\n")] = 0;
345
346     add_history(input);
347
348     if (!isatty(0))
349         echo_input(stdout, input_prompt, input);
350
351     if (settings.logfp)
352         echo_input(settings.logfp, "", input);
353
354     return (input);
355 }
356
357 bool silent_yes()
358 {
359     bool outcome = false;
360
361     for (;;) {
362         char* reply = get_input();
363         if (reply == NULL) {
364             // LCOV_EXCL_START
365             // Should be unreachable. Reply should never be NULL
366             free(reply);
367             exit(EXIT_SUCCESS);
368             // LCOV_EXCL_STOP
369         }
370         if (strlen(reply) == 0) {
371             free(reply);
372             rspeak(PLEASE_ANSWER);
373             continue;
374         }
375
376         char* firstword = (char*) xmalloc(strlen(reply) + 1);
377         sscanf(reply, "%s", firstword);
378
379         free(reply);
380
381         for (int i = 0; i < (int)strlen(firstword); ++i)
382             firstword[i] = tolower(firstword[i]);
383
384         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
385         int y = strncmp("y", firstword, sizeof("y") - 1);
386         int no = strncmp("no", firstword, sizeof("no") - 1);
387         int n = strncmp("n", firstword, sizeof("n") - 1);
388
389         free(firstword);
390
391         if (yes == 0 ||
392             y == 0) {
393             outcome = true;
394             break;
395         } else if (no == 0 ||
396                    n == 0) {
397             outcome = false;
398             break;
399         } else
400             rspeak(PLEASE_ANSWER);
401     }
402     return (outcome);
403 }
404
405
406 bool yes(const char* question, const char* yes_response, const char* no_response)
407 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
408  *  if no, print Z and return false. */
409 {
410     bool outcome = false;
411
412     for (;;) {
413         speak(question);
414
415         char* reply = get_input();
416         if (reply == NULL) {
417             // LCOV_EXCL_START
418             // Should be unreachable. Reply should never be NULL
419             free(reply);
420             exit(EXIT_SUCCESS);
421             // LCOV_EXCL_STOP
422         }
423
424         if (strlen(reply) == 0) {
425             free(reply);
426             rspeak(PLEASE_ANSWER);
427             continue;
428         }
429
430         char* firstword = (char*) xmalloc(strlen(reply) + 1);
431         sscanf(reply, "%s", firstword);
432
433         free(reply);
434
435         for (int i = 0; i < (int)strlen(firstword); ++i)
436             firstword[i] = tolower(firstword[i]);
437
438         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
439         int y = strncmp("y", firstword, sizeof("y") - 1);
440         int no = strncmp("no", firstword, sizeof("no") - 1);
441         int n = strncmp("n", firstword, sizeof("n") - 1);
442
443         free(firstword);
444
445         if (yes == 0 ||
446             y == 0) {
447             speak(yes_response);
448             outcome = true;
449             break;
450         } else if (no == 0 ||
451                    n == 0) {
452             speak(no_response);
453             outcome = false;
454             break;
455         } else
456             rspeak(PLEASE_ANSWER);
457
458     }
459
460     return (outcome);
461 }
462
463 /*  Data structure  routines */
464
465 int get_motion_vocab_id(const char* word)
466 // Return the first motion number that has 'word' as one of its words.
467 {
468     for (int i = 0; i < NMOTIONS; ++i) {
469         for (int j = 0; j < motions[i].words.n; ++j) {
470             if (strcasecmp(word, motions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
471                     strchr(ignore, word[0]) == NULL ||
472                     !settings.oldstyle))
473                 return (i);
474         }
475     }
476     // If execution reaches here, we didn't find the word.
477     return (WORD_NOT_FOUND);
478 }
479
480 int get_object_vocab_id(const char* word)
481 // Return the first object number that has 'word' as one of its words.
482 {
483     for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
484         for (int j = 0; j < objects[i].words.n; ++j) {
485             if (strcasecmp(word, objects[i].words.strs[j]) == 0)
486                 return (i);
487         }
488     }
489     // If execution reaches here, we didn't find the word.
490     return (WORD_NOT_FOUND);
491 }
492
493 int get_action_vocab_id(const char* word)
494 // Return the first motion number that has 'word' as one of its words.
495 {
496     for (int i = 0; i < NACTIONS; ++i) {
497         for (int j = 0; j < actions[i].words.n; ++j) {
498             if (strcasecmp(word, actions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
499                     strchr(ignore, word[0]) == NULL ||
500                     !settings.oldstyle))
501                 return (i);
502         }
503     }
504     // If execution reaches here, we didn't find the word.
505     return (WORD_NOT_FOUND);
506 }
507
508 int get_special_vocab_id(const char* word)
509 // Return the first special number that has 'word' as one of its words.
510 {
511     for (int i = 0; i < NSPECIALS; ++i) {
512         for (int j = 0; j < specials[i].words.n; ++j) {
513             if (strcasecmp(word, specials[i].words.strs[j]) == 0)
514                 return (i);
515         }
516     }
517     // If execution reaches here, we didn't find the word.
518     return (WORD_NOT_FOUND);
519 }
520
521 void get_vocab_metadata(const char* word, long* id, enum wordtype* type)
522 {
523     /* Check for an empty string */
524     if (strncmp(word, "", sizeof("")) == 0) {
525         *id = WORD_EMPTY;
526         *type = NO_WORD_TYPE;
527         return;
528     }
529
530     long ref_num;
531
532     ref_num = get_motion_vocab_id(word);
533     if (ref_num != WORD_NOT_FOUND) {
534         *id = ref_num;
535         *type = MOTION;
536         return;
537     }
538
539     ref_num = get_object_vocab_id(word);
540     if (ref_num != WORD_NOT_FOUND) {
541         *id = ref_num;
542         *type = OBJECT;
543         return;
544     }
545
546     ref_num = get_action_vocab_id(word);
547     if (ref_num != WORD_NOT_FOUND) {
548         *id = ref_num;
549         *type = ACTION;
550         return;
551     }
552
553     ref_num = get_special_vocab_id(word);
554     if (ref_num != WORD_NOT_FOUND) {
555         *id = ref_num;
556         *type = SPECIAL;
557         return;
558     }
559
560     // Check for the reservoir magic word.
561     if (strcasecmp(word, game.zzword) == 0) {
562         *id = PART;
563         *type = ACTION;
564         return;
565     }
566
567     *id = WORD_NOT_FOUND;
568     *type = NO_WORD_TYPE;
569     return;
570 }
571
572 void juggle(obj_t object)
573 /*  Juggle an object by picking it up and putting it down again, the purpose
574  *  being to get the object to the front of the chain of things at its loc. */
575 {
576     loc_t i, j;
577
578     i = game.place[object];
579     j = game.fixed[object];
580     move(object, i);
581     move(object + NOBJECTS, j);
582 }
583
584 void move(obj_t object, loc_t where)
585 /*  Place any object anywhere by picking it up and dropping it.  May
586  *  already be toting, in which case the carry is a no-op.  Mustn't
587  *  pick up objects which are not at any loc, since carry wants to
588  *  remove objects from game.atloc chains. */
589 {
590     long from;
591
592     if (object > NOBJECTS)
593         from = game.fixed[object - NOBJECTS];
594     else
595         from = game.place[object];
596     /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
597     if (from != LOC_NOWHERE && from != CARRIED)
598         carry(object, from);
599     drop(object, where);
600 }
601
602 long put(obj_t object, loc_t where, long pval)
603 /*  put() is the same as move(), except it returns a value used to set up the
604  *  negated game.prop values for the repository objects. */
605 {
606     move(object, where);
607     return STASHED(pval);
608 }
609
610 void carry(obj_t object, loc_t where)
611 /*  Start toting an object, removing it from the list of things at its former
612  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
613  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
614 {
615     long temp;
616
617     if (object <= NOBJECTS) {
618         if (game.place[object] == CARRIED)
619             return;
620         game.place[object] = CARRIED;
621         ++game.holdng;
622     }
623     if (game.atloc[where] == object) {
624         game.atloc[where] = game.link[object];
625         return;
626     }
627     temp = game.atloc[where];
628     while (game.link[temp] != object) {
629         temp = game.link[temp];
630     }
631     game.link[temp] = game.link[object];
632 }
633
634 void drop(obj_t object, loc_t where)
635 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
636  *  game.holdng if the object was being toted. */
637 {
638     if (object > NOBJECTS)
639         game.fixed[object - NOBJECTS] = where;
640     else {
641         if (game.place[object] == CARRIED)
642             --game.holdng;
643         game.place[object] = where;
644     }
645     if (where == LOC_NOWHERE ||
646         where == CARRIED)
647         return;
648     game.link[object] = game.atloc[where];
649     game.atloc[where] = object;
650 }
651
652 long atdwrf(loc_t where)
653 /*  Return the index of first dwarf at the given location, zero if no dwarf is
654  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
655  *  the pirate (6th dwarf). */
656 {
657     long at;
658
659     at = 0;
660     if (game.dflag < 2)
661         return (at);
662     at = -1;
663     for (long i = 1; i <= NDWARVES - 1; i++) {
664         if (game.dloc[i] == where)
665             return i;
666         if (game.dloc[i] != 0)
667             at = 0;
668     }
669     return (at);
670 }
671
672 /*  Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
673  *  randrange) */
674
675 long setbit(long bit)
676 /*  Returns 2**bit for use in constructing bit-masks. */
677 {
678     return (1L << bit);
679 }
680
681 bool tstbit(long mask, int bit)
682 /*  Returns true if the specified bit is set in the mask. */
683 {
684     return (mask & (1 << bit)) != 0;
685 }
686
687 void set_seed(long seedval)
688 /* Set the LCG seed */
689 {
690     game.lcg_x = (unsigned long) seedval % game.lcg_m;
691
692     // once seed is set, we need to generate the Z`ZZZ word
693     make_zzword(game.zzword);
694 }
695
696 unsigned long get_next_lcg_value(void)
697 /* Return the LCG's current value, and then iterate it. */
698 {
699     unsigned long old_x = game.lcg_x;
700     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
701     return old_x;
702 }
703
704 long randrange(long range)
705 /* Return a random integer from [0, range). */
706 {
707     return range * get_next_lcg_value() / game.lcg_m;
708 }
709
710 void make_zzword(char zzword[TOKLEN + 1])
711 {
712     for (int i = 0; i < 5; ++i) {
713         zzword[i] = 'A' + randrange(26);
714     }
715     zzword[1] = '\''; // force second char to apostrophe
716     zzword[5] = '\0';
717 }
718
719 // LCOV_EXCL_START
720 void bug(enum bugtype num, const char *error_string)
721 {
722     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
723     exit(EXIT_FAILURE);
724 }
725 // LCOV_EXCL_STOP
726
727 /* end */
728
729 void state_change(obj_t obj, long state)
730 /* Object must have a change-message list for this to be useful; only some do */
731 {
732     game.prop[obj] = state;
733     pspeak(obj, change, state, true);
734 }
735
736 /* end */