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