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