ltkx

GUI toolkit for X11 (WIP)
git clone git://lumidify.org/ltkx.git
Log | Files | Refs | README | LICENSE

stb_truetype.h (152431B)


      1 // stb_truetype.h - v1.13 - public domain
      2 // authored from 2009-2016 by Sean Barrett / RAD Game Tools
      3 //
      4 //   This library processes TrueType files:
      5 //        parse files
      6 //        extract glyph metrics
      7 //        extract glyph shapes
      8 //        render glyphs to one-channel bitmaps with antialiasing (box filter)
      9 //
     10 //   Todo:
     11 //        non-MS cmaps
     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?
     18 //
     19 // ADDITIONAL CONTRIBUTORS
     20 //
     21 //   Mikko Mononen: compound shape support, more cmap formats
     22 //   Tor Andersson: kerning, subpixel rendering
     23 //   Dougall Johnson: OpenType / Type 2 font handling
     24 //
     25 //   Misc other:
     26 //       Ryan Gordon
     27 //       Simon Glass
     28 //       github:IntellectualKitty
     29 //
     30 //   Bug/warning reports/fixes:
     31 //       "Zer" on mollyrocket (with fix)
     32 //       Cass Everitt
     33 //       stoiko (Haemimont Games)
     34 //       Brian Hook 
     35 //       Walter van Niftrik
     36 //       David Gow
     37 //       David Given
     38 //       Ivan-Assen Ivanov
     39 //       Anthony Pesch
     40 //       Johan Duparc
     41 //       Hou Qiming
     42 //       Fabian "ryg" Giesen
     43 //       Martins Mozeiko
     44 //       Cap Petschulat
     45 //       Omar Cornut
     46 //       github:aloucks
     47 //       Peter LaValle
     48 //       Sergey Popov
     49 //       Giumo X. Clanjor
     50 //       Higor Euripedes
     51 //       Thomas Fields
     52 //       Derek Vinyard
     53 //
     54 // VERSION HISTORY
     55 //
     56 //   1.13 (2017-01-02) support OpenType fonts, certain Apple fonts, num-fonts-in-TTC function
     57 //   1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
     58 //   1.11 (2016-04-02) fix unused-variable warning
     59 //   1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef
     60 //   1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly
     61 //   1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
     62 //   1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
     63 //                     variant PackFontRanges to pack and render in separate phases;
     64 //                     fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
     65 //                     fixed an assert() bug in the new rasterizer
     66 //                     replace assert() with STBTT_assert() in new rasterizer
     67 //
     68 //   Full history can be found at the end of this file.
     69 //
     70 // LICENSE
     71 //
     72 //   This software is dual-licensed to the public domain and under the following
     73 //   license: you are granted a perpetual, irrevocable license to copy, modify,
     74 //   publish, and distribute this file as you see fit.
     75 //
     76 // USAGE
     77 //
     78 //   Include this file in whatever places neeed to refer to it. In ONE C/C++
     79 //   file, write:
     80 //      #define STB_TRUETYPE_IMPLEMENTATION
     81 //   before the #include of this file. This expands out the actual
     82 //   implementation into that C/C++ file.
     83 //
     84 //   To make the implementation private to the file that generates the implementation,
     85 //      #define STBTT_STATIC
     86 //
     87 //   Simple 3D API (don't ship this, but it's fine for tools and quick start)
     88 //           stbtt_BakeFontBitmap()               -- bake a font to a bitmap for use as texture
     89 //           stbtt_GetBakedQuad()                 -- compute quad to draw for a given char
     90 //
     91 //   Improved 3D API (more shippable):
     92 //           #include "stb_rect_pack.h"           -- optional, but you really want it
     93 //           stbtt_PackBegin()
     94 //           stbtt_PackSetOversample()            -- for improved quality on small fonts
     95 //           stbtt_PackFontRanges()               -- pack and renders
     96 //           stbtt_PackEnd()
     97 //           stbtt_GetPackedQuad()
     98 //
     99 //   "Load" a font file from a memory buffer (you have to keep the buffer loaded)
    100 //           stbtt_InitFont()
    101 //           stbtt_GetFontOffsetForIndex()        -- indexing for TTC font collections
    102 //           stbtt_GetNumberOfFonts()             -- number of fonts for TTC font collections
    103 //
    104 //   Render a unicode codepoint to a bitmap
    105 //           stbtt_GetCodepointBitmap()           -- allocates and returns a bitmap
    106 //           stbtt_MakeCodepointBitmap()          -- renders into bitmap you provide
    107 //           stbtt_GetCodepointBitmapBox()        -- how big the bitmap must be
    108 //
    109 //   Character advance/positioning
    110 //           stbtt_GetCodepointHMetrics()
    111 //           stbtt_GetFontVMetrics()
    112 //           stbtt_GetCodepointKernAdvance()
    113 //
    114 //   Starting with version 1.06, the rasterizer was replaced with a new,
    115 //   faster and generally-more-precise rasterizer. The new rasterizer more
    116 //   accurately measures pixel coverage for anti-aliasing, except in the case
    117 //   where multiple shapes overlap, in which case it overestimates the AA pixel
    118 //   coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If
    119 //   this turns out to be a problem, you can re-enable the old rasterizer with
    120 //        #define STBTT_RASTERIZER_VERSION 1
    121 //   which will incur about a 15% speed hit.
    122 //
    123 // ADDITIONAL DOCUMENTATION
    124 //
    125 //   Immediately after this block comment are a series of sample programs.
    126 //
    127 //   After the sample programs is the "header file" section. This section
    128 //   includes documentation for each API function.
    129 //
    130 //   Some important concepts to understand to use this library:
    131 //
    132 //      Codepoint
    133 //         Characters are defined by unicode codepoints, e.g. 65 is
    134 //         uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
    135 //         the hiragana for "ma".
    136 //
    137 //      Glyph
    138 //         A visual character shape (every codepoint is rendered as
    139 //         some glyph)
    140 //
    141 //      Glyph index
    142 //         A font-specific integer ID representing a glyph
    143 //
    144 //      Baseline
    145 //         Glyph shapes are defined relative to a baseline, which is the
    146 //         bottom of uppercase characters. Characters extend both above
    147 //         and below the baseline.
    148 //
    149 //      Current Point
    150 //         As you draw text to the screen, you keep track of a "current point"
    151 //         which is the origin of each character. The current point's vertical
    152 //         position is the baseline. Even "baked fonts" use this model.
    153 //
    154 //      Vertical Font Metrics
    155 //         The vertical qualities of the font, used to vertically position
    156 //         and space the characters. See docs for stbtt_GetFontVMetrics.
    157 //
    158 //      Font Size in Pixels or Points
    159 //         The preferred interface for specifying font sizes in stb_truetype
    160 //         is to specify how tall the font's vertical extent should be in pixels.
    161 //         If that sounds good enough, skip the next paragraph.
    162 //
    163 //         Most font APIs instead use "points", which are a common typographic
    164 //         measurement for describing font size, defined as 72 points per inch.
    165 //         stb_truetype provides a point API for compatibility. However, true
    166 //         "per inch" conventions don't make much sense on computer displays
    167 //         since they different monitors have different number of pixels per
    168 //         inch. For example, Windows traditionally uses a convention that
    169 //         there are 96 pixels per inch, thus making 'inch' measurements have
    170 //         nothing to do with inches, and thus effectively defining a point to
    171 //         be 1.333 pixels. Additionally, the TrueType font data provides
    172 //         an explicit scale factor to scale a given font's glyphs to points,
    173 //         but the author has observed that this scale factor is often wrong
    174 //         for non-commercial fonts, thus making fonts scaled in points
    175 //         according to the TrueType spec incoherently sized in practice.
    176 //
    177 // ADVANCED USAGE
    178 //
    179 //   Quality:
    180 //
    181 //    - Use the functions with Subpixel at the end to allow your characters
    182 //      to have subpixel positioning. Since the font is anti-aliased, not
    183 //      hinted, this is very import for quality. (This is not possible with
    184 //      baked fonts.)
    185 //
    186 //    - Kerning is now supported, and if you're supporting subpixel rendering
    187 //      then kerning is worth using to give your text a polished look.
    188 //
    189 //   Performance:
    190 //
    191 //    - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
    192 //      if you don't do this, stb_truetype is forced to do the conversion on
    193 //      every call.
    194 //
    195 //    - There are a lot of memory allocations. We should modify it to take
    196 //      a temp buffer and allocate from the temp buffer (without freeing),
    197 //      should help performance a lot.
    198 //
    199 // NOTES
    200 //
    201 //   The system uses the raw data found in the .ttf file without changing it
    202 //   and without building auxiliary data structures. This is a bit inefficient
    203 //   on little-endian systems (the data is big-endian), but assuming you're
    204 //   caching the bitmaps or glyph shapes this shouldn't be a big deal.
    205 //
    206 //   It appears to be very hard to programmatically determine what font a
    207 //   given file is in a general way. I provide an API for this, but I don't
    208 //   recommend it.
    209 //
    210 //
    211 // SOURCE STATISTICS (based on v0.6c, 2050 LOC)
    212 //
    213 //   Documentation & header file        520 LOC  \___ 660 LOC documentation
    214 //   Sample code                        140 LOC  /
    215 //   Truetype parsing                   620 LOC  ---- 620 LOC TrueType
    216 //   Software rasterization             240 LOC  \                           .
    217 //   Curve tesselation                  120 LOC   \__ 550 LOC Bitmap creation
    218 //   Bitmap management                  100 LOC   /
    219 //   Baked bitmap interface              70 LOC  /
    220 //   Font name matching & access        150 LOC  ---- 150 
    221 //   C runtime library abstraction       60 LOC  ----  60
    222 //
    223 //
    224 // PERFORMANCE MEASUREMENTS FOR 1.06:
    225 //
    226 //                      32-bit     64-bit
    227 //   Previous release:  8.83 s     7.68 s
    228 //   Pool allocations:  7.72 s     6.34 s
    229 //   Inline sort     :  6.54 s     5.65 s
    230 //   New rasterizer  :  5.63 s     5.00 s
    231 
    232 //////////////////////////////////////////////////////////////////////////////
    233 //////////////////////////////////////////////////////////////////////////////
    234 ////
    235 ////  SAMPLE PROGRAMS
    236 ////
    237 //
    238 //  Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
    239 //
    240 #if 0
    241 #define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation
    242 #include "stb_truetype.h"
    243 
    244 unsigned char ttf_buffer[1<<20];
    245 unsigned char temp_bitmap[512*512];
    246 
    247 stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
    248 GLuint ftex;
    249 
    250 void my_stbtt_initfont(void)
    251 {
    252    fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
    253    stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
    254    // can free ttf_buffer at this point
    255    glGenTextures(1, &ftex);
    256    glBindTexture(GL_TEXTURE_2D, ftex);
    257    glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
    258    // can free temp_bitmap at this point
    259    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    260 }
    261 
    262 void my_stbtt_print(float x, float y, char *text)
    263 {
    264    // assume orthographic projection with units = screen pixels, origin at top left
    265    glEnable(GL_TEXTURE_2D);
    266    glBindTexture(GL_TEXTURE_2D, ftex);
    267    glBegin(GL_QUADS);
    268    while (*text) {
    269       if (*text >= 32 && *text < 128) {
    270          stbtt_aligned_quad q;
    271          stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
    272          glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
    273          glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
    274          glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
    275          glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
    276       }
    277       ++text;
    278    }
    279    glEnd();
    280 }
    281 #endif
    282 //
    283 //
    284 //////////////////////////////////////////////////////////////////////////////
    285 //
    286 // Complete program (this compiles): get a single bitmap, print as ASCII art
    287 //
    288 #if 0
    289 #include <stdio.h>
    290 #define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation
    291 #include "stb_truetype.h"
    292 
    293 char ttf_buffer[1<<25];
    294 
    295 int main(int argc, char **argv)
    296 {
    297    stbtt_fontinfo font;
    298    unsigned char *bitmap;
    299    int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
    300 
    301    fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
    302 
    303    stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
    304    bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
    305 
    306    for (j=0; j < h; ++j) {
    307       for (i=0; i < w; ++i)
    308          putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
    309       putchar('\n');
    310    }
    311    return 0;
    312 }
    313 #endif 
    314 //
    315 // Output:
    316 //
    317 //     .ii.
    318 //    @@@@@@.
    319 //   V@Mio@@o
    320 //   :i.  V@V
    321 //     :oM@@M
    322 //   :@@@MM@M
    323 //   @@o  o@M
    324 //  :@@.  M@M
    325 //   @@@o@@@@
    326 //   :M@@V:@@.
    327 //  
    328 //////////////////////////////////////////////////////////////////////////////
    329 // 
    330 // Complete program: print "Hello World!" banner, with bugs
    331 //
    332 #if 0
    333 char buffer[24<<20];
    334 unsigned char screen[20][79];
    335 
    336 int main(int arg, char **argv)
    337 {
    338    stbtt_fontinfo font;
    339    int i,j,ascent,baseline,ch=0;
    340    float scale, xpos=2; // leave a little padding in case the character extends left
    341    char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness
    342 
    343    fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
    344    stbtt_InitFont(&font, buffer, 0);
    345 
    346    scale = stbtt_ScaleForPixelHeight(&font, 15);
    347    stbtt_GetFontVMetrics(&font, &ascent,0,0);
    348    baseline = (int) (ascent*scale);
    349 
    350    while (text[ch]) {
    351       int advance,lsb,x0,y0,x1,y1;
    352       float x_shift = xpos - (float) floor(xpos);
    353       stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
    354       stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
    355       stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
    356       // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
    357       // because this API is really for baking character bitmaps into textures. if you want to render
    358       // a sequence of characters, you really need to render each bitmap to a temp buffer, then
    359       // "alpha blend" that into the working buffer
    360       xpos += (advance * scale);
    361       if (text[ch+1])
    362          xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
    363       ++ch;
    364    }
    365 
    366    for (j=0; j < 20; ++j) {
    367       for (i=0; i < 78; ++i)
    368          putchar(" .:ioVM@"[screen[j][i]>>5]);
    369       putchar('\n');
    370    }
    371 
    372    return 0;
    373 }
    374 #endif
    375 
    376 
    377 //////////////////////////////////////////////////////////////////////////////
    378 //////////////////////////////////////////////////////////////////////////////
    379 ////
    380 ////   INTEGRATION WITH YOUR CODEBASE
    381 ////
    382 ////   The following sections allow you to supply alternate definitions
    383 ////   of C library functions used by stb_truetype.
    384 
    385 #ifdef STB_TRUETYPE_IMPLEMENTATION
    386    // #define your own (u)stbtt_int8/16/32 before including to override this
    387    #ifndef stbtt_uint8
    388    typedef unsigned char   stbtt_uint8;
    389    typedef signed   char   stbtt_int8;
    390    typedef unsigned short  stbtt_uint16;
    391    typedef signed   short  stbtt_int16;
    392    typedef unsigned int    stbtt_uint32;
    393    typedef signed   int    stbtt_int32;
    394    #endif
    395 
    396    typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
    397    typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
    398 
    399    // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
    400    #ifndef STBTT_ifloor
    401    #include <math.h>
    402    #define STBTT_ifloor(x)   ((int) floor(x))
    403    #define STBTT_iceil(x)    ((int) ceil(x))
    404    #endif
    405 
    406    #ifndef STBTT_sqrt
    407    #include <math.h>
    408    #define STBTT_sqrt(x)      sqrt(x)
    409    #endif
    410 
    411    #ifndef STBTT_fabs
    412    #include <math.h>
    413    #define STBTT_fabs(x)      fabs(x)
    414    #endif
    415 
    416    // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
    417    #ifndef STBTT_malloc
    418    #include <stdlib.h>
    419    #define STBTT_malloc(x,u)  ((void)(u),malloc(x))
    420    #define STBTT_free(x,u)    ((void)(u),free(x))
    421    #endif
    422 
    423    #ifndef STBTT_assert
    424    #include <assert.h>
    425    #define STBTT_assert(x)    assert(x)
    426    #endif
    427 
    428    #ifndef STBTT_strlen
    429    #include <string.h>
    430    #define STBTT_strlen(x)    strlen(x)
    431    #endif
    432 
    433    #ifndef STBTT_memcpy
    434    #include <memory.h>
    435    #define STBTT_memcpy       memcpy
    436    #define STBTT_memset       memset
    437    #endif
    438 #endif
    439 
    440 ///////////////////////////////////////////////////////////////////////////////
    441 ///////////////////////////////////////////////////////////////////////////////
    442 ////
    443 ////   INTERFACE
    444 ////
    445 ////
    446 
    447 #ifndef __STB_INCLUDE_STB_TRUETYPE_H__
    448 #define __STB_INCLUDE_STB_TRUETYPE_H__
    449 
    450 #ifdef STBTT_STATIC
    451 #define STBTT_DEF static
    452 #else
    453 #define STBTT_DEF extern
    454 #endif
    455 
    456 #ifdef __cplusplus
    457 extern "C" {
    458 #endif
    459 
    460 // private structure
    461 typedef struct
    462 {
    463    unsigned char *data;
    464    int cursor;
    465    int size;
    466 } stbtt__buf;
    467 
    468 //////////////////////////////////////////////////////////////////////////////
    469 //
    470 // TEXTURE BAKING API
    471 //
    472 // If you use this API, you only have to call two functions ever.
    473 //
    474 
    475 typedef struct
    476 {
    477    unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
    478    float xoff,yoff,xadvance;
    479 } stbtt_bakedchar;
    480 
    481 STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)
    482                                 float pixel_height,                     // height of font in pixels
    483                                 unsigned char *pixels, int pw, int ph,  // bitmap to be filled in
    484                                 int first_char, int num_chars,          // characters to bake
    485                                 stbtt_bakedchar *chardata);             // you allocate this, it's num_chars long
    486 // if return is positive, the first unused row of the bitmap
    487 // if return is negative, returns the negative of the number of characters that fit
    488 // if return is 0, no characters fit and no rows were used
    489 // This uses a very crappy packing.
    490 
    491 typedef struct
    492 {
    493    float x0,y0,s0,t0; // top-left
    494    float x1,y1,s1,t1; // bottom-right
    495 } stbtt_aligned_quad;
    496 
    497 STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph,  // same data as above
    498                                int char_index,             // character to display
    499                                float *xpos, float *ypos,   // pointers to current position in screen pixel space
    500                                stbtt_aligned_quad *q,      // output: quad to draw
    501                                int opengl_fillrule);       // true if opengl fill rule; false if DX9 or earlier
    502 // Call GetBakedQuad with char_index = 'character - first_char', and it
    503 // creates the quad you need to draw and advances the current position.
    504 //
    505 // The coordinate system used assumes y increases downwards.
    506 //
    507 // Characters will extend both above and below the current position;
    508 // see discussion of "BASELINE" above.
    509 //
    510 // It's inefficient; you might want to c&p it and optimize it.
    511 
    512 
    513 
    514 //////////////////////////////////////////////////////////////////////////////
    515 //
    516 // NEW TEXTURE BAKING API
    517 //
    518 // This provides options for packing multiple fonts into one atlas, not
    519 // perfectly but better than nothing.
    520 
    521 typedef struct
    522 {
    523    unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
    524    float xoff,yoff,xadvance;
    525    float xoff2,yoff2;
    526 } stbtt_packedchar;
    527 
    528 typedef struct stbtt_pack_context stbtt_pack_context;
    529 typedef struct stbtt_fontinfo stbtt_fontinfo;
    530 #ifndef STB_RECT_PACK_VERSION
    531 typedef struct stbrp_rect stbrp_rect;
    532 #endif
    533 
    534 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);
    535 // Initializes a packing context stored in the passed-in stbtt_pack_context.
    536 // Future calls using this context will pack characters into the bitmap passed
    537 // in here: a 1-channel bitmap that is weight x height. stride_in_bytes is
    538 // the distance from one row to the next (or 0 to mean they are packed tightly
    539 // together). "padding" is the amount of padding to leave between each
    540 // character (normally you want '1' for bitmaps you'll use as textures with
    541 // bilinear filtering).
    542 //
    543 // Returns 0 on failure, 1 on success.
    544 
    545 STBTT_DEF void stbtt_PackEnd  (stbtt_pack_context *spc);
    546 // Cleans up the packing context and frees all memory.
    547 
    548 #define STBTT_POINT_SIZE(x)   (-(x))
    549 
    550 STBTT_DEF int  stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size,
    551                                 int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);
    552 // Creates character bitmaps from the font_index'th font found in fontdata (use
    553 // font_index=0 if you don't know what that is). It creates num_chars_in_range
    554 // bitmaps for characters with unicode values starting at first_unicode_char_in_range
    555 // and increasing. Data for how to render them is stored in chardata_for_range;
    556 // pass these to stbtt_GetPackedQuad to get back renderable quads.
    557 //
    558 // font_size is the full height of the character from ascender to descender,
    559 // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed
    560 // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()
    561 // and pass that result as 'font_size':
    562 //       ...,                  20 , ... // font max minus min y is 20 pixels tall
    563 //       ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall
    564 
    565 typedef struct
    566 {
    567    float font_size;
    568    int first_unicode_codepoint_in_range;  // if non-zero, then the chars are continuous, and this is the first codepoint
    569    int *array_of_unicode_codepoints;       // if non-zero, then this is an array of unicode codepoints
    570    int num_chars;
    571    stbtt_packedchar *chardata_for_range; // output
    572    unsigned char h_oversample, v_oversample; // don't set these, they're used internally
    573 } stbtt_pack_range;
    574 
    575 STBTT_DEF int  stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
    576 // Creates character bitmaps from multiple ranges of characters stored in
    577 // ranges. This will usually create a better-packed bitmap than multiple
    578 // calls to stbtt_PackFontRange. Note that you can call this multiple
    579 // times within a single PackBegin/PackEnd.
    580 
    581 STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);
    582 // Oversampling a font increases the quality by allowing higher-quality subpixel
    583 // positioning, and is especially valuable at smaller text sizes.
    584 //
    585 // This function sets the amount of oversampling for all following calls to
    586 // stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given
    587 // pack context. The default (no oversampling) is achieved by h_oversample=1
    588 // and v_oversample=1. The total number of pixels required is
    589 // h_oversample*v_oversample larger than the default; for example, 2x2
    590 // oversampling requires 4x the storage of 1x1. For best results, render
    591 // oversampled textures with bilinear filtering. Look at the readme in
    592 // stb/tests/oversample for information about oversampled fonts
    593 //
    594 // To use with PackFontRangesGather etc., you must set it before calls
    595 // call to PackFontRangesGatherRects.
    596 
    597 STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph,  // same data as above
    598                                int char_index,             // character to display
    599                                float *xpos, float *ypos,   // pointers to current position in screen pixel space
    600                                stbtt_aligned_quad *q,      // output: quad to draw
    601                                int align_to_integer);
    602 
    603 STBTT_DEF int  stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
    604 STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);
    605 STBTT_DEF int  stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
    606 // Calling these functions in sequence is roughly equivalent to calling
    607 // stbtt_PackFontRanges(). If you more control over the packing of multiple
    608 // fonts, or if you want to pack custom data into a font texture, take a look
    609 // at the source to of stbtt_PackFontRanges() and create a custom version 
    610 // using these functions, e.g. call GatherRects multiple times,
    611 // building up a single array of rects, then call PackRects once,
    612 // then call RenderIntoRects repeatedly. This may result in a
    613 // better packing than calling PackFontRanges multiple times
    614 // (or it may not).
    615 
    616 // this is an opaque structure that you shouldn't mess with which holds
    617 // all the context needed from PackBegin to PackEnd.
    618 struct stbtt_pack_context {
    619    void *user_allocator_context;
    620    void *pack_info;
    621    int   width;
    622    int   height;
    623    int   stride_in_bytes;
    624    int   padding;
    625    unsigned int   h_oversample, v_oversample;
    626    unsigned char *pixels;
    627    void  *nodes;
    628 };
    629 
    630 //////////////////////////////////////////////////////////////////////////////
    631 //
    632 // FONT LOADING
    633 //
    634 //
    635 
    636 STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data);
    637 // This function will determine the number of fonts in a font file.  TrueType
    638 // collection (.ttc) files may contain multiple fonts, while TrueType font
    639 // (.ttf) files only contain one font. The number of fonts can be used for
    640 // indexing with the previous function where the index is between zero and one
    641 // less than the total fonts. If an error occurs, -1 is returned.
    642 
    643 STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
    644 // Each .ttf/.ttc file may have more than one font. Each font has a sequential
    645 // index number starting from 0. Call this function to get the font offset for
    646 // a given index; it returns -1 if the index is out of range. A regular .ttf
    647 // file will only define one font and it always be at offset 0, so it will
    648 // return '0' for index 0, and -1 for all other indices.
    649 
    650 // The following structure is defined publically so you can declare one on
    651 // the stack or as a global or etc, but you should treat it as opaque.
    652 struct stbtt_fontinfo
    653 {
    654    void           * userdata;
    655    unsigned char  * data;              // pointer to .ttf file
    656    int              fontstart;         // offset of start of font
    657 
    658    int numGlyphs;                     // number of glyphs, needed for range checking
    659 
    660    int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf
    661    int index_map;                     // a cmap mapping for our chosen character encoding
    662    int indexToLocFormat;              // format needed to map from glyph index to glyph
    663 
    664    stbtt__buf cff;                    // cff font data
    665    stbtt__buf charstrings;            // the charstring index
    666    stbtt__buf gsubrs;                 // global charstring subroutines index
    667    stbtt__buf subrs;                  // private charstring subroutines index
    668    stbtt__buf fontdicts;              // array of font dicts
    669    stbtt__buf fdselect;               // map from glyph to fontdict
    670 };
    671 
    672 STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
    673 // Given an offset into the file that defines a font, this function builds
    674 // the necessary cached info for the rest of the system. You must allocate
    675 // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
    676 // need to do anything special to free it, because the contents are pure
    677 // value data with no additional data structures. Returns 0 on failure.
    678 
    679 
    680 //////////////////////////////////////////////////////////////////////////////
    681 //
    682 // CHARACTER TO GLYPH-INDEX CONVERSIOn
    683 
    684 STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
    685 // If you're going to perform multiple operations on the same character
    686 // and you want a speed-up, call this function with the character you're
    687 // going to process, then use glyph-based functions instead of the
    688 // codepoint-based functions.
    689 
    690 
    691 //////////////////////////////////////////////////////////////////////////////
    692 //
    693 // CHARACTER PROPERTIES
    694 //
    695 
    696 STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
    697 // computes a scale factor to produce a font whose "height" is 'pixels' tall.
    698 // Height is measured as the distance from the highest ascender to the lowest
    699 // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
    700 // and computing:
    701 //       scale = pixels / (ascent - descent)
    702 // so if you prefer to measure height by the ascent only, use a similar calculation.
    703 
    704 STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
    705 // computes a scale factor to produce a font whose EM size is mapped to
    706 // 'pixels' tall. This is probably what traditional APIs compute, but
    707 // I'm not positive.
    708 
    709 STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
    710 // ascent is the coordinate above the baseline the font extends; descent
    711 // is the coordinate below the baseline the font extends (i.e. it is typically negative)
    712 // lineGap is the spacing between one row's descent and the next row's ascent...
    713 // so you should advance the vertical position by "*ascent - *descent + *lineGap"
    714 //   these are expressed in unscaled coordinates, so you must multiply by
    715 //   the scale factor for a given size
    716 
    717 STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
    718 // the bounding box around all possible characters
    719 
    720 STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
    721 // leftSideBearing is the offset from the current horizontal position to the left edge of the character
    722 // advanceWidth is the offset from the current horizontal position to the next horizontal position
    723 //   these are expressed in unscaled coordinates
    724 
    725 STBTT_DEF int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
    726 // an additional amount to add to the 'advance' value between ch1 and ch2
    727 
    728 STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
    729 // Gets the bounding box of the visible part of the glyph, in unscaled coordinates
    730 
    731 STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
    732 STBTT_DEF int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
    733 STBTT_DEF int  stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
    734 // as above, but takes one or more glyph indices for greater efficiency
    735 
    736 
    737 //////////////////////////////////////////////////////////////////////////////
    738 //
    739 // GLYPH SHAPES (you probably don't need these, but they have to go before
    740 // the bitmaps for C declaration-order reasons)
    741 //
    742 
    743 #ifndef STBTT_vmove // you can predefine these to use different values (but why?)
    744    enum {
    745       STBTT_vmove=1,
    746       STBTT_vline,
    747       STBTT_vcurve,
    748       STBTT_vcubic
    749    };
    750 #endif
    751 
    752 #ifndef stbtt_vertex // you can predefine this to use different values
    753                    // (we share this with other code at RAD)
    754    #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
    755    typedef struct
    756    {
    757       stbtt_vertex_type x,y,cx,cy,cx1,cy1;
    758       unsigned char type,padding;
    759    } stbtt_vertex;
    760 #endif
    761 
    762 STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
    763 // returns non-zero if nothing is drawn for this glyph
    764 
    765 STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
    766 STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
    767 // returns # of vertices and fills *vertices with the pointer to them
    768 //   these are expressed in "unscaled" coordinates
    769 //
    770 // The shape is a series of countours. Each one starts with
    771 // a STBTT_moveto, then consists of a series of mixed
    772 // STBTT_lineto and STBTT_curveto segments. A lineto
    773 // draws a line from previous endpoint to its x,y; a curveto
    774 // draws a quadratic bezier from previous endpoint to
    775 // its x,y, using cx,cy as the bezier control point.
    776 
    777 STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
    778 // frees the data allocated above
    779 
    780 //////////////////////////////////////////////////////////////////////////////
    781 //
    782 // BITMAP RENDERING
    783 //
    784 
    785 STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
    786 // frees the bitmap allocated below
    787 
    788 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);
    789 // allocates a large-enough single-channel 8bpp bitmap and renders the
    790 // specified character/glyph at the specified scale into it, with
    791 // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
    792 // *width & *height are filled out with the width & height of the bitmap,
    793 // which is stored left-to-right, top-to-bottom.
    794 //
    795 // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
    796 
    797 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);
    798 // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
    799 // shift for the character
    800 
    801 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);
    802 // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
    803 // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
    804 // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
    805 // width and height and positioning info for it first.
    806 
    807 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);
    808 // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
    809 // shift for the character
    810 
    811 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);
    812 // get the bbox of the bitmap centered around the glyph origin; so the
    813 // bitmap width is ix1-ix0, height is iy1-iy0, and location to place
    814 // the bitmap top left is (leftSideBearing*scale,iy0).
    815 // (Note that the bitmap uses y-increases-down, but the shape uses
    816 // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
    817 
    818 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);
    819 // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
    820 // shift for the character
    821 
    822 // the following functions are equivalent to the above functions, but operate
    823 // on glyph indices instead of Unicode codepoints (for efficiency)
    824 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);
    825 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);
    826 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);
    827 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);
    828 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);
    829 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);
    830 
    831 
    832 // @TODO: don't expose this structure
    833 typedef struct
    834 {
    835    int w,h,stride;
    836    unsigned char *pixels;
    837 } stbtt__bitmap;
    838 
    839 // rasterize a shape with quadratic beziers into a bitmap
    840 STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result,        // 1-channel bitmap to draw into
    841                                float flatness_in_pixels,     // allowable error of curve in pixels
    842                                stbtt_vertex *vertices,       // array of vertices defining shape
    843                                int num_verts,                // number of vertices in above array
    844                                float scale_x, float scale_y, // scale applied to input vertices
    845                                float shift_x, float shift_y, // translation applied to input vertices
    846                                int x_off, int y_off,         // another translation applied to input
    847                                int invert,                   // if non-zero, vertically flip shape
    848                                void *userdata);              // context for to STBTT_MALLOC
    849 
    850 //////////////////////////////////////////////////////////////////////////////
    851 //
    852 // Finding the right font...
    853 //
    854 // You should really just solve this offline, keep your own tables
    855 // of what font is what, and don't try to get it out of the .ttf file.
    856 // That's because getting it out of the .ttf file is really hard, because
    857 // the names in the file can appear in many possible encodings, in many
    858 // possible languages, and e.g. if you need a case-insensitive comparison,
    859 // the details of that depend on the encoding & language in a complex way
    860 // (actually underspecified in truetype, but also gigantic).
    861 //
    862 // But you can use the provided functions in two possible ways:
    863 //     stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
    864 //             unicode-encoded names to try to find the font you want;
    865 //             you can run this before calling stbtt_InitFont()
    866 //
    867 //     stbtt_GetFontNameString() lets you get any of the various strings
    868 //             from the file yourself and do your own comparisons on them.
    869 //             You have to have called stbtt_InitFont() first.
    870 
    871 
    872 STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
    873 // returns the offset (not index) of the font that matches, or -1 if none
    874 //   if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
    875 //   if you use any other flag, use a font name like "Arial"; this checks
    876 //     the 'macStyle' header field; i don't know if fonts set this consistently
    877 #define STBTT_MACSTYLE_DONTCARE     0
    878 #define STBTT_MACSTYLE_BOLD         1
    879 #define STBTT_MACSTYLE_ITALIC       2
    880 #define STBTT_MACSTYLE_UNDERSCORE   4
    881 #define STBTT_MACSTYLE_NONE         8   // <= not same as 0, this makes us check the bitfield is 0
    882 
    883 STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
    884 // returns 1/0 whether the first string interpreted as utf8 is identical to
    885 // the second string interpreted as big-endian utf16... useful for strings from next func
    886 
    887 STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
    888 // returns the string (which may be big-endian double byte, e.g. for unicode)
    889 // and puts the length in bytes in *length.
    890 //
    891 // some of the values for the IDs are below; for more see the truetype spec:
    892 //     http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
    893 //     http://www.microsoft.com/typography/otspec/name.htm
    894 
    895 enum { // platformID
    896    STBTT_PLATFORM_ID_UNICODE   =0,
    897    STBTT_PLATFORM_ID_MAC       =1,
    898    STBTT_PLATFORM_ID_ISO       =2,
    899    STBTT_PLATFORM_ID_MICROSOFT =3
    900 };
    901 
    902 enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
    903    STBTT_UNICODE_EID_UNICODE_1_0    =0,
    904    STBTT_UNICODE_EID_UNICODE_1_1    =1,
    905    STBTT_UNICODE_EID_ISO_10646      =2,
    906    STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
    907    STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
    908 };
    909 
    910 enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
    911    STBTT_MS_EID_SYMBOL        =0,
    912    STBTT_MS_EID_UNICODE_BMP   =1,
    913    STBTT_MS_EID_SHIFTJIS      =2,
    914    STBTT_MS_EID_UNICODE_FULL  =10
    915 };
    916 
    917 enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
    918    STBTT_MAC_EID_ROMAN        =0,   STBTT_MAC_EID_ARABIC       =4,
    919    STBTT_MAC_EID_JAPANESE     =1,   STBTT_MAC_EID_HEBREW       =5,
    920    STBTT_MAC_EID_CHINESE_TRAD =2,   STBTT_MAC_EID_GREEK        =6,
    921    STBTT_MAC_EID_KOREAN       =3,   STBTT_MAC_EID_RUSSIAN      =7
    922 };
    923 
    924 enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
    925        // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
    926    STBTT_MS_LANG_ENGLISH     =0x0409,   STBTT_MS_LANG_ITALIAN     =0x0410,
    927    STBTT_MS_LANG_CHINESE     =0x0804,   STBTT_MS_LANG_JAPANESE    =0x0411,
    928    STBTT_MS_LANG_DUTCH       =0x0413,   STBTT_MS_LANG_KOREAN      =0x0412,
    929    STBTT_MS_LANG_FRENCH      =0x040c,   STBTT_MS_LANG_RUSSIAN     =0x0419,
    930    STBTT_MS_LANG_GERMAN      =0x0407,   STBTT_MS_LANG_SPANISH     =0x0409,
    931    STBTT_MS_LANG_HEBREW      =0x040d,   STBTT_MS_LANG_SWEDISH     =0x041D
    932 };
    933 
    934 enum { // languageID for STBTT_PLATFORM_ID_MAC
    935    STBTT_MAC_LANG_ENGLISH      =0 ,   STBTT_MAC_LANG_JAPANESE     =11,
    936    STBTT_MAC_LANG_ARABIC       =12,   STBTT_MAC_LANG_KOREAN       =23,
    937    STBTT_MAC_LANG_DUTCH        =4 ,   STBTT_MAC_LANG_RUSSIAN      =32,
    938    STBTT_MAC_LANG_FRENCH       =1 ,   STBTT_MAC_LANG_SPANISH      =6 ,
    939    STBTT_MAC_LANG_GERMAN       =2 ,   STBTT_MAC_LANG_SWEDISH      =5 ,
    940    STBTT_MAC_LANG_HEBREW       =10,   STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
    941    STBTT_MAC_LANG_ITALIAN      =3 ,   STBTT_MAC_LANG_CHINESE_TRAD =19
    942 };
    943 
    944 #ifdef __cplusplus
    945 }
    946 #endif
    947 
    948 #endif // __STB_INCLUDE_STB_TRUETYPE_H__
    949 
    950 ///////////////////////////////////////////////////////////////////////////////
    951 ///////////////////////////////////////////////////////////////////////////////
    952 ////
    953 ////   IMPLEMENTATION
    954 ////
    955 ////
    956 
    957 #ifdef STB_TRUETYPE_IMPLEMENTATION
    958 
    959 #ifndef STBTT_MAX_OVERSAMPLE
    960 #define STBTT_MAX_OVERSAMPLE   8
    961 #endif
    962 
    963 #if STBTT_MAX_OVERSAMPLE > 255
    964 #error "STBTT_MAX_OVERSAMPLE cannot be > 255"
    965 #endif
    966 
    967 typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];
    968 
    969 #ifndef STBTT_RASTERIZER_VERSION
    970 #define STBTT_RASTERIZER_VERSION 2
    971 #endif
    972 
    973 #ifdef _MSC_VER
    974 #define STBTT__NOTUSED(v)  (void)(v)
    975 #else
    976 #define STBTT__NOTUSED(v)  (void)sizeof(v)
    977 #endif
    978 
    979 //////////////////////////////////////////////////////////////////////////
    980 //
    981 // stbtt__buf helpers to parse data from file
    982 //
    983 
    984 static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b)
    985 {
    986    if (b->cursor >= b->size)
    987       return 0;
    988    return b->data[b->cursor++];
    989 }
    990 
    991 static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b)
    992 {
    993    if (b->cursor >= b->size)
    994       return 0;
    995    return b->data[b->cursor];
    996 }
    997 
    998 static void stbtt__buf_seek(stbtt__buf *b, int o)
    999 {
   1000    STBTT_assert(!(o > b->size || o < 0));
   1001    b->cursor = (o > b->size || o < 0) ? b->size : o;
   1002 }
   1003 
   1004 static void stbtt__buf_skip(stbtt__buf *b, int o)
   1005 {
   1006    stbtt__buf_seek(b, b->cursor + o);
   1007 }
   1008 
   1009 static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n)
   1010 {
   1011    stbtt_uint32 v = 0;
   1012    int i;
   1013    STBTT_assert(n >= 1 && n <= 4);
   1014    for (i = 0; i < n; i++)
   1015       v = (v << 8) | stbtt__buf_get8(b);
   1016    return v;
   1017 }
   1018 
   1019 static stbtt__buf stbtt__new_buf(const void *p, size_t size)
   1020 {
   1021    stbtt__buf r;
   1022    STBTT_assert(size < 0x40000000);
   1023    r.data = (stbtt_uint8*) p;
   1024    r.size = (int) size;
   1025    r.cursor = 0;
   1026    return r;
   1027 }
   1028 
   1029 #define stbtt__buf_get16(b)  stbtt__buf_get((b), 2)
   1030 #define stbtt__buf_get32(b)  stbtt__buf_get((b), 4)
   1031 
   1032 static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s)
   1033 {
   1034    stbtt__buf r = stbtt__new_buf(NULL, 0);
   1035    if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r;
   1036    r.data = b->data + o;
   1037    r.size = s;
   1038    return r;
   1039 }
   1040 
   1041 static stbtt__buf stbtt__cff_get_index(stbtt__buf *b)
   1042 {
   1043    int count, start, offsize;
   1044    start = b->cursor;
   1045    count = stbtt__buf_get16(b);
   1046    if (count) {
   1047       offsize = stbtt__buf_get8(b);
   1048       STBTT_assert(offsize >= 1 && offsize <= 4);
   1049       stbtt__buf_skip(b, offsize * count);
   1050       stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);
   1051    }
   1052    return stbtt__buf_range(b, start, b->cursor - start);
   1053 }
   1054 
   1055 static stbtt_uint32 stbtt__cff_int(stbtt__buf *b)
   1056 {
   1057    int b0 = stbtt__buf_get8(b);
   1058    if (b0 >= 32 && b0 <= 246)       return b0 - 139;
   1059    else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108;
   1060    else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108;
   1061    else if (b0 == 28)               return stbtt__buf_get16(b);
   1062    else if (b0 == 29)               return stbtt__buf_get32(b);
   1063    STBTT_assert(0);
   1064    return 0;
   1065 }
   1066 
   1067 static void stbtt__cff_skip_operand(stbtt__buf *b) {
   1068    int v, b0 = stbtt__buf_peek8(b);
   1069    STBTT_assert(b0 >= 28);
   1070    if (b0 == 30) {
   1071       stbtt__buf_skip(b, 1);
   1072       while (b->cursor < b->size) {
   1073          v = stbtt__buf_get8(b);
   1074          if ((v & 0xF) == 0xF || (v >> 4) == 0xF)
   1075             break;
   1076       }
   1077    } else {
   1078       stbtt__cff_int(b);
   1079    }
   1080 }
   1081 
   1082 static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key)
   1083 {
   1084    stbtt__buf_seek(b, 0);
   1085    while (b->cursor < b->size) {
   1086       int start = b->cursor, end, op;
   1087       while (stbtt__buf_peek8(b) >= 28)
   1088          stbtt__cff_skip_operand(b);
   1089       end = b->cursor;
   1090       op = stbtt__buf_get8(b);
   1091       if (op == 12)  op = stbtt__buf_get8(b) | 0x100;
   1092       if (op == key) return stbtt__buf_range(b, start, end-start);
   1093    }
   1094    return stbtt__buf_range(b, 0, 0);
   1095 }
   1096 
   1097 static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out)
   1098 {
   1099    int i;
   1100    stbtt__buf operands = stbtt__dict_get(b, key);
   1101    for (i = 0; i < outcount && operands.cursor < operands.size; i++)
   1102       out[i] = stbtt__cff_int(&operands);
   1103 }
   1104 
   1105 static int stbtt__cff_index_count(stbtt__buf *b)
   1106 {
   1107    stbtt__buf_seek(b, 0);
   1108    return stbtt__buf_get16(b);
   1109 }
   1110 
   1111 static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)
   1112 {
   1113    int count, offsize, start, end;
   1114    stbtt__buf_seek(&b, 0);
   1115    count = stbtt__buf_get16(&b);
   1116    offsize = stbtt__buf_get8(&b);
   1117    STBTT_assert(i >= 0 && i < count);
   1118    STBTT_assert(offsize >= 1 && offsize <= 4);
   1119    stbtt__buf_skip(&b, i*offsize);
   1120    start = stbtt__buf_get(&b, offsize);
   1121    end = stbtt__buf_get(&b, offsize);
   1122    return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start);
   1123 }
   1124 
   1125 //////////////////////////////////////////////////////////////////////////
   1126 //
   1127 // accessors to parse data from file
   1128 //
   1129 
   1130 // on platforms that don't allow misaligned reads, if we want to allow
   1131 // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
   1132 
   1133 #define ttBYTE(p)     (* (stbtt_uint8 *) (p))
   1134 #define ttCHAR(p)     (* (stbtt_int8 *) (p))
   1135 #define ttFixed(p)    ttLONG(p)
   1136 
   1137 static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }
   1138 static stbtt_int16 ttSHORT(stbtt_uint8 *p)   { return p[0]*256 + p[1]; }
   1139 static stbtt_uint32 ttULONG(stbtt_uint8 *p)  { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
   1140 static stbtt_int32 ttLONG(stbtt_uint8 *p)    { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
   1141 
   1142 #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
   1143 #define stbtt_tag(p,str)           stbtt_tag4(p,str[0],str[1],str[2],str[3])
   1144 
   1145 static int stbtt__isfont(stbtt_uint8 *font)
   1146 {
   1147    // check the version number
   1148    if (stbtt_tag4(font, '1',0,0,0))  return 1; // TrueType 1
   1149    if (stbtt_tag(font, "typ1"))   return 1; // TrueType with type 1 font -- we don't support this!
   1150    if (stbtt_tag(font, "OTTO"))   return 1; // OpenType with CFF
   1151    if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
   1152    if (stbtt_tag(font, "true"))   return 1; // Apple specification for TrueType fonts
   1153    return 0;
   1154 }
   1155 
   1156 // @OPTIMIZE: binary search
   1157 static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
   1158 {
   1159    stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
   1160    stbtt_uint32 tabledir = fontstart + 12;
   1161    stbtt_int32 i;
   1162    for (i=0; i < num_tables; ++i) {
   1163       stbtt_uint32 loc = tabledir + 16*i;
   1164       if (stbtt_tag(data+loc+0, tag))
   1165          return ttULONG(data+loc+8);
   1166    }
   1167    return 0;
   1168 }
   1169 
   1170 static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index)
   1171 {
   1172    // if it's just a font, there's only one valid index
   1173    if (stbtt__isfont(font_collection))
   1174       return index == 0 ? 0 : -1;
   1175 
   1176    // check if it's a TTC
   1177    if (stbtt_tag(font_collection, "ttcf")) {
   1178       // version 1?
   1179       if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
   1180          stbtt_int32 n = ttLONG(font_collection+8);
   1181          if (index >= n)
   1182             return -1;
   1183          return ttULONG(font_collection+12+index*4);
   1184       }
   1185    }
   1186    return -1;
   1187 }
   1188 
   1189 static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection)
   1190 {
   1191    // if it's just a font, there's only one valid font
   1192    if (stbtt__isfont(font_collection))
   1193       return 1;
   1194 
   1195    // check if it's a TTC
   1196    if (stbtt_tag(font_collection, "ttcf")) {
   1197       // version 1?
   1198       if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
   1199          return ttLONG(font_collection+8);
   1200       }
   1201    }
   1202    return 0;
   1203 }
   1204 
   1205 static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)
   1206 {
   1207    stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };
   1208    stbtt__buf pdict;
   1209    stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);
   1210    if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);
   1211    pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);
   1212    stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);
   1213    if (!subrsoff) return stbtt__new_buf(NULL, 0);
   1214    stbtt__buf_seek(&cff, private_loc[1]+subrsoff);
   1215    return stbtt__cff_get_index(&cff);
   1216 }
   1217 
   1218 static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart)
   1219 {
   1220    stbtt_uint32 cmap, t;
   1221    stbtt_int32 i,numTables;
   1222 
   1223    info->data = data;
   1224    info->fontstart = fontstart;
   1225    info->cff = stbtt__new_buf(NULL, 0);
   1226 
   1227    cmap = stbtt__find_table(data, fontstart, "cmap");       // required
   1228    info->loca = stbtt__find_table(data, fontstart, "loca"); // required
   1229    info->head = stbtt__find_table(data, fontstart, "head"); // required
   1230    info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
   1231    info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
   1232    info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
   1233    info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
   1234 
   1235    if (!cmap || !info->head || !info->hhea || !info->hmtx)
   1236       return 0;
   1237    if (info->glyf) {
   1238       // required for truetype
   1239       if (!info->loca) return 0;
   1240    } else {
   1241       // initialization for CFF / Type2 fonts (OTF)
   1242       stbtt__buf b, topdict, topdictidx;
   1243       stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;
   1244       stbtt_uint32 cff;
   1245 
   1246       cff = stbtt__find_table(data, fontstart, "CFF ");
   1247       if (!cff) return 0;
   1248 
   1249       info->fontdicts = stbtt__new_buf(NULL, 0);
   1250       info->fdselect = stbtt__new_buf(NULL, 0);
   1251 
   1252       // @TODO this should use size from table (not 512MB)
   1253       info->cff = stbtt__new_buf(data+cff, 512*1024*1024);
   1254       b = info->cff;
   1255 
   1256       // read the header
   1257       stbtt__buf_skip(&b, 2);
   1258       stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize
   1259 
   1260       // @TODO the name INDEX could list multiple fonts,
   1261       // but we just use the first one.
   1262       stbtt__cff_get_index(&b);  // name INDEX
   1263       topdictidx = stbtt__cff_get_index(&b);
   1264       topdict = stbtt__cff_index_get(topdictidx, 0);
   1265       stbtt__cff_get_index(&b);  // string INDEX
   1266       info->gsubrs = stbtt__cff_get_index(&b);
   1267 
   1268       stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);
   1269       stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);
   1270       stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);
   1271       stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);
   1272       info->subrs = stbtt__get_subrs(b, topdict);
   1273 
   1274       // we only support Type 2 charstrings
   1275       if (cstype != 2) return 0;
   1276       if (charstrings == 0) return 0;
   1277 
   1278       if (fdarrayoff) {
   1279          // looks like a CID font
   1280          if (!fdselectoff) return 0;
   1281          stbtt__buf_seek(&b, fdarrayoff);
   1282          info->fontdicts = stbtt__cff_get_index(&b);
   1283          info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff);
   1284       }
   1285 
   1286       stbtt__buf_seek(&b, charstrings);
   1287       info->charstrings = stbtt__cff_get_index(&b);
   1288    }
   1289 
   1290    t = stbtt__find_table(data, fontstart, "maxp");
   1291    if (t)
   1292       info->numGlyphs = ttUSHORT(data+t+4);
   1293    else
   1294       info->numGlyphs = 0xffff;
   1295 
   1296    // find a cmap encoding table we understand *now* to avoid searching
   1297    // later. (todo: could make this installable)
   1298    // the same regardless of glyph.
   1299    numTables = ttUSHORT(data + cmap + 2);
   1300    info->index_map = 0;
   1301    for (i=0; i < numTables; ++i) {
   1302       stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
   1303       // find an encoding we understand:
   1304       switch(ttUSHORT(data+encoding_record)) {
   1305          case STBTT_PLATFORM_ID_MICROSOFT:
   1306             switch (ttUSHORT(data+encoding_record+2)) {
   1307                case STBTT_MS_EID_UNICODE_BMP:
   1308                case STBTT_MS_EID_UNICODE_FULL:
   1309                   // MS/Unicode
   1310                   info->index_map = cmap + ttULONG(data+encoding_record+4);
   1311                   break;
   1312             }
   1313             break;
   1314         case STBTT_PLATFORM_ID_UNICODE:
   1315             // Mac/iOS has these
   1316             // all the encodingIDs are unicode, so we don't bother to check it
   1317             info->index_map = cmap + ttULONG(data+encoding_record+4);
   1318             break;
   1319       }
   1320    }
   1321    if (info->index_map == 0)
   1322       return 0;
   1323 
   1324    info->indexToLocFormat = ttUSHORT(data+info->head + 50);
   1325    return 1;
   1326 }
   1327 
   1328 STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
   1329 {
   1330    stbtt_uint8 *data = info->data;
   1331    stbtt_uint32 index_map = info->index_map;
   1332 
   1333    stbtt_uint16 format = ttUSHORT(data + index_map + 0);
   1334    if (format == 0) { // apple byte encoding
   1335       stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
   1336       if (unicode_codepoint < bytes-6)
   1337          return ttBYTE(data + index_map + 6 + unicode_codepoint);
   1338       return 0;
   1339    } else if (format == 6) {
   1340       stbtt_uint32 first = ttUSHORT(data + index_map + 6);
   1341       stbtt_uint32 count = ttUSHORT(data + index_map + 8);
   1342       if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
   1343          return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
   1344       return 0;
   1345    } else if (format == 2) {
   1346       STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
   1347       return 0;
   1348    } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges
   1349       stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
   1350       stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
   1351       stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
   1352       stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
   1353 
   1354       // do a binary search of the segments
   1355       stbtt_uint32 endCount = index_map + 14;
   1356       stbtt_uint32 search = endCount;
   1357 
   1358       if (unicode_codepoint > 0xffff)
   1359          return 0;
   1360 
   1361       // they lie from endCount .. endCount + segCount
   1362       // but searchRange is the nearest power of two, so...
   1363       if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
   1364          search += rangeShift*2;
   1365 
   1366       // now decrement to bias correctly to find smallest
   1367       search -= 2;
   1368       while (entrySelector) {
   1369          stbtt_uint16 end;
   1370          searchRange >>= 1;
   1371          end = ttUSHORT(data + search + searchRange*2);
   1372          if (unicode_codepoint > end)
   1373             search += searchRange*2;
   1374          --entrySelector;
   1375       }
   1376       search += 2;
   1377 
   1378       {
   1379          stbtt_uint16 offset, start;
   1380          stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);
   1381 
   1382          STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
   1383          start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
   1384          if (unicode_codepoint < start)
   1385             return 0;
   1386 
   1387          offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
   1388          if (offset == 0)
   1389             return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
   1390 
   1391          return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
   1392       }
   1393    } else if (format == 12 || format == 13) {
   1394       stbtt_uint32 ngroups = ttULONG(data+index_map+12);
   1395       stbtt_int32 low,high;
   1396       low = 0; high = (stbtt_int32)ngroups;
   1397       // Binary search the right group.
   1398       while (low < high) {
   1399          stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high
   1400          stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
   1401          stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
   1402          if ((stbtt_uint32) unicode_codepoint < start_char)
   1403             high = mid;
   1404          else if ((stbtt_uint32) unicode_codepoint > end_char)
   1405             low = mid+1;
   1406          else {
   1407             stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
   1408             if (format == 12)
   1409                return start_glyph + unicode_codepoint-start_char;
   1410             else // format == 13
   1411                return start_glyph;
   1412          }
   1413       }
   1414       return 0; // not found
   1415    }
   1416    // @TODO
   1417    STBTT_assert(0);
   1418    return 0;
   1419 }
   1420 
   1421 STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
   1422 {
   1423    return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
   1424 }
   1425 
   1426 static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
   1427 {
   1428    v->type = type;
   1429    v->x = (stbtt_int16) x;
   1430    v->y = (stbtt_int16) y;
   1431    v->cx = (stbtt_int16) cx;
   1432    v->cy = (stbtt_int16) cy;
   1433 }
   1434 
   1435 static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
   1436 {
   1437    int g1,g2;
   1438 
   1439    STBTT_assert(!info->cff.size);
   1440 
   1441    if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
   1442    if (info->indexToLocFormat >= 2)    return -1; // unknown index->glyph map format
   1443 
   1444    if (info->indexToLocFormat == 0) {
   1445       g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
   1446       g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
   1447    } else {
   1448       g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
   1449       g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
   1450    }
   1451 
   1452    return g1==g2 ? -1 : g1; // if length is 0, return -1
   1453 }
   1454 
   1455 static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
   1456 
   1457 STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
   1458 {
   1459    if (info->cff.size) {
   1460       stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);
   1461    } else {
   1462       int g = stbtt__GetGlyfOffset(info, glyph_index);
   1463       if (g < 0) return 0;
   1464 
   1465       if (x0) *x0 = ttSHORT(info->data + g + 2);
   1466       if (y0) *y0 = ttSHORT(info->data + g + 4);
   1467       if (x1) *x1 = ttSHORT(info->data + g + 6);
   1468       if (y1) *y1 = ttSHORT(info->data + g + 8);
   1469    }
   1470    return 1;
   1471 }
   1472 
   1473 STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
   1474 {
   1475    return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
   1476 }
   1477 
   1478 STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
   1479 {
   1480    stbtt_int16 numberOfContours;
   1481    int g;
   1482    if (info->cff.size)
   1483       return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;
   1484    g = stbtt__GetGlyfOffset(info, glyph_index);
   1485    if (g < 0) return 1;
   1486    numberOfContours = ttSHORT(info->data + g);
   1487    return numberOfContours == 0;
   1488 }
   1489 
   1490 static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
   1491     stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
   1492 {
   1493    if (start_off) {
   1494       if (was_off)
   1495          stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
   1496       stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
   1497    } else {
   1498       if (was_off)
   1499          stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
   1500       else
   1501          stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
   1502    }
   1503    return num_vertices;
   1504 }
   1505 
   1506 static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
   1507 {
   1508    stbtt_int16 numberOfContours;
   1509    stbtt_uint8 *endPtsOfContours;
   1510    stbtt_uint8 *data = info->data;
   1511    stbtt_vertex *vertices=0;
   1512    int num_vertices=0;
   1513    int g = stbtt__GetGlyfOffset(info, glyph_index);
   1514 
   1515    *pvertices = NULL;
   1516 
   1517    if (g < 0) return 0;
   1518 
   1519    numberOfContours = ttSHORT(data + g);
   1520 
   1521    if (numberOfContours > 0) {
   1522       stbtt_uint8 flags=0,flagcount;
   1523       stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
   1524       stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
   1525       stbtt_uint8 *points;
   1526       endPtsOfContours = (data + g + 10);
   1527       ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
   1528       points = data + g + 10 + numberOfContours * 2 + 2 + ins;
   1529 
   1530       n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
   1531 
   1532       m = n + 2*numberOfContours;  // a loose bound on how many vertices we might need
   1533       vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
   1534       if (vertices == 0)
   1535          return 0;
   1536 
   1537       next_move = 0;
   1538       flagcount=0;
   1539 
   1540       // in first pass, we load uninterpreted data into the allocated array
   1541       // above, shifted to the end of the array so we won't overwrite it when
   1542       // we create our final data starting from the front
   1543 
   1544       off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
   1545 
   1546       // first load flags
   1547 
   1548       for (i=0; i < n; ++i) {
   1549          if (flagcount == 0) {
   1550             flags = *points++;
   1551             if (flags & 8)
   1552                flagcount = *points++;
   1553          } else
   1554             --flagcount;
   1555          vertices[off+i].type = flags;
   1556       }
   1557 
   1558       // now load x coordinates
   1559       x=0;
   1560       for (i=0; i < n; ++i) {
   1561          flags = vertices[off+i].type;
   1562          if (flags & 2) {
   1563             stbtt_int16 dx = *points++;
   1564             x += (flags & 16) ? dx : -dx; // ???
   1565          } else {
   1566             if (!(flags & 16)) {
   1567                x = x + (stbtt_int16) (points[0]*256 + points[1]);
   1568                points += 2;
   1569             }
   1570          }
   1571          vertices[off+i].x = (stbtt_int16) x;
   1572       }
   1573 
   1574       // now load y coordinates
   1575       y=0;
   1576       for (i=0; i < n; ++i) {
   1577          flags = vertices[off+i].type;
   1578          if (flags & 4) {
   1579             stbtt_int16 dy = *points++;
   1580             y += (flags & 32) ? dy : -dy; // ???
   1581          } else {
   1582             if (!(flags & 32)) {
   1583                y = y + (stbtt_int16) (points[0]*256 + points[1]);
   1584                points += 2;
   1585             }
   1586          }
   1587          vertices[off+i].y = (stbtt_int16) y;
   1588       }
   1589 
   1590       // now convert them to our format
   1591       num_vertices=0;
   1592       sx = sy = cx = cy = scx = scy = 0;
   1593       for (i=0; i < n; ++i) {
   1594          flags = vertices[off+i].type;
   1595          x     = (stbtt_int16) vertices[off+i].x;
   1596          y     = (stbtt_int16) vertices[off+i].y;
   1597 
   1598          if (next_move == i) {
   1599             if (i != 0)
   1600                num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
   1601 
   1602             // now start the new one               
   1603             start_off = !(flags & 1);
   1604             if (start_off) {
   1605                // if we start off with an off-curve point, then when we need to find a point on the curve
   1606                // where we can start, and we need to save some state for when we wraparound.
   1607                scx = x;
   1608                scy = y;
   1609                if (!(vertices[off+i+1].type & 1)) {
   1610                   // next point is also a curve point, so interpolate an on-point curve
   1611                   sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
   1612                   sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
   1613                } else {
   1614                   // otherwise just use the next point as our start point
   1615                   sx = (stbtt_int32) vertices[off+i+1].x;
   1616                   sy = (stbtt_int32) vertices[off+i+1].y;
   1617                   ++i; // we're using point i+1 as the starting point, so skip it
   1618                }
   1619             } else {
   1620                sx = x;
   1621                sy = y;
   1622             }
   1623             stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
   1624             was_off = 0;
   1625             next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
   1626             ++j;
   1627          } else {
   1628             if (!(flags & 1)) { // if it's a curve
   1629                if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
   1630                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
   1631                cx = x;
   1632                cy = y;
   1633                was_off = 1;
   1634             } else {
   1635                if (was_off)
   1636                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
   1637                else
   1638                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
   1639                was_off = 0;
   1640             }
   1641          }
   1642       }
   1643       num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
   1644    } else if (numberOfContours == -1) {
   1645       // Compound shapes.
   1646       int more = 1;
   1647       stbtt_uint8 *comp = data + g + 10;
   1648       num_vertices = 0;
   1649       vertices = 0;
   1650       while (more) {
   1651          stbtt_uint16 flags, gidx;
   1652          int comp_num_verts = 0, i;
   1653          stbtt_vertex *comp_verts = 0, *tmp = 0;
   1654          float mtx[6] = {1,0,0,1,0,0}, m, n;
   1655          
   1656          flags = ttSHORT(comp); comp+=2;
   1657          gidx = ttSHORT(comp); comp+=2;
   1658 
   1659          if (flags & 2) { // XY values
   1660             if (flags & 1) { // shorts
   1661                mtx[4] = ttSHORT(comp); comp+=2;
   1662                mtx[5] = ttSHORT(comp); comp+=2;
   1663             } else {
   1664                mtx[4] = ttCHAR(comp); comp+=1;
   1665                mtx[5] = ttCHAR(comp); comp+=1;
   1666             }
   1667          }
   1668          else {
   1669             // @TODO handle matching point
   1670             STBTT_assert(0);
   1671          }
   1672          if (flags & (1<<3)) { // WE_HAVE_A_SCALE
   1673             mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
   1674             mtx[1] = mtx[2] = 0;
   1675          } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
   1676             mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
   1677             mtx[1] = mtx[2] = 0;
   1678             mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
   1679          } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
   1680             mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
   1681             mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
   1682             mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
   1683             mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
   1684          }
   1685          
   1686          // Find transformation scales.
   1687          m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
   1688          n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
   1689 
   1690          // Get indexed glyph.
   1691          comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
   1692          if (comp_num_verts > 0) {
   1693             // Transform vertices.
   1694             for (i = 0; i < comp_num_verts; ++i) {
   1695                stbtt_vertex* v = &comp_verts[i];
   1696                stbtt_vertex_type x,y;
   1697                x=v->x; y=v->y;
   1698                v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
   1699                v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
   1700                x=v->cx; y=v->cy;
   1701                v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
   1702                v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
   1703             }
   1704             // Append vertices.
   1705             tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
   1706             if (!tmp) {
   1707                if (vertices) STBTT_free(vertices, info->userdata);
   1708                if (comp_verts) STBTT_free(comp_verts, info->userdata);
   1709                return 0;
   1710             }
   1711             if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));
   1712             STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
   1713             if (vertices) STBTT_free(vertices, info->userdata);
   1714             vertices = tmp;
   1715             STBTT_free(comp_verts, info->userdata);
   1716             num_vertices += comp_num_verts;
   1717          }
   1718          // More components ?
   1719          more = flags & (1<<5);
   1720       }
   1721    } else if (numberOfContours < 0) {
   1722       // @TODO other compound variations?
   1723       STBTT_assert(0);
   1724    } else {
   1725       // numberOfCounters == 0, do nothing
   1726    }
   1727 
   1728    *pvertices = vertices;
   1729    return num_vertices;
   1730 }
   1731 
   1732 typedef struct
   1733 {
   1734    int bounds;
   1735    int started;
   1736    float first_x, first_y;
   1737    float x, y;
   1738    stbtt_int32 min_x, max_x, min_y, max_y;
   1739 
   1740    stbtt_vertex *pvertices;
   1741    int num_vertices;
   1742 } stbtt__csctx;
   1743 
   1744 #define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}
   1745 
   1746 static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y)
   1747 {
   1748    if (x > c->max_x || !c->started) c->max_x = x;
   1749    if (y > c->max_y || !c->started) c->max_y = y;
   1750    if (x < c->min_x || !c->started) c->min_x = x;
   1751    if (y < c->min_y || !c->started) c->min_y = y;
   1752    c->started = 1;
   1753 }
   1754 
   1755 static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)
   1756 {
   1757    if (c->bounds) {
   1758       stbtt__track_vertex(c, x, y);
   1759       if (type == STBTT_vcubic) {
   1760          stbtt__track_vertex(c, cx, cy);
   1761          stbtt__track_vertex(c, cx1, cy1);
   1762       }
   1763    } else {
   1764       stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);
   1765       c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1;
   1766       c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1;
   1767    }
   1768    c->num_vertices++;
   1769 }
   1770 
   1771 static void stbtt__csctx_close_shape(stbtt__csctx *ctx)
   1772 {
   1773    if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)
   1774       stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);
   1775 }
   1776 
   1777 static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy)
   1778 {
   1779    stbtt__csctx_close_shape(ctx);
   1780    ctx->first_x = ctx->x = ctx->x + dx;
   1781    ctx->first_y = ctx->y = ctx->y + dy;
   1782    stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
   1783 }
   1784 
   1785 static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy)
   1786 {
   1787    ctx->x += dx;
   1788    ctx->y += dy;
   1789    stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
   1790 }
   1791 
   1792 static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)
   1793 {
   1794    float cx1 = ctx->x + dx1;
   1795    float cy1 = ctx->y + dy1;
   1796    float cx2 = cx1 + dx2;
   1797    float cy2 = cy1 + dy2;
   1798    ctx->x = cx2 + dx3;
   1799    ctx->y = cy2 + dy3;
   1800    stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);
   1801 }
   1802 
   1803 static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)
   1804 {
   1805    int count = stbtt__cff_index_count(&idx);
   1806    int bias = 107;
   1807    if (count >= 33900)
   1808       bias = 32768;
   1809    else if (count >= 1240)
   1810       bias = 1131;
   1811    n += bias;
   1812    if (n < 0 || n >= count)
   1813       return stbtt__new_buf(NULL, 0);
   1814    return stbtt__cff_index_get(idx, n);
   1815 }
   1816 
   1817 static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index)
   1818 {
   1819    stbtt__buf fdselect = info->fdselect;
   1820    int nranges, start, end, v, fmt, fdselector = -1, i;
   1821 
   1822    stbtt__buf_seek(&fdselect, 0);
   1823    fmt = stbtt__buf_get8(&fdselect);
   1824    if (fmt == 0) {
   1825       // untested
   1826       stbtt__buf_skip(&fdselect, glyph_index);
   1827       fdselector = stbtt__buf_get8(&fdselect);
   1828    } else if (fmt == 3) {
   1829       nranges = stbtt__buf_get16(&fdselect);
   1830       start = stbtt__buf_get16(&fdselect);
   1831       for (i = 0; i < nranges; i++) {
   1832          v = stbtt__buf_get8(&fdselect);
   1833          end = stbtt__buf_get16(&fdselect);
   1834          if (glyph_index >= start && glyph_index < end) {
   1835             fdselector = v;
   1836             break;
   1837          }
   1838          start = end;
   1839       }
   1840    }
   1841    if (fdselector == -1) stbtt__new_buf(NULL, 0);
   1842    return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));
   1843 }
   1844 
   1845 static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c)
   1846 {
   1847    int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;
   1848    int has_subrs = 0, clear_stack;
   1849    float s[48];
   1850    stbtt__buf subr_stack[10], subrs = info->subrs, b;
   1851    float f;
   1852 
   1853 #define STBTT__CSERR(s) (0)
   1854 
   1855    // this currently ignores the initial width value, which isn't needed if we have hmtx
   1856    b = stbtt__cff_index_get(info->charstrings, glyph_index);
   1857    while (b.cursor < b.size) {
   1858       i = 0;
   1859       clear_stack = 1;
   1860       b0 = stbtt__buf_get8(&b);
   1861       switch (b0) {
   1862       // @TODO implement hinting
   1863       case 0x13: // hintmask
   1864       case 0x14: // cntrmask
   1865          if (in_header)
   1866             maskbits += (sp / 2); // implicit "vstem"
   1867          in_header = 0;
   1868          stbtt__buf_skip(&b, (maskbits + 7) / 8);
   1869          break;
   1870 
   1871       case 0x01: // hstem
   1872       case 0x03: // vstem
   1873       case 0x12: // hstemhm
   1874       case 0x17: // vstemhm
   1875          maskbits += (sp / 2);
   1876          break;
   1877 
   1878       case 0x15: // rmoveto
   1879          in_header = 0;
   1880          if (sp < 2) return STBTT__CSERR("rmoveto stack");
   1881          stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]);
   1882          break;
   1883       case 0x04: // vmoveto
   1884          in_header = 0;
   1885          if (sp < 1) return STBTT__CSERR("vmoveto stack");
   1886          stbtt__csctx_rmove_to(c, 0, s[sp-1]);
   1887          break;
   1888       case 0x16: // hmoveto
   1889          in_header = 0;
   1890          if (sp < 1) return STBTT__CSERR("hmoveto stack");
   1891          stbtt__csctx_rmove_to(c, s[sp-1], 0);
   1892          break;
   1893 
   1894       case 0x05: // rlineto
   1895          if (sp < 2) return STBTT__CSERR("rlineto stack");
   1896          for (; i + 1 < sp; i += 2)
   1897             stbtt__csctx_rline_to(c, s[i], s[i+1]);
   1898          break;
   1899 
   1900       // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical
   1901       // starting from a different place.
   1902 
   1903       case 0x07: // vlineto
   1904          if (sp < 1) return STBTT__CSERR("vlineto stack");
   1905          goto vlineto;
   1906       case 0x06: // hlineto
   1907          if (sp < 1) return STBTT__CSERR("hlineto stack");
   1908          for (;;) {
   1909             if (i >= sp) break;
   1910             stbtt__csctx_rline_to(c, s[i], 0);
   1911             i++;
   1912       vlineto:
   1913             if (i >= sp) break;
   1914             stbtt__csctx_rline_to(c, 0, s[i]);
   1915             i++;
   1916          }
   1917          break;
   1918 
   1919       case 0x1F: // hvcurveto
   1920          if (sp < 4) return STBTT__CSERR("hvcurveto stack");
   1921          goto hvcurveto;
   1922       case 0x1E: // vhcurveto
   1923          if (sp < 4) return STBTT__CSERR("vhcurveto stack");
   1924          for (;;) {
   1925             if (i + 3 >= sp) break;
   1926             stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f);
   1927             i += 4;
   1928       hvcurveto:
   1929             if (i + 3 >= sp) break;
   1930             stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]);
   1931             i += 4;
   1932          }
   1933          break;
   1934 
   1935       case 0x08: // rrcurveto
   1936          if (sp < 6) return STBTT__CSERR("rcurveline stack");
   1937          for (; i + 5 < sp; i += 6)
   1938             stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
   1939          break;
   1940 
   1941       case 0x18: // rcurveline
   1942          if (sp < 8) return STBTT__CSERR("rcurveline stack");
   1943          for (; i + 5 < sp - 2; i += 6)
   1944             stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
   1945          if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack");
   1946          stbtt__csctx_rline_to(c, s[i], s[i+1]);
   1947          break;
   1948 
   1949       case 0x19: // rlinecurve
   1950          if (sp < 8) return STBTT__CSERR("rlinecurve stack");
   1951          for (; i + 1 < sp - 6; i += 2)
   1952             stbtt__csctx_rline_to(c, s[i], s[i+1]);
   1953          if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack");
   1954          stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
   1955          break;
   1956 
   1957       case 0x1A: // vvcurveto
   1958       case 0x1B: // hhcurveto
   1959          if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack");
   1960          f = 0.0;
   1961          if (sp & 1) { f = s[i]; i++; }
   1962          for (; i + 3 < sp; i += 4) {
   1963             if (b0 == 0x1B)
   1964                stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0);
   1965             else
   1966                stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]);
   1967             f = 0.0;
   1968          }
   1969          break;
   1970 
   1971       case 0x0A: // callsubr
   1972          if (!has_subrs) {
   1973             if (info->fdselect.size)
   1974                subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);
   1975             has_subrs = 1;
   1976          }
   1977          // fallthrough
   1978       case 0x1D: // callgsubr
   1979          if (sp < 1) return STBTT__CSERR("call(g|)subr stack");
   1980          v = (int) s[--sp];
   1981          if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit");
   1982          subr_stack[subr_stack_height++] = b;
   1983          b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);
   1984          if (b.size == 0) return STBTT__CSERR("subr not found");
   1985          b.cursor = 0;
   1986          clear_stack = 0;
   1987          break;
   1988 
   1989       case 0x0B: // return
   1990          if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr");
   1991          b = subr_stack[--subr_stack_height];
   1992          clear_stack = 0;
   1993          break;
   1994 
   1995       case 0x0E: // endchar
   1996          stbtt__csctx_close_shape(c);
   1997          return 1;
   1998 
   1999       case 0x0C: { // two-byte escape
   2000          float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;
   2001          float dx, dy;
   2002          int b1 = stbtt__buf_get8(&b);
   2003          switch (b1) {
   2004          // @TODO These "flex" implementations ignore the flex-depth and resolution,
   2005          // and always draw beziers.
   2006          case 0x22: // hflex
   2007             if (sp < 7) return STBTT__CSERR("hflex stack");
   2008             dx1 = s[0];
   2009             dx2 = s[1];
   2010             dy2 = s[2];
   2011             dx3 = s[3];
   2012             dx4 = s[4];
   2013             dx5 = s[5];
   2014             dx6 = s[6];
   2015             stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);
   2016             stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);
   2017             break;
   2018 
   2019          case 0x23: // flex
   2020             if (sp < 13) return STBTT__CSERR("flex stack");
   2021             dx1 = s[0];
   2022             dy1 = s[1];
   2023             dx2 = s[2];
   2024             dy2 = s[3];
   2025             dx3 = s[4];
   2026             dy3 = s[5];
   2027             dx4 = s[6];
   2028             dy4 = s[7];
   2029             dx5 = s[8];
   2030             dy5 = s[9];
   2031             dx6 = s[10];
   2032             dy6 = s[11];
   2033             //fd is s[12]
   2034             stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
   2035             stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
   2036             break;
   2037 
   2038          case 0x24: // hflex1
   2039             if (sp < 9) return STBTT__CSERR("hflex1 stack");
   2040             dx1 = s[0];
   2041             dy1 = s[1];
   2042             dx2 = s[2];
   2043             dy2 = s[3];
   2044             dx3 = s[4];
   2045             dx4 = s[5];
   2046             dx5 = s[6];
   2047             dy5 = s[7];
   2048             dx6 = s[8];
   2049             stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);
   2050             stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5));
   2051             break;
   2052 
   2053          case 0x25: // flex1
   2054             if (sp < 11) return STBTT__CSERR("flex1 stack");
   2055             dx1 = s[0];
   2056             dy1 = s[1];
   2057             dx2 = s[2];
   2058             dy2 = s[3];
   2059             dx3 = s[4];
   2060             dy3 = s[5];
   2061             dx4 = s[6];
   2062             dy4 = s[7];
   2063             dx5 = s[8];
   2064             dy5 = s[9];
   2065             dx6 = dy6 = s[10];
   2066             dx = dx1+dx2+dx3+dx4+dx5;
   2067             dy = dy1+dy2+dy3+dy4+dy5;
   2068             if (STBTT_fabs(dx) > STBTT_fabs(dy))
   2069                dy6 = -dy;
   2070             else
   2071                dx6 = -dx;
   2072             stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
   2073             stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
   2074             break;
   2075 
   2076          default:
   2077             return STBTT__CSERR("unimplemented");
   2078          }
   2079       } break;
   2080 
   2081       default:
   2082          if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254))
   2083             return STBTT__CSERR("reserved operator");
   2084 
   2085          // push immediate
   2086          if (b0 == 255) {
   2087             f = (float)stbtt__buf_get32(&b) / 0x10000;
   2088          } else {
   2089             stbtt__buf_skip(&b, -1);
   2090             f = (float)(stbtt_int16)stbtt__cff_int(&b);
   2091          }
   2092          if (sp >= 48) return STBTT__CSERR("push stack overflow");
   2093          s[sp++] = f;
   2094          clear_stack = 0;
   2095          break;
   2096       }
   2097       if (clear_stack) sp = 0;
   2098    }
   2099    return STBTT__CSERR("no endchar");
   2100 
   2101 #undef STBTT__CSERR
   2102 }
   2103 
   2104 static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
   2105 {
   2106    // runs the charstring twice, once to count and once to output (to avoid realloc)
   2107    stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);
   2108    stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);
   2109    if (stbtt__run_charstring(info, glyph_index, &count_ctx)) {
   2110       *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata);
   2111       output_ctx.pvertices = *pvertices;
   2112       if (stbtt__run_charstring(info, glyph_index, &output_ctx)) {
   2113          STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);
   2114          return output_ctx.num_vertices;
   2115       }
   2116    }
   2117    *pvertices = NULL;
   2118    return 0;
   2119 }
   2120 
   2121 static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
   2122 {
   2123    stbtt__csctx c = STBTT__CSCTX_INIT(1);
   2124    int r = stbtt__run_charstring(info, glyph_index, &c);
   2125    if (x0) {
   2126       *x0 = r ? c.min_x : 0;
   2127       *y0 = r ? c.min_y : 0;
   2128       *x1 = r ? c.max_x : 0;
   2129       *y1 = r ? c.max_y : 0;
   2130    }
   2131    return r ? c.num_vertices : 0;
   2132 }
   2133 
   2134 STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
   2135 {
   2136    if (!info->cff.size)
   2137       return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);
   2138    else
   2139       return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);
   2140 }
   2141 
   2142 STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
   2143 {
   2144    stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
   2145    if (glyph_index < numOfLongHorMetrics) {
   2146       if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*glyph_index);
   2147       if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
   2148    } else {
   2149       if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
   2150       if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
   2151    }
   2152 }
   2153 
   2154 STBTT_DEF int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
   2155 {
   2156    stbtt_uint8 *data = info->data + info->kern;
   2157    stbtt_uint32 needle, straw;
   2158    int l, r, m;
   2159 
   2160    // we only look at the first table. it must be 'horizontal' and format 0.
   2161    if (!info->kern)
   2162       return 0;
   2163    if (ttUSHORT(data+2) < 1) // number of tables, need at least 1
   2164       return 0;
   2165    if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format
   2166       return 0;
   2167 
   2168    l = 0;
   2169    r = ttUSHORT(data+10) - 1;
   2170    needle = glyph1 << 16 | glyph2;
   2171    while (l <= r) {
   2172       m = (l + r) >> 1;
   2173       straw = ttULONG(data+18+(m*6)); // note: unaligned read
   2174       if (needle < straw)
   2175          r = m - 1;
   2176       else if (needle > straw)
   2177          l = m + 1;
   2178       else
   2179          return ttSHORT(data+22+(m*6));
   2180    }
   2181    return 0;
   2182 }
   2183 
   2184 STBTT_DEF int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
   2185 {
   2186    if (!info->kern) // if no kerning table, don't waste time looking up both codepoint->glyphs
   2187       return 0;
   2188    return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
   2189 }
   2190 
   2191 STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
   2192 {
   2193    stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
   2194 }
   2195 
   2196 STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
   2197 {
   2198    if (ascent ) *ascent  = ttSHORT(info->data+info->hhea + 4);
   2199    if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
   2200    if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
   2201 }
   2202 
   2203 STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
   2204 {
   2205    *x0 = ttSHORT(info->data + info->head + 36);
   2206    *y0 = ttSHORT(info->data + info->head + 38);
   2207    *x1 = ttSHORT(info->data + info->head + 40);
   2208    *y1 = ttSHORT(info->data + info->head + 42);
   2209 }
   2210 
   2211 STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
   2212 {
   2213    int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
   2214    return (float) height / fheight;
   2215 }
   2216 
   2217 STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
   2218 {
   2219    int unitsPerEm = ttUSHORT(info->data + info->head + 18);
   2220    return pixels / unitsPerEm;
   2221 }
   2222 
   2223 STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
   2224 {
   2225    STBTT_free(v, info->userdata);
   2226 }
   2227 
   2228 //////////////////////////////////////////////////////////////////////////////
   2229 //
   2230 // antialiasing software rasterizer
   2231 //
   2232 
   2233 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)
   2234 {
   2235    int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning
   2236    if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {
   2237       // e.g. space character
   2238       if (ix0) *ix0 = 0;
   2239       if (iy0) *iy0 = 0;
   2240       if (ix1) *ix1 = 0;
   2241       if (iy1) *iy1 = 0;
   2242    } else {
   2243       // move to integral bboxes (treating pixels as little squares, what pixels get touched)?
   2244       if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);
   2245       if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);
   2246       if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);
   2247       if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);
   2248    }
   2249 }
   2250 
   2251 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)
   2252 {
   2253    stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
   2254 }
   2255 
   2256 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)
   2257 {
   2258    stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
   2259 }
   2260 
   2261 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)
   2262 {
   2263    stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
   2264 }
   2265 
   2266 //////////////////////////////////////////////////////////////////////////////
   2267 //
   2268 //  Rasterizer
   2269 
   2270 typedef struct stbtt__hheap_chunk
   2271 {
   2272    struct stbtt__hheap_chunk *next;
   2273 } stbtt__hheap_chunk;
   2274 
   2275 typedef struct stbtt__hheap
   2276 {
   2277    struct stbtt__hheap_chunk *head;
   2278    void   *first_free;
   2279    int    num_remaining_in_head_chunk;
   2280 } stbtt__hheap;
   2281 
   2282 static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)
   2283 {
   2284    if (hh->first_free) {
   2285       void *p = hh->first_free;
   2286       hh->first_free = * (void **) p;
   2287       return p;
   2288    } else {
   2289       if (hh->num_remaining_in_head_chunk == 0) {
   2290          int count = (size < 32 ? 2000 : size < 128 ? 800 : 100);
   2291          stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);
   2292          if (c == NULL)
   2293             return NULL;
   2294          c->next = hh->head;
   2295          hh->head = c;
   2296          hh->num_remaining_in_head_chunk = count;
   2297       }
   2298       --hh->num_remaining_in_head_chunk;
   2299       return (char *) (hh->head) + size * hh->num_remaining_in_head_chunk;
   2300    }
   2301 }
   2302 
   2303 static void stbtt__hheap_free(stbtt__hheap *hh, void *p)
   2304 {
   2305    *(void **) p = hh->first_free;
   2306    hh->first_free = p;
   2307 }
   2308 
   2309 static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata)
   2310 {
   2311    stbtt__hheap_chunk *c = hh->head;
   2312    while (c) {
   2313       stbtt__hheap_chunk *n = c->next;
   2314       STBTT_free(c, userdata);
   2315       c = n;
   2316    }
   2317 }
   2318 
   2319 typedef struct stbtt__edge {
   2320    float x0,y0, x1,y1;
   2321    int invert;
   2322 } stbtt__edge;
   2323 
   2324 
   2325 typedef struct stbtt__active_edge
   2326 {
   2327    struct stbtt__active_edge *next;
   2328    #if STBTT_RASTERIZER_VERSION==1
   2329    int x,dx;
   2330    float ey;
   2331    int direction;
   2332    #elif STBTT_RASTERIZER_VERSION==2
   2333    float fx,fdx,fdy;
   2334    float direction;
   2335    float sy;
   2336    float ey;
   2337    #else
   2338    #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
   2339    #endif
   2340 } stbtt__active_edge;
   2341 
   2342 #if STBTT_RASTERIZER_VERSION == 1
   2343 #define STBTT_FIXSHIFT   10
   2344 #define STBTT_FIX        (1 << STBTT_FIXSHIFT)
   2345 #define STBTT_FIXMASK    (STBTT_FIX-1)
   2346 
   2347 static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
   2348 {
   2349    stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
   2350    float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
   2351    STBTT_assert(z != NULL);
   2352    if (!z) return z;
   2353    
   2354    // round dx down to avoid overshooting
   2355    if (dxdy < 0)
   2356       z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);
   2357    else
   2358       z->dx = STBTT_ifloor(STBTT_FIX * dxdy);
   2359 
   2360    z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount
   2361    z->x -= off_x * STBTT_FIX;
   2362 
   2363    z->ey = e->y1;
   2364    z->next = 0;
   2365    z->direction = e->invert ? 1 : -1;
   2366    return z;
   2367 }
   2368 #elif STBTT_RASTERIZER_VERSION == 2
   2369 static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
   2370 {
   2371    stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
   2372    float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
   2373    STBTT_assert(z != NULL);
   2374    //STBTT_assert(e->y0 <= start_point);
   2375    if (!z) return z;
   2376    z->fdx = dxdy;
   2377    z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f;
   2378    z->fx = e->x0 + dxdy * (start_point - e->y0);
   2379    z->fx -= off_x;
   2380    z->direction = e->invert ? 1.0f : -1.0f;
   2381    z->sy = e->y0;
   2382    z->ey = e->y1;
   2383    z->next = 0;
   2384    return z;
   2385 }
   2386 #else
   2387 #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
   2388 #endif
   2389 
   2390 #if STBTT_RASTERIZER_VERSION == 1
   2391 // note: this routine clips fills that extend off the edges... ideally this
   2392 // wouldn't happen, but it could happen if the truetype glyph bounding boxes
   2393 // are wrong, or if the user supplies a too-small bitmap
   2394 static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
   2395 {
   2396    // non-zero winding fill
   2397    int x0=0, w=0;
   2398 
   2399    while (e) {
   2400       if (w == 0) {
   2401          // if we're currently at zero, we need to record the edge start point
   2402          x0 = e->x; w += e->direction;
   2403       } else {
   2404          int x1 = e->x; w += e->direction;
   2405          // if we went to zero, we need to draw
   2406          if (w == 0) {
   2407             int i = x0 >> STBTT_FIXSHIFT;
   2408             int j = x1 >> STBTT_FIXSHIFT;
   2409 
   2410             if (i < len && j >= 0) {
   2411                if (i == j) {
   2412                   // x0,x1 are the same pixel, so compute combined coverage
   2413                   scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT);
   2414                } else {
   2415                   if (i >= 0) // add antialiasing for x0
   2416                      scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);
   2417                   else
   2418                      i = -1; // clip
   2419 
   2420                   if (j < len) // add antialiasing for x1
   2421                      scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);
   2422                   else
   2423                      j = len; // clip
   2424 
   2425                   for (++i; i < j; ++i) // fill pixels between x0 and x1
   2426                      scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
   2427                }
   2428             }
   2429          }
   2430       }
   2431       
   2432       e = e->next;
   2433    }
   2434 }
   2435 
   2436 static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
   2437 {
   2438    stbtt__hheap hh = { 0, 0, 0 };
   2439    stbtt__active_edge *active = NULL;
   2440    int y,j=0;
   2441    int max_weight = (255 / vsubsample);  // weight per vertical scanline
   2442    int s; // vertical subsample index
   2443    unsigned char scanline_data[512], *scanline;
   2444 
   2445    if (result->w > 512)
   2446       scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
   2447    else
   2448       scanline = scanline_data;
   2449 
   2450    y = off_y * vsubsample;
   2451    e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
   2452 
   2453    while (j < result->h) {
   2454       STBTT_memset(scanline, 0, result->w);
   2455       for (s=0; s < vsubsample; ++s) {
   2456          // find center of pixel for this scanline
   2457          float scan_y = y + 0.5f;
   2458          stbtt__active_edge **step = &active;
   2459 
   2460          // update all active edges;
   2461          // remove all active edges that terminate before the center of this scanline
   2462          while (*step) {
   2463             stbtt__active_edge * z = *step;
   2464             if (z->ey <= scan_y) {
   2465                *step = z->next; // delete from list
   2466                STBTT_assert(z->direction);
   2467                z->direction = 0;
   2468                stbtt__hheap_free(&hh, z);
   2469             } else {
   2470                z->x += z->dx; // advance to position for current scanline
   2471                step = &((*step)->next); // advance through list
   2472             }
   2473          }
   2474 
   2475          // resort the list if needed
   2476          for(;;) {
   2477             int changed=0;
   2478             step = &active;
   2479             while (*step && (*step)->next) {
   2480                if ((*step)->x > (*step)->next->x) {
   2481                   stbtt__active_edge *t = *step;
   2482                   stbtt__active_edge *q = t->next;
   2483 
   2484                   t->next = q->next;
   2485                   q->next = t;
   2486                   *step = q;
   2487                   changed = 1;
   2488                }
   2489                step = &(*step)->next;
   2490             }
   2491             if (!changed) break;
   2492          }
   2493 
   2494          // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
   2495          while (e->y0 <= scan_y) {
   2496             if (e->y1 > scan_y) {
   2497                stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);
   2498                if (z != NULL) {
   2499                   // find insertion point
   2500                   if (active == NULL)
   2501                      active = z;
   2502                   else if (z->x < active->x) {
   2503                      // insert at front
   2504                      z->next = active;
   2505                      active = z;
   2506                   } else {
   2507                      // find thing to insert AFTER
   2508                      stbtt__active_edge *p = active;
   2509                      while (p->next && p->next->x < z->x)
   2510                         p = p->next;
   2511                      // at this point, p->next->x is NOT < z->x
   2512                      z->next = p->next;
   2513                      p->next = z;
   2514                   }
   2515                }
   2516             }
   2517             ++e;
   2518          }
   2519 
   2520          // now process all active edges in XOR fashion
   2521          if (active)
   2522             stbtt__fill_active_edges(scanline, result->w, active, max_weight);
   2523 
   2524          ++y;
   2525       }
   2526       STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
   2527       ++j;
   2528    }
   2529 
   2530    stbtt__hheap_cleanup(&hh, userdata);
   2531 
   2532    if (scanline != scanline_data)
   2533       STBTT_free(scanline, userdata);
   2534 }
   2535 
   2536 #elif STBTT_RASTERIZER_VERSION == 2
   2537 
   2538 // the edge passed in here does not cross the vertical line at x or the vertical line at x+1
   2539 // (i.e. it has already been clipped to those)
   2540 static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1)
   2541 {
   2542    if (y0 == y1) return;
   2543    STBTT_assert(y0 < y1);
   2544    STBTT_assert(e->sy <= e->ey);
   2545    if (y0 > e->ey) return;
   2546    if (y1 < e->sy) return;
   2547    if (y0 < e->sy) {
   2548       x0 += (x1-x0) * (e->sy - y0) / (y1-y0);
   2549       y0 = e->sy;
   2550    }
   2551    if (y1 > e->ey) {
   2552       x1 += (x1-x0) * (e->ey - y1) / (y1-y0);
   2553       y1 = e->ey;
   2554    }
   2555 
   2556    if (x0 == x)
   2557       STBTT_assert(x1 <= x+1);
   2558    else if (x0 == x+1)
   2559       STBTT_assert(x1 >= x);
   2560    else if (x0 <= x)
   2561       STBTT_assert(x1 <= x);
   2562    else if (x0 >= x+1)
   2563       STBTT_assert(x1 >= x+1);
   2564    else
   2565       STBTT_assert(x1 >= x && x1 <= x+1);
   2566 
   2567    if (x0 <= x && x1 <= x)
   2568       scanline[x] += e->direction * (y1-y0);
   2569    else if (x0 >= x+1 && x1 >= x+1)
   2570       ;
   2571    else {
   2572       STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1);
   2573       scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position
   2574    }
   2575 }
   2576 
   2577 static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top)
   2578 {
   2579    float y_bottom = y_top+1;
   2580 
   2581    while (e) {
   2582       // brute force every pixel
   2583 
   2584       // compute intersection points with top & bottom
   2585       STBTT_assert(e->ey >= y_top);
   2586 
   2587       if (e->fdx == 0) {
   2588          float x0 = e->fx;
   2589          if (x0 < len) {
   2590             if (x0 >= 0) {
   2591                stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom);
   2592                stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom);
   2593             } else {
   2594                stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom);
   2595             }
   2596          }
   2597       } else {
   2598          float x0 = e->fx;
   2599          float dx = e->fdx;
   2600          float xb = x0 + dx;
   2601          float x_top, x_bottom;
   2602          float sy0,sy1;
   2603          float dy = e->fdy;
   2604          STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);
   2605 
   2606          // compute endpoints of line segment clipped to this scanline (if the
   2607          // line segment starts on this scanline. x0 is the intersection of the
   2608          // line with y_top, but that may be off the line segment.
   2609          if (e->sy > y_top) {
   2610             x_top = x0 + dx * (e->sy - y_top);
   2611             sy0 = e->sy;
   2612          } else {
   2613             x_top = x0;
   2614             sy0 = y_top;
   2615          }
   2616          if (e->ey < y_bottom) {
   2617             x_bottom = x0 + dx * (e->ey - y_top);
   2618             sy1 = e->ey;
   2619          } else {
   2620             x_bottom = xb;
   2621             sy1 = y_bottom;
   2622          }
   2623 
   2624          if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {
   2625             // from here on, we don't have to range check x values
   2626 
   2627             if ((int) x_top == (int) x_bottom) {
   2628                float height;
   2629                // simple case, only spans one pixel
   2630                int x = (int) x_top;
   2631                height = sy1 - sy0;
   2632                STBTT_assert(x >= 0 && x < len);
   2633                scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2)  * height;
   2634                scanline_fill[x] += e->direction * height; // everything right of this pixel is filled
   2635             } else {
   2636                int x,x1,x2;
   2637                float y_crossing, step, sign, area;
   2638                // covers 2+ pixels
   2639                if (x_top > x_bottom) {
   2640                   // flip scanline vertically; signed area is the same
   2641                   float t;
   2642                   sy0 = y_bottom - (sy0 - y_top);
   2643                   sy1 = y_bottom - (sy1 - y_top);
   2644                   t = sy0, sy0 = sy1, sy1 = t;
   2645                   t = x_bottom, x_bottom = x_top, x_top = t;
   2646                   dx = -dx;
   2647                   dy = -dy;
   2648                   t = x0, x0 = xb, xb = t;
   2649                }
   2650 
   2651                x1 = (int) x_top;
   2652                x2 = (int) x_bottom;
   2653                // compute intersection with y axis at x1+1
   2654                y_crossing = (x1+1 - x0) * dy + y_top;
   2655 
   2656                sign = e->direction;
   2657                // area of the rectangle covered from y0..y_crossing
   2658                area = sign * (y_crossing-sy0);
   2659                // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing)
   2660                scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2);
   2661 
   2662                step = sign * dy;
   2663                for (x = x1+1; x < x2; ++x) {
   2664                   scanline[x] += area + step/2;
   2665                   area += step;
   2666                }
   2667                y_crossing += dy * (x2 - (x1+1));
   2668 
   2669                STBTT_assert(STBTT_fabs(area) <= 1.01f);
   2670 
   2671                scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing);
   2672 
   2673                scanline_fill[x2] += sign * (sy1-sy0);
   2674             }
   2675          } else {
   2676             // if edge goes outside of box we're drawing, we require
   2677             // clipping logic. since this does not match the intended use
   2678             // of this library, we use a different, very slow brute
   2679             // force implementation
   2680             int x;
   2681             for (x=0; x < len; ++x) {
   2682                // cases:
   2683                //
   2684                // there can be up to two intersections with the pixel. any intersection
   2685                // with left or right edges can be handled by splitting into two (or three)
   2686                // regions. intersections with top & bottom do not necessitate case-wise logic.
   2687                //
   2688                // the old way of doing this found the intersections with the left & right edges,
   2689                // then used some simple logic to produce up to three segments in sorted order
   2690                // from top-to-bottom. however, this had a problem: if an x edge was epsilon
   2691                // across the x border, then the corresponding y position might not be distinct
   2692                // from the other y segment, and it might ignored as an empty segment. to avoid
   2693                // that, we need to explicitly produce segments based on x positions.
   2694 
   2695                // rename variables to clear pairs
   2696                float y0 = y_top;
   2697                float x1 = (float) (x);
   2698                float x2 = (float) (x+1);
   2699                float x3 = xb;
   2700                float y3 = y_bottom;
   2701                float y1,y2;
   2702 
   2703                // x = e->x + e->dx * (y-y_top)
   2704                // (y-y_top) = (x - e->x) / e->dx
   2705                // y = (x - e->x) / e->dx + y_top
   2706                y1 = (x - x0) / dx + y_top;
   2707                y2 = (x+1 - x0) / dx + y_top;
   2708 
   2709                if (x0 < x1 && x3 > x2) {         // three segments descending down-right
   2710                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
   2711                   stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2);
   2712                   stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
   2713                } else if (x3 < x1 && x0 > x2) {  // three segments descending down-left
   2714                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
   2715                   stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1);
   2716                   stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
   2717                } else if (x0 < x1 && x3 > x1) {  // two segments across x, down-right
   2718                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
   2719                   stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
   2720                } else if (x3 < x1 && x0 > x1) {  // two segments across x, down-left
   2721                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
   2722                   stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
   2723                } else if (x0 < x2 && x3 > x2) {  // two segments across x+1, down-right
   2724                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
   2725                   stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
   2726                } else if (x3 < x2 && x0 > x2) {  // two segments across x+1, down-left
   2727                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
   2728                   stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
   2729                } else {  // one segment
   2730                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3);
   2731                }
   2732             }
   2733          }
   2734       }
   2735       e = e->next;
   2736    }
   2737 }
   2738 
   2739 // directly AA rasterize edges w/o supersampling
   2740 static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
   2741 {
   2742    stbtt__hheap hh = { 0, 0, 0 };
   2743    stbtt__active_edge *active = NULL;
   2744    int y,j=0, i;
   2745    float scanline_data[129], *scanline, *scanline2;
   2746 
   2747    STBTT__NOTUSED(vsubsample);
   2748 
   2749    if (result->w > 64)
   2750       scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata);
   2751    else
   2752       scanline = scanline_data;
   2753 
   2754    scanline2 = scanline + result->w;
   2755 
   2756    y = off_y;
   2757    e[n].y0 = (float) (off_y + result->h) + 1;
   2758 
   2759    while (j < result->h) {
   2760       // find center of pixel for this scanline
   2761       float scan_y_top    = y + 0.0f;
   2762       float scan_y_bottom = y + 1.0f;
   2763       stbtt__active_edge **step = &active;
   2764 
   2765       STBTT_memset(scanline , 0, result->w*sizeof(scanline[0]));
   2766       STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0]));
   2767 
   2768       // update all active edges;
   2769       // remove all active edges that terminate before the top of this scanline
   2770       while (*step) {
   2771          stbtt__active_edge * z = *step;
   2772          if (z->ey <= scan_y_top) {
   2773             *step = z->next; // delete from list
   2774             STBTT_assert(z->direction);
   2775             z->direction = 0;
   2776             stbtt__hheap_free(&hh, z);
   2777          } else {
   2778             step = &((*step)->next); // advance through list
   2779          }
   2780       }
   2781 
   2782       // insert all edges that start before the bottom of this scanline
   2783       while (e->y0 <= scan_y_bottom) {
   2784          if (e->y0 != e->y1) {
   2785             stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);
   2786             if (z != NULL) {
   2787                STBTT_assert(z->ey >= scan_y_top);
   2788                // insert at front
   2789                z->next = active;
   2790                active = z;
   2791             }
   2792          }
   2793          ++e;
   2794       }
   2795 
   2796       // now process all active edges
   2797       if (active)
   2798          stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top);
   2799 
   2800       {
   2801          float sum = 0;
   2802          for (i=0; i < result->w; ++i) {
   2803             float k;
   2804             int m;
   2805             sum += scanline2[i];
   2806             k = scanline[i] + sum;
   2807             k = (float) STBTT_fabs(k)*255 + 0.5f;
   2808             m = (int) k;
   2809             if (m > 255) m = 255;
   2810             result->pixels[j*result->stride + i] = (unsigned char) m;
   2811          }
   2812       }
   2813       // advance all the edges
   2814       step = &active;
   2815       while (*step) {
   2816          stbtt__active_edge *z = *step;
   2817          z->fx += z->fdx; // advance to position for current scanline
   2818          step = &((*step)->next); // advance through list
   2819       }
   2820 
   2821       ++y;
   2822       ++j;
   2823    }
   2824 
   2825    stbtt__hheap_cleanup(&hh, userdata);
   2826 
   2827    if (scanline != scanline_data)
   2828       STBTT_free(scanline, userdata);
   2829 }
   2830 #else
   2831 #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
   2832 #endif
   2833 
   2834 #define STBTT__COMPARE(a,b)  ((a)->y0 < (b)->y0)
   2835 
   2836 static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n)
   2837 {
   2838    int i,j;
   2839    for (i=1; i < n; ++i) {
   2840       stbtt__edge t = p[i], *a = &t;
   2841       j = i;
   2842       while (j > 0) {
   2843          stbtt__edge *b = &p[j-1];
   2844          int c = STBTT__COMPARE(a,b);
   2845          if (!c) break;
   2846          p[j] = p[j-1];
   2847          --j;
   2848       }
   2849       if (i != j)
   2850          p[j] = t;
   2851    }
   2852 }
   2853 
   2854 static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n)
   2855 {
   2856    /* threshhold for transitioning to insertion sort */
   2857    while (n > 12) {
   2858       stbtt__edge t;
   2859       int c01,c12,c,m,i,j;
   2860 
   2861       /* compute median of three */
   2862       m = n >> 1;
   2863       c01 = STBTT__COMPARE(&p[0],&p[m]);
   2864       c12 = STBTT__COMPARE(&p[m],&p[n-1]);
   2865       /* if 0 >= mid >= end, or 0 < mid < end, then use mid */
   2866       if (c01 != c12) {
   2867          /* otherwise, we'll need to swap something else to middle */
   2868          int z;
   2869          c = STBTT__COMPARE(&p[0],&p[n-1]);
   2870          /* 0>mid && mid<n:  0>n => n; 0<n => 0 */
   2871          /* 0<mid && mid>n:  0>n => 0; 0<n => n */
   2872          z = (c == c12) ? 0 : n-1;
   2873          t = p[z];
   2874          p[z] = p[m];
   2875          p[m] = t;
   2876       }
   2877       /* now p[m] is the median-of-three */
   2878       /* swap it to the beginning so it won't move around */
   2879       t = p[0];
   2880       p[0] = p[m];
   2881       p[m] = t;
   2882 
   2883       /* partition loop */
   2884       i=1;
   2885       j=n-1;
   2886       for(;;) {
   2887          /* handling of equality is crucial here */
   2888          /* for sentinels & efficiency with duplicates */
   2889          for (;;++i) {
   2890             if (!STBTT__COMPARE(&p[i], &p[0])) break;
   2891          }
   2892          for (;;--j) {
   2893             if (!STBTT__COMPARE(&p[0], &p[j])) break;
   2894          }
   2895          /* make sure we haven't crossed */
   2896          if (i >= j) break;
   2897          t = p[i];
   2898          p[i] = p[j];
   2899          p[j] = t;
   2900 
   2901          ++i;
   2902          --j;
   2903       }
   2904       /* recurse on smaller side, iterate on larger */
   2905       if (j < (n-i)) {
   2906          stbtt__sort_edges_quicksort(p,j);
   2907          p = p+i;
   2908          n = n-i;
   2909       } else {
   2910          stbtt__sort_edges_quicksort(p+i, n-i);
   2911          n = j;
   2912       }
   2913    }
   2914 }
   2915 
   2916 static void stbtt__sort_edges(stbtt__edge *p, int n)
   2917 {
   2918    stbtt__sort_edges_quicksort(p, n);
   2919    stbtt__sort_edges_ins_sort(p, n);
   2920 }
   2921 
   2922 typedef struct
   2923 {
   2924    float x,y;
   2925 } stbtt__point;
   2926 
   2927 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)
   2928 {
   2929    float y_scale_inv = invert ? -scale_y : scale_y;
   2930    stbtt__edge *e;
   2931    int n,i,j,k,m;
   2932 #if STBTT_RASTERIZER_VERSION == 1
   2933    int vsubsample = result->h < 8 ? 15 : 5;
   2934 #elif STBTT_RASTERIZER_VERSION == 2
   2935    int vsubsample = 1;
   2936 #else
   2937    #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
   2938 #endif
   2939    // vsubsample should divide 255 evenly; otherwise we won't reach full opacity
   2940 
   2941    // now we have to blow out the windings into explicit edge lists
   2942    n = 0;
   2943    for (i=0; i < windings; ++i)
   2944       n += wcount[i];
   2945 
   2946    e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel
   2947    if (e == 0) return;
   2948    n = 0;
   2949 
   2950    m=0;
   2951    for (i=0; i < windings; ++i) {
   2952       stbtt__point *p = pts + m;
   2953       m += wcount[i];
   2954       j = wcount[i]-1;
   2955       for (k=0; k < wcount[i]; j=k++) {
   2956          int a=k,b=j;
   2957          // skip the edge if horizontal
   2958          if (p[j].y == p[k].y)
   2959             continue;
   2960          // add edge from j to k to the list
   2961          e[n].invert = 0;
   2962          if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
   2963             e[n].invert = 1;
   2964             a=j,b=k;
   2965          }
   2966          e[n].x0 = p[a].x * scale_x + shift_x;
   2967          e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;
   2968          e[n].x1 = p[b].x * scale_x + shift_x;
   2969          e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;
   2970          ++n;
   2971       }
   2972    }
   2973 
   2974    // now sort the edges by their highest point (should snap to integer, and then by x)
   2975    //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
   2976    stbtt__sort_edges(e, n);
   2977 
   2978    // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
   2979    stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
   2980 
   2981    STBTT_free(e, userdata);
   2982 }
   2983 
   2984 static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
   2985 {
   2986    if (!points) return; // during first pass, it's unallocated
   2987    points[n].x = x;
   2988    points[n].y = y;
   2989 }
   2990 
   2991 // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching
   2992 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)
   2993 {
   2994    // midpoint
   2995    float mx = (x0 + 2*x1 + x2)/4;
   2996    float my = (y0 + 2*y1 + y2)/4;
   2997    // versus directly drawn line
   2998    float dx = (x0+x2)/2 - mx;
   2999    float dy = (y0+y2)/2 - my;
   3000    if (n > 16) // 65536 segments on one curve better be enough!
   3001       return 1;
   3002    if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
   3003       stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
   3004       stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
   3005    } else {
   3006       stbtt__add_point(points, *num_points,x2,y2);
   3007       *num_points = *num_points+1;
   3008    }
   3009    return 1;
   3010 }
   3011 
   3012 static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n)
   3013 {
   3014    // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough
   3015    float dx0 = x1-x0;
   3016    float dy0 = y1-y0;
   3017    float dx1 = x2-x1;
   3018    float dy1 = y2-y1;
   3019    float dx2 = x3-x2;
   3020    float dy2 = y3-y2;
   3021    float dx = x3-x0;
   3022    float dy = y3-y0;
   3023    float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2));
   3024    float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy);
   3025    float flatness_squared = longlen*longlen-shortlen*shortlen;
   3026 
   3027    if (n > 16) // 65536 segments on one curve better be enough!
   3028       return;
   3029 
   3030    if (flatness_squared > objspace_flatness_squared) {
   3031       float x01 = (x0+x1)/2;
   3032       float y01 = (y0+y1)/2;
   3033       float x12 = (x1+x2)/2;
   3034       float y12 = (y1+y2)/2;
   3035       float x23 = (x2+x3)/2;
   3036       float y23 = (y2+y3)/2;
   3037 
   3038       float xa = (x01+x12)/2;
   3039       float ya = (y01+y12)/2;
   3040       float xb = (x12+x23)/2;
   3041       float yb = (y12+y23)/2;
   3042 
   3043       float mx = (xa+xb)/2;
   3044       float my = (ya+yb)/2;
   3045 
   3046       stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1);
   3047       stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1);
   3048    } else {
   3049       stbtt__add_point(points, *num_points,x3,y3);
   3050       *num_points = *num_points+1;
   3051    }
   3052 }
   3053 
   3054 // returns number of contours
   3055 static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
   3056 {
   3057    stbtt__point *points=0;
   3058    int num_points=0;
   3059 
   3060    float objspace_flatness_squared = objspace_flatness * objspace_flatness;
   3061    int i,n=0,start=0, pass;
   3062 
   3063    // count how many "moves" there are to get the contour count
   3064    for (i=0; i < num_verts; ++i)
   3065       if (vertices[i].type == STBTT_vmove)
   3066          ++n;
   3067 
   3068    *num_contours = n;
   3069    if (n == 0) return 0;
   3070 
   3071    *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
   3072 
   3073    if (*contour_lengths == 0) {
   3074       *num_contours = 0;
   3075       return 0;
   3076    }
   3077 
   3078    // make two passes through the points so we don't need to realloc
   3079    for (pass=0; pass < 2; ++pass) {
   3080       float x=0,y=0;
   3081       if (pass == 1) {
   3082          points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
   3083          if (points == NULL) goto error;
   3084       }
   3085       num_points = 0;
   3086       n= -1;
   3087       for (i=0; i < num_verts; ++i) {
   3088          switch (vertices[i].type) {
   3089             case STBTT_vmove:
   3090                // start the next contour
   3091                if (n >= 0)
   3092                   (*contour_lengths)[n] = num_points - start;
   3093                ++n;
   3094                start = num_points;
   3095 
   3096                x = vertices[i].x, y = vertices[i].y;
   3097                stbtt__add_point(points, num_points++, x,y);
   3098                break;
   3099             case STBTT_vline:
   3100                x = vertices[i].x, y = vertices[i].y;
   3101                stbtt__add_point(points, num_points++, x, y);
   3102                break;
   3103             case STBTT_vcurve:
   3104                stbtt__tesselate_curve(points, &num_points, x,y,
   3105                                         vertices[i].cx, vertices[i].cy,
   3106                                         vertices[i].x,  vertices[i].y,
   3107                                         objspace_flatness_squared, 0);
   3108                x = vertices[i].x, y = vertices[i].y;
   3109                break;
   3110             case STBTT_vcubic:
   3111                stbtt__tesselate_cubic(points, &num_points, x,y,
   3112                                         vertices[i].cx, vertices[i].cy,
   3113                                         vertices[i].cx1, vertices[i].cy1,
   3114                                         vertices[i].x,  vertices[i].y,
   3115                                         objspace_flatness_squared, 0);
   3116                x = vertices[i].x, y = vertices[i].y;
   3117                break;
   3118          }
   3119       }
   3120       (*contour_lengths)[n] = num_points - start;
   3121    }
   3122 
   3123    return points;
   3124 error:
   3125    STBTT_free(points, userdata);
   3126    STBTT_free(*contour_lengths, userdata);
   3127    *contour_lengths = 0;
   3128    *num_contours = 0;
   3129    return NULL;
   3130 }
   3131 
   3132 STBTT_DEF 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)
   3133 {
   3134    float scale = scale_x > scale_y ? scale_y : scale_x;
   3135    int winding_count, *winding_lengths;
   3136    stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
   3137    if (windings) {
   3138       stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
   3139       STBTT_free(winding_lengths, userdata);
   3140       STBTT_free(windings, userdata);
   3141    }
   3142 }
   3143 
   3144 STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
   3145 {
   3146    STBTT_free(bitmap, userdata);
   3147 }
   3148 
   3149 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)
   3150 {
   3151    int ix0,iy0,ix1,iy1;
   3152    stbtt__bitmap gbm;
   3153    stbtt_vertex *vertices;   
   3154    int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
   3155 
   3156    if (scale_x == 0) scale_x = scale_y;
   3157    if (scale_y == 0) {
   3158       if (scale_x == 0) {
   3159          STBTT_free(vertices, info->userdata);
   3160          return NULL;
   3161       }
   3162       scale_y = scale_x;
   3163    }
   3164 
   3165    stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
   3166 
   3167    // now we get the size
   3168    gbm.w = (ix1 - ix0);
   3169    gbm.h = (iy1 - iy0);
   3170    gbm.pixels = NULL; // in case we error
   3171 
   3172    if (width ) *width  = gbm.w;
   3173    if (height) *height = gbm.h;
   3174    if (xoff  ) *xoff   = ix0;
   3175    if (yoff  ) *yoff   = iy0;
   3176    
   3177    if (gbm.w && gbm.h) {
   3178       gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
   3179       if (gbm.pixels) {
   3180          gbm.stride = gbm.w;
   3181 
   3182          stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
   3183       }
   3184    }
   3185    STBTT_free(vertices, info->userdata);
   3186    return gbm.pixels;
   3187 }   
   3188 
   3189 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)
   3190 {
   3191    return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
   3192 }
   3193 
   3194 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)
   3195 {
   3196    int ix0,iy0;
   3197    stbtt_vertex *vertices;
   3198    int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
   3199    stbtt__bitmap gbm;   
   3200 
   3201    stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
   3202    gbm.pixels = output;
   3203    gbm.w = out_w;
   3204    gbm.h = out_h;
   3205    gbm.stride = out_stride;
   3206 
   3207    if (gbm.w && gbm.h)
   3208       stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
   3209 
   3210    STBTT_free(vertices, info->userdata);
   3211 }
   3212 
   3213 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)
   3214 {
   3215    stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
   3216 }
   3217 
   3218 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)
   3219 {
   3220    return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
   3221 }   
   3222 
   3223 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)
   3224 {
   3225    stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
   3226 }
   3227 
   3228 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)
   3229 {
   3230    return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
   3231 }   
   3232 
   3233 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)
   3234 {
   3235    stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
   3236 }
   3237 
   3238 //////////////////////////////////////////////////////////////////////////////
   3239 //
   3240 // bitmap baking
   3241 //
   3242 // This is SUPER-CRAPPY packing to keep source code small
   3243 
   3244 static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)
   3245                                 float pixel_height,                     // height of font in pixels
   3246                                 unsigned char *pixels, int pw, int ph,  // bitmap to be filled in
   3247                                 int first_char, int num_chars,          // characters to bake
   3248                                 stbtt_bakedchar *chardata)
   3249 {
   3250    float scale;
   3251    int x,y,bottom_y, i;
   3252    stbtt_fontinfo f;
   3253    f.userdata = NULL;
   3254    if (!stbtt_InitFont(&f, data, offset))
   3255       return -1;
   3256    STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
   3257    x=y=1;
   3258    bottom_y = 1;
   3259 
   3260    scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
   3261 
   3262    for (i=0; i < num_chars; ++i) {
   3263       int advance, lsb, x0,y0,x1,y1,gw,gh;
   3264       int g = stbtt_FindGlyphIndex(&f, first_char + i);
   3265       stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
   3266       stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
   3267       gw = x1-x0;
   3268       gh = y1-y0;
   3269       if (x + gw + 1 >= pw)
   3270          y = bottom_y, x = 1; // advance to next row
   3271       if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
   3272          return -i;
   3273       STBTT_assert(x+gw < pw);
   3274       STBTT_assert(y+gh < ph);
   3275       stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
   3276       chardata[i].x0 = (stbtt_int16) x;
   3277       chardata[i].y0 = (stbtt_int16) y;
   3278       chardata[i].x1 = (stbtt_int16) (x + gw);
   3279       chardata[i].y1 = (stbtt_int16) (y + gh);
   3280       chardata[i].xadvance = scale * advance;
   3281       chardata[i].xoff     = (float) x0;
   3282       chardata[i].yoff     = (float) y0;
   3283       x = x + gw + 1;
   3284       if (y+gh+1 > bottom_y)
   3285          bottom_y = y+gh+1;
   3286    }
   3287    return bottom_y;
   3288 }
   3289 
   3290 STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
   3291 {
   3292    float d3d_bias = opengl_fillrule ? 0 : -0.5f;
   3293    float ipw = 1.0f / pw, iph = 1.0f / ph;
   3294    stbtt_bakedchar *b = chardata + char_index;
   3295    int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);
   3296    int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);
   3297 
   3298    q->x0 = round_x + d3d_bias;
   3299    q->y0 = round_y + d3d_bias;
   3300    q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
   3301    q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
   3302 
   3303    q->s0 = b->x0 * ipw;
   3304    q->t0 = b->y0 * iph;
   3305    q->s1 = b->x1 * ipw;
   3306    q->t1 = b->y1 * iph;
   3307 
   3308    *xpos += b->xadvance;
   3309 }
   3310 
   3311 //////////////////////////////////////////////////////////////////////////////
   3312 //
   3313 // rectangle packing replacement routines if you don't have stb_rect_pack.h
   3314 //
   3315 
   3316 #ifndef STB_RECT_PACK_VERSION
   3317 
   3318 typedef int stbrp_coord;
   3319 
   3320 ////////////////////////////////////////////////////////////////////////////////////
   3321 //                                                                                //
   3322 //                                                                                //
   3323 // COMPILER WARNING ?!?!?                                                         //
   3324 //                                                                                //
   3325 //                                                                                //
   3326 // if you get a compile warning due to these symbols being defined more than      //
   3327 // once, move #include "stb_rect_pack.h" before #include "stb_truetype.h"         //
   3328 //                                                                                //
   3329 ////////////////////////////////////////////////////////////////////////////////////
   3330 
   3331 typedef struct
   3332 {
   3333    int width,height;
   3334    int x,y,bottom_y;
   3335 } stbrp_context;
   3336 
   3337 typedef struct
   3338 {
   3339    unsigned char x;
   3340 } stbrp_node;
   3341 
   3342 struct stbrp_rect
   3343 {
   3344    stbrp_coord x,y;
   3345    int id,w,h,was_packed;
   3346 };
   3347 
   3348 static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)
   3349 {
   3350    con->width  = pw;
   3351    con->height = ph;
   3352    con->x = 0;
   3353    con->y = 0;
   3354    con->bottom_y = 0;
   3355    STBTT__NOTUSED(nodes);
   3356    STBTT__NOTUSED(num_nodes);   
   3357 }
   3358 
   3359 static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)
   3360 {
   3361    int i;
   3362    for (i=0; i < num_rects; ++i) {
   3363       if (con->x + rects[i].w > con->width) {
   3364          con->x = 0;
   3365          con->y = con->bottom_y;
   3366       }
   3367       if (con->y + rects[i].h > con->height)
   3368          break;
   3369       rects[i].x = con->x;
   3370       rects[i].y = con->y;
   3371       rects[i].was_packed = 1;
   3372       con->x += rects[i].w;
   3373       if (con->y + rects[i].h > con->bottom_y)
   3374          con->bottom_y = con->y + rects[i].h;
   3375    }
   3376    for (   ; i < num_rects; ++i)
   3377       rects[i].was_packed = 0;
   3378 }
   3379 #endif
   3380 
   3381 //////////////////////////////////////////////////////////////////////////////
   3382 //
   3383 // bitmap baking
   3384 //
   3385 // This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If
   3386 // stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.
   3387 
   3388 STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context)
   3389 {
   3390    stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context)            ,alloc_context);
   3391    int            num_nodes = pw - padding;
   3392    stbrp_node    *nodes   = (stbrp_node    *) STBTT_malloc(sizeof(*nodes  ) * num_nodes,alloc_context);
   3393 
   3394    if (context == NULL || nodes == NULL) {
   3395       if (context != NULL) STBTT_free(context, alloc_context);
   3396       if (nodes   != NULL) STBTT_free(nodes  , alloc_context);
   3397       return 0;
   3398    }
   3399 
   3400    spc->user_allocator_context = alloc_context;
   3401    spc->width = pw;
   3402    spc->height = ph;
   3403    spc->pixels = pixels;
   3404    spc->pack_info = context;
   3405    spc->nodes = nodes;
   3406    spc->padding = padding;
   3407    spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;
   3408    spc->h_oversample = 1;
   3409    spc->v_oversample = 1;
   3410 
   3411    stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);
   3412 
   3413    if (pixels)
   3414       STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
   3415 
   3416    return 1;
   3417 }
   3418 
   3419 STBTT_DEF void stbtt_PackEnd  (stbtt_pack_context *spc)
   3420 {
   3421    STBTT_free(spc->nodes    , spc->user_allocator_context);
   3422    STBTT_free(spc->pack_info, spc->user_allocator_context);
   3423 }
   3424 
   3425 STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)
   3426 {
   3427    STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);
   3428    STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);
   3429    if (h_oversample <= STBTT_MAX_OVERSAMPLE)
   3430       spc->h_oversample = h_oversample;
   3431    if (v_oversample <= STBTT_MAX_OVERSAMPLE)
   3432       spc->v_oversample = v_oversample;
   3433 }
   3434 
   3435 #define STBTT__OVER_MASK  (STBTT_MAX_OVERSAMPLE-1)
   3436 
   3437 static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
   3438 {
   3439    unsigned char buffer[STBTT_MAX_OVERSAMPLE];
   3440    int safe_w = w - kernel_width;
   3441    int j;
   3442    STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
   3443    for (j=0; j < h; ++j) {
   3444       int i;
   3445       unsigned int total;
   3446       STBTT_memset(buffer, 0, kernel_width);
   3447 
   3448       total = 0;
   3449 
   3450       // make kernel_width a constant in common cases so compiler can optimize out the divide
   3451       switch (kernel_width) {
   3452          case 2:
   3453             for (i=0; i <= safe_w; ++i) {
   3454                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
   3455                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
   3456                pixels[i] = (unsigned char) (total / 2);
   3457             }
   3458             break;
   3459          case 3:
   3460             for (i=0; i <= safe_w; ++i) {
   3461                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
   3462                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
   3463                pixels[i] = (unsigned char) (total / 3);
   3464             }
   3465             break;
   3466          case 4:
   3467             for (i=0; i <= safe_w; ++i) {
   3468                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
   3469                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
   3470                pixels[i] = (unsigned char) (total / 4);
   3471             }
   3472             break;
   3473          case 5:
   3474             for (i=0; i <= safe_w; ++i) {
   3475                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
   3476                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
   3477                pixels[i] = (unsigned char) (total / 5);
   3478             }
   3479             break;
   3480          default:
   3481             for (i=0; i <= safe_w; ++i) {
   3482                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
   3483                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
   3484                pixels[i] = (unsigned char) (total / kernel_width);
   3485             }
   3486             break;
   3487       }
   3488 
   3489       for (; i < w; ++i) {
   3490          STBTT_assert(pixels[i] == 0);
   3491          total -= buffer[i & STBTT__OVER_MASK];
   3492          pixels[i] = (unsigned char) (total / kernel_width);
   3493       }
   3494 
   3495       pixels += stride_in_bytes;
   3496    }
   3497 }
   3498 
   3499 static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
   3500 {
   3501    unsigned char buffer[STBTT_MAX_OVERSAMPLE];
   3502    int safe_h = h - kernel_width;
   3503    int j;
   3504    STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
   3505    for (j=0; j < w; ++j) {
   3506       int i;
   3507       unsigned int total;
   3508       STBTT_memset(buffer, 0, kernel_width);
   3509 
   3510       total = 0;
   3511 
   3512       // make kernel_width a constant in common cases so compiler can optimize out the divide
   3513       switch (kernel_width) {
   3514          case 2:
   3515             for (i=0; i <= safe_h; ++i) {
   3516                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
   3517                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
   3518                pixels[i*stride_in_bytes] = (unsigned char) (total / 2);
   3519             }
   3520             break;
   3521          case 3:
   3522             for (i=0; i <= safe_h; ++i) {
   3523                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
   3524                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
   3525                pixels[i*stride_in_bytes] = (unsigned char) (total / 3);
   3526             }
   3527             break;
   3528          case 4:
   3529             for (i=0; i <= safe_h; ++i) {
   3530                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
   3531                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
   3532                pixels[i*stride_in_bytes] = (unsigned char) (total / 4);
   3533             }
   3534             break;
   3535          case 5:
   3536             for (i=0; i <= safe_h; ++i) {
   3537                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
   3538                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
   3539                pixels[i*stride_in_bytes] = (unsigned char) (total / 5);
   3540             }
   3541             break;
   3542          default:
   3543             for (i=0; i <= safe_h; ++i) {
   3544                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
   3545                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
   3546                pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
   3547             }
   3548             break;
   3549       }
   3550 
   3551       for (; i < h; ++i) {
   3552          STBTT_assert(pixels[i*stride_in_bytes] == 0);
   3553          total -= buffer[i & STBTT__OVER_MASK];
   3554          pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
   3555       }
   3556 
   3557       pixels += 1;
   3558    }
   3559 }
   3560 
   3561 static float stbtt__oversample_shift(int oversample)
   3562 {
   3563    if (!oversample)
   3564       return 0.0f;
   3565 
   3566    // The prefilter is a box filter of width "oversample",
   3567    // which shifts phase by (oversample - 1)/2 pixels in
   3568    // oversampled space. We want to shift in the opposite
   3569    // direction to counter this.
   3570    return (float)-(oversample - 1) / (2.0f * (float)oversample);
   3571 }
   3572 
   3573 // rects array must be big enough to accommodate all characters in the given ranges
   3574 STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
   3575 {
   3576    int i,j,k;
   3577 
   3578    k=0;
   3579    for (i=0; i < num_ranges; ++i) {
   3580       float fh = ranges[i].font_size;
   3581       float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
   3582       ranges[i].h_oversample = (unsigned char) spc->h_oversample;
   3583       ranges[i].v_oversample = (unsigned char) spc->v_oversample;
   3584       for (j=0; j < ranges[i].num_chars; ++j) {
   3585          int x0,y0,x1,y1;
   3586          int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
   3587          int glyph = stbtt_FindGlyphIndex(info, codepoint);
   3588          stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,
   3589                                          scale * spc->h_oversample,
   3590                                          scale * spc->v_oversample,
   3591                                          0,0,
   3592                                          &x0,&y0,&x1,&y1);
   3593          rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);
   3594          rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);
   3595          ++k;
   3596       }
   3597    }
   3598 
   3599    return k;
   3600 }
   3601 
   3602 // rects array must be big enough to accommodate all characters in the given ranges
   3603 STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
   3604 {
   3605    int i,j,k, return_value = 1;
   3606 
   3607    // save current values
   3608    int old_h_over = spc->h_oversample;
   3609    int old_v_over = spc->v_oversample;
   3610 
   3611    k = 0;
   3612    for (i=0; i < num_ranges; ++i) {
   3613       float fh = ranges[i].font_size;
   3614       float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
   3615       float recip_h,recip_v,sub_x,sub_y;
   3616       spc->h_oversample = ranges[i].h_oversample;
   3617       spc->v_oversample = ranges[i].v_oversample;
   3618       recip_h = 1.0f / spc->h_oversample;
   3619       recip_v = 1.0f / spc->v_oversample;
   3620       sub_x = stbtt__oversample_shift(spc->h_oversample);
   3621       sub_y = stbtt__oversample_shift(spc->v_oversample);
   3622       for (j=0; j < ranges[i].num_chars; ++j) {
   3623          stbrp_rect *r = &rects[k];
   3624          if (r->was_packed) {
   3625             stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];
   3626             int advance, lsb, x0,y0,x1,y1;
   3627             int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
   3628             int glyph = stbtt_FindGlyphIndex(info, codepoint);
   3629             stbrp_coord pad = (stbrp_coord) spc->padding;
   3630 
   3631             // pad on left and top
   3632             r->x += pad;
   3633             r->y += pad;
   3634             r->w -= pad;
   3635             r->h -= pad;
   3636             stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);
   3637             stbtt_GetGlyphBitmapBox(info, glyph,
   3638                                     scale * spc->h_oversample,
   3639                                     scale * spc->v_oversample,
   3640                                     &x0,&y0,&x1,&y1);
   3641             stbtt_MakeGlyphBitmapSubpixel(info,
   3642                                           spc->pixels + r->x + r->y*spc->stride_in_bytes,
   3643                                           r->w - spc->h_oversample+1,
   3644                                           r->h - spc->v_oversample+1,
   3645                                           spc->stride_in_bytes,
   3646                                           scale * spc->h_oversample,
   3647                                           scale * spc->v_oversample,
   3648                                           0,0,
   3649                                           glyph);
   3650 
   3651             if (spc->h_oversample > 1)
   3652                stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
   3653                                   r->w, r->h, spc->stride_in_bytes,
   3654                                   spc->h_oversample);
   3655 
   3656             if (spc->v_oversample > 1)
   3657                stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
   3658                                   r->w, r->h, spc->stride_in_bytes,
   3659                                   spc->v_oversample);
   3660 
   3661             bc->x0       = (stbtt_int16)  r->x;
   3662             bc->y0       = (stbtt_int16)  r->y;
   3663             bc->x1       = (stbtt_int16) (r->x + r->w);
   3664             bc->y1       = (stbtt_int16) (r->y + r->h);
   3665             bc->xadvance =                scale * advance;
   3666             bc->xoff     =       (float)  x0 * recip_h + sub_x;
   3667             bc->yoff     =       (float)  y0 * recip_v + sub_y;
   3668             bc->xoff2    =                (x0 + r->w) * recip_h + sub_x;
   3669             bc->yoff2    =                (y0 + r->h) * recip_v + sub_y;
   3670          } else {
   3671             return_value = 0; // if any fail, report failure
   3672          }
   3673 
   3674          ++k;
   3675       }
   3676    }
   3677 
   3678    // restore original values
   3679    spc->h_oversample = old_h_over;
   3680    spc->v_oversample = old_v_over;
   3681 
   3682    return return_value;
   3683 }
   3684 
   3685 STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects)
   3686 {
   3687    stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);
   3688 }
   3689 
   3690 STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)
   3691 {
   3692    stbtt_fontinfo info;
   3693    int i,j,n, return_value = 1;
   3694    //stbrp_context *context = (stbrp_context *) spc->pack_info;
   3695    stbrp_rect    *rects;
   3696 
   3697    // flag all characters as NOT packed
   3698    for (i=0; i < num_ranges; ++i)
   3699       for (j=0; j < ranges[i].num_chars; ++j)
   3700          ranges[i].chardata_for_range[j].x0 =
   3701          ranges[i].chardata_for_range[j].y0 =
   3702          ranges[i].chardata_for_range[j].x1 =
   3703          ranges[i].chardata_for_range[j].y1 = 0;
   3704 
   3705    n = 0;
   3706    for (i=0; i < num_ranges; ++i)
   3707       n += ranges[i].num_chars;
   3708          
   3709    rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
   3710    if (rects == NULL)
   3711       return 0;
   3712 
   3713    info.userdata = spc->user_allocator_context;
   3714    stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));
   3715 
   3716    n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);
   3717 
   3718    stbtt_PackFontRangesPackRects(spc, rects, n);
   3719   
   3720    return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);
   3721 
   3722    STBTT_free(rects, spc->user_allocator_context);
   3723    return return_value;
   3724 }
   3725 
   3726 STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size,
   3727             int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)
   3728 {
   3729    stbtt_pack_range range;
   3730    range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;
   3731    range.array_of_unicode_codepoints = NULL;
   3732    range.num_chars                   = num_chars_in_range;
   3733    range.chardata_for_range          = chardata_for_range;
   3734    range.font_size                   = font_size;
   3735    return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
   3736 }
   3737 
   3738 STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)
   3739 {
   3740    float ipw = 1.0f / pw, iph = 1.0f / ph;
   3741    stbtt_packedchar *b = chardata + char_index;
   3742 
   3743    if (align_to_integer) {
   3744       float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);
   3745       float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f);
   3746       q->x0 = x;
   3747       q->y0 = y;
   3748       q->x1 = x + b->xoff2 - b->xoff;
   3749       q->y1 = y + b->yoff2 - b->yoff;
   3750    } else {
   3751       q->x0 = *xpos + b->xoff;
   3752       q->y0 = *ypos + b->yoff;
   3753       q->x1 = *xpos + b->xoff2;
   3754       q->y1 = *ypos + b->yoff2;
   3755    }
   3756 
   3757    q->s0 = b->x0 * ipw;
   3758    q->t0 = b->y0 * iph;
   3759    q->s1 = b->x1 * ipw;
   3760    q->t1 = b->y1 * iph;
   3761 
   3762    *xpos += b->xadvance;
   3763 }
   3764 
   3765 
   3766 //////////////////////////////////////////////////////////////////////////////
   3767 //
   3768 // font name matching -- recommended not to use this
   3769 //
   3770 
   3771 // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
   3772 static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) 
   3773 {
   3774    stbtt_int32 i=0;
   3775 
   3776    // convert utf16 to utf8 and compare the results while converting
   3777    while (len2) {
   3778       stbtt_uint16 ch = s2[0]*256 + s2[1];
   3779       if (ch < 0x80) {
   3780          if (i >= len1) return -1;
   3781          if (s1[i++] != ch) return -1;
   3782       } else if (ch < 0x800) {
   3783          if (i+1 >= len1) return -1;
   3784          if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
   3785          if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
   3786       } else if (ch >= 0xd800 && ch < 0xdc00) {
   3787          stbtt_uint32 c;
   3788          stbtt_uint16 ch2 = s2[2]*256 + s2[3];
   3789          if (i+3 >= len1) return -1;
   3790          c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
   3791          if (s1[i++] != 0xf0 + (c >> 18)) return -1;
   3792          if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
   3793          if (s1[i++] != 0x80 + ((c >>  6) & 0x3f)) return -1;
   3794          if (s1[i++] != 0x80 + ((c      ) & 0x3f)) return -1;
   3795          s2 += 2; // plus another 2 below
   3796          len2 -= 2;
   3797       } else if (ch >= 0xdc00 && ch < 0xe000) {
   3798          return -1;
   3799       } else {
   3800          if (i+2 >= len1) return -1;
   3801          if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
   3802          if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
   3803          if (s1[i++] != 0x80 + ((ch     ) & 0x3f)) return -1;
   3804       }
   3805       s2 += 2;
   3806       len2 -= 2;
   3807    }
   3808    return i;
   3809 }
   3810 
   3811 static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) 
   3812 {
   3813    return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2);
   3814 }
   3815 
   3816 // returns results in whatever encoding you request... but note that 2-byte encodings
   3817 // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
   3818 STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
   3819 {
   3820    stbtt_int32 i,count,stringOffset;
   3821    stbtt_uint8 *fc = font->data;
   3822    stbtt_uint32 offset = font->fontstart;
   3823    stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
   3824    if (!nm) return NULL;
   3825 
   3826    count = ttUSHORT(fc+nm+2);
   3827    stringOffset = nm + ttUSHORT(fc+nm+4);
   3828    for (i=0; i < count; ++i) {
   3829       stbtt_uint32 loc = nm + 6 + 12 * i;
   3830       if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
   3831           && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
   3832          *length = ttUSHORT(fc+loc+8);
   3833          return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
   3834       }
   3835    }
   3836    return NULL;
   3837 }
   3838 
   3839 static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
   3840 {
   3841    stbtt_int32 i;
   3842    stbtt_int32 count = ttUSHORT(fc+nm+2);
   3843    stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
   3844 
   3845    for (i=0; i < count; ++i) {
   3846       stbtt_uint32 loc = nm + 6 + 12 * i;
   3847       stbtt_int32 id = ttUSHORT(fc+loc+6);
   3848       if (id == target_id) {
   3849          // find the encoding
   3850          stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
   3851 
   3852          // is this a Unicode encoding?
   3853          if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
   3854             stbtt_int32 slen = ttUSHORT(fc+loc+8);
   3855             stbtt_int32 off = ttUSHORT(fc+loc+10);
   3856 
   3857             // check if there's a prefix match
   3858             stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
   3859             if (matchlen >= 0) {
   3860                // check for target_id+1 immediately following, with same encoding & language
   3861                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) {
   3862                   slen = ttUSHORT(fc+loc+12+8);
   3863                   off = ttUSHORT(fc+loc+12+10);
   3864                   if (slen == 0) {
   3865                      if (matchlen == nlen)
   3866                         return 1;
   3867                   } else if (matchlen < nlen && name[matchlen] == ' ') {
   3868                      ++matchlen;
   3869                      if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
   3870                         return 1;
   3871                   }
   3872                } else {
   3873                   // if nothing immediately following
   3874                   if (matchlen == nlen)
   3875                      return 1;
   3876                }
   3877             }
   3878          }
   3879 
   3880          // @TODO handle other encodings
   3881       }
   3882    }
   3883    return 0;
   3884 }
   3885 
   3886 static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
   3887 {
   3888    stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
   3889    stbtt_uint32 nm,hd;
   3890    if (!stbtt__isfont(fc+offset)) return 0;
   3891 
   3892    // check italics/bold/underline flags in macStyle...
   3893    if (flags) {
   3894       hd = stbtt__find_table(fc, offset, "head");
   3895       if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
   3896    }
   3897 
   3898    nm = stbtt__find_table(fc, offset, "name");
   3899    if (!nm) return 0;
   3900 
   3901    if (flags) {
   3902       // if we checked the macStyle flags, then just check the family and ignore the subfamily
   3903       if (stbtt__matchpair(fc, nm, name, nlen, 16, -1))  return 1;
   3904       if (stbtt__matchpair(fc, nm, name, nlen,  1, -1))  return 1;
   3905       if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;
   3906    } else {
   3907       if (stbtt__matchpair(fc, nm, name, nlen, 16, 17))  return 1;
   3908       if (stbtt__matchpair(fc, nm, name, nlen,  1,  2))  return 1;
   3909       if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;
   3910    }
   3911 
   3912    return 0;
   3913 }
   3914 
   3915 static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags)
   3916 {
   3917    stbtt_int32 i;
   3918    for (i=0;;++i) {
   3919       stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
   3920       if (off < 0) return off;
   3921       if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
   3922          return off;
   3923    }
   3924 }
   3925 
   3926 #if defined(__GNUC__) || defined(__clang__)
   3927 #pragma GCC diagnostic push
   3928 #pragma GCC diagnostic ignored "-Wcast-qual"
   3929 #endif
   3930 
   3931 STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,
   3932                                 float pixel_height, unsigned char *pixels, int pw, int ph,
   3933                                 int first_char, int num_chars, stbtt_bakedchar *chardata)
   3934 {
   3935    return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata);
   3936 }
   3937 
   3938 STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index)
   3939 {
   3940    return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index);   
   3941 }
   3942 
   3943 STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data)
   3944 {
   3945    return stbtt_GetNumberOfFonts_internal((unsigned char *) data);
   3946 }
   3947 
   3948 STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset)
   3949 {
   3950    return stbtt_InitFont_internal(info, (unsigned char *) data, offset);
   3951 }
   3952 
   3953 STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags)
   3954 {
   3955    return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags);
   3956 }
   3957 
   3958 STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
   3959 {
   3960    return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2);
   3961 }
   3962 
   3963 #if defined(__GNUC__) || defined(__clang__)
   3964 #pragma GCC diagnostic pop
   3965 #endif
   3966 
   3967 #endif // STB_TRUETYPE_IMPLEMENTATION
   3968 
   3969 
   3970 // FULL VERSION HISTORY
   3971 //
   3972 //   1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
   3973 //   1.11 (2016-04-02) fix unused-variable warning
   3974 //   1.10 (2016-04-02) allow user-defined fabs() replacement
   3975 //                     fix memory leak if fontsize=0.0
   3976 //                     fix warning from duplicate typedef
   3977 //   1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges
   3978 //   1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
   3979 //   1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
   3980 //                     allow PackFontRanges to pack and render in separate phases;
   3981 //                     fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
   3982 //                     fixed an assert() bug in the new rasterizer
   3983 //                     replace assert() with STBTT_assert() in new rasterizer
   3984 //   1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
   3985 //                     also more precise AA rasterizer, except if shapes overlap
   3986 //                     remove need for STBTT_sort
   3987 //   1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
   3988 //   1.04 (2015-04-15) typo in example
   3989 //   1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
   3990 //   1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++
   3991 //   1.01 (2014-12-08) fix subpixel position when oversampling to exactly match
   3992 //                        non-oversampled; STBTT_POINT_SIZE for packed case only
   3993 //   1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling
   3994 //   0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)
   3995 //   0.9  (2014-08-07) support certain mac/iOS fonts without an MS platformID
   3996 //   0.8b (2014-07-07) fix a warning
   3997 //   0.8  (2014-05-25) fix a few more warnings
   3998 //   0.7  (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
   3999 //   0.6c (2012-07-24) improve documentation
   4000 //   0.6b (2012-07-20) fix a few more warnings
   4001 //   0.6  (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
   4002 //                        stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
   4003 //   0.5  (2011-12-09) bugfixes:
   4004 //                        subpixel glyph renderer computed wrong bounding box
   4005 //                        first vertex of shape can be off-curve (FreeSans)
   4006 //   0.4b (2011-12-03) fixed an error in the font baking example
   4007 //   0.4  (2011-12-01) kerning, subpixel rendering (tor)
   4008 //                    bugfixes for:
   4009 //                        codepoint-to-glyph conversion using table fmt=12
   4010 //                        codepoint-to-glyph conversion using table fmt=4
   4011 //                        stbtt_GetBakedQuad with non-square texture (Zer)
   4012 //                    updated Hello World! sample to use kerning and subpixel
   4013 //                    fixed some warnings
   4014 //   0.3  (2009-06-24) cmap fmt=12, compound shapes (MM)
   4015 //                    userdata, malloc-from-userdata, non-zero fill (stb)
   4016 //   0.2  (2009-03-11) Fix unsigned/signed char warnings
   4017 //   0.1  (2009-03-09) First public release
   4018 //