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