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