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