Explain the prompting logic more fully.
[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[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 < 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 i = 0; i < strlen(parameters[pi]); ++i)
109                 {
110                   parameters[pi][i] = tolower(parameters[pi][i]);
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 i = 0; i < strlen(parameters[pi]); ++i)
120                 {
121                   parameters[pi][i] = tolower(parameters[pi][i]);
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(53);
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(185);
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 i, lexeme;
320
321     for (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 DSTROY(long object)
341 /*  Permanently eliminate "object" by moving to a non-existent location. */
342 {
343     MOVE(object,0);
344 }
345
346 void JUGGLE(long object)
347 /*  Juggle an object by picking it up and putting it down again, the purpose
348  *  being to get the object to the front of the chain of things at its loc. */
349 {
350     long i, j;
351
352     i=game.place[object];
353     j=game.fixed[object];
354     MOVE(object,i);
355     MOVE(object+NOBJECTS,j);
356 }
357
358 void MOVE(long object, long where)
359 /*  Place any object anywhere by picking it up and dropping it.  May
360  *  already be toting, in which case the carry is a no-op.  Mustn't
361  *  pick up objects which are not at any loc, since carry wants to
362  *  remove objects from game.atloc chains. */
363 {
364     long from;
365
366     if (object > NOBJECTS) 
367         from=game.fixed[object-NOBJECTS];
368     else
369         from=game.place[object];
370     if (from > 0 && from <= 300)
371         CARRY(object,from);
372     DROP(object,where);
373 }
374
375 long PUT(long object, long where, long pval)
376 /*  PUT is the same as MOVE, except it returns a value used to set up the
377  *  negated game.prop values for the repository objects. */
378 {
379     MOVE(object,where);
380     return (-1)-pval;;
381 }
382
383 void CARRY(long object, long where) 
384 /*  Start toting an object, removing it from the list of things at its former
385  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
386  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
387 {
388     long temp;
389
390     if (object <= NOBJECTS) {
391         if (game.place[object] == -1)
392             return;
393         game.place[object]= -1;
394         ++game.holdng;
395     }
396     if (game.atloc[where] == object) {
397         game.atloc[where]=game.link[object];
398         return;
399     }
400     temp=game.atloc[where];
401     while (game.link[temp] != object) {
402         temp=game.link[temp];
403     }
404     game.link[temp]=game.link[object];
405 }
406
407 void DROP(long object, long where)
408 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
409  *  game.holdng if the object was being toted. */
410 {
411     if (object > NOBJECTS)
412         game.fixed[object-NOBJECTS] = where;
413     else
414     {
415         if (game.place[object] == -1)
416             --game.holdng;
417         game.place[object] = where;
418     }
419     if (where <= 0)
420         return;
421     game.link[object] = game.atloc[where];
422     game.atloc[where] = object;
423 }
424
425 long ATDWRF(long where)
426 /*  Return the index of first dwarf at the given location, zero if no dwarf is
427  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
428  *  the pirate (6th dwarf). */
429 {
430     long at, i;
431
432     at =0;
433     if (game.dflag < 2)
434         return(at);
435     at = -1;
436     for (i=1; i<=NDWARVES-1; i++) {
437         if (game.dloc[i] == where)
438             return i;
439         if (game.dloc[i] != 0)
440             at=0;
441     }
442     return(at);
443 }
444
445 /*  Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
446  *  randrange, RNDVOC, BUG) */
447
448 long SETBIT(long bit)
449 /*  Returns 2**bit for use in constructing bit-masks. */
450 {
451     return(1 << bit);
452 }
453
454 bool TSTBIT(long mask, int bit)
455 /*  Returns true if the specified bit is set in the mask. */
456 {
457     return (mask & (1 << bit)) != 0;
458 }
459
460 void set_seed(long seedval)
461 /* Set the LCG seed */
462 {
463     lcgstate.x = (unsigned long) seedval % lcgstate.m;
464 }
465
466 unsigned long get_next_lcg_value(void)
467 /* Return the LCG's current value, and then iterate it. */
468 {
469     unsigned long old_x = lcgstate.x;
470     lcgstate.x = (lcgstate.a * lcgstate.x + lcgstate.c) % lcgstate.m;
471     return old_x;
472 }
473
474 long randrange(long range)
475 /* Return a random integer from [0, range). */
476 {
477     return range * get_next_lcg_value() / lcgstate.m;
478 }
479
480 long RNDVOC(long second, long force)
481 /*  Searches the vocabulary ATAB for a word whose second character is
482  *  char, and changes that word such that each of the other four
483  *  characters is a random letter.  If force is non-zero, it is used
484  *  as the new word.  Returns the new word. */
485 {
486     long rnd = force;
487
488     if (rnd == 0) {
489         for (int i = 1; i <= 5; i++) {
490             long j = 11 + randrange(26);
491             if (i == 2)
492                 j = second;
493             rnd = rnd * 64 + j;
494         }
495     }
496
497     long div = 64L * 64L * 64L;
498     for (int i = 1; i <= TABSIZ; i++) {
499         if (MOD(ATAB[i]/div, 64L) == second)
500         {
501             ATAB[i] = rnd;
502             break;
503         }
504     }
505
506     return rnd;
507 }
508
509 void BUG(long num)
510 /*  The following conditions are currently considered fatal bugs.  Numbers < 20
511  *  are detected while reading the database; the others occur at "run time".
512  *      0       Message line > 70 characters
513  *      1       Null line in message
514  *      2       Too many words of messages
515  *      3       Too many travel options
516  *      4       Too many vocabulary words
517  *      5       Required vocabulary word not found
518  *      6       Too many RTEXT messages
519  *      7       Too many hints
520  *      8       Location has cond bit being set twice
521  *      9       Invalid section number in database
522  *      10      Too many locations
523  *      11      Too many class or turn messages
524  *      20      Special travel (500>L>300) exceeds goto list
525  *      21      Ran off end of vocabulary table
526  *      22      Vocabulary type (N/1000) not between 0 and 3
527  *      23      Intransitive action verb exceeds goto list
528  *      24      Transitive action verb exceeds goto list
529  *      25      Conditional travel entry with no alternative
530  *      26      Location has no travel entries
531  *      27      Hint number exceeds goto list
532  *      28      Invalid month returned by date function
533  *      29      Too many parameters given to SETPRM */
534 {
535
536     printf("Fatal error %ld.  See source code for interpretation.\n", num);
537     exit(0);
538 }
539
540 /*  Machine dependent routines (MAPLIN, TYPE, SAVEIO) */
541
542 bool MAPLIN(FILE *fp)
543 {
544     long i, val;
545     bool eof;
546
547     /* Read a line of input, from the specified input source.
548      * This logic is complicated partly because it has to serve 
549      * several cases with different requirements and partly because
550      * of a quirk in linenoise().
551      *
552      * The quirk shows up when you paste a test log from the clipboard
553      * to the program's command prompt.  While fgets (as expected)
554      * consumes it a line at a time, linenoise() returns the first
555      * line and discards the rest.  Thus, there needs to be an
556      * editline (-s) option to fall back to fgets while still
557      * prompting.  Note that linenoise does behave properly when
558      * fed redirected stdin.
559      *
560      * The logging is a bit of a mess because there are two distinct cases
561      * in which you want to echo commands.  One is when shipping them to 
562      * a log under the -l option, in which case you want to suppress
563      * prompt generation (so test logs are unadorned command sequences).
564      * On the other hand, if you redireceted stdin and are feeding the program 
565      * a logfile, you *do* want prompt generation - it makes checkfiles
566      * easier to read when the commands are maked by a preceding prompt.
567      */
568     do {
569         if (!editline) {
570             if (prompt)
571                 fputs("> ", stdout);
572             IGNORE(fgets(rawbuf,sizeof(rawbuf)-1,fp));
573             eof = (feof(fp));
574         } else {
575             char *cp = linenoise("> ");
576             eof = (cp == NULL);
577             if (!eof) {
578                 strncpy(rawbuf, cp, sizeof(rawbuf)-1);
579                 linenoiseHistoryAdd(rawbuf);
580                 strncat(rawbuf, "\n", sizeof(rawbuf)-1);
581                 linenoiseFree(cp);
582             }
583         }
584     } while
585             (!eof && rawbuf[0] == '#');
586     if (eof) {
587         if (logfp && fp == stdin)
588             fclose(logfp);
589         return false;
590     } else {
591         FILE *efp = NULL;
592         if (logfp && fp == stdin)
593             efp = logfp;
594         else if (!isatty(0))
595             efp = stdout;
596         if (efp != NULL)
597         {
598             if (prompt && efp == stdout)
599                 fputs("> ", efp);
600             IGNORE(fputs(rawbuf, efp));
601         }
602         strcpy(INLINE+1, rawbuf);
603     /*  translate the chars to integers in the range 0-126 and store
604      *  them in the common array "INLINE".  Integer values are as follows:
605      *     0   = space [ASCII CODE 40 octal, 32 decimal]
606      *    1-2  = !" [ASCII 41-42 octal, 33-34 decimal]
607      *    3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
608      *   11-36 = upper-case letters
609      *   37-62 = lower-case letters
610      *    63   = percent (%) [ASCII 45 octal, 37 decimal]
611      *   64-73 = digits, 0 through 9
612      *  Remaining characters can be translated any way that is convenient;
613      *  The "TYPE" routine below is used to map them back to characters when
614      *  necessary.  The above mappings are required so that certain special
615      *  characters are known to fit in 6 bits and/or can be easily spotted.
616      *  Array elements beyond the end of the line should be filled with 0,
617      *  and LNLENG should be set to the index of the last character.
618      *
619      *  If the data file uses a character other than space (e.g., tab) to
620      *  separate numbers, that character should also translate to 0.
621      *
622      *  This procedure may use the map1,map2 arrays to maintain static data for
623      *  the mapping.  MAP2(1) is set to 0 when the program starts
624      *  and is not changed thereafter unless the routines on this page choose
625      *  to do so. */
626         LNLENG=0;
627         for (i=1; i<=(long)sizeof(INLINE) && INLINE[i]!=0; i++) {
628             val=INLINE[i];
629             INLINE[i]=ascii_to_advent[val];
630             if (INLINE[i] != 0)
631                 LNLENG=i;
632         }
633         LNPOSN=1;
634         return true;
635     }
636 }
637
638 void TYPE(void)
639 /*  Type the first "LNLENG" characters stored in inline, mapping them
640  *  from integers to text per the rules described above.  INLINE
641  *  may be changed by this routine. */
642 {
643     long i;
644
645     if (LNLENG == 0) {
646         printf("\n");
647         return;
648     }
649
650     for (i=1; i<=LNLENG; i++) {
651         INLINE[i]=advent_to_ascii[INLINE[i]];
652     }
653     INLINE[LNLENG+1]=0;
654     printf("%s\n", INLINE+1);
655     return;
656 }
657
658 void DATIME(long* d, long* t)
659 {
660     struct timeval tv;
661     gettimeofday(&tv, NULL);
662     *d = (long) tv.tv_sec;
663     *t = (long) tv.tv_usec;
664 }
665
666 /* end */