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