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