libdrawtext

view src/font.c @ 86:69e1ccbda826

fixed the glyphmap buffer size bug
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 17 Apr 2014 10:43:03 +0300
parents 5beaab3df0cb
children f067608d8a7c
line source
1 /*
2 libdrawtext - a simple library for fast text rendering in OpenGL
3 Copyright (C) 2011-2014 John Tsiombikas <nuclear@member.fsf.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18 #ifndef NO_FREETYPE
19 #define USE_FREETYPE
20 #endif
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <math.h>
26 #include <limits.h>
27 #include <ctype.h>
28 #include <float.h>
29 #include <errno.h>
30 #ifdef USE_FREETYPE
31 #include <ft2build.h>
32 #include FT_FREETYPE_H
33 #endif
34 #include "drawtext.h"
35 #include "drawtext_impl.h"
37 #define FTSZ_TO_PIXELS(x) ((x) / 64)
38 #define MAX_IMG_WIDTH 4096
41 #ifdef USE_FREETYPE
42 static int init_freetype(void);
43 static void cleanup(void);
45 static void calc_best_size(int total_width, int max_gwidth, int max_gheight,
46 int padding, int pow2, int *imgw, int *imgh);
47 static int next_pow2(int x);
49 static FT_Library ft;
52 static int init_done;
54 static int init_freetype(void)
55 {
56 if(!init_done) {
57 if(FT_Init_FreeType(&ft) != 0) {
58 return -1;
59 }
60 atexit(cleanup);
61 init_done = 1;
62 }
63 return 0;
64 }
66 static void cleanup(void)
67 {
68 if(init_done) {
69 FT_Done_FreeType(ft);
70 }
71 }
72 #endif /* USE_FREETYPE */
74 struct dtx_font *dtx_open_font(const char *fname, int sz)
75 {
76 struct dtx_font *fnt = 0;
78 #ifdef USE_FREETYPE
79 init_freetype();
81 if(!(fnt = calloc(1, sizeof *fnt))) {
82 fperror("failed to allocate font structure");
83 return 0;
84 }
86 if(FT_New_Face(ft, fname, 0, (FT_Face*)&fnt->face) != 0) {
87 fprintf(stderr, "failed to open font file: %s\n", fname);
88 return 0;
89 }
91 /* pre-create the extended ASCII range glyphmap */
92 if(sz) {
93 dtx_prepare_range(fnt, sz, 0, 256);
95 if(!dtx_font) {
96 dtx_use_font(fnt, sz);
97 }
98 }
99 #else
100 fprintf(stderr, "ignoring call to dtx_open_font: not compiled with freetype support!\n");
101 #endif
103 return fnt;
104 }
106 struct dtx_font *dtx_open_font_glyphmap(const char *fname)
107 {
108 struct dtx_font *fnt;
109 struct dtx_glyphmap *gmap;
111 if(!(fnt = calloc(1, sizeof *fnt))) {
112 fperror("failed to allocate font structure");
113 return 0;
114 }
116 if(fname) {
117 if(!(gmap = dtx_load_glyphmap(fname))) {
118 free(fnt);
119 return 0;
120 }
122 dtx_add_glyphmap(fnt, gmap);
123 }
124 return fnt;
125 }
127 void dtx_close_font(struct dtx_font *fnt)
128 {
129 if(!fnt) return;
131 #ifdef USE_FREETYPE
132 FT_Done_Face(fnt->face);
133 #endif
135 /* destroy the glyphmaps */
136 while(fnt->gmaps) {
137 void *tmp = fnt->gmaps;
138 fnt->gmaps = fnt->gmaps->next;
139 dtx_free_glyphmap(tmp);
140 }
142 free(fnt);
143 }
145 void dtx_prepare(struct dtx_font *fnt, int sz)
146 {
147 if(!dtx_get_font_glyphmap_range(fnt, sz, 0, 256)) {
148 fprintf(stderr, "%s: failed (sz: %d, range: 0-255 [ascii])\n", __FUNCTION__, sz);
149 }
150 }
152 void dtx_prepare_range(struct dtx_font *fnt, int sz, int cstart, int cend)
153 {
154 if(!dtx_get_font_glyphmap_range(fnt, sz, cstart, cend)) {
155 fprintf(stderr, "%s: failed (sz: %d, range: %d-%d)\n", __FUNCTION__, sz, cstart, cend);
156 }
157 }
159 struct dtx_glyphmap *dtx_get_font_glyphmap(struct dtx_font *fnt, int sz, int code)
160 {
161 struct dtx_glyphmap *gm;
163 /* check to see if the last we've given out fits the bill */
164 if(fnt->last_gmap && code >= fnt->last_gmap->cstart && code < fnt->last_gmap->cend && fnt->last_gmap->ptsize == sz) {
165 return fnt->last_gmap;
166 }
168 /* otherwise search for the appropriate glyphmap */
169 gm = fnt->gmaps;
170 while(gm) {
171 if(code >= gm->cstart && code < gm->cend && sz == gm->ptsize) {
172 fnt->last_gmap = gm;
173 return gm;
174 }
175 gm = gm->next;
176 }
177 return 0;
178 }
180 struct dtx_glyphmap *dtx_get_font_glyphmap_range(struct dtx_font *fnt, int sz, int cstart, int cend)
181 {
182 struct dtx_glyphmap *gm;
184 /* search the available glyphmaps to see if we've got one that includes
185 * the requested range
186 */
187 gm = fnt->gmaps;
188 while(gm) {
189 if(gm->cstart <= cstart && gm->cend >= cend && gm->ptsize == sz) {
190 return gm;
191 }
192 gm = gm->next;
193 }
195 /* not found, create one and add it to the list */
196 if(!(gm = dtx_create_glyphmap_range(fnt, sz, cstart, cend))) {
197 return 0;
198 }
199 return gm;
200 }
202 struct dtx_glyphmap *dtx_create_glyphmap_range(struct dtx_font *fnt, int sz, int cstart, int cend)
203 {
204 struct dtx_glyphmap *gmap = 0;
206 #ifdef USE_FREETYPE
207 FT_Face face = fnt->face;
208 int i, j;
209 int gx, gy;
210 int padding = 4;
211 int total_width, max_width, max_height;
213 FT_Set_Char_Size(fnt->face, 0, sz * 64, 72, 72);
215 if(!(gmap = calloc(1, sizeof *gmap))) {
216 return 0;
217 }
219 gmap->ptsize = sz;
220 gmap->cstart = cstart;
221 gmap->cend = cend;
222 gmap->crange = cend - cstart;
223 gmap->line_advance = FTSZ_TO_PIXELS((float)face->size->metrics.height);
225 if(!(gmap->glyphs = malloc(gmap->crange * sizeof *gmap->glyphs))) {
226 free(gmap);
227 return 0;
228 }
230 total_width = padding;
231 max_width = max_height = 0;
233 for(i=0; i<gmap->crange; i++) {
234 int w, h;
236 FT_Load_Char(face, i + cstart, 0);
237 w = FTSZ_TO_PIXELS(face->glyph->metrics.width);
238 h = FTSZ_TO_PIXELS(face->glyph->metrics.height);
240 if(w > max_width) max_width = w;
241 if(h > max_height) max_height = h;
243 total_width += w + padding;
244 }
246 calc_best_size(total_width, max_width, max_height, padding, 1, &gmap->xsz, &gmap->ysz);
248 if(!(gmap->pixels = malloc(gmap->xsz * gmap->ysz))) {
249 free(gmap->glyphs);
250 free(gmap);
251 return 0;
252 }
253 memset(gmap->pixels, 0, gmap->xsz * gmap->ysz);
255 gx = padding;
256 gy = padding;
258 for(i=0; i<gmap->crange; i++) {
259 float gwidth, gheight;
260 unsigned char *src, *dst;
261 FT_GlyphSlot glyph;
263 FT_Load_Char(face, i + cstart, FT_LOAD_RENDER);
264 glyph = face->glyph;
265 gwidth = FTSZ_TO_PIXELS((float)glyph->metrics.width);
266 gheight = FTSZ_TO_PIXELS((float)glyph->metrics.height);
268 if(gx > gmap->xsz - gwidth - padding) {
269 gx = padding;
270 gy += max_height + padding;
271 }
273 src = glyph->bitmap.buffer;
274 dst = gmap->pixels + gy * gmap->xsz + gx;
276 for(j=0; j<glyph->bitmap.rows; j++) {
277 memcpy(dst, src, glyph->bitmap.width);
278 dst += gmap->xsz;
279 src += glyph->bitmap.pitch;
280 }
282 gmap->glyphs[i].code = i;
283 gmap->glyphs[i].x = gx - 1;
284 gmap->glyphs[i].y = gy - 1;
285 gmap->glyphs[i].width = gwidth + 2;
286 gmap->glyphs[i].height = gheight + 2;
287 gmap->glyphs[i].orig_x = -FTSZ_TO_PIXELS((float)glyph->metrics.horiBearingX) + 1;
288 gmap->glyphs[i].orig_y = FTSZ_TO_PIXELS((float)glyph->metrics.height - glyph->metrics.horiBearingY) + 1;
289 gmap->glyphs[i].advance = FTSZ_TO_PIXELS((float)glyph->metrics.horiAdvance);
290 /* also precalc normalized */
291 gmap->glyphs[i].nx = (float)gmap->glyphs[i].x / (float)gmap->xsz;
292 gmap->glyphs[i].ny = (float)gmap->glyphs[i].y / (float)gmap->ysz;
293 gmap->glyphs[i].nwidth = (float)gmap->glyphs[i].width / (float)gmap->xsz;
294 gmap->glyphs[i].nheight = (float)gmap->glyphs[i].height / (float)gmap->ysz;
296 gx += gwidth + padding;
297 }
299 /* add it to the glyphmaps list of the font */
300 dtx_add_glyphmap(fnt, gmap);
301 #endif /* USE_FREETYPE */
303 return gmap;
304 }
306 void dtx_free_glyphmap(struct dtx_glyphmap *gmap)
307 {
308 if(gmap) {
309 free(gmap->pixels);
310 free(gmap->glyphs);
311 free(gmap);
312 }
313 }
315 unsigned char *dtx_get_glyphmap_pixels(struct dtx_glyphmap *gmap)
316 {
317 return gmap->pixels;
318 }
320 int dtx_get_glyphmap_width(struct dtx_glyphmap *gmap)
321 {
322 return gmap->xsz;
323 }
325 int dtx_get_glyphmap_height(struct dtx_glyphmap *gmap)
326 {
327 return gmap->ysz;
328 }
330 struct dtx_glyphmap *dtx_load_glyphmap(const char *fname)
331 {
332 FILE *fp;
333 struct dtx_glyphmap *gmap;
335 if(!(fp = fopen(fname, "r"))) {
336 return 0;
337 }
338 gmap = dtx_load_glyphmap_stream(fp);
339 fclose(fp);
340 return gmap;
341 }
343 struct dtx_glyphmap *dtx_load_glyphmap_stream(FILE *fp)
344 {
345 char buf[512];
346 int hdr_lines = 0;
347 struct dtx_glyphmap *gmap;
348 struct glyph *glyphs = 0;
349 struct glyph *g;
350 int min_code = INT_MAX;
351 int max_code = INT_MIN;
352 int i, max_pixval, num_pixels;
354 if(!(gmap = calloc(1, sizeof *gmap))) {
355 fperror("failed to allocate glyphmap");
356 return 0;
357 }
358 gmap->ptsize = -1;
359 gmap->line_advance = FLT_MIN;
361 while(hdr_lines < 3) {
362 char *line = buf;
363 if(!fgets(buf, sizeof buf, fp)) {
364 fperror("unexpected end of file");
365 goto err;
366 }
368 while(isspace(*line)) {
369 line++;
370 }
372 if(line[0] == '#') {
373 int c, res;
374 float x, y, xsz, ysz, orig_x, orig_y, adv, line_adv;
375 int ptsize;
377 if((res = sscanf(line + 1, " size: %d\n", &ptsize)) == 1) {
378 gmap->ptsize = ptsize;
380 } else if((res = sscanf(line + 1, " advance: %f\n", &line_adv)) == 1) {
381 gmap->line_advance = line_adv;
383 } else if((res = sscanf(line + 1, " %d: %fx%f+%f+%f o:%f,%f adv:%f\n",
384 &c, &xsz, &ysz, &x, &y, &orig_x, &orig_y, &adv)) == 8) {
385 if(!(g = malloc(sizeof *g))) {
386 fperror("failed to allocate glyph");
387 goto err;
388 }
389 g->code = c;
390 g->x = x;
391 g->y = y;
392 g->width = xsz;
393 g->height = ysz;
394 g->orig_x = orig_x;
395 g->orig_y = orig_y;
396 g->advance = adv;
397 /* normalized coordinates will be precalculated after everything is loaded */
399 g->next = glyphs;
400 glyphs = g;
402 if(c < min_code) {
403 min_code = c;
404 }
405 if(c > max_code) {
406 max_code = c;
407 }
409 } else {
410 fprintf(stderr, "%s: invalid glyph info line\n", __FUNCTION__);
411 goto err;
412 }
414 } else {
415 switch(hdr_lines) {
416 case 0:
417 if(0[line] != 'P' || 1[line] != '6') {
418 fprintf(stderr, "%s: invalid file format (magic)\n", __FUNCTION__);
419 goto err;
420 }
421 break;
423 case 1:
424 if(sscanf(line, "%d %d", &gmap->xsz, &gmap->ysz) != 2) {
425 fprintf(stderr, "%s: invalid file format (dim)\n", __FUNCTION__);
426 goto err;
427 }
428 break;
430 case 2:
431 {
432 char *endp;
433 max_pixval = strtol(line, &endp, 10);
434 if(endp == line) {
435 fprintf(stderr, "%s: invalid file format (maxval)\n", __FUNCTION__);
436 goto err;
437 }
438 }
439 break;
441 default:
442 break; /* can't happen */
443 }
444 hdr_lines++;
445 }
446 }
448 if(gmap->ptsize == -1 || gmap->line_advance == FLT_MIN) {
449 fprintf(stderr, "%s: invalid glyphmap, insufficient information in ppm comments\n", __FUNCTION__);
450 goto err;
451 }
453 /* precalculate normalized glyph coordinates */
454 g = glyphs;
455 while(g) {
456 g->nx = g->x / gmap->xsz;
457 g->ny = g->y / gmap->ysz;
458 g->nwidth = g->width / gmap->xsz;
459 g->nheight = g->height / gmap->ysz;
460 g = g->next;
461 }
463 num_pixels = gmap->xsz * gmap->ysz;
464 if(!(gmap->pixels = malloc(num_pixels))) {
465 fperror("failed to allocate pixels");
466 goto err;
467 }
469 for(i=0; i<num_pixels; i++) {
470 long c = fgetc(fp);
471 if(c == -1) {
472 fprintf(stderr, "unexpected end of file while reading pixels\n");
473 goto err;
474 }
475 gmap->pixels[i] = 255 * c / max_pixval;
476 fseek(fp, 2, SEEK_CUR);
477 }
479 gmap->cstart = min_code;
480 gmap->cend = max_code + 1;
481 gmap->crange = gmap->cend - gmap->cstart;
483 if(!(gmap->glyphs = calloc(gmap->crange, sizeof *gmap->glyphs))) {
484 fperror("failed to allocate glyph info");
485 goto err;
486 }
488 while(glyphs) {
489 struct glyph *g = glyphs;
490 glyphs = glyphs->next;
492 gmap->glyphs[g->code - gmap->cstart] = *g;
493 free(g);
494 }
495 return gmap;
497 err:
498 dtx_free_glyphmap(gmap);
499 while(glyphs) {
500 void *tmp = glyphs;
501 glyphs = glyphs->next;
502 free(tmp);
503 }
504 return 0;
505 }
507 int dtx_save_glyphmap(const char *fname, const struct dtx_glyphmap *gmap)
508 {
509 FILE *fp;
510 int res;
512 if(!(fp = fopen(fname, "wb"))) {
513 fprintf(stderr, "%s: failed to open file: %s: %s\n", __FUNCTION__, fname, strerror(errno));
514 return -1;
515 }
516 res = dtx_save_glyphmap_stream(fp, gmap);
517 fclose(fp);
518 return res;
519 }
521 int dtx_save_glyphmap_stream(FILE *fp, const struct dtx_glyphmap *gmap)
522 {
523 int i, num_pixels;
524 struct glyph *g = gmap->glyphs;
526 fprintf(fp, "P6\n%d %d\n", gmap->xsz, gmap->ysz);
527 fprintf(fp, "# size: %d\n", gmap->ptsize);
528 fprintf(fp, "# advance: %g\n", gmap->line_advance);
529 for(i=0; i<gmap->crange; i++) {
530 fprintf(fp, "# %d: %gx%g+%g+%g o:%g,%g adv:%g\n", g->code, g->width, g->height, g->x, g->y,
531 g->orig_x, g->orig_y, g->advance);
532 g++;
533 }
534 fprintf(fp, "255\n");
536 num_pixels = gmap->xsz * gmap->ysz;
537 for(i=0; i<num_pixels; i++) {
538 int c = gmap->pixels[i];
539 fputc(c, fp);
540 fputc(c, fp);
541 fputc(c, fp);
542 }
543 return 0;
544 }
546 void dtx_add_glyphmap(struct dtx_font *fnt, struct dtx_glyphmap *gmap)
547 {
548 gmap->next = fnt->gmaps;
549 fnt->gmaps = gmap;
550 }
553 void dtx_use_font(struct dtx_font *fnt, int sz)
554 {
555 dtx_gl_init();
557 dtx_font = fnt;
558 dtx_font_sz = sz;
559 }
561 float dtx_line_height(void)
562 {
563 struct dtx_glyphmap *gmap = dtx_get_font_glyphmap(dtx_font, dtx_font_sz, '\n');
565 return gmap->line_advance;
566 }
568 void dtx_glyph_box(int code, struct dtx_box *box)
569 {
570 int cidx;
571 struct dtx_glyphmap *gmap;
572 gmap = dtx_get_font_glyphmap(dtx_font, dtx_font_sz, code);
574 cidx = code - gmap->cstart;
576 box->x = gmap->glyphs[cidx].orig_x;
577 box->y = gmap->glyphs[cidx].orig_y;
578 box->width = gmap->glyphs[cidx].width;
579 box->height = gmap->glyphs[cidx].height;
580 }
582 float dtx_glyph_width(int code)
583 {
584 struct dtx_box box;
585 dtx_glyph_box(code, &box);
586 return box.width;
587 }
589 float dtx_glyph_height(int code)
590 {
591 struct dtx_box box;
592 dtx_glyph_box(code, &box);
593 return box.height;
594 }
596 void dtx_string_box(const char *str, struct dtx_box *box)
597 {
598 int code;
599 float pos_x = 0.0f, pos_y = 0.0f;
600 struct glyph *g = 0;
601 float x0, y0, x1, y1;
603 x0 = y0 = FLT_MAX;
604 x1 = y1 = -FLT_MAX;
606 while(*str) {
607 float px, py;
608 struct dtx_glyphmap *gmap;
610 code = dtx_utf8_char_code(str);
611 str = dtx_utf8_next_char((char*)str);
613 px = pos_x;
614 py = pos_y;
616 if((gmap = dtx_proc_char(code, &pos_x, &pos_y))) {
617 g = gmap->glyphs + code - gmap->cstart;
619 if(px + g->orig_x < x0) {
620 x0 = px + g->orig_x;
621 }
622 if(py - g->orig_y < y0) {
623 y0 = py - g->orig_y;
624 }
625 if(px + g->orig_x + g->width > x1) {
626 x1 = px + g->orig_x + g->width;
627 }
628 if(py - g->orig_y + g->height > y1) {
629 y1 = py - g->orig_y + g->height;
630 }
631 }
632 }
634 box->x = x0;
635 box->y = y0;
636 box->width = x1 - x0;
637 box->height = y1 - y0;
638 }
640 float dtx_string_width(const char *str)
641 {
642 struct dtx_box box;
644 dtx_string_box(str, &box);
645 return box.width;
646 }
648 float dtx_string_height(const char *str)
649 {
650 struct dtx_box box;
652 dtx_string_box(str, &box);
653 return box.height;
654 }
656 float dtx_char_pos(const char *str, int n)
657 {
658 int i;
659 float pos = 0.0;
660 struct dtx_glyphmap *gmap;
662 for(i=0; i<n; i++) {
663 int code = dtx_utf8_char_code(str);
664 str = dtx_utf8_next_char((char*)str);
666 gmap = dtx_get_font_glyphmap(dtx_font, dtx_font_sz, code);
667 pos += gmap->glyphs[i].advance;
668 }
669 return pos;
670 }
672 int dtx_char_at_pt(const char *str, float pt)
673 {
674 int i;
675 float prev_pos = 0.0f, pos = 0.0f;
676 struct dtx_glyphmap *gmap;
678 for(i=0; *str; i++) {
679 int code = dtx_utf8_char_code(str);
680 str = dtx_utf8_next_char((char*)str);
682 gmap = dtx_get_font_glyphmap(dtx_font, dtx_font_sz, code);
683 pos += gmap->glyphs[i].advance;
685 if(fabs(pt - prev_pos) < fabs(pt - pos)) {
686 break;
687 }
688 prev_pos = pos;
689 }
690 return i;
691 }
693 struct dtx_glyphmap *dtx_proc_char(int code, float *xpos, float *ypos)
694 {
695 struct dtx_glyphmap *gmap;
696 gmap = dtx_get_font_glyphmap(dtx_font, dtx_font_sz, code);
698 switch(code) {
699 case '\n':
700 *xpos = 0.0;
701 if(gmap) {
702 *ypos -= gmap->line_advance;
703 }
704 return 0;
706 case '\t':
707 if(gmap) {
708 *xpos = (fmod(*xpos, 4.0) + 4.0) * gmap->glyphs[0].advance;
709 }
710 return 0;
712 case '\r':
713 *xpos = 0.0;
714 return 0;
716 default:
717 break;
718 }
720 if(gmap) {
721 *xpos += gmap->glyphs[code - gmap->cstart].advance;
722 }
723 return gmap;
724 }
726 #ifdef USE_FREETYPE
727 static void calc_best_size(int total_width, int max_gwidth, int max_gheight, int padding, int pow2, int *imgw, int *imgh)
728 {
729 int xsz, ysz, num_rows;
730 float aspect;
732 for(xsz=2; xsz<=MAX_IMG_WIDTH; xsz *= 2) {
733 num_rows = total_width / xsz + 1;
735 /* assume worst case, all last glyphs will float to the next line
736 * so let's add extra rows for that. */
737 num_rows += (padding + (max_gwidth + padding) * num_rows + xsz - 1) / xsz;
739 ysz = num_rows * (max_gheight + padding) + padding;
740 if(pow2) {
741 ysz = next_pow2(ysz);
742 }
743 aspect = (float)xsz / (float)ysz;
745 if(aspect >= 1.0) {
746 break;
747 }
748 }
750 if(xsz > MAX_IMG_WIDTH) {
751 xsz = MAX_IMG_WIDTH;
752 }
754 *imgw = xsz;
755 *imgh = ysz;
756 }
759 static int next_pow2(int x)
760 {
761 x--;
762 x = (x >> 1) | x;
763 x = (x >> 2) | x;
764 x = (x >> 4) | x;
765 x = (x >> 8) | x;
766 x = (x >> 16) | x;
767 return x + 1;
768 }
769 #endif