Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

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