stb_truetype.h (38851B)
1 // stb_truetype.h - v1.26 - public domain 2 // authored from 2009-2021 by Sean Barrett / RAD Game Tools 3 // 4 // ======================================================================= 5 // 6 // NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES 7 // 8 // This library does no range checking of the offsets found in the file, 9 // meaning an attacker can use it to read arbitrary memory. 10 // 11 // ======================================================================= 12 // 13 // This library processes TrueType files: 14 // parse files 15 // extract glyph metrics 16 // extract glyph shapes 17 // render glyphs to one-channel bitmaps with antialiasing (box filter) 18 // render glyphs to one-channel SDF bitmaps (signed-distance field/function) 19 // 20 // Todo: 21 // non-MS cmaps 22 // crashproof on bad data 23 // hinting? (no longer patented) 24 // cleartype-style AA? 25 // optimize: use simple memory allocator for intermediates 26 // optimize: build edge-list directly from curves 27 // optimize: rasterize directly from curves? 28 // 29 // ADDITIONAL CONTRIBUTORS 30 // 31 // Mikko Mononen: compound shape support, more cmap formats 32 // Tor Andersson: kerning, subpixel rendering 33 // Dougall Johnson: OpenType / Type 2 font handling 34 // Daniel Ribeiro Maciel: basic GPOS-based kerning 35 // 36 // Misc other: 37 // Ryan Gordon 38 // Simon Glass 39 // github:IntellectualKitty 40 // Imanol Celaya 41 // Daniel Ribeiro Maciel 42 // 43 // Bug/warning reports/fixes: 44 // "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe 45 // Cass Everitt Martins Mozeiko github:aloucks 46 // stoiko (Haemimont Games) Cap Petschulat github:oyvindjam 47 // Brian Hook Omar Cornut github:vassvik 48 // Walter van Niftrik Ryan Griege 49 // David Gow Peter LaValle 50 // David Given Sergey Popov 51 // Ivan-Assen Ivanov Giumo X. Clanjor 52 // Anthony Pesch Higor Euripedes 53 // Johan Duparc Thomas Fields 54 // Hou Qiming Derek Vinyard 55 // Rob Loach Cort Stratton 56 // Kenney Phillis Jr. Brian Costabile 57 // Ken Voskuil (kaesve) 58 // 59 // VERSION HISTORY 60 // 61 // 1.26 (2021-08-28) fix broken rasterizer 62 // 1.25 (2021-07-11) many fixes 63 // 1.24 (2020-02-05) fix warning 64 // 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) 65 // 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined 66 // 1.21 (2019-02-25) fix warning 67 // 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() 68 // 1.19 (2018-02-11) GPOS kerning, STBTT_fmod 69 // 1.18 (2018-01-29) add missing function 70 // 1.17 (2017-07-23) make more arguments const; doc fix 71 // 1.16 (2017-07-12) SDF support 72 // 1.15 (2017-03-03) make more arguments const 73 // 1.14 (2017-01-16) num-fonts-in-TTC function 74 // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts 75 // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual 76 // 1.11 (2016-04-02) fix unused-variable warning 77 // 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef 78 // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly 79 // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges 80 // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; 81 // variant PackFontRanges to pack and render in separate phases; 82 // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); 83 // fixed an assert() bug in the new rasterizer 84 // replace assert() with STBTT_assert() in new rasterizer 85 // 86 // Full history can be found at the end of this file. 87 // 88 // LICENSE 89 // 90 // See end of file for license information. 91 92 /////////////////////////////////////////////////////////////////////////////// 93 /////////////////////////////////////////////////////////////////////////////// 94 //// 95 //// INTERFACE 96 //// 97 //// 98 99 #ifndef __STB_INCLUDE_STB_TRUETYPE_H__ 100 #define __STB_INCLUDE_STB_TRUETYPE_H__ 101 102 #ifdef STBTT_STATIC 103 #define STBTT_DEF static 104 #else 105 #define STBTT_DEF extern 106 #endif 107 108 #ifdef __cplusplus 109 extern "C" { 110 #endif 111 112 // private structure 113 typedef struct 114 { 115 unsigned char *data; 116 int cursor; 117 int size; 118 } stbtt__buf; 119 120 ////////////////////////////////////////////////////////////////////////////// 121 // 122 // TEXTURE BAKING API 123 // 124 // If you use this API, you only have to call two functions ever. 125 // 126 127 typedef struct 128 { 129 unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap 130 float xoff,yoff,xadvance; 131 } stbtt_bakedchar; 132 133 STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) 134 float pixel_height, // height of font in pixels 135 unsigned char *pixels, int pw, int ph, // bitmap to be filled in 136 int first_char, int num_chars, // characters to bake 137 stbtt_bakedchar *chardata); // you allocate this, it's num_chars long 138 // if return is positive, the first unused row of the bitmap 139 // if return is negative, returns the negative of the number of characters that fit 140 // if return is 0, no characters fit and no rows were used 141 // This uses a very crappy packing. 142 143 typedef struct 144 { 145 float x0,y0,s0,t0; // top-left 146 float x1,y1,s1,t1; // bottom-right 147 } stbtt_aligned_quad; 148 149 STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above 150 int char_index, // character to display 151 float *xpos, float *ypos, // pointers to current position in screen pixel space 152 stbtt_aligned_quad *q, // output: quad to draw 153 int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier 154 // Call GetBakedQuad with char_index = 'character - first_char', and it 155 // creates the quad you need to draw and advances the current position. 156 // 157 // The coordinate system used assumes y increases downwards. 158 // 159 // Characters will extend both above and below the current position; 160 // see discussion of "BASELINE" above. 161 // 162 // It's inefficient; you might want to c&p it and optimize it. 163 164 STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); 165 // Query the font vertical metrics without having to create a font first. 166 167 168 ////////////////////////////////////////////////////////////////////////////// 169 // 170 // NEW TEXTURE BAKING API 171 // 172 // This provides options for packing multiple fonts into one atlas, not 173 // perfectly but better than nothing. 174 175 typedef struct 176 { 177 unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap 178 float xoff,yoff,xadvance; 179 float xoff2,yoff2; 180 } stbtt_packedchar; 181 182 typedef struct stbtt_pack_context stbtt_pack_context; 183 typedef struct stbtt_fontinfo stbtt_fontinfo; 184 #ifndef STB_RECT_PACK_VERSION 185 typedef struct stbrp_rect stbrp_rect; 186 #endif 187 188 STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); 189 // Initializes a packing context stored in the passed-in stbtt_pack_context. 190 // Future calls using this context will pack characters into the bitmap passed 191 // in here: a 1-channel bitmap that is width * height. stride_in_bytes is 192 // the distance from one row to the next (or 0 to mean they are packed tightly 193 // together). "padding" is the amount of padding to leave between each 194 // character (normally you want '1' for bitmaps you'll use as textures with 195 // bilinear filtering). 196 // 197 // Returns 0 on failure, 1 on success. 198 199 STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); 200 // Cleans up the packing context and frees all memory. 201 202 #define STBTT_POINT_SIZE(x) (-(x)) 203 204 STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, 205 int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); 206 // Creates character bitmaps from the font_index'th font found in fontdata (use 207 // font_index=0 if you don't know what that is). It creates num_chars_in_range 208 // bitmaps for characters with unicode values starting at first_unicode_char_in_range 209 // and increasing. Data for how to render them is stored in chardata_for_range; 210 // pass these to stbtt_GetPackedQuad to get back renderable quads. 211 // 212 // font_size is the full height of the character from ascender to descender, 213 // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed 214 // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() 215 // and pass that result as 'font_size': 216 // ..., 20 , ... // font max minus min y is 20 pixels tall 217 // ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall 218 219 typedef struct 220 { 221 float font_size; 222 int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint 223 int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints 224 int num_chars; 225 stbtt_packedchar *chardata_for_range; // output 226 unsigned char h_oversample, v_oversample; // don't set these, they're used internally 227 } stbtt_pack_range; 228 229 STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); 230 // Creates character bitmaps from multiple ranges of characters stored in 231 // ranges. This will usually create a better-packed bitmap than multiple 232 // calls to stbtt_PackFontRange. Note that you can call this multiple 233 // times within a single PackBegin/PackEnd. 234 235 STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); 236 // Oversampling a font increases the quality by allowing higher-quality subpixel 237 // positioning, and is especially valuable at smaller text sizes. 238 // 239 // This function sets the amount of oversampling for all following calls to 240 // stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given 241 // pack context. The default (no oversampling) is achieved by h_oversample=1 242 // and v_oversample=1. The total number of pixels required is 243 // h_oversample*v_oversample larger than the default; for example, 2x2 244 // oversampling requires 4x the storage of 1x1. For best results, render 245 // oversampled textures with bilinear filtering. Look at the readme in 246 // stb/tests/oversample for information about oversampled fonts 247 // 248 // To use with PackFontRangesGather etc., you must set it before calls 249 // call to PackFontRangesGatherRects. 250 251 STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); 252 // If skip != 0, this tells stb_truetype to skip any codepoints for which 253 // there is no corresponding glyph. If skip=0, which is the default, then 254 // codepoints without a glyph recived the font's "missing character" glyph, 255 // typically an empty box by convention. 256 257 STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above 258 int char_index, // character to display 259 float *xpos, float *ypos, // pointers to current position in screen pixel space 260 stbtt_aligned_quad *q, // output: quad to draw 261 int align_to_integer); 262 263 STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); 264 STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); 265 STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); 266 // Calling these functions in sequence is roughly equivalent to calling 267 // stbtt_PackFontRanges(). If you more control over the packing of multiple 268 // fonts, or if you want to pack custom data into a font texture, take a look 269 // at the source to of stbtt_PackFontRanges() and create a custom version 270 // using these functions, e.g. call GatherRects multiple times, 271 // building up a single array of rects, then call PackRects once, 272 // then call RenderIntoRects repeatedly. This may result in a 273 // better packing than calling PackFontRanges multiple times 274 // (or it may not). 275 276 // this is an opaque structure that you shouldn't mess with which holds 277 // all the context needed from PackBegin to PackEnd. 278 struct stbtt_pack_context { 279 void *user_allocator_context; 280 void *pack_info; 281 int width; 282 int height; 283 int stride_in_bytes; 284 int padding; 285 int skip_missing; 286 unsigned int h_oversample, v_oversample; 287 unsigned char *pixels; 288 void *nodes; 289 }; 290 291 ////////////////////////////////////////////////////////////////////////////// 292 // 293 // FONT LOADING 294 // 295 // 296 297 STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); 298 // This function will determine the number of fonts in a font file. TrueType 299 // collection (.ttc) files may contain multiple fonts, while TrueType font 300 // (.ttf) files only contain one font. The number of fonts can be used for 301 // indexing with the previous function where the index is between zero and one 302 // less than the total fonts. If an error occurs, -1 is returned. 303 304 STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); 305 // Each .ttf/.ttc file may have more than one font. Each font has a sequential 306 // index number starting from 0. Call this function to get the font offset for 307 // a given index; it returns -1 if the index is out of range. A regular .ttf 308 // file will only define one font and it always be at offset 0, so it will 309 // return '0' for index 0, and -1 for all other indices. 310 311 // The following structure is defined publicly so you can declare one on 312 // the stack or as a global or etc, but you should treat it as opaque. 313 struct stbtt_fontinfo 314 { 315 void * userdata; 316 unsigned char * data; // pointer to .ttf file 317 int fontstart; // offset of start of font 318 319 int numGlyphs; // number of glyphs, needed for range checking 320 321 int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf 322 int index_map; // a cmap mapping for our chosen character encoding 323 int indexToLocFormat; // format needed to map from glyph index to glyph 324 325 stbtt__buf cff; // cff font data 326 stbtt__buf charstrings; // the charstring index 327 stbtt__buf gsubrs; // global charstring subroutines index 328 stbtt__buf subrs; // private charstring subroutines index 329 stbtt__buf fontdicts; // array of font dicts 330 stbtt__buf fdselect; // map from glyph to fontdict 331 }; 332 333 STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); 334 // Given an offset into the file that defines a font, this function builds 335 // the necessary cached info for the rest of the system. You must allocate 336 // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't 337 // need to do anything special to free it, because the contents are pure 338 // value data with no additional data structures. Returns 0 on failure. 339 340 341 ////////////////////////////////////////////////////////////////////////////// 342 // 343 // CHARACTER TO GLYPH-INDEX CONVERSIOn 344 345 STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); 346 // If you're going to perform multiple operations on the same character 347 // and you want a speed-up, call this function with the character you're 348 // going to process, then use glyph-based functions instead of the 349 // codepoint-based functions. 350 // Returns 0 if the character codepoint is not defined in the font. 351 352 353 ////////////////////////////////////////////////////////////////////////////// 354 // 355 // CHARACTER PROPERTIES 356 // 357 358 STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); 359 // computes a scale factor to produce a font whose "height" is 'pixels' tall. 360 // Height is measured as the distance from the highest ascender to the lowest 361 // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics 362 // and computing: 363 // scale = pixels / (ascent - descent) 364 // so if you prefer to measure height by the ascent only, use a similar calculation. 365 366 STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); 367 // computes a scale factor to produce a font whose EM size is mapped to 368 // 'pixels' tall. This is probably what traditional APIs compute, but 369 // I'm not positive. 370 371 STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); 372 // ascent is the coordinate above the baseline the font extends; descent 373 // is the coordinate below the baseline the font extends (i.e. it is typically negative) 374 // lineGap is the spacing between one row's descent and the next row's ascent... 375 // so you should advance the vertical position by "*ascent - *descent + *lineGap" 376 // these are expressed in unscaled coordinates, so you must multiply by 377 // the scale factor for a given size 378 379 STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); 380 // analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 381 // table (specific to MS/Windows TTF files). 382 // 383 // Returns 1 on success (table present), 0 on failure. 384 385 STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); 386 // the bounding box around all possible characters 387 388 STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); 389 // leftSideBearing is the offset from the current horizontal position to the left edge of the character 390 // advanceWidth is the offset from the current horizontal position to the next horizontal position 391 // these are expressed in unscaled coordinates 392 393 STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); 394 // an additional amount to add to the 'advance' value between ch1 and ch2 395 396 STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); 397 // Gets the bounding box of the visible part of the glyph, in unscaled coordinates 398 399 STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); 400 STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); 401 STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); 402 // as above, but takes one or more glyph indices for greater efficiency 403 404 typedef struct stbtt_kerningentry 405 { 406 int glyph1; // use stbtt_FindGlyphIndex 407 int glyph2; 408 int advance; 409 } stbtt_kerningentry; 410 411 STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info); 412 STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length); 413 // Retrieves a complete list of all of the kerning pairs provided by the font 414 // stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. 415 // The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) 416 417 ////////////////////////////////////////////////////////////////////////////// 418 // 419 // GLYPH SHAPES (you probably don't need these, but they have to go before 420 // the bitmaps for C declaration-order reasons) 421 // 422 423 #ifndef STBTT_vmove // you can predefine these to use different values (but why?) 424 enum { 425 STBTT_vmove=1, 426 STBTT_vline, 427 STBTT_vcurve, 428 STBTT_vcubic 429 }; 430 #endif 431 432 #ifndef stbtt_vertex // you can predefine this to use different values 433 // (we share this with other code at RAD) 434 #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file 435 typedef struct 436 { 437 stbtt_vertex_type x,y,cx,cy,cx1,cy1; 438 unsigned char type,padding; 439 } stbtt_vertex; 440 #endif 441 442 STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); 443 // returns non-zero if nothing is drawn for this glyph 444 445 STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); 446 STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); 447 // returns # of vertices and fills *vertices with the pointer to them 448 // these are expressed in "unscaled" coordinates 449 // 450 // The shape is a series of contours. Each one starts with 451 // a STBTT_moveto, then consists of a series of mixed 452 // STBTT_lineto and STBTT_curveto segments. A lineto 453 // draws a line from previous endpoint to its x,y; a curveto 454 // draws a quadratic bezier from previous endpoint to 455 // its x,y, using cx,cy as the bezier control point. 456 457 STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); 458 // frees the data allocated above 459 460 STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl); 461 STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg); 462 STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg); 463 // fills svg with the character's SVG data. 464 // returns data size or 0 if SVG not found. 465 466 ////////////////////////////////////////////////////////////////////////////// 467 // 468 // BITMAP RENDERING 469 // 470 471 STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); 472 // frees the bitmap allocated below 473 474 STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); 475 // allocates a large-enough single-channel 8bpp bitmap and renders the 476 // specified character/glyph at the specified scale into it, with 477 // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). 478 // *width & *height are filled out with the width & height of the bitmap, 479 // which is stored left-to-right, top-to-bottom. 480 // 481 // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap 482 483 STBTT_DEF 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); 484 // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel 485 // shift for the character 486 487 STBTT_DEF 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); 488 // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap 489 // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap 490 // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the 491 // width and height and positioning info for it first. 492 493 STBTT_DEF 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); 494 // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel 495 // shift for the character 496 497 STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(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 oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); 498 // same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering 499 // is performed (see stbtt_PackSetOversampling) 500 501 STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); 502 // get the bbox of the bitmap centered around the glyph origin; so the 503 // bitmap width is ix1-ix0, height is iy1-iy0, and location to place 504 // the bitmap top left is (leftSideBearing*scale,iy0). 505 // (Note that the bitmap uses y-increases-down, but the shape uses 506 // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) 507 508 STBTT_DEF 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); 509 // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel 510 // shift for the character 511 512 // the following functions are equivalent to the above functions, but operate 513 // on glyph indices instead of Unicode codepoints (for efficiency) 514 STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); 515 STBTT_DEF 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); 516 STBTT_DEF 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); 517 STBTT_DEF 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); 518 STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(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 oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); 519 STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); 520 STBTT_DEF 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); 521 522 523 // @TODO: don't expose this structure 524 typedef struct 525 { 526 int w,h,stride; 527 unsigned char *pixels; 528 } stbtt__bitmap; 529 530 // rasterize a shape with quadratic beziers into a bitmap 531 STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into 532 float flatness_in_pixels, // allowable error of curve in pixels 533 stbtt_vertex *vertices, // array of vertices defining shape 534 int num_verts, // number of vertices in above array 535 float scale_x, float scale_y, // scale applied to input vertices 536 float shift_x, float shift_y, // translation applied to input vertices 537 int x_off, int y_off, // another translation applied to input 538 int invert, // if non-zero, vertically flip shape 539 void *userdata); // context for to STBTT_MALLOC 540 541 ////////////////////////////////////////////////////////////////////////////// 542 // 543 // Signed Distance Function (or Field) rendering 544 545 STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); 546 // frees the SDF bitmap allocated below 547 548 STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); 549 STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); 550 // These functions compute a discretized SDF field for a single character, suitable for storing 551 // in a single-channel texture, sampling with bilinear filtering, and testing against 552 // larger than some threshold to produce scalable fonts. 553 // info -- the font 554 // scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap 555 // glyph/codepoint -- the character to generate the SDF for 556 // padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), 557 // which allows effects like bit outlines 558 // onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) 559 // pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) 560 // if positive, > onedge_value is inside; if negative, < onedge_value is inside 561 // width,height -- output height & width of the SDF bitmap (including padding) 562 // xoff,yoff -- output origin of the character 563 // return value -- a 2D array of bytes 0..255, width*height in size 564 // 565 // pixel_dist_scale & onedge_value are a scale & bias that allows you to make 566 // optimal use of the limited 0..255 for your application, trading off precision 567 // and special effects. SDF values outside the range 0..255 are clamped to 0..255. 568 // 569 // Example: 570 // scale = stbtt_ScaleForPixelHeight(22) 571 // padding = 5 572 // onedge_value = 180 573 // pixel_dist_scale = 180/5.0 = 36.0 574 // 575 // This will create an SDF bitmap in which the character is about 22 pixels 576 // high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled 577 // shape, sample the SDF at each pixel and fill the pixel if the SDF value 578 // is greater than or equal to 180/255. (You'll actually want to antialias, 579 // which is beyond the scope of this example.) Additionally, you can compute 580 // offset outlines (e.g. to stroke the character border inside & outside, 581 // or only outside). For example, to fill outside the character up to 3 SDF 582 // pixels, you would compare against (180-36.0*3)/255 = 72/255. The above 583 // choice of variables maps a range from 5 pixels outside the shape to 584 // 2 pixels inside the shape to 0..255; this is intended primarily for apply 585 // outside effects only (the interior range is needed to allow proper 586 // antialiasing of the font at *smaller* sizes) 587 // 588 // The function computes the SDF analytically at each SDF pixel, not by e.g. 589 // building a higher-res bitmap and approximating it. In theory the quality 590 // should be as high as possible for an SDF of this size & representation, but 591 // unclear if this is true in practice (perhaps building a higher-res bitmap 592 // and computing from that can allow drop-out prevention). 593 // 594 // The algorithm has not been optimized at all, so expect it to be slow 595 // if computing lots of characters or very large sizes. 596 597 598 599 ////////////////////////////////////////////////////////////////////////////// 600 // 601 // Finding the right font... 602 // 603 // You should really just solve this offline, keep your own tables 604 // of what font is what, and don't try to get it out of the .ttf file. 605 // That's because getting it out of the .ttf file is really hard, because 606 // the names in the file can appear in many possible encodings, in many 607 // possible languages, and e.g. if you need a case-insensitive comparison, 608 // the details of that depend on the encoding & language in a complex way 609 // (actually underspecified in truetype, but also gigantic). 610 // 611 // But you can use the provided functions in two possible ways: 612 // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on 613 // unicode-encoded names to try to find the font you want; 614 // you can run this before calling stbtt_InitFont() 615 // 616 // stbtt_GetFontNameString() lets you get any of the various strings 617 // from the file yourself and do your own comparisons on them. 618 // You have to have called stbtt_InitFont() first. 619 620 621 STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); 622 // returns the offset (not index) of the font that matches, or -1 if none 623 // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". 624 // if you use any other flag, use a font name like "Arial"; this checks 625 // the 'macStyle' header field; i don't know if fonts set this consistently 626 #define STBTT_MACSTYLE_DONTCARE 0 627 #define STBTT_MACSTYLE_BOLD 1 628 #define STBTT_MACSTYLE_ITALIC 2 629 #define STBTT_MACSTYLE_UNDERSCORE 4 630 #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 631 632 STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); 633 // returns 1/0 whether the first string interpreted as utf8 is identical to 634 // the second string interpreted as big-endian utf16... useful for strings from next func 635 636 STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); 637 // returns the string (which may be big-endian double byte, e.g. for unicode) 638 // and puts the length in bytes in *length. 639 // 640 // some of the values for the IDs are below; for more see the truetype spec: 641 // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html 642 // http://www.microsoft.com/typography/otspec/name.htm 643 644 enum { // platformID 645 STBTT_PLATFORM_ID_UNICODE =0, 646 STBTT_PLATFORM_ID_MAC =1, 647 STBTT_PLATFORM_ID_ISO =2, 648 STBTT_PLATFORM_ID_MICROSOFT =3 649 }; 650 651 enum { // encodingID for STBTT_PLATFORM_ID_UNICODE 652 STBTT_UNICODE_EID_UNICODE_1_0 =0, 653 STBTT_UNICODE_EID_UNICODE_1_1 =1, 654 STBTT_UNICODE_EID_ISO_10646 =2, 655 STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, 656 STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 657 }; 658 659 enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT 660 STBTT_MS_EID_SYMBOL =0, 661 STBTT_MS_EID_UNICODE_BMP =1, 662 STBTT_MS_EID_SHIFTJIS =2, 663 STBTT_MS_EID_UNICODE_FULL =10 664 }; 665 666 enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes 667 STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, 668 STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, 669 STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, 670 STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 671 }; 672 673 enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... 674 // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs 675 STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, 676 STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, 677 STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, 678 STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, 679 STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, 680 STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D 681 }; 682 683 enum { // languageID for STBTT_PLATFORM_ID_MAC 684 STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, 685 STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, 686 STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, 687 STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , 688 STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , 689 STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, 690 STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 691 }; 692 693 #ifdef __cplusplus 694 } 695 #endif 696 697 #endif // __STB_INCLUDE_STB_TRUETYPE_H__ 698 699 /* 700 ------------------------------------------------------------------------------ 701 This software is available under 2 licenses -- choose whichever you prefer. 702 ------------------------------------------------------------------------------ 703 ALTERNATIVE A - MIT License 704 Copyright (c) 2017 Sean Barrett 705 Permission is hereby granted, free of charge, to any person obtaining a copy of 706 this software and associated documentation files (the "Software"), to deal in 707 the Software without restriction, including without limitation the rights to 708 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 709 of the Software, and to permit persons to whom the Software is furnished to do 710 so, subject to the following conditions: 711 The above copyright notice and this permission notice shall be included in all 712 copies or substantial portions of the Software. 713 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 714 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 715 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 716 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 717 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 718 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 719 SOFTWARE. 720 ------------------------------------------------------------------------------ 721 ALTERNATIVE B - Public Domain (www.unlicense.org) 722 This is free and unencumbered software released into the public domain. 723 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this 724 software, either in source code form or as a compiled binary, for any purpose, 725 commercial or non-commercial, and by any means. 726 In jurisdictions that recognize copyright laws, the author or authors of this 727 software dedicate any and all copyright interest in the software to the public 728 domain. We make this dedication for the benefit of the public at large and to 729 the detriment of our heirs and successors. We intend this dedication to be an 730 overt act of relinquishment in perpetuity of all present and future rights to 731 this software under copyright law. 732 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 733 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 734 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 735 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 736 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 737 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 738 ------------------------------------------------------------------------------ 739 */