Merge branch 'blender2.7'
[blender.git] / source / blender / blenfont / intern / blf_glyph.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2009 Blender Foundation.
17  * All rights reserved.
18  */
19
20 /** \file \ingroup blf
21  *
22  * Glyph rendering, texturing and caching. Wraps Freetype and OpenGL functions.
23  */
24
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <math.h>
30
31 #include <ft2build.h>
32
33 #include FT_FREETYPE_H
34 #include FT_GLYPH_H
35 #include FT_OUTLINE_H
36 #include FT_BITMAP_H
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_vec_types.h"
41 #include "DNA_userdef_types.h"
42
43 #include "BLI_listbase.h"
44 #include "BLI_rect.h"
45 #include "BLI_threads.h"
46
47 #include "BLF_api.h"
48
49 #ifndef BLF_STANDALONE
50 #  include "GPU_immediate.h"
51 #  include "GPU_extensions.h"
52 #endif
53
54 #include "blf_internal_types.h"
55 #include "blf_internal.h"
56
57 #include "BLI_strict_flags.h"
58 #include "BLI_math_vector.h"
59
60 KerningCacheBLF *blf_kerning_cache_find(FontBLF *font)
61 {
62         KerningCacheBLF *p;
63
64         p = (KerningCacheBLF *)font->kerning_caches.first;
65         while (p) {
66                 if (p->mode == font->kerning_mode)
67                         return p;
68                 p = p->next;
69         }
70         return NULL;
71 }
72
73 /* Create a new glyph cache for the current kerning mode. */
74 KerningCacheBLF *blf_kerning_cache_new(FontBLF *font)
75 {
76         KerningCacheBLF *kc;
77
78         kc = (KerningCacheBLF *)MEM_callocN(sizeof(KerningCacheBLF), "blf_kerning_cache_new");
79         kc->next = NULL;
80         kc->prev = NULL;
81         kc->mode = font->kerning_mode;
82
83         unsigned int i, j;
84         for (i = 0; i < 0x80; i++) {
85                 for (j = 0; j < 0x80; j++) {
86                         GlyphBLF *g = blf_glyph_search(font->glyph_cache, i);
87                         if (!g) {
88                                 FT_UInt glyph_index = FT_Get_Char_Index(font->face, i);
89                                 g = blf_glyph_add(font, glyph_index, i);
90                         }
91                         /* Cannot fail since it has been added just before. */
92                         GlyphBLF *g_prev = blf_glyph_search(font->glyph_cache, j);
93
94                         FT_Vector delta = { .x = 0, .y = 0, };
95                         if (FT_Get_Kerning(font->face, g_prev->idx, g->idx, kc->mode, &delta) == 0) {
96                                 kc->table[i][j] = (int)delta.x >> 6;
97                         }
98                         else {
99                                 kc->table[i][j] = 0;
100                         }
101                 }
102         }
103
104         BLI_addhead(&font->kerning_caches, kc);
105         return kc;
106 }
107
108 void blf_kerning_cache_clear(FontBLF *font)
109 {
110         font->kerning_cache = NULL;
111         BLI_freelistN(&font->kerning_caches);
112 }
113
114 GlyphCacheBLF *blf_glyph_cache_find(FontBLF *font, unsigned int size, unsigned int dpi)
115 {
116         GlyphCacheBLF *p;
117
118         p = (GlyphCacheBLF *)font->cache.first;
119         while (p) {
120                 if (p->size == size && p->dpi == dpi)
121                         return p;
122                 p = p->next;
123         }
124         return NULL;
125 }
126
127 /* Create a new glyph cache for the current size and dpi. */
128 GlyphCacheBLF *blf_glyph_cache_new(FontBLF *font)
129 {
130         GlyphCacheBLF *gc;
131
132         gc = (GlyphCacheBLF *)MEM_callocN(sizeof(GlyphCacheBLF), "blf_glyph_cache_new");
133         gc->next = NULL;
134         gc->prev = NULL;
135         gc->size = font->size;
136         gc->dpi = font->dpi;
137
138         memset(gc->glyph_ascii_table, 0, sizeof(gc->glyph_ascii_table));
139         memset(gc->bucket, 0, sizeof(gc->bucket));
140
141         gc->textures = (GPUTexture **)MEM_callocN(sizeof(GPUTexture *) * 256, __func__);
142         gc->textures_len = 256;
143         gc->texture_current = BLF_TEXTURE_UNSET;
144         gc->offset_x = 3; /* enough padding for blur */
145         gc->offset_y = 3; /* enough padding for blur */
146         gc->pad = 6;
147
148         gc->glyphs_len_max = (int)font->face->num_glyphs;
149         gc->glyphs_len_free = (int)font->face->num_glyphs;
150         gc->ascender = ((float)font->face->size->metrics.ascender) / 64.0f;
151         gc->descender = ((float)font->face->size->metrics.descender) / 64.0f;
152
153         if (FT_IS_SCALABLE(font->face)) {
154                 gc->glyph_width_max = (int)((float)(font->face->bbox.xMax - font->face->bbox.xMin) *
155                                             (((float)font->face->size->metrics.x_ppem) /
156                                              ((float)font->face->units_per_EM)));
157
158                 gc->glyph_height_max = (int)((float)(font->face->bbox.yMax - font->face->bbox.yMin) *
159                                              (((float)font->face->size->metrics.y_ppem) /
160                                               ((float)font->face->units_per_EM)));
161         }
162         else {
163                 gc->glyph_width_max = (int)(((float)font->face->size->metrics.max_advance) / 64.0f);
164                 gc->glyph_height_max = (int)(((float)font->face->size->metrics.height) / 64.0f);
165         }
166
167         /* can happen with size 1 fonts */
168         CLAMP_MIN(gc->glyph_width_max, 1);
169         CLAMP_MIN(gc->glyph_height_max, 1);
170
171         gc->p2_width = 0;
172         gc->p2_height = 0;
173
174         BLI_addhead(&font->cache, gc);
175         return gc;
176 }
177
178 void blf_glyph_cache_clear(FontBLF *font)
179 {
180         GlyphCacheBLF *gc;
181
182         while ((gc = BLI_pophead(&font->cache))) {
183                 blf_glyph_cache_free(gc);
184         }
185         font->glyph_cache = NULL;
186 }
187
188 void blf_glyph_cache_free(GlyphCacheBLF *gc)
189 {
190         GlyphBLF *g;
191         unsigned int i;
192
193         for (i = 0; i < 257; i++) {
194                 while ((g = BLI_pophead(&gc->bucket[i]))) {
195                         blf_glyph_free(g);
196                 }
197         }
198         for (i = 0; i < gc->textures_len; i++) {
199                 if (gc->textures[i]) {
200                         GPU_texture_free(gc->textures[i]);
201                 }
202         }
203         MEM_freeN(gc->textures);
204         MEM_freeN(gc);
205 }
206
207 static void blf_glyph_cache_texture(FontBLF *font, GlyphCacheBLF *gc)
208 {
209         int i;
210         char error[256];
211
212         /* move the index. */
213         gc->texture_current++;
214
215         if (UNLIKELY(gc->texture_current >= gc->textures_len)) {
216                 gc->textures_len *= 2;
217                 gc->textures = MEM_recallocN((void *)gc->textures, sizeof(GPUTexture *) * gc->textures_len);
218         }
219
220         gc->p2_width = (int)blf_next_p2((unsigned int)((gc->glyphs_len_free * gc->glyph_width_max) + (gc->pad * 2)));
221         if (gc->p2_width > font->tex_size_max) {
222                 gc->p2_width = font->tex_size_max;
223         }
224
225         i = (int)((gc->p2_width - (gc->pad * 2)) / gc->glyph_width_max);
226         gc->p2_height = (int)blf_next_p2((unsigned int)(((gc->glyphs_len_max / i) + 1) * gc->glyph_height_max + (gc->pad * 2)));
227
228         if (gc->p2_height > font->tex_size_max) {
229                 gc->p2_height = font->tex_size_max;
230         }
231
232         unsigned char *pixels = MEM_callocN((size_t)gc->p2_width * (size_t)gc->p2_height, "BLF texture init");
233         GPUTexture *tex = GPU_texture_create_nD(gc->p2_width, gc->p2_height, 0, 2, pixels, GPU_R8, GPU_DATA_UNSIGNED_BYTE, 0, false, error);
234         MEM_freeN(pixels);
235         gc->textures[gc->texture_current] = tex;
236         GPU_texture_bind(tex, 0);
237         GPU_texture_wrap_mode(tex, false);
238         GPU_texture_filters(tex, GPU_NEAREST, GPU_LINEAR);
239         GPU_texture_unbind(tex);
240 }
241
242 GlyphBLF *blf_glyph_search(GlyphCacheBLF *gc, unsigned int c)
243 {
244         GlyphBLF *p;
245         unsigned int key;
246
247         key = blf_hash(c);
248         p = gc->bucket[key].first;
249         while (p) {
250                 if (p->c == c)
251                         return p;
252                 p = p->next;
253         }
254         return NULL;
255 }
256
257 GlyphBLF *blf_glyph_add(FontBLF *font, unsigned int index, unsigned int c)
258 {
259         FT_GlyphSlot slot;
260         GlyphBLF *g;
261         FT_Error err;
262         FT_Bitmap bitmap, tempbitmap;
263         FT_BBox bbox;
264         unsigned int key;
265
266         g = blf_glyph_search(font->glyph_cache, c);
267         if (g)
268                 return g;
269
270         /* glyphs are dynamically created as needed by font rendering. this means that
271          * to make font rendering thread safe we have to do locking here. note that this
272          * must be a lock for the whole library and not just per font, because the font
273          * renderer uses a shared buffer internally */
274         BLI_spin_lock(font->ft_lib_mutex);
275
276         /* search again after locking */
277         g = blf_glyph_search(font->glyph_cache, c);
278         if (g) {
279                 BLI_spin_unlock(font->ft_lib_mutex);
280                 return g;
281         }
282
283         if (font->flags & BLF_MONOCHROME) {
284                 err = FT_Load_Glyph(font->face, (FT_UInt)index, FT_LOAD_TARGET_MONO);
285         }
286         else {
287                 int flags = FT_LOAD_NO_BITMAP;
288
289                 if (font->flags & BLF_HINTING_NONE) {
290                         flags |= FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING;
291                 }
292                 else if (font->flags & BLF_HINTING_SLIGHT) {
293                         flags |= FT_LOAD_TARGET_LIGHT;
294                 }
295                 else if (font->flags & BLF_HINTING_FULL) {
296                         flags |= FT_LOAD_TARGET_NORMAL;
297                 }
298                 else {
299                         /* Default, hinting disabled until FreeType has been upgraded
300                          * to give good results on all platforms. */
301                         flags |= FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING;
302                 }
303
304                 err = FT_Load_Glyph(font->face, (FT_UInt)index, flags);
305         }
306
307         if (err) {
308                 BLI_spin_unlock(font->ft_lib_mutex);
309                 return NULL;
310         }
311
312         /* get the glyph. */
313         slot = font->face->glyph;
314
315         if (font->flags & BLF_MONOCHROME) {
316                 err = FT_Render_Glyph(slot, FT_RENDER_MODE_MONO);
317
318                 /* Convert result from 1 bit per pixel to 8 bit per pixel */
319                 /* Accum errors for later, fine if not interested beyond "ok vs any error" */
320                 FT_Bitmap_New(&tempbitmap);
321                 err += FT_Bitmap_Convert(font->ft_lib, &slot->bitmap, &tempbitmap, 1); /* Does Blender use Pitch 1 always? It works so far */
322                 err += FT_Bitmap_Copy(font->ft_lib, &tempbitmap, &slot->bitmap);
323                 err += FT_Bitmap_Done(font->ft_lib, &tempbitmap);
324         }
325         else {
326                 err = FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
327         }
328
329         if (err || slot->format != FT_GLYPH_FORMAT_BITMAP) {
330                 BLI_spin_unlock(font->ft_lib_mutex);
331                 return NULL;
332         }
333
334         g = (GlyphBLF *)MEM_callocN(sizeof(GlyphBLF), "blf_glyph_add");
335         g->c = c;
336         g->idx = (FT_UInt)index;
337         g->offset_x = -1;
338         g->offset_y = -1;
339         bitmap = slot->bitmap;
340         g->width = (int)bitmap.width;
341         g->height = (int)bitmap.rows;
342
343         if (g->width && g->height) {
344                 if (font->flags & BLF_MONOCHROME) {
345                         /* Font buffer uses only 0 or 1 values, Blender expects full 0..255 range */
346                         int i;
347                         for (i = 0; i < (g->width * g->height); i++) {
348                                 bitmap.buffer[i] = bitmap.buffer[i] ? 255 : 0;
349                         }
350                 }
351
352                 g->bitmap = (unsigned char *)MEM_mallocN((size_t)g->width * (size_t)g->height, "glyph bitmap");
353                 memcpy((void *)g->bitmap, (void *)bitmap.buffer, (size_t)g->width * (size_t)g->height);
354         }
355
356         g->advance = ((float)slot->advance.x) / 64.0f;
357         g->advance_i = (int)g->advance;
358         g->pos_x = (float)slot->bitmap_left;
359         g->pos_y = (float)slot->bitmap_top;
360         g->pitch = slot->bitmap.pitch;
361
362         FT_Outline_Get_CBox(&(slot->outline), &bbox);
363         g->box.xmin = ((float)bbox.xMin) / 64.0f;
364         g->box.xmax = ((float)bbox.xMax) / 64.0f;
365         g->box.ymin = ((float)bbox.yMin) / 64.0f;
366         g->box.ymax = ((float)bbox.yMax) / 64.0f;
367
368         key = blf_hash(g->c);
369         BLI_addhead(&(font->glyph_cache->bucket[key]), g);
370
371         BLI_spin_unlock(font->ft_lib_mutex);
372
373         return g;
374 }
375
376 void blf_glyph_free(GlyphBLF *g)
377 {
378         /* don't need free the texture, the GlyphCache already
379          * have a list of all the texture and free it.
380          */
381         if (g->bitmap)
382                 MEM_freeN(g->bitmap);
383         MEM_freeN(g);
384 }
385
386 static void blf_texture_draw(const unsigned char color[4], const float uv[2][2], float x1, float y1, float x2, float y2)
387 {
388         /* Only one vertex per glyph, geometry shader expand it into a quad. */
389         /* TODO Get rid of Geom Shader because it's not optimal AT ALL for the GPU */
390         copy_v4_fl4(GPU_vertbuf_raw_step(&g_batch.pos_step), x1 + g_batch.ofs[0], y1 + g_batch.ofs[1],
391                                                              x2 + g_batch.ofs[0], y2 + g_batch.ofs[1]);
392         copy_v4_v4(GPU_vertbuf_raw_step(&g_batch.tex_step), (float *)uv);
393         copy_v4_v4_uchar(GPU_vertbuf_raw_step(&g_batch.col_step), color);
394         g_batch.glyph_len++;
395         /* Flush cache if it's full. */
396         if (g_batch.glyph_len == BLF_BATCH_DRAW_LEN_MAX) {
397                 blf_batch_draw();
398         }
399 }
400
401 static void blf_texture5_draw(const unsigned char color_in[4], int tex_w, int tex_h, const float uv[2][2],
402                               float x1, float y1, float x2, float y2)
403 {
404         float ofs[2] = { 2 / (float)tex_w, 2 / (float)tex_h };
405         float uv_flag[2][2];
406         copy_v4_v4((float *)uv_flag, (float *)uv);
407         /* flag the x and y component signs for 5x5 blurring */
408         uv_flag[0][0] = -(uv_flag[0][0] - ofs[0]);
409         uv_flag[0][1] = -(uv_flag[0][1] - ofs[1]);
410         uv_flag[1][0] = -(uv_flag[1][0] + ofs[0]);
411         uv_flag[1][1] = -(uv_flag[1][1] + ofs[1]);
412
413         blf_texture_draw(color_in, uv_flag, x1 - 2, y1 + 2, x2 + 2, y2 - 2);
414 }
415
416 static void blf_texture3_draw(const unsigned char color_in[4], int tex_w, int tex_h, const float uv[2][2],
417                               float x1, float y1, float x2, float y2)
418 {
419         float ofs[2] = { 1 / (float)tex_w, 1 / (float)tex_h };
420         float uv_flag[2][2];
421         copy_v4_v4((float *)uv_flag, (float *)uv);
422         /* flag the x component sign for 3x3 blurring */
423         uv_flag[0][0] = -(uv_flag[0][0] - ofs[0]);
424         uv_flag[0][1] =  (uv_flag[0][1] - ofs[1]);
425         uv_flag[1][0] = -(uv_flag[1][0] + ofs[0]);
426         uv_flag[1][1] =  (uv_flag[1][1] + ofs[1]);
427
428         blf_texture_draw(color_in, uv_flag, x1 - 1, y1 + 1, x2 + 1, y2 - 1);
429 }
430
431 static void blf_glyph_calc_rect(rctf *rect, GlyphBLF *g, float x, float y)
432 {
433         rect->xmin = floorf(x + g->pos_x);
434         rect->xmax = rect->xmin + (float)g->width;
435         rect->ymin = floorf(y + g->pos_y);
436         rect->ymax = rect->ymin - (float)g->height;
437 }
438
439 void blf_glyph_render(FontBLF *font, GlyphBLF *g, float x, float y)
440 {
441         rctf rect;
442
443         if ((!g->width) || (!g->height))
444                 return;
445
446         if (g->build_tex == 0) {
447                 GlyphCacheBLF *gc = font->glyph_cache;
448
449                 if (font->tex_size_max == -1)
450                         font->tex_size_max = GPU_max_texture_size();
451
452                 if (gc->texture_current == BLF_TEXTURE_UNSET) {
453                         blf_glyph_cache_texture(font, gc);
454                         gc->offset_x = gc->pad;
455                         gc->offset_y = 3; /* enough padding for blur */
456                 }
457
458                 if (gc->offset_x > (gc->p2_width - gc->glyph_width_max)) {
459                         gc->offset_x = gc->pad;
460                         gc->offset_y += gc->glyph_height_max;
461
462                         if (gc->offset_y > (gc->p2_height - gc->glyph_height_max)) {
463                                 gc->offset_y = 3; /* enough padding for blur */
464                                 blf_glyph_cache_texture(font, gc);
465                         }
466                 }
467
468                 g->tex = gc->textures[gc->texture_current];
469                 g->offset_x = gc->offset_x;
470                 g->offset_y = gc->offset_y;
471
472                 /* prevent glTexSubImage2D from failing if the character
473                  * asks for pixels out of bounds, this tends only to happen
474                  * with very small sizes (5px high or less) */
475                 if (UNLIKELY((g->offset_x + g->width)  > gc->p2_width)) {
476                         g->width  -= (g->offset_x + g->width)  - gc->p2_width;
477                         BLI_assert(g->width > 0);
478                 }
479                 if (UNLIKELY((g->offset_y + g->height) > gc->p2_height)) {
480                         g->height -= (g->offset_y + g->height) - gc->p2_height;
481                         BLI_assert(g->height > 0);
482                 }
483
484                 GPU_texture_update_sub(g->tex, GPU_DATA_UNSIGNED_BYTE, g->bitmap, g->offset_x, g->offset_y, 0, g->width, g->height, 0);
485
486                 g->uv[0][0] = ((float)g->offset_x) / ((float)gc->p2_width);
487                 g->uv[0][1] = ((float)g->offset_y) / ((float)gc->p2_height);
488                 g->uv[1][0] = ((float)(g->offset_x + g->width)) / ((float)gc->p2_width);
489                 g->uv[1][1] = ((float)(g->offset_y + g->height)) / ((float)gc->p2_height);
490
491                 /* update the x offset for the next glyph. */
492                 gc->offset_x += (int)BLI_rctf_size_x(&g->box) + gc->pad;
493
494                 gc->glyphs_len_free--;
495                 g->build_tex = 1;
496         }
497
498         blf_glyph_calc_rect(&rect, g, x, y);
499
500         if (font->flags & BLF_CLIPPING) {
501                 /* intentionally check clipping without shadow offset */
502                 rctf rect_test = rect;
503                 BLI_rctf_translate(&rect_test, font->pos[0], font->pos[1]);
504
505                 if (!BLI_rctf_inside_rctf(&font->clip_rec, &rect_test)) {
506                         return;
507                 }
508         }
509
510         if (font->tex_bind_state != g->tex) {
511                 blf_batch_draw();
512                 font->tex_bind_state = g->tex;
513                 GPU_texture_bind(font->tex_bind_state, 0);
514         }
515
516         g_batch.tex_bind_state = g->tex;
517
518         if (font->flags & BLF_SHADOW) {
519                 rctf rect_ofs;
520                 blf_glyph_calc_rect(&rect_ofs, g,
521                                     x + (float)font->shadow_x,
522                                     y + (float)font->shadow_y);
523
524                 if (font->shadow == 0) {
525                         blf_texture_draw(font->shadow_color, g->uv, rect_ofs.xmin, rect_ofs.ymin, rect_ofs.xmax, rect_ofs.ymax);
526                 }
527                 else if (font->shadow <= 4) {
528                         blf_texture3_draw(font->shadow_color, font->glyph_cache->p2_width, font->glyph_cache->p2_height, g->uv,
529                                           rect_ofs.xmin, rect_ofs.ymin, rect_ofs.xmax, rect_ofs.ymax);
530                 }
531                 else {
532                         blf_texture5_draw(font->shadow_color, font->glyph_cache->p2_width, font->glyph_cache->p2_height, g->uv,
533                                           rect_ofs.xmin, rect_ofs.ymin, rect_ofs.xmax, rect_ofs.ymax);
534                 }
535         }
536
537 #if BLF_BLUR_ENABLE
538         switch (font->blur) {
539                 case 3:
540                         blf_texture3_draw(font->color, font->glyph_cache->p2_width, font->glyph_cache->p2_height, g->uv,
541                                           rect.xmin, rect.ymin, rect.xmax, rect.ymax);
542                         break;
543                 case 5:
544                         blf_texture5_draw(font->color, font->glyph_cache->p2_width, font->glyph_cache->p2_height, g->uv,
545                                           rect.xmin, rect.ymin, rect.xmax, rect.ymax);
546                         break;
547                 default:
548                         blf_texture_draw(font->color, g->uv, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
549         }
550 #else
551         blf_texture_draw(font->color, g->uv, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
552 #endif
553 }