1 // stb_truetype.h - v0.7 - 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)
33 // 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
34 // 0.6c (2012-07-24) improve documentation
35 // 0.6b (2012-07-20) fix a few more warnings
36 // 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
37 // stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
38 // 0.5 (2011-12-09) bugfixes:
39 // subpixel glyph renderer computed wrong bounding box
40 // first vertex of shape can be off-curve (FreeSans)
41 // 0.4b (2011-12-03) fixed an error in the font baking example
42 // 0.4 (2011-12-01) kerning, subpixel rendering (tor)
44 // codepoint-to-glyph conversion using table fmt=12
45 // codepoint-to-glyph conversion using table fmt=4
46 // stbtt_GetBakedQuad with non-square texture (Zer)
47 // updated Hello World! sample to use kerning and subpixel
48 // fixed some warnings
49 // 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)
50 // userdata, malloc-from-userdata, non-zero fill (STB)
51 // 0.2 (2009-03-11) Fix unsigned/signed char warnings
52 // 0.1 (2009-03-09) First public release
56 // This software is in the public domain. Where that dedication is not
57 // recognized, you are granted a perpetual, irrevokable license to copy
58 // and modify this file as you see fit.
62 // Include this file in whatever places neeed to refer to it. In ONE C/C++
64 // #define STB_TRUETYPE_IMPLEMENTATION
65 // before the #include of this file. This expands out the actual
66 // implementation into that C/C++ file.
68 // Simple 3D API (don't ship this, but it's fine for tools and quick start,
69 // and you can cut and paste from it to move to more advanced)
70 // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture
71 // stbtt_GetBakedQuad() -- compute quad to draw for a given char
73 // "Load" a font file from a memory buffer (you have to keep the buffer loaded)
75 // stbtt_GetFontOffsetForIndex() -- use for TTC font collections
77 // Render a unicode codepoint to a bitmap
78 // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
79 // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide
80 // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
82 // Character advance/positioning
83 // stbtt_GetCodepointHMetrics()
84 // stbtt_GetFontVMetrics()
85 // stbtt_GetCodepointKernAdvance()
87 // ADDITIONAL DOCUMENTATION
89 // Immediately after this block comment are a series of sample programs.
91 // After the sample programs is the "header file" section. This section
92 // includes documentation for each API function.
94 // Some important concepts to understand to use this library:
97 // Characters are defined by unicode codepoints, e.g. 65 is
98 // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
99 // the hiragana for "ma".
102 // A visual character shape (every codepoint is rendered as
106 // A font-specific integer ID representing a glyph
109 // Glyph shapes are defined relative to a baseline, which is the
110 // bottom of uppercase characters. Characters extend both above
111 // and below the baseline.
114 // As you draw text to the screen, you keep track of a "current point"
115 // which is the origin of each character. The current point's vertical
116 // position is the baseline. Even "baked fonts" use this model.
118 // Vertical Font Metrics
119 // The vertical qualities of the font, used to vertically position
120 // and space the characters. See docs for stbtt_GetFontVMetrics.
122 // Font Size in Pixels or Points
123 // The preferred interface for specifying font sizes in stb_truetype
124 // is to specify how tall the font's vertical extent should be in pixels.
125 // If that sounds good enough, skip the next paragraph.
127 // Most font APIs instead use "points", which are a common typographic
128 // measurement for describing font size, defined as 72 points per inch.
129 // stb_truetype provides a point API for compatibility. However, true
130 // "per inch" conventions don't make much sense on computer displays
131 // since they different monitors have different number of pixels per
132 // inch. For example, Windows traditionally uses a convention that
133 // there are 96 pixels per inch, thus making 'inch' measurements have
134 // nothing to do with inches, and thus effectively defining a point to
135 // be 1.333 pixels. Additionally, the TrueType font data provides
136 // an explicit scale factor to scale a given font's glyphs to points,
137 // but the author has observed that this scale factor is often wrong
138 // for non-commercial fonts, thus making fonts scaled in points
139 // according to the TrueType spec incoherently sized in practice.
145 // - Use the functions with Subpixel at the end to allow your characters
146 // to have subpixel positioning. Since the font is anti-aliased, not
147 // hinted, this is very import for quality. (This is not possible with
150 // - Kerning is now supported, and if you're supporting subpixel rendering
151 // then kerning is worth using to give your text a polished look.
155 // - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
156 // if you don't do this, stb_truetype is forced to do the conversion on
159 // - There are a lot of memory allocations. We should modify it to take
160 // a temp buffer and allocate from the temp buffer (without freeing),
161 // should help performance a lot.
165 // The system uses the raw data found in the .ttf file without changing it
166 // and without building auxiliary data structures. This is a bit inefficient
167 // on little-endian systems (the data is big-endian), but assuming you're
168 // caching the bitmaps or glyph shapes this shouldn't be a big deal.
170 // It appears to be very hard to programmatically determine what font a
171 // given file is in a general way. I provide an API for this, but I don't
175 // SOURCE STATISTICS (based on v0.6c, 2050 LOC)
177 // Documentation & header file 520 LOC \___ 660 LOC documentation
178 // Sample code 140 LOC /
179 // Truetype parsing 620 LOC ---- 620 LOC TrueType
180 // Software rasterization 240 LOC \ .
181 // Curve tesselation 120 LOC \__ 550 LOC Bitmap creation
182 // Bitmap management 100 LOC /
183 // Baked bitmap interface 70 LOC /
184 // Font name matching & access 150 LOC ---- 150
185 // C runtime library abstraction 60 LOC ---- 60
188 //////////////////////////////////////////////////////////////////////////////
189 //////////////////////////////////////////////////////////////////////////////
194 // Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
197 #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
198 #include "stb_truetype.h"
200 char ttf_buffer[1<<20];
201 unsigned char temp_bitmap[512*512];
203 stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
206 void my_stbtt_initfont(void)
208 fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
209 stbtt_BakeFontBitmap(data,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
210 // can free ttf_buffer at this point
211 glGenTextures(1, &ftex);
212 glBindTexture(GL_TEXTURE_2D, ftex);
213 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
214 // can free temp_bitmap at this point
215 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
218 void my_stbtt_print(float x, float y, char *text)
220 // assume orthographic projection with units = screen pixels, origin at top left
221 glBindTexture(GL_TEXTURE_2D, ftex);
224 if (*text >= 32 && *text < 128) {
225 stbtt_aligned_quad q;
226 stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl,0=old d3d
227 glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
228 glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
229 glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
230 glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
239 //////////////////////////////////////////////////////////////////////////////
241 // Complete program (this compiles): get a single bitmap, print as ASCII art
245 #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
246 #include "stb_truetype.h"
248 char ttf_buffer[1<<25];
250 int main(int argc, char **argv)
253 unsigned char *bitmap;
254 int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
256 fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
258 stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
259 bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
261 for (j=0; j < h; ++j) {
262 for (i=0; i < w; ++i)
263 putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
283 //////////////////////////////////////////////////////////////////////////////
285 // Complete program: print "Hello World!" banner, with bugs
289 unsigned char screen[20][79];
291 int main(int arg, char **argv)
294 int i,j,ascent,baseline,ch=0;
296 char *text = "Heljo World!";
298 fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
299 stbtt_InitFont(&font, buffer, 0);
301 scale = stbtt_ScaleForPixelHeight(&font, 15);
302 stbtt_GetFontVMetrics(&font, &ascent,0,0);
303 baseline = (int) (ascent*scale);
306 int advance,lsb,x0,y0,x1,y1;
307 float x_shift = xpos - (float) floor(xpos);
308 stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
309 stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
310 stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
311 // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
312 // because this API is really for baking character bitmaps into textures. if you want to render
313 // a sequence of characters, you really need to render each bitmap to a temp buffer, then
314 // "alpha blend" that into the working buffer
315 xpos += (advance * scale);
317 xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
321 for (j=0; j < 20; ++j) {
322 for (i=0; i < 78; ++i)
323 putchar(" .:ioVM@"[screen[j][i]>>5]);
332 //////////////////////////////////////////////////////////////////////////////
333 //////////////////////////////////////////////////////////////////////////////
335 //// INTEGRATION WITH YOUR CODEBASE
337 //// The following sections allow you to supply alternate definitions
338 //// of C library functions used by stb_truetype.
340 #ifdef STB_TRUETYPE_IMPLEMENTATION
341 // #define your own (u)stbtt_int8/16/32 before including to override this
343 typedef unsigned char stbtt_uint8;
344 typedef signed char stbtt_int8;
345 typedef unsigned short stbtt_uint16;
346 typedef signed short stbtt_int16;
347 typedef unsigned int stbtt_uint32;
348 typedef signed int stbtt_int32;
351 typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
352 typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
354 // #define your own STBTT_sort() to override this to avoid qsort
357 #define STBTT_sort(data,num_items,item_size,compare_func) qsort(data,num_items,item_size,compare_func)
360 // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
363 #define STBTT_ifloor(x) ((int) floor(x))
364 #define STBTT_iceil(x) ((int) ceil(x))
367 // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
370 #define STBTT_malloc(x,u) malloc(x)
371 #define STBTT_free(x,u) free(x)
376 #define STBTT_assert(x) assert(x)
381 #define STBTT_strlen(x) strlen(x)
386 #define STBTT_memcpy memcpy
387 #define STBTT_memset memset
391 ///////////////////////////////////////////////////////////////////////////////
392 ///////////////////////////////////////////////////////////////////////////////
398 #ifndef __STB_INCLUDE_STB_TRUETYPE_H__
399 #define __STB_INCLUDE_STB_TRUETYPE_H__
405 //////////////////////////////////////////////////////////////////////////////
407 // TEXTURE BAKING API
409 // If you use this API, you only have to call two functions ever.
414 unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
415 float xoff,yoff,xadvance;
418 extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
419 float pixel_height, // height of font in pixels
420 unsigned char *pixels, int pw, int ph, // bitmap to be filled in
421 int first_char, int num_chars, // characters to bake
422 stbtt_bakedchar *chardata); // you allocate this, it's num_chars long
423 // if return is positive, the first unused row of the bitmap
424 // if return is negative, returns the negative of the number of characters that fit
425 // if return is 0, no characters fit and no rows were used
426 // This uses a very crappy packing.
430 float x0,y0,s0,t0; // top-left
431 float x1,y1,s1,t1; // bottom-right
432 } stbtt_aligned_quad;
434 extern void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, // same data as above
435 int char_index, // character to display
436 float *xpos, float *ypos, // pointers to current position in screen pixel space
437 stbtt_aligned_quad *q, // output: quad to draw
438 int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier
439 // Call GetBakedQuad with char_index = 'character - first_char', and it
440 // creates the quad you need to draw and advances the current position.
442 // The coordinate system used assumes y increases downwards.
444 // Characters will extend both above and below the current position;
445 // see discussion of "BASELINE" above.
447 // It's inefficient; you might want to c&p it and optimize it.
450 //////////////////////////////////////////////////////////////////////////////
456 extern int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
457 // Each .ttf/.ttc file may have more than one font. Each font has a sequential
458 // index number starting from 0. Call this function to get the font offset for
459 // a given index; it returns -1 if the index is out of range. A regular .ttf
460 // file will only define one font and it always be at offset 0, so it will
461 // return '0' for index 0, and -1 for all other indices. You can just skip
462 // this step if you know it's that kind of font.
465 // The following structure is defined publically so you can declare one on
466 // the stack or as a global or etc, but you should treat it as opaque.
467 typedef struct stbtt_fontinfo
470 unsigned char * data; // pointer to .ttf file
471 int fontstart; // offset of start of font
473 int numGlyphs; // number of glyphs, needed for range checking
475 int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf
476 int index_map; // a cmap mapping for our chosen character encoding
477 int indexToLocFormat; // format needed to map from glyph index to glyph
480 extern int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
481 // Given an offset into the file that defines a font, this function builds
482 // the necessary cached info for the rest of the system. You must allocate
483 // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
484 // need to do anything special to free it, because the contents are pure
485 // value data with no additional data structures. Returns 0 on failure.
488 //////////////////////////////////////////////////////////////////////////////
490 // CHARACTER TO GLYPH-INDEX CONVERSIOn
492 int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
493 // If you're going to perform multiple operations on the same character
494 // and you want a speed-up, call this function with the character you're
495 // going to process, then use glyph-based functions instead of the
496 // codepoint-based functions.
499 //////////////////////////////////////////////////////////////////////////////
501 // CHARACTER PROPERTIES
504 extern float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
505 // computes a scale factor to produce a font whose "height" is 'pixels' tall.
506 // Height is measured as the distance from the highest ascender to the lowest
507 // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
509 // scale = pixels / (ascent - descent)
510 // so if you prefer to measure height by the ascent only, use a similar calculation.
512 extern float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
513 // computes a scale factor to produce a font whose EM size is mapped to
514 // 'pixels' tall. This is probably what traditional APIs compute, but
517 extern void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
518 // ascent is the coordinate above the baseline the font extends; descent
519 // is the coordinate below the baseline the font extends (i.e. it is typically negative)
520 // lineGap is the spacing between one row's descent and the next row's ascent...
521 // so you should advance the vertical position by "*ascent - *descent + *lineGap"
522 // these are expressed in unscaled coordinates, so you must multiply by
523 // the scale factor for a given size
525 extern void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
526 // the bounding box around all possible characters
528 extern void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
529 // leftSideBearing is the offset from the current horizontal position to the left edge of the character
530 // advanceWidth is the offset from the current horizontal position to the next horizontal position
531 // these are expressed in unscaled coordinates
533 extern int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
534 // an additional amount to add to the 'advance' value between ch1 and ch2
535 // @TODO; for now always returns 0!
537 extern int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
538 // Gets the bounding box of the visible part of the glyph, in unscaled coordinates
540 extern void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
541 extern int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
542 extern int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
543 // as above, but takes one or more glyph indices for greater efficiency
546 //////////////////////////////////////////////////////////////////////////////
548 // GLYPH SHAPES (you probably don't need these, but they have to go before
549 // the bitmaps for C declaration-order reasons)
552 #ifndef STBTT_vmove // you can predefine these to use different values (but why?)
560 #ifndef stbtt_vertex // you can predefine this to use different values
561 // (we share this with other code at RAD)
562 #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
565 stbtt_vertex_type x,y,cx,cy;
566 unsigned char type,padding;
570 extern int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
571 // returns non-zero if nothing is drawn for this glyph
573 extern int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
574 extern int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
575 // returns # of vertices and fills *vertices with the pointer to them
576 // these are expressed in "unscaled" coordinates
578 extern void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
579 // frees the data allocated above
581 //////////////////////////////////////////////////////////////////////////////
586 extern void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
587 // frees the bitmap allocated below
589 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);
590 // allocates a large-enough single-channel 8bpp bitmap and renders the
591 // specified character/glyph at the specified scale into it, with
592 // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
593 // *width & *height are filled out with the width & height of the bitmap,
594 // which is stored left-to-right, top-to-bottom.
596 // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
598 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);
599 // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
600 // shift for the character
602 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);
603 // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
604 // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
605 // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
606 // width and height and positioning info for it first.
608 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);
609 // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
610 // shift for the character
612 extern void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
613 // get the bbox of the bitmap centered around the glyph origin; so the
614 // bitmap width is ix1-ix0, height is iy1-iy0, and location to place
615 // the bitmap top left is (leftSideBearing*scale,iy0).
616 // (Note that the bitmap uses y-increases-down, but the shape uses
617 // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
619 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);
620 // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
621 // shift for the character
623 // the following functions are equivalent to the above functions, but operate
624 // on glyph indices instead of Unicode codepoints (for efficiency)
625 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);
626 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);
627 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);
628 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);
629 extern void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
630 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);
633 // @TODO: don't expose this structure
637 unsigned char *pixels;
640 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);
642 //////////////////////////////////////////////////////////////////////////////
644 // Finding the right font...
646 // You should really just solve this offline, keep your own tables
647 // of what font is what, and don't try to get it out of the .ttf file.
648 // That's because getting it out of the .ttf file is really hard, because
649 // the names in the file can appear in many possible encodings, in many
650 // possible languages, and e.g. if you need a case-insensitive comparison,
651 // the details of that depend on the encoding & language in a complex way
652 // (actually underspecified in truetype, but also gigantic).
654 // But you can use the provided functions in two possible ways:
655 // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
656 // unicode-encoded names to try to find the font you want;
657 // you can run this before calling stbtt_InitFont()
659 // stbtt_GetFontNameString() lets you get any of the various strings
660 // from the file yourself and do your own comparisons on them.
661 // You have to have called stbtt_InitFont() first.
664 extern int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
665 // returns the offset (not index) of the font that matches, or -1 if none
666 // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
667 // if you use any other flag, use a font name like "Arial"; this checks
668 // the 'macStyle' header field; i don't know if fonts set this consistently
669 #define STBTT_MACSTYLE_DONTCARE 0
670 #define STBTT_MACSTYLE_BOLD 1
671 #define STBTT_MACSTYLE_ITALIC 2
672 #define STBTT_MACSTYLE_UNDERSCORE 4
673 #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0
675 extern int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
676 // returns 1/0 whether the first string interpreted as utf8 is identical to
677 // the second string interpreted as big-endian utf16... useful for strings from next func
679 extern const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
680 // returns the string (which may be big-endian double byte, e.g. for unicode)
681 // and puts the length in bytes in *length.
683 // some of the values for the IDs are below; for more see the truetype spec:
684 // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
685 // http://www.microsoft.com/typography/otspec/name.htm
688 STBTT_PLATFORM_ID_UNICODE =0,
689 STBTT_PLATFORM_ID_MAC =1,
690 STBTT_PLATFORM_ID_ISO =2,
691 STBTT_PLATFORM_ID_MICROSOFT =3
694 enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
695 STBTT_UNICODE_EID_UNICODE_1_0 =0,
696 STBTT_UNICODE_EID_UNICODE_1_1 =1,
697 STBTT_UNICODE_EID_ISO_10646 =2,
698 STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
699 STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
702 enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
703 STBTT_MS_EID_SYMBOL =0,
704 STBTT_MS_EID_UNICODE_BMP =1,
705 STBTT_MS_EID_SHIFTJIS =2,
706 STBTT_MS_EID_UNICODE_FULL =10
709 enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
710 STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4,
711 STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5,
712 STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6,
713 STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7
716 enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
717 // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
718 STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410,
719 STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411,
720 STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412,
721 STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419,
722 STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409,
723 STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D
726 enum { // languageID for STBTT_PLATFORM_ID_MAC
727 STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11,
728 STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23,
729 STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32,
730 STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 ,
731 STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 ,
732 STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
733 STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19
740 #endif // __STB_INCLUDE_STB_TRUETYPE_H__
742 ///////////////////////////////////////////////////////////////////////////////
743 ///////////////////////////////////////////////////////////////////////////////
749 #ifdef STB_TRUETYPE_IMPLEMENTATION
751 //////////////////////////////////////////////////////////////////////////
753 // accessors to parse data from file
756 // on platforms that don't allow misaligned reads, if we want to allow
757 // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
759 #define ttBYTE(p) (* (stbtt_uint8 *) (p))
760 #define ttCHAR(p) (* (stbtt_int8 *) (p))
761 #define ttFixed(p) ttLONG(p)
763 #if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE)
765 #define ttUSHORT(p) (* (stbtt_uint16 *) (p))
766 #define ttSHORT(p) (* (stbtt_int16 *) (p))
767 #define ttULONG(p) (* (stbtt_uint32 *) (p))
768 #define ttLONG(p) (* (stbtt_int32 *) (p))
772 stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
773 stbtt_int16 ttSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
774 stbtt_uint32 ttULONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
775 stbtt_int32 ttLONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
779 #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
780 #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])
782 static int stbtt__isfont(const stbtt_uint8 *font)
784 // check the version number
785 if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1
786 if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!
787 if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF
788 if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
792 // @OPTIMIZE: binary search
793 static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
795 stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
796 stbtt_uint32 tabledir = fontstart + 12;
798 for (i=0; i < num_tables; ++i) {
799 stbtt_uint32 loc = tabledir + 16*i;
800 if (stbtt_tag(data+loc+0, tag))
801 return ttULONG(data+loc+8);
806 int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, int index)
808 // if it's just a font, there's only one valid index
809 if (stbtt__isfont(font_collection))
810 return index == 0 ? 0 : -1;
812 // check if it's a TTC
813 if (stbtt_tag(font_collection, "ttcf")) {
815 if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
816 stbtt_int32 n = ttLONG(font_collection+8);
819 return ttULONG(font_collection+12+index*14);
825 int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart)
827 stbtt_uint8 *data = (stbtt_uint8 *) data2;
828 stbtt_uint32 cmap, t;
829 stbtt_int32 i,numTables;
832 info->fontstart = fontstart;
834 cmap = stbtt__find_table(data, fontstart, "cmap"); // required
835 info->loca = stbtt__find_table(data, fontstart, "loca"); // required
836 info->head = stbtt__find_table(data, fontstart, "head"); // required
837 info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
838 info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
839 info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
840 info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
841 if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx)
844 t = stbtt__find_table(data, fontstart, "maxp");
846 info->numGlyphs = ttUSHORT(data+t+4);
848 info->numGlyphs = 0xffff;
850 // find a cmap encoding table we understand *now* to avoid searching
851 // later. (todo: could make this installable)
852 // the same regardless of glyph.
853 numTables = ttUSHORT(data + cmap + 2);
855 for (i=0; i < numTables; ++i) {
856 stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
857 // find an encoding we understand:
858 switch(ttUSHORT(data+encoding_record)) {
859 case STBTT_PLATFORM_ID_MICROSOFT:
860 switch (ttUSHORT(data+encoding_record+2)) {
861 case STBTT_MS_EID_UNICODE_BMP:
862 case STBTT_MS_EID_UNICODE_FULL:
864 info->index_map = cmap + ttULONG(data+encoding_record+4);
870 if (info->index_map == 0)
873 info->indexToLocFormat = ttUSHORT(data+info->head + 50);
877 int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
879 stbtt_uint8 *data = info->data;
880 stbtt_uint32 index_map = info->index_map;
882 stbtt_uint16 format = ttUSHORT(data + index_map + 0);
883 if (format == 0) { // apple byte encoding
884 stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
885 if (unicode_codepoint < bytes-6)
886 return ttBYTE(data + index_map + 6 + unicode_codepoint);
888 } else if (format == 6) {
889 stbtt_uint32 first = ttUSHORT(data + index_map + 6);
890 stbtt_uint32 count = ttUSHORT(data + index_map + 8);
891 if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
892 return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
894 } else if (format == 2) {
895 STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
897 } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges
898 stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
899 stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
900 stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
901 stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
902 stbtt_uint16 item, offset, start, end;
904 // do a binary search of the segments
905 stbtt_uint32 endCount = index_map + 14;
906 stbtt_uint32 search = endCount;
908 if (unicode_codepoint > 0xffff)
911 // they lie from endCount .. endCount + segCount
912 // but searchRange is the nearest power of two, so...
913 if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
914 search += rangeShift*2;
916 // now decrement to bias correctly to find smallest
918 while (entrySelector) {
919 stbtt_uint16 start, end;
921 start = ttUSHORT(data + search + 2 + segcount*2 + 2);
922 end = ttUSHORT(data + search + 2);
923 start = ttUSHORT(data + search + searchRange*2 + segcount*2 + 2);
924 end = ttUSHORT(data + search + searchRange*2);
925 if (unicode_codepoint > end)
926 search += searchRange*2;
931 item = (stbtt_uint16) ((search - endCount) >> 1);
933 STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
934 start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
935 end = ttUSHORT(data + index_map + 14 + 2 + 2*item);
936 if (unicode_codepoint < start)
939 offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
941 return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
943 return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
944 } else if (format == 12 || format == 13) {
945 stbtt_uint32 ngroups = ttULONG(data+index_map+12);
946 stbtt_int32 low,high;
947 low = 0; high = (stbtt_int32)ngroups;
948 // Binary search the right group.
950 stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high
951 stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
952 stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
953 if ((stbtt_uint32) unicode_codepoint < start_char)
955 else if ((stbtt_uint32) unicode_codepoint > end_char)
958 stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
960 return start_glyph + unicode_codepoint-start_char;
965 return 0; // not found
972 int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
974 return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
977 static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
980 v->x = (stbtt_int16) x;
981 v->y = (stbtt_int16) y;
982 v->cx = (stbtt_int16) cx;
983 v->cy = (stbtt_int16) cy;
986 static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
990 if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
991 if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format
993 if (info->indexToLocFormat == 0) {
994 g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
995 g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
997 g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
998 g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
1001 return g1==g2 ? -1 : g1; // if length is 0, return -1
1004 int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
1006 int g = stbtt__GetGlyfOffset(info, glyph_index);
1007 if (g < 0) return 0;
1009 if (x0) *x0 = ttSHORT(info->data + g + 2);
1010 if (y0) *y0 = ttSHORT(info->data + g + 4);
1011 if (x1) *x1 = ttSHORT(info->data + g + 6);
1012 if (y1) *y1 = ttSHORT(info->data + g + 8);
1016 int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
1018 return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
1021 int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
1023 stbtt_int16 numberOfContours;
1024 int g = stbtt__GetGlyfOffset(info, glyph_index);
1025 if (g < 0) return 1;
1026 numberOfContours = ttSHORT(info->data + g);
1027 return numberOfContours == 0;
1030 static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
1031 stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
1035 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
1036 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
1039 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
1041 stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
1043 return num_vertices;
1046 int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
1048 stbtt_int16 numberOfContours;
1049 stbtt_uint8 *endPtsOfContours;
1050 stbtt_uint8 *data = info->data;
1051 stbtt_vertex *vertices=0;
1053 int g = stbtt__GetGlyfOffset(info, glyph_index);
1057 if (g < 0) return 0;
1059 numberOfContours = ttSHORT(data + g);
1061 if (numberOfContours > 0) {
1062 stbtt_uint8 flags=0,flagcount;
1063 stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
1064 stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
1065 stbtt_uint8 *points;
1066 endPtsOfContours = (data + g + 10);
1067 ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
1068 points = data + g + 10 + numberOfContours * 2 + 2 + ins;
1070 n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
1072 m = n + 2*numberOfContours; // a loose bound on how many vertices we might need
1073 vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
1080 // in first pass, we load uninterpreted data into the allocated array
1081 // above, shifted to the end of the array so we won't overwrite it when
1082 // we create our final data starting from the front
1084 off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
1088 for (i=0; i < n; ++i) {
1089 if (flagcount == 0) {
1092 flagcount = *points++;
1095 vertices[off+i].type = flags;
1098 // now load x coordinates
1100 for (i=0; i < n; ++i) {
1101 flags = vertices[off+i].type;
1103 stbtt_int16 dx = *points++;
1104 x += (flags & 16) ? dx : -dx; // ???
1106 if (!(flags & 16)) {
1107 x = x + (stbtt_int16) (points[0]*256 + points[1]);
1111 vertices[off+i].x = (stbtt_int16) x;
1114 // now load y coordinates
1116 for (i=0; i < n; ++i) {
1117 flags = vertices[off+i].type;
1119 stbtt_int16 dy = *points++;
1120 y += (flags & 32) ? dy : -dy; // ???
1122 if (!(flags & 32)) {
1123 y = y + (stbtt_int16) (points[0]*256 + points[1]);
1127 vertices[off+i].y = (stbtt_int16) y;
1130 // now convert them to our format
1132 sx = sy = cx = cy = scx = scy = 0;
1133 for (i=0; i < n; ++i) {
1134 flags = vertices[off+i].type;
1135 x = (stbtt_int16) vertices[off+i].x;
1136 y = (stbtt_int16) vertices[off+i].y;
1138 if (next_move == i) {
1140 num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
1142 // now start the new one
1143 start_off = !(flags & 1);
1145 // if we start off with an off-curve point, then when we need to find a point on the curve
1146 // where we can start, and we need to save some state for when we wraparound.
1149 if (!(vertices[off+i+1].type & 1)) {
1150 // next point is also a curve point, so interpolate an on-point curve
1151 sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
1152 sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
1154 // otherwise just use the next point as our start point
1155 sx = (stbtt_int32) vertices[off+i+1].x;
1156 sy = (stbtt_int32) vertices[off+i+1].y;
1157 ++i; // we're using point i+1 as the starting point, so skip it
1163 stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
1165 next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
1168 if (!(flags & 1)) { // if it's a curve
1169 if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
1170 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
1176 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
1178 stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
1183 num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
1184 } else if (numberOfContours == -1) {
1187 stbtt_uint8 *comp = data + g + 10;
1191 stbtt_uint16 flags, gidx;
1192 int comp_num_verts = 0, i;
1193 stbtt_vertex *comp_verts = 0, *tmp = 0;
1194 float mtx[6] = {1,0,0,1,0,0}, m, n;
1196 flags = ttSHORT(comp); comp+=2;
1197 gidx = ttSHORT(comp); comp+=2;
1199 if (flags & 2) { // XY values
1200 if (flags & 1) { // shorts
1201 mtx[4] = ttSHORT(comp); comp+=2;
1202 mtx[5] = ttSHORT(comp); comp+=2;
1204 mtx[4] = ttCHAR(comp); comp+=1;
1205 mtx[5] = ttCHAR(comp); comp+=1;
1209 // @TODO handle matching point
1212 if (flags & (1<<3)) { // WE_HAVE_A_SCALE
1213 mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1214 mtx[1] = mtx[2] = 0;
1215 } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
1216 mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
1217 mtx[1] = mtx[2] = 0;
1218 mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1219 } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
1220 mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
1221 mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
1222 mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
1223 mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1226 // Find transformation scales.
1227 m = (float) sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
1228 n = (float) sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
1230 // Get indexed glyph.
1231 comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
1232 if (comp_num_verts > 0) {
1233 // Transform vertices.
1234 for (i = 0; i < comp_num_verts; ++i) {
1235 stbtt_vertex* v = &comp_verts[i];
1236 stbtt_vertex_type x,y;
1238 v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
1239 v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
1241 v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
1242 v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
1245 tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
1247 if (vertices) STBTT_free(vertices, info->userdata);
1248 if (comp_verts) STBTT_free(comp_verts, info->userdata);
1251 if (num_vertices > 0) memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));
1252 memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
1253 if (vertices) STBTT_free(vertices, info->userdata);
1255 STBTT_free(comp_verts, info->userdata);
1256 num_vertices += comp_num_verts;
1258 // More components ?
1259 more = flags & (1<<5);
1261 } else if (numberOfContours < 0) {
1262 // @TODO other compound variations?
1265 // numberOfCounters == 0, do nothing
1268 *pvertices = vertices;
1269 return num_vertices;
1272 void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
1274 stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
1275 if (glyph_index < numOfLongHorMetrics) {
1276 if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index);
1277 if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
1279 if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
1280 if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
1284 int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
1286 stbtt_uint8 *data = info->data + info->kern;
1287 stbtt_uint32 needle, straw;
1290 // we only look at the first table. it must be 'horizontal' and format 0.
1293 if (ttUSHORT(data+2) < 1) // number of tables, need at least 1
1295 if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format
1299 r = ttUSHORT(data+10) - 1;
1300 needle = glyph1 << 16 | glyph2;
1303 straw = ttULONG(data+18+(m*6)); // note: unaligned read
1306 else if (needle > straw)
1309 return ttSHORT(data+22+(m*6));
1314 int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
1316 if (!info->kern) // if no kerning table, don't waste time looking up both codepoint->glyphs
1318 return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
1321 void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
1323 stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
1326 void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
1328 if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4);
1329 if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
1330 if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
1333 void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
1335 *x0 = ttSHORT(info->data + info->head + 36);
1336 *y0 = ttSHORT(info->data + info->head + 38);
1337 *x1 = ttSHORT(info->data + info->head + 40);
1338 *y1 = ttSHORT(info->data + info->head + 42);
1341 float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
1343 int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
1344 return (float) height / fheight;
1347 float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
1349 int unitsPerEm = ttUSHORT(info->data + info->head + 18);
1350 return pixels / unitsPerEm;
1353 void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
1355 STBTT_free(v, info->userdata);
1358 //////////////////////////////////////////////////////////////////////////////
1360 // antialiasing software rasterizer
1363 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)
1366 if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1))
1367 x0=y0=x1=y1=0; // e.g. space character
1368 // now move to integral bboxes (treating pixels as little squares, what pixels get touched)?
1369 if (ix0) *ix0 = STBTT_ifloor(x0 * scale_x + shift_x);
1370 if (iy0) *iy0 = -STBTT_iceil (y1 * scale_y + shift_y);
1371 if (ix1) *ix1 = STBTT_iceil (x1 * scale_x + shift_x);
1372 if (iy1) *iy1 = -STBTT_ifloor(y0 * scale_y + shift_y);
1374 void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
1376 stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
1379 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)
1381 stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
1384 void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
1386 stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
1389 typedef struct stbtt__edge {
1394 typedef struct stbtt__active_edge
1398 struct stbtt__active_edge *next;
1400 } stbtt__active_edge;
1403 #define FIX (1 << FIXSHIFT)
1404 #define FIXMASK (FIX-1)
1406 static stbtt__active_edge *new_active(stbtt__edge *e, int off_x, float start_point, void *userdata)
1408 stbtt__active_edge *z = (stbtt__active_edge *) STBTT_malloc(sizeof(*z), userdata); // @TODO: make a pool of these!!!
1409 float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
1410 STBTT_assert(e->y0 <= start_point);
1412 // round dx down to avoid going too far
1414 z->dx = -STBTT_ifloor(FIX * -dxdy);
1416 z->dx = STBTT_ifloor(FIX * dxdy);
1417 z->x = STBTT_ifloor(FIX * (e->x0 + dxdy * (start_point - e->y0)));
1418 z->x -= off_x * FIX;
1421 z->valid = e->invert ? 1 : -1;
1425 // note: this routine clips fills that extend off the edges... ideally this
1426 // wouldn't happen, but it could happen if the truetype glyph bounding boxes
1427 // are wrong, or if the user supplies a too-small bitmap
1428 static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
1430 // non-zero winding fill
1435 // if we're currently at zero, we need to record the edge start point
1436 x0 = e->x; w += e->valid;
1438 int x1 = e->x; w += e->valid;
1439 // if we went to zero, we need to draw
1441 int i = x0 >> FIXSHIFT;
1442 int j = x1 >> FIXSHIFT;
1444 if (i < len && j >= 0) {
1446 // x0,x1 are the same pixel, so compute combined coverage
1447 scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> FIXSHIFT);
1449 if (i >= 0) // add antialiasing for x0
1450 scanline[i] = scanline[i] + (stbtt_uint8) (((FIX - (x0 & FIXMASK)) * max_weight) >> FIXSHIFT);
1454 if (j < len) // add antialiasing for x1
1455 scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & FIXMASK) * max_weight) >> FIXSHIFT);
1459 for (++i; i < j; ++i) // fill pixels between x0 and x1
1460 scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
1470 static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
1472 stbtt__active_edge *active = NULL;
1474 int max_weight = (255 / vsubsample); // weight per vertical scanline
1475 int s; // vertical subsample index
1476 unsigned char scanline_data[512], *scanline;
1478 if (result->w > 512)
1479 scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
1481 scanline = scanline_data;
1483 y = off_y * vsubsample;
1484 e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
1486 while (j < result->h) {
1487 STBTT_memset(scanline, 0, result->w);
1488 for (s=0; s < vsubsample; ++s) {
1489 // find center of pixel for this scanline
1490 float scan_y = y + 0.5f;
1491 stbtt__active_edge **step = &active;
1493 // update all active edges;
1494 // remove all active edges that terminate before the center of this scanline
1496 stbtt__active_edge * z = *step;
1497 if (z->ey <= scan_y) {
1498 *step = z->next; // delete from list
1499 STBTT_assert(z->valid);
1501 STBTT_free(z, userdata);
1503 z->x += z->dx; // advance to position for current scanline
1504 step = &((*step)->next); // advance through list
1508 // resort the list if needed
1512 while (*step && (*step)->next) {
1513 if ((*step)->x > (*step)->next->x) {
1514 stbtt__active_edge *t = *step;
1515 stbtt__active_edge *q = t->next;
1522 step = &(*step)->next;
1524 if (!changed) break;
1527 // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
1528 while (e->y0 <= scan_y) {
1529 if (e->y1 > scan_y) {
1530 stbtt__active_edge *z = new_active(e, off_x, scan_y, userdata);
1531 // find insertion point
1534 else if (z->x < active->x) {
1539 // find thing to insert AFTER
1540 stbtt__active_edge *p = active;
1541 while (p->next && p->next->x < z->x)
1543 // at this point, p->next->x is NOT < z->x
1551 // now process all active edges in XOR fashion
1553 stbtt__fill_active_edges(scanline, result->w, active, max_weight);
1557 STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
1562 stbtt__active_edge *z = active;
1563 active = active->next;
1564 STBTT_free(z, userdata);
1567 if (scanline != scanline_data)
1568 STBTT_free(scanline, userdata);
1571 static int stbtt__edge_compare(const void *p, const void *q)
1573 stbtt__edge *a = (stbtt__edge *) p;
1574 stbtt__edge *b = (stbtt__edge *) q;
1576 if (a->y0 < b->y0) return -1;
1577 if (a->y0 > b->y0) return 1;
1586 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)
1588 float y_scale_inv = invert ? -scale_y : scale_y;
1591 int vsubsample = result->h < 8 ? 15 : 5;
1592 // vsubsample should divide 255 evenly; otherwise we won't reach full opacity
1594 // now we have to blow out the windings into explicit edge lists
1596 for (i=0; i < windings; ++i)
1599 e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel
1604 for (i=0; i < windings; ++i) {
1605 stbtt__point *p = pts + m;
1608 for (k=0; k < wcount[i]; j=k++) {
1610 // skip the edge if horizontal
1611 if (p[j].y == p[k].y)
1613 // add edge from j to k to the list
1615 if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
1619 e[n].x0 = p[a].x * scale_x + shift_x;
1620 e[n].y0 = p[a].y * y_scale_inv * vsubsample + shift_y;
1621 e[n].x1 = p[b].x * scale_x + shift_x;
1622 e[n].y1 = p[b].y * y_scale_inv * vsubsample + shift_y;
1627 // now sort the edges by their highest point (should snap to integer, and then by x)
1628 STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
1630 // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
1631 stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
1633 STBTT_free(e, userdata);
1636 static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
1638 if (!points) return; // during first pass, it's unallocated
1643 // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching
1644 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)
1647 float mx = (x0 + 2*x1 + x2)/4;
1648 float my = (y0 + 2*y1 + y2)/4;
1649 // versus directly drawn line
1650 float dx = (x0+x2)/2 - mx;
1651 float dy = (y0+y2)/2 - my;
1652 if (n > 16) // 65536 segments on one curve better be enough!
1654 if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
1655 stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
1656 stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
1658 stbtt__add_point(points, *num_points,x2,y2);
1659 *num_points = *num_points+1;
1664 // returns number of contours
1665 stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
1667 stbtt__point *points=0;
1670 float objspace_flatness_squared = objspace_flatness * objspace_flatness;
1671 int i,n=0,start=0, pass;
1673 // count how many "moves" there are to get the contour count
1674 for (i=0; i < num_verts; ++i)
1675 if (vertices[i].type == STBTT_vmove)
1679 if (n == 0) return 0;
1681 *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
1683 if (*contour_lengths == 0) {
1688 // make two passes through the points so we don't need to realloc
1689 for (pass=0; pass < 2; ++pass) {
1692 points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
1693 if (points == NULL) goto error;
1697 for (i=0; i < num_verts; ++i) {
1698 switch (vertices[i].type) {
1700 // start the next contour
1702 (*contour_lengths)[n] = num_points - start;
1706 x = vertices[i].x, y = vertices[i].y;
1707 stbtt__add_point(points, num_points++, x,y);
1710 x = vertices[i].x, y = vertices[i].y;
1711 stbtt__add_point(points, num_points++, x, y);
1714 stbtt__tesselate_curve(points, &num_points, x,y,
1715 vertices[i].cx, vertices[i].cy,
1716 vertices[i].x, vertices[i].y,
1717 objspace_flatness_squared, 0);
1718 x = vertices[i].x, y = vertices[i].y;
1722 (*contour_lengths)[n] = num_points - start;
1727 STBTT_free(points, userdata);
1728 STBTT_free(*contour_lengths, userdata);
1729 *contour_lengths = 0;
1734 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)
1736 float scale = scale_x > scale_y ? scale_y : scale_x;
1737 int winding_count, *winding_lengths;
1738 stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
1740 stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
1741 STBTT_free(winding_lengths, userdata);
1742 STBTT_free(windings, userdata);
1746 void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
1748 STBTT_free(bitmap, userdata);
1751 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)
1753 int ix0,iy0,ix1,iy1;
1755 stbtt_vertex *vertices;
1756 int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
1758 if (scale_x == 0) scale_x = scale_y;
1760 if (scale_x == 0) return NULL;
1764 stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
1766 // now we get the size
1767 gbm.w = (ix1 - ix0);
1768 gbm.h = (iy1 - iy0);
1769 gbm.pixels = NULL; // in case we error
1771 if (width ) *width = gbm.w;
1772 if (height) *height = gbm.h;
1773 if (xoff ) *xoff = ix0;
1774 if (yoff ) *yoff = iy0;
1776 if (gbm.w && gbm.h) {
1777 gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
1781 stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
1784 STBTT_free(vertices, info->userdata);
1788 unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)
1790 return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
1793 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)
1796 stbtt_vertex *vertices;
1797 int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
1800 stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
1801 gbm.pixels = output;
1804 gbm.stride = out_stride;
1807 stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
1809 STBTT_free(vertices, info->userdata);
1812 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)
1814 stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
1817 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)
1819 return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
1822 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)
1824 stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
1827 unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
1829 return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
1832 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)
1834 stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
1837 //////////////////////////////////////////////////////////////////////////////
1841 // This is SUPER-CRAPPY packing to keep source code small
1843 extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
1844 float pixel_height, // height of font in pixels
1845 unsigned char *pixels, int pw, int ph, // bitmap to be filled in
1846 int first_char, int num_chars, // characters to bake
1847 stbtt_bakedchar *chardata)
1850 int x,y,bottom_y, i;
1852 stbtt_InitFont(&f, data, offset);
1853 STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
1857 scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
1859 for (i=0; i < num_chars; ++i) {
1860 int advance, lsb, x0,y0,x1,y1,gw,gh;
1861 int g = stbtt_FindGlyphIndex(&f, first_char + i);
1862 stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
1863 stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
1866 if (x + gw + 1 >= pw)
1867 y = bottom_y, x = 1; // advance to next row
1868 if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
1870 STBTT_assert(x+gw < pw);
1871 STBTT_assert(y+gh < ph);
1872 stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
1873 chardata[i].x0 = (stbtt_int16) x;
1874 chardata[i].y0 = (stbtt_int16) y;
1875 chardata[i].x1 = (stbtt_int16) (x + gw);
1876 chardata[i].y1 = (stbtt_int16) (y + gh);
1877 chardata[i].xadvance = scale * advance;
1878 chardata[i].xoff = (float) x0;
1879 chardata[i].yoff = (float) y0;
1881 if (y+gh+2 > bottom_y)
1887 void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
1889 float d3d_bias = opengl_fillrule ? 0 : -0.5f;
1890 float ipw = 1.0f / pw, iph = 1.0f / ph;
1891 stbtt_bakedchar *b = chardata + char_index;
1892 int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5);
1893 int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5);
1895 q->x0 = round_x + d3d_bias;
1896 q->y0 = round_y + d3d_bias;
1897 q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
1898 q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
1900 q->s0 = b->x0 * ipw;
1901 q->t0 = b->y0 * iph;
1902 q->s1 = b->x1 * ipw;
1903 q->t1 = b->y1 * iph;
1905 *xpos += b->xadvance;
1908 //////////////////////////////////////////////////////////////////////////////
1910 // font name matching -- recommended not to use this
1913 // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
1914 static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(const stbtt_uint8 *s1, stbtt_int32 len1, const stbtt_uint8 *s2, stbtt_int32 len2)
1918 // convert utf16 to utf8 and compare the results while converting
1920 stbtt_uint16 ch = s2[0]*256 + s2[1];
1922 if (i >= len1) return -1;
1923 if (s1[i++] != ch) return -1;
1924 } else if (ch < 0x800) {
1925 if (i+1 >= len1) return -1;
1926 if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
1927 if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
1928 } else if (ch >= 0xd800 && ch < 0xdc00) {
1930 stbtt_uint16 ch2 = s2[2]*256 + s2[3];
1931 if (i+3 >= len1) return -1;
1932 c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
1933 if (s1[i++] != 0xf0 + (c >> 18)) return -1;
1934 if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
1935 if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1;
1936 if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1;
1937 s2 += 2; // plus another 2 below
1939 } else if (ch >= 0xdc00 && ch < 0xe000) {
1942 if (i+2 >= len1) return -1;
1943 if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
1944 if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
1945 if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1;
1953 int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
1955 return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((const stbtt_uint8*) s1, len1, (const stbtt_uint8*) s2, len2);
1958 // returns results in whatever encoding you request... but note that 2-byte encodings
1959 // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
1960 const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
1962 stbtt_int32 i,count,stringOffset;
1963 stbtt_uint8 *fc = font->data;
1964 stbtt_uint32 offset = font->fontstart;
1965 stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
1966 if (!nm) return NULL;
1968 count = ttUSHORT(fc+nm+2);
1969 stringOffset = nm + ttUSHORT(fc+nm+4);
1970 for (i=0; i < count; ++i) {
1971 stbtt_uint32 loc = nm + 6 + 12 * i;
1972 if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
1973 && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
1974 *length = ttUSHORT(fc+loc+8);
1975 return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
1981 static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
1984 stbtt_int32 count = ttUSHORT(fc+nm+2);
1985 stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
1987 for (i=0; i < count; ++i) {
1988 stbtt_uint32 loc = nm + 6 + 12 * i;
1989 stbtt_int32 id = ttUSHORT(fc+loc+6);
1990 if (id == target_id) {
1991 // find the encoding
1992 stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
1994 // is this a Unicode encoding?
1995 if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
1996 stbtt_int32 slen = ttUSHORT(fc+loc+8), off = ttUSHORT(fc+loc+10);
1998 // check if there's a prefix match
1999 stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
2000 if (matchlen >= 0) {
2001 // check for target_id+1 immediately following, with same encoding & language
2002 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) {
2003 stbtt_int32 slen = ttUSHORT(fc+loc+12+8), off = ttUSHORT(fc+loc+12+10);
2005 if (matchlen == nlen)
2007 } else if (matchlen < nlen && name[matchlen] == ' ') {
2009 if (stbtt_CompareUTF8toUTF16_bigendian((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
2013 // if nothing immediately following
2014 if (matchlen == nlen)
2020 // @TODO handle other encodings
2026 static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
2028 stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
2030 if (!stbtt__isfont(fc+offset)) return 0;
2032 // check italics/bold/underline flags in macStyle...
2034 hd = stbtt__find_table(fc, offset, "head");
2035 if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
2038 nm = stbtt__find_table(fc, offset, "name");
2042 // if we checked the macStyle flags, then just check the family and ignore the subfamily
2043 if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1;
2044 if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1;
2045 if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
2047 if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1;
2048 if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1;
2049 if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
2055 int stbtt_FindMatchingFont(const unsigned char *font_collection, const char *name_utf8, stbtt_int32 flags)
2059 stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
2060 if (off < 0) return off;
2061 if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
2066 #endif // STB_TRUETYPE_IMPLEMENTATION