Upgrade get_vocab_id() to handle empty strings.
[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     /* FIXME: put a bound prefix on the %s to prevent buffer overflow */
98     int word_count = sscanf(raw, "%s%s", cmd->raw1, cmd->raw2);
99
100     // pack the substrings
101     cmd->wd1  = token_to_packed(cmd->raw1);
102     cmd->wd2  = token_to_packed(cmd->raw2);
103 }
104
105 /* Hide the fact that wods are corrently packed longs */
106
107 bool wordeq(token_t a, token_t b)
108 {
109     return a == b;
110 }
111
112 bool wordempty(token_t a)
113 {
114     return a == 0;
115 }
116
117 void wordclear(token_t *v)
118 {
119     *v = 0;
120 }
121
122 /*  I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
123
124 void vspeak(const char* msg, bool blank, va_list ap)
125 {
126     // Do nothing if we got a null pointer.
127     if (msg == NULL)
128         return;
129
130     // Do nothing if we got an empty string.
131     if (strlen(msg) == 0)
132         return;
133
134     if (blank == true)
135         printf("\n");
136
137     int msglen = strlen(msg);
138
139     // Rendered string
140     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
141     char* rendered = xmalloc(size);
142     char* renderp = rendered;
143
144     // Handle format specifiers (including the custom %C, %L, %S) by
145     // adjusting the parameter accordingly, and replacing the
146     // specifier with %s.
147     long previous_arg = 0;
148     for (int i = 0; i < msglen; i++) {
149         if (msg[i] != '%') {
150             *renderp++ = msg[i];
151             size--;
152         } else {
153             long arg = va_arg(ap, long);
154             if (arg == -1)
155                 arg = 0; // LCOV_EXCL_LINE - don't think we can get here.
156             i++;
157             // Integer specifier. In order to accommodate the fact
158             // that PARMS can have both legitimate integers *and*
159             // packed tokens, stringify everything. Future work may
160             // eliminate the need for this.
161             if (msg[i] == 'd') {
162                 int ret = snprintf(renderp, size, "%ld", arg);
163                 if (ret < size) {
164                     renderp += ret;
165                     size -= ret;
166                 }
167             }
168
169             // Unmodified string specifier.
170             if (msg[i] == 's') {
171                 packed_to_token(arg, renderp); /* unpack directly to destination */
172                 size_t len = strlen(renderp);
173                 renderp += len;
174                 size -= len;
175             }
176
177             // Singular/plural specifier.
178             if (msg[i] == 'S') {
179                 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
180                     *renderp++ = 's';
181                     size--;
182                 }
183             }
184
185             /* Version specifier */
186             if (msg[i] == 'V') {
187                 strcpy(renderp, VERSION);
188                 size_t len = strlen(VERSION);
189                 renderp += len;
190                 size -= len;
191             }
192
193             previous_arg = arg;
194         }
195     }
196     *renderp = 0;
197
198     // Print the message.
199     printf("%s\n", rendered);
200
201     free(rendered);
202 }
203
204 void speak(const char* msg, ...)
205 {
206     va_list ap;
207     va_start(ap, msg);
208     vspeak(msg, true, ap);
209     va_end(ap);
210 }
211
212 void sspeak(const long msg, ...)
213 {
214     va_list ap;
215     va_start(ap, msg);
216     fputc('\n', stdout);
217     vprintf(arbitrary_messages[msg], ap);
218     fputc('\n', stdout);
219     va_end(ap);
220 }
221
222 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
223 /* Find the skip+1st message from msg and print it.  Modes are:
224  * feel = for inventory, what you can touch
225  * look = the long description for the state the object is in
226  * listen = the sound for the state the object is in
227  * study = text on the object. */
228 {
229     va_list ap;
230     va_start(ap, blank);
231     switch (mode) {
232     case touch:
233         vspeak(objects[msg].inventory, blank, ap);
234         break;
235     case look:
236         vspeak(objects[msg].descriptions[skip], blank, ap);
237         break;
238     case hear:
239         vspeak(objects[msg].sounds[skip], blank, ap);
240         break;
241     case study:
242         vspeak(objects[msg].texts[skip], blank, ap);
243         break;
244     case change:
245         vspeak(objects[msg].changes[skip], blank, ap);
246         break;
247     }
248     va_end(ap);
249 }
250
251 void rspeak(vocab_t i, ...)
252 /* Print the i-th "random" message (section 6 of database). */
253 {
254     va_list ap;
255     va_start(ap, i);
256     vspeak(arbitrary_messages[i], true, ap);
257     va_end(ap);
258 }
259
260 void echo_input(FILE* destination, const char* input_prompt, const char* input)
261 {
262     size_t len = strlen(input_prompt) + strlen(input) + 1;
263     char* prompt_and_input = (char*) xmalloc(len);
264     strcpy(prompt_and_input, input_prompt);
265     strcat(prompt_and_input, input);
266     fprintf(destination, "%s\n", prompt_and_input);
267     free(prompt_and_input);
268 }
269
270 int word_count(char* str)
271 {
272     char delims[] = " \t";
273     int count = 0;
274     int inblanks = true;
275
276     for (char *s = str; *s; s++)
277         if (inblanks) {
278             if (strchr(delims, *s) == 0) {
279                 ++count;
280                 inblanks = false;
281             }
282         } else {
283             if (strchr(delims, *s) != 0) {
284                 inblanks = true;
285             }
286         }
287
288     return (count);
289 }
290
291 char* get_input()
292 {
293     // Set up the prompt
294     char input_prompt[] = "> ";
295     if (!settings.prompt)
296         input_prompt[0] = '\0';
297
298     // Print a blank line
299     printf("\n");
300
301     char* input;
302     while (true) {
303         input = readline(input_prompt);
304
305         if (input == NULL) // Got EOF; return with it.
306             return (input);
307         else if (input[0] == '#') { // Ignore comments.
308             free(input);
309             continue;
310         } else // We have a 'normal' line; leave the loop.
311             break;
312     }
313
314     // Strip trailing newlines from the input
315     input[strcspn(input, "\n")] = 0;
316
317     add_history(input);
318
319     if (!isatty(0))
320         echo_input(stdout, input_prompt, input);
321
322     if (settings.logfp)
323         echo_input(settings.logfp, "", input);
324
325     return (input);
326 }
327
328 bool silent_yes()
329 {
330     char* reply;
331     bool outcome;
332
333     for (;;) {
334         reply = get_input();
335         if (reply == NULL) {
336             // LCOV_EXCL_START
337             // Should be unreachable. Reply should never be NULL
338             free(reply);
339             exit(EXIT_SUCCESS);
340             // LCOV_EXCL_STOP
341         }
342
343         char* firstword = (char*) xmalloc(strlen(reply) + 1);
344         sscanf(reply, "%s", firstword);
345
346         free(reply);
347
348         for (int i = 0; i < (int)strlen(firstword); ++i)
349             firstword[i] = tolower(firstword[i]);
350
351         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
352         int y = strncmp("y", firstword, sizeof("y") - 1);
353         int no = strncmp("no", firstword, sizeof("no") - 1);
354         int n = strncmp("n", firstword, sizeof("n") - 1);
355
356         free(firstword);
357
358         if (yes == 0 ||
359             y == 0) {
360             outcome = true;
361             break;
362         } else if (no == 0 ||
363                    n == 0) {
364             outcome = false;
365             break;
366         } else
367             rspeak(PLEASE_ANSWER);
368     }
369     return (outcome);
370 }
371
372
373 bool yes(const char* question, const char* yes_response, const char* no_response)
374 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
375  *  if no, print Z and return false. */
376 {
377     char* reply;
378     bool outcome;
379
380     for (;;) {
381         speak(question);
382
383         reply = get_input();
384         if (reply == NULL) {
385             // LCOV_EXCL_START
386             // Should be unreachable. Reply should never be NULL
387             free(reply);
388             exit(EXIT_SUCCESS);
389             // LCOV_EXCL_STOP
390         }
391
392         char* firstword = (char*) xmalloc(strlen(reply) + 1);
393         sscanf(reply, "%s", firstword);
394
395         free(reply);
396
397         for (int i = 0; i < (int)strlen(firstword); ++i)
398             firstword[i] = tolower(firstword[i]);
399
400         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
401         int y = strncmp("y", firstword, sizeof("y") - 1);
402         int no = strncmp("no", firstword, sizeof("no") - 1);
403         int n = strncmp("n", firstword, sizeof("n") - 1);
404
405         free(firstword);
406
407         if (yes == 0 ||
408             y == 0) {
409             speak(yes_response);
410             outcome = true;
411             break;
412         } else if (no == 0 ||
413                    n == 0) {
414             speak(no_response);
415             outcome = false;
416             break;
417         } else
418             rspeak(PLEASE_ANSWER);
419
420     }
421
422     return (outcome);
423 }
424
425 /*  Data structure  routines */
426
427 int get_motion_vocab_id(const char* word)
428 // Return the first motion number that has 'word' as one of its words.
429 {
430     for (int i = 0; i < NMOTIONS; ++i) {
431         for (int j = 0; j < motions[i].words.n; ++j) {
432             if (strcasecmp(word, motions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
433                     strchr(ignore, word[0]) == NULL ||
434                     !settings.oldstyle))
435                 return (i);
436         }
437     }
438     // If execution reaches here, we didn't find the word.
439     return (WORD_NOT_FOUND);
440 }
441
442 int get_object_vocab_id(const char* word)
443 // Return the first object number that has 'word' as one of its words.
444 {
445     for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
446         for (int j = 0; j < objects[i].words.n; ++j) {
447             if (strcasecmp(word, objects[i].words.strs[j]) == 0)
448                 return (i);
449         }
450     }
451     // If execution reaches here, we didn't find the word.
452     return (WORD_NOT_FOUND);
453 }
454
455 int get_action_vocab_id(const char* word)
456 // Return the first motion number that has 'word' as one of its words.
457 {
458     for (int i = 0; i < NACTIONS; ++i) {
459         for (int j = 0; j < actions[i].words.n; ++j) {
460             if (strcasecmp(word, actions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
461                     strchr(ignore, word[0]) == NULL ||
462                     !settings.oldstyle))
463                 return (i);
464         }
465     }
466     // If execution reaches here, we didn't find the word.
467     return (WORD_NOT_FOUND);
468 }
469
470 int get_special_vocab_id(const char* word)
471 // Return the first special number that has 'word' as one of its words.
472 {
473     for (int i = 0; i < NSPECIALS; ++i) {
474         for (int j = 0; j < specials[i].words.n; ++j) {
475             if (strcasecmp(word, specials[i].words.strs[j]) == 0)
476                 return (i);
477         }
478     }
479     // If execution reaches here, we didn't find the word.
480     return (WORD_NOT_FOUND);
481 }
482
483 long get_vocab_id(const char* word)
484 // Search the vocab categories in order for the supplied word.
485 {
486     /* Check for an empty string */
487     if (strncmp(word, "", sizeof("")) == 0)
488       return (WORD_EMPTY);
489
490     long ref_num;
491
492     /* FIXME: Magic numbers related to vocabulary */
493     ref_num = get_motion_vocab_id(word);
494     if (ref_num != WORD_NOT_FOUND)
495         return (ref_num + 0); // FIXME: replace with a proper hash
496
497     ref_num = get_object_vocab_id(word);
498     if (ref_num != WORD_NOT_FOUND)
499         return (ref_num + 1000); // FIXME: replace with a proper hash
500
501     ref_num = get_action_vocab_id(word);
502     if (ref_num != WORD_NOT_FOUND)
503         return (ref_num + 2000); // FIXME: replace with a proper hash
504
505     ref_num = get_special_vocab_id(word);
506     if (ref_num != WORD_NOT_FOUND)
507         return (ref_num + 3000); // FIXME: replace with a proper hash
508
509     // Check for the reservoir magic word.
510     if (strcasecmp(word, game.zzword) == 0)
511         return (PART + 2000); // FIXME: replace with a proper hash
512
513     return (WORD_NOT_FOUND);
514 }
515
516 void juggle(long object)
517 /*  Juggle an object by picking it up and putting it down again, the purpose
518  *  being to get the object to the front of the chain of things at its loc. */
519 {
520     long i, j;
521
522     i = game.place[object];
523     j = game.fixed[object];
524     move(object, i);
525     move(object + NOBJECTS, j);
526 }
527
528 void move(long object, long where)
529 /*  Place any object anywhere by picking it up and dropping it.  May
530  *  already be toting, in which case the carry is a no-op.  Mustn't
531  *  pick up objects which are not at any loc, since carry wants to
532  *  remove objects from game.atloc chains. */
533 {
534     long from;
535
536     if (object > NOBJECTS)
537         from = game.fixed[object - NOBJECTS];
538     else
539         from = game.place[object];
540     if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
541         carry(object, from);
542     drop(object, where);
543 }
544
545 long put(long object, long where, long pval)
546 /*  PUT is the same as MOVE, except it returns a value used to set up the
547  *  negated game.prop values for the repository objects. */
548 {
549     move(object, where);
550     return (-1) - pval;;
551 }
552
553 void carry(long object, long where)
554 /*  Start toting an object, removing it from the list of things at its former
555  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
556  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
557 {
558     long temp;
559
560     if (object <= NOBJECTS) {
561         if (game.place[object] == CARRIED)
562             return;
563         game.place[object] = CARRIED;
564         ++game.holdng;
565     }
566     if (game.atloc[where] == object) {
567         game.atloc[where] = game.link[object];
568         return;
569     }
570     temp = game.atloc[where];
571     while (game.link[temp] != object) {
572         temp = game.link[temp];
573     }
574     game.link[temp] = game.link[object];
575 }
576
577 void drop(long object, long where)
578 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
579  *  game.holdng if the object was being toted. */
580 {
581     if (object > NOBJECTS)
582         game.fixed[object - NOBJECTS] = where;
583     else {
584         if (game.place[object] == CARRIED)
585             --game.holdng;
586         game.place[object] = where;
587     }
588     if (where <= 0)
589         return;
590     game.link[object] = game.atloc[where];
591     game.atloc[where] = object;
592 }
593
594 long atdwrf(long where)
595 /*  Return the index of first dwarf at the given location, zero if no dwarf is
596  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
597  *  the pirate (6th dwarf). */
598 {
599     long at;
600
601     at = 0;
602     if (game.dflag < 2)
603         return (at);
604     at = -1;
605     for (long i = 1; i <= NDWARVES - 1; i++) {
606         if (game.dloc[i] == where)
607             return i;
608         if (game.dloc[i] != 0)
609             at = 0;
610     }
611     return (at);
612 }
613
614 /*  Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
615  *  randrange) */
616
617 long setbit(long bit)
618 /*  Returns 2**bit for use in constructing bit-masks. */
619 {
620     return (1L << bit);
621 }
622
623 bool tstbit(long mask, int bit)
624 /*  Returns true if the specified bit is set in the mask. */
625 {
626     return (mask & (1 << bit)) != 0;
627 }
628
629 void set_seed(long seedval)
630 /* Set the LCG seed */
631 {
632     game.lcg_x = (unsigned long) seedval % game.lcg_m;
633
634     // once seed is set, we need to generate the Z`ZZZ word
635     make_zzword(game.zzword);
636 }
637
638 unsigned long get_next_lcg_value(void)
639 /* Return the LCG's current value, and then iterate it. */
640 {
641     unsigned long old_x = game.lcg_x;
642     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
643     return old_x;
644 }
645
646 long randrange(long range)
647 /* Return a random integer from [0, range). */
648 {
649     return range * get_next_lcg_value() / game.lcg_m;
650 }
651
652 void make_zzword(char zzword[TOKLEN+1])
653 {
654     for (int i = 0; i < 5; ++i) {
655         zzword[i] = 'A' + randrange(26);
656     }
657     zzword[1] = '\''; // force second char to apostrophe
658     zzword[5] = '\0';
659 }
660
661 // LCOV_EXCL_START
662 void bug(enum bugtype num, const char *error_string)
663 {
664     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
665     exit(EXIT_FAILURE);
666 }
667 // LCOV_EXCL_STOP
668
669 /* end */