libdrawtext

view src/font.c @ 22:df6d52b36bd6

- properly supported building of no-freetype version, separately installed as libdrawtext-noft.whatever - saving/loading glyphmaps now work correctly - added nofreetype program in examples, to illustrate how to use libdrawtext-noft with prebuilt glyphmaps (see tools/font2glyphmap)
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 15 Apr 2014 05:10:39 +0300
parents baec6ad7b2dd
children 5beaab3df0cb
line source
1 /*
2 libdrawtext - a simple library for fast text rendering in OpenGL
3 Copyright (C) 2011 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_glyph_height, int padding, int pow2, int *imgw, int *imgh);
46 static int next_pow2(int x);
48 static FT_Library ft;
51 static int init_done;
53 static int init_freetype(void)
54 {
55 if(!init_done) {
56 if(FT_Init_FreeType(&ft) != 0) {
57 return -1;
58 }
59 atexit(cleanup);
60 init_done = 1;
61 }
62 return 0;
63 }
65 static void cleanup(void)
66 {
67 if(init_done) {
68 FT_Done_FreeType(ft);
69 }
70 }
71 #endif /* USE_FREETYPE */
73 struct dtx_font *dtx_open_font(const char *fname, int sz)
74 {
75 struct dtx_font *fnt = 0;
77 #ifdef USE_FREETYPE
78 init_freetype();
80 if(!(fnt = calloc(1, sizeof *fnt))) {
81 fperror("failed to allocate font structure");
82 return 0;
83 }
85 if(FT_New_Face(ft, fname, 0, (FT_Face*)&fnt->face) != 0) {
86 fprintf(stderr, "failed to open font file: %s\n", fname);
87 return 0;
88 }
90 /* pre-create the extended ASCII range glyphmap */
91 if(sz) {
92 dtx_prepare_range(fnt, sz, 0, 256);
94 if(!dtx_font) {
95 dtx_use_font(fnt, sz);
96 }
97 }
98 #else
99 fprintf(stderr, "ignoring call to dtx_open_font: not compiled with freetype support!\n");
100 #endif
102 return fnt;
103 }
105 struct dtx_font *dtx_open_font_glyphmap(const char *fname)
106 {
107 struct dtx_font *fnt;
108 struct dtx_glyphmap *gmap;
110 if(!(fnt = calloc(1, sizeof *fnt))) {
111 fperror("failed to allocate font structure");
112 return 0;
113 }
115 if(fname) {
116 if(!(gmap = dtx_load_glyphmap(fname))) {
117 free(fnt);
118 return 0;
119 }
121 dtx_add_glyphmap(fnt, gmap);
122 }
123 return fnt;
124 }
126 void dtx_close_font(struct dtx_font *fnt)
127 {
128 if(!fnt) return;
130 #ifdef USE_FREETYPE
131 FT_Done_Face(fnt->face);
132 #endif
134 /* destroy the glyphmaps */
135 while(fnt->gmaps) {
136 void *tmp = fnt->gmaps;
137 fnt->gmaps = fnt->gmaps->next;
138 dtx_free_glyphmap(tmp);
139 }
141 free(fnt);
142 }
144 void dtx_prepare(struct dtx_font *fnt, int sz)
145 {
146 if(!dtx_get_font_glyphmap_range(fnt, sz, 0, 256)) {
147 fprintf(stderr, "%s: failed (sz: %d, range: 0-255 [ascii])\n", __FUNCTION__, sz);
148 }
149 }
151 void dtx_prepare_range(struct dtx_font *fnt, int sz, int cstart, int cend)
152 {
153 if(!dtx_get_font_glyphmap_range(fnt, sz, cstart, cend)) {
154 fprintf(stderr, "%s: failed (sz: %d, range: %d-%d)\n", __FUNCTION__, sz, cstart, cend);
155 }
156 }
158 struct dtx_glyphmap *dtx_get_font_glyphmap(struct dtx_font *fnt, int sz, int code)
159 {
160 struct dtx_glyphmap *gm;
162 /* check to see if the last we've given out fits the bill */
163 if(fnt->last_gmap && code >= fnt->last_gmap->cstart && code < fnt->last_gmap->cend && fnt->last_gmap->ptsize == sz) {
164 return fnt->last_gmap;
165 }
167 /* otherwise search for the appropriate glyphmap */
168 gm = fnt->gmaps;
169 while(gm) {
170 if(code >= gm->cstart && code < gm->cend && sz == gm->ptsize) {
171 fnt->last_gmap = gm;
172 return gm;
173 }
174 gm = gm->next;
175 }
176 return 0;
177 }
179 struct dtx_glyphmap *dtx_get_font_glyphmap_range(struct dtx_font *fnt, int sz, int cstart, int cend)
180 {
181 struct dtx_glyphmap *gm;
183 /* search the available glyphmaps to see if we've got one that includes
184 * the requested range
185 */
186 gm = fnt->gmaps;
187 while(gm) {
188 if(gm->cstart <= cstart && gm->cend >= cend && gm->ptsize == sz) {
189 return gm;
190 }
191 gm = gm->next;
192 }
194 /* not found, create one and add it to the list */
195 if(!(gm = dtx_create_glyphmap_range(fnt, sz, cstart, cend))) {
196 return 0;
197 }
198 return gm;
199 }
201 struct dtx_glyphmap *dtx_create_glyphmap_range(struct dtx_font *fnt, int sz, int cstart, int cend)
202 {
203 struct dtx_glyphmap *gmap = 0;
205 #ifdef USE_FREETYPE
206 FT_Face face = fnt->face;
207 int i, j;
208 int gx, gy;
209 int padding = 4;
210 int total_width = padding;
211 int max_height = 0;
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 for(i=0; i<gmap->crange; i++) {
231 int h;
233 FT_Load_Char(face, i + cstart, 0);
234 h = FTSZ_TO_PIXELS(face->glyph->metrics.height);
236 if(h > max_height) {
237 max_height = h;
238 }
239 total_width += FTSZ_TO_PIXELS(face->glyph->metrics.width) + padding;
240 }
242 calc_best_size(total_width, max_height, padding, 1, &gmap->xsz, &gmap->ysz);
244 if(!(gmap->pixels = malloc(gmap->xsz * gmap->ysz))) {
245 free(gmap->glyphs);
246 free(gmap);
247 return 0;
248 }
249 memset(gmap->pixels, 0, gmap->xsz * gmap->ysz);
251 gx = padding;
252 gy = padding;
254 for(i=0; i<gmap->crange; i++) {
255 float gwidth, gheight;
256 unsigned char *src, *dst;
257 FT_GlyphSlot glyph;
259 FT_Load_Char(face, i + cstart, FT_LOAD_RENDER);
260 glyph = face->glyph;
261 gwidth = FTSZ_TO_PIXELS((float)glyph->metrics.width);
262 gheight = FTSZ_TO_PIXELS((float)glyph->metrics.height);
264 if(gx > gmap->xsz - gwidth - padding) {
265 gx = padding;
266 gy += max_height + padding;
267 }
269 src = glyph->bitmap.buffer;
270 dst = gmap->pixels + gy * gmap->xsz + gx;
272 for(j=0; j<glyph->bitmap.rows; j++) {
273 memcpy(dst, src, glyph->bitmap.width);
274 dst += gmap->xsz;
275 src += glyph->bitmap.pitch;
276 }
278 gmap->glyphs[i].code = i;
279 gmap->glyphs[i].x = gx - 1;
280 gmap->glyphs[i].y = gy - 1;
281 gmap->glyphs[i].width = gwidth + 2;
282 gmap->glyphs[i].height = gheight + 2;
283 gmap->glyphs[i].orig_x = -FTSZ_TO_PIXELS((float)glyph->metrics.horiBearingX) + 1;
284 gmap->glyphs[i].orig_y = FTSZ_TO_PIXELS((float)glyph->metrics.height - glyph->metrics.horiBearingY) + 1;
285 gmap->glyphs[i].advance = FTSZ_TO_PIXELS((float)glyph->metrics.horiAdvance);
286 /* also precalc normalized */
287 gmap->glyphs[i].nx = (float)gmap->glyphs[i].x / (float)gmap->xsz;
288 gmap->glyphs[i].ny = (float)gmap->glyphs[i].y / (float)gmap->ysz;
289 gmap->glyphs[i].nwidth = (float)gmap->glyphs[i].width / (float)gmap->xsz;
290 gmap->glyphs[i].nheight = (float)gmap->glyphs[i].height / (float)gmap->ysz;
292 gx += gwidth + padding;
293 }
295 /* add it to the glyphmaps list of the font */
296 dtx_add_glyphmap(fnt, gmap);
297 #endif /* USE_FREETYPE */
299 return gmap;
300 }
302 void dtx_free_glyphmap(struct dtx_glyphmap *gmap)
303 {
304 if(gmap) {
305 free(gmap->pixels);
306 free(gmap->glyphs);
307 free(gmap);
308 }
309 }
311 unsigned char *dtx_get_glyphmap_pixels(struct dtx_glyphmap *gmap)
312 {
313 return gmap->pixels;
314 }
316 int dtx_get_glyphmap_width(struct dtx_glyphmap *gmap)
317 {
318 return gmap->xsz;
319 }
321 int dtx_get_glyphmap_height(struct dtx_glyphmap *gmap)
322 {
323 return gmap->ysz;
324 }
326 struct dtx_glyphmap *dtx_load_glyphmap(const char *fname)
327 {
328 FILE *fp;
329 struct dtx_glyphmap *gmap;
331 if(!(fp = fopen(fname, "r"))) {
332 return 0;
333 }
334 gmap = dtx_load_glyphmap_stream(fp);
335 fclose(fp);
336 return gmap;
337 }
339 struct dtx_glyphmap *dtx_load_glyphmap_stream(FILE *fp)
340 {
341 char buf[512];
342 int hdr_lines = 0;
343 struct dtx_glyphmap *gmap;
344 struct glyph *glyphs = 0;
345 struct glyph *g;
346 int min_code = INT_MAX;
347 int max_code = INT_MIN;
348 int i, max_pixval, num_pixels;
350 if(!(gmap = calloc(1, sizeof *gmap))) {
351 fperror("failed to allocate glyphmap");
352 return 0;
353 }
354 gmap->ptsize = -1;
355 gmap->line_advance = FLT_MIN;
357 while(hdr_lines < 3) {
358 char *line = buf;
359 if(!fgets(buf, sizeof buf, fp)) {
360 fperror("unexpected end of file");
361 goto err;
362 }
364 while(isspace(*line)) {
365 line++;
366 }
368 if(line[0] == '#') {
369 int c, res;
370 float x, y, xsz, ysz, orig_x, orig_y, adv, line_adv;
371 int ptsize;
373 if((res = sscanf(line + 1, " size: %d\n", &ptsize)) == 1) {
374 gmap->ptsize = ptsize;
376 } else if((res = sscanf(line + 1, " advance: %f\n", &line_adv)) == 1) {
377 gmap->line_advance = line_adv;
379 } else if((res = sscanf(line + 1, " %d: %fx%f+%f+%f o:%f,%f adv:%f\n",
380 &c, &xsz, &ysz, &x, &y, &orig_x, &orig_y, &adv)) == 8) {
381 if(!(g = malloc(sizeof *g))) {
382 fperror("failed to allocate glyph");
383 goto err;
384 }
385 g->code = c;
386 g->x = x;
387 g->y = y;
388 g->width = xsz;
389 g->height = ysz;
390 g->orig_x = orig_x;
391 g->orig_y = orig_y;
392 g->advance = adv;
393 /* normalized coordinates will be precalculated after everything is loaded */
395 g->next = glyphs;
396 glyphs = g;
398 if(c < min_code) {
399 min_code = c;
400 }
401 if(c > max_code) {
402 max_code = c;
403 }
405 } else {
406 fprintf(stderr, "%s: invalid glyph info line\n", __FUNCTION__);
407 goto err;
408 }
410 } else {
411 switch(hdr_lines) {
412 case 0:
413 if(0[line] != 'P' || 1[line] != '6') {
414 fprintf(stderr, "%s: invalid file format (magic)\n", __FUNCTION__);
415 goto err;
416 }
417 break;
419 case 1:
420 if(sscanf(line, "%d %d", &gmap->xsz, &gmap->ysz) != 2) {
421 fprintf(stderr, "%s: invalid file format (dim)\n", __FUNCTION__);
422 goto err;
423 }
424 break;
426 case 2:
427 {
428 char *endp;
429 max_pixval = strtol(line, &endp, 10);
430 if(endp == line) {
431 fprintf(stderr, "%s: invalid file format (maxval)\n", __FUNCTION__);
432 goto err;
433 }
434 }
435 break;
437 default:
438 break; /* can't happen */
439 }
440 hdr_lines++;
441 }
442 }
444 if(gmap->ptsize == -1 || gmap->line_advance == FLT_MIN) {
445 fprintf(stderr, "%s: invalid glyphmap, insufficient information in ppm comments\n", __FUNCTION__);
446 goto err;
447 }
449 /* precalculate normalized glyph coordinates */
450 g = glyphs;
451 while(g) {
452 g->nx = g->x / gmap->xsz;
453 g->ny = g->y / gmap->ysz;
454 g->nwidth = g->width / gmap->xsz;
455 g->nheight = g->height / gmap->ysz;
456 g = g->next;
457 }
459 num_pixels = gmap->xsz * gmap->ysz;
460 if(!(gmap->pixels = malloc(num_pixels))) {
461 fperror("failed to allocate pixels");
462 goto err;
463 }
465 for(i=0; i<num_pixels; i++) {
466 long c = fgetc(fp);
467 if(c == -1) {
468 fprintf(stderr, "unexpected end of file while reading pixels\n");
469 goto err;
470 }
471 gmap->pixels[i] = 255 * c / max_pixval;
472 fseek(fp, 2, SEEK_CUR);
473 }
475 gmap->cstart = min_code;
476 gmap->cend = max_code + 1;
477 gmap->crange = gmap->cend - gmap->cstart;
479 if(!(gmap->glyphs = calloc(gmap->crange, sizeof *gmap->glyphs))) {
480 fperror("failed to allocate glyph info");
481 goto err;
482 }
484 while(glyphs) {
485 struct glyph *g = glyphs;
486 glyphs = glyphs->next;
488 gmap->glyphs[g->code - gmap->cstart] = *g;
489 free(g);
490 }
491 return gmap;
493 err:
494 dtx_free_glyphmap(gmap);
495 while(glyphs) {
496 void *tmp = glyphs;
497 glyphs = glyphs->next;
498 free(tmp);
499 }
500 return 0;
501 }
503 int dtx_save_glyphmap(const char *fname, const struct dtx_glyphmap *gmap)
504 {
505 FILE *fp;
506 int res;
508 if(!(fp = fopen(fname, "wb"))) {
509 fprintf(stderr, "%s: failed to open file: %s: %s\n", __FUNCTION__, fname, strerror(errno));
510 return -1;
511 }
512 res = dtx_save_glyphmap_stream(fp, gmap);
513 fclose(fp);
514 return res;
515 }
517 int dtx_save_glyphmap_stream(FILE *fp, const struct dtx_glyphmap *gmap)
518 {
519 int i, num_pixels;
520 struct glyph *g = gmap->glyphs;
522 fprintf(fp, "P6\n%d %d\n", gmap->xsz, gmap->ysz);
523 fprintf(fp, "# size: %d\n", gmap->ptsize);
524 fprintf(fp, "# advance: %g\n", gmap->line_advance);
525 for(i=0; i<gmap->crange; i++) {
526 fprintf(fp, "# %d: %gx%g+%g+%g o:%g,%g adv:%g\n", g->code, g->width, g->height, g->x, g->y,
527 g->orig_x, g->orig_y, g->advance);
528 g++;
529 }
530 fprintf(fp, "255\n");
532 num_pixels = gmap->xsz * gmap->ysz;
533 for(i=0; i<num_pixels; i++) {
534 int c = gmap->pixels[i];
535 fputc(c, fp);
536 fputc(c, fp);
537 fputc(c, fp);
538 }
539 return 0;
540 }
542 void dtx_add_glyphmap(struct dtx_font *fnt, struct dtx_glyphmap *gmap)
543 {
544 gmap->next = fnt->gmaps;
545 fnt->gmaps = gmap;
546 }
549 void dtx_use_font(struct dtx_font *fnt, int sz)
550 {
551 dtx_gl_init();
553 dtx_font = fnt;
554 dtx_font_sz = sz;
555 }
557 float dtx_line_height(void)
558 {
559 struct dtx_glyphmap *gmap = dtx_get_font_glyphmap(dtx_font, dtx_font_sz, '\n');
561 return gmap->line_advance;
562 }
564 void dtx_glyph_box(int code, struct dtx_box *box)
565 {
566 int cidx;
567 struct dtx_glyphmap *gmap;
568 gmap = dtx_get_font_glyphmap(dtx_font, dtx_font_sz, code);
570 cidx = code - gmap->cstart;
572 box->x = gmap->glyphs[cidx].orig_x;
573 box->y = gmap->glyphs[cidx].orig_y;
574 box->width = gmap->glyphs[cidx].width;
575 box->height = gmap->glyphs[cidx].height;
576 }
578 float dtx_glyph_width(int code)
579 {
580 struct dtx_box box;
581 dtx_glyph_box(code, &box);
582 return box.width;
583 }
585 float dtx_glyph_height(int code)
586 {
587 struct dtx_box box;
588 dtx_glyph_box(code, &box);
589 return box.height;
590 }
592 void dtx_string_box(const char *str, struct dtx_box *box)
593 {
594 int code;
595 float pos_x = 0.0f, pos_y = 0.0f;
596 struct glyph *g = 0;
597 float x0, y0, x1, y1;
599 x0 = y0 = FLT_MAX;
600 x1 = y1 = -FLT_MAX;
602 while(*str) {
603 float px, py;
604 struct dtx_glyphmap *gmap;
606 code = dtx_utf8_char_code(str);
607 str = dtx_utf8_next_char((char*)str);
609 px = pos_x;
610 py = pos_y;
612 if((gmap = dtx_proc_char(code, &pos_x, &pos_y))) {
613 g = gmap->glyphs + code - gmap->cstart;
615 if(px + g->orig_x < x0) {
616 x0 = px + g->orig_x;
617 }
618 if(py - g->orig_y < y0) {
619 y0 = py - g->orig_y;
620 }
621 if(px + g->orig_x + g->width > x1) {
622 x1 = px + g->orig_x + g->width;
623 }
624 if(py - g->orig_y + g->height > y1) {
625 y1 = py - g->orig_y + g->height;
626 }
627 }
628 }
630 box->x = x0;
631 box->y = y0;
632 box->width = x1 - x0;
633 box->height = y1 - y0;
634 }
636 float dtx_string_width(const char *str)
637 {
638 struct dtx_box box;
640 dtx_string_box(str, &box);
641 return box.width;
642 }
644 float dtx_string_height(const char *str)
645 {
646 struct dtx_box box;
648 dtx_string_box(str, &box);
649 return box.height;
650 }
652 float dtx_char_pos(const char *str, int n)
653 {
654 int i;
655 float pos = 0.0;
656 struct dtx_glyphmap *gmap;
658 for(i=0; i<n; i++) {
659 int code = dtx_utf8_char_code(str);
660 str = dtx_utf8_next_char((char*)str);
662 gmap = dtx_get_font_glyphmap(dtx_font, dtx_font_sz, code);
663 pos += gmap->glyphs[i].advance;
664 }
665 return pos;
666 }
668 int dtx_char_at_pt(const char *str, float pt)
669 {
670 int i;
671 float prev_pos = 0.0f, pos = 0.0f;
672 struct dtx_glyphmap *gmap;
674 for(i=0; *str; i++) {
675 int code = dtx_utf8_char_code(str);
676 str = dtx_utf8_next_char((char*)str);
678 gmap = dtx_get_font_glyphmap(dtx_font, dtx_font_sz, code);
679 pos += gmap->glyphs[i].advance;
681 if(fabs(pt - prev_pos) < fabs(pt - pos)) {
682 break;
683 }
684 prev_pos = pos;
685 }
686 return i;
687 }
689 struct dtx_glyphmap *dtx_proc_char(int code, float *xpos, float *ypos)
690 {
691 struct dtx_glyphmap *gmap;
692 gmap = dtx_get_font_glyphmap(dtx_font, dtx_font_sz, code);
694 switch(code) {
695 case '\n':
696 *xpos = 0.0;
697 if(gmap) {
698 *ypos -= gmap->line_advance;
699 }
700 return 0;
702 case '\t':
703 if(gmap) {
704 *xpos = (fmod(*xpos, 4.0) + 4.0) * gmap->glyphs[0].advance;
705 }
706 return 0;
708 case '\r':
709 *xpos = 0.0;
710 return 0;
712 default:
713 break;
714 }
716 if(gmap) {
717 *xpos += gmap->glyphs[code - gmap->cstart].advance;
718 }
719 return gmap;
720 }
722 #ifdef USE_FREETYPE
723 static void calc_best_size(int total_width, int max_glyph_height, int padding, int pow2, int *imgw, int *imgh)
724 {
725 int xsz, ysz, num_rows;
726 float aspect;
728 for(xsz=2; xsz<=MAX_IMG_WIDTH; xsz *= 2) {
729 num_rows = total_width / xsz + 1;
731 /* take into account the one extra padding for each row after the first */
732 num_rows = (total_width + padding * (num_rows - 1)) / xsz + 1;
734 ysz = num_rows * (max_glyph_height + padding) + padding;
735 if(pow2) {
736 ysz = next_pow2(ysz);
737 }
738 aspect = (float)xsz / (float)ysz;
740 if(aspect >= 1.0) {
741 break;
742 }
743 }
745 if(xsz > MAX_IMG_WIDTH) {
746 xsz = MAX_IMG_WIDTH;
747 }
749 *imgw = xsz;
750 *imgh = ysz;
751 }
754 static int next_pow2(int x)
755 {
756 x--;
757 x = (x >> 1) | x;
758 x = (x >> 2) | x;
759 x = (x >> 4) | x;
760 x = (x >> 8) | x;
761 x = (x >> 16) | x;
762 return x + 1;
763 }
764 #endif