Subversion Repositories Kolibri OS

Rev

Rev 3002 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. // stb_truetype.h - v1.02 - public domain
  2. // authored from 2009-2014 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. //
  24. //   Bug/warning reports/fixes:
  25. //       "Zer" on mollyrocket (with fix)
  26. //       Cass Everitt
  27. //       stoiko (Haemimont Games)
  28. //       Brian Hook
  29. //       Walter van Niftrik
  30. //       David Gow
  31. //       David Given
  32. //       Ivan-Assen Ivanov
  33. //       Anthony Pesch
  34. //       Johan Duparc
  35. //       Hou Qiming
  36. //       Fabian "ryg" Giesen
  37. //
  38. //   Misc other:
  39. //       Ryan Gordon
  40. //
  41. // VERSION HISTORY
  42. //
  43. //   1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++
  44. //   1.01 (2014-12-08) fix subpixel position when oversampling to exactly match
  45. //                        non-oversampled; STBTT_POINT_SIZE for packed case only
  46. //   1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling
  47. //   0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)
  48. //   0.9  (2014-08-07) support certain mac/iOS fonts without an MS platformID
  49. //   0.8b (2014-07-07) fix a warning
  50. //   0.8  (2014-05-25) fix a few more warnings
  51. //   0.7  (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
  52. //   0.6c (2012-07-24) improve documentation
  53. //   0.6b (2012-07-20) fix a few more warnings
  54. //   0.6  (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
  55. //                        stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
  56. //   0.5  (2011-12-09) bugfixes:
  57. //                        subpixel glyph renderer computed wrong bounding box
  58. //                        first vertex of shape can be off-curve (FreeSans)
  59. //   0.4b (2011-12-03) fixed an error in the font baking example
  60. //   0.4  (2011-12-01) kerning, subpixel rendering (tor)
  61. //                    bugfixes for:
  62. //                        codepoint-to-glyph conversion using table fmt=12
  63. //                        codepoint-to-glyph conversion using table fmt=4
  64. //                        stbtt_GetBakedQuad with non-square texture (Zer)
  65. //                    updated Hello World! sample to use kerning and subpixel
  66. //                    fixed some warnings
  67. //   0.3  (2009-06-24) cmap fmt=12, compound shapes (MM)
  68. //                    userdata, malloc-from-userdata, non-zero fill (stb)
  69. //   0.2  (2009-03-11) Fix unsigned/signed char warnings
  70. //   0.1  (2009-03-09) First public release
  71. //
  72. // LICENSE
  73. //
  74. //   This software is in the public domain. Where that dedication is not
  75. //   recognized, you are granted a perpetual, irrevokable license to copy
  76. //   and modify this file as you see fit.
  77. //
  78. // USAGE
  79. //
  80. //   Include this file in whatever places neeed to refer to it. In ONE C/C++
  81. //   file, write:
  82. //      #define STB_TRUETYPE_IMPLEMENTATION
  83. //   before the #include of this file. This expands out the actual
  84. //   implementation into that C/C++ file.
  85. //
  86. //   Simple 3D API (don't ship this, but it's fine for tools and quick start)
  87. //           stbtt_BakeFontBitmap()               -- bake a font to a bitmap for use as texture
  88. //           stbtt_GetBakedQuad()                 -- compute quad to draw for a given char
  89. //
  90. //   Improved 3D API (more shippable):
  91. //           #include "stb_rect_pack.h"           -- optional, but you really want it
  92. //           stbtt_PackBegin()
  93. //           stbtt_PackSetOversample()            -- for improved quality on small fonts
  94. //           stbtt_PackFontRanges()
  95. //           stbtt_PackEnd()
  96. //           stbtt_GetPackedQuad()
  97. //
  98. //   "Load" a font file from a memory buffer (you have to keep the buffer loaded)
  99. //           stbtt_InitFont()
  100. //           stbtt_GetFontOffsetForIndex()        -- use for TTC font collections
  101. //
  102. //   Render a unicode codepoint to a bitmap
  103. //           stbtt_GetCodepointBitmap()           -- allocates and returns a bitmap
  104. //           stbtt_MakeCodepointBitmap()          -- renders into bitmap you provide
  105. //           stbtt_GetCodepointBitmapBox()        -- how big the bitmap must be
  106. //
  107. //   Character advance/positioning
  108. //           stbtt_GetCodepointHMetrics()
  109. //           stbtt_GetFontVMetrics()
  110. //           stbtt_GetCodepointKernAdvance()
  111. //
  112. // ADDITIONAL DOCUMENTATION
  113. //
  114. //   Immediately after this block comment are a series of sample programs.
  115. //
  116. //   After the sample programs is the "header file" section. This section
  117. //   includes documentation for each API function.
  118. //
  119. //   Some important concepts to understand to use this library:
  120. //
  121. //      Codepoint
  122. //         Characters are defined by unicode codepoints, e.g. 65 is
  123. //         uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
  124. //         the hiragana for "ma".
  125. //
  126. //      Glyph
  127. //         A visual character shape (every codepoint is rendered as
  128. //         some glyph)
  129. //
  130. //      Glyph index
  131. //         A font-specific integer ID representing a glyph
  132. //
  133. //      Baseline
  134. //         Glyph shapes are defined relative to a baseline, which is the
  135. //         bottom of uppercase characters. Characters extend both above
  136. //         and below the baseline.
  137. //
  138. //      Current Point
  139. //         As you draw text to the screen, you keep track of a "current point"
  140. //         which is the origin of each character. The current point's vertical
  141. //         position is the baseline. Even "baked fonts" use this model.
  142. //
  143. //      Vertical Font Metrics
  144. //         The vertical qualities of the font, used to vertically position
  145. //         and space the characters. See docs for stbtt_GetFontVMetrics.
  146. //
  147. //      Font Size in Pixels or Points
  148. //         The preferred interface for specifying font sizes in stb_truetype
  149. //         is to specify how tall the font's vertical extent should be in pixels.
  150. //         If that sounds good enough, skip the next paragraph.
  151. //
  152. //         Most font APIs instead use "points", which are a common typographic
  153. //         measurement for describing font size, defined as 72 points per inch.
  154. //         stb_truetype provides a point API for compatibility. However, true
  155. //         "per inch" conventions don't make much sense on computer displays
  156. //         since they different monitors have different number of pixels per
  157. //         inch. For example, Windows traditionally uses a convention that
  158. //         there are 96 pixels per inch, thus making 'inch' measurements have
  159. //         nothing to do with inches, and thus effectively defining a point to
  160. //         be 1.333 pixels. Additionally, the TrueType font data provides
  161. //         an explicit scale factor to scale a given font's glyphs to points,
  162. //         but the author has observed that this scale factor is often wrong
  163. //         for non-commercial fonts, thus making fonts scaled in points
  164. //         according to the TrueType spec incoherently sized in practice.
  165. //
  166. // ADVANCED USAGE
  167. //
  168. //   Quality:
  169. //
  170. //    - Use the functions with Subpixel at the end to allow your characters
  171. //      to have subpixel positioning. Since the font is anti-aliased, not
  172. //      hinted, this is very import for quality. (This is not possible with
  173. //      baked fonts.)
  174. //
  175. //    - Kerning is now supported, and if you're supporting subpixel rendering
  176. //      then kerning is worth using to give your text a polished look.
  177. //
  178. //   Performance:
  179. //
  180. //    - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
  181. //      if you don't do this, stb_truetype is forced to do the conversion on
  182. //      every call.
  183. //
  184. //    - There are a lot of memory allocations. We should modify it to take
  185. //      a temp buffer and allocate from the temp buffer (without freeing),
  186. //      should help performance a lot.
  187. //
  188. // NOTES
  189. //
  190. //   The system uses the raw data found in the .ttf file without changing it
  191. //   and without building auxiliary data structures. This is a bit inefficient
  192. //   on little-endian systems (the data is big-endian), but assuming you're
  193. //   caching the bitmaps or glyph shapes this shouldn't be a big deal.
  194. //
  195. //   It appears to be very hard to programmatically determine what font a
  196. //   given file is in a general way. I provide an API for this, but I don't
  197. //   recommend it.
  198. //
  199. //
  200. // SOURCE STATISTICS (based on v0.6c, 2050 LOC)
  201. //
  202. //   Documentation & header file        520 LOC  \___ 660 LOC documentation
  203. //   Sample code                        140 LOC  /
  204. //   Truetype parsing                   620 LOC  ---- 620 LOC TrueType
  205. //   Software rasterization             240 LOC  \                           .
  206. //   Curve tesselation                  120 LOC   \__ 550 LOC Bitmap creation
  207. //   Bitmap management                  100 LOC   /
  208. //   Baked bitmap interface              70 LOC  /
  209. //   Font name matching & access        150 LOC  ---- 150
  210. //   C runtime library abstraction       60 LOC  ----  60
  211.  
  212.  
  213. //////////////////////////////////////////////////////////////////////////////
  214. //////////////////////////////////////////////////////////////////////////////
  215. ////
  216. ////  SAMPLE PROGRAMS
  217. ////
  218. //
  219. //  Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
  220. //
  221. #if 0
  222. #define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation
  223. #include "stb_truetype.h"
  224.  
  225. char ttf_buffer[1<<20];
  226. unsigned char temp_bitmap[512*512];
  227.  
  228. stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
  229. GLstbtt_uint ftex;
  230.  
  231. void my_stbtt_initfont(void)
  232. {
  233.    fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
  234.    stbtt_BakeFontBitmap(data,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
  235.    // can free ttf_buffer at this point
  236.    glGenTextures(1, &ftex);
  237.    glBindTexture(GL_TEXTURE_2D, ftex);
  238.    glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
  239.    // can free temp_bitmap at this point
  240.    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  241. }
  242.  
  243. void my_stbtt_print(float x, float y, char *text)
  244. {
  245.    // assume orthographic projection with units = screen pixels, origin at top left
  246.    glBindTexture(GL_TEXTURE_2D, ftex);
  247.    glBegin(GL_QUADS);
  248.    while (*text) {
  249.       if (*text >= 32 && *text < 128) {
  250.          stbtt_aligned_quad q;
  251.          stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
  252.          glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
  253.          glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
  254.          glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
  255.          glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
  256.       }
  257.       ++text;
  258.    }
  259.    glEnd();
  260. }
  261. #endif
  262. //
  263. //
  264. //////////////////////////////////////////////////////////////////////////////
  265. //
  266. // Complete program (this compiles): get a single bitmap, print as ASCII art
  267. //
  268. #if 0
  269. #include <stdio.h>
  270. #define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation
  271. #include "stb_truetype.h"
  272.  
  273. char ttf_buffer[1<<25];
  274.  
  275. int main(int argc, char **argv)
  276. {
  277.    stbtt_fontinfo font;
  278.    unsigned char *bitmap;
  279.    int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
  280.  
  281.    fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
  282.  
  283.    stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
  284.    bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
  285.  
  286.    for (j=0; j < h; ++j) {
  287.       for (i=0; i < w; ++i)
  288.          putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
  289.       putchar('\n');
  290.    }
  291.    return 0;
  292. }
  293. #endif
  294. //
  295. // Output:
  296. //
  297. //     .ii.
  298. //    @@@@@@.
  299. //   V@Mio@@o
  300. //   :i.  V@V
  301. //     :oM@@M
  302. //   :@@@MM@M
  303. //   @@o  o@M
  304. //  :@@.  M@M
  305. //   @@@o@@@@
  306. //   :M@@V:@@.
  307. //  
  308. //////////////////////////////////////////////////////////////////////////////
  309. //
  310. // Complete program: print "Hello World!" banner, with bugs
  311. //
  312. #if 0
  313. char buffer[24<<20];
  314. unsigned char screen[20][79];
  315.  
  316. int main(int arg, char **argv)
  317. {
  318.    stbtt_fontinfo font;
  319.    int i,j,ascent,baseline,ch=0;
  320.    float scale, xpos=2; // leave a little padding in case the character extends left
  321.    char *text = "Heljo World!";
  322.  
  323.    fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
  324.    stbtt_InitFont(&font, buffer, 0);
  325.  
  326.    scale = stbtt_ScaleForPixelHeight(&font, 15);
  327.    stbtt_GetFontVMetrics(&font, &ascent,0,0);
  328.    baseline = (int) (ascent*scale);
  329.  
  330.    while (text[ch]) {
  331.       int advance,lsb,x0,y0,x1,y1;
  332.       float x_shift = xpos - (float) floor(xpos);
  333.       stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
  334.       stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
  335.       stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
  336.       // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
  337.       // because this API is really for baking character bitmaps into textures. if you want to render
  338.       // a sequence of characters, you really need to render each bitmap to a temp buffer, then
  339.       // "alpha blend" that into the working buffer
  340.       xpos += (advance * scale);
  341.       if (text[ch+1])
  342.          xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
  343.       ++ch;
  344.    }
  345.  
  346.    for (j=0; j < 20; ++j) {
  347.       for (i=0; i < 78; ++i)
  348.          putchar(" .:ioVM@"[screen[j][i]>>5]);
  349.       putchar('\n');
  350.    }
  351.  
  352.    return 0;
  353. }
  354. #endif
  355.  
  356.  
  357. //////////////////////////////////////////////////////////////////////////////
  358. //////////////////////////////////////////////////////////////////////////////
  359. ////
  360. ////   INTEGRATION WITH YOUR CODEBASE
  361. ////
  362. ////   The following sections allow you to supply alternate definitions
  363. ////   of C library functions used by stb_truetype.
  364.  
  365. #ifdef STB_TRUETYPE_IMPLEMENTATION
  366.    // #define your own (u)stbtt_int8/16/32 before including to override this
  367.    #ifndef stbtt_uint8
  368.    typedef unsigned char   stbtt_uint8;
  369.    typedef signed   char   stbtt_int8;
  370.    typedef unsigned short  stbtt_uint16;
  371.    typedef signed   short  stbtt_int16;
  372.    typedef unsigned int    stbtt_uint32;
  373.    typedef signed   int    stbtt_int32;
  374.    #endif
  375.  
  376.    typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
  377.    typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
  378.  
  379.    // #define your own STBTT_sort() to override this to avoid qsort
  380.    #ifndef STBTT_sort
  381.    #include <stdlib.h>
  382.    #define STBTT_sort(data,num_items,item_size,compare_func)   qsort(data,num_items,item_size,compare_func)
  383.    #endif
  384.  
  385.    // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
  386.    #ifndef STBTT_ifloor
  387.    #include <math.h>
  388.    #define STBTT_ifloor(x)   ((int) floor(x))
  389.    #define STBTT_iceil(x)    ((int) ceil(x))
  390.    #endif
  391.  
  392.    #ifndef STBTT_sqrt
  393.    #include <math.h>
  394.    #define STBTT_sqrt(x)      sqrt(x)
  395.    #endif
  396.  
  397.    // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
  398.    #ifndef STBTT_malloc
  399.    #include <stdlib.h>
  400.    #define STBTT_malloc(x,u)  ((void)(u),malloc(x))
  401.    #define STBTT_free(x,u)    ((void)(u),free(x))
  402.    #endif
  403.  
  404.    #ifndef STBTT_assert
  405.    #include <assert.h>
  406.    #define STBTT_assert(x)    assert(x)
  407.    #endif
  408.  
  409.    #ifndef STBTT_strlen
  410.    #include <string.h>
  411.    #define STBTT_strlen(x)    strlen(x)
  412.    #endif
  413.  
  414.    #ifndef STBTT_memcpy
  415.    #include <memory.h>
  416.    #define STBTT_memcpy       memcpy
  417.    #define STBTT_memset       memset
  418.    #endif
  419. #endif
  420.  
  421. ///////////////////////////////////////////////////////////////////////////////
  422. ///////////////////////////////////////////////////////////////////////////////
  423. ////
  424. ////   INTERFACE
  425. ////
  426. ////
  427.  
  428. #ifndef __STB_INCLUDE_STB_TRUETYPE_H__
  429. #define __STB_INCLUDE_STB_TRUETYPE_H__
  430.  
  431. #ifdef __cplusplus
  432. extern "C" {
  433. #endif
  434.  
  435. //////////////////////////////////////////////////////////////////////////////
  436. //
  437. // TEXTURE BAKING API
  438. //
  439. // If you use this API, you only have to call two functions ever.
  440. //
  441.  
  442. typedef struct
  443. {
  444.    unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
  445.    float xoff,yoff,xadvance;
  446. } stbtt_bakedchar;
  447.  
  448. extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)
  449.                                 float pixel_height,                     // height of font in pixels
  450.                                 unsigned char *pixels, int pw, int ph,  // bitmap to be filled in
  451.                                 int first_char, int num_chars,          // characters to bake
  452.                                 stbtt_bakedchar *chardata);             // you allocate this, it's num_chars long
  453. // if return is positive, the first unused row of the bitmap
  454. // if return is negative, returns the negative of the number of characters that fit
  455. // if return is 0, no characters fit and no rows were used
  456. // This uses a very crappy packing.
  457.  
  458. typedef struct
  459. {
  460.    float x0,y0,s0,t0; // top-left
  461.    float x1,y1,s1,t1; // bottom-right
  462. } stbtt_aligned_quad;
  463.  
  464. extern void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph,  // same data as above
  465.                                int char_index,             // character to display
  466.                                float *xpos, float *ypos,   // pointers to current position in screen pixel space
  467.                                stbtt_aligned_quad *q,      // output: quad to draw
  468.                                int opengl_fillrule);       // true if opengl fill rule; false if DX9 or earlier
  469. // Call GetBakedQuad with char_index = 'character - first_char', and it
  470. // creates the quad you need to draw and advances the current position.
  471. //
  472. // The coordinate system used assumes y increases downwards.
  473. //
  474. // Characters will extend both above and below the current position;
  475. // see discussion of "BASELINE" above.
  476. //
  477. // It's inefficient; you might want to c&p it and optimize it.
  478.  
  479.  
  480.  
  481. //////////////////////////////////////////////////////////////////////////////
  482. //
  483. // NEW TEXTURE BAKING API
  484. //
  485. // This provides options for packing multiple fonts into one atlas, not
  486. // perfectly but better than nothing.
  487.  
  488. typedef struct
  489. {
  490.    unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
  491.    float xoff,yoff,xadvance;
  492.    float xoff2,yoff2;
  493. } stbtt_packedchar;
  494.  
  495. typedef struct stbtt_pack_context stbtt_pack_context;
  496.  
  497. extern int  stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);
  498. // Initializes a packing context stored in the passed-in stbtt_pack_context.
  499. // Future calls using this context will pack characters into the bitmap passed
  500. // in here: a 1-channel bitmap that is weight x height. stride_in_bytes is
  501. // the distance from one row to the next (or 0 to mean they are packed tightly
  502. // together). "padding" is // the amount of padding to leave between each
  503. // character (normally you want '1' for bitmaps you'll use as textures with
  504. // bilinear filtering).
  505. //
  506. // Returns 0 on failure, 1 on success.
  507.  
  508. extern void stbtt_PackEnd  (stbtt_pack_context *spc);
  509. // Cleans up the packing context and frees all memory.
  510.  
  511. #define STBTT_POINT_SIZE(x)   (-(x))
  512.  
  513. extern int  stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size,
  514.                                 int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);
  515. // Creates character bitmaps from the font_index'th font found in fontdata (use
  516. // font_index=0 if you don't know what that is). It creates num_chars_in_range
  517. // bitmaps for characters with unicode values starting at first_unicode_char_in_range
  518. // and increasing. Data for how to render them is stored in chardata_for_range;
  519. // pass these to stbtt_GetPackedQuad to get back renderable quads.
  520. //
  521. // font_size is the full height of the character from ascender to descender,
  522. // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed
  523. // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()
  524. // and pass that result as 'font_size':
  525. //       ...,                  20 , ... // font max minus min y is 20 pixels tall
  526. //       ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall
  527.  
  528. typedef struct
  529. {
  530.    float font_size;
  531.    int first_unicode_char_in_range;
  532.    int num_chars_in_range;
  533.    stbtt_packedchar *chardata_for_range; // output
  534. } stbtt_pack_range;
  535.  
  536. extern int  stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
  537. // Creates character bitmaps from multiple ranges of characters stored in
  538. // ranges. This will usually create a better-packed bitmap than multiple
  539. // calls to stbtt_PackFontRange.
  540.  
  541.  
  542. extern void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);
  543. // Oversampling a font increases the quality by allowing higher-quality subpixel
  544. // positioning, and is especially valuable at smaller text sizes.
  545. //
  546. // This function sets the amount of oversampling for all following calls to
  547. // stbtt_PackFontRange(s). The default (no oversampling) is achieved by
  548. // h_oversample=1, v_oversample=1. The total number of pixels required is
  549. // h_oversample*v_oversample larger than the default; for example, 2x2
  550. // oversampling requires 4x the storage of 1x1. For best results, render
  551. // oversampled textures with bilinear filtering. Look at the readme in
  552. // stb/tests/oversample for information about oversampled fonts
  553.  
  554. extern void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph,  // same data as above
  555.                                int char_index,             // character to display
  556.                                float *xpos, float *ypos,   // pointers to current position in screen pixel space
  557.                                stbtt_aligned_quad *q,      // output: quad to draw
  558.                                int align_to_integer);
  559.  
  560. // this is an opaque structure that you shouldn't mess with which holds
  561. // all the context needed from PackBegin to PackEnd.
  562. struct stbtt_pack_context {
  563.    void *user_allocator_context;
  564.    void *pack_info;
  565.    int   width;
  566.    int   height;
  567.    int   stride_in_bytes;
  568.    int   padding;
  569.    unsigned int   h_oversample, v_oversample;
  570.    unsigned char *pixels;
  571.    void  *nodes;
  572. };
  573.  
  574. //////////////////////////////////////////////////////////////////////////////
  575. //
  576. // FONT LOADING
  577. //
  578. //
  579.  
  580. extern int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
  581. // Each .ttf/.ttc file may have more than one font. Each font has a sequential
  582. // index number starting from 0. Call this function to get the font offset for
  583. // a given index; it returns -1 if the index is out of range. A regular .ttf
  584. // file will only define one font and it always be at offset 0, so it will
  585. // return '0' for index 0, and -1 for all other indices. You can just skip
  586. // this step if you know it's that kind of font.
  587.  
  588.  
  589. // The following structure is defined publically so you can declare one on
  590. // the stack or as a global or etc, but you should treat it as opaque.
  591. typedef struct stbtt_fontinfo
  592. {
  593.    void           * userdata;
  594.    unsigned char  * data;              // pointer to .ttf file
  595.    int              fontstart;         // offset of start of font
  596.  
  597.    int numGlyphs;                     // number of glyphs, needed for range checking
  598.  
  599.    int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf
  600.    int index_map;                     // a cmap mapping for our chosen character encoding
  601.    int indexToLocFormat;              // format needed to map from glyph index to glyph
  602. } stbtt_fontinfo;
  603.  
  604. extern int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
  605. // Given an offset into the file that defines a font, this function builds
  606. // the necessary cached info for the rest of the system. You must allocate
  607. // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
  608. // need to do anything special to free it, because the contents are pure
  609. // value data with no additional data structures. Returns 0 on failure.
  610.  
  611.  
  612. //////////////////////////////////////////////////////////////////////////////
  613. //
  614. // CHARACTER TO GLYPH-INDEX CONVERSIOn
  615.  
  616. int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
  617. // If you're going to perform multiple operations on the same character
  618. // and you want a speed-up, call this function with the character you're
  619. // going to process, then use glyph-based functions instead of the
  620. // codepoint-based functions.
  621.  
  622.  
  623. //////////////////////////////////////////////////////////////////////////////
  624. //
  625. // CHARACTER PROPERTIES
  626. //
  627.  
  628. extern float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
  629. // computes a scale factor to produce a font whose "height" is 'pixels' tall.
  630. // Height is measured as the distance from the highest ascender to the lowest
  631. // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
  632. // and computing:
  633. //       scale = pixels / (ascent - descent)
  634. // so if you prefer to measure height by the ascent only, use a similar calculation.
  635.  
  636. extern float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
  637. // computes a scale factor to produce a font whose EM size is mapped to
  638. // 'pixels' tall. This is probably what traditional APIs compute, but
  639. // I'm not positive.
  640.  
  641. extern void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
  642. // ascent is the coordinate above the baseline the font extends; descent
  643. // is the coordinate below the baseline the font extends (i.e. it is typically negative)
  644. // lineGap is the spacing between one row's descent and the next row's ascent...
  645. // so you should advance the vertical position by "*ascent - *descent + *lineGap"
  646. //   these are expressed in unscaled coordinates, so you must multiply by
  647. //   the scale factor for a given size
  648.  
  649. extern void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
  650. // the bounding box around all possible characters
  651.  
  652. extern void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
  653. // leftSideBearing is the offset from the current horizontal position to the left edge of the character
  654. // advanceWidth is the offset from the current horizontal position to the next horizontal position
  655. //   these are expressed in unscaled coordinates
  656.  
  657. extern int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
  658. // an additional amount to add to the 'advance' value between ch1 and ch2
  659.  
  660. extern int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
  661. // Gets the bounding box of the visible part of the glyph, in unscaled coordinates
  662.  
  663. extern void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
  664. extern int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
  665. extern int  stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
  666. // as above, but takes one or more glyph indices for greater efficiency
  667.  
  668.  
  669. //////////////////////////////////////////////////////////////////////////////
  670. //
  671. // GLYPH SHAPES (you probably don't need these, but they have to go before
  672. // the bitmaps for C declaration-order reasons)
  673. //
  674.  
  675. #ifndef STBTT_vmove // you can predefine these to use different values (but why?)
  676.    enum {
  677.       STBTT_vmove=1,
  678.       STBTT_vline,
  679.       STBTT_vcurve
  680.    };
  681. #endif
  682.  
  683. #ifndef stbtt_vertex // you can predefine this to use different values
  684.                    // (we share this with other code at RAD)
  685.    #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
  686.    typedef struct
  687.    {
  688.       stbtt_vertex_type x,y,cx,cy;
  689.       unsigned char type,padding;
  690.    } stbtt_vertex;
  691. #endif
  692.  
  693. extern int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
  694. // returns non-zero if nothing is drawn for this glyph
  695.  
  696. extern int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
  697. extern int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
  698. // returns # of vertices and fills *vertices with the pointer to them
  699. //   these are expressed in "unscaled" coordinates
  700. //
  701. // The shape is a series of countours. Each one starts with
  702. // a STBTT_moveto, then consists of a series of mixed
  703. // STBTT_lineto and STBTT_curveto segments. A lineto
  704. // draws a line from previous endpoint to its x,y; a curveto
  705. // draws a quadratic bezier from previous endpoint to
  706. // its x,y, using cx,cy as the bezier control point.
  707.  
  708. extern void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
  709. // frees the data allocated above
  710.  
  711. //////////////////////////////////////////////////////////////////////////////
  712. //
  713. // BITMAP RENDERING
  714. //
  715.  
  716. extern void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
  717. // frees the bitmap allocated below
  718.  
  719. extern unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
  720. // allocates a large-enough single-channel 8bpp bitmap and renders the
  721. // specified character/glyph at the specified scale into it, with
  722. // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
  723. // *width & *height are filled out with the width & height of the bitmap,
  724. // which is stored left-to-right, top-to-bottom.
  725. //
  726. // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
  727.  
  728. extern unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
  729. // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
  730. // shift for the character
  731.  
  732. extern void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint);
  733. // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
  734. // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
  735. // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
  736. // width and height and positioning info for it first.
  737.  
  738. extern void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint);
  739. // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
  740. // shift for the character
  741.  
  742. extern void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
  743. // get the bbox of the bitmap centered around the glyph origin; so the
  744. // bitmap width is ix1-ix0, height is iy1-iy0, and location to place
  745. // the bitmap top left is (leftSideBearing*scale,iy0).
  746. // (Note that the bitmap uses y-increases-down, but the shape uses
  747. // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
  748.  
  749. extern void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
  750. // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
  751. // shift for the character
  752.  
  753. // the following functions are equivalent to the above functions, but operate
  754. // on glyph indices instead of Unicode codepoints (for efficiency)
  755. extern unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);
  756. extern unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff);
  757. extern void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);
  758. extern void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);
  759. extern void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
  760. extern void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
  761.  
  762.  
  763. // @TODO: don't expose this structure
  764. typedef struct
  765. {
  766.    int w,h,stride;
  767.    unsigned char *pixels;
  768. } stbtt__bitmap;
  769.  
  770. extern void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata);
  771.  
  772. //////////////////////////////////////////////////////////////////////////////
  773. //
  774. // Finding the right font...
  775. //
  776. // You should really just solve this offline, keep your own tables
  777. // of what font is what, and don't try to get it out of the .ttf file.
  778. // That's because getting it out of the .ttf file is really hard, because
  779. // the names in the file can appear in many possible encodings, in many
  780. // possible languages, and e.g. if you need a case-insensitive comparison,
  781. // the details of that depend on the encoding & language in a complex way
  782. // (actually underspecified in truetype, but also gigantic).
  783. //
  784. // But you can use the provided functions in two possible ways:
  785. //     stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
  786. //             unicode-encoded names to try to find the font you want;
  787. //             you can run this before calling stbtt_InitFont()
  788. //
  789. //     stbtt_GetFontNameString() lets you get any of the various strings
  790. //             from the file yourself and do your own comparisons on them.
  791. //             You have to have called stbtt_InitFont() first.
  792.  
  793.  
  794. extern int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
  795. // returns the offset (not index) of the font that matches, or -1 if none
  796. //   if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
  797. //   if you use any other flag, use a font name like "Arial"; this checks
  798. //     the 'macStyle' header field; i don't know if fonts set this consistently
  799. #define STBTT_MACSTYLE_DONTCARE     0
  800. #define STBTT_MACSTYLE_BOLD         1
  801. #define STBTT_MACSTYLE_ITALIC       2
  802. #define STBTT_MACSTYLE_UNDERSCORE   4
  803. #define STBTT_MACSTYLE_NONE         8   // <= not same as 0, this makes us check the bitfield is 0
  804.  
  805. extern int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
  806. // returns 1/0 whether the first string interpreted as utf8 is identical to
  807. // the second string interpreted as big-endian utf16... useful for strings from next func
  808.  
  809. extern const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
  810. // returns the string (which may be big-endian double byte, e.g. for unicode)
  811. // and puts the length in bytes in *length.
  812. //
  813. // some of the values for the IDs are below; for more see the truetype spec:
  814. //     http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
  815. //     http://www.microsoft.com/typography/otspec/name.htm
  816.  
  817. enum { // platformID
  818.    STBTT_PLATFORM_ID_UNICODE   =0,
  819.    STBTT_PLATFORM_ID_MAC       =1,
  820.    STBTT_PLATFORM_ID_ISO       =2,
  821.    STBTT_PLATFORM_ID_MICROSOFT =3
  822. };
  823.  
  824. enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
  825.    STBTT_UNICODE_EID_UNICODE_1_0    =0,
  826.    STBTT_UNICODE_EID_UNICODE_1_1    =1,
  827.    STBTT_UNICODE_EID_ISO_10646      =2,
  828.    STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
  829.    STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
  830. };
  831.  
  832. enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
  833.    STBTT_MS_EID_SYMBOL        =0,
  834.    STBTT_MS_EID_UNICODE_BMP   =1,
  835.    STBTT_MS_EID_SHIFTJIS      =2,
  836.    STBTT_MS_EID_UNICODE_FULL  =10
  837. };
  838.  
  839. enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
  840.    STBTT_MAC_EID_ROMAN        =0,   STBTT_MAC_EID_ARABIC       =4,
  841.    STBTT_MAC_EID_JAPANESE     =1,   STBTT_MAC_EID_HEBREW       =5,
  842.    STBTT_MAC_EID_CHINESE_TRAD =2,   STBTT_MAC_EID_GREEK        =6,
  843.    STBTT_MAC_EID_KOREAN       =3,   STBTT_MAC_EID_RUSSIAN      =7
  844. };
  845.  
  846. enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
  847.        // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
  848.    STBTT_MS_LANG_ENGLISH     =0x0409,   STBTT_MS_LANG_ITALIAN     =0x0410,
  849.    STBTT_MS_LANG_CHINESE     =0x0804,   STBTT_MS_LANG_JAPANESE    =0x0411,
  850.    STBTT_MS_LANG_DUTCH       =0x0413,   STBTT_MS_LANG_KOREAN      =0x0412,
  851.    STBTT_MS_LANG_FRENCH      =0x040c,   STBTT_MS_LANG_RUSSIAN     =0x0419,
  852.    STBTT_MS_LANG_GERMAN      =0x0407,   STBTT_MS_LANG_SPANISH     =0x0409,
  853.    STBTT_MS_LANG_HEBREW      =0x040d,   STBTT_MS_LANG_SWEDISH     =0x041D
  854. };
  855.  
  856. enum { // languageID for STBTT_PLATFORM_ID_MAC
  857.    STBTT_MAC_LANG_ENGLISH      =0 ,   STBTT_MAC_LANG_JAPANESE     =11,
  858.    STBTT_MAC_LANG_ARABIC       =12,   STBTT_MAC_LANG_KOREAN       =23,
  859.    STBTT_MAC_LANG_DUTCH        =4 ,   STBTT_MAC_LANG_RUSSIAN      =32,
  860.    STBTT_MAC_LANG_FRENCH       =1 ,   STBTT_MAC_LANG_SPANISH      =6 ,
  861.    STBTT_MAC_LANG_GERMAN       =2 ,   STBTT_MAC_LANG_SWEDISH      =5 ,
  862.    STBTT_MAC_LANG_HEBREW       =10,   STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
  863.    STBTT_MAC_LANG_ITALIAN      =3 ,   STBTT_MAC_LANG_CHINESE_TRAD =19
  864. };
  865.  
  866. #ifdef __cplusplus
  867. }
  868. #endif
  869.  
  870. #endif // __STB_INCLUDE_STB_TRUETYPE_H__
  871.  
  872. ///////////////////////////////////////////////////////////////////////////////
  873. ///////////////////////////////////////////////////////////////////////////////
  874. ////
  875. ////   IMPLEMENTATION
  876. ////
  877. ////
  878.  
  879. #ifdef STB_TRUETYPE_IMPLEMENTATION
  880.  
  881. #ifndef STBTT_MAX_OVERSAMPLE
  882. #define STBTT_MAX_OVERSAMPLE   8
  883. #endif
  884.  
  885. typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];
  886.  
  887. //////////////////////////////////////////////////////////////////////////
  888. //
  889. // accessors to parse data from file
  890. //
  891.  
  892. // on platforms that don't allow misaligned reads, if we want to allow
  893. // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
  894.  
  895. #define ttBYTE(p)     (* (stbtt_uint8 *) (p))
  896. #define ttCHAR(p)     (* (stbtt_int8 *) (p))
  897. #define ttFixed(p)    ttLONG(p)
  898.  
  899. #if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE)
  900.  
  901.    #define ttUSHORT(p)   (* (stbtt_uint16 *) (p))
  902.    #define ttSHORT(p)    (* (stbtt_int16 *) (p))
  903.    #define ttULONG(p)    (* (stbtt_uint32 *) (p))
  904.    #define ttLONG(p)     (* (stbtt_int32 *) (p))
  905.  
  906. #else
  907.  
  908.    stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
  909.    stbtt_int16 ttSHORT(const stbtt_uint8 *p)   { return p[0]*256 + p[1]; }
  910.    stbtt_uint32 ttULONG(const stbtt_uint8 *p)  { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
  911.    stbtt_int32 ttLONG(const stbtt_uint8 *p)    { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
  912.  
  913. #endif
  914.  
  915. #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
  916. #define stbtt_tag(p,str)           stbtt_tag4(p,str[0],str[1],str[2],str[3])
  917.  
  918. static int stbtt__isfont(const stbtt_uint8 *font)
  919. {
  920.    // check the version number
  921.    if (stbtt_tag4(font, '1',0,0,0))  return 1; // TrueType 1
  922.    if (stbtt_tag(font, "typ1"))   return 1; // TrueType with type 1 font -- we don't support this!
  923.    if (stbtt_tag(font, "OTTO"))   return 1; // OpenType with CFF
  924.    if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
  925.    return 0;
  926. }
  927.  
  928. // @OPTIMIZE: binary search
  929. static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
  930. {
  931.    stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
  932.    stbtt_uint32 tabledir = fontstart + 12;
  933.    stbtt_int32 i;
  934.    for (i=0; i < num_tables; ++i) {
  935.       stbtt_uint32 loc = tabledir + 16*i;
  936.       if (stbtt_tag(data+loc+0, tag))
  937.          return ttULONG(data+loc+8);
  938.    }
  939.    return 0;
  940. }
  941.  
  942. int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, int index)
  943. {
  944.    // if it's just a font, there's only one valid index
  945.    if (stbtt__isfont(font_collection))
  946.       return index == 0 ? 0 : -1;
  947.  
  948.    // check if it's a TTC
  949.    if (stbtt_tag(font_collection, "ttcf")) {
  950.       // version 1?
  951.       if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
  952.          stbtt_int32 n = ttLONG(font_collection+8);
  953.          if (index >= n)
  954.             return -1;
  955.          return ttULONG(font_collection+12+index*14);
  956.       }
  957.    }
  958.    return -1;
  959. }
  960.  
  961. int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart)
  962. {
  963.    stbtt_uint8 *data = (stbtt_uint8 *) data2;
  964.    stbtt_uint32 cmap, t;
  965.    stbtt_int32 i,numTables;
  966.  
  967.    info->data = data;
  968.    info->fontstart = fontstart;
  969.  
  970.    cmap = stbtt__find_table(data, fontstart, "cmap");       // required
  971.    info->loca = stbtt__find_table(data, fontstart, "loca"); // required
  972.    info->head = stbtt__find_table(data, fontstart, "head"); // required
  973.    info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
  974.    info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
  975.    info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
  976.    info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
  977.    if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx)
  978.       return 0;
  979.  
  980.    t = stbtt__find_table(data, fontstart, "maxp");
  981.    if (t)
  982.       info->numGlyphs = ttUSHORT(data+t+4);
  983.    else
  984.       info->numGlyphs = 0xffff;
  985.  
  986.    // find a cmap encoding table we understand *now* to avoid searching
  987.    // later. (todo: could make this installable)
  988.    // the same regardless of glyph.
  989.    numTables = ttUSHORT(data + cmap + 2);
  990.    info->index_map = 0;
  991.    for (i=0; i < numTables; ++i) {
  992.       stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
  993.       // find an encoding we understand:
  994.       switch(ttUSHORT(data+encoding_record)) {
  995.          case STBTT_PLATFORM_ID_MICROSOFT:
  996.             switch (ttUSHORT(data+encoding_record+2)) {
  997.                case STBTT_MS_EID_UNICODE_BMP:
  998.                case STBTT_MS_EID_UNICODE_FULL:
  999.                   // MS/Unicode
  1000.                   info->index_map = cmap + ttULONG(data+encoding_record+4);
  1001.                   break;
  1002.             }
  1003.             break;
  1004.         case STBTT_PLATFORM_ID_UNICODE:
  1005.             // Mac/iOS has these
  1006.             // all the encodingIDs are unicode, so we don't bother to check it
  1007.             info->index_map = cmap + ttULONG(data+encoding_record+4);
  1008.             break;
  1009.       }
  1010.    }
  1011.    if (info->index_map == 0)
  1012.       return 0;
  1013.  
  1014.    info->indexToLocFormat = ttUSHORT(data+info->head + 50);
  1015.    return 1;
  1016. }
  1017.  
  1018. int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
  1019. {
  1020.    stbtt_uint8 *data = info->data;
  1021.    stbtt_uint32 index_map = info->index_map;
  1022.  
  1023.    stbtt_uint16 format = ttUSHORT(data + index_map + 0);
  1024.    if (format == 0) { // apple byte encoding
  1025.       stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
  1026.       if (unicode_codepoint < bytes-6)
  1027.          return ttBYTE(data + index_map + 6 + unicode_codepoint);
  1028.       return 0;
  1029.    } else if (format == 6) {
  1030.       stbtt_uint32 first = ttUSHORT(data + index_map + 6);
  1031.       stbtt_uint32 count = ttUSHORT(data + index_map + 8);
  1032.       if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
  1033.          return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
  1034.       return 0;
  1035.    } else if (format == 2) {
  1036.       STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
  1037.       return 0;
  1038.    } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges
  1039.       stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
  1040.       stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
  1041.       stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
  1042.       stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
  1043.       stbtt_uint16 item, offset, start, end;
  1044.  
  1045.       // do a binary search of the segments
  1046.       stbtt_uint32 endCount = index_map + 14;
  1047.       stbtt_uint32 search = endCount;
  1048.  
  1049.       if (unicode_codepoint > 0xffff)
  1050.          return 0;
  1051.  
  1052.       // they lie from endCount .. endCount + segCount
  1053.       // but searchRange is the nearest power of two, so...
  1054.       if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
  1055.          search += rangeShift*2;
  1056.  
  1057.       // now decrement to bias correctly to find smallest
  1058.       search -= 2;
  1059.       while (entrySelector) {
  1060.          searchRange >>= 1;
  1061.          start = ttUSHORT(data + search + searchRange*2 + segcount*2 + 2);
  1062.          end = ttUSHORT(data + search + searchRange*2);
  1063.          if (unicode_codepoint > end)
  1064.             search += searchRange*2;
  1065.          --entrySelector;
  1066.       }
  1067.       search += 2;
  1068.  
  1069.       item = (stbtt_uint16) ((search - endCount) >> 1);
  1070.  
  1071.       STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
  1072.       start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
  1073.       end = ttUSHORT(data + index_map + 14 + 2 + 2*item);
  1074.       if (unicode_codepoint < start)
  1075.          return 0;
  1076.  
  1077.       offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
  1078.       if (offset == 0)
  1079.          return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
  1080.  
  1081.       return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
  1082.    } else if (format == 12 || format == 13) {
  1083.       stbtt_uint32 ngroups = ttULONG(data+index_map+12);
  1084.       stbtt_int32 low,high;
  1085.       low = 0; high = (stbtt_int32)ngroups;
  1086.       // Binary search the right group.
  1087.       while (low < high) {
  1088.          stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high
  1089.          stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
  1090.          stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
  1091.          if ((stbtt_uint32) unicode_codepoint < start_char)
  1092.             high = mid;
  1093.          else if ((stbtt_uint32) unicode_codepoint > end_char)
  1094.             low = mid+1;
  1095.          else {
  1096.             stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
  1097.             if (format == 12)
  1098.                return start_glyph + unicode_codepoint-start_char;
  1099.             else // format == 13
  1100.                return start_glyph;
  1101.          }
  1102.       }
  1103.       return 0; // not found
  1104.    }
  1105.    // @TODO
  1106.    STBTT_assert(0);
  1107.    return 0;
  1108. }
  1109.  
  1110. int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
  1111. {
  1112.    return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
  1113. }
  1114.  
  1115. static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
  1116. {
  1117.    v->type = type;
  1118.    v->x = (stbtt_int16) x;
  1119.    v->y = (stbtt_int16) y;
  1120.    v->cx = (stbtt_int16) cx;
  1121.    v->cy = (stbtt_int16) cy;
  1122. }
  1123.  
  1124. static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
  1125. {
  1126.    int g1,g2;
  1127.  
  1128.    if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
  1129.    if (info->indexToLocFormat >= 2)    return -1; // unknown index->glyph map format
  1130.  
  1131.    if (info->indexToLocFormat == 0) {
  1132.       g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
  1133.       g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
  1134.    } else {
  1135.       g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
  1136.       g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
  1137.    }
  1138.  
  1139.    return g1==g2 ? -1 : g1; // if length is 0, return -1
  1140. }
  1141.  
  1142. int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
  1143. {
  1144.    int g = stbtt__GetGlyfOffset(info, glyph_index);
  1145.    if (g < 0) return 0;
  1146.  
  1147.    if (x0) *x0 = ttSHORT(info->data + g + 2);
  1148.    if (y0) *y0 = ttSHORT(info->data + g + 4);
  1149.    if (x1) *x1 = ttSHORT(info->data + g + 6);
  1150.    if (y1) *y1 = ttSHORT(info->data + g + 8);
  1151.    return 1;
  1152. }
  1153.  
  1154. int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
  1155. {
  1156.    return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
  1157. }
  1158.  
  1159. int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
  1160. {
  1161.    stbtt_int16 numberOfContours;
  1162.    int g = stbtt__GetGlyfOffset(info, glyph_index);
  1163.    if (g < 0) return 1;
  1164.    numberOfContours = ttSHORT(info->data + g);
  1165.    return numberOfContours == 0;
  1166. }
  1167.  
  1168. static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
  1169.     stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
  1170. {
  1171.    if (start_off) {
  1172.       if (was_off)
  1173.          stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
  1174.       stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
  1175.    } else {
  1176.       if (was_off)
  1177.          stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
  1178.       else
  1179.          stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
  1180.    }
  1181.    return num_vertices;
  1182. }
  1183.  
  1184. int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
  1185. {
  1186.    stbtt_int16 numberOfContours;
  1187.    stbtt_uint8 *endPtsOfContours;
  1188.    stbtt_uint8 *data = info->data;
  1189.    stbtt_vertex *vertices=0;
  1190.    int num_vertices=0;
  1191.    int g = stbtt__GetGlyfOffset(info, glyph_index);
  1192.  
  1193.    *pvertices = NULL;
  1194.  
  1195.    if (g < 0) return 0;
  1196.  
  1197.    numberOfContours = ttSHORT(data + g);
  1198.  
  1199.    if (numberOfContours > 0) {
  1200.       stbtt_uint8 flags=0,flagcount;
  1201.       stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
  1202.       stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
  1203.       stbtt_uint8 *points;
  1204.       endPtsOfContours = (data + g + 10);
  1205.       ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
  1206.       points = data + g + 10 + numberOfContours * 2 + 2 + ins;
  1207.  
  1208.       n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
  1209.  
  1210.       m = n + 2*numberOfContours;  // a loose bound on how many vertices we might need
  1211.       vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
  1212.       if (vertices == 0)
  1213.          return 0;
  1214.  
  1215.       next_move = 0;
  1216.       flagcount=0;
  1217.  
  1218.       // in first pass, we load uninterpreted data into the allocated array
  1219.       // above, shifted to the end of the array so we won't overwrite it when
  1220.       // we create our final data starting from the front
  1221.  
  1222.       off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
  1223.  
  1224.       // first load flags
  1225.  
  1226.       for (i=0; i < n; ++i) {
  1227.          if (flagcount == 0) {
  1228.             flags = *points++;
  1229.             if (flags & 8)
  1230.                flagcount = *points++;
  1231.          } else
  1232.             --flagcount;
  1233.          vertices[off+i].type = flags;
  1234.       }
  1235.  
  1236.       // now load x coordinates
  1237.       x=0;
  1238.       for (i=0; i < n; ++i) {
  1239.          flags = vertices[off+i].type;
  1240.          if (flags & 2) {
  1241.             stbtt_int16 dx = *points++;
  1242.             x += (flags & 16) ? dx : -dx; // ???
  1243.          } else {
  1244.             if (!(flags & 16)) {
  1245.                x = x + (stbtt_int16) (points[0]*256 + points[1]);
  1246.                points += 2;
  1247.             }
  1248.          }
  1249.          vertices[off+i].x = (stbtt_int16) x;
  1250.       }
  1251.  
  1252.       // now load y coordinates
  1253.       y=0;
  1254.       for (i=0; i < n; ++i) {
  1255.          flags = vertices[off+i].type;
  1256.          if (flags & 4) {
  1257.             stbtt_int16 dy = *points++;
  1258.             y += (flags & 32) ? dy : -dy; // ???
  1259.          } else {
  1260.             if (!(flags & 32)) {
  1261.                y = y + (stbtt_int16) (points[0]*256 + points[1]);
  1262.                points += 2;
  1263.             }
  1264.          }
  1265.          vertices[off+i].y = (stbtt_int16) y;
  1266.       }
  1267.  
  1268.       // now convert them to our format
  1269.       num_vertices=0;
  1270.       sx = sy = cx = cy = scx = scy = 0;
  1271.       for (i=0; i < n; ++i) {
  1272.          flags = vertices[off+i].type;
  1273.          x     = (stbtt_int16) vertices[off+i].x;
  1274.          y     = (stbtt_int16) vertices[off+i].y;
  1275.  
  1276.          if (next_move == i) {
  1277.             if (i != 0)
  1278.                num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
  1279.  
  1280.             // now start the new one              
  1281.             start_off = !(flags & 1);
  1282.             if (start_off) {
  1283.                // if we start off with an off-curve point, then when we need to find a point on the curve
  1284.                // where we can start, and we need to save some state for when we wraparound.
  1285.                scx = x;
  1286.                scy = y;
  1287.                if (!(vertices[off+i+1].type & 1)) {
  1288.                   // next point is also a curve point, so interpolate an on-point curve
  1289.                   sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
  1290.                   sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
  1291.                } else {
  1292.                   // otherwise just use the next point as our start point
  1293.                   sx = (stbtt_int32) vertices[off+i+1].x;
  1294.                   sy = (stbtt_int32) vertices[off+i+1].y;
  1295.                   ++i; // we're using point i+1 as the starting point, so skip it
  1296.                }
  1297.             } else {
  1298.                sx = x;
  1299.                sy = y;
  1300.             }
  1301.             stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
  1302.             was_off = 0;
  1303.             next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
  1304.             ++j;
  1305.          } else {
  1306.             if (!(flags & 1)) { // if it's a curve
  1307.                if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
  1308.                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
  1309.                cx = x;
  1310.                cy = y;
  1311.                was_off = 1;
  1312.             } else {
  1313.                if (was_off)
  1314.                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
  1315.                else
  1316.                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
  1317.                was_off = 0;
  1318.             }
  1319.          }
  1320.       }
  1321.       num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
  1322.    } else if (numberOfContours == -1) {
  1323.       // Compound shapes.
  1324.       int more = 1;
  1325.       stbtt_uint8 *comp = data + g + 10;
  1326.       num_vertices = 0;
  1327.       vertices = 0;
  1328.       while (more) {
  1329.          stbtt_uint16 flags, gidx;
  1330.          int comp_num_verts = 0, i;
  1331.          stbtt_vertex *comp_verts = 0, *tmp = 0;
  1332.          float mtx[6] = {1,0,0,1,0,0}, m, n;
  1333.          
  1334.          flags = ttSHORT(comp); comp+=2;
  1335.          gidx = ttSHORT(comp); comp+=2;
  1336.  
  1337.          if (flags & 2) { // XY values
  1338.             if (flags & 1) { // shorts
  1339.                mtx[4] = ttSHORT(comp); comp+=2;
  1340.                mtx[5] = ttSHORT(comp); comp+=2;
  1341.             } else {
  1342.                mtx[4] = ttCHAR(comp); comp+=1;
  1343.                mtx[5] = ttCHAR(comp); comp+=1;
  1344.             }
  1345.          }
  1346.          else {
  1347.             // @TODO handle matching point
  1348.             STBTT_assert(0);
  1349.          }
  1350.          if (flags & (1<<3)) { // WE_HAVE_A_SCALE
  1351.             mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1352.             mtx[1] = mtx[2] = 0;
  1353.          } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
  1354.             mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
  1355.             mtx[1] = mtx[2] = 0;
  1356.             mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1357.          } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
  1358.             mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
  1359.             mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
  1360.             mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
  1361.             mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1362.          }
  1363.          
  1364.          // Find transformation scales.
  1365.          m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
  1366.          n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
  1367.  
  1368.          // Get indexed glyph.
  1369.          comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
  1370.          if (comp_num_verts > 0) {
  1371.             // Transform vertices.
  1372.             for (i = 0; i < comp_num_verts; ++i) {
  1373.                stbtt_vertex* v = &comp_verts[i];
  1374.                stbtt_vertex_type x,y;
  1375.                x=v->x; y=v->y;
  1376.                v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
  1377.                v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
  1378.                x=v->cx; y=v->cy;
  1379.                v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
  1380.                v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
  1381.             }
  1382.             // Append vertices.
  1383.             tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
  1384.             if (!tmp) {
  1385.                if (vertices) STBTT_free(vertices, info->userdata);
  1386.                if (comp_verts) STBTT_free(comp_verts, info->userdata);
  1387.                return 0;
  1388.             }
  1389.             if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));
  1390.             STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
  1391.             if (vertices) STBTT_free(vertices, info->userdata);
  1392.             vertices = tmp;
  1393.             STBTT_free(comp_verts, info->userdata);
  1394.             num_vertices += comp_num_verts;
  1395.          }
  1396.          // More components ?
  1397.          more = flags & (1<<5);
  1398.       }
  1399.    } else if (numberOfContours < 0) {
  1400.       // @TODO other compound variations?
  1401.       STBTT_assert(0);
  1402.    } else {
  1403.       // numberOfCounters == 0, do nothing
  1404.    }
  1405.  
  1406.    *pvertices = vertices;
  1407.    return num_vertices;
  1408. }
  1409.  
  1410. void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
  1411. {
  1412.    stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
  1413.    if (glyph_index < numOfLongHorMetrics) {
  1414.       if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*glyph_index);
  1415.       if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
  1416.    } else {
  1417.       if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
  1418.       if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
  1419.    }
  1420. }
  1421.  
  1422. int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
  1423. {
  1424.    stbtt_uint8 *data = info->data + info->kern;
  1425.    stbtt_uint32 needle, straw;
  1426.    int l, r, m;
  1427.  
  1428.    // we only look at the first table. it must be 'horizontal' and format 0.
  1429.    if (!info->kern)
  1430.       return 0;
  1431.    if (ttUSHORT(data+2) < 1) // number of tables, need at least 1
  1432.       return 0;
  1433.    if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format
  1434.       return 0;
  1435.  
  1436.    l = 0;
  1437.    r = ttUSHORT(data+10) - 1;
  1438.    needle = glyph1 << 16 | glyph2;
  1439.    while (l <= r) {
  1440.       m = (l + r) >> 1;
  1441.       straw = ttULONG(data+18+(m*6)); // note: unaligned read
  1442.       if (needle < straw)
  1443.          r = m - 1;
  1444.       else if (needle > straw)
  1445.          l = m + 1;
  1446.       else
  1447.          return ttSHORT(data+22+(m*6));
  1448.    }
  1449.    return 0;
  1450. }
  1451.  
  1452. int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
  1453. {
  1454.    if (!info->kern) // if no kerning table, don't waste time looking up both codepoint->glyphs
  1455.       return 0;
  1456.    return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
  1457. }
  1458.  
  1459. void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
  1460. {
  1461.    stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
  1462. }
  1463.  
  1464. void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
  1465. {
  1466.    if (ascent ) *ascent  = ttSHORT(info->data+info->hhea + 4);
  1467.    if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
  1468.    if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
  1469. }
  1470.  
  1471. void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
  1472. {
  1473.    *x0 = ttSHORT(info->data + info->head + 36);
  1474.    *y0 = ttSHORT(info->data + info->head + 38);
  1475.    *x1 = ttSHORT(info->data + info->head + 40);
  1476.    *y1 = ttSHORT(info->data + info->head + 42);
  1477. }
  1478.  
  1479. float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
  1480. {
  1481.    int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
  1482.    return (float) height / fheight;
  1483. }
  1484.  
  1485. float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
  1486. {
  1487.    int unitsPerEm = ttUSHORT(info->data + info->head + 18);
  1488.    return pixels / unitsPerEm;
  1489. }
  1490.  
  1491. void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
  1492. {
  1493.    STBTT_free(v, info->userdata);
  1494. }
  1495.  
  1496. //////////////////////////////////////////////////////////////////////////////
  1497. //
  1498. // antialiasing software rasterizer
  1499. //
  1500.  
  1501. 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)
  1502. {
  1503.    int x0,y0,x1,y1;
  1504.    if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {
  1505.       // e.g. space character
  1506.       if (ix0) *ix0 = 0;
  1507.       if (iy0) *iy0 = 0;
  1508.       if (ix1) *ix1 = 0;
  1509.       if (iy1) *iy1 = 0;
  1510.    } else {
  1511.       // move to integral bboxes (treating pixels as little squares, what pixels get touched)?
  1512.       if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);
  1513.       if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);
  1514.       if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);
  1515.       if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);
  1516.    }
  1517. }
  1518.  
  1519. void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
  1520. {
  1521.    stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
  1522. }
  1523.  
  1524. 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)
  1525. {
  1526.    stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
  1527. }
  1528.  
  1529. void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
  1530. {
  1531.    stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
  1532. }
  1533.  
  1534. typedef struct stbtt__edge {
  1535.    float x0,y0, x1,y1;
  1536.    int invert;
  1537. } stbtt__edge;
  1538.  
  1539. typedef struct stbtt__active_edge
  1540. {
  1541.    int x,dx;
  1542.    float ey;
  1543.    struct stbtt__active_edge *next;
  1544.    int valid;
  1545. } stbtt__active_edge;
  1546.  
  1547. #define FIXSHIFT   10
  1548. #define FIX        (1 << FIXSHIFT)
  1549. #define FIXMASK    (FIX-1)
  1550.  
  1551. static stbtt__active_edge *new_active(stbtt__edge *e, int off_x, float start_point, void *userdata)
  1552. {
  1553.    stbtt__active_edge *z = (stbtt__active_edge *) STBTT_malloc(sizeof(*z), userdata); // @TODO: make a pool of these!!!
  1554.    float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
  1555.    STBTT_assert(e->y0 <= start_point);
  1556.    if (!z) return z;
  1557.    // round dx down to avoid going too far
  1558.    if (dxdy < 0)
  1559.       z->dx = -STBTT_ifloor(FIX * -dxdy);
  1560.    else
  1561.       z->dx = STBTT_ifloor(FIX * dxdy);
  1562.    z->x = STBTT_ifloor(FIX * (e->x0 + dxdy * (start_point - e->y0)));
  1563.    z->x -= off_x * FIX;
  1564.    z->ey = e->y1;
  1565.    z->next = 0;
  1566.    z->valid = e->invert ? 1 : -1;
  1567.    return z;
  1568. }
  1569.  
  1570. // note: this routine clips fills that extend off the edges... ideally this
  1571. // wouldn't happen, but it could happen if the truetype glyph bounding boxes
  1572. // are wrong, or if the user supplies a too-small bitmap
  1573. static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
  1574. {
  1575.    // non-zero winding fill
  1576.    int x0=0, w=0;
  1577.  
  1578.    while (e) {
  1579.       if (w == 0) {
  1580.          // if we're currently at zero, we need to record the edge start point
  1581.          x0 = e->x; w += e->valid;
  1582.       } else {
  1583.          int x1 = e->x; w += e->valid;
  1584.          // if we went to zero, we need to draw
  1585.          if (w == 0) {
  1586.             int i = x0 >> FIXSHIFT;
  1587.             int j = x1 >> FIXSHIFT;
  1588.  
  1589.             if (i < len && j >= 0) {
  1590.                if (i == j) {
  1591.                   // x0,x1 are the same pixel, so compute combined coverage
  1592.                   scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> FIXSHIFT);
  1593.                } else {
  1594.                   if (i >= 0) // add antialiasing for x0
  1595.                      scanline[i] = scanline[i] + (stbtt_uint8) (((FIX - (x0 & FIXMASK)) * max_weight) >> FIXSHIFT);
  1596.                   else
  1597.                      i = -1; // clip
  1598.  
  1599.                   if (j < len) // add antialiasing for x1
  1600.                      scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & FIXMASK) * max_weight) >> FIXSHIFT);
  1601.                   else
  1602.                      j = len; // clip
  1603.  
  1604.                   for (++i; i < j; ++i) // fill pixels between x0 and x1
  1605.                      scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
  1606.                }
  1607.             }
  1608.          }
  1609.       }
  1610.      
  1611.       e = e->next;
  1612.    }
  1613. }
  1614.  
  1615. static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
  1616. {
  1617.    stbtt__active_edge *active = NULL;
  1618.    int y,j=0;
  1619.    int max_weight = (255 / vsubsample);  // weight per vertical scanline
  1620.    int s; // vertical subsample index
  1621.    unsigned char scanline_data[512], *scanline;
  1622.  
  1623.    if (result->w > 512)
  1624.       scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
  1625.    else
  1626.       scanline = scanline_data;
  1627.  
  1628.    y = off_y * vsubsample;
  1629.    e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
  1630.  
  1631.    while (j < result->h) {
  1632.       STBTT_memset(scanline, 0, result->w);
  1633.       for (s=0; s < vsubsample; ++s) {
  1634.          // find center of pixel for this scanline
  1635.          float scan_y = y + 0.5f;
  1636.          stbtt__active_edge **step = &active;
  1637.  
  1638.          // update all active edges;
  1639.          // remove all active edges that terminate before the center of this scanline
  1640.          while (*step) {
  1641.             stbtt__active_edge * z = *step;
  1642.             if (z->ey <= scan_y) {
  1643.                *step = z->next; // delete from list
  1644.                STBTT_assert(z->valid);
  1645.                z->valid = 0;
  1646.                STBTT_free(z, userdata);
  1647.             } else {
  1648.                z->x += z->dx; // advance to position for current scanline
  1649.                step = &((*step)->next); // advance through list
  1650.             }
  1651.          }
  1652.  
  1653.          // resort the list if needed
  1654.          for(;;) {
  1655.             int changed=0;
  1656.             step = &active;
  1657.             while (*step && (*step)->next) {
  1658.                if ((*step)->x > (*step)->next->x) {
  1659.                   stbtt__active_edge *t = *step;
  1660.                   stbtt__active_edge *q = t->next;
  1661.  
  1662.                   t->next = q->next;
  1663.                   q->next = t;
  1664.                   *step = q;
  1665.                   changed = 1;
  1666.                }
  1667.                step = &(*step)->next;
  1668.             }
  1669.             if (!changed) break;
  1670.          }
  1671.  
  1672.          // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
  1673.          while (e->y0 <= scan_y) {
  1674.             if (e->y1 > scan_y) {
  1675.                stbtt__active_edge *z = new_active(e, off_x, scan_y, userdata);
  1676.                // find insertion point
  1677.                if (active == NULL)
  1678.                   active = z;
  1679.                else if (z->x < active->x) {
  1680.                   // insert at front
  1681.                   z->next = active;
  1682.                   active = z;
  1683.                } else {
  1684.                   // find thing to insert AFTER
  1685.                   stbtt__active_edge *p = active;
  1686.                   while (p->next && p->next->x < z->x)
  1687.                      p = p->next;
  1688.                   // at this point, p->next->x is NOT < z->x
  1689.                   z->next = p->next;
  1690.                   p->next = z;
  1691.                }
  1692.             }
  1693.             ++e;
  1694.          }
  1695.  
  1696.          // now process all active edges in XOR fashion
  1697.          if (active)
  1698.             stbtt__fill_active_edges(scanline, result->w, active, max_weight);
  1699.  
  1700.          ++y;
  1701.       }
  1702.       STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
  1703.       ++j;
  1704.    }
  1705.  
  1706.    while (active) {
  1707.       stbtt__active_edge *z = active;
  1708.       active = active->next;
  1709.       STBTT_free(z, userdata);
  1710.    }
  1711.  
  1712.    if (scanline != scanline_data)
  1713.       STBTT_free(scanline, userdata);
  1714. }
  1715.  
  1716. static int stbtt__edge_compare(const void *p, const void *q)
  1717. {
  1718.    stbtt__edge *a = (stbtt__edge *) p;
  1719.    stbtt__edge *b = (stbtt__edge *) q;
  1720.  
  1721.    if (a->y0 < b->y0) return -1;
  1722.    if (a->y0 > b->y0) return  1;
  1723.    return 0;
  1724. }
  1725.  
  1726. typedef struct
  1727. {
  1728.    float x,y;
  1729. } stbtt__point;
  1730.  
  1731. 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)
  1732. {
  1733.    float y_scale_inv = invert ? -scale_y : scale_y;
  1734.    stbtt__edge *e;
  1735.    int n,i,j,k,m;
  1736.    int vsubsample = result->h < 8 ? 15 : 5;
  1737.    // vsubsample should divide 255 evenly; otherwise we won't reach full opacity
  1738.  
  1739.    // now we have to blow out the windings into explicit edge lists
  1740.    n = 0;
  1741.    for (i=0; i < windings; ++i)
  1742.       n += wcount[i];
  1743.  
  1744.    e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel
  1745.    if (e == 0) return;
  1746.    n = 0;
  1747.  
  1748.    m=0;
  1749.    for (i=0; i < windings; ++i) {
  1750.       stbtt__point *p = pts + m;
  1751.       m += wcount[i];
  1752.       j = wcount[i]-1;
  1753.       for (k=0; k < wcount[i]; j=k++) {
  1754.          int a=k,b=j;
  1755.          // skip the edge if horizontal
  1756.          if (p[j].y == p[k].y)
  1757.             continue;
  1758.          // add edge from j to k to the list
  1759.          e[n].invert = 0;
  1760.          if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
  1761.             e[n].invert = 1;
  1762.             a=j,b=k;
  1763.          }
  1764.          e[n].x0 = p[a].x * scale_x + shift_x;
  1765.          e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;
  1766.          e[n].x1 = p[b].x * scale_x + shift_x;
  1767.          e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;
  1768.          ++n;
  1769.       }
  1770.    }
  1771.  
  1772.    // now sort the edges by their highest point (should snap to integer, and then by x)
  1773.    STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
  1774.  
  1775.    // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
  1776.    stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
  1777.  
  1778.    STBTT_free(e, userdata);
  1779. }
  1780.  
  1781. static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
  1782. {
  1783.    if (!points) return; // during first pass, it's unallocated
  1784.    points[n].x = x;
  1785.    points[n].y = y;
  1786. }
  1787.  
  1788. // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching
  1789. 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)
  1790. {
  1791.    // midpoint
  1792.    float mx = (x0 + 2*x1 + x2)/4;
  1793.    float my = (y0 + 2*y1 + y2)/4;
  1794.    // versus directly drawn line
  1795.    float dx = (x0+x2)/2 - mx;
  1796.    float dy = (y0+y2)/2 - my;
  1797.    if (n > 16) // 65536 segments on one curve better be enough!
  1798.       return 1;
  1799.    if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
  1800.       stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
  1801.       stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
  1802.    } else {
  1803.       stbtt__add_point(points, *num_points,x2,y2);
  1804.       *num_points = *num_points+1;
  1805.    }
  1806.    return 1;
  1807. }
  1808.  
  1809. // returns number of contours
  1810. stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
  1811. {
  1812.    stbtt__point *points=0;
  1813.    int num_points=0;
  1814.  
  1815.    float objspace_flatness_squared = objspace_flatness * objspace_flatness;
  1816.    int i,n=0,start=0, pass;
  1817.  
  1818.    // count how many "moves" there are to get the contour count
  1819.    for (i=0; i < num_verts; ++i)
  1820.       if (vertices[i].type == STBTT_vmove)
  1821.          ++n;
  1822.  
  1823.    *num_contours = n;
  1824.    if (n == 0) return 0;
  1825.  
  1826.    *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
  1827.  
  1828.    if (*contour_lengths == 0) {
  1829.       *num_contours = 0;
  1830.       return 0;
  1831.    }
  1832.  
  1833.    // make two passes through the points so we don't need to realloc
  1834.    for (pass=0; pass < 2; ++pass) {
  1835.       float x=0,y=0;
  1836.       if (pass == 1) {
  1837.          points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
  1838.          if (points == NULL) goto error;
  1839.       }
  1840.       num_points = 0;
  1841.       n= -1;
  1842.       for (i=0; i < num_verts; ++i) {
  1843.          switch (vertices[i].type) {
  1844.             case STBTT_vmove:
  1845.                // start the next contour
  1846.                if (n >= 0)
  1847.                   (*contour_lengths)[n] = num_points - start;
  1848.                ++n;
  1849.                start = num_points;
  1850.  
  1851.                x = vertices[i].x, y = vertices[i].y;
  1852.                stbtt__add_point(points, num_points++, x,y);
  1853.                break;
  1854.             case STBTT_vline:
  1855.                x = vertices[i].x, y = vertices[i].y;
  1856.                stbtt__add_point(points, num_points++, x, y);
  1857.                break;
  1858.             case STBTT_vcurve:
  1859.                stbtt__tesselate_curve(points, &num_points, x,y,
  1860.                                         vertices[i].cx, vertices[i].cy,
  1861.                                         vertices[i].x,  vertices[i].y,
  1862.                                         objspace_flatness_squared, 0);
  1863.                x = vertices[i].x, y = vertices[i].y;
  1864.                break;
  1865.          }
  1866.       }
  1867.       (*contour_lengths)[n] = num_points - start;
  1868.    }
  1869.  
  1870.    return points;
  1871. error:
  1872.    STBTT_free(points, userdata);
  1873.    STBTT_free(*contour_lengths, userdata);
  1874.    *contour_lengths = 0;
  1875.    *num_contours = 0;
  1876.    return NULL;
  1877. }
  1878.  
  1879. 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)
  1880. {
  1881.    float scale = scale_x > scale_y ? scale_y : scale_x;
  1882.    int winding_count, *winding_lengths;
  1883.    stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
  1884.    if (windings) {
  1885.       stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
  1886.       STBTT_free(winding_lengths, userdata);
  1887.       STBTT_free(windings, userdata);
  1888.    }
  1889. }
  1890.  
  1891. void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
  1892. {
  1893.    STBTT_free(bitmap, userdata);
  1894. }
  1895.  
  1896. 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)
  1897. {
  1898.    int ix0,iy0,ix1,iy1;
  1899.    stbtt__bitmap gbm;
  1900.    stbtt_vertex *vertices;  
  1901.    int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
  1902.  
  1903.    if (scale_x == 0) scale_x = scale_y;
  1904.    if (scale_y == 0) {
  1905.       if (scale_x == 0) return NULL;
  1906.       scale_y = scale_x;
  1907.    }
  1908.  
  1909.    stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
  1910.  
  1911.    // now we get the size
  1912.    gbm.w = (ix1 - ix0);
  1913.    gbm.h = (iy1 - iy0);
  1914.    gbm.pixels = NULL; // in case we error
  1915.  
  1916.    if (width ) *width  = gbm.w;
  1917.    if (height) *height = gbm.h;
  1918.    if (xoff  ) *xoff   = ix0;
  1919.    if (yoff  ) *yoff   = iy0;
  1920.    
  1921.    if (gbm.w && gbm.h) {
  1922.       gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
  1923.       if (gbm.pixels) {
  1924.          gbm.stride = gbm.w;
  1925.  
  1926.          stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
  1927.       }
  1928.    }
  1929.    STBTT_free(vertices, info->userdata);
  1930.    return gbm.pixels;
  1931. }  
  1932.  
  1933. unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)
  1934. {
  1935.    return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
  1936. }
  1937.  
  1938. 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)
  1939. {
  1940.    int ix0,iy0;
  1941.    stbtt_vertex *vertices;
  1942.    int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
  1943.    stbtt__bitmap gbm;  
  1944.  
  1945.    stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
  1946.    gbm.pixels = output;
  1947.    gbm.w = out_w;
  1948.    gbm.h = out_h;
  1949.    gbm.stride = out_stride;
  1950.  
  1951.    if (gbm.w && gbm.h)
  1952.       stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
  1953.  
  1954.    STBTT_free(vertices, info->userdata);
  1955. }
  1956.  
  1957. 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)
  1958. {
  1959.    stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
  1960. }
  1961.  
  1962. 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)
  1963. {
  1964.    return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
  1965. }  
  1966.  
  1967. 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)
  1968. {
  1969.    stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
  1970. }
  1971.  
  1972. unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
  1973. {
  1974.    return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
  1975. }  
  1976.  
  1977. 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)
  1978. {
  1979.    stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
  1980. }
  1981.  
  1982. //////////////////////////////////////////////////////////////////////////////
  1983. //
  1984. // bitmap baking
  1985. //
  1986. // This is SUPER-CRAPPY packing to keep source code small
  1987.  
  1988. extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)
  1989.                                 float pixel_height,                     // height of font in pixels
  1990.                                 unsigned char *pixels, int pw, int ph,  // bitmap to be filled in
  1991.                                 int first_char, int num_chars,          // characters to bake
  1992.                                 stbtt_bakedchar *chardata)
  1993. {
  1994.    float scale;
  1995.    int x,y,bottom_y, i;
  1996.    stbtt_fontinfo f;
  1997.    if (!stbtt_InitFont(&f, data, offset))
  1998.       return -1;
  1999.    STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
  2000.    x=y=1;
  2001.    bottom_y = 1;
  2002.  
  2003.    scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
  2004.  
  2005.    for (i=0; i < num_chars; ++i) {
  2006.       int advance, lsb, x0,y0,x1,y1,gw,gh;
  2007.       int g = stbtt_FindGlyphIndex(&f, first_char + i);
  2008.       stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
  2009.       stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
  2010.       gw = x1-x0;
  2011.       gh = y1-y0;
  2012.       if (x + gw + 1 >= pw)
  2013.          y = bottom_y, x = 1; // advance to next row
  2014.       if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
  2015.          return -i;
  2016.       STBTT_assert(x+gw < pw);
  2017.       STBTT_assert(y+gh < ph);
  2018.       stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
  2019.       chardata[i].x0 = (stbtt_int16) x;
  2020.       chardata[i].y0 = (stbtt_int16) y;
  2021.       chardata[i].x1 = (stbtt_int16) (x + gw);
  2022.       chardata[i].y1 = (stbtt_int16) (y + gh);
  2023.       chardata[i].xadvance = scale * advance;
  2024.       chardata[i].xoff     = (float) x0;
  2025.       chardata[i].yoff     = (float) y0;
  2026.       x = x + gw + 1;
  2027.       if (y+gh+1 > bottom_y)
  2028.          bottom_y = y+gh+1;
  2029.    }
  2030.    return bottom_y;
  2031. }
  2032.  
  2033. void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
  2034. {
  2035.    float d3d_bias = opengl_fillrule ? 0 : -0.5f;
  2036.    float ipw = 1.0f / pw, iph = 1.0f / ph;
  2037.    stbtt_bakedchar *b = chardata + char_index;
  2038.    int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5);
  2039.    int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5);
  2040.  
  2041.    q->x0 = round_x + d3d_bias;
  2042.    q->y0 = round_y + d3d_bias;
  2043.    q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
  2044.    q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
  2045.  
  2046.    q->s0 = b->x0 * ipw;
  2047.    q->t0 = b->y0 * iph;
  2048.    q->s1 = b->x1 * ipw;
  2049.    q->t1 = b->y1 * iph;
  2050.  
  2051.    *xpos += b->xadvance;
  2052. }
  2053.  
  2054. //////////////////////////////////////////////////////////////////////////////
  2055. //
  2056. // rectangle packing replacement routines if you don't have stb_rect_pack.h
  2057. //
  2058.  
  2059. #ifndef STB_RECT_PACK_VERSION
  2060. #ifdef _MSC_VER
  2061. #define STBTT__NOTUSED(v)  (void)(v)
  2062. #else
  2063. #define STBTT__NOTUSED(v)  (void)sizeof(v)
  2064. #endif
  2065.  
  2066. typedef int stbrp_coord;
  2067.  
  2068. ////////////////////////////////////////////////////////////////////////////////////
  2069. //                                                                                //
  2070. //                                                                                //
  2071. // COMPILER WARNING ?!?!?                                                         //
  2072. //                                                                                //
  2073. //                                                                                //
  2074. // if you get a compile warning due to these symbols being defined more than      //
  2075. // once, move #include "stb_rect_pack.h" before #include "stb_truetype.h"         //
  2076. //                                                                                //
  2077. ////////////////////////////////////////////////////////////////////////////////////
  2078.  
  2079. typedef struct
  2080. {
  2081.    int width,height;
  2082.    int x,y,bottom_y;
  2083. } stbrp_context;
  2084.  
  2085. typedef struct
  2086. {
  2087.    unsigned char x;
  2088. } stbrp_node;
  2089.  
  2090. typedef struct
  2091. {
  2092.    stbrp_coord x,y;
  2093.    int id,w,h,was_packed;
  2094. } stbrp_rect;
  2095.  
  2096. static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)
  2097. {
  2098.    con->width  = pw;
  2099.    con->height = ph;
  2100.    con->x = 0;
  2101.    con->y = 0;
  2102.    con->bottom_y = 0;
  2103.    STBTT__NOTUSED(nodes);
  2104.    STBTT__NOTUSED(num_nodes);  
  2105. }
  2106.  
  2107. static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)
  2108. {
  2109.    int i;
  2110.    for (i=0; i < num_rects; ++i) {
  2111.       if (con->x + rects[i].w > con->width) {
  2112.          con->x = 0;
  2113.          con->y = con->bottom_y;
  2114.       }
  2115.       if (con->y + rects[i].h > con->height)
  2116.          break;
  2117.       rects[i].x = con->x;
  2118.       rects[i].y = con->y;
  2119.       rects[i].was_packed = 1;
  2120.       con->x += rects[i].w;
  2121.       if (con->y + rects[i].h > con->bottom_y)
  2122.          con->bottom_y = con->y + rects[i].h;
  2123.    }
  2124.    for (   ; i < num_rects; ++i)
  2125.       rects[i].was_packed = 0;
  2126. }
  2127. #endif
  2128.  
  2129. //////////////////////////////////////////////////////////////////////////////
  2130. //
  2131. // bitmap baking
  2132. //
  2133. // This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If
  2134. // stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.
  2135.  
  2136. int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context)
  2137. {
  2138.    stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context)            ,alloc_context);
  2139.    int            num_nodes = pw - padding;
  2140.    stbrp_node    *nodes   = (stbrp_node    *) STBTT_malloc(sizeof(*nodes  ) * num_nodes,alloc_context);
  2141.  
  2142.    if (context == NULL || nodes == NULL) {
  2143.       if (context != NULL) STBTT_free(context, alloc_context);
  2144.       if (nodes   != NULL) STBTT_free(nodes  , alloc_context);
  2145.       return 0;
  2146.    }
  2147.  
  2148.    spc->user_allocator_context = alloc_context;
  2149.    spc->width = pw;
  2150.    spc->height = ph;
  2151.    spc->pixels = pixels;
  2152.    spc->pack_info = context;
  2153.    spc->nodes = nodes;
  2154.    spc->padding = padding;
  2155.    spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;
  2156.    spc->h_oversample = 1;
  2157.    spc->v_oversample = 1;
  2158.  
  2159.    stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);
  2160.  
  2161.    STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
  2162.  
  2163.    return 1;
  2164. }
  2165.  
  2166. void stbtt_PackEnd  (stbtt_pack_context *spc)
  2167. {
  2168.    STBTT_free(spc->nodes    , spc->user_allocator_context);
  2169.    STBTT_free(spc->pack_info, spc->user_allocator_context);
  2170. }
  2171.  
  2172. void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)
  2173. {
  2174.    STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);
  2175.    STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);
  2176.    if (h_oversample <= STBTT_MAX_OVERSAMPLE)
  2177.       spc->h_oversample = h_oversample;
  2178.    if (v_oversample <= STBTT_MAX_OVERSAMPLE)
  2179.       spc->v_oversample = v_oversample;
  2180. }
  2181.  
  2182. #define STBTT__OVER_MASK  (STBTT_MAX_OVERSAMPLE-1)
  2183.  
  2184. static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
  2185. {
  2186.    unsigned char buffer[STBTT_MAX_OVERSAMPLE];
  2187.    int safe_w = w - kernel_width;
  2188.    int j;
  2189.    for (j=0; j < h; ++j) {
  2190.       int i;
  2191.       unsigned int total;
  2192.       STBTT_memset(buffer, 0, kernel_width);
  2193.  
  2194.       total = 0;
  2195.  
  2196.       // make kernel_width a constant in common cases so compiler can optimize out the divide
  2197.       switch (kernel_width) {
  2198.          case 2:
  2199.             for (i=0; i <= safe_w; ++i) {
  2200.                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  2201.                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  2202.                pixels[i] = (unsigned char) (total / 2);
  2203.             }
  2204.             break;
  2205.          case 3:
  2206.             for (i=0; i <= safe_w; ++i) {
  2207.                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  2208.                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  2209.                pixels[i] = (unsigned char) (total / 3);
  2210.             }
  2211.             break;
  2212.          case 4:
  2213.             for (i=0; i <= safe_w; ++i) {
  2214.                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  2215.                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  2216.                pixels[i] = (unsigned char) (total / 4);
  2217.             }
  2218.             break;
  2219.          default:
  2220.             for (i=0; i <= safe_w; ++i) {
  2221.                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  2222.                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  2223.                pixels[i] = (unsigned char) (total / kernel_width);
  2224.             }
  2225.             break;
  2226.       }
  2227.  
  2228.       for (; i < w; ++i) {
  2229.          STBTT_assert(pixels[i] == 0);
  2230.          total -= buffer[i & STBTT__OVER_MASK];
  2231.          pixels[i] = (unsigned char) (total / kernel_width);
  2232.       }
  2233.  
  2234.       pixels += stride_in_bytes;
  2235.    }
  2236. }
  2237.  
  2238. static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
  2239. {
  2240.    unsigned char buffer[STBTT_MAX_OVERSAMPLE];
  2241.    int safe_h = h - kernel_width;
  2242.    int j;
  2243.    for (j=0; j < w; ++j) {
  2244.       int i;
  2245.       unsigned int total;
  2246.       STBTT_memset(buffer, 0, kernel_width);
  2247.  
  2248.       total = 0;
  2249.  
  2250.       // make kernel_width a constant in common cases so compiler can optimize out the divide
  2251.       switch (kernel_width) {
  2252.          case 2:
  2253.             for (i=0; i <= safe_h; ++i) {
  2254.                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  2255.                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  2256.                pixels[i*stride_in_bytes] = (unsigned char) (total / 2);
  2257.             }
  2258.             break;
  2259.          case 3:
  2260.             for (i=0; i <= safe_h; ++i) {
  2261.                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  2262.                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  2263.                pixels[i*stride_in_bytes] = (unsigned char) (total / 3);
  2264.             }
  2265.             break;
  2266.          case 4:
  2267.             for (i=0; i <= safe_h; ++i) {
  2268.                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  2269.                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  2270.                pixels[i*stride_in_bytes] = (unsigned char) (total / 4);
  2271.             }
  2272.             break;
  2273.          default:
  2274.             for (i=0; i <= safe_h; ++i) {
  2275.                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  2276.                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  2277.                pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
  2278.             }
  2279.             break;
  2280.       }
  2281.  
  2282.       for (; i < h; ++i) {
  2283.          STBTT_assert(pixels[i*stride_in_bytes] == 0);
  2284.          total -= buffer[i & STBTT__OVER_MASK];
  2285.          pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
  2286.       }
  2287.  
  2288.       pixels += 1;
  2289.    }
  2290. }
  2291.  
  2292. static float stbtt__oversample_shift(int oversample)
  2293. {
  2294.    if (!oversample)
  2295.       return 0.0f;
  2296.  
  2297.    // The prefilter is a box filter of width "oversample",
  2298.    // which shifts phase by (oversample - 1)/2 pixels in
  2299.    // oversampled space. We want to shift in the opposite
  2300.    // direction to counter this.
  2301.    return (float)-(oversample - 1) / (2.0f * (float)oversample);
  2302. }
  2303.  
  2304. int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)
  2305. {
  2306.    stbtt_fontinfo info;
  2307.    float recip_h = 1.0f / spc->h_oversample;
  2308.    float recip_v = 1.0f / spc->v_oversample;
  2309.    float sub_x = stbtt__oversample_shift(spc->h_oversample);
  2310.    float sub_y = stbtt__oversample_shift(spc->v_oversample);
  2311.    int i,j,k,n, return_value = 1;
  2312.    stbrp_context *context = (stbrp_context *) spc->pack_info;
  2313.    stbrp_rect    *rects;
  2314.  
  2315.    // flag all characters as NOT packed
  2316.    for (i=0; i < num_ranges; ++i)
  2317.       for (j=0; j < ranges[i].num_chars_in_range; ++j)
  2318.          ranges[i].chardata_for_range[j].x0 =
  2319.          ranges[i].chardata_for_range[j].y0 =
  2320.          ranges[i].chardata_for_range[j].x1 =
  2321.          ranges[i].chardata_for_range[j].y1 = 0;
  2322.  
  2323.    n = 0;
  2324.    for (i=0; i < num_ranges; ++i)
  2325.       n += ranges[i].num_chars_in_range;
  2326.          
  2327.    rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
  2328.    if (rects == NULL)
  2329.       return 0;
  2330.  
  2331.    stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));
  2332.    k=0;
  2333.    for (i=0; i < num_ranges; ++i) {
  2334.       float fh = ranges[i].font_size;
  2335.       float scale = fh > 0 ? stbtt_ScaleForPixelHeight(&info, fh) : stbtt_ScaleForMappingEmToPixels(&info, -fh);
  2336.       for (j=0; j < ranges[i].num_chars_in_range; ++j) {
  2337.          int x0,y0,x1,y1;
  2338.          stbtt_GetCodepointBitmapBoxSubpixel(&info, ranges[i].first_unicode_char_in_range + j,
  2339.                                               scale * spc->h_oversample,
  2340.                                               scale * spc->v_oversample,
  2341.                                               0,0,
  2342.                                               &x0,&y0,&x1,&y1);
  2343.          rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);
  2344.          rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);
  2345.          ++k;
  2346.       }
  2347.    }
  2348.  
  2349.    stbrp_pack_rects(context, rects, k);
  2350.  
  2351.    k = 0;
  2352.    for (i=0; i < num_ranges; ++i) {
  2353.       float fh = ranges[i].font_size;
  2354.       float scale = fh > 0 ? stbtt_ScaleForPixelHeight(&info, fh) : stbtt_ScaleForMappingEmToPixels(&info, -fh);
  2355.       for (j=0; j < ranges[i].num_chars_in_range; ++j) {
  2356.          stbrp_rect *r = &rects[k];
  2357.          if (r->was_packed) {
  2358.             stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];
  2359.             int advance, lsb, x0,y0,x1,y1;
  2360.             int glyph = stbtt_FindGlyphIndex(&info, ranges[i].first_unicode_char_in_range + j);
  2361.             stbrp_coord pad = (stbrp_coord) spc->padding;
  2362.  
  2363.             // pad on left and top
  2364.             r->x += pad;
  2365.             r->y += pad;
  2366.             r->w -= pad;
  2367.             r->h -= pad;
  2368.             stbtt_GetGlyphHMetrics(&info, glyph, &advance, &lsb);
  2369.             stbtt_GetGlyphBitmapBox(&info, glyph,
  2370.                                     scale * spc->h_oversample,
  2371.                                     scale * spc->v_oversample,
  2372.                                     &x0,&y0,&x1,&y1);
  2373.             stbtt_MakeGlyphBitmapSubpixel(&info,
  2374.                                           spc->pixels + r->x + r->y*spc->stride_in_bytes,
  2375.                                           r->w - spc->h_oversample+1,
  2376.                                           r->h - spc->v_oversample+1,
  2377.                                           spc->stride_in_bytes,
  2378.                                           scale * spc->h_oversample,
  2379.                                           scale * spc->v_oversample,
  2380.                                           0,0,
  2381.                                           glyph);
  2382.  
  2383.             if (spc->h_oversample > 1)
  2384.                stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
  2385.                                   r->w, r->h, spc->stride_in_bytes,
  2386.                                   spc->h_oversample);
  2387.  
  2388.             if (spc->v_oversample > 1)
  2389.                stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
  2390.                                   r->w, r->h, spc->stride_in_bytes,
  2391.                                   spc->v_oversample);
  2392.  
  2393.             bc->x0       = (stbtt_int16)  r->x;
  2394.             bc->y0       = (stbtt_int16)  r->y;
  2395.             bc->x1       = (stbtt_int16) (r->x + r->w);
  2396.             bc->y1       = (stbtt_int16) (r->y + r->h);
  2397.             bc->xadvance =                scale * advance;
  2398.             bc->xoff     =       (float)  x0 * recip_h + sub_x;
  2399.             bc->yoff     =       (float)  y0 * recip_v + sub_y;
  2400.             bc->xoff2    =                (x0 + r->w) * recip_h + sub_x;
  2401.             bc->yoff2    =                (y0 + r->h) * recip_v + sub_y;
  2402.          } else {
  2403.             return_value = 0; // if any fail, report failure
  2404.          }
  2405.  
  2406.          ++k;
  2407.       }
  2408.    }
  2409.    
  2410.    zfree(rects);                ///////////////////////////////
  2411.  
  2412.    return return_value;
  2413. }
  2414.  
  2415. int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size,
  2416.             int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)
  2417. {
  2418.    stbtt_pack_range range;
  2419.    range.first_unicode_char_in_range = first_unicode_char_in_range;
  2420.    range.num_chars_in_range          = num_chars_in_range;
  2421.    range.chardata_for_range          = chardata_for_range;
  2422.    range.font_size                   = font_size;
  2423.    return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
  2424. }
  2425.  
  2426. 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)
  2427. {
  2428.    float ipw = 1.0f / pw, iph = 1.0f / ph;
  2429.    stbtt_packedchar *b = chardata + char_index;
  2430.  
  2431.    if (align_to_integer) {
  2432.       float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5);
  2433.       float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5);
  2434.       q->x0 = x;
  2435.       q->y0 = y;
  2436.       q->x1 = x + b->xoff2 - b->xoff;
  2437.       q->y1 = y + b->yoff2 - b->yoff;
  2438.    } else {
  2439.       q->x0 = *xpos + b->xoff;
  2440.       q->y0 = *ypos + b->yoff;
  2441.       q->x1 = *xpos + b->xoff2;
  2442.       q->y1 = *ypos + b->yoff2;
  2443.    }
  2444.  
  2445.    q->s0 = b->x0 * ipw;
  2446.    q->t0 = b->y0 * iph;
  2447.    q->s1 = b->x1 * ipw;
  2448.    q->t1 = b->y1 * iph;
  2449.  
  2450.    *xpos += b->xadvance;
  2451. }
  2452.  
  2453.  
  2454. //////////////////////////////////////////////////////////////////////////////
  2455. //
  2456. // font name matching -- recommended not to use this
  2457. //
  2458.  
  2459. // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
  2460. static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(const stbtt_uint8 *s1, stbtt_int32 len1, const stbtt_uint8 *s2, stbtt_int32 len2)
  2461. {
  2462.    stbtt_int32 i=0;
  2463.  
  2464.    // convert utf16 to utf8 and compare the results while converting
  2465.    while (len2) {
  2466.       stbtt_uint16 ch = s2[0]*256 + s2[1];
  2467.       if (ch < 0x80) {
  2468.          if (i >= len1) return -1;
  2469.          if (s1[i++] != ch) return -1;
  2470.       } else if (ch < 0x800) {
  2471.          if (i+1 >= len1) return -1;
  2472.          if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
  2473.          if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
  2474.       } else if (ch >= 0xd800 && ch < 0xdc00) {
  2475.          stbtt_uint32 c;
  2476.          stbtt_uint16 ch2 = s2[2]*256 + s2[3];
  2477.          if (i+3 >= len1) return -1;
  2478.          c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
  2479.          if (s1[i++] != 0xf0 + (c >> 18)) return -1;
  2480.          if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
  2481.          if (s1[i++] != 0x80 + ((c >>  6) & 0x3f)) return -1;
  2482.          if (s1[i++] != 0x80 + ((c      ) & 0x3f)) return -1;
  2483.          s2 += 2; // plus another 2 below
  2484.          len2 -= 2;
  2485.       } else if (ch >= 0xdc00 && ch < 0xe000) {
  2486.          return -1;
  2487.       } else {
  2488.          if (i+2 >= len1) return -1;
  2489.          if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
  2490.          if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
  2491.          if (s1[i++] != 0x80 + ((ch     ) & 0x3f)) return -1;
  2492.       }
  2493.       s2 += 2;
  2494.       len2 -= 2;
  2495.    }
  2496.    return i;
  2497. }
  2498.  
  2499. int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
  2500. {
  2501.    return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((const stbtt_uint8*) s1, len1, (const stbtt_uint8*) s2, len2);
  2502. }
  2503.  
  2504. // returns results in whatever encoding you request... but note that 2-byte encodings
  2505. // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
  2506. const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
  2507. {
  2508.    stbtt_int32 i,count,stringOffset;
  2509.    stbtt_uint8 *fc = font->data;
  2510.    stbtt_uint32 offset = font->fontstart;
  2511.    stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
  2512.    if (!nm) return NULL;
  2513.  
  2514.    count = ttUSHORT(fc+nm+2);
  2515.    stringOffset = nm + ttUSHORT(fc+nm+4);
  2516.    for (i=0; i < count; ++i) {
  2517.       stbtt_uint32 loc = nm + 6 + 12 * i;
  2518.       if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
  2519.           && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
  2520.          *length = ttUSHORT(fc+loc+8);
  2521.          return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
  2522.       }
  2523.    }
  2524.    return NULL;
  2525. }
  2526.  
  2527. static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
  2528. {
  2529.    stbtt_int32 i;
  2530.    stbtt_int32 count = ttUSHORT(fc+nm+2);
  2531.    stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
  2532.  
  2533.    for (i=0; i < count; ++i) {
  2534.       stbtt_uint32 loc = nm + 6 + 12 * i;
  2535.       stbtt_int32 id = ttUSHORT(fc+loc+6);
  2536.       if (id == target_id) {
  2537.          // find the encoding
  2538.          stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
  2539.  
  2540.          // is this a Unicode encoding?
  2541.          if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
  2542.             stbtt_int32 slen = ttUSHORT(fc+loc+8);
  2543.             stbtt_int32 off = ttUSHORT(fc+loc+10);
  2544.  
  2545.             // check if there's a prefix match
  2546.             stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
  2547.             if (matchlen >= 0) {
  2548.                // check for target_id+1 immediately following, with same encoding & language
  2549.                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) {
  2550.                   slen = ttUSHORT(fc+loc+12+8);
  2551.                   off = ttUSHORT(fc+loc+12+10);
  2552.                   if (slen == 0) {
  2553.                      if (matchlen == nlen)
  2554.                         return 1;
  2555.                   } else if (matchlen < nlen && name[matchlen] == ' ') {
  2556.                      ++matchlen;
  2557.                      if (stbtt_CompareUTF8toUTF16_bigendian((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
  2558.                         return 1;
  2559.                   }
  2560.                } else {
  2561.                   // if nothing immediately following
  2562.                   if (matchlen == nlen)
  2563.                      return 1;
  2564.                }
  2565.             }
  2566.          }
  2567.  
  2568.          // @TODO handle other encodings
  2569.       }
  2570.    }
  2571.    return 0;
  2572. }
  2573.  
  2574. static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
  2575. {
  2576.    stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
  2577.    stbtt_uint32 nm,hd;
  2578.    if (!stbtt__isfont(fc+offset)) return 0;
  2579.  
  2580.    // check italics/bold/underline flags in macStyle...
  2581.    if (flags) {
  2582.       hd = stbtt__find_table(fc, offset, "head");
  2583.       if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
  2584.    }
  2585.  
  2586.    nm = stbtt__find_table(fc, offset, "name");
  2587.    if (!nm) return 0;
  2588.  
  2589.    if (flags) {
  2590.       // if we checked the macStyle flags, then just check the family and ignore the subfamily
  2591.       if (stbtt__matchpair(fc, nm, name, nlen, 16, -1))  return 1;
  2592.       if (stbtt__matchpair(fc, nm, name, nlen,  1, -1))  return 1;
  2593.       if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;
  2594.    } else {
  2595.       if (stbtt__matchpair(fc, nm, name, nlen, 16, 17))  return 1;
  2596.       if (stbtt__matchpair(fc, nm, name, nlen,  1,  2))  return 1;
  2597.       if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;
  2598.    }
  2599.  
  2600.    return 0;
  2601. }
  2602.  
  2603. int stbtt_FindMatchingFont(const unsigned char *font_collection, const char *name_utf8, stbtt_int32 flags)
  2604. {
  2605.    stbtt_int32 i;
  2606.    for (i=0;;++i) {
  2607.       stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
  2608.       if (off < 0) return off;
  2609.       if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
  2610.          return off;
  2611.    }
  2612. }
  2613.  
  2614. #endif // STB_TRUETYPE_IMPLEMENTATION
  2615.