1 // stb_truetype.h - v0.8 - public domain
2 // authored from 2009-2013 by Sean Barrett / RAD Game Tools
4 // This library processes TrueType files:
6 // extract glyph metrics
7 // extract glyph shapes
8 // render glyphs to one-channel bitmaps with antialiasing (box filter)
12 // crashproof on bad data
13 // hinting? (no longer patented)
14 // cleartype-style AA?
15 // optimize: use simple memory allocator for intermediates
16 // optimize: build edge-list directly from curves
17 // optimize: rasterize directly from curves?
19 // ADDITIONAL CONTRIBUTORS
21 // Mikko Mononen: compound shape support, more cmap formats
22 // Tor Andersson: kerning, subpixel rendering
24 // Bug/warning reports:
25 // "Zer" on mollyrocket (with fix)
27 // stoiko (Haemimont Games)
37 // 0.8 (2014-05-25) fix a few more warnings
38 // 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
39 // 0.6c (2012-07-24) improve documentation
40 // 0.6b (2012-07-20) fix a few more warnings
41 // 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
42 // stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
43 // 0.5 (2011-12-09) bugfixes:
44 // subpixel glyph renderer computed wrong bounding box
45 // first vertex of shape can be off-curve (FreeSans)
46 // 0.4b (2011-12-03) fixed an error in the font baking example
47 // 0.4 (2011-12-01) kerning, subpixel rendering (tor)
49 // codepoint-to-glyph conversion using table fmt=12
50 // codepoint-to-glyph conversion using table fmt=4
51 // stbtt_GetBakedQuad with non-square texture (Zer)
52 // updated Hello World! sample to use kerning and subpixel
53 // fixed some warnings
54 // 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)
55 // userdata, malloc-from-userdata, non-zero fill (STB)
56 // 0.2 (2009-03-11) Fix unsigned/signed char warnings
57 // 0.1 (2009-03-09) First public release
61 // This software is in the public domain. Where that dedication is not
62 // recognized, you are granted a perpetual, irrevokable license to copy
63 // and modify this file as you see fit.
67 // Include this file in whatever places neeed to refer to it. In ONE C/C++
69 // #define STB_TRUETYPE_IMPLEMENTATION
70 // before the #include of this file. This expands out the actual
71 // implementation into that C/C++ file.
73 // Simple 3D API (don't ship this, but it's fine for tools and quick start,
74 // and you can cut and paste from it to move to more advanced)
75 // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture
76 // stbtt_GetBakedQuad() -- compute quad to draw for a given char
78 // "Load" a font file from a memory buffer (you have to keep the buffer loaded)
80 // stbtt_GetFontOffsetForIndex() -- use for TTC font collections
82 // Render a unicode codepoint to a bitmap
83 // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
84 // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide
85 // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
87 // Character advance/positioning
88 // stbtt_GetCodepointHMetrics()
89 // stbtt_GetFontVMetrics()
90 // stbtt_GetCodepointKernAdvance()
92 // ADDITIONAL DOCUMENTATION
94 // Immediately after this block comment are a series of sample programs.
96 // After the sample programs is the "header file" section. This section
97 // includes documentation for each API function.
99 // Some important concepts to understand to use this library:
102 // Characters are defined by unicode codepoints, e.g. 65 is
103 // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
104 // the hiragana for "ma".
107 // A visual character shape (every codepoint is rendered as
111 // A font-specific integer ID representing a glyph
114 // Glyph shapes are defined relative to a baseline, which is the
115 // bottom of uppercase characters. Characters extend both above
116 // and below the baseline.
119 // As you draw text to the screen, you keep track of a "current point"
120 // which is the origin of each character. The current point's vertical
121 // position is the baseline. Even "baked fonts" use this model.
123 // Vertical Font Metrics
124 // The vertical qualities of the font, used to vertically position
125 // and space the characters. See docs for stbtt_GetFontVMetrics.
127 // Font Size in Pixels or Points
128 // The preferred interface for specifying font sizes in stb_truetype
129 // is to specify how tall the font's vertical extent should be in pixels.
130 // If that sounds good enough, skip the next paragraph.
132 // Most font APIs instead use "points", which are a common typographic
133 // measurement for describing font size, defined as 72 points per inch.
134 // stb_truetype provides a point API for compatibility. However, true
135 // "per inch" conventions don't make much sense on computer displays
136 // since they different monitors have different number of pixels per
137 // inch. For example, Windows traditionally uses a convention that
138 // there are 96 pixels per inch, thus making 'inch' measurements have
139 // nothing to do with inches, and thus effectively defining a point to
140 // be 1.333 pixels. Additionally, the TrueType font data provides
141 // an explicit scale factor to scale a given font's glyphs to points,
142 // but the author has observed that this scale factor is often wrong
143 // for non-commercial fonts, thus making fonts scaled in points
144 // according to the TrueType spec incoherently sized in practice.
150 // - Use the functions with Subpixel at the end to allow your characters
151 // to have subpixel positioning. Since the font is anti-aliased, not
152 // hinted, this is very import for quality. (This is not possible with
155 // - Kerning is now supported, and if you're supporting subpixel rendering
156 // then kerning is worth using to give your text a polished look.
160 // - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
161 // if you don't do this, stb_truetype is forced to do the conversion on
164 // - There are a lot of memory allocations. We should modify it to take
165 // a temp buffer and allocate from the temp buffer (without freeing),
166 // should help performance a lot.
170 // The system uses the raw data found in the .ttf file without changing it
171 // and without building auxiliary data structures. This is a bit inefficient
172 // on little-endian systems (the data is big-endian), but assuming you're
173 // caching the bitmaps or glyph shapes this shouldn't be a big deal.
175 // It appears to be very hard to programmatically determine what font a
176 // given file is in a general way. I provide an API for this, but I don't
180 // SOURCE STATISTICS (based on v0.6c, 2050 LOC)
182 // Documentation & header file 520 LOC \___ 660 LOC documentation
183 // Sample code 140 LOC /
184 // Truetype parsing 620 LOC ---- 620 LOC TrueType
185 // Software rasterization 240 LOC \ .
186 // Curve tesselation 120 LOC \__ 550 LOC Bitmap creation
187 // Bitmap management 100 LOC /
188 // Baked bitmap interface 70 LOC /
189 // Font name matching & access 150 LOC ---- 150
190 // C runtime library abstraction 60 LOC ---- 60
193 //////////////////////////////////////////////////////////////////////////////
194 //////////////////////////////////////////////////////////////////////////////
199 // Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
202 #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
203 #include "stb_truetype.h"
205 char ttf_buffer[1<<20];
206 unsigned char temp_bitmap[512*512];
208 stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
211 void my_stbtt_initfont(void)
213 fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
214 stbtt_BakeFontBitmap(data,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
215 // can free ttf_buffer at this point
216 glGenTextures(1, &ftex);
217 glBindTexture(GL_TEXTURE_2D, ftex);
218 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
219 // can free temp_bitmap at this point
220 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
223 void my_stbtt_print(float x, float y, char *text)
225 // assume orthographic projection with units = screen pixels, origin at top left
226 glBindTexture(GL_TEXTURE_2D, ftex);
229 if (*text >= 32 && *text < 128) {
230 stbtt_aligned_quad q;
231 stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
232 glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
233 glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
234 glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
235 glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
244 //////////////////////////////////////////////////////////////////////////////
246 // Complete program (this compiles): get a single bitmap, print as ASCII art
250 #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
251 #include "stb_truetype.h"
253 char ttf_buffer[1<<25];
255 int main(int argc, char **argv)
258 unsigned char *bitmap;
259 int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
261 fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
263 stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
264 bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
266 for (j=0; j < h; ++j) {
267 for (i=0; i < w; ++i)
268 putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
288 //////////////////////////////////////////////////////////////////////////////
290 // Complete program: print "Hello World!" banner, with bugs
294 unsigned char screen[20][79];
296 int main(int arg, char **argv)
299 int i,j,ascent,baseline,ch=0;
300 float scale, xpos=2; // leave a little padding in case the character extends left
301 char *text = "Heljo World!";
303 fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
304 stbtt_InitFont(&font, buffer, 0);
306 scale = stbtt_ScaleForPixelHeight(&font, 15);
307 stbtt_GetFontVMetrics(&font, &ascent,0,0);
308 baseline = (int) (ascent*scale);
311 int advance,lsb,x0,y0,x1,y1;
312 float x_shift = xpos - (float) floor(xpos);
313 stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
314 stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
315 stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
316 // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
317 // because this API is really for baking character bitmaps into textures. if you want to render
318 // a sequence of characters, you really need to render each bitmap to a temp buffer, then
319 // "alpha blend" that into the working buffer
320 xpos += (advance * scale);
322 xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
326 for (j=0; j < 20; ++j) {
327 for (i=0; i < 78; ++i)
328 putchar(" .:ioVM@"[screen[j][i]>>5]);
337 //////////////////////////////////////////////////////////////////////////////
338 //////////////////////////////////////////////////////////////////////////////
340 //// INTEGRATION WITH YOUR CODEBASE
342 //// The following sections allow you to supply alternate definitions
343 //// of C library functions used by stb_truetype.
345 #ifdef STB_TRUETYPE_IMPLEMENTATION
346 // #define your own (u)stbtt_int8/16/32 before including to override this
348 typedef unsigned char stbtt_uint8;
349 typedef signed char stbtt_int8;
350 typedef unsigned short stbtt_uint16;
351 typedef signed short stbtt_int16;
352 typedef unsigned int stbtt_uint32;
353 typedef signed int stbtt_int32;
356 typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
357 typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
359 // #define your own STBTT_sort() to override this to avoid qsort
362 #define STBTT_sort(data,num_items,item_size,compare_func) qsort(data,num_items,item_size,compare_func)
365 // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
368 #define STBTT_ifloor(x) ((int) floor(x))
369 #define STBTT_iceil(x) ((int) ceil(x))
374 #define STBTT_sqrt(x) sqrt(x)
377 // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
380 #define STBTT_malloc(x,u) ((void)(u),malloc(x))
381 #define STBTT_free(x,u) free(x)
386 #define STBTT_assert(x) assert(x)
391 #define STBTT_strlen(x) strlen(x)
396 #define STBTT_memcpy memcpy
397 #define STBTT_memset memset
401 ///////////////////////////////////////////////////////////////////////////////
402 ///////////////////////////////////////////////////////////////////////////////
408 #ifndef __STB_INCLUDE_STB_TRUETYPE_H__
409 #define __STB_INCLUDE_STB_TRUETYPE_H__
415 //////////////////////////////////////////////////////////////////////////////
417 // TEXTURE BAKING API
419 // If you use this API, you only have to call two functions ever.
424 unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
425 float xoff,yoff,xadvance;
428 extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
429 float pixel_height, // height of font in pixels
430 unsigned char *pixels, int pw, int ph, // bitmap to be filled in
431 int first_char, int num_chars, // characters to bake
432 stbtt_bakedchar *chardata); // you allocate this, it's num_chars long
433 // if return is positive, the first unused row of the bitmap
434 // if return is negative, returns the negative of the number of characters that fit
435 // if return is 0, no characters fit and no rows were used
436 // This uses a very crappy packing.
440 float x0,y0,s0,t0; // top-left
441 float x1,y1,s1,t1; // bottom-right
442 } stbtt_aligned_quad;
444 extern void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, // same data as above
445 int char_index, // character to display
446 float *xpos, float *ypos, // pointers to current position in screen pixel space
447 stbtt_aligned_quad *q, // output: quad to draw
448 int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier
449 // Call GetBakedQuad with char_index = 'character - first_char', and it
450 // creates the quad you need to draw and advances the current position.
452 // The coordinate system used assumes y increases downwards.
454 // Characters will extend both above and below the current position;
455 // see discussion of "BASELINE" above.
457 // It's inefficient; you might want to c&p it and optimize it.
460 //////////////////////////////////////////////////////////////////////////////
466 extern int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
467 // Each .ttf/.ttc file may have more than one font. Each font has a sequential
468 // index number starting from 0. Call this function to get the font offset for
469 // a given index; it returns -1 if the index is out of range. A regular .ttf
470 // file will only define one font and it always be at offset 0, so it will
471 // return '0' for index 0, and -1 for all other indices. You can just skip
472 // this step if you know it's that kind of font.
475 // The following structure is defined publically so you can declare one on
476 // the stack or as a global or etc, but you should treat it as opaque.
477 typedef struct stbtt_fontinfo
480 unsigned char * data; // pointer to .ttf file
481 int fontstart; // offset of start of font
483 int numGlyphs; // number of glyphs, needed for range checking
485 int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf
486 int index_map; // a cmap mapping for our chosen character encoding
487 int indexToLocFormat; // format needed to map from glyph index to glyph
490 extern int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
491 // Given an offset into the file that defines a font, this function builds
492 // the necessary cached info for the rest of the system. You must allocate
493 // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
494 // need to do anything special to free it, because the contents are pure
495 // value data with no additional data structures. Returns 0 on failure.
498 //////////////////////////////////////////////////////////////////////////////
500 // CHARACTER TO GLYPH-INDEX CONVERSIOn
502 int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
503 // If you're going to perform multiple operations on the same character
504 // and you want a speed-up, call this function with the character you're
505 // going to process, then use glyph-based functions instead of the
506 // codepoint-based functions.
509 //////////////////////////////////////////////////////////////////////////////
511 // CHARACTER PROPERTIES
514 extern float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
515 // computes a scale factor to produce a font whose "height" is 'pixels' tall.
516 // Height is measured as the distance from the highest ascender to the lowest
517 // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
519 // scale = pixels / (ascent - descent)
520 // so if you prefer to measure height by the ascent only, use a similar calculation.
522 extern float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
523 // computes a scale factor to produce a font whose EM size is mapped to
524 // 'pixels' tall. This is probably what traditional APIs compute, but
527 extern void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
528 // ascent is the coordinate above the baseline the font extends; descent
529 // is the coordinate below the baseline the font extends (i.e. it is typically negative)
530 // lineGap is the spacing between one row's descent and the next row's ascent...
531 // so you should advance the vertical position by "*ascent - *descent + *lineGap"
532 // these are expressed in unscaled coordinates, so you must multiply by
533 // the scale factor for a given size
535 extern void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
536 // the bounding box around all possible characters
538 extern void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
539 // leftSideBearing is the offset from the current horizontal position to the left edge of the character
540 // advanceWidth is the offset from the current horizontal position to the next horizontal position
541 // these are expressed in unscaled coordinates
543 extern int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
544 // an additional amount to add to the 'advance' value between ch1 and ch2
546 extern int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
547 // Gets the bounding box of the visible part of the glyph, in unscaled coordinates
549 extern void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
550 extern int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
551 extern int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
552 // as above, but takes one or more glyph indices for greater efficiency
555 //////////////////////////////////////////////////////////////////////////////
557 // GLYPH SHAPES (you probably don't need these, but they have to go before
558 // the bitmaps for C declaration-order reasons)
561 #ifndef STBTT_vmove // you can predefine these to use different values (but why?)
569 #ifndef stbtt_vertex // you can predefine this to use different values
570 // (we share this with other code at RAD)
571 #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
574 stbtt_vertex_type x,y,cx,cy;
575 unsigned char type,padding;
579 extern int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
580 // returns non-zero if nothing is drawn for this glyph
582 extern int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
583 extern int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
584 // returns # of vertices and fills *vertices with the pointer to them
585 // these are expressed in "unscaled" coordinates
587 // The shape is a series of countours. Each one starts with
588 // a STBTT_moveto, then consists of a series of mixed
589 // STBTT_lineto and STBTT_curveto segments. A lineto
590 // draws a line from previous endpoint to its x,y; a curveto
591 // draws a quadratic bezier from previous endpoint to
592 // its x,y, using cx,cy as the bezier control point.
594 extern void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
595 // frees the data allocated above
597 //////////////////////////////////////////////////////////////////////////////
602 extern void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
603 // frees the bitmap allocated below
605 extern unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
606 // allocates a large-enough single-channel 8bpp bitmap and renders the
607 // specified character/glyph at the specified scale into it, with
608 // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
609 // *width & *height are filled out with the width & height of the bitmap,
610 // which is stored left-to-right, top-to-bottom.
612 // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
614 extern unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
615 // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
616 // shift for the character
618 extern void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint);
619 // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
620 // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
621 // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
622 // width and height and positioning info for it first.
624 extern void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint);
625 // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
626 // shift for the character
628 extern void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
629 // get the bbox of the bitmap centered around the glyph origin; so the
630 // bitmap width is ix1-ix0, height is iy1-iy0, and location to place
631 // the bitmap top left is (leftSideBearing*scale,iy0).
632 // (Note that the bitmap uses y-increases-down, but the shape uses
633 // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
635 extern void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
636 // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
637 // shift for the character
639 // the following functions are equivalent to the above functions, but operate
640 // on glyph indices instead of Unicode codepoints (for efficiency)
641 extern unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);
642 extern unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff);
643 extern void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);
644 extern void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);
645 extern void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
646 extern void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
649 // @TODO: don't expose this structure
653 unsigned char *pixels;
656 extern void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata);
658 //////////////////////////////////////////////////////////////////////////////
660 // Finding the right font...
662 // You should really just solve this offline, keep your own tables
663 // of what font is what, and don't try to get it out of the .ttf file.
664 // That's because getting it out of the .ttf file is really hard, because
665 // the names in the file can appear in many possible encodings, in many
666 // possible languages, and e.g. if you need a case-insensitive comparison,
667 // the details of that depend on the encoding & language in a complex way
668 // (actually underspecified in truetype, but also gigantic).
670 // But you can use the provided functions in two possible ways:
671 // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
672 // unicode-encoded names to try to find the font you want;
673 // you can run this before calling stbtt_InitFont()
675 // stbtt_GetFontNameString() lets you get any of the various strings
676 // from the file yourself and do your own comparisons on them.
677 // You have to have called stbtt_InitFont() first.
680 extern int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
681 // returns the offset (not index) of the font that matches, or -1 if none
682 // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
683 // if you use any other flag, use a font name like "Arial"; this checks
684 // the 'macStyle' header field; i don't know if fonts set this consistently
685 #define STBTT_MACSTYLE_DONTCARE 0
686 #define STBTT_MACSTYLE_BOLD 1
687 #define STBTT_MACSTYLE_ITALIC 2
688 #define STBTT_MACSTYLE_UNDERSCORE 4
689 #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0
691 extern int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
692 // returns 1/0 whether the first string interpreted as utf8 is identical to
693 // the second string interpreted as big-endian utf16... useful for strings from next func
695 extern const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
696 // returns the string (which may be big-endian double byte, e.g. for unicode)
697 // and puts the length in bytes in *length.
699 // some of the values for the IDs are below; for more see the truetype spec:
700 // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
701 // http://www.microsoft.com/typography/otspec/name.htm
704 STBTT_PLATFORM_ID_UNICODE =0,
705 STBTT_PLATFORM_ID_MAC =1,
706 STBTT_PLATFORM_ID_ISO =2,
707 STBTT_PLATFORM_ID_MICROSOFT =3
710 enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
711 STBTT_UNICODE_EID_UNICODE_1_0 =0,
712 STBTT_UNICODE_EID_UNICODE_1_1 =1,
713 STBTT_UNICODE_EID_ISO_10646 =2,
714 STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
715 STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
718 enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
719 STBTT_MS_EID_SYMBOL =0,
720 STBTT_MS_EID_UNICODE_BMP =1,
721 STBTT_MS_EID_SHIFTJIS =2,
722 STBTT_MS_EID_UNICODE_FULL =10
725 enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
726 STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4,
727 STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5,
728 STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6,
729 STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7
732 enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
733 // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
734 STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410,
735 STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411,
736 STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412,
737 STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419,
738 STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409,
739 STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D
742 enum { // languageID for STBTT_PLATFORM_ID_MAC
743 STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11,
744 STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23,
745 STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32,
746 STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 ,
747 STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 ,
748 STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
749 STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19
756 #endif // __STB_INCLUDE_STB_TRUETYPE_H__
758 ///////////////////////////////////////////////////////////////////////////////
759 ///////////////////////////////////////////////////////////////////////////////
765 #ifdef STB_TRUETYPE_IMPLEMENTATION
767 //////////////////////////////////////////////////////////////////////////
769 // accessors to parse data from file
772 // on platforms that don't allow misaligned reads, if we want to allow
773 // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
775 #define ttBYTE(p) (* (stbtt_uint8 *) (p))
776 #define ttCHAR(p) (* (stbtt_int8 *) (p))
777 #define ttFixed(p) ttLONG(p)
779 #if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE)
781 #define ttUSHORT(p) (* (stbtt_uint16 *) (p))
782 #define ttSHORT(p) (* (stbtt_int16 *) (p))
783 #define ttULONG(p) (* (stbtt_uint32 *) (p))
784 #define ttLONG(p) (* (stbtt_int32 *) (p))
788 stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
789 stbtt_int16 ttSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
790 stbtt_uint32 ttULONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
791 stbtt_int32 ttLONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
795 #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
796 #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])
798 static int stbtt__isfont(const stbtt_uint8 *font)
800 // check the version number
801 if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1
802 if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!
803 if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF
804 if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
808 // @OPTIMIZE: binary search
809 static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
811 stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
812 stbtt_uint32 tabledir = fontstart + 12;
814 for (i=0; i < num_tables; ++i) {
815 stbtt_uint32 loc = tabledir + 16*i;
816 if (stbtt_tag(data+loc+0, tag))
817 return ttULONG(data+loc+8);
822 int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, int index)
824 // if it's just a font, there's only one valid index
825 if (stbtt__isfont(font_collection))
826 return index == 0 ? 0 : -1;
828 // check if it's a TTC
829 if (stbtt_tag(font_collection, "ttcf")) {
831 if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
832 stbtt_int32 n = ttLONG(font_collection+8);
835 return ttULONG(font_collection+12+index*14);
841 int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart)
843 stbtt_uint8 *data = (stbtt_uint8 *) data2;
844 stbtt_uint32 cmap, t;
845 stbtt_int32 i,numTables;
848 info->fontstart = fontstart;
850 cmap = stbtt__find_table(data, fontstart, "cmap"); // required
851 info->loca = stbtt__find_table(data, fontstart, "loca"); // required
852 info->head = stbtt__find_table(data, fontstart, "head"); // required
853 info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
854 info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
855 info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
856 info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
857 if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx)
860 t = stbtt__find_table(data, fontstart, "maxp");
862 info->numGlyphs = ttUSHORT(data+t+4);
864 info->numGlyphs = 0xffff;
866 // find a cmap encoding table we understand *now* to avoid searching
867 // later. (todo: could make this installable)
868 // the same regardless of glyph.
869 numTables = ttUSHORT(data + cmap + 2);
871 for (i=0; i < numTables; ++i) {
872 stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
873 // find an encoding we understand:
874 switch(ttUSHORT(data+encoding_record)) {
875 case STBTT_PLATFORM_ID_MICROSOFT:
876 switch (ttUSHORT(data+encoding_record+2)) {
877 case STBTT_MS_EID_UNICODE_BMP:
878 case STBTT_MS_EID_UNICODE_FULL:
880 info->index_map = cmap + ttULONG(data+encoding_record+4);
886 if (info->index_map == 0)
889 info->indexToLocFormat = ttUSHORT(data+info->head + 50);
893 int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
895 stbtt_uint8 *data = info->data;
896 stbtt_uint32 index_map = info->index_map;
898 stbtt_uint16 format = ttUSHORT(data + index_map + 0);
899 if (format == 0) { // apple byte encoding
900 stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
901 if (unicode_codepoint < bytes-6)
902 return ttBYTE(data + index_map + 6 + unicode_codepoint);
904 } else if (format == 6) {
905 stbtt_uint32 first = ttUSHORT(data + index_map + 6);
906 stbtt_uint32 count = ttUSHORT(data + index_map + 8);
907 if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
908 return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
910 } else if (format == 2) {
911 STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
913 } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges
914 stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
915 stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
916 stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
917 stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
918 stbtt_uint16 item, offset, start, end;
920 // do a binary search of the segments
921 stbtt_uint32 endCount = index_map + 14;
922 stbtt_uint32 search = endCount;
924 if (unicode_codepoint > 0xffff)
927 // they lie from endCount .. endCount + segCount
928 // but searchRange is the nearest power of two, so...
929 if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
930 search += rangeShift*2;
932 // now decrement to bias correctly to find smallest
934 while (entrySelector) {
936 start = ttUSHORT(data + search + searchRange*2 + segcount*2 + 2);
937 end = ttUSHORT(data + search + searchRange*2);
938 if (unicode_codepoint > end)
939 search += searchRange*2;
944 item = (stbtt_uint16) ((search - endCount) >> 1);
946 STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
947 start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
948 end = ttUSHORT(data + index_map + 14 + 2 + 2*item);
949 if (unicode_codepoint < start)
952 offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
954 return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
956 return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
957 } else if (format == 12 || format == 13) {
958 stbtt_uint32 ngroups = ttULONG(data+index_map+12);
959 stbtt_int32 low,high;
960 low = 0; high = (stbtt_int32)ngroups;
961 // Binary search the right group.
963 stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high
964 stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
965 stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
966 if ((stbtt_uint32) unicode_codepoint < start_char)
968 else if ((stbtt_uint32) unicode_codepoint > end_char)
971 stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
973 return start_glyph + unicode_codepoint-start_char;
978 return 0; // not found
985 int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
987 return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
990 static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
993 v->x = (stbtt_int16) x;
994 v->y = (stbtt_int16) y;
995 v->cx = (stbtt_int16) cx;
996 v->cy = (stbtt_int16) cy;
999 static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
1003 if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
1004 if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format
1006 if (info->indexToLocFormat == 0) {
1007 g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
1008 g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
1010 g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
1011 g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
1014 return g1==g2 ? -1 : g1; // if length is 0, return -1
1017 int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
1019 int g = stbtt__GetGlyfOffset(info, glyph_index);
1020 if (g < 0) return 0;
1022 if (x0) *x0 = ttSHORT(info->data + g + 2);
1023 if (y0) *y0 = ttSHORT(info->data + g + 4);
1024 if (x1) *x1 = ttSHORT(info->data + g + 6);
1025 if (y1) *y1 = ttSHORT(info->data + g + 8);
1029 int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
1031 return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
1034 int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
1036 stbtt_int16 numberOfContours;
1037 int g = stbtt__GetGlyfOffset(info, glyph_index);
1038 if (g < 0) return 1;
1039 numberOfContours = ttSHORT(info->data + g);
1040 return numberOfContours == 0;
1043 static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
1044 stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
1048 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
1049 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
1052 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
1054 stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
1056 return num_vertices;
1059 int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
1061 stbtt_int16 numberOfContours;
1062 stbtt_uint8 *endPtsOfContours;
1063 stbtt_uint8 *data = info->data;
1064 stbtt_vertex *vertices=0;
1066 int g = stbtt__GetGlyfOffset(info, glyph_index);
1070 if (g < 0) return 0;
1072 numberOfContours = ttSHORT(data + g);
1074 if (numberOfContours > 0) {
1075 stbtt_uint8 flags=0,flagcount;
1076 stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
1077 stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
1078 stbtt_uint8 *points;
1079 endPtsOfContours = (data + g + 10);
1080 ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
1081 points = data + g + 10 + numberOfContours * 2 + 2 + ins;
1083 n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
1085 m = n + 2*numberOfContours; // a loose bound on how many vertices we might need
1086 vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
1093 // in first pass, we load uninterpreted data into the allocated array
1094 // above, shifted to the end of the array so we won't overwrite it when
1095 // we create our final data starting from the front
1097 off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
1101 for (i=0; i < n; ++i) {
1102 if (flagcount == 0) {
1105 flagcount = *points++;
1108 vertices[off+i].type = flags;
1111 // now load x coordinates
1113 for (i=0; i < n; ++i) {
1114 flags = vertices[off+i].type;
1116 stbtt_int16 dx = *points++;
1117 x += (flags & 16) ? dx : -dx; // ???
1119 if (!(flags & 16)) {
1120 x = x + (stbtt_int16) (points[0]*256 + points[1]);
1124 vertices[off+i].x = (stbtt_int16) x;
1127 // now load y coordinates
1129 for (i=0; i < n; ++i) {
1130 flags = vertices[off+i].type;
1132 stbtt_int16 dy = *points++;
1133 y += (flags & 32) ? dy : -dy; // ???
1135 if (!(flags & 32)) {
1136 y = y + (stbtt_int16) (points[0]*256 + points[1]);
1140 vertices[off+i].y = (stbtt_int16) y;
1143 // now convert them to our format
1145 sx = sy = cx = cy = scx = scy = 0;
1146 for (i=0; i < n; ++i) {
1147 flags = vertices[off+i].type;
1148 x = (stbtt_int16) vertices[off+i].x;
1149 y = (stbtt_int16) vertices[off+i].y;
1151 if (next_move == i) {
1153 num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
1155 // now start the new one
1156 start_off = !(flags & 1);
1158 // if we start off with an off-curve point, then when we need to find a point on the curve
1159 // where we can start, and we need to save some state for when we wraparound.
1162 if (!(vertices[off+i+1].type & 1)) {
1163 // next point is also a curve point, so interpolate an on-point curve
1164 sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
1165 sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
1167 // otherwise just use the next point as our start point
1168 sx = (stbtt_int32) vertices[off+i+1].x;
1169 sy = (stbtt_int32) vertices[off+i+1].y;
1170 ++i; // we're using point i+1 as the starting point, so skip it
1176 stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
1178 next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
1181 if (!(flags & 1)) { // if it's a curve
1182 if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
1183 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
1189 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
1191 stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
1196 num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
1197 } else if (numberOfContours == -1) {
1200 stbtt_uint8 *comp = data + g + 10;
1204 stbtt_uint16 flags, gidx;
1205 int comp_num_verts = 0, i;
1206 stbtt_vertex *comp_verts = 0, *tmp = 0;
1207 float mtx[6] = {1,0,0,1,0,0}, m, n;
1209 flags = ttSHORT(comp); comp+=2;
1210 gidx = ttSHORT(comp); comp+=2;
1212 if (flags & 2) { // XY values
1213 if (flags & 1) { // shorts
1214 mtx[4] = ttSHORT(comp); comp+=2;
1215 mtx[5] = ttSHORT(comp); comp+=2;
1217 mtx[4] = ttCHAR(comp); comp+=1;
1218 mtx[5] = ttCHAR(comp); comp+=1;
1222 // @TODO handle matching point
1225 if (flags & (1<<3)) { // WE_HAVE_A_SCALE
1226 mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1227 mtx[1] = mtx[2] = 0;
1228 } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
1229 mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
1230 mtx[1] = mtx[2] = 0;
1231 mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1232 } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
1233 mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
1234 mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
1235 mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
1236 mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1239 // Find transformation scales.
1240 m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
1241 n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
1243 // Get indexed glyph.
1244 comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
1245 if (comp_num_verts > 0) {
1246 // Transform vertices.
1247 for (i = 0; i < comp_num_verts; ++i) {
1248 stbtt_vertex* v = &comp_verts[i];
1249 stbtt_vertex_type x,y;
1251 v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
1252 v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
1254 v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
1255 v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
1258 tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
1260 if (vertices) STBTT_free(vertices, info->userdata);
1261 if (comp_verts) STBTT_free(comp_verts, info->userdata);
1264 if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));
1265 STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
1266 if (vertices) STBTT_free(vertices, info->userdata);
1268 STBTT_free(comp_verts, info->userdata);
1269 num_vertices += comp_num_verts;
1271 // More components ?
1272 more = flags & (1<<5);
1274 } else if (numberOfContours < 0) {
1275 // @TODO other compound variations?
1278 // numberOfCounters == 0, do nothing
1281 *pvertices = vertices;
1282 return num_vertices;
1285 void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
1287 stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
1288 if (glyph_index < numOfLongHorMetrics) {
1289 if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index);
1290 if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
1292 if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
1293 if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
1297 int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
1299 stbtt_uint8 *data = info->data + info->kern;
1300 stbtt_uint32 needle, straw;
1303 // we only look at the first table. it must be 'horizontal' and format 0.
1306 if (ttUSHORT(data+2) < 1) // number of tables, need at least 1
1308 if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format
1312 r = ttUSHORT(data+10) - 1;
1313 needle = glyph1 << 16 | glyph2;
1316 straw = ttULONG(data+18+(m*6)); // note: unaligned read
1319 else if (needle > straw)
1322 return ttSHORT(data+22+(m*6));
1327 int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
1329 if (!info->kern) // if no kerning table, don't waste time looking up both codepoint->glyphs
1331 return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
1334 void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
1336 stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
1339 void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
1341 if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4);
1342 if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
1343 if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
1346 void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
1348 *x0 = ttSHORT(info->data + info->head + 36);
1349 *y0 = ttSHORT(info->data + info->head + 38);
1350 *x1 = ttSHORT(info->data + info->head + 40);
1351 *y1 = ttSHORT(info->data + info->head + 42);
1354 float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
1356 int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
1357 return (float) height / fheight;
1360 float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
1362 int unitsPerEm = ttUSHORT(info->data + info->head + 18);
1363 return pixels / unitsPerEm;
1366 void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
1368 STBTT_free(v, info->userdata);
1371 //////////////////////////////////////////////////////////////////////////////
1373 // antialiasing software rasterizer
1376 void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
1379 if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1))
1380 x0=y0=x1=y1=0; // e.g. space character
1381 // now move to integral bboxes (treating pixels as little squares, what pixels get touched)?
1382 if (ix0) *ix0 = STBTT_ifloor(x0 * scale_x + shift_x);
1383 if (iy0) *iy0 = -STBTT_iceil (y1 * scale_y + shift_y);
1384 if (ix1) *ix1 = STBTT_iceil (x1 * scale_x + shift_x);
1385 if (iy1) *iy1 = -STBTT_ifloor(y0 * scale_y + shift_y);
1387 void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
1389 stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
1392 void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
1394 stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
1397 void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
1399 stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
1402 typedef struct stbtt__edge {
1407 typedef struct stbtt__active_edge
1411 struct stbtt__active_edge *next;
1413 } stbtt__active_edge;
1416 #define FIX (1 << FIXSHIFT)
1417 #define FIXMASK (FIX-1)
1419 static stbtt__active_edge *new_active(stbtt__edge *e, int off_x, float start_point, void *userdata)
1421 stbtt__active_edge *z = (stbtt__active_edge *) STBTT_malloc(sizeof(*z), userdata); // @TODO: make a pool of these!!!
1422 float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
1423 STBTT_assert(e->y0 <= start_point);
1425 // round dx down to avoid going too far
1427 z->dx = -STBTT_ifloor(FIX * -dxdy);
1429 z->dx = STBTT_ifloor(FIX * dxdy);
1430 z->x = STBTT_ifloor(FIX * (e->x0 + dxdy * (start_point - e->y0)));
1431 z->x -= off_x * FIX;
1434 z->valid = e->invert ? 1 : -1;
1438 // note: this routine clips fills that extend off the edges... ideally this
1439 // wouldn't happen, but it could happen if the truetype glyph bounding boxes
1440 // are wrong, or if the user supplies a too-small bitmap
1441 static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
1443 // non-zero winding fill
1448 // if we're currently at zero, we need to record the edge start point
1449 x0 = e->x; w += e->valid;
1451 int x1 = e->x; w += e->valid;
1452 // if we went to zero, we need to draw
1454 int i = x0 >> FIXSHIFT;
1455 int j = x1 >> FIXSHIFT;
1457 if (i < len && j >= 0) {
1459 // x0,x1 are the same pixel, so compute combined coverage
1460 scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> FIXSHIFT);
1462 if (i >= 0) // add antialiasing for x0
1463 scanline[i] = scanline[i] + (stbtt_uint8) (((FIX - (x0 & FIXMASK)) * max_weight) >> FIXSHIFT);
1467 if (j < len) // add antialiasing for x1
1468 scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & FIXMASK) * max_weight) >> FIXSHIFT);
1472 for (++i; i < j; ++i) // fill pixels between x0 and x1
1473 scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
1483 static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
1485 stbtt__active_edge *active = NULL;
1487 int max_weight = (255 / vsubsample); // weight per vertical scanline
1488 int s; // vertical subsample index
1489 unsigned char scanline_data[512], *scanline;
1491 if (result->w > 512)
1492 scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
1494 scanline = scanline_data;
1496 y = off_y * vsubsample;
1497 e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
1499 while (j < result->h) {
1500 STBTT_memset(scanline, 0, result->w);
1501 for (s=0; s < vsubsample; ++s) {
1502 // find center of pixel for this scanline
1503 float scan_y = y + 0.5f;
1504 stbtt__active_edge **step = &active;
1506 // update all active edges;
1507 // remove all active edges that terminate before the center of this scanline
1509 stbtt__active_edge * z = *step;
1510 if (z->ey <= scan_y) {
1511 *step = z->next; // delete from list
1512 STBTT_assert(z->valid);
1514 STBTT_free(z, userdata);
1516 z->x += z->dx; // advance to position for current scanline
1517 step = &((*step)->next); // advance through list
1521 // resort the list if needed
1525 while (*step && (*step)->next) {
1526 if ((*step)->x > (*step)->next->x) {
1527 stbtt__active_edge *t = *step;
1528 stbtt__active_edge *q = t->next;
1535 step = &(*step)->next;
1537 if (!changed) break;
1540 // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
1541 while (e->y0 <= scan_y) {
1542 if (e->y1 > scan_y) {
1543 stbtt__active_edge *z = new_active(e, off_x, scan_y, userdata);
1544 // find insertion point
1547 else if (z->x < active->x) {
1552 // find thing to insert AFTER
1553 stbtt__active_edge *p = active;
1554 while (p->next && p->next->x < z->x)
1556 // at this point, p->next->x is NOT < z->x
1564 // now process all active edges in XOR fashion
1566 stbtt__fill_active_edges(scanline, result->w, active, max_weight);
1570 STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
1575 stbtt__active_edge *z = active;
1576 active = active->next;
1577 STBTT_free(z, userdata);
1580 if (scanline != scanline_data)
1581 STBTT_free(scanline, userdata);
1584 static int stbtt__edge_compare(const void *p, const void *q)
1586 stbtt__edge *a = (stbtt__edge *) p;
1587 stbtt__edge *b = (stbtt__edge *) q;
1589 if (a->y0 < b->y0) return -1;
1590 if (a->y0 > b->y0) return 1;
1599 static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata)
1601 float y_scale_inv = invert ? -scale_y : scale_y;
1604 int vsubsample = result->h < 8 ? 15 : 5;
1605 // vsubsample should divide 255 evenly; otherwise we won't reach full opacity
1607 // now we have to blow out the windings into explicit edge lists
1609 for (i=0; i < windings; ++i)
1612 e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel
1617 for (i=0; i < windings; ++i) {
1618 stbtt__point *p = pts + m;
1621 for (k=0; k < wcount[i]; j=k++) {
1623 // skip the edge if horizontal
1624 if (p[j].y == p[k].y)
1626 // add edge from j to k to the list
1628 if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
1632 e[n].x0 = p[a].x * scale_x + shift_x;
1633 e[n].y0 = p[a].y * y_scale_inv * vsubsample + shift_y;
1634 e[n].x1 = p[b].x * scale_x + shift_x;
1635 e[n].y1 = p[b].y * y_scale_inv * vsubsample + shift_y;
1640 // now sort the edges by their highest point (should snap to integer, and then by x)
1641 STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
1643 // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
1644 stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
1646 STBTT_free(e, userdata);
1649 static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
1651 if (!points) return; // during first pass, it's unallocated
1656 // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching
1657 static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n)
1660 float mx = (x0 + 2*x1 + x2)/4;
1661 float my = (y0 + 2*y1 + y2)/4;
1662 // versus directly drawn line
1663 float dx = (x0+x2)/2 - mx;
1664 float dy = (y0+y2)/2 - my;
1665 if (n > 16) // 65536 segments on one curve better be enough!
1667 if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
1668 stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
1669 stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
1671 stbtt__add_point(points, *num_points,x2,y2);
1672 *num_points = *num_points+1;
1677 // returns number of contours
1678 stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
1680 stbtt__point *points=0;
1683 float objspace_flatness_squared = objspace_flatness * objspace_flatness;
1684 int i,n=0,start=0, pass;
1686 // count how many "moves" there are to get the contour count
1687 for (i=0; i < num_verts; ++i)
1688 if (vertices[i].type == STBTT_vmove)
1692 if (n == 0) return 0;
1694 *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
1696 if (*contour_lengths == 0) {
1701 // make two passes through the points so we don't need to realloc
1702 for (pass=0; pass < 2; ++pass) {
1705 points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
1706 if (points == NULL) goto error;
1710 for (i=0; i < num_verts; ++i) {
1711 switch (vertices[i].type) {
1713 // start the next contour
1715 (*contour_lengths)[n] = num_points - start;
1719 x = vertices[i].x, y = vertices[i].y;
1720 stbtt__add_point(points, num_points++, x,y);
1723 x = vertices[i].x, y = vertices[i].y;
1724 stbtt__add_point(points, num_points++, x, y);
1727 stbtt__tesselate_curve(points, &num_points, x,y,
1728 vertices[i].cx, vertices[i].cy,
1729 vertices[i].x, vertices[i].y,
1730 objspace_flatness_squared, 0);
1731 x = vertices[i].x, y = vertices[i].y;
1735 (*contour_lengths)[n] = num_points - start;
1740 STBTT_free(points, userdata);
1741 STBTT_free(*contour_lengths, userdata);
1742 *contour_lengths = 0;
1747 void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata)
1749 float scale = scale_x > scale_y ? scale_y : scale_x;
1750 int winding_count, *winding_lengths;
1751 stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
1753 stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
1754 STBTT_free(winding_lengths, userdata);
1755 STBTT_free(windings, userdata);
1759 void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
1761 STBTT_free(bitmap, userdata);
1764 unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff)
1766 int ix0,iy0,ix1,iy1;
1768 stbtt_vertex *vertices;
1769 int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
1771 if (scale_x == 0) scale_x = scale_y;
1773 if (scale_x == 0) return NULL;
1777 stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
1779 // now we get the size
1780 gbm.w = (ix1 - ix0);
1781 gbm.h = (iy1 - iy0);
1782 gbm.pixels = NULL; // in case we error
1784 if (width ) *width = gbm.w;
1785 if (height) *height = gbm.h;
1786 if (xoff ) *xoff = ix0;
1787 if (yoff ) *yoff = iy0;
1789 if (gbm.w && gbm.h) {
1790 gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
1794 stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
1797 STBTT_free(vertices, info->userdata);
1801 unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)
1803 return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
1806 void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph)
1809 stbtt_vertex *vertices;
1810 int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
1813 stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
1814 gbm.pixels = output;
1817 gbm.stride = out_stride;
1820 stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
1822 STBTT_free(vertices, info->userdata);
1825 void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph)
1827 stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
1830 unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
1832 return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
1835 void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint)
1837 stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
1840 unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
1842 return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
1845 void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint)
1847 stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
1850 //////////////////////////////////////////////////////////////////////////////
1854 // This is SUPER-CRAPPY packing to keep source code small
1856 extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
1857 float pixel_height, // height of font in pixels
1858 unsigned char *pixels, int pw, int ph, // bitmap to be filled in
1859 int first_char, int num_chars, // characters to bake
1860 stbtt_bakedchar *chardata)
1863 int x,y,bottom_y, i;
1865 stbtt_InitFont(&f, data, offset);
1866 STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
1870 scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
1872 for (i=0; i < num_chars; ++i) {
1873 int advance, lsb, x0,y0,x1,y1,gw,gh;
1874 int g = stbtt_FindGlyphIndex(&f, first_char + i);
1875 stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
1876 stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
1879 if (x + gw + 1 >= pw)
1880 y = bottom_y, x = 1; // advance to next row
1881 if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
1883 STBTT_assert(x+gw < pw);
1884 STBTT_assert(y+gh < ph);
1885 stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
1886 chardata[i].x0 = (stbtt_int16) x;
1887 chardata[i].y0 = (stbtt_int16) y;
1888 chardata[i].x1 = (stbtt_int16) (x + gw);
1889 chardata[i].y1 = (stbtt_int16) (y + gh);
1890 chardata[i].xadvance = scale * advance;
1891 chardata[i].xoff = (float) x0;
1892 chardata[i].yoff = (float) y0;
1894 if (y+gh+2 > bottom_y)
1900 void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
1902 float d3d_bias = opengl_fillrule ? 0 : -0.5f;
1903 float ipw = 1.0f / pw, iph = 1.0f / ph;
1904 stbtt_bakedchar *b = chardata + char_index;
1905 int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5);
1906 int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5);
1908 q->x0 = round_x + d3d_bias;
1909 q->y0 = round_y + d3d_bias;
1910 q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
1911 q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
1913 q->s0 = b->x0 * ipw;
1914 q->t0 = b->y0 * iph;
1915 q->s1 = b->x1 * ipw;
1916 q->t1 = b->y1 * iph;
1918 *xpos += b->xadvance;
1921 //////////////////////////////////////////////////////////////////////////////
1923 // font name matching -- recommended not to use this
1926 // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
1927 static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(const stbtt_uint8 *s1, stbtt_int32 len1, const stbtt_uint8 *s2, stbtt_int32 len2)
1931 // convert utf16 to utf8 and compare the results while converting
1933 stbtt_uint16 ch = s2[0]*256 + s2[1];
1935 if (i >= len1) return -1;
1936 if (s1[i++] != ch) return -1;
1937 } else if (ch < 0x800) {
1938 if (i+1 >= len1) return -1;
1939 if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
1940 if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
1941 } else if (ch >= 0xd800 && ch < 0xdc00) {
1943 stbtt_uint16 ch2 = s2[2]*256 + s2[3];
1944 if (i+3 >= len1) return -1;
1945 c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
1946 if (s1[i++] != 0xf0 + (c >> 18)) return -1;
1947 if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
1948 if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1;
1949 if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1;
1950 s2 += 2; // plus another 2 below
1952 } else if (ch >= 0xdc00 && ch < 0xe000) {
1955 if (i+2 >= len1) return -1;
1956 if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
1957 if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
1958 if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1;
1966 int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
1968 return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((const stbtt_uint8*) s1, len1, (const stbtt_uint8*) s2, len2);
1971 // returns results in whatever encoding you request... but note that 2-byte encodings
1972 // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
1973 const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
1975 stbtt_int32 i,count,stringOffset;
1976 stbtt_uint8 *fc = font->data;
1977 stbtt_uint32 offset = font->fontstart;
1978 stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
1979 if (!nm) return NULL;
1981 count = ttUSHORT(fc+nm+2);
1982 stringOffset = nm + ttUSHORT(fc+nm+4);
1983 for (i=0; i < count; ++i) {
1984 stbtt_uint32 loc = nm + 6 + 12 * i;
1985 if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
1986 && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
1987 *length = ttUSHORT(fc+loc+8);
1988 return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
1994 static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
1997 stbtt_int32 count = ttUSHORT(fc+nm+2);
1998 stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
2000 for (i=0; i < count; ++i) {
2001 stbtt_uint32 loc = nm + 6 + 12 * i;
2002 stbtt_int32 id = ttUSHORT(fc+loc+6);
2003 if (id == target_id) {
2004 // find the encoding
2005 stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
2007 // is this a Unicode encoding?
2008 if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
2009 stbtt_int32 slen = ttUSHORT(fc+loc+8);
2010 stbtt_int32 off = ttUSHORT(fc+loc+10);
2012 // check if there's a prefix match
2013 stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
2014 if (matchlen >= 0) {
2015 // check for target_id+1 immediately following, with same encoding & language
2016 if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) {
2017 slen = ttUSHORT(fc+loc+12+8);
2018 off = ttUSHORT(fc+loc+12+10);
2020 if (matchlen == nlen)
2022 } else if (matchlen < nlen && name[matchlen] == ' ') {
2024 if (stbtt_CompareUTF8toUTF16_bigendian((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
2028 // if nothing immediately following
2029 if (matchlen == nlen)
2035 // @TODO handle other encodings
2041 static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
2043 stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
2045 if (!stbtt__isfont(fc+offset)) return 0;
2047 // check italics/bold/underline flags in macStyle...
2049 hd = stbtt__find_table(fc, offset, "head");
2050 if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
2053 nm = stbtt__find_table(fc, offset, "name");
2057 // if we checked the macStyle flags, then just check the family and ignore the subfamily
2058 if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1;
2059 if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1;
2060 if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
2062 if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1;
2063 if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1;
2064 if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
2070 int stbtt_FindMatchingFont(const unsigned char *font_collection, const char *name_utf8, stbtt_int32 flags)
2074 stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
2075 if (off < 0) return off;
2076 if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
2081 #endif // STB_TRUETYPE_IMPLEMENTATION