Debian Codegraph @

common/readable.c

raw symbols SCIP
1 /*
2 * Crossfire -- cooperative multi-player graphical RPG and adventure game
3 *
4 * Copyright (c) 1999-2014 Mark Wedel and the Crossfire Development Team
5 * Copyright (c) 1992 Frank Tore Johansen
6 *
7 * Crossfire is free software and comes with ABSOLUTELY NO WARRANTY. You are
8 * welcome to redistribute it under certain conditions. For details, please
9 * see COPYING and LICENSE.
10 *
11 * The authors can be reached via e-mail at <[email protected]>.
12 */
13
14 /**
15 * @file readable.c
16 * This file contains code relevant to the BOOKS hack -- designed
17 * to allow randomly occuring messages in non-magical texts.
18 *
19 * @todo
20 * replace message type with defines/enums & such things.
21 */
22
23 /* laid down initial file - dec 1995. -b.t. [email protected] */
24
25 #include "global.h"
26
27 #include <assert.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/stat.h>
32
33 #include "book.h"
34 #include "living.h"
35 #include "output_file.h"
36 #include "spells.h"
37
38 /* Define this if you want to archive book titles by contents.
39 * This option should enforce UNIQUE combinations of titles,authors and
40 * msg contents during and *between *game sessions.
41 * Note: a slight degeneracy exists since books are archived based on an integer
42 * index value calculated from the message text (similar to alchemy formulae).
43 * Sometimes two widely different messages have the same index value (rare). In
44 * this case, it is possible to occasionally generate 2 books with same title and
45 * different message content. Not really a bug, but rather a feature. This action
46 * should keeps player on their toes ;).
47 * Also, note that there is *finite *space available for archiving message and titles.
48 * Once this space is used, books will stop being archived. Not a serious problem
49 * under the current regime, since there are generally fewer possible (random)
50 * messages than space available on the titlelists.
51 * One exception (for sure) are the monster messages. But no worries, you should
52 * see all of the monster info in some order (but not all possble combinations)
53 * before the monster titlelist space is run out. You can increase titlelist
54 * space by increasing the array sizes for the monster book_authours and book_names
55 * (see max_titles[] array and include/read.h). Since the unique_book algorthm is
56 * kinda stupid, this program *may *slow down program execution if defined (but I don't
57 * think its a significant problem, at least, I have no problems running this option
58 * on a Sparc 10! Also, once archive title lists are filled and/or all possible msg
59 * combinations have been generated, unique_book isnt called anymore. It takes 5-10
60 * sessions for this to happen).
61 * Final note: the game remembers book/title/msg combinations from reading the
62 * file lib/bookarch. If you REMOVE this file, you will lose your archive. So
63 * be sure to copy it over to the new lib directory when you change versions.
64 * -b.t.
65 */
66
67 /* This flag is useful to see what kind of output messages are created */
68 /* #define BOOK_MSG_DEBUG */
69
70 /* This flag is useful for debugging archiving action */
71 /* #define ARCHIVE_DEBUG */
72
73 /** How many times to try to generate a unique name for a book. */
74 #define MAX_TITLE_CHECK 20
75
76 /** Message from the lib/messages file. */
77 #define MSGTYPE_LIB 0
78 /** Monster-related information. */
79 #define MSGTYPE_MONSTER 1
80 /** Artifact-related information. */
81 #define MSGTYPE_ARTIFACT 2
82 /** Spellpath-related information. */
83 #define MSGTYPE_SPELLPATH 3
84 /** Alchemy-related information. */
85 #define MSGTYPE_ALCHEMY 4
86 /** God-related information. */
87 #define MSGTYPE_GODS 5
88 /** Message from the lib/messages file. */
89 #define MSGTYPE_MSGFILE 6
90
91 /**
92 * Returns the element size of an array.
93 * @param arrayname the array's name
94 * @return the number of elements
95 */
96 #define arraysize(arrayname) (sizeof(arrayname)/sizeof(*(arrayname)))
97
98 /* Moved these structures from struct.h to this file in 0.94.3 - they
99 * are not needed anyplace else, so why have them globally declared?
100 */
101
102 /**
103 * Information on one title.
104 * 'title' and 'titlelist' are used by the readable code
105 */
106 typedef struct titlestruct {
107 const char *name; /**< the name of the book */
108 const char *authour; /**< the name of the book authour */
109 const char *archname; /**< the archetype name of the book */
110 unsigned int level; /**< level of difficulty of this message */
111 size_t size; /**< size of the book message */
112 int msg_index; /**< an index value derived from book message */
113 struct titlestruct *next; /**< next item in the list */
114 } title;
115
116 /**
117 * Titles for one message type.
118 */
119 typedef struct titleliststruct {
120 int number; /**< number of items in the list */
121 struct titlestruct *first_book; /**< pointer to first book in this list */
122 struct titleliststruct *next; /**< pointer to next book list */
123 } titlelist;
124
125 /** special structure, used only by art_name_array[] */
126 typedef struct namebytype {
127 const char *name; /**< generic name to call artifacts of this type */
128 int type; /**< matching type */
129 } arttypename;
130
131 /**
132 * One general message, from the lib/messages file.
133 */
134 struct GeneralMessage {
135 int chance; /**< Relative chance of the message appearing
136 randomly. If 0 will never appear. */
137 sstring identifier; /**< Message identifier, can be NULL. */
138 sstring title; /**< The message's title, only used for knowledge. */
139 sstring message; /**< The message's body. */
140 sstring quest_code; /**< Optional quest code and state this message will start. */
141 const Face *face; /**< Face the message displays at in the knowledge dialog, NULL if no face defined. */
142 GeneralMessage *next; /**< Next message in the list. */
143 };
144
145 static void add_book(title *book, int type, const char *fname, int lineno);
146
147 /**
148 * Buffer of books read in from the bookarch file. It's element
149 * size does not exceed arraysize(max_titles).
150 */
151 static titlelist *booklist = NULL;
152
153 /** Information on monsters. */
154 static objectlink *first_mon_info = NULL;
155
156 static int nrofmon = 0, /**< Number of monsters in the ::first_mon_info list. */
157 need_to_write_bookarchive = 0; /**< If set then we have information to save. */
158
159 /**
160 * First message from data read from the messages file.
161 * Note that this points to the last message in the file,
162 * as messages are added to the start of the list.
163 */
164 static GeneralMessage *first_msg = NULL;
165
166 /**
167 * Total chance of messages (GeneralMessage), to randomly select one.
168 */
169 static int msg_total_chance = 0;
170
171 /**
172 * Spellpath information.
173 */
174 static const uint32_t spellpathdef[NRSPELLPATHS] = {
175 PATH_PROT,
176 PATH_FIRE,
177 PATH_FROST,
178 PATH_ELEC,
179 PATH_MISSILE,
180 PATH_SELF,
181 PATH_SUMMON,
182 PATH_ABJURE,
183 PATH_RESTORE,
184 PATH_DETONATE,
185 PATH_MIND,
186 PATH_CREATE,
187 PATH_TELE,
188 PATH_INFO,
189 PATH_TRANSMUTE,
190 PATH_TRANSFER,
191 PATH_TURNING,
192 PATH_WOUNDING,
193 PATH_DEATH,
194 PATH_LIGHT
195 };
196
197 /** Book names for path information. */
198 static const char *const path_book_name[] = {
199 "codex",
200 "compendium",
201 "documentary",
202 "exposition",
203 "tables",
204 "treatise"
205 };
206
207 /** Used by spellpath texts. */
208 static const char *const path_author[] = {
209 "aether",
210 "arcana",
211 "astral byways",
212 "connections",
213 "the Grey Council",
214 "deep pathways",
215 "knowledge",
216 "magic",
217 "mystic ways",
218 "pathways",
219 "power",
220 "spells",
221 "transforms",
222 "the mystic veil",
223 "unknown spells"
224 };
225
226 /**
227 * Artiface/item information.
228 *
229 * if it isnt listed here, then art_attr_msg() will never generate
230 * a message for this type of artifact. -b.t.
231 */
232 static const arttypename art_name_array[] = {
233 { "Helmet", HELMET },
234 { "Amulet", AMULET },
235 { "Shield", SHIELD },
236 { "Bracers", BRACERS },
237 { "Boots", BOOTS },
238 { "Cloak", CLOAK },
239 { "Gloves", GLOVES },
240 { "Gridle", GIRDLE },
241 { "Ring", RING },
242 { "Horn", ROD },
243 { "Missile Weapon", BOW },
244 { "Missile", ARROW },
245 { "Hand Weapon", WEAPON },
246 { "Artifact", SKILL },
247 { "Food", FOOD },
248 { "Body Armour", ARMOUR }
249 };
250
251 /** Book titles for artifact information. */
252 static const char *const art_book_name[] = {
253 "collection",
254 "file",
255 "files",
256 "guide",
257 "handbook",
258 "index",
259 "inventory",
260 "list",
261 "listing",
262 "omnibus",
263 "record",
264 "record book"
265 };
266
267 /** Used by artifact texts */
268 static const char *const art_author[] = {
269 "ancient things",
270 "artifacts",
271 "Havlor", /* ancient warrior scribe :) */
272 "items",
273 "lost artifacts",
274 "the ancients",
275 "treasures",
276 "useful things"
277 };
278
279 /**
280 * Monster book information.
281 */
282 static const char *const mon_book_name[] = {
283 "beastuary",
284 "catalog",
285 "compilation",
286 "collection",
287 "encyclopedia",
288 "guide",
289 "handbook",
290 "list",
291 "manual",
292 "notes",
293 "omnibus",
294 "record",
295 "register",
296 "volume"
297 };
298
299 /** Used by monster beastuary texts. */
300 static const char *const mon_author[] = {
301 "beasts",
302 "creatures",
303 "dezidens",
304 "dwellers",
305 "evil nature",
306 "life",
307 "monsters",
308 "nature",
309 "new life",
310 "residents",
311 "the spawn",
312 "the living",
313 "things"
314 };
315
316 /**
317 * God book information.
318 */
319 static const char *const gods_book_name[] = {
320 "devotional",
321 "devout notes",
322 "divine text",
323 "divine work",
324 "holy book",
325 "holy record",
326 "illuminated text",
327 "moral text",
328 "sacred guide",
329 "testament",
330 "transcript"
331 };
332
333 /** Used by gods texts. */
334 static const char *const gods_author[] = {
335 "cults",
336 "joy",
337 "lasting curse",
338 "madness",
339 "religions",
340 "the dead",
341 "the gods",
342 "the heirophant",
343 "the poor priest",
344 "the priestess",
345 "pain",
346 "white"
347 };
348
349 /**
350 * Alchemy (formula) information.
351 */
352 static const char *const formula_book_name[] = {
353 "cookbook",
354 "formulary",
355 "lab book",
356 "lab notes",
357 "recipe book",
358 "experiment record",
359 "work plan",
360 "design notes",
361 "research notes",
362 "crafting manual"
363 };
364
365 /** This isn't used except for empty books. */
366 static const char *const formula_author[] = {
367 "Albertus Magnus",
368 "alchemy",
369 "balms",
370 "creation",
371 "dusts",
372 "magical manufacture",
373 "making",
374 "philosophical items",
375 "potions",
376 "powders",
377 "the cauldron",
378 "the lamp black",
379 "transmutation",
380 "waters"
381 };
382
383 /**
384 * Generic book information
385 */
386
387 /** Used by msg file and 'generic' books. */
388 static const char *const light_book_name[] = {
389 "calendar",
390 "datebook",
391 "diary",
392 "essay",
393 "guidebook",
394 "handbook",
395 "ledger",
396 "notes",
397 "notebook",
398 "octavo",
399 "opuscule",
400 "pamphlet",
401 "practicum",
402 "script",
403 "transcript"
404 };
405
406 /** Name for big books. */
407 static const char *const heavy_book_name[] = {
408 "catalog",
409 "compendium",
410 "dissertation",
411 "guide",
412 "manual",
413 "opus",
414 "tome",
415 "treatise",
416 "volume",
417 "work"
418 };
419
420 /** Used by 'generic' books. */
421 static const char *const book_author[] = {
422 "Abdulah",
423 "Al'hezred",
424 "Alywn",
425 "Arundel",
426 "Arvind",
427 "Aerlingas",
428 "Bacon",
429 "Baliqendii",
430 "Bosworth",
431 "Beathis",
432 "Bertil",
433 "Cauchy",
434 "Chakrabarti",
435 "der Waalis",
436 "Dirk",
437 "Djwimii",
438 "Eisenstaadt",
439 "Fendris",
440 "Frank",
441 "Habbi",
442 "Harlod",
443 "Ichibod",
444 "Janus",
445 "June",
446 "Laplace",
447 "Magnuson",
448 "Nandii",
449 "Nitfeder",
450 "Norris",
451 "Parael",
452 "Penhew",
453 "Sophia",
454 "Skilly",
455 "Tahir",
456 "Thockmorton",
457 "Thomas",
458 "van Helsing",
459 "van Pelt",
460 "Voormis",
461 "Xavier",
462 "Xeno",
463 "Zardoz",
464 "Zagy"
465 };
466
467 /** Book descriptions. */
468 static const char *const book_descrpt[] = {
469 "ancient",
470 "cryptic",
471 "cryptical",
472 "dusty",
473 "hierarchical",
474 "grizzled",
475 "gold-gilt",
476 "great",
477 "lost",
478 "magnificent",
479 "musty",
480 "mythical",
481 "mystical",
482 "rustic",
483 "stained",
484 "silvered",
485 "transcendental",
486 "weathered"
487 };
488
489 /**
490 * Each line of this array is a readable subtype.
491 * Be careful to keep the order. If you add readable subtype, add them
492 * at the bottom of the list. Never delete a subtype because index is used as
493 * subtype parameter in arch files!
494 */
495 static const readable_message_type readable_message_types[] = {
496 /*subtype 0 */ { 0, 0 },
497 /* book messages subtypes */
498 /*subtype 1 */ { MSG_TYPE_BOOK, MSG_TYPE_BOOK_CLASP_1 },
499 { MSG_TYPE_BOOK, MSG_TYPE_BOOK_CLASP_2 },
500 { MSG_TYPE_BOOK, MSG_TYPE_BOOK_ELEGANT_1 },
501 { MSG_TYPE_BOOK, MSG_TYPE_BOOK_ELEGANT_2 },
502 { MSG_TYPE_BOOK, MSG_TYPE_BOOK_QUARTO_1 },
503 { MSG_TYPE_BOOK, MSG_TYPE_BOOK_QUARTO_2 },
504 { MSG_TYPE_BOOK, MSG_TYPE_BOOK_SPELL_EVOKER },
505 { MSG_TYPE_BOOK, MSG_TYPE_BOOK_SPELL_PRAYER },
506 { MSG_TYPE_BOOK, MSG_TYPE_BOOK_SPELL_PYRO },
507 /*subtype 10 */ { MSG_TYPE_BOOK, MSG_TYPE_BOOK_SPELL_SORCERER },
508 { MSG_TYPE_BOOK, MSG_TYPE_BOOK_SPELL_SUMMONER },
509 /* card messages subtypes*/
510 { MSG_TYPE_CARD, MSG_TYPE_CARD_SIMPLE_1 },
511 { MSG_TYPE_CARD, MSG_TYPE_CARD_SIMPLE_2 },
512 { MSG_TYPE_CARD, MSG_TYPE_CARD_SIMPLE_3 },
513 { MSG_TYPE_CARD, MSG_TYPE_CARD_ELEGANT_1 },
514 { MSG_TYPE_CARD, MSG_TYPE_CARD_ELEGANT_2 },
515 { MSG_TYPE_CARD, MSG_TYPE_CARD_ELEGANT_3 },
516 { MSG_TYPE_CARD, MSG_TYPE_CARD_STRANGE_1 },
517 { MSG_TYPE_CARD, MSG_TYPE_CARD_STRANGE_2 },
518 /*subtype 20 */ { MSG_TYPE_CARD, MSG_TYPE_CARD_STRANGE_3 },
519 { MSG_TYPE_CARD, MSG_TYPE_CARD_MONEY_1 },
520 { MSG_TYPE_CARD, MSG_TYPE_CARD_MONEY_2 },
521 { MSG_TYPE_CARD, MSG_TYPE_CARD_MONEY_3 },
522 /* Paper messages subtypes */
523 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_NOTE_1 },
524 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_NOTE_2 },
525 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_NOTE_3 },
526 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_LETTER_OLD_1 },
527 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_LETTER_OLD_2 },
528 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_LETTER_NEW_1 },
529 /*subtype 30 */ { MSG_TYPE_PAPER, MSG_TYPE_PAPER_LETTER_NEW_2 },
530 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_ENVELOPE_1 },
531 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_ENVELOPE_2 },
532 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_SCROLL_OLD_1 },
533 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_SCROLL_OLD_2 },
534 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_SCROLL_NEW_1 },
535 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_SCROLL_NEW_2 },
536 { MSG_TYPE_PAPER, MSG_TYPE_PAPER_SCROLL_MAGIC },
537 /* road signs messages subtypes */
538 { MSG_TYPE_SIGN, MSG_TYPE_SIGN_BASIC },
539 { MSG_TYPE_SIGN, MSG_TYPE_SIGN_DIR_LEFT },
540 /*subtype 40 */ { MSG_TYPE_SIGN, MSG_TYPE_SIGN_DIR_RIGHT },
541 { MSG_TYPE_SIGN, MSG_TYPE_SIGN_DIR_BOTH },
542 /* stones and monument messages */
543 { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_STONE_1 },
544 { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_STONE_2 },
545 { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_STONE_3 },
546 { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_STATUE_1 },
547 { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_STATUE_2 },
548 { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_STATUE_3 },
549 { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_GRAVESTONE_1 },
550 { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_GRAVESTONE_2 },
551 /*subtype 50 */ { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_GRAVESTONE_3 },
552 { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_WALL_1 },
553 { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_WALL_2 },
554 { MSG_TYPE_MONUMENT, MSG_TYPE_MONUMENT_WALL_3 },
555 { MSG_TYPE_SIGN, MSG_TYPE_SIGN_MAGIC_MOUTH }
556 };
557
558 /** Number of elements in ::readable_message_types. */
559 static const int last_readable_subtype = arraysize(readable_message_types);
560
561 /** Number of titles for different name lists. */
562 static const int max_titles[6] = {
563 (arraysize(light_book_name)+arraysize(heavy_book_name))*arraysize(book_author), /* MSGTYPE_LIB */
564 arraysize(mon_book_name)*arraysize(mon_author), /* MSGTYPE_MONSTER */
565 arraysize(art_book_name)*arraysize(art_author), /* MSGTYPE_ARTIFACT */
566 arraysize(path_book_name)*arraysize(path_author), /* MSGTYPE_SPELLPATH */
567 arraysize(formula_book_name)*arraysize(formula_author), /* MSGTYPE_ALCHEMY */
568 arraysize(gods_book_name)*arraysize(gods_author), /* MSGTYPE_GODS */
569 };
570
571 /******************************************************************************
572 *
573 * Start of misc. readable functions used by others functions in this file
574 *
575 *****************************************************************************/
576
577 /**
578 * Creates a titlelist.
579 *
580 * @return
581 * new titlelist.
582 *
583 * @note
584 * if memory allocation failes, calls fatal().
585 */
586 static titlelist *get_empty_booklist(void) {
587 titlelist *bl = (titlelist *)malloc(sizeof(titlelist));
588
589 if (bl == NULL)
590 fatal(OUT_OF_MEMORY);
591 bl->number = 0;
592 bl->first_book = NULL;
593 bl->next = NULL;
594 return bl;
595 }
596
597 /**
598 * Creates a title.
599 *
600 * @return
601 * new title.
602 *
603 * @note
604 * if memory allocation failes, calls fatal().
605 */
606 static title *get_empty_book(void) {
607 title *t = (title *)malloc(sizeof(title));
608
609 if (t == NULL)
610 fatal(OUT_OF_MEMORY);
611 t->name = NULL;
612 t->archname = NULL;
613 t->authour = NULL;
614 t->level = 0;
615 t->size = 0;
616 t->msg_index = 0;
617 t->next = NULL;
618 return t;
619 }
620
621 /**
622 * Gets the ith titlelist.
623 *
624 * Will create items if they don't exist.
625 *
626 * @param i
627 * index to get.
628 * @return
629 * pointer to the title list referenced by i. Will never be NULL.
630 */
631 static titlelist *get_titlelist(int i) {
632 titlelist *tl;
633 int number;
634
635 if (i < 0 || i >= (int)arraysize(max_titles)) {
636 LOG(llevInfo, "Warning: invalid book index %d, using 0 instead\n", i);
637 return booklist;
638 }
639
640 for (tl = booklist, number = i; tl && number; tl = tl->next, number--) {
641 if (!tl->next)
642 tl->next = get_empty_booklist();
643 }
644
645 return tl;
646 }
647
648 /* HANDMADE STRING FUNCTIONS.., perhaps these belong in another file
649 * (shstr.c ?), but the quantity BOOK_BUF will need to be defined. */
650
651 /**
652 * Simple routine to return the number of list
653 * items in buf1 as separated by the value of buf2
654 *
655 * @param buf1
656 * items we want to split.
657 * @param buf2
658 * what to split by.
659 * @return
660 * number of elements.
661 */
662 int nstrtok(const char *buf1, const char *buf2) {
663 char *tbuf, buf[MAX_BUF];
664 int number = 0;
665
666 if (!buf1 || !buf2)
667 return 0;
668
669 strlcpy(buf, buf1, sizeof(buf));
670 for (tbuf = strtok(buf, buf2); tbuf; tbuf = strtok(NULL, buf2)) {
671 number++;
672 }
673 return number;
674 }
675
676 /**
677 * Takes a string in buf1 and separates it into
678 * a list of strings delimited by buf2. Then returns a comma
679 * separated string w/ decent punctuation.
680 *
681 * @param buf1
682 * buffer to split.
683 * @param buf2
684 * what to split buf1 by.
685 * @param retbuf
686 * where to write the resulting string.
687 * @param size
688 * length of retbuf.
689 * @return
690 * retbuf.
691 */
692 char *strtoktolin(const char *buf1, const char *buf2, char *retbuf, size_t size) {
693 int maxi, i = nstrtok(buf1, buf2);
694 char *tbuf, buf[MAX_BUF];
695
696 maxi = i;
697 strlcpy(buf, buf1, sizeof(buf));
698 snprintf(retbuf, size, " ");
699 for (tbuf = strtok(buf, buf2); tbuf && i > 0; tbuf = strtok(NULL, buf2)) {
700 snprintf(retbuf+strlen(retbuf), size-strlen(retbuf), "%s", tbuf);
701 i--;
702 if (i == 1 && maxi > 1)
703 snprintf(retbuf+strlen(retbuf), size-strlen(retbuf), " and ");
704 else if (i > 0 && maxi > 1)
705 snprintf(retbuf+strlen(retbuf), size-strlen(retbuf), ", ");
706 else
707 snprintf(retbuf+strlen(retbuf), size-strlen(retbuf), ".");
708 }
709 return retbuf;
710 }
711
712 /**
713 * Checks if buf1 and buf2 can be combined.
714 * @param buf1
715 * @param buf2
716 * buffer we plan on combining.
717 * @param booksize
718 * maximum book size.
719 * @return
720 * 0 if buffers can be combined, 1 else.
721 */
722 int book_overflow(const char *buf1, const char *buf2, size_t booksize) {
723 if (buf_overflow(buf1, buf2, BOOK_BUF-2) /* 2 less so always room for trailing \n */
724 || buf_overflow(buf1, buf2, booksize))
725 return 1;
726 return 0;
727 }
728
729 /*****************************************************************************
730 *
731 * Start of initialization related functions.
732 *
733 ****************************************************************************/
734
735 /**
736 * If not called before, initialize the info list.
737 *
738 * Reads the messages file into the list pointed to by first_msg
739 */
740 static void init_msgfile(void) {
741 FILE *fp;
742 char buf[MAX_BUF], msgbuf[HUGE_BUF], fname[MAX_BUF], *cp;
743 int text = 0, nrofmsg = 0;
744 static int did_init_msgfile = 0;
745
746 if (did_init_msgfile)
747 return;
748 did_init_msgfile = 1;
749
750 snprintf(fname, sizeof(fname), "%s/messages", settings.datadir);
751 LOG(llevDebug, "Reading messages from %s...\n", fname);
752
753 fp = fopen(fname, "r");
754 if (fp != NULL) {
755 GeneralMessage *tmp = NULL;
756 int lineno;
757 int error_lineno;
758
759 error_lineno = 0;
760 for (lineno = 1; fgets(buf, MAX_BUF, fp) != NULL; lineno++) {
761 if (*buf == '#')
762 continue;
763 cp = strchr(buf, '\n');
764 if (cp != NULL) {
765 // Remove trailing whitespace
766 while (cp > buf && (cp[-1] == ' ' || cp[-1] == '\t'))
767 cp--;
768 /* If we make sure there is a newline here,
769 * we can avoid the auto-append of it and make long
770 * blocks of text not get split.
771 * But only do that if we are getting the message.
772 * Everywhere else we do not want the newline.
773 * Daniel Hawkins 2018-10-24
774 */
775 if (text)
776 {
777 *cp = '\n';
778 // to have found a newline means we have room for a null terminator, too
779 *(++cp)= '\0';
780 }
781 else
782 *cp = '\0';
783 }
784 if (tmp != NULL) {
785 if (text && strncmp(buf, "ENDMSG", 6) == 0) {
786 if (strlen(msgbuf) > BOOK_BUF) {
787 LOG(llevDebug, "Warning: this string exceeded max book buf size:\n");
788 LOG(llevDebug, " %s\n", msgbuf);
789 }
790 tmp->message = add_string(msgbuf);
791 tmp->next = first_msg;
792 first_msg = tmp;
793 nrofmsg++;
794 if (tmp->identifier != NULL && tmp->title == NULL) {
795 LOG(llevError, "Error: message can't have identifier without title, on line %d\n", error_lineno);
796 fatal(SEE_LAST_ERROR);
797 }
798 tmp = NULL;
799 text = 0;
800 } else if (text) {
801 if (!buf_overflow(msgbuf, buf, HUGE_BUF-1)) {
802 strcat(msgbuf, buf);
803 // If there is a newline in the text, it will be included in the output where it belongs
804 // We should avoid really long lines of text getting split up this way.
805 } else if (error_lineno != 0) {
806 LOG(llevInfo, "Warning: truncating book at %s, line %d\n", fname, error_lineno);
807 }
808 } else if (strcmp(buf, "TEXT") == 0) {
809 text = 1;
810 } else if (strncmp(buf, "CHANCE ", 7) == 0) {
811 tmp->chance = atoi(buf + 7);
812 msg_total_chance += tmp->chance;
813 } else if (strncmp(buf, "TITLE ", 6) == 0) {
814 tmp->title = add_string(buf + 6);
815 } else if (strncmp(buf, "QUEST ", 6) == 0) {
816 tmp->quest_code = add_string(buf + 6);
817 } else if (strncmp(buf, "FACE ", 5) == 0) {
818 const Face *face = find_face(buf + 5, NULL);
819 if (face != NULL) {
820 tmp->face = face;
821 } else {
822 LOG(llevInfo, "Warning: unknown face %s for message %s, line %d\n", buf + 5, tmp->identifier, error_lineno);
823 }
824 } else if (error_lineno != 0) {
825 LOG(llevInfo, "Warning: unknown line %s, line %d\n", buf, error_lineno);
826 }
827 } else if (strncmp(buf, "MSG", 3) == 0) {
828 error_lineno = lineno;
829 tmp = (GeneralMessage *)calloc(1, sizeof(GeneralMessage));
830 tmp->face = NULL;
831 strcpy(msgbuf, ""); /* reset msgbuf for new message */
832 if (buf[3] == ' ') {
833 int i = 4;
834 while (buf[i] == ' ' && buf[i] != '\0')
835 i++;
836 if (buf[i] != '\0') {
837 tmp->identifier = add_string(buf + i);
838 if (get_message_from_identifier(buf + i)) {
839 LOG(llevError, "Duplicated message identifier %s at line %d\n", buf + i, error_lineno);
840 fatal(SEE_LAST_ERROR);
841 }
842 }
843 }
844 } else {
845 LOG(llevInfo, "Warning: syntax error at %s, line %d\n", fname, lineno);
846 }
847 }
848 fclose(fp);
849
850 if (tmp != NULL) {
851 LOG(llevError, "Invalid file %s", fname);
852 fatal(SEE_LAST_ERROR);
853 }
854 }
855
856 LOG(llevDebug, "done messages, found %d for total chance %d.\n", nrofmsg, msg_total_chance);
857 }
858
859 /**
860 * If not called before, initialize the info list.
861 *
862 * This reads in the bookarch file into memory. bookarch is the file
863 * created and updated across multiple runs of the program.
864 */
865 static void init_book_archive(void) {
866 FILE *fp;
867 int nroftitle = 0;
868 char buf[MAX_BUF], fname[MAX_BUF], *cp;
869 static int did_init_barch = 0;
870
871 if (did_init_barch)
872 return;
873 did_init_barch = 1;
874
875 if (!booklist)
876 booklist = get_empty_booklist();
877
878 snprintf(fname, sizeof(fname), "%s/bookarch", settings.localdir);
879 LOG(llevDebug, " Reading bookarch from %s...\n", fname);
880
881 fp = fopen(fname, "r");
882 if (fp != NULL) {
883 int type;
884 size_t i;
885 titlelist *bl;
886 int lineno;
887 title *book;
888 int skipping;
889
890 skipping = 0;
891 book = NULL;
892 type = -1;
893 for (lineno = 1; fgets(buf, MAX_BUF, fp) != NULL; lineno++) {
894 int len;
895 int value;
896
897 if (*buf == '#')
898 continue;
899 cp = strchr(buf, '\n');
900 if (cp != NULL) {
901 while (cp > buf && (cp[-1] == ' ' || cp[-1] == '\t'))
902 cp--;
903 *cp = '\0';
904 }
905 cp = buf;
906 if (strncmp(buf, "title ", 6) == 0) {
907 skipping = 0;
908 cp = buf+6;
909 while (*cp == ' ' || *cp == '\t')
910 cp++;
911 if (*cp == '\0') {
912 LOG(llevInfo, "Warning: missing book title at %s, line %d\n", fname, lineno);
913 book = NULL;
914 } else {
915 book = get_empty_book(); /* init new book entry */
916 book->name = add_string(cp);
917 type = -1;
918 nroftitle++;
919 }
920 } else if (book == NULL) {
921 if (!skipping) {
922 skipping = 1;
923 LOG(llevInfo, "Warning: expecting 'title' at %s, line %d\n", fname, lineno);
924 }
925 } else if (strncmp(buf, "authour ", 8) == 0) {
926 cp = buf+8;
927 while (*cp == ' ' || *cp == '\t')
928 cp++;
929 if (*cp == '\0') {
930 LOG(llevInfo, "Warning: missing book authour at %s, line %d\n", fname, lineno);
931 } else {
932 book->authour = add_string(cp);
933 }
934 } else if (strncmp(buf, "arch ", 5) == 0) {
935 cp = buf+5;
936 while (*cp == ' ' || *cp == '\t')
937 cp++;
938 if (*cp == '\0') {
939 LOG(llevInfo, "Warning: missing book arch at %s, line %d\n", fname, lineno);
940 } else {
941 book->archname = add_string(cp);
942 }
943 } else if (sscanf(buf, "level %d%n", &value, &len) == 1 && len == (int)strlen(buf)) {
944 book->level = value;
945 } else if (sscanf(buf, "type %d%n", &value, &len) == 1 && len == (int)strlen(buf)) {
946 type = value;
947 } else if (sscanf(buf, "size %d%n", &value, &len) == 1 && len == (int)strlen(buf)) {
948 book->size = value;
949 } else if (sscanf(buf, "index %d%n", &value, &len) == 1 && len == (int)strlen(buf)) {
950 book->msg_index = value;
951 } else if (strcmp(buf, "end") == 0) { /* link it */
952 add_book(book, type, fname, lineno);
953 book = NULL;
954 type = -1;
955 } else {
956 LOG(llevInfo, "Warning: syntax error at %s, line %d\n", fname, lineno);
957 }
958 }
959 if (book != NULL) {
960 LOG(llevInfo, "Warning: missing 'end' at %s, line %d\n", fname, lineno);
961 add_book(book, type, fname, lineno);
962 }
963 LOG(llevDebug, " book archives(used/avail):\n");
964 for (bl = booklist, i = 0; bl != NULL && i < arraysize(max_titles); bl = bl->next, i++) {
965 LOG(llevDebug, "(%d/%d)\n", bl->number, max_titles[i]);
966 }
967 fclose(fp);
968 }
969
970 #ifdef BOOK_MSG_DEBUG
971 LOG(llevDebug, "\n init_book_archive() got %d titles.\n", nroftitle);
972 #endif
973 LOG(llevDebug, " done.\n");
974 }
975
976 /**
977 * Appends a book to the booklist.
978 * @param book the book to add
979 * @param type the book type
980 * @param fname the file name; for error messages
981 * @param lineno the line number; for error messages
982 */
983 static void add_book(title *book, int type, const char *fname, int lineno) {
984 titlelist *bl;
985
986 if (type == -1) {
987 LOG(llevInfo, "Warning: book with no type at %s, line %d; using type 0\n", fname, lineno);
988 type = 0;
989 }
990
991 bl = get_titlelist(type);
992 book->next = bl->first_book;
993 bl->first_book = book;
994 bl->number++;
995 }
996
997 /**
998 * Creates the linked list of pointers to
999 * monster archetype objects if not called previously.
1000 */
1001 static void init_mon_info(void) {
1002 archetype *at;
1003 static int did_init_mon_info = 0;
1004
1005 if (did_init_mon_info)
1006 return;
1007 did_init_mon_info = 1;
1008
1009 for (at = first_archetype; at != NULL; at = at->next) {
1010 if (QUERY_FLAG(&at->clone, FLAG_MONSTER)
1011 && (!QUERY_FLAG(&at->clone, FLAG_CHANGING) || QUERY_FLAG(&at->clone, FLAG_UNAGGRESSIVE))) {
1012 objectlink *mon = (objectlink *)malloc(sizeof(objectlink));
1013 if (!mon) {
1014 LOG(llevError, "init_mon_info: malloc failed!\n");
1015 abort();
1016 }
1017 mon->ob = &at->clone;
1018 mon->id = nrofmon;
1019 mon->next = first_mon_info;
1020 first_mon_info = mon;
1021 nrofmon++;
1022 }
1023 }
1024 LOG(llevDebug, "init_mon_info() got %d monsters\n", nrofmon);
1025 }
1026
1027 /**
1028 * Initialize linked lists utilized by message functions in tailor_readable_ob()
1029 *
1030 * This is the function called by the main routine to initialize
1031 * all the readable information.
1032 */
1033 void init_readable(void) {
1034 static int did_this = 0;
1035
1036 if (did_this)
1037 return;
1038 did_this = 1;
1039
1040 LOG(llevDebug, "Initializing reading data...\n");
1041 init_msgfile();
1042 init_book_archive();
1043 init_mon_info();
1044 LOG(llevDebug, " done reading data\n");
1045 }
1046
1047 /*****************************************************************************
1048 *
1049 * This is the start of the administrative functions when creating
1050 * new books (ie, updating title and the like)
1051 *
1052 *****************************************************************************/
1053
1054 /**
1055 * Search the titlelist (based on msgtype) to see if
1056 * book matches something already there. IF so, return that title.
1057 *
1058 * @param book
1059 * book we're searching.
1060 * @param msgtype
1061 * message type.
1062 * @return
1063 * title if found, NULL if no match.
1064 */
1065 static title *find_title(const object *book, int msgtype) {
1066 title *t;
1067 titlelist *tl;
1068 size_t length;
1069 int index;
1070
1071 if (msgtype < 0)
1072 return (title *)NULL;
1073
1074 tl = get_titlelist(msgtype);
1075 if (!tl)
1076 return (title *)NULL;
1077
1078 length = strlen(book->msg);
1079 index = strtoint(book->msg);
1080 for (t = tl->first_book; t; t = t->next)
1081 if (t->size == length && t->msg_index == index) {
1082 #ifdef ARCHIVE_DEBUG
1083 LOG(llevDebug, "Found title match (list %d): %s %s (%d)\n", msgtype, t->name, t->authour, t->msg_index);
1084 #endif
1085 return t;
1086 }
1087
1088 return (title *)NULL;
1089 }
1090
1091 /**
1092 * Only for objects of type BOOK. SPELLBOOK stuff is
1093 * handled directly in change_book_name(). Names are based on text
1094 * msgtype
1095 *
1096 * This sets book book->name based on msgtype given. What name
1097 * is given is based on various criteria
1098 *
1099 * @param book
1100 * book we want to alter.
1101 * @param msgtype
1102 * what information we want in the book.
1103 */
1104 static void new_text_name(object *book, int msgtype) {
1105 const char *name;
1106
1107 if (book->type != BOOK)
1108 return;
1109
1110 switch (msgtype) {
1111 case MSGTYPE_MONSTER:
1112 name = mon_book_name[RANDOM()%arraysize(mon_book_name)];
1113 break;
1114
1115 case MSGTYPE_ARTIFACT:
1116 name = art_book_name[RANDOM()%arraysize(art_book_name)];
1117 break;
1118
1119 case MSGTYPE_SPELLPATH:
1120 name = path_book_name[RANDOM()%arraysize(path_book_name)];
1121 break;
1122
1123 case MSGTYPE_ALCHEMY:
1124 name = formula_book_name[RANDOM()%arraysize(formula_book_name)];
1125 break;
1126
1127 case MSGTYPE_GODS:
1128 name = gods_book_name[RANDOM()%arraysize(gods_book_name)];
1129 break;
1130
1131 case MSGTYPE_MSGFILE:
1132 default:
1133 if (book->weight > 2000) { /* based on weight */
1134 name = heavy_book_name[RANDOM()%arraysize(heavy_book_name)];
1135 } else {
1136 name = light_book_name[RANDOM()%arraysize(light_book_name)];
1137 }
1138 break;
1139 }
1140 free_string(book->name);
1141 book->name = add_string(name);
1142 }
1143
1144 /**
1145 * A lot like new_text_name() above, but instead chooses an author
1146 * and sets op->title to that value
1147 *
1148 * @param op
1149 * book to alter.
1150 * @param msgtype
1151 * information we want.
1152 */
1153 static void add_author(object *op, int msgtype) {
1154 char title[MAX_BUF];
1155 const char *name;
1156
1157 if (msgtype < 0 || strlen(op->msg) < 5)
1158 return;
1159
1160 switch (msgtype) {
1161 case MSGTYPE_MONSTER:
1162 name = mon_author[RANDOM()%arraysize(mon_author)];
1163 break;
1164
1165 case MSGTYPE_ARTIFACT:
1166 name = art_author[RANDOM()%arraysize(art_author)];
1167 break;
1168
1169 case MSGTYPE_SPELLPATH:
1170 name = path_author[RANDOM()%arraysize(path_author)];
1171 break;
1172
1173 case MSGTYPE_ALCHEMY:
1174 name = formula_author[RANDOM()%arraysize(formula_author)];
1175 break;
1176
1177 case MSGTYPE_GODS:
1178 name = gods_author[RANDOM()%arraysize(gods_author)];
1179 break;
1180
1181 case MSGTYPE_MSGFILE:
1182 default:
1183 name = book_author[RANDOM()%arraysize(book_author)];
1184 }
1185
1186 snprintf(title, sizeof(title), "of %s", name);
1187 op->title = add_string(title);
1188 }
1189
1190 /**
1191 * Check to see if the book title/msg is unique. We
1192 * go through the entire list of possibilities each time. If we find
1193 * a match, then unique_book returns true (because inst unique).
1194 *
1195 * @param book
1196 * book we're searching.
1197 * @param msgtype
1198 * type of information contained.
1199 * @return
1200 */
1201 static int unique_book(const object *book, int msgtype) {
1202 title *test;
1203
1204 if (!booklist)
1205 return 1; /* No archival entries! Must be unique! */
1206
1207 /* Go through the booklist. If the author and name match, not unique so
1208 * return 0.
1209 */
1210 for (test = get_titlelist(msgtype)->first_book; test; test = test->next) {
1211 if (!strcmp(test->name, book->name) && !strcmp(book->title, test->authour))
1212 return 0;
1213 }
1214 return 1;
1215 }
1216
1217 /**
1218 * Adds a book to the list of existing books.
1219 *
1220 * @param book
1221 * book to add.
1222 * @param msgtype
1223 * what information the book contains.
1224 */
1225 static void add_book_to_list(const object *book, int msgtype) {
1226 titlelist *tl = get_titlelist(msgtype);
1227 title *t;
1228
1229 if (!tl) {
1230 LOG(llevError, "add_book_to_list can't get booklist!\n");
1231 return;
1232 }
1233
1234 t = get_empty_book();
1235 t->name = add_string(book->name);
1236 t->authour = add_string(book->title);
1237 t->size = strlen(book->msg);
1238 t->msg_index = strtoint(book->msg);
1239 t->archname = add_string(book->arch->name);
1240 t->level = book->level;
1241
1242 t->next = tl->first_book;
1243 tl->first_book = t;
1244 tl->number++;
1245
1246 /* We have stuff we need to write now */
1247 need_to_write_bookarchive = 1;
1248
1249 #ifdef ARCHIVE_DEBUG
1250 LOG(llevDebug, "Archiving new title: %s %s (%d)\n", book->name, book->title, msgtype);
1251 #endif
1252 }
1253
1254 /**
1255 * Give a new, fancier name to generated
1256 * objects of type BOOK and SPELLBOOK.
1257 * Aug 96 I changed this so we will attempt to create consistent
1258 * authour/title and message content for BOOKs. Also, we will
1259 * alter books that match archive entries to the archival
1260 * levels and architypes. -b.t.
1261 *
1262 * @param book
1263 * book to alter. Should be of type BOOK.
1264 * @param msgtype
1265 * what information the book contains.
1266 */
1267 static void change_book(object *book, int msgtype) {
1268 titlelist *tl;
1269 title *t;
1270 int tries;
1271
1272 if (book->type != BOOK) {
1273 LOG(llevError, "change_book_name() called w/ illegal obj type.\n");
1274 return;
1275 }
1276
1277 tl = get_titlelist(msgtype);
1278 t = NULL;
1279 tries = 0;
1280
1281 /* look to see if our msg already been archived. If so, alter
1282 * the book to match the archival text. If we fail to match,
1283 * then we archive the new title/name/msg combo if there is
1284 * room on the titlelist.
1285 */
1286
1287 if (strlen(book->msg) > 5 && (t = find_title(book, msgtype))) {
1288 object *tmpbook;
1289 sstring marker = object_get_value(book, "knowledge_marker");
1290
1291 /* alter book properties */
1292 tmpbook = create_archetype(t->archname);
1293 if (marker != NULL)
1294 /* need to copy the knowledge_marker */
1295 object_set_value(tmpbook, "knowledge_marker", marker, 1);
1296 object_set_msg(tmpbook, book->msg);
1297 object_copy(tmpbook, book);
1298 object_free_drop_inventory(tmpbook);
1299
1300 book->title = add_string(t->authour);
1301 free_string(book->name);
1302 book->name = add_string(t->name);
1303 book->level = t->level;
1304 } else { /* Don't have any default title, so lets make up a new one */
1305 int numb, maxnames = max_titles[msgtype];
1306 const char *old_title;
1307 const char *old_name;
1308
1309 old_title = book->title ? add_string(book->title) : NULL;
1310 old_name = add_string(book->name);
1311
1312 /* some pre-generated books have title already set (from
1313 * maps), also don't bother looking for unique title if
1314 * we already used up all the available names! */
1315
1316 if (!tl) {
1317 LOG(llevError, "change_book_name(): can't find title list\n");
1318 numb = 0;
1319 } else
1320 numb = tl->number;
1321
1322 if (numb == maxnames) {
1323 #ifdef ARCHIVE_DEBUG
1324 LOG(llevDebug, "titles for list %d full (%d possible).\n", msgtype, maxnames);
1325 #endif
1326 if (old_title != NULL)
1327 free_string(old_title);
1328 free_string(old_name);
1329 return;
1330 }
1331 /* shouldnt change map-maker books */
1332 if (!book->title)
1333 do {
1334 /* random book name */
1335 new_text_name(book, msgtype);
1336 add_author(book, msgtype); /* random author */
1337 tries++;
1338 } while (!unique_book(book, msgtype) && tries < MAX_TITLE_CHECK);
1339
1340 /* Now deal with 2 cases.
1341 * 1) If no space for a new title exists lets just restore
1342 * the old book properties. Remember, if the book had
1343 * matchd an older entry on the titlelist, we shouldnt
1344 * have called this routine in the first place!
1345 * 2) If we got a unique title, we need to add it to
1346 * the list.
1347 */
1348
1349 if (tries == MAX_TITLE_CHECK) {
1350 #ifdef ARCHIVE_DEBUG
1351 LOG(llevDebug, "Failed to obtain unique title for %s %s (names:%d/%d)\n", book->name, book->title, numb, maxnames);
1352 #endif
1353 /* restore old book properties here */
1354 free_string(book->name);
1355 free_string(book->title);
1356 book->title = old_title != NULL ? add_string(old_title) : NULL;
1357
1358 if (RANDOM()%4) {
1359 /* Lets give the book a description to individualize it some */
1360 char new_name[MAX_BUF];
1361
1362 snprintf(new_name, MAX_BUF, "%s %s", book_descrpt[RANDOM()%arraysize(book_descrpt)], old_name);
1363 book->name = add_string(new_name);
1364 } else {
1365 book->name = add_string(old_name);
1366 }
1367 } else if (book->title && strlen(book->msg) > 5) { /* archive if long msg texts */
1368 add_book_to_list(book, msgtype);
1369 }
1370
1371 if (old_title != NULL)
1372 free_string(old_title);
1373 free_string(old_name);
1374 }
1375 }
1376
1377 /*****************************************************************************
1378 *
1379 * This is the start of the area that generates the actual contents
1380 * of the book.
1381 *
1382 *****************************************************************************/
1383
1384 /*****************************************************************************
1385 * Monster msg generation code.
1386 ****************************************************************************/
1387
1388 /**
1389 * Returns a random monster selected from linked
1390 * list of all monsters in the current game.
1391 * Changed 971225 to be greater than equal to level passed. Also
1392 * made choosing by level more random.
1393 *
1394 * @param level
1395 * if non-zero, then only monsters greater than that level will be returned.
1396 * @return
1397 * random monster, or NULL if failure.
1398 */
1399 object *get_random_mon(int level) {
1400 objectlink *mon;
1401 int i, monnr;
1402
1403 /* safety check. Problem w/ init_mon_info list? */
1404 if (!nrofmon || !first_mon_info)
1405 return (object *)NULL;
1406
1407 if (!level) {
1408 /* lets get a random monster from the mon_info linked list */
1409 monnr = RANDOM()%nrofmon;
1410
1411 for (mon = first_mon_info, i = 0; mon; mon = mon->next, i++)
1412 if (i == monnr)
1413 break;
1414
1415 if (!mon) {
1416 LOG(llevError, "get_random_mon: Didn't find a monster when we should have\n");
1417 return NULL;
1418 }
1419 return mon->ob;
1420 }
1421
1422 /* Case where we are searching by level. Redone 971225 to be clearer
1423 * and more random. Before, it looks like it took a random monster from
1424 * the list, and then returned the first monster after that which was
1425 * appropriate level. This wasn't very random because if you had a
1426 * bunch of low level monsters and then a high level one, if the random
1427 * determine took one of the low level ones, it would just forward to the
1428 * high level one and return that. Thus, monsters that immediately followed
1429 * a bunch of low level monsters would be more heavily returned. It also
1430 * means some of the dragons would be poorly represented, since they
1431 * are a group of high level monsters all around each other.
1432 */
1433
1434 /* First count number of monsters meeting level criteria */
1435 for (mon = first_mon_info, i = 0; mon; mon = mon->next)
1436 if (mon->ob->level >= level)
1437 i++;
1438
1439 if (i == 0) {
1440 LOG(llevError, "get_random_mon() couldn't return monster for level %d\n", level);
1441 return NULL;
1442 }
1443
1444 monnr = RANDOM()%i;
1445 for (mon = first_mon_info; mon; mon = mon->next)
1446 if (mon->ob->level >= level && monnr-- == 0)
1447 return mon->ob;
1448
1449 LOG(llevError, "get_random_mon(): didn't find a monster when we should have\n");
1450 return NULL;
1451 }
1452
1453 /**
1454 * Returns a description of the monster. This really needs to be
1455 * redone, as describe_item really gives a pretty internal description.
1456 *
1457 * @param mon
1458 * monster to describe.
1459 * @return
1460 * new StringBuffer containing the description.
1461 */
1462 static StringBuffer *mon_desc(const object *mon) {
1463 StringBuffer *desc = stringbuffer_new();
1464 stringbuffer_append_printf(desc, "\n---\n *** %s ***\n", mon->name);
1465 describe_item(mon, NULL, 0, desc);
1466 return desc;
1467 }
1468
1469 /**
1470 * This function returns the next monster after 'tmp' in the monster list.
1471 *
1472 * @param tmp
1473 * monster.
1474 * @return
1475 * next monster, or if no match is found, it returns NULL.
1476 *
1477 * @note
1478 * list is considered circular, asking for the next of the last element will return the first one.
1479 */
1480 static object *get_next_mon(const object *tmp) {
1481 objectlink *mon;
1482
1483 for (mon = first_mon_info; mon; mon = mon->next)
1484 if (mon->ob == tmp)
1485 break;
1486
1487 /* didn't find a match */
1488 if (!mon)
1489 return NULL;
1490 if (mon->next)
1491 return mon->next->ob;
1492 else
1493 return first_mon_info->ob;
1494 }
1495
1496 /**
1497 * Generate a message detailing the properties of randomly monster(s), and add relevant knowledge markers.
1498 *
1499 * @param level
1500 * book level.
1501 * @param booksize
1502 * size (in characters) of the book we want.
1503 * @param book
1504 * book in which we will put the information.
1505 * @return
1506 * StringBuffer containing the information.
1507 */
1508 static StringBuffer *mon_info_msg(int level, size_t booksize, object *book) {
1509 object *tmp;
1510 StringBuffer *marker = stringbuffer_new(), *desc = stringbuffer_new(), *mon = NULL;
1511 int added = 0;
1512 sstring final;
1513 const char *sep = ":";
1514
1515 /*preamble */
1516 stringbuffer_append_string(desc, "This beastiary contains:");
1517 stringbuffer_append_string(marker, "monster");
1518
1519 /* lets print info on as many monsters as will fit in our
1520 * document.
1521 * 8-96 Had to change this a bit, otherwise there would
1522 * have been an impossibly large number of combinations
1523 * of text! (and flood out the available number of titles
1524 * in the archive in a snap!) -b.t.
1525 */
1526 for (tmp = get_random_mon(level*3); tmp; tmp = get_next_mon(tmp)) {
1527 /* monster description */
1528 mon = mon_desc(tmp);
1529
1530 if (stringbuffer_length(desc) + stringbuffer_length(mon) >= booksize)
1531 break;
1532 added++;
1533 stringbuffer_append_printf(marker, "%s%s", sep, tmp->arch->name);
1534 sep = "/";
1535 stringbuffer_append_stringbuffer(desc, mon);
1536 stringbuffer_delete(mon);
1537 mon = NULL;
1538 }
1539
1540 if (mon != NULL) {
1541 stringbuffer_delete(mon);
1542 }
1543
1544 final = stringbuffer_finish_shared(marker);
1545 if (added)
1546 object_set_value(book, "knowledge_marker", final, 1);
1547 free_string(final);
1548
1549 return desc;
1550 }
1551
1552 /*****************************************************************************
1553 * Artifact msg generation code.
1554 ****************************************************************************/
1555
1556 /**
1557 * Describe an artifact.
1558 * @param art artifact to describe.
1559 * @param al list art is part of.
1560 * @param message if non zero, and the artifact has a suitable message, add it to the description.
1561 * @param art_name index in ::art_name_array the artifact is in.
1562 * @param separator if non zero, a separator is inserted at the start of the description.
1563 * @return newly allocated StringBuffer* containing the description.
1564 */
1565 static StringBuffer *artifact_describe(const artifact *art, const artifactlist *al, int message, int art_name, int separator) {
1566 object *tmp;
1567 int chance;
1568 StringBuffer *desc = stringbuffer_new(), *sbuf;
1569
1570 if (separator)
1571 stringbuffer_append_string(desc, "---\n");
1572
1573 /* Name */
1574 if (art->allowed != NULL) {
1575 archetype *arch;
1576 linked_char *temp = art->allowed;
1577 int inv = 0, w;
1578
1579 assert(art->allowed_size > 0);
1580 if (art->allowed_size > 1)
1581 w = 1 + RANDOM() % art->allowed_size;
1582 else
1583 w = 1;
1584
1585 while (w > 1) {
1586 assert(temp);
1587 temp = temp->next;
1588 w--;
1589 }
1590
1591 if (temp->name[0] == '!')
1592 inv = 1;
1593
1594 /** @todo check archetype when loading archetypes, not here */
1595 arch = try_find_archetype(temp->name + inv);
1596 if (!arch)
1597 arch = find_archetype_by_object_name(temp->name + inv);
1598
1599 if (!arch)
1600 LOG(llevError, "artifact_msg: missing archetype %s for artifact %s (type %d)\n", temp->name + inv, art->item->name, art->item->type);
1601 else {
1602 if (inv)
1603 stringbuffer_append_printf(desc, " A %s (excepted %s) of %s", art_name_array[art_name].name, arch->clone.name_pl, art->item->name);
1604 else
1605 stringbuffer_append_printf(desc, " A %s of %s", arch->clone.name, art->item->name);
1606 }
1607 } else { /* default name is used */
1608 /* use the base 'generic' name for our artifact */
1609 stringbuffer_append_printf(desc, " The %s of %s", art_name_array[art_name].name, art->item->name);
1610 }
1611
1612 /* chance of finding */
1613 stringbuffer_append_string(desc, " is ");
1614 chance = 100*((float)art->chance/al->total_chance);
1615 if (chance >= 20)
1616 stringbuffer_append_string(desc, "an uncommon");
1617 else if (chance >= 10)
1618 stringbuffer_append_string(desc, "an unusual");
1619 else if (chance >= 5)
1620 stringbuffer_append_string(desc, "a rare");
1621 else
1622 stringbuffer_append_string(desc, "a very rare");
1623
1624 /* value of artifact */
1625 stringbuffer_append_printf(desc, " item with a value that is %d times normal.\n", art->item->value);
1626
1627 /* include the message about the artifact, if exists, and book
1628 * level is kinda high */
1629 if (message && !(strlen(art->item->msg) > BOOK_BUF))
1630 stringbuffer_append_string(desc, art->item->msg);
1631
1632 /* properties of the artifact */
1633 tmp = object_new();
1634 add_abilities(tmp, art->item);
1635 tmp->type = al->type;
1636 SET_FLAG(tmp, FLAG_IDENTIFIED);
1637 sbuf = describe_item(tmp, NULL, 0, NULL);
1638 if (stringbuffer_length(sbuf) > 1) {
1639 stringbuffer_append_string(desc, " Properties of this artifact include:\n ");
1640 stringbuffer_append_stringbuffer(desc, sbuf);
1641 stringbuffer_append_string(desc, "\n");
1642 }
1643 free(stringbuffer_finish(sbuf));
1644 object_free_drop_inventory(tmp);
1645
1646 return desc;
1647 }
1648
1649 /**
1650 * Generate a message detailing the properties
1651 * of 1-6 artifacts drawn sequentially from the artifact list.
1652 *
1653 * @param level
1654 * level of the book.
1655 * @param booksize
1656 * maximum length of the book.
1657 * @return
1658 * new StringBuffer containing the dsecription.
1659 */
1660 static StringBuffer *artifact_msg(unsigned int level, size_t booksize) {
1661 const artifactlist *al;
1662 const artifact *art;
1663 int i, type, index;
1664 int book_entries = level > 5 ? RANDOM()%3+RANDOM()%3+2 : RANDOM()%level+1;
1665 StringBuffer *desc, *message = stringbuffer_new();
1666
1667 /* values greater than 5 create msg buffers that are too big! */
1668 if (book_entries > 5)
1669 book_entries = 5;
1670
1671 /* lets determine what kind of artifact type randomly.
1672 * Right now legal artifacts only come from those listed
1673 * in art_name_array. Also, we check to be sure an artifactlist
1674 * for that type exists!
1675 */
1676 i = 0;
1677 do {
1678 index = RANDOM()%arraysize(art_name_array);
1679 type = art_name_array[index].type;
1680 al = find_artifactlist(type);
1681 i++;
1682 } while (al == NULL && i < 10);
1683
1684 if (i == 10) { /* Unable to find a message */
1685 stringbuffer_append_string(message, "None");
1686 return message;
1687 }
1688
1689 /* There is no reason to start on the artifact list at the beginning. Lets
1690 * take our starting position randomly... */
1691 art = al->items;
1692 for (i = RANDOM()%level+RANDOM()%2+1; i > 0; i--) {
1693 if (art == NULL)
1694 art = al->items; /* hmm, out of stuff, loop back around */
1695 art = art->next;
1696 }
1697
1698 /* Ok, lets print out the contents */
1699 stringbuffer_append_printf(message, "Herein %s detailed %s...\n", book_entries > 1 ? "are" : "is", book_entries > 1 ? "some artifacts" : "an artifact");
1700
1701 i = 0;
1702 /* artifact msg attributes loop. Lets keep adding entries to the 'book'
1703 * as long as we have space up to the allowed max # (book_entires)
1704 */
1705 while (book_entries > 0) {
1706 int with_message;
1707 if (art == NULL)
1708 art = al->items;
1709 with_message = (art->item->msg && RANDOM()%4+1 < level) ? 1 : 0;
1710
1711 desc = artifact_describe(art, al, with_message, index, i++);
1712
1713 if (stringbuffer_length(message) + stringbuffer_length(desc) >= booksize) {
1714 stringbuffer_delete(desc);
1715 break;
1716 }
1717
1718 stringbuffer_append_stringbuffer(message, desc);
1719 stringbuffer_delete(desc);
1720
1721 art = art->next;
1722 book_entries--;
1723 }
1724
1725 return message;
1726 }
1727
1728 /*****************************************************************************
1729 * Spellpath message generation
1730 *****************************************************************************/
1731
1732 /**
1733 * Generate a message detailing the member incantations/prayers (and some of their
1734 * properties) belonging to a random spellpath.
1735 *
1736 * @param level
1737 * level of the book.
1738 * @param booksize
1739 * maximumlength of the book.
1740 * @param buf
1741 * where to store the message. If not NULL, it is supposed to contain the message header.
1742 * @return
1743 * buf, newly allocated StringBuffer if buf is NULL.
1744 */
1745 static StringBuffer *spellpath_msg(int level, size_t booksize, StringBuffer *buf) {
1746 int path = RANDOM()%NRSPELLPATHS, prayers = RANDOM()%2;
1747 int did_first_sp = 0;
1748 uint32_t pnum = spellpathdef[path];
1749 archetype *at;
1750
1751 if (buf == NULL) {
1752 buf = stringbuffer_new();
1753 /* Preamble */
1754 stringbuffer_append_printf(buf, "Herein are detailed the names of %s", prayers ? "prayers" : "incantations");
1755 stringbuffer_append_printf(buf, " belonging to the path of %s:\n ", spellpathnames[path]);
1756 }
1757
1758 for (at = first_archetype; at != NULL; at = at->next) {
1759 /* Determine if this is an appropriate spell. Must
1760 * be of matching path, must be of appropriate type (prayer
1761 * or not), and must be within the valid level range.
1762 */
1763 if (at->clone.type == SPELL
1764 && at->clone.path_attuned&pnum
1765 && ((at->clone.stats.grace && prayers) || (at->clone.stats.sp && !prayers))
1766 && at->clone.level < level*8) {
1767 if (strlen(at->clone.name) + stringbuffer_length(buf) >= booksize)
1768 break;
1769
1770 if (did_first_sp)
1771 stringbuffer_append_string(buf, ",\n ");
1772 did_first_sp = 1;
1773 stringbuffer_append_string(buf,at->clone.name);
1774 }
1775 }
1776
1777 /* Geez, no spells were generated. */
1778 if (!did_first_sp) {
1779 if (RANDOM()%4) { /* usually, lets make a recursive call... */
1780 return spellpath_msg(level, booksize, buf);
1781 }
1782 /* give up, cause knowing no spells exist for path is info too. need the header too. */
1783 stringbuffer_append_string(buf, "- no known spells exist -\n");
1784 }
1785 return buf;
1786 }
1787
1788 /**
1789 * Generate a message detailing the properties of a randomly selected alchemical formula.
1790 *
1791 * @param book
1792 * book we write to.
1793 * @param level
1794 * level for formulaes and such.
1795 */
1796 static void make_formula_book(object *book, int level) {
1797 recipelist *fl;
1798 recipe *formula;
1799 int chance, count = 0;
1800 const char *op_name;
1801 archetype *at;
1802 StringBuffer *text, *title;
1803 char *final, km[MAX_BUF];
1804
1805 /* the higher the book level, the more complex (ie number of
1806 * ingredients) the formula can be.
1807 */
1808 fl = get_formulalist((RANDOM()%level)/3+1);
1809 if (!fl)
1810 fl = get_formulalist(1); /* safety */
1811
1812 if (fl->total_chance == 0) {
1813 object_set_msg(book, " <indecipherable text>\n");
1814 new_text_name(book, MSGTYPE_ALCHEMY);
1815 add_author(book, MSGTYPE_ALCHEMY);
1816 return;
1817 }
1818
1819 /* get a random formula, weighted by its bookchance */
1820 chance = RANDOM()%fl->total_chance;
1821 for (formula = fl->items; formula != NULL; formula = formula->next) {
1822 chance -= formula->chance;
1823 if (chance <= 0 && formula->chance != 0 && !formula->is_combination)
1824 break;
1825 }
1826
1827 if (!formula || formula->arch_names <= 0) {
1828 object_set_msg(book, " <indecipherable text>\n");
1829 new_text_name(book, MSGTYPE_ALCHEMY);
1830 add_author(book, MSGTYPE_ALCHEMY);
1831 return;
1832 }
1833
1834 /* looks like a formula was found. Base the amount
1835 * of information on the booklevel and the spellevel
1836 * of the formula. */
1837
1838 op_name = formula->arch_name[RANDOM()%formula->arch_names];
1839 at = find_archetype(op_name);
1840 if (at == (archetype *)NULL) {
1841 LOG(llevError, "formula_msg() can't find arch %s for formula.\n", op_name);
1842 object_set_msg(book, " <indecipherable text>\n");
1843 new_text_name(book, MSGTYPE_ALCHEMY);
1844 add_author(book, MSGTYPE_ALCHEMY);
1845 return;
1846 }
1847 op_name = at->clone.name;
1848
1849 text = stringbuffer_new();
1850 title = stringbuffer_new();
1851
1852 /* preamble */
1853 stringbuffer_append_printf(text, "Herein is described a project using %s:\n", formula->skill ? formula->skill : "an unknown skill");
1854
1855 /* item name */
1856 if (strcmp(formula->title, "NONE")) {
1857 stringbuffer_append_printf(text, "The %s of %s", op_name, formula->title);
1858 /* This results in things like pile of philo. sulfur.
1859 * while philo. sulfur may look better, without this,
1860 * you get things like 'the wise' because its missing the
1861 * water of section.
1862 */
1863 stringbuffer_append_printf(title, "%s: %s of %s", formula_book_name[RANDOM()%arraysize(formula_book_name)], op_name, formula->title);
1864 } else {
1865 stringbuffer_append_printf(text, "The %s", op_name);
1866 stringbuffer_append_printf(title, "%s: %s", formula_book_name[RANDOM()%arraysize(formula_book_name)], op_name);
1867 if (at->clone.title) {
1868 stringbuffer_append_printf(text, " %s", at->clone.title);
1869 stringbuffer_append_printf(title, " %s", at->clone.title);
1870 }
1871 }
1872 /* Lets name the book something meaningful ! */
1873 if (book->name)
1874 free_string(book->name);
1875 book->name = stringbuffer_finish_shared(title);
1876 if (book->title) {
1877 free_string(book->title);
1878 book->title = NULL;
1879 }
1880
1881 /* ingredients to make it */
1882 if (formula->ingred != NULL) {
1883 linked_char *next;
1884 archetype *at;
1885 char name[MAX_BUF];
1886
1887 at = find_archetype(formula->cauldron);
1888 if (at)
1889 query_name(&at->clone, name, MAX_BUF);
1890 else
1891 snprintf(name, sizeof(name), "an unknown place");
1892
1893 stringbuffer_append_printf(text, " may be made at %s using the following ingredients:\n", name);
1894
1895 for (next = formula->ingred; next != NULL; next = next->next) {
1896 count++;
1897 stringbuffer_append_printf(text, "%s\n", next->name);
1898 }
1899 } else {
1900 LOG(llevError, "formula_msg() no ingredient list for object %s of %s\n", op_name, formula->title);
1901 stringbuffer_append_string(text, "\n");
1902 }
1903
1904 final = stringbuffer_finish(text);
1905 object_set_msg(book, final);
1906 free(final);
1907
1908 /** knowledge marker */
1909 /** @todo this would be better in knowledge.c, except this file is in server, not common... */
1910 snprintf(km, sizeof(km), "alchemy:%d:%d:%s", count, formula->index, formula->title);
1911 object_set_value(book, "knowledge_marker", km, 1);
1912 }
1913
1914 /**
1915 * Generate a message drawn randomly from lib/messages.
1916 *
1917 * @param book
1918 * book to fill.
1919 * @param booksize
1920 * length of the book we want.
1921 * @return
1922 * message to put into book, newly allocated StringBuffer the caller should free.
1923 */
1924 static StringBuffer *msgfile_msg(object *book, size_t booksize) {
1925 int weight;
1926 GeneralMessage *msg = NULL;
1927 StringBuffer *ret = stringbuffer_new();
1928
1929 /* get a random message for the 'book' from linked list */
1930 if (msg_total_chance > 0) {
1931 assert(first_msg != NULL);
1932 msg = first_msg;
1933 weight = (RANDOM() % msg_total_chance);
1934 while (msg) {
1935 weight -= msg->chance;
1936 if (weight < 0)
1937 break;
1938 msg = msg->next;
1939 }
1940 /* if msg is NULL, then something is really wrong in the computation! */
1941 assert(msg != NULL);
1942 }
1943
1944 if (msg && strlen(msg->message) <= booksize) {
1945 stringbuffer_append_string(ret, msg->message);
1946 if (msg->identifier != NULL) {
1947 char km[HUGE_BUF];
1948 /** knowledge marker */
1949 /** @todo this would be better in knowledge.c, except this file is in server, not common... */
1950 snprintf(km, sizeof(km), "message:%s", msg->identifier);
1951 object_set_value(book, "knowledge_marker", km, 1);
1952 }
1953 if (msg->quest_code) {
1954 /* add a 'apply' hook to launch the quest */
1955 archetype *at = find_archetype("quest_advance_apply");
1956 if (at != NULL) {
1957 object *event = object_create_arch(at);
1958 FREE_AND_COPY(event->name, msg->quest_code);
1959 object_insert_in_ob(event, book);
1960 }
1961 }
1962 } else
1963 stringbuffer_append_string(ret, "\n <undecipherable text>");
1964
1965 return ret;
1966 }
1967
1968 /**
1969 * Generate a message detailing the properties
1970 * of a random god. Used by the book hack. b.t.
1971 *
1972 * @param level
1973 * number of elements to give.
1974 * @param booksize
1975 * desired length of the book.
1976 * @param book
1977 * book we're writing the information to, for knowledge management.
1978 * @return
1979 * StringBuffer with the information that the caller is responsible for cleaning,
1980 * NULL if information overflows the booksize.
1981 */
1982 static StringBuffer *god_info_msg(int level, size_t booksize, object *book) {
1983 int what = 0;
1984 const object *god = pntr_to_god_obj(get_rand_god());
1985 StringBuffer *desc = NULL;
1986
1987 if (!god)
1988 return NULL; /* oops, problems... */
1989
1990 if (booksize > BOOK_BUF) {
1991 LOG(llevError, "common/readable.c:god_info_msg() - passed in booksize (%lu) is larger than book buffer (%d)\n", (unsigned long)booksize, BOOK_BUF);
1992 booksize = BOOK_BUF;
1993 }
1994
1995 if (level >= 2 && RANDOM()%2) {
1996 what |= GOD_ENEMY;
1997 }
1998 if (level >= 3 && RANDOM()%2) {
1999 what |= GOD_HOLYWORD;
2000 }
2001 if (level >= 4 && RANDOM()%2) {
2002 what |= GOD_RESISTANCES;
2003 }
2004 if (level >= 5 && RANDOM()%2) {
2005 what |= GOD_SACRED;
2006 }
2007 if (level >= 6 && RANDOM()%2) {
2008 what |= GOD_BLESSED;
2009 }
2010 if (level >= 8 && RANDOM()%2) {
2011 what |= GOD_IMMUNITIES;
2012 }
2013 if (level >= 12 && RANDOM()%2) {
2014 what |= GOD_PATHS;
2015 }
2016
2017 desc = stringbuffer_new();
2018 what = describe_god(god, what, desc, booksize);
2019
2020 /* check to be sure new buffer size dont exceed either
2021 * the maximum buffer size, or the 'natural' size of the
2022 * book... */
2023 if (stringbuffer_length(desc) > 1 && stringbuffer_length(desc) <= booksize) {
2024 char buf[BOOK_BUF];
2025 snprintf(buf, sizeof(buf), "god:%s:%d", god->name, what);
2026 object_set_value(book, "knowledge_marker", buf, 1);
2027 return desc;
2028 }
2029
2030 stringbuffer_delete(desc);
2031 return NULL;
2032 }
2033
2034 /**
2035 * The main routine. This chooses a random
2036 * message to put in given readable object (type==BOOK) which will
2037 * be referred hereafter as a 'book'. We use the book level to de-
2038 * termine the value of the information we will insert. Higher
2039 * values mean the book will (generally) have better/more info.
2040 * See individual cases as to how this will be utilized.
2041 * "Book" name/content length are based on the weight of the
2042 * document. If the value of msg_type is negative, we will randomly
2043 * choose the kind of message to generate.
2044 * -b.t. [email protected]
2045 *
2046 * @param book
2047 * the object we are creating into. Must be a book, can have a level.
2048 * @param msg_type
2049 * if it is a positive value, we use that to determine the
2050 * message type - otherwise a random value is used.
2051 */
2052 void tailor_readable_ob(object *book, int msg_type) {
2053 int level = book->level ? RANDOM()%book->level+1 : 1;
2054 size_t book_buf_size;
2055 StringBuffer *message = NULL;
2056
2057 /* safety */
2058 if (book->type != BOOK)
2059 return;
2060
2061 if (level <= 0)
2062 return; /* if no level no point in doing any more... */
2063
2064 /* Max text length this book can have. */
2065 book_buf_size = BOOKSIZE(book);
2066 book_buf_size -= strlen("\n"); /* Keep enough for final \n. */
2067 assert(book_buf_size < BOOK_BUF);
2068
2069 /* &&& The message switch &&& */
2070 /* Below all of the possible types of messages in the "book"s.
2071 */
2072 /*
2073 * IF you add a new type of book msg, you will have to do several things.
2074 * 1) make sure there is an entry in the msg switch below!
2075 * 2) make sure there is an entry in max_titles[] array.
2076 * 3) make sure there are entries for your case in new_text_title()
2077 * and add_authour().
2078 * 4) you may want separate authour/book name arrays in read.h
2079 */
2080
2081 if (msg_type >= (int)arraysize(max_titles))
2082 msg_type = 0;
2083
2084 msg_type = msg_type > 0 ? msg_type : (int)(RANDOM()%6);
2085 switch (msg_type) {
2086 case MSGTYPE_MONSTER:
2087 message = mon_info_msg(level, book_buf_size, book);
2088 break;
2089
2090 case MSGTYPE_ARTIFACT:
2091 message = artifact_msg(level, book_buf_size);
2092 break;
2093
2094 case MSGTYPE_SPELLPATH: /* grouping incantations/prayers by path */
2095 message = spellpath_msg(level, book_buf_size, NULL);
2096 break;
2097
2098 case MSGTYPE_ALCHEMY: /* describe an alchemy formula */
2099 make_formula_book(book, level);
2100 /* make_formula_book already gives title */
2101 return;
2102 break;
2103
2104 case MSGTYPE_GODS: /* bits of information about a god */
2105 message = god_info_msg(level, book_buf_size, book);
2106 break;
2107
2108 case MSGTYPE_LIB: /* use info list in lib/ */
2109 default:
2110 message = msgfile_msg(book, book_buf_size);
2111 break;
2112 }
2113
2114 if (message != NULL) {
2115 char *final;
2116 stringbuffer_append_string(message, "\n");
2117 final = stringbuffer_finish(message);
2118 object_set_msg(book, final);
2119 free(final);
2120 /* lets give the "book" a new name, which may be a compound word */
2121 change_book(book, msg_type);
2122 }
2123 }
2124
2125 /*****************************************************************************
2126 *
2127 * Cleanup routine for readable stuff.
2128 *
2129 *****************************************************************************/
2130
2131 /**
2132 * Free all readable-related information.
2133 */
2134 void free_all_readable(void) {
2135 titlelist *tlist, *tnext;
2136 title *title1, *titlenext;
2137 GeneralMessage *lmsg, *nextmsg;
2138 objectlink *monlink, *nextmon;
2139
2140 LOG(llevDebug, "freeing all book information\n");
2141
2142 for (tlist = booklist; tlist != NULL; tlist = tnext) {
2143 tnext = tlist->next;
2144 for (title1 = tlist->first_book; title1; title1 = titlenext) {
2145 titlenext = title1->next;
2146 if (title1->name)
2147 free_string(title1->name);
2148 if (title1->authour)
2149 free_string(title1->authour);
2150 if (title1->archname)
2151 free_string(title1->archname);
2152 free(title1);
2153 }
2154 free(tlist);
2155 }
2156 for (lmsg = first_msg; lmsg; lmsg = nextmsg) {
2157 nextmsg = lmsg->next;
2158 if (lmsg->identifier)
2159 free_string(lmsg->identifier);
2160 if (lmsg->title)
2161 free_string(lmsg->title);
2162 if (lmsg->message)
2163 free_string(lmsg->message);
2164 if (lmsg->quest_code)
2165 free_string(lmsg->quest_code);
2166 free(lmsg);
2167 }
2168 for (monlink = first_mon_info; monlink; monlink = nextmon) {
2169 nextmon = monlink->next;
2170 free(monlink);
2171 }
2172 }
2173
2174 /*****************************************************************************
2175 *
2176 * Writeback routine for updating the bookarchive.
2177 *
2178 ****************************************************************************/
2179
2180 /**
2181 * Write out the updated book archive to bookarch file.
2182 */
2183 void write_book_archive(void) {
2184 FILE *fp;
2185 OutputFile of;
2186 int index;
2187 char fname[MAX_BUF];
2188 title *book;
2189 titlelist *bl;
2190
2191 /* If nothing changed, don't write anything */
2192 if (!need_to_write_bookarchive)
2193 return;
2194
2195 snprintf(fname, sizeof(fname), "%s/bookarch", settings.localdir);
2196 LOG(llevDebug, "Updating book archive: %s...\n", fname);
2197
2198 fp = of_open(&of, fname);
2199 if (fp == NULL)
2200 return;
2201
2202 for (bl = get_titlelist(0), index = 0; bl; bl = bl->next, index++) {
2203 for (book = bl->first_book; book; book = book->next)
2204 if (book && book->authour) {
2205 fprintf(fp, "title %s\n", book->name);
2206 fprintf(fp, "authour %s\n", book->authour);
2207 fprintf(fp, "arch %s\n", book->archname);
2208 fprintf(fp, "level %d\n", book->level);
2209 fprintf(fp, "type %d\n", index);
2210 /* C89 doesn't have %zu... */
2211 fprintf(fp, "size %lu\n", (unsigned long)book->size);
2212 fprintf(fp, "index %d\n", book->msg_index);
2213 fprintf(fp, "end\n");
2214 }
2215 }
2216 if (!of_close(&of))
2217 return;
2218
2219 if (chmod(fname, SAVE_MODE) != 0) {
2220 LOG(llevError, "Could not set permissions on '%s'\n", fname);
2221 }
2222
2223 need_to_write_bookarchive = 0;
2224 }
2225
2226 /**
2227 * Get the readable type for an object (hopefully book).
2228 * @param readable
2229 * object for which we want the readable type.
2230 * @return
2231 * type of the book. Will never be NULL.
2232 */
2233 const readable_message_type *get_readable_message_type(object *readable) {
2234 uint8_t subtype = readable->subtype;
2235
2236 if (subtype > last_readable_subtype)
2237 return &readable_message_types[0];
2238 return &readable_message_types[subtype];
2239 }
2240
2241 /**
2242 * Find the message from its identifier.
2243 * @param identifier message's identifier.
2244 * @return corresponding message, NULL if no such message.
2245 */
2246 const GeneralMessage *get_message_from_identifier(const char *identifier) {
2247 GeneralMessage *msg = first_msg;
2248 while (msg && ((msg->identifier == 0) || (strcmp(msg->identifier, identifier) != 0)))
2249 msg = msg->next;
2250
2251 return msg;
2252 }
2253
2254 /**
2255 * Get a message's title.
2256 * @param message message, must not be NULL.
2257 * @return title.
2258 */
2259 sstring get_message_title(const GeneralMessage *message) {
2260 return message->title;
2261 }
2262
2263 /**
2264 * Get a message's body.
2265 * @param message message, must not be NULL.
2266 * @return body.
2267 */
2268 sstring get_message_body(const GeneralMessage *message) {
2269 return message->message;
2270 }
2271
2272 /**
2273 * Get a message's face.
2274 * @param message message, must not be NULL.
2275 * @return face, -1 if not defined.
2276 */
2277 const Face *get_message_face(const GeneralMessage *message) {
2278 return message->face;
2279 }