Elimination of OBJSND.
[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 "database.h"
11 #include "linenoise/linenoise.h"
12 #include "newdb.h"
13
14 void* xmalloc(size_t size)
15 {
16     void* ptr = malloc(size);
17     if (ptr == NULL) {
18         fprintf(stderr, "Out of memory!\n");
19         exit(EXIT_FAILURE);
20     }
21     return (ptr);
22 }
23
24 void packed_to_token(long packed, char token[6])
25 {
26     // Unpack and map back to ASCII.
27     for (int i = 0; i < 5; ++i) {
28         char advent = (packed >> i * 6) & 63;
29         token[4 - i] = advent_to_ascii[(int) advent];
30     }
31
32     // Ensure the last character is \0.
33     token[5] = '\0';
34
35     // Replace trailing whitespace with \0.
36     for (int i = 4; i >= 0; --i) {
37         if (token[i] == ' ' || token[i] == '\t')
38             token[i] = '\0';
39         else
40             break;
41     }
42 }
43
44 void token_to_packed(char token[6], long* packed)
45 {
46   *packed = 0;
47   for (size_t i = 0; i < 5; ++i)
48     {
49       if (token[4 - i] == '\0')
50         continue;       
51       char mapped = ascii_to_advent[(int) token[4 - i]];
52       *packed |= (mapped << (6 * i));
53     }
54 }
55
56 /* Hide the fact that wods are corrently packed longs */
57
58 bool wordeq(token_t a, token_t b)
59 {
60     return a == b;
61 }
62
63 bool wordempty(token_t a)
64 {
65     return a == 0;
66 }
67
68 void wordclear(token_t *v)
69 {
70     *v = 0;
71 }
72
73 /*  I/O routines (speak, pspeak, rspeak, GETIN, YES) */
74
75 void vspeak(const char* msg, va_list ap)
76 {
77     // Do nothing if we got a null pointer.
78     if (msg == NULL)
79         return;
80
81     // Do nothing if we got an empty string.
82     if (strlen(msg) == 0)
83         return;
84
85     // Print a newline if the global game.blklin says to.
86     if (game.blklin == true)
87         printf("\n");
88
89     int msglen = strlen(msg);
90
91     // Rendered string
92     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
93     char* rendered = xmalloc(size);
94     char* renderp = rendered;
95
96     // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
97     long previous_arg = 0;
98     for (int i = 0; i < msglen; i++) {
99         if (msg[i] != '%') {
100             *renderp++ = msg[i];
101             size--;
102         } else {
103             long arg = va_arg(ap, long);
104             if (arg == -1)
105               arg = 0;
106             i++;
107             // 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.
108             if (msg[i] == 'd') {
109                 int ret = snprintf(renderp, size, "%ld", arg);
110                 if (ret < size) {
111                     renderp += ret;
112                     size -= ret;
113                 }
114             }
115
116             // Unmodified string specifier.
117             if (msg[i] == 's') {
118                 packed_to_token(arg, renderp); /* unpack directly to destination */
119                 size_t len = strlen(renderp);
120                 renderp += len;
121                 size -= len;
122             }
123
124             // Singular/plural specifier.
125             if (msg[i] == 'S') {
126                 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
127                     *renderp++ = 's';
128                     size--;
129                 }
130             }
131
132             // All-lowercase specifier.
133             if (msg[i] == 'L' || msg[i] == 'C') {
134                 packed_to_token(arg, renderp); /* unpack directly to destination */
135                 int len = strlen(renderp);
136                 for (int j = 0; j < len; ++j) {
137                     renderp[j] = tolower(renderp[j]);
138                 }
139                 if (msg[i] == 'C') // First char uppercase, rest lowercase.
140                     renderp[0] = toupper(renderp[0]);
141                 renderp += len;
142                 size -= len;
143             }
144
145             previous_arg = arg;
146         }
147     }
148     *renderp = 0;
149
150     // Print the message.
151     printf("%s\n", rendered);
152
153     free(rendered);
154 }
155
156 void speak(const char* msg, ...)
157 {
158     va_list ap;
159     va_start(ap, msg);
160     vspeak(msg, ap);
161     va_end(ap);
162 }
163
164 void pspeak(vocab_t msg, enum speaktype mode, int skip, ...)
165 /* Find the skip+1st message from msg and print it.  Modes are:
166  * feel = for inventory, what you can touch
167  * look = the long description for the state the object is in
168  * listen = the sound for the state the object is in
169  * study = text on the object. */
170 {
171     va_list ap;
172     va_start(ap, skip);
173     switch (mode) {
174     case touch:
175         vspeak(object_descriptions[msg].inventory, ap);
176         break;
177     case look: 
178         vspeak(object_descriptions[msg].longs[skip], ap);
179         break;
180     case hear:
181         vspeak(object_descriptions[msg].sounds[skip], ap);
182         break;
183     case study:
184         vspeak(object_descriptions[msg].texts[skip], ap);
185         break;
186     }
187     va_end(ap);
188 }
189
190 void rspeak(vocab_t i, ...)
191 /* Print the i-th "random" message (section 6 of database). */
192 {
193     va_list ap;
194     va_start(ap, i);
195     vspeak(arbitrary_messages[i], ap);
196     va_end(ap);
197 }
198
199 bool GETIN(FILE *input,
200            long *pword1, long *pword1x,
201            long *pword2, long *pword2x)
202 /*  Get a command from the adventurer.  Snarf out the first word, pad it with
203  *  blanks, and return it in WORD1.  Chars 6 thru 10 are returned in WORD1X, in
204  *  case we need to print out the whole word in an error message.  Any number of
205  *  blanks may follow the word.  If a second word appears, it is returned in
206  *  WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
207 {
208     long junk;
209
210     for (;;) {
211         if (game.blklin)
212             fputc('\n', stdout);;
213         if (!MAPLIN(input))
214             return false;
215         *pword1 = GETTXT(true, true, true);
216         if (game.blklin && *pword1 < 0)
217             continue;
218         *pword1x = GETTXT(false, true, true);
219         do {
220             junk = GETTXT(false, true, true);
221         } while
222         (junk > 0);
223         *pword2 = GETTXT(true, true, true);
224         *pword2x = GETTXT(false, true, true);
225         do {
226             junk = GETTXT(false, true, true);
227         } while
228         (junk > 0);
229         if (GETTXT(true, true, true) <= 0)
230             return true;
231         rspeak(TWO_WORDS);
232     }
233 }
234
235 void echo_input(FILE* destination, char* input_prompt, char* input)
236 {
237     size_t len = strlen(input_prompt) + strlen(input) + 1;
238     char* prompt_and_input = (char*) xmalloc(len);
239     strcpy(prompt_and_input, input_prompt);
240     strcat(prompt_and_input, input);
241     fprintf(destination, "%s\n", prompt_and_input);
242     free(prompt_and_input);
243 }
244
245 char* get_input()
246 {
247     // Set up the prompt
248     char input_prompt[] = "> ";
249     if (!prompt)
250         input_prompt[0] = '\0';
251
252     // Print a blank line if game.blklin tells us to.
253     if (game.blklin == true)
254         printf("\n");
255
256     char* input;
257     while (true) {
258         if (editline)
259             input = linenoise(input_prompt);
260         else {
261             input = NULL;
262             size_t n = 0;
263             if (isatty(0))
264                 printf("%s", input_prompt);
265             IGNORE(getline(&input, &n, stdin));
266         }
267
268         if (input == NULL) // Got EOF; return with it.
269             return(input);
270         else if (input[0] == '#') // Ignore comments.
271             continue;
272         else // We have a 'normal' line; leave the loop.
273             break;
274     }
275
276     // Strip trailing newlines from the input
277     input[strcspn(input, "\n")] = 0;
278
279     linenoiseHistoryAdd(input);
280
281     if (!isatty(0))
282         echo_input(stdout, input_prompt, input);
283
284     if (logfp)
285         echo_input(logfp, input_prompt, input);
286
287     return (input);
288 }
289
290 bool YES(const char* question, const char* yes_response, const char* no_response)
291 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
292  *  if no, print Z and return false. */
293 {
294     char* reply;
295     bool outcome;
296
297     for (;;) {
298         speak(question);
299
300         reply = get_input();
301         if (reply == NULL) {
302           linenoiseFree(reply);
303           exit(EXIT_SUCCESS);
304         }
305
306         char* firstword = (char*) xmalloc(strlen(reply)+1);
307         sscanf(reply, "%s", firstword);
308
309         for (int i = 0; i < (int)strlen(firstword); ++i)
310             firstword[i] = tolower(firstword[i]);
311
312         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
313         int y = strncmp("y", firstword, sizeof("y") - 1);
314         int no = strncmp("no", firstword, sizeof("no") - 1);
315         int n = strncmp("n", firstword, sizeof("n") - 1);
316
317         free(firstword);
318
319         if (yes == 0 || y == 0) {
320             speak(yes_response);
321             outcome = true;
322             break;
323         } else if (no == 0 || n == 0) {
324             speak(no_response);
325             outcome = false;
326             break;
327         } else
328             rspeak(PLEASE_ANSWER);
329     }
330     linenoiseFree(reply);
331     return (outcome);
332 }
333
334 /*  Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
335
336 long GETTXT(bool skip, bool onewrd, bool upper)
337 /*  Take characters from an input line and pack them into 30-bit words.
338  *  Skip says to skip leading blanks.  ONEWRD says stop if we come to a
339  *  blank.  UPPER says to map all letters to uppercase.  If we reach the
340  *  end of the line, the word is filled up with blanks (which encode as 0's).
341  *  If we're already at end of line when TEXT is called, we return -1. */
342 {
343     long text;
344     static long splitting = -1;
345
346     if (LNPOSN != splitting)
347         splitting = -1;
348     text = -1;
349     while (true) {
350         if (LNPOSN > LNLENG)
351             return (text);
352         if ((!skip) || INLINE[LNPOSN] != 0)
353             break;
354         ++LNPOSN;
355     }
356
357     text = 0;
358     for (int I = 1; I <= TOKLEN; I++) {
359         text = text * 64;
360         if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
361             continue;
362         char current = INLINE[LNPOSN];
363         if (current < ascii_to_advent['%']) {
364             splitting = -1;
365             if (upper && current >= ascii_to_advent['a'])
366                 current = current - 26;
367             text = text + current;
368             ++LNPOSN;
369             continue;
370         }
371         if (splitting != LNPOSN) {
372             text = text + ascii_to_advent['%'];
373             splitting = LNPOSN;
374             continue;
375         }
376
377         text = text + current - ascii_to_advent['%'];
378         splitting = -1;
379         ++LNPOSN;
380     }
381
382     return text;
383 }
384
385 token_t MAKEWD(long letters)
386 /*  Combine TOKLEN (currently 5) uppercase letters (represented by
387  *  pairs of decimal digits in lettrs) to form a 30-bit value matching
388  *  the one that GETTXT would return given those characters plus
389  *  trailing blanks.  Caution: lettrs will overflow 31 bits if
390  *  5-letter word starts with V-Z.  As a kludgey workaround, you can
391  *  increment a letter by 5 by adding 50 to the next pair of
392  *  digits. */
393 {
394     long i = 1, word = 0;
395
396     for (long k = letters; k != 0; k = k / 100) {
397         word = word + i * (MOD(k, 50) + 10);
398         i = i * 64;
399         if (MOD(k, 100) > 50)word = word + i * 5;
400     }
401     i = 64L * 64L * 64L * 64L * 64L / i;
402     word = word * i;
403     return word;
404 }
405
406 /*  Data structure  routines */
407
408 long VOCAB(long id, long init)
409 /*  Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
410  *  -1 if not found.  If INIT is positive, this is an initialisation call setting
411  *  up a keyword variable, and not finding it constitutes a bug.  It also means
412  *  that only KTAB values which taken over 1000 equal INIT may be considered.
413  *  (Thus "STEPS", which is a motion verb as well as an object, may be located
414  *  as an object.)  And it also means the KTAB value is taken modulo 1000. */
415 {
416     long lexeme;
417
418     for (long i = 1; i <= TABSIZ; i++) {
419         if (KTAB[i] == -1) {
420             lexeme = -1;
421             if (init < 0)
422                 return (lexeme);
423             BUG(REQUIRED_VOCABULARY_WORD_NOT_FOUND);
424         }
425         if (init >= 0 && KTAB[i] / 1000 != init)
426             continue;
427         if (ATAB[i] == id) {
428             lexeme = KTAB[i];
429             if (init >= 0)
430                 lexeme = MOD(lexeme, 1000);
431             return (lexeme);
432         }
433     }
434     BUG(RAN_OFF_END_OF_VOCABULARY_TABLE);
435 }
436
437 void JUGGLE(long object)
438 /*  Juggle an object by picking it up and putting it down again, the purpose
439  *  being to get the object to the front of the chain of things at its loc. */
440 {
441     long i, j;
442
443     i = game.place[object];
444     j = game.fixed[object];
445     MOVE(object, i);
446     MOVE(object + NOBJECTS, j);
447 }
448
449 void MOVE(long object, long where)
450 /*  Place any object anywhere by picking it up and dropping it.  May
451  *  already be toting, in which case the carry is a no-op.  Mustn't
452  *  pick up objects which are not at any loc, since carry wants to
453  *  remove objects from game.atloc chains. */
454 {
455     long from;
456
457     if (object > NOBJECTS)
458         from = game.fixed[object - NOBJECTS];
459     else
460         from = game.place[object];
461     if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
462         CARRY(object, from);
463     DROP(object, where);
464 }
465
466 long PUT(long object, long where, long pval)
467 /*  PUT is the same as MOVE, except it returns a value used to set up the
468  *  negated game.prop values for the repository objects. */
469 {
470     MOVE(object, where);
471     return (-1) - pval;;
472 }
473
474 void CARRY(long object, long where)
475 /*  Start toting an object, removing it from the list of things at its former
476  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
477  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
478 {
479     long temp;
480
481     if (object <= NOBJECTS) {
482         if (game.place[object] == CARRIED)
483             return;
484         game.place[object] = CARRIED;
485         ++game.holdng;
486     }
487     if (game.atloc[where] == object) {
488         game.atloc[where] = game.link[object];
489         return;
490     }
491     temp = game.atloc[where];
492     while (game.link[temp] != object) {
493         temp = game.link[temp];
494     }
495     game.link[temp] = game.link[object];
496 }
497
498 void DROP(long object, long where)
499 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
500  *  game.holdng if the object was being toted. */
501 {
502     if (object > NOBJECTS)
503         game.fixed[object - NOBJECTS] = where;
504     else {
505         if (game.place[object] == CARRIED)
506             --game.holdng;
507         game.place[object] = where;
508     }
509     if (where <= 0)
510         return;
511     game.link[object] = game.atloc[where];
512     game.atloc[where] = object;
513 }
514
515 long ATDWRF(long where)
516 /*  Return the index of first dwarf at the given location, zero if no dwarf is
517  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
518  *  the pirate (6th dwarf). */
519 {
520     long at;
521
522     at = 0;
523     if (game.dflag < 2)
524         return (at);
525     at = -1;
526     for (long i = 1; i <= NDWARVES - 1; i++) {
527         if (game.dloc[i] == where)
528             return i;
529         if (game.dloc[i] != 0)
530             at = 0;
531     }
532     return (at);
533 }
534
535 /*  Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
536  *  randrange, RNDVOC) */
537
538 long SETBIT(long bit)
539 /*  Returns 2**bit for use in constructing bit-masks. */
540 {
541     return (1 << bit);
542 }
543
544 bool TSTBIT(long mask, int bit)
545 /*  Returns true if the specified bit is set in the mask. */
546 {
547     return (mask & (1 << bit)) != 0;
548 }
549
550 void set_seed(long seedval)
551 /* Set the LCG seed */
552 {
553     game.lcg_x = (unsigned long) seedval % game.lcg_m;
554 }
555
556 unsigned long get_next_lcg_value(void)
557 /* Return the LCG's current value, and then iterate it. */
558 {
559     unsigned long old_x = game.lcg_x;
560     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
561     return old_x;
562 }
563
564 long randrange(long range)
565 /* Return a random integer from [0, range). */
566 {
567     return range * get_next_lcg_value() / game.lcg_m;
568 }
569
570 long RNDVOC(long second, long force)
571 /*  Searches the vocabulary ATAB for a word whose second character is
572  *  char, and changes that word such that each of the other four
573  *  characters is a random letter.  If force is non-zero, it is used
574  *  as the new word.  Returns the new word. */
575 {
576     long rnd = force;
577
578     if (rnd == 0) {
579         for (int i = 1; i <= 5; i++) {
580             long j = 11 + randrange(26);
581             if (i == 2)
582                 j = second;
583             rnd = rnd * 64 + j;
584         }
585     }
586
587     long div = 64L * 64L * 64L;
588     for (int i = 1; i <= TABSIZ; i++) {
589         if (MOD(ATAB[i] / div, 64L) == second) {
590             ATAB[i] = rnd;
591             break;
592         }
593     }
594
595     return rnd;
596 }
597
598
599 /*  Machine dependent routines (MAPLIN, SAVEIO) */
600
601 bool MAPLIN(FILE *fp)
602 {
603     bool eof;
604
605     /* Read a line of input, from the specified input source.
606      * This logic is complicated partly because it has to serve
607      * several cases with different requirements and partly because
608      * of a quirk in linenoise().
609      *
610      * The quirk shows up when you paste a test log from the clipboard
611      * to the program's command prompt.  While fgets (as expected)
612      * consumes it a line at a time, linenoise() returns the first
613      * line and discards the rest.  Thus, there needs to be an
614      * editline (-s) option to fall back to fgets while still
615      * prompting.  Note that linenoise does behave properly when
616      * fed redirected stdin.
617      *
618      * The logging is a bit of a mess because there are two distinct cases
619      * in which you want to echo commands.  One is when shipping them to
620      * a log under the -l option, in which case you want to suppress
621      * prompt generation (so test logs are unadorned command sequences).
622      * On the other hand, if you redirected stdin and are feeding the program
623      * a logfile, you *do* want prompt generation - it makes checkfiles
624      * easier to read when the commands are marked by a preceding prompt.
625      */
626     do {
627         if (!editline) {
628             if (prompt)
629                 fputs("> ", stdout);
630             IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
631             eof = (feof(fp));
632         } else {
633             char *cp = linenoise("> ");
634             eof = (cp == NULL);
635             if (!eof) {
636                 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
637                 linenoiseHistoryAdd(rawbuf);
638                 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
639                 linenoiseFree(cp);
640             }
641         }
642     } while
643     (!eof && rawbuf[0] == '#');
644     if (eof) {
645         if (logfp && fp == stdin)
646             fclose(logfp);
647         return false;
648     } else {
649         FILE *efp = NULL;
650         if (logfp && fp == stdin)
651             efp = logfp;
652         else if (!isatty(0))
653             efp = stdout;
654         if (efp != NULL) {
655             if (prompt && efp == stdout)
656                 fputs("> ", efp);
657             IGNORE(fputs(rawbuf, efp));
658         }
659         strcpy(INLINE + 1, rawbuf);
660         /*  translate the chars to integers in the range 0-126 and store
661          *  them in the common array "INLINE".  Integer values are as follows:
662          *     0   = space [ASCII CODE 40 octal, 32 decimal]
663          *    1-2  = !" [ASCII 41-42 octal, 33-34 decimal]
664          *    3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
665          *   11-36 = upper-case letters
666          *   37-62 = lower-case letters
667          *    63   = percent (%) [ASCII 45 octal, 37 decimal]
668          *   64-73 = digits, 0 through 9
669          *  Remaining characters can be translated any way that is convenient;
670          *  The above mappings are required so that certain special
671          *  characters are known to fit in 6 bits and/or can be easily spotted.
672          *  Array elements beyond the end of the line should be filled with 0,
673          *  and LNLENG should be set to the index of the last character.
674          *
675          *  If the data file uses a character other than space (e.g., tab) to
676          *  separate numbers, that character should also translate to 0.
677          *
678          *  This procedure may use the map1,map2 arrays to maintain
679          *  static data for he mapping.  MAP2(1) is set to 0 when the
680          *  program starts and is not changed thereafter unless the
681          *  routines in this module choose to do so. */
682         LNLENG = 0;
683         for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
684             long val = INLINE[i];
685             INLINE[i] = ascii_to_advent[val];
686             if (INLINE[i] != 0)
687                 LNLENG = i;
688         }
689         LNPOSN = 1;
690         return true;
691     }
692 }
693
694 void DATIME(long* d, long* t)
695 {
696     struct timeval tv;
697     gettimeofday(&tv, NULL);
698     *d = (long) tv.tv_sec;
699     *t = (long) tv.tv_usec;
700 }
701
702 void bug(enum bugtype num, const char *error_string)
703 {
704     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
705     exit(EXIT_FAILURE);
706 }
707
708 /* end */