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