~rebel/horde3d/trunk

« back to all changes in this revision

Viewing changes to trunk/Tools/Dependencies/RecastNavigation/RecastDemo/Contrib/stb_truetype.h

  • Committer: felix
  • Date: 2015-07-07 12:57:07 UTC
  • Revision ID: svn-v4:5ce291ac-9df0-446f-9e4f-d57731c4dda7::1699
- Updated RecastNavigation to latest version and fixed multiple issues.
- Adapted GameDetourComponent, GameDetourCrowdComponent, DetourCrowdDemo and AAA accordingly.

Show diffs side-by-side

added added

removed removed

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