code cleanup: favor braces when blocks have mixed brace use.
[blender.git] / source / blender / blenlib / intern / freetypefont.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is written by Rob Haarsma (phase)
19  * All rights reserved.
20  *
21  * Contributor(s): none yet.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  *
25  * This code parses the Freetype font outline data to chains of Blender's beziertriples.
26  * Additional information can be found at the bottom of this file.
27  *
28  * Code that uses exotic character maps is present but commented out.
29  */
30
31 /** \file blender/blenlib/intern/freetypefont.c
32  *  \ingroup bli
33  */
34
35
36 #ifdef _MSC_VER
37 #  pragma warning (disable:4244)
38 #endif
39
40 #include <ft2build.h>
41 #include FT_FREETYPE_H
42 /* not needed yet */
43 // #include FT_GLYPH_H
44 // #include FT_BBOX_H
45 // #include FT_SIZES_H
46 // #include <freetype/ttnameid.h>
47
48 #include "MEM_guardedalloc.h"
49
50 #include "BLI_vfontdata.h"
51 #include "BLI_blenlib.h"
52 #include "BLI_math.h"
53 #include "BLI_utildefines.h"
54
55 #include "DNA_vfont_types.h"
56 #include "DNA_packedFile_types.h"
57 #include "DNA_curve_types.h"
58
59 /* local variables */
60 static FT_Library library;
61 static FT_Error err;
62
63
64 static void freetypechar_to_vchar(FT_Face face, FT_ULong charcode, VFontData *vfd)
65 {
66         /* Blender */
67         struct Nurb *nu;
68         struct VChar *che;
69         struct BezTriple *bezt;
70
71         /* Freetype2 */
72         FT_GlyphSlot glyph;
73         FT_UInt glyph_index;
74         FT_Outline ftoutline;
75         float scale, height;
76         float dx, dy;
77         int j, k, l, m = 0;
78
79         /* adjust font size */
80         height = ((double) face->bbox.yMax - (double) face->bbox.yMin);
81         if (height != 0.0f)
82                 scale = 1.0f / height;
83         else
84                 scale = 1.0f / 1000.0f;
85
86         /*
87          * Generate the character 3D data
88          *
89          * Get the FT Glyph index and load the Glyph */
90         glyph_index = FT_Get_Char_Index(face, charcode);
91         err = FT_Load_Glyph(face, glyph_index, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP);
92
93         /* If loading succeeded, convert the FT glyph to the internal format */
94         if (!err) {
95                 int *npoints;
96                 int *onpoints;
97
98                 /* First we create entry for the new character to the character list */
99                 che = (VChar *) MEM_callocN(sizeof(struct VChar), "objfnt_char");
100                 BLI_addtail(&vfd->characters, che);
101
102                 /* Take some data for modifying purposes */
103                 glyph = face->glyph;
104                 ftoutline = glyph->outline;
105
106                 /* Set the width and character code */
107                 che->index = charcode;
108                 che->width = glyph->advance.x * scale;
109
110                 /* Start converting the FT data */
111                 npoints = (int *)MEM_callocN((ftoutline.n_contours) * sizeof(int), "endpoints");
112                 onpoints = (int *)MEM_callocN((ftoutline.n_contours) * sizeof(int), "onpoints");
113
114                 /* calculate total points of each contour */
115                 for (j = 0; j < ftoutline.n_contours; j++) {
116                         if (j == 0)
117                                 npoints[j] = ftoutline.contours[j] + 1;
118                         else
119                                 npoints[j] = ftoutline.contours[j] - ftoutline.contours[j - 1];
120                 }
121
122                 /* get number of on-curve points for beziertriples (including conic virtual on-points) */
123                 for (j = 0; j < ftoutline.n_contours; j++) {
124                         for (k = 0; k < npoints[j]; k++) {
125                                 l = (j > 0) ? (k + ftoutline.contours[j - 1] + 1) : k;
126
127                                 if (ftoutline.tags[l] == FT_Curve_Tag_On)
128                                         onpoints[j]++;
129
130                                 if (k < npoints[j] - 1) {
131                                         if (ftoutline.tags[l] == FT_Curve_Tag_Conic &&
132                                             ftoutline.tags[l + 1] == FT_Curve_Tag_Conic)
133                                         {
134                                                 onpoints[j]++;
135                                         }
136                                 }
137                         }
138                 }
139
140                 /* contour loop, bezier & conic styles merged */
141                 for (j = 0; j < ftoutline.n_contours; j++) {
142                         /* add new curve */
143                         nu  =  (Nurb *)MEM_callocN(sizeof(struct Nurb), "objfnt_nurb");
144                         bezt = (BezTriple *)MEM_callocN((onpoints[j]) * sizeof(BezTriple), "objfnt_bezt");
145                         BLI_addtail(&che->nurbsbase, nu);
146
147                         nu->type = CU_BEZIER;
148                         nu->pntsu = onpoints[j];
149                         nu->resolu = 8;
150                         nu->flag = CU_2D;
151                         nu->flagu = CU_NURB_CYCLIC;
152                         nu->bezt = bezt;
153
154                         /* individual curve loop, start-end */
155                         for (k = 0; k < npoints[j]; k++) {
156                                 if (j > 0) l = k + ftoutline.contours[j - 1] + 1; else l = k;
157                                 if (k == 0) m = l;
158
159                                 /* virtual conic on-curve points */
160                                 if (k < npoints[j] - 1) {
161                                         if (ftoutline.tags[l] == FT_Curve_Tag_Conic && ftoutline.tags[l + 1] == FT_Curve_Tag_Conic) {
162                                                 dx = (ftoutline.points[l].x + ftoutline.points[l + 1].x) * scale / 2.0f;
163                                                 dy = (ftoutline.points[l].y + ftoutline.points[l + 1].y) * scale / 2.0f;
164
165                                                 /* left handle */
166                                                 bezt->vec[0][0] = (dx + (2 * ftoutline.points[l].x) * scale) / 3.0f;
167                                                 bezt->vec[0][1] = (dy + (2 * ftoutline.points[l].y) * scale) / 3.0f;
168
169                                                 /* midpoint (virtual on-curve point) */
170                                                 bezt->vec[1][0] = dx;
171                                                 bezt->vec[1][1] = dy;
172
173                                                 /* right handle */
174                                                 bezt->vec[2][0] = (dx + (2 * ftoutline.points[l + 1].x) * scale) / 3.0f;
175                                                 bezt->vec[2][1] = (dy + (2 * ftoutline.points[l + 1].y) * scale) / 3.0f;
176
177                                                 bezt->h1 = bezt->h2 = HD_ALIGN;
178                                                 bezt->radius = 1.0f;
179                                                 bezt++;
180                                         }
181                                 }
182
183                                 /* on-curve points */
184                                 if (ftoutline.tags[l] == FT_Curve_Tag_On) {
185                                         /* left handle */
186                                         if (k > 0) {
187                                                 if (ftoutline.tags[l - 1] == FT_Curve_Tag_Cubic) {
188                                                         bezt->vec[0][0] = ftoutline.points[l - 1].x * scale;
189                                                         bezt->vec[0][1] = ftoutline.points[l - 1].y * scale;
190                                                         bezt->h1 = HD_FREE;
191                                                 }
192                                                 else if (ftoutline.tags[l - 1] == FT_Curve_Tag_Conic) {
193                                                         bezt->vec[0][0] = (ftoutline.points[l].x + (2 * ftoutline.points[l - 1].x)) * scale / 3.0f;
194                                                         bezt->vec[0][1] = (ftoutline.points[l].y + (2 * ftoutline.points[l - 1].y)) * scale / 3.0f;
195                                                         bezt->h1 = HD_FREE;
196                                                 }
197                                                 else {
198                                                         bezt->vec[0][0] = ftoutline.points[l].x * scale - (ftoutline.points[l].x - ftoutline.points[l - 1].x) * scale / 3.0f;
199                                                         bezt->vec[0][1] = ftoutline.points[l].y * scale - (ftoutline.points[l].y - ftoutline.points[l - 1].y) * scale / 3.0f;
200                                                         bezt->h1 = HD_VECT;
201                                                 }
202                                         }
203                                         else { /* first point on curve */
204                                                 if (ftoutline.tags[ftoutline.contours[j]] == FT_Curve_Tag_Cubic) {
205                                                         bezt->vec[0][0] = ftoutline.points[ftoutline.contours[j]].x * scale;
206                                                         bezt->vec[0][1] = ftoutline.points[ftoutline.contours[j]].y * scale;
207                                                         bezt->h1 = HD_FREE;
208                                                 }
209                                                 else if (ftoutline.tags[ftoutline.contours[j]] == FT_Curve_Tag_Conic) {
210                                                         bezt->vec[0][0] = (ftoutline.points[l].x + (2 * ftoutline.points[ftoutline.contours[j]].x)) * scale / 3.0f;
211                                                         bezt->vec[0][1] = (ftoutline.points[l].y + (2 * ftoutline.points[ftoutline.contours[j]].y)) * scale / 3.0f;
212                                                         bezt->h1 = HD_FREE;
213                                                 }
214                                                 else {
215                                                         bezt->vec[0][0] = ftoutline.points[l].x * scale - (ftoutline.points[l].x - ftoutline.points[ftoutline.contours[j]].x) * scale / 3.0f;
216                                                         bezt->vec[0][1] = ftoutline.points[l].y * scale - (ftoutline.points[l].y - ftoutline.points[ftoutline.contours[j]].y) * scale / 3.0f;
217                                                         bezt->h1 = HD_VECT;
218                                                 }
219                                         }
220
221                                         /* midpoint (on-curve point) */
222                                         bezt->vec[1][0] = ftoutline.points[l].x * scale;
223                                         bezt->vec[1][1] = ftoutline.points[l].y * scale;
224
225                                         /* right handle */
226                                         if (k < (npoints[j] - 1)) {
227                                                 if (ftoutline.tags[l + 1] == FT_Curve_Tag_Cubic) {
228                                                         bezt->vec[2][0] = ftoutline.points[l + 1].x * scale;
229                                                         bezt->vec[2][1] = ftoutline.points[l + 1].y * scale;
230                                                         bezt->h2 = HD_FREE;
231                                                 }
232                                                 else if (ftoutline.tags[l + 1] == FT_Curve_Tag_Conic) {
233                                                         bezt->vec[2][0] = (ftoutline.points[l].x + (2 * ftoutline.points[l + 1].x)) * scale / 3.0f;
234                                                         bezt->vec[2][1] = (ftoutline.points[l].y + (2 * ftoutline.points[l + 1].y)) * scale / 3.0f;
235                                                         bezt->h2 = HD_FREE;
236                                                 }
237                                                 else {
238                                                         bezt->vec[2][0] = ftoutline.points[l].x * scale - (ftoutline.points[l].x - ftoutline.points[l + 1].x) * scale / 3.0f;
239                                                         bezt->vec[2][1] = ftoutline.points[l].y * scale - (ftoutline.points[l].y - ftoutline.points[l + 1].y) * scale / 3.0f;
240                                                         bezt->h2 = HD_VECT;
241                                                 }
242                                         }
243                                         else { /* last point on curve */
244                                                 if (ftoutline.tags[m] == FT_Curve_Tag_Cubic) {
245                                                         bezt->vec[2][0] = ftoutline.points[m].x * scale;
246                                                         bezt->vec[2][1] = ftoutline.points[m].y * scale;
247                                                         bezt->h2 = HD_FREE;
248                                                 }
249                                                 else if (ftoutline.tags[m] == FT_Curve_Tag_Conic) {
250                                                         bezt->vec[2][0] = (ftoutline.points[l].x + (2 * ftoutline.points[m].x)) * scale / 3.0f;
251                                                         bezt->vec[2][1] = (ftoutline.points[l].y + (2 * ftoutline.points[m].y)) * scale / 3.0f;
252                                                         bezt->h2 = HD_FREE;
253                                                 }
254                                                 else {
255                                                         bezt->vec[2][0] = ftoutline.points[l].x * scale - (ftoutline.points[l].x - ftoutline.points[m].x) * scale / 3.0f;
256                                                         bezt->vec[2][1] = ftoutline.points[l].y * scale - (ftoutline.points[l].y - ftoutline.points[m].y) * scale / 3.0f;
257                                                         bezt->h2 = HD_VECT;
258                                                 }
259                                         }
260
261                                         /* get the handles that are aligned, tricky...
262                                          * dist_to_line_v2, check if the three beztriple points are on one line
263                                          * len_squared_v2v2, see if there's a distance between the three points
264                                          * len_squared_v2v2 again, to check the angle between the handles
265                                          * finally, check if one of them is a vector handle */
266                                         if ((bezt->h1 != HD_VECT && bezt->h2 != HD_VECT) &&
267                                             (dist_to_line_v2(bezt->vec[0], bezt->vec[1], bezt->vec[2]) < 0.001f) &&
268                                             (len_squared_v2v2(bezt->vec[0], bezt->vec[1]) > 0.0001f * 0.0001f) &&
269                                             (len_squared_v2v2(bezt->vec[1], bezt->vec[2]) > 0.0001f * 0.0001f) &&
270                                             (len_squared_v2v2(bezt->vec[0], bezt->vec[2]) > 0.0002f * 0.0001f) &&
271                                             (len_squared_v2v2(bezt->vec[0], bezt->vec[2]) >
272                                              max_ff(len_squared_v2v2(bezt->vec[0], bezt->vec[1]),
273                                                   len_squared_v2v2(bezt->vec[1], bezt->vec[2]))))
274                                         {
275                                                 bezt->h1 = bezt->h2 = HD_ALIGN;
276                                         }
277                                         bezt->radius = 1.0f;
278                                         bezt++;
279                                 }
280                         }
281                 }
282                 if (npoints) MEM_freeN(npoints);
283                 if (onpoints) MEM_freeN(onpoints);
284         }
285 }
286
287 static int objchr_to_ftvfontdata(VFont *vfont, FT_ULong charcode)
288 {
289         /* Freetype2 */
290         FT_Face face;
291
292         /* Load the font to memory */
293         if (vfont->temp_pf) {
294                 err = FT_New_Memory_Face(library,
295                                          vfont->temp_pf->data,
296                                          vfont->temp_pf->size,
297                                          0,
298                                          &face);
299                 if (err) return FALSE;
300         }
301         else {
302                 err = TRUE;
303                 return FALSE;
304         }
305                 
306         /* Read the char */
307         freetypechar_to_vchar(face, charcode, vfont->data);
308         
309         /* And everything went ok */
310         return TRUE;
311 }
312
313
314 static VFontData *objfnt_to_ftvfontdata(PackedFile *pf)
315 {
316         /* Variables */
317         FT_Face face;
318         FT_ULong charcode = 0, lcode;
319         FT_UInt glyph_index;
320         const char *fontname;
321         VFontData *vfd;
322
323 #if 0
324         FT_CharMap found = 0;
325         FT_CharMap charmap;
326         FT_UShort my_platform_id = TT_PLATFORM_MICROSOFT;
327         FT_UShort my_encoding_id = TT_MS_ID_UNICODE_CS;
328         int n;
329 #endif
330
331         /* load the freetype font */
332         err = FT_New_Memory_Face(library,
333                                  pf->data,
334                                  pf->size,
335                                  0,
336                                  &face);
337
338         if (err) return NULL;
339
340 #if 0
341         for (n = 0; n < face->num_charmaps; n++)
342         {
343                 charmap = face->charmaps[n];
344                 if (charmap->platform_id == my_platform_id &&
345                     charmap->encoding_id == my_encoding_id)
346                 {
347                         found = charmap;
348                         break;
349                 }
350         }
351
352         if (!found) { return NULL; }
353
354         /* now, select the charmap for the face object */
355         err = FT_Set_Charmap(face, found);
356         if (err) { return NULL; }
357 #endif
358
359         /* allocate blender font */
360         vfd = MEM_callocN(sizeof(*vfd), "FTVFontData");
361
362         /* get the name */
363         fontname = FT_Get_Postscript_Name(face);
364         BLI_strncpy(vfd->name, (fontname == NULL) ? "" : fontname, sizeof(vfd->name));
365
366         /* Extract the first 256 character from TTF */
367         lcode = charcode = FT_Get_First_Char(face, &glyph_index);
368
369         /* No charmap found from the ttf so we need to figure it out */
370         if (glyph_index == 0) {
371                 FT_CharMap found = NULL;
372                 FT_CharMap charmap;
373                 int n;
374
375                 for (n = 0; n < face->num_charmaps; n++) {
376                         charmap = face->charmaps[n];
377                         if (charmap->encoding == FT_ENCODING_APPLE_ROMAN) {
378                                 found = charmap;
379                                 break;
380                         }
381                 }
382
383                 err = FT_Set_Charmap(face, found);
384
385                 if (err)
386                         return NULL;
387
388                 lcode = charcode = FT_Get_First_Char(face, &glyph_index);
389         }
390
391         /* Load characters */
392         while (charcode < 256) {
393                 /* Generate the font data */
394                 freetypechar_to_vchar(face, charcode, vfd);
395
396                 /* Next glyph */
397                 charcode = FT_Get_Next_Char(face, charcode, &glyph_index);
398
399                 /* Check that we won't start infinite loop */
400                 if (charcode <= lcode)
401                         break;
402                 lcode = charcode;
403         }
404
405         return vfd;
406 }
407
408
409 static int check_freetypefont(PackedFile *pf)
410 {
411         FT_Face face;
412         FT_GlyphSlot glyph;
413         FT_UInt glyph_index;
414 #if 0
415         FT_CharMap charmap;
416         FT_CharMap found;
417         FT_UShort my_platform_id = TT_PLATFORM_MICROSOFT;
418         FT_UShort my_encoding_id = TT_MS_ID_UNICODE_CS;
419         int n;
420 #endif
421         int success = 0;
422
423         err = FT_New_Memory_Face(library,
424                                  pf->data,
425                                  pf->size,
426                                  0,
427                                  &face);
428         if (err) {
429                 success = 0;
430                 //XXX error("This is not a valid font");
431         }
432         else {
433
434 #if 0
435                 for (n = 0; n < face->num_charmaps; n++) {
436                         charmap = face->charmaps[n];
437                         if (charmap->platform_id == my_platform_id && charmap->encoding_id == my_encoding_id) {
438                                 found = charmap;
439                                 break;
440                         }
441                 }
442
443                 if (!found) { return 0; }
444
445                 /* now, select the charmap for the face object */
446                 err = FT_Set_Charmap(face, found);
447                 if (err) { return 0; }
448 #endif
449
450                 glyph_index = FT_Get_Char_Index(face, 'A');
451                 err = FT_Load_Glyph(face, glyph_index, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP);
452                 if (err) {
453                         success = 0;
454                 }
455                 else {
456                         glyph = face->glyph;
457                         if (glyph->format == ft_glyph_format_outline) {
458                                 success = 1;
459                         }
460                         else {
461                                 //XXX error("Selected Font has no outline data");
462                                 success = 0;
463                         }
464                 }
465         }
466         
467         return success;
468 }
469
470
471 VFontData *BLI_vfontdata_from_freetypefont(PackedFile *pf)
472 {
473         VFontData *vfd = NULL;
474         int success = 0;
475
476         /* init Freetype */
477         err = FT_Init_FreeType(&library);
478         if (err) {
479                 /* XXX error("Failed to load the Freetype font library"); */
480                 return NULL;
481         }
482
483         success = check_freetypefont(pf);
484         
485         if (success) {
486                 vfd = objfnt_to_ftvfontdata(pf);
487         }
488
489         /* free Freetype */
490         FT_Done_FreeType(library);
491         
492         return vfd;
493 }
494
495 int BLI_vfontchar_from_freetypefont(VFont *vfont, unsigned long character)
496 {
497         int success = FALSE;
498
499         if (!vfont) return FALSE;
500
501         /* Init Freetype */
502         err = FT_Init_FreeType(&library);
503         if (err) {
504                 /* XXX error("Failed to load the Freetype font library"); */
505                 return 0;
506         }
507
508         /* Load the character */
509         success = objchr_to_ftvfontdata(vfont, character);
510         if (success == FALSE) return FALSE;
511
512         /* Free Freetype */
513         FT_Done_FreeType(library);
514
515         /* Ahh everything ok */
516         return TRUE;
517 }
518
519 #if 0
520
521 /* Freetype2 Outline struct */
522
523 typedef struct  FT_Outline_
524 {
525         short       n_contours;      /* number of contours in glyph        */
526         short       n_points;        /* number of points in the glyph      */
527
528         FT_Vector  *points;          /* the outline's points               */
529         char       *tags;            /* the points flags                   */
530         short      *contours;        /* the contour end points             */
531
532         int         flags;           /* outline masks                      */
533 } FT_Outline;
534
535 #endif
536
537 /*
538  * from: http://www.freetype.org/freetype2/docs/glyphs/glyphs-6.html#section-1
539  *
540  * Vectorial representation of Freetype glyphs
541  *
542  * The source format of outlines is a collection of closed paths called "contours". Each contour is
543  * made of a series of line segments and bezier arcs. Depending on the file format, these can be
544  * second-order or third-order polynomials. The former are also called quadratic or conic arcs, and
545  * they come from the TrueType format. The latter are called cubic arcs and mostly come from the
546  * Type1 format.
547  *
548  * Each arc is described through a series of start, end and control points. Each point of the outline
549  * has a specific tag which indicates whether it is used to describe a line segment or an arc.
550  *
551  *
552  * The following rules are applied to decompose the contour's points into segments and arcs :
553  *
554  * # two successive "on" points indicate a line segment joining them.
555  *
556  * # one conic "off" point amidst two "on" points indicates a conic bezier arc, the "off" point being
557  *   the control point, and the "on" ones the start and end points.
558  *
559  * # Two successive cubic "off" points amidst two "on" points indicate a cubic bezier arc. There must
560  *   be exactly two cubic control points and two on points for each cubic arc (using a single cubic
561  *   "off" point between two "on" points is forbidden, for example).
562  *
563  * # finally, two successive conic "off" points forces the rasterizer to create (during the scan-line
564  *   conversion process exclusively) a virtual "on" point amidst them, at their exact middle. This
565  *   greatly facilitates the definition of successive conic bezier arcs. Moreover, it's the way
566  *   outlines are described in the TrueType specification.
567  *
568  * Note that it is possible to mix conic and cubic arcs in a single contour, even though no current
569  * font driver produces such outlines.
570  *
571  *                                   *            # on
572  *                                                * off
573  *                                __---__
574  *   #-__                      _--       -_
575  *       --__                _-            -
576  *           --__           #               \
577  *               --__                        #
578  *                   -#
579  *                            Two "on" points
580  *    Two "on" points       and one "conic" point
581  *                             between them
582  *
583  *
584  *
585  *                 *
586  *   #            __      Two "on" points with two "conic"
587  *    \          -  -     points between them. The point
588  *     \        /    \    marked '0' is the middle of the
589  *      -      0      \   "off" points, and is a 'virtual'
590  *       -_  _-       #   "on" point where the curve passes.
591  *         --             It does not appear in the point
592  *                        list.
593  *         *
594  *
595  *
596  *
597  *
598  *         *                # on
599  *                    *     * off
600  *          __---__
601  *       _--       -_
602  *     _-            -
603  *    #               \
604  *                     #
605  *
606  *      Two "on" points
607  *    and two "cubic" point
608  *       between them
609  *
610  *
611  * Each glyph's original outline points are located on a grid of indivisible units. The points are stored
612  * in the font file as 16-bit integer grid coordinates, with the grid origin's being at (0, 0); they thus
613  * range from -16384 to 16383.
614  *
615  * Convert conic to bezier arcs:
616  * Conic P0 P1 P2
617  * Bezier B0 B1 B2 B3
618  * B0=P0
619  * B1=(P0+2*P1)/3
620  * B2=(P2+2*P1)/3
621  * B3=P2
622  *
623  */