cleanup of drawing init text
[rocksndiamonds.git] / src / libgame / text.c
1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // text.c
10 // ============================================================================
11
12 #include <stdio.h>
13 #include <stdarg.h>
14
15 #include "text.h"
16 #include "misc.h"
17
18
19 /* ========================================================================= */
20 /* font functions                                                            */
21 /* ========================================================================= */
22
23 void InitFontInfo(struct FontBitmapInfo *font_bitmap_info, int num_fonts,
24                   int (*select_font_function)(int),
25                   int (*get_font_from_token_function)(char *))
26 {
27   gfx.num_fonts = num_fonts;
28   gfx.font_bitmap_info = font_bitmap_info;
29   gfx.select_font_function = select_font_function;
30   gfx.get_font_from_token_function = get_font_from_token_function;
31 }
32
33 void FreeFontInfo(struct FontBitmapInfo *font_bitmap_info)
34 {
35   if (font_bitmap_info == NULL)
36     return;
37
38   free(font_bitmap_info);
39 }
40
41 struct FontBitmapInfo *getFontBitmapInfo(int font_nr)
42 {
43   int font_bitmap_id = gfx.select_font_function(font_nr);
44
45   return &gfx.font_bitmap_info[font_bitmap_id];
46 }
47
48 int getFontWidth(int font_nr)
49 {
50   int font_bitmap_id = gfx.select_font_function(font_nr);
51
52   return gfx.font_bitmap_info[font_bitmap_id].width;
53 }
54
55 int getFontHeight(int font_nr)
56 {
57   int font_bitmap_id = gfx.select_font_function(font_nr);
58
59   return gfx.font_bitmap_info[font_bitmap_id].height;
60 }
61
62 int getTextWidth(char *text, int font_nr)
63 {
64   return (text != NULL ? strlen(text) * getFontWidth(font_nr) : 0);
65 }
66
67 static int getFontCharPosition(int font_nr, char c)
68 {
69   int font_bitmap_id = gfx.select_font_function(font_nr);
70   struct FontBitmapInfo *font = &gfx.font_bitmap_info[font_bitmap_id];
71   boolean default_font = (font->num_chars == DEFAULT_NUM_CHARS_PER_FONT);
72   int font_pos = (unsigned char)c - 32;
73
74   /* map some special characters to their ascii values in default font */
75   if (default_font)
76     font_pos = MAP_FONT_ASCII(c) - 32;
77
78   /* this allows dynamic special characters together with special font */
79   if (font_pos < 0 || font_pos >= font->num_chars)
80     font_pos = 0;
81
82   return font_pos;
83 }
84
85 void getFontCharSource(int font_nr, char c, Bitmap **bitmap, int *x, int *y)
86 {
87   int font_bitmap_id = gfx.select_font_function(font_nr);
88   struct FontBitmapInfo *font = &gfx.font_bitmap_info[font_bitmap_id];
89   int font_pos = getFontCharPosition(font_nr, c);
90
91   *bitmap = font->bitmap;
92   *x = font->src_x + (font_pos % font->num_chars_per_line) * font->width;
93   *y = font->src_y + (font_pos / font->num_chars_per_line) * font->height;
94 }
95
96
97 /* ========================================================================= */
98 /* text string helper functions                                              */
99 /* ========================================================================= */
100
101 int maxWordLengthInString(char *text)
102 {
103   char *text_ptr;
104   int word_len = 0, max_word_len = 0;
105
106   for (text_ptr = text; *text_ptr; text_ptr++)
107   {
108     word_len = (*text_ptr != ' ' ? word_len + 1 : 0);
109
110     max_word_len = MAX(word_len, max_word_len);
111   }
112
113   return max_word_len;
114 }
115
116
117 /* ========================================================================= */
118 /* simple text drawing functions                                             */
119 /* ========================================================================= */
120
121 void DrawInitText(char *text, int ypos, int font_nr)
122 {
123   LimitScreenUpdates(TRUE);
124
125   UPDATE_BUSY_STATE();
126
127   if (window != NULL &&
128       gfx.draw_init_text &&
129       gfx.num_fonts > 0 &&
130       gfx.font_bitmap_info[font_nr].bitmap != NULL)
131   {
132     int x = (video.width - getTextWidth(text, font_nr)) / 2;
133     int y = ypos;
134     int width = video.width;
135     int height = getFontHeight(font_nr);
136
137     ClearRectangle(drawto, 0, y, width, height);
138     DrawTextExt(drawto, x, y, text, font_nr, BLIT_OPAQUE);
139
140     BlitBitmap(drawto, window, 0, 0, video.width, video.height, 0, 0);
141   }
142 }
143
144 void DrawTextF(int x, int y, int font_nr, char *format, ...)
145 {
146   char buffer[MAX_OUTPUT_LINESIZE + 1];
147   va_list ap;
148
149   va_start(ap, format);
150   vsprintf(buffer, format, ap);
151   va_end(ap);
152
153   if (strlen(buffer) > MAX_OUTPUT_LINESIZE)
154     Error(ERR_EXIT, "string too long in DrawTextF() -- aborting");
155
156   DrawText(gfx.sx + x, gfx.sy + y, buffer, font_nr);
157 }
158
159 void DrawTextFCentered(int y, int font_nr, char *format, ...)
160 {
161   char buffer[MAX_OUTPUT_LINESIZE + 1];
162   va_list ap;
163
164   va_start(ap, format);
165   vsprintf(buffer, format, ap);
166   va_end(ap);
167
168   if (strlen(buffer) > MAX_OUTPUT_LINESIZE)
169     Error(ERR_EXIT, "string too long in DrawTextFCentered() -- aborting");
170
171   DrawText(gfx.sx + (gfx.sxsize - getTextWidth(buffer, font_nr)) / 2,
172            gfx.sy + y, buffer, font_nr);
173 }
174
175 void DrawTextS(int x, int y, int font_nr, char *text)
176 {
177   DrawText(gfx.sx + x, gfx.sy + y, text, font_nr);
178 }
179
180 void DrawTextSCentered(int y, int font_nr, char *text)
181 {
182   DrawText(gfx.sx + (gfx.sxsize - getTextWidth(text, font_nr)) / 2,
183            gfx.sy + y, text, font_nr);
184 }
185
186 void DrawTextCentered(int y, int font_nr, char *text)
187 {
188   DrawText((gfx.sxsize - getTextWidth(text, font_nr)) / 2, y, text, font_nr);
189 }
190
191 void DrawTextSAligned(int x, int y, char *text, int font_nr, int align)
192 {
193   DrawText(gfx.sx + ALIGNED_XPOS(x, getTextWidth(text, font_nr), align),
194            gfx.sx + y, text, font_nr);
195 }
196
197 void DrawTextAligned(int x, int y, char *text, int font_nr, int align)
198 {
199   DrawText(ALIGNED_XPOS(x, getTextWidth(text, font_nr), align),
200            y, text, font_nr);
201 }
202
203 void DrawText(int x, int y, char *text, int font_nr)
204 {
205   int mask_mode = BLIT_OPAQUE;
206
207   if (DrawingOnBackground(x, y))
208     mask_mode = BLIT_ON_BACKGROUND;
209
210   DrawTextExt(drawto, x, y, text, font_nr, mask_mode);
211
212   if (IN_GFX_FIELD_FULL(x, y))
213     redraw_mask |= REDRAW_FIELD;
214   else if (IN_GFX_DOOR_1(x, y))
215     redraw_mask |= REDRAW_DOOR_1;
216   else if (IN_GFX_DOOR_2(x, y))
217     redraw_mask |= REDRAW_DOOR_2;
218   else if (IN_GFX_DOOR_3(x, y))
219     redraw_mask |= REDRAW_DOOR_3;
220   else
221     redraw_mask |= REDRAW_ALL;
222 }
223
224 void DrawTextExt(DrawBuffer *dst_bitmap, int dst_x, int dst_y, char *text,
225                  int font_nr, int mask_mode)
226 {
227   struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
228   int font_width = getFontWidth(font_nr);
229   int font_height = getFontHeight(font_nr);
230   Bitmap *src_bitmap;
231   int src_x, src_y;
232   char *text_ptr = text;
233
234   if (font->bitmap == NULL)
235     return;
236
237   /* skip text to be printed outside the window (left/right will be clipped) */
238   if (dst_y < 0 || dst_y + font_height > video.height)
239     return;
240
241   /* add offset for drawing font characters */
242   dst_x += font->draw_xoffset;
243   dst_y += font->draw_yoffset;
244
245   while (*text_ptr)
246   {
247     char c = *text_ptr++;
248
249     if (c == '\n')
250       c = ' ';          /* print space instead of newline */
251
252     getFontCharSource(font_nr, c, &src_bitmap, &src_x, &src_y);
253
254     /* clip text at the left side of the window */
255     if (dst_x < 0)
256     {
257       dst_x += font_width;
258
259       continue;
260     }
261
262     /* clip text at the right side of the window */
263     if (dst_x + font_width > video.width)
264       break;
265
266     if (mask_mode == BLIT_INVERSE)      /* special mode for text gadgets */
267     {
268       /* first step: draw solid colored rectangle (use "cursor" character) */
269       if (strlen(text) == 1)    /* only one char inverted => draw cursor */
270       {
271         Bitmap *cursor_bitmap;
272         int cursor_x, cursor_y;
273
274         getFontCharSource(font_nr, FONT_ASCII_CURSOR, &cursor_bitmap,
275                           &cursor_x, &cursor_y);
276
277         BlitBitmap(cursor_bitmap, dst_bitmap, cursor_x, cursor_y,
278                    font_width, font_height, dst_x, dst_y);
279       }
280
281       /* second step: draw masked inverted character */
282       SDLCopyInverseMasked(src_bitmap, dst_bitmap, src_x, src_y,
283                            font_width, font_height, dst_x, dst_y);
284     }
285     else if (mask_mode == BLIT_MASKED || mask_mode == BLIT_ON_BACKGROUND)
286     {
287       if (mask_mode == BLIT_ON_BACKGROUND)
288       {
289         /* clear font character background */
290         ClearRectangleOnBackground(dst_bitmap, dst_x, dst_y,
291                                    font_width, font_height);
292       }
293
294       BlitBitmapMasked(src_bitmap, dst_bitmap, src_x, src_y,
295                        font_width, font_height, dst_x, dst_y);
296     }
297     else        /* normal, non-masked font blitting */
298     {
299       BlitBitmap(src_bitmap, dst_bitmap, src_x, src_y,
300                  font_width, font_height, dst_x, dst_y);
301     }
302
303     dst_x += font_width;
304   }
305 }
306
307
308 /* ========================================================================= */
309 /* text buffer drawing functions                                             */
310 /* ========================================================================= */
311
312 #define MAX_LINES_FROM_FILE             1024
313
314 char *GetTextBufferFromFile(char *filename, int max_lines)
315 {
316   File *file;
317   char *buffer;
318   int num_lines = 0;
319
320   if (filename == NULL)
321     return NULL;
322
323   if (!(file = openFile(filename, MODE_READ)))
324     return NULL;
325
326   buffer = checked_calloc(1);   /* start with valid, but empty text buffer */
327
328   while (!checkEndOfFile(file) && num_lines < max_lines)
329   {
330     char line[MAX_LINE_LEN];
331
332     /* read next line of input file */
333     if (!getStringFromFile(file, line, MAX_LINE_LEN))
334       break;
335
336     buffer = checked_realloc(buffer, strlen(buffer) + strlen(line) + 1);
337
338     strcat(buffer, line);
339
340     num_lines++;
341   }
342
343   closeFile(file);
344
345   return buffer;
346 }
347
348 static boolean RenderLineToBuffer(char **src_buffer_ptr, char *dst_buffer,
349                                   int *dst_buffer_len, int line_length,
350                                   boolean last_line_was_empty)
351 {
352   char *text_ptr = *src_buffer_ptr;
353   char *buffer = dst_buffer;
354   int buffer_len = *dst_buffer_len;
355   boolean buffer_filled = FALSE;
356
357   while (*text_ptr)
358   {
359     char *word_ptr;
360     int word_len;
361
362     /* skip leading whitespaces */
363     while (*text_ptr == ' ' || *text_ptr == '\t')
364       text_ptr++;
365
366     word_ptr = text_ptr;
367     word_len = 0;
368
369     /* look for end of next word */
370     while (*word_ptr != ' ' && *word_ptr != '\t' && *word_ptr != '\0')
371     {
372       word_ptr++;
373       word_len++;
374     }
375
376     if (word_len == 0)
377     {
378       continue;
379     }
380     else if (*text_ptr == '\n')         /* special case: force empty line */
381     {
382       if (buffer_len == 0)
383         text_ptr++;
384
385       /* prevent printing of multiple empty lines */
386       if (buffer_len > 0 || !last_line_was_empty)
387         buffer_filled = TRUE;
388     }
389     else if (word_len < line_length - buffer_len)
390     {
391       /* word fits into text buffer -- add word */
392
393       if (buffer_len > 0)
394         buffer[buffer_len++] = ' ';
395
396       strncpy(&buffer[buffer_len], text_ptr, word_len);
397       buffer_len += word_len;
398       buffer[buffer_len] = '\0';
399       text_ptr += word_len;
400     }
401     else if (buffer_len > 0)
402     {
403       /* not enough space left for word in text buffer -- print buffer */
404
405       buffer_filled = TRUE;
406     }
407     else
408     {
409       /* word does not fit at all into empty text buffer -- cut word */
410
411       strncpy(buffer, text_ptr, line_length);
412       buffer[line_length] = '\0';
413       text_ptr += line_length;
414       buffer_filled = TRUE;
415     }
416
417     if (buffer_filled)
418       break;
419   }
420
421   *src_buffer_ptr = text_ptr;
422   *dst_buffer_len = buffer_len;
423
424   return buffer_filled;
425 }
426
427 static boolean getCheckedTokenValueFromString(char *string, char **token,
428                                               char **value)
429 {
430   char *ptr;
431
432   if (!getTokenValueFromString(string, token, value))
433     return FALSE;
434
435   if (**token != '.')                   /* token should begin with dot */
436     return FALSE;
437
438   for (ptr = *token; *ptr; ptr++)       /* token should contain no whitespace */
439     if (*ptr == ' ' || *ptr == '\t')
440       return FALSE;
441
442   for (ptr = *value; *ptr; ptr++)       /* value should contain no whitespace */
443     if (*ptr == ' ' || *ptr == '\t')
444       return FALSE;
445
446   return TRUE;
447 }
448
449 static void DrawTextBuffer_Flush(int x, int y, char *buffer, int font_nr,
450                                  int line_length, int cut_length,
451                                  int line_spacing, int mask_mode,
452                                  boolean centered, int current_line)
453 {
454   int buffer_len = strlen(buffer);
455   int font_width = getFontWidth(font_nr);
456   int font_height = getFontHeight(font_nr);
457   int offset_chars = (centered ? (line_length - buffer_len) / 2 : 0);
458   int offset_xsize =
459     (centered ? font_width * (line_length - buffer_len) / 2 : 0);
460   int final_cut_length = MAX(0, cut_length - offset_chars);
461   int xx = x + offset_xsize;
462   int yy = y + current_line * (font_height + line_spacing);
463
464   buffer[final_cut_length] = '\0';
465
466   if (mask_mode != -1)
467     DrawTextExt(drawto, xx, yy, buffer, font_nr, mask_mode);
468   else
469     DrawText(xx, yy, buffer, font_nr);
470 }
471
472 int DrawTextBuffer(int x, int y, char *text_buffer, int font_nr,
473                    int line_length, int cut_length, int max_lines,
474                    int line_spacing, int mask_mode, boolean autowrap,
475                    boolean centered, boolean parse_comments)
476 {
477   char buffer[line_length + 1];
478   int buffer_len;
479   int current_line = 0;
480
481   if (text_buffer == NULL || *text_buffer == '\0')
482     return 0;
483
484   if (current_line >= max_lines)
485     return 0;
486
487   if (cut_length == -1)
488     cut_length = line_length;
489
490   buffer[0] = '\0';
491   buffer_len = 0;
492
493   while (*text_buffer && current_line < max_lines)
494   {
495     char line[MAX_LINE_LEN + 1];
496     char *line_ptr;
497     boolean last_line_was_empty = TRUE;
498     int num_line_chars = MAX_LINE_LEN;
499     int i;
500
501     /* copy next line from text buffer to line buffer (nearly fgets() style) */
502     for (i = 0; i < num_line_chars && *text_buffer; i++)
503       if ((line[i] = *text_buffer++) == '\n')
504         break;
505     line[i] = '\0';
506
507     /* prevent 'num_line_chars' sized lines to cause additional empty line */
508     if (i == num_line_chars && *text_buffer == '\n')
509       text_buffer++;
510
511     /* skip comments (lines directly beginning with '#') */
512     if (line[0] == '#' && parse_comments)
513     {
514       char *token, *value;
515
516       /* try to read generic token/value pair definition after comment sign */
517       if (getCheckedTokenValueFromString(line + 1, &token, &value))
518       {
519         /* if found, flush the current buffer, if non-empty */
520         if (buffer_len > 0 && current_line < max_lines)
521         {
522           DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
523                                line_spacing, mask_mode, centered, current_line);
524
525           current_line++;
526
527           buffer[0] = '\0';
528           buffer_len = 0;
529         }
530
531         if (strEqual(token, ".font"))
532           font_nr = gfx.get_font_from_token_function(value);
533         else if (strEqual(token, ".autowrap"))
534           autowrap = get_boolean_from_string(value);
535         else if (strEqual(token, ".centered"))
536           centered = get_boolean_from_string(value);
537         else if (strEqual(token, ".parse_comments"))
538           parse_comments = get_boolean_from_string(value);
539       }
540
541       continue;
542     }
543
544     /* cut trailing newline and carriage return from input line */
545     for (line_ptr = line; *line_ptr; line_ptr++)
546     {
547       if (*line_ptr == '\n' || *line_ptr == '\r')
548       {
549         *line_ptr = '\0';
550         break;
551       }
552     }
553
554     if (strlen(line) == 0)              /* special case: force empty line */
555       strcpy(line, "\n");
556
557     line_ptr = line;
558
559     while (*line_ptr && current_line < max_lines)
560     {
561       boolean buffer_filled;
562
563       if (autowrap)
564       {
565         buffer_filled = RenderLineToBuffer(&line_ptr, buffer, &buffer_len,
566                                            line_length, last_line_was_empty);
567       }
568       else
569       {
570         if (strlen(line_ptr) <= line_length)
571         {
572           buffer_len = strlen(line_ptr);
573           strcpy(buffer, line_ptr);
574         }
575         else
576         {
577           buffer_len = line_length;
578           strncpy(buffer, line_ptr, line_length);
579         }
580
581         buffer[buffer_len] = '\0';
582         line_ptr += buffer_len;
583
584         buffer_filled = TRUE;
585       }
586
587       if (buffer_filled)
588       {
589         DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
590                              line_spacing, mask_mode, centered, current_line);
591         current_line++;
592
593         last_line_was_empty = (buffer_len == 0);
594
595         buffer[0] = '\0';
596         buffer_len = 0;
597       }
598     }
599   }
600
601   if (buffer_len > 0 && current_line < max_lines)
602   {
603     DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
604                          line_spacing, mask_mode, centered, current_line);
605     current_line++;
606   }
607
608   return current_line;
609 }
610
611 int DrawTextBufferVA(int x, int y, char *format, va_list ap, int font_nr,
612                      int line_length, int cut_length, int max_lines,
613                      int line_spacing, int mask_mode, boolean autowrap,
614                      boolean centered, boolean parse_comments)
615 {
616   char text_buffer[MAX_OUTPUT_LINESIZE];
617   int text_length = vsnprintf(text_buffer, MAX_OUTPUT_LINESIZE, format, ap);
618
619   if (text_length >= MAX_OUTPUT_LINESIZE)
620     Error(ERR_WARN, "string too long in DrawTextBufferVA() -- truncated");
621
622   int num_lines_printed = DrawTextBuffer(x, y, text_buffer, font_nr,
623                                          line_length, cut_length, max_lines,
624                                          line_spacing, mask_mode, autowrap,
625                                          centered, parse_comments);
626   return num_lines_printed;
627 }
628
629 int DrawTextFile(int x, int y, char *filename, int font_nr,
630                  int line_length, int cut_length, int max_lines,
631                  int line_spacing, int mask_mode, boolean autowrap,
632                  boolean centered, boolean parse_comments)
633 {
634   char *text_buffer = GetTextBufferFromFile(filename, MAX_LINES_FROM_FILE);
635   int num_lines_printed = DrawTextBuffer(x, y, text_buffer, font_nr,
636                                          line_length, cut_length, max_lines,
637                                          line_spacing, mask_mode, autowrap,
638                                          centered, parse_comments);
639   checked_free(text_buffer);
640
641   return num_lines_printed;
642 }