1 // stb_truetype.h - v1.14 - public domain
2 // authored from 2009-2016 by Sean Barrett / RAD Game Tools
4 // This library processes TrueType files:
6 // extract glyph metrics
7 // extract glyph shapes
8 // render glyphs to one-channel bitmaps with antialiasing (box filter)
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?
19 // ADDITIONAL CONTRIBUTORS
21 // Mikko Mononen: compound shape support, more cmap formats
22 // Tor Andersson: kerning, subpixel rendering
23 // Dougall Johnson: OpenType / Type 2 font handling
28 // github:IntellectualKitty
30 // Bug/warning reports/fixes:
31 // "Zer" on mollyrocket (with fix)
33 // stoiko (Haemimont Games)
42 // Fabian "ryg" Giesen
56 // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts, num-fonts-in-TTC function
57 // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
58 // 1.11 (2016-04-02) fix unused-variable warning
59 // 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef
60 // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly
61 // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
62 // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
63 // variant PackFontRanges to pack and render in separate phases;
64 // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
65 // fixed an assert() bug in the new rasterizer
66 // replace assert() with STBTT_assert() in new rasterizer
68 // Full history can be found at the end of this file.
72 // This software is dual-licensed to the public domain and under the following
73 // license: you are granted a perpetual, irrevocable license to copy, modify,
74 // publish, and distribute this file as you see fit.
78 // Include this file in whatever places neeed to refer to it. In ONE C/C++
80 // #define STB_TRUETYPE_IMPLEMENTATION
81 // before the #include of this file. This expands out the actual
82 // implementation into that C/C++ file.
84 // To make the implementation private to the file that generates the implementation,
85 // #define STBTT_STATIC
87 // Simple 3D API (don't ship this, but it's fine for tools and quick start)
88 // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture
89 // stbtt_GetBakedQuad() -- compute quad to draw for a given char
91 // Improved 3D API (more shippable):
92 // #include "stb_rect_pack.h" -- optional, but you really want it
94 // stbtt_PackSetOversample() -- for improved quality on small fonts
95 // stbtt_PackFontRanges() -- pack and renders
97 // stbtt_GetPackedQuad()
99 // "Load" a font file from a memory buffer (you have to keep the buffer loaded)
101 // stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections
102 // stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections
104 // Render a unicode codepoint to a bitmap
105 // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
106 // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide
107 // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
109 // Character advance/positioning
110 // stbtt_GetCodepointHMetrics()
111 // stbtt_GetFontVMetrics()
112 // stbtt_GetCodepointKernAdvance()
114 // Starting with version 1.06, the rasterizer was replaced with a new,
115 // faster and generally-more-precise rasterizer. The new rasterizer more
116 // accurately measures pixel coverage for anti-aliasing, except in the case
117 // where multiple shapes overlap, in which case it overestimates the AA pixel
118 // coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If
119 // this turns out to be a problem, you can re-enable the old rasterizer with
120 // #define STBTT_RASTERIZER_VERSION 1
121 // which will incur about a 15% speed hit.
123 // ADDITIONAL DOCUMENTATION
125 // Immediately after this block comment are a series of sample programs.
127 // After the sample programs is the "header file" section. This section
128 // includes documentation for each API function.
130 // Some important concepts to understand to use this library:
133 // Characters are defined by unicode codepoints, e.g. 65 is
134 // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
135 // the hiragana for "ma".
138 // A visual character shape (every codepoint is rendered as
142 // A font-specific integer ID representing a glyph
145 // Glyph shapes are defined relative to a baseline, which is the
146 // bottom of uppercase characters. Characters extend both above
147 // and below the baseline.
150 // As you draw text to the screen, you keep track of a "current point"
151 // which is the origin of each character. The current point's vertical
152 // position is the baseline. Even "baked fonts" use this model.
154 // Vertical Font Metrics
155 // The vertical qualities of the font, used to vertically position
156 // and space the characters. See docs for stbtt_GetFontVMetrics.
158 // Font Size in Pixels or Points
159 // The preferred interface for specifying font sizes in stb_truetype
160 // is to specify how tall the font's vertical extent should be in pixels.
161 // If that sounds good enough, skip the next paragraph.
163 // Most font APIs instead use "points", which are a common typographic
164 // measurement for describing font size, defined as 72 points per inch.
165 // stb_truetype provides a point API for compatibility. However, true
166 // "per inch" conventions don't make much sense on computer displays
167 // since they different monitors have different number of pixels per
168 // inch. For example, Windows traditionally uses a convention that
169 // there are 96 pixels per inch, thus making 'inch' measurements have
170 // nothing to do with inches, and thus effectively defining a point to
171 // be 1.333 pixels. Additionally, the TrueType font data provides
172 // an explicit scale factor to scale a given font's glyphs to points,
173 // but the author has observed that this scale factor is often wrong
174 // for non-commercial fonts, thus making fonts scaled in points
175 // according to the TrueType spec incoherently sized in practice.
181 // - Use the functions with Subpixel at the end to allow your characters
182 // to have subpixel positioning. Since the font is anti-aliased, not
183 // hinted, this is very import for quality. (This is not possible with
186 // - Kerning is now supported, and if you're supporting subpixel rendering
187 // then kerning is worth using to give your text a polished look.
191 // - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
192 // if you don't do this, stb_truetype is forced to do the conversion on
195 // - There are a lot of memory allocations. We should modify it to take
196 // a temp buffer and allocate from the temp buffer (without freeing),
197 // should help performance a lot.
201 // The system uses the raw data found in the .ttf file without changing it
202 // and without building auxiliary data structures. This is a bit inefficient
203 // on little-endian systems (the data is big-endian), but assuming you're
204 // caching the bitmaps or glyph shapes this shouldn't be a big deal.
206 // It appears to be very hard to programmatically determine what font a
207 // given file is in a general way. I provide an API for this, but I don't
211 // SOURCE STATISTICS (based on v0.6c, 2050 LOC)
213 // Documentation & header file 520 LOC \___ 660 LOC documentation
214 // Sample code 140 LOC /
215 // Truetype parsing 620 LOC ---- 620 LOC TrueType
216 // Software rasterization 240 LOC \ .
217 // Curve tesselation 120 LOC \__ 550 LOC Bitmap creation
218 // Bitmap management 100 LOC /
219 // Baked bitmap interface 70 LOC /
220 // Font name matching & access 150 LOC ---- 150
221 // C runtime library abstraction 60 LOC ---- 60
224 // PERFORMANCE MEASUREMENTS FOR 1.06:
227 // Previous release: 8.83 s 7.68 s
228 // Pool allocations: 7.72 s 6.34 s
229 // Inline sort : 6.54 s 5.65 s
230 // New rasterizer : 5.63 s 5.00 s
232 //////////////////////////////////////////////////////////////////////////////
233 //////////////////////////////////////////////////////////////////////////////
238 // Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
241 #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
242 #include "stb_truetype.h"
244 unsigned char ttf_buffer
[1<<20];
245 unsigned char temp_bitmap
[512*512];
247 stbtt_bakedchar cdata
[96]; // ASCII 32..126 is 95 glyphs
250 void my_stbtt_initfont(void)
252 fread(ttf_buffer
, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
253 stbtt_BakeFontBitmap(ttf_buffer
,0, 32.0, temp_bitmap
,512,512, 32,96, cdata
); // no guarantee this fits!
254 // can free ttf_buffer at this point
255 glGenTextures(1, &ftex
);
256 glBindTexture(GL_TEXTURE_2D
, ftex
);
257 glTexImage2D(GL_TEXTURE_2D
, 0, GL_ALPHA
, 512,512, 0, GL_ALPHA
, GL_UNSIGNED_BYTE
, temp_bitmap
);
258 // can free temp_bitmap at this point
259 glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
);
262 void my_stbtt_print(float x
, float y
, char *text
)
264 // assume orthographic projection with units = screen pixels, origin at top left
265 glEnable(GL_TEXTURE_2D
);
266 glBindTexture(GL_TEXTURE_2D
, ftex
);
269 if (*text
>= 32 && *text
< 128) {
270 stbtt_aligned_quad q
;
271 stbtt_GetBakedQuad(cdata
, 512,512, *text
-32, &x
,&y
,&q
,1);//1=opengl & d3d10+,0=d3d9
272 glTexCoord2f(q
.s0
,q
.t1
); glVertex2f(q
.x0
,q
.y0
);
273 glTexCoord2f(q
.s1
,q
.t1
); glVertex2f(q
.x1
,q
.y0
);
274 glTexCoord2f(q
.s1
,q
.t0
); glVertex2f(q
.x1
,q
.y1
);
275 glTexCoord2f(q
.s0
,q
.t0
); glVertex2f(q
.x0
,q
.y1
);
284 //////////////////////////////////////////////////////////////////////////////
286 // Complete program (this compiles): get a single bitmap, print as ASCII art
290 #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
291 #include "stb_truetype.h"
293 char ttf_buffer
[1<<25];
295 int main(int argc
, char **argv
)
298 unsigned char *bitmap
;
299 int w
,h
,i
,j
,c
= (argc
> 1 ? atoi(argv
[1]) : 'a'), s
= (argc
> 2 ? atoi(argv
[2]) : 20);
301 fread(ttf_buffer
, 1, 1<<25, fopen(argc
> 3 ? argv
[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
303 stbtt_InitFont(&font
, ttf_buffer
, stbtt_GetFontOffsetForIndex(ttf_buffer
,0));
304 bitmap
= stbtt_GetCodepointBitmap(&font
, 0,stbtt_ScaleForPixelHeight(&font
, s
), c
, &w
, &h
, 0,0);
306 for (j
=0; j
< h
; ++j
) {
307 for (i
=0; i
< w
; ++i
)
308 putchar(" .:ioVM@"[bitmap
[j
*w
+i
]>>5]);
328 //////////////////////////////////////////////////////////////////////////////
330 // Complete program: print "Hello World!" banner, with bugs
334 unsigned char screen
[20][79];
336 int main(int arg
, char **argv
)
339 int i
,j
,ascent
,baseline
,ch
=0;
340 float scale
, xpos
=2; // leave a little padding in case the character extends left
341 char *text
= "Heljo World!"; // intentionally misspelled to show 'lj' brokenness
343 fread(buffer
, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
344 stbtt_InitFont(&font
, buffer
, 0);
346 scale
= stbtt_ScaleForPixelHeight(&font
, 15);
347 stbtt_GetFontVMetrics(&font
, &ascent
,0,0);
348 baseline
= (int) (ascent
*scale
);
351 int advance
,lsb
,x0
,y0
,x1
,y1
;
352 float x_shift
= xpos
- (float) floor(xpos
);
353 stbtt_GetCodepointHMetrics(&font
, text
[ch
], &advance
, &lsb
);
354 stbtt_GetCodepointBitmapBoxSubpixel(&font
, text
[ch
], scale
,scale
,x_shift
,0, &x0
,&y0
,&x1
,&y1
);
355 stbtt_MakeCodepointBitmapSubpixel(&font
, &screen
[baseline
+ y0
][(int) xpos
+ x0
], x1
-x0
,y1
-y0
, 79, scale
,scale
,x_shift
,0, text
[ch
]);
356 // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
357 // because this API is really for baking character bitmaps into textures. if you want to render
358 // a sequence of characters, you really need to render each bitmap to a temp buffer, then
359 // "alpha blend" that into the working buffer
360 xpos
+= (advance
* scale
);
362 xpos
+= scale
*stbtt_GetCodepointKernAdvance(&font
, text
[ch
],text
[ch
+1]);
366 for (j
=0; j
< 20; ++j
) {
367 for (i
=0; i
< 78; ++i
)
368 putchar(" .:ioVM@"[screen
[j
][i
]>>5]);
377 //////////////////////////////////////////////////////////////////////////////
378 //////////////////////////////////////////////////////////////////////////////
380 //// INTEGRATION WITH YOUR CODEBASE
382 //// The following sections allow you to supply alternate definitions
383 //// of C library functions used by stb_truetype.
385 #ifdef STB_TRUETYPE_IMPLEMENTATION
386 // #define your own (u)stbtt_int8/16/32 before including to override this
388 typedef unsigned char stbtt_uint8
;
389 typedef signed char stbtt_int8
;
390 typedef unsigned short stbtt_uint16
;
391 typedef signed short stbtt_int16
;
392 typedef unsigned int stbtt_uint32
;
393 typedef signed int stbtt_int32
;
396 typedef char stbtt__check_size32
[sizeof(stbtt_int32
)==4 ? 1 : -1];
397 typedef char stbtt__check_size16
[sizeof(stbtt_int16
)==2 ? 1 : -1];
399 // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
402 #define STBTT_ifloor(x) ((int) floor(x))
403 #define STBTT_iceil(x) ((int) ceil(x))
408 #define STBTT_sqrt(x) sqrt(x)
413 #define STBTT_fabs(x) fabs(x)
416 // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
419 #define STBTT_malloc(x,u) ((void)(u),malloc(x))
420 #define STBTT_free(x,u) ((void)(u),free(x))
425 #define STBTT_assert(x) assert(x)
430 #define STBTT_strlen(x) strlen(x)
435 #define STBTT_memcpy memcpy
436 #define STBTT_memset memset
440 ///////////////////////////////////////////////////////////////////////////////
441 ///////////////////////////////////////////////////////////////////////////////
447 #ifndef __STB_INCLUDE_STB_TRUETYPE_H__
448 #define __STB_INCLUDE_STB_TRUETYPE_H__
451 #define STBTT_DEF static
453 #define STBTT_DEF extern
468 //////////////////////////////////////////////////////////////////////////////
470 // TEXTURE BAKING API
472 // If you use this API, you only have to call two functions ever.
477 unsigned short x0
,y0
,x1
,y1
; // coordinates of bbox in bitmap
478 float xoff
,yoff
,xadvance
;
481 STBTT_DEF
int stbtt_BakeFontBitmap(const unsigned char *data
, int offset
, // font location (use offset=0 for plain .ttf)
482 float pixel_height
, // height of font in pixels
483 unsigned char *pixels
, int pw
, int ph
, // bitmap to be filled in
484 int first_char
, int num_chars
, // characters to bake
485 stbtt_bakedchar
*chardata
); // you allocate this, it's num_chars long
486 // if return is positive, the first unused row of the bitmap
487 // if return is negative, returns the negative of the number of characters that fit
488 // if return is 0, no characters fit and no rows were used
489 // This uses a very crappy packing.
493 float x0
,y0
,s0
,t0
; // top-left
494 float x1
,y1
,s1
,t1
; // bottom-right
495 } stbtt_aligned_quad
;
497 STBTT_DEF
void stbtt_GetBakedQuad(stbtt_bakedchar
*chardata
, int pw
, int ph
, // same data as above
498 int char_index
, // character to display
499 float *xpos
, float *ypos
, // pointers to current position in screen pixel space
500 stbtt_aligned_quad
*q
, // output: quad to draw
501 int opengl_fillrule
); // true if opengl fill rule; false if DX9 or earlier
502 // Call GetBakedQuad with char_index = 'character - first_char', and it
503 // creates the quad you need to draw and advances the current position.
505 // The coordinate system used assumes y increases downwards.
507 // Characters will extend both above and below the current position;
508 // see discussion of "BASELINE" above.
510 // It's inefficient; you might want to c&p it and optimize it.
514 //////////////////////////////////////////////////////////////////////////////
516 // NEW TEXTURE BAKING API
518 // This provides options for packing multiple fonts into one atlas, not
519 // perfectly but better than nothing.
523 unsigned short x0
,y0
,x1
,y1
; // coordinates of bbox in bitmap
524 float xoff
,yoff
,xadvance
;
528 typedef struct stbtt_pack_context stbtt_pack_context
;
529 typedef struct stbtt_fontinfo stbtt_fontinfo
;
530 #ifndef STB_RECT_PACK_VERSION
531 typedef struct stbrp_rect stbrp_rect
;
534 STBTT_DEF
int stbtt_PackBegin(stbtt_pack_context
*spc
, unsigned char *pixels
, int width
, int height
, int stride_in_bytes
, int padding
, void *alloc_context
);
535 // Initializes a packing context stored in the passed-in stbtt_pack_context.
536 // Future calls using this context will pack characters into the bitmap passed
537 // in here: a 1-channel bitmap that is width * height. stride_in_bytes is
538 // the distance from one row to the next (or 0 to mean they are packed tightly
539 // together). "padding" is the amount of padding to leave between each
540 // character (normally you want '1' for bitmaps you'll use as textures with
541 // bilinear filtering).
543 // Returns 0 on failure, 1 on success.
545 STBTT_DEF
void stbtt_PackEnd (stbtt_pack_context
*spc
);
546 // Cleans up the packing context and frees all memory.
548 #define STBTT_POINT_SIZE(x) (-(x))
550 STBTT_DEF
int stbtt_PackFontRange(stbtt_pack_context
*spc
, unsigned char *fontdata
, int font_index
, float font_size
,
551 int first_unicode_char_in_range
, int num_chars_in_range
, stbtt_packedchar
*chardata_for_range
);
552 // Creates character bitmaps from the font_index'th font found in fontdata (use
553 // font_index=0 if you don't know what that is). It creates num_chars_in_range
554 // bitmaps for characters with unicode values starting at first_unicode_char_in_range
555 // and increasing. Data for how to render them is stored in chardata_for_range;
556 // pass these to stbtt_GetPackedQuad to get back renderable quads.
558 // font_size is the full height of the character from ascender to descender,
559 // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed
560 // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()
561 // and pass that result as 'font_size':
562 // ..., 20 , ... // font max minus min y is 20 pixels tall
563 // ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall
568 int first_unicode_codepoint_in_range
; // if non-zero, then the chars are continuous, and this is the first codepoint
569 int *array_of_unicode_codepoints
; // if non-zero, then this is an array of unicode codepoints
571 stbtt_packedchar
*chardata_for_range
; // output
572 unsigned char h_oversample
, v_oversample
; // don't set these, they're used internally
575 STBTT_DEF
int stbtt_PackFontRanges(stbtt_pack_context
*spc
, unsigned char *fontdata
, int font_index
, stbtt_pack_range
*ranges
, int num_ranges
);
576 // Creates character bitmaps from multiple ranges of characters stored in
577 // ranges. This will usually create a better-packed bitmap than multiple
578 // calls to stbtt_PackFontRange. Note that you can call this multiple
579 // times within a single PackBegin/PackEnd.
581 STBTT_DEF
void stbtt_PackSetOversampling(stbtt_pack_context
*spc
, unsigned int h_oversample
, unsigned int v_oversample
);
582 // Oversampling a font increases the quality by allowing higher-quality subpixel
583 // positioning, and is especially valuable at smaller text sizes.
585 // This function sets the amount of oversampling for all following calls to
586 // stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given
587 // pack context. The default (no oversampling) is achieved by h_oversample=1
588 // and v_oversample=1. The total number of pixels required is
589 // h_oversample*v_oversample larger than the default; for example, 2x2
590 // oversampling requires 4x the storage of 1x1. For best results, render
591 // oversampled textures with bilinear filtering. Look at the readme in
592 // stb/tests/oversample for information about oversampled fonts
594 // To use with PackFontRangesGather etc., you must set it before calls
595 // call to PackFontRangesGatherRects.
597 STBTT_DEF
void stbtt_GetPackedQuad(stbtt_packedchar
*chardata
, int pw
, int ph
, // same data as above
598 int char_index
, // character to display
599 float *xpos
, float *ypos
, // pointers to current position in screen pixel space
600 stbtt_aligned_quad
*q
, // output: quad to draw
601 int align_to_integer
);
603 STBTT_DEF
int stbtt_PackFontRangesGatherRects(stbtt_pack_context
*spc
, const stbtt_fontinfo
*info
, stbtt_pack_range
*ranges
, int num_ranges
, stbrp_rect
*rects
);
604 STBTT_DEF
void stbtt_PackFontRangesPackRects(stbtt_pack_context
*spc
, stbrp_rect
*rects
, int num_rects
);
605 STBTT_DEF
int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context
*spc
, const stbtt_fontinfo
*info
, stbtt_pack_range
*ranges
, int num_ranges
, stbrp_rect
*rects
);
606 // Calling these functions in sequence is roughly equivalent to calling
607 // stbtt_PackFontRanges(). If you more control over the packing of multiple
608 // fonts, or if you want to pack custom data into a font texture, take a look
609 // at the source to of stbtt_PackFontRanges() and create a custom version
610 // using these functions, e.g. call GatherRects multiple times,
611 // building up a single array of rects, then call PackRects once,
612 // then call RenderIntoRects repeatedly. This may result in a
613 // better packing than calling PackFontRanges multiple times
616 // this is an opaque structure that you shouldn't mess with which holds
617 // all the context needed from PackBegin to PackEnd.
618 struct stbtt_pack_context
{
619 void *user_allocator_context
;
625 unsigned int h_oversample
, v_oversample
;
626 unsigned char *pixels
;
630 //////////////////////////////////////////////////////////////////////////////
636 STBTT_DEF
int stbtt_GetNumberOfFonts(const unsigned char *data
);
637 // This function will determine the number of fonts in a font file. TrueType
638 // collection (.ttc) files may contain multiple fonts, while TrueType font
639 // (.ttf) files only contain one font. The number of fonts can be used for
640 // indexing with the previous function where the index is between zero and one
641 // less than the total fonts. If an error occurs, -1 is returned.
643 STBTT_DEF
int stbtt_GetFontOffsetForIndex(const unsigned char *data
, int index
);
644 // Each .ttf/.ttc file may have more than one font. Each font has a sequential
645 // index number starting from 0. Call this function to get the font offset for
646 // a given index; it returns -1 if the index is out of range. A regular .ttf
647 // file will only define one font and it always be at offset 0, so it will
648 // return '0' for index 0, and -1 for all other indices.
650 // The following structure is defined publically so you can declare one on
651 // the stack or as a global or etc, but you should treat it as opaque.
652 struct stbtt_fontinfo
655 unsigned char * data
; // pointer to .ttf file
656 int fontstart
; // offset of start of font
658 int numGlyphs
; // number of glyphs, needed for range checking
660 int loca
,head
,glyf
,hhea
,hmtx
,kern
; // table locations as offset from start of .ttf
661 int index_map
; // a cmap mapping for our chosen character encoding
662 int indexToLocFormat
; // format needed to map from glyph index to glyph
664 stbtt__buf cff
; // cff font data
665 stbtt__buf charstrings
; // the charstring index
666 stbtt__buf gsubrs
; // global charstring subroutines index
667 stbtt__buf subrs
; // private charstring subroutines index
668 stbtt__buf fontdicts
; // array of font dicts
669 stbtt__buf fdselect
; // map from glyph to fontdict
672 STBTT_DEF
int stbtt_InitFont(stbtt_fontinfo
*info
, const unsigned char *data
, int offset
);
673 // Given an offset into the file that defines a font, this function builds
674 // the necessary cached info for the rest of the system. You must allocate
675 // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
676 // need to do anything special to free it, because the contents are pure
677 // value data with no additional data structures. Returns 0 on failure.
680 //////////////////////////////////////////////////////////////////////////////
682 // CHARACTER TO GLYPH-INDEX CONVERSIOn
684 STBTT_DEF
int stbtt_FindGlyphIndex(const stbtt_fontinfo
*info
, int unicode_codepoint
);
685 // If you're going to perform multiple operations on the same character
686 // and you want a speed-up, call this function with the character you're
687 // going to process, then use glyph-based functions instead of the
688 // codepoint-based functions.
691 //////////////////////////////////////////////////////////////////////////////
693 // CHARACTER PROPERTIES
696 STBTT_DEF
float stbtt_ScaleForPixelHeight(const stbtt_fontinfo
*info
, float pixels
);
697 // computes a scale factor to produce a font whose "height" is 'pixels' tall.
698 // Height is measured as the distance from the highest ascender to the lowest
699 // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
701 // scale = pixels / (ascent - descent)
702 // so if you prefer to measure height by the ascent only, use a similar calculation.
704 STBTT_DEF
float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo
*info
, float pixels
);
705 // computes a scale factor to produce a font whose EM size is mapped to
706 // 'pixels' tall. This is probably what traditional APIs compute, but
709 STBTT_DEF
void stbtt_GetFontVMetrics(const stbtt_fontinfo
*info
, int *ascent
, int *descent
, int *lineGap
);
710 // ascent is the coordinate above the baseline the font extends; descent
711 // is the coordinate below the baseline the font extends (i.e. it is typically negative)
712 // lineGap is the spacing between one row's descent and the next row's ascent...
713 // so you should advance the vertical position by "*ascent - *descent + *lineGap"
714 // these are expressed in unscaled coordinates, so you must multiply by
715 // the scale factor for a given size
717 STBTT_DEF
void stbtt_GetFontBoundingBox(const stbtt_fontinfo
*info
, int *x0
, int *y0
, int *x1
, int *y1
);
718 // the bounding box around all possible characters
720 STBTT_DEF
void stbtt_GetCodepointHMetrics(const stbtt_fontinfo
*info
, int codepoint
, int *advanceWidth
, int *leftSideBearing
);
721 // leftSideBearing is the offset from the current horizontal position to the left edge of the character
722 // advanceWidth is the offset from the current horizontal position to the next horizontal position
723 // these are expressed in unscaled coordinates
725 STBTT_DEF
int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo
*info
, int ch1
, int ch2
);
726 // an additional amount to add to the 'advance' value between ch1 and ch2
728 STBTT_DEF
int stbtt_GetCodepointBox(const stbtt_fontinfo
*info
, int codepoint
, int *x0
, int *y0
, int *x1
, int *y1
);
729 // Gets the bounding box of the visible part of the glyph, in unscaled coordinates
731 STBTT_DEF
void stbtt_GetGlyphHMetrics(const stbtt_fontinfo
*info
, int glyph_index
, int *advanceWidth
, int *leftSideBearing
);
732 STBTT_DEF
int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo
*info
, int glyph1
, int glyph2
);
733 STBTT_DEF
int stbtt_GetGlyphBox(const stbtt_fontinfo
*info
, int glyph_index
, int *x0
, int *y0
, int *x1
, int *y1
);
734 // as above, but takes one or more glyph indices for greater efficiency
737 //////////////////////////////////////////////////////////////////////////////
739 // GLYPH SHAPES (you probably don't need these, but they have to go before
740 // the bitmaps for C declaration-order reasons)
743 #ifndef STBTT_vmove // you can predefine these to use different values (but why?)
752 #ifndef stbtt_vertex // you can predefine this to use different values
753 // (we share this with other code at RAD)
754 #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
757 stbtt_vertex_type x
,y
,cx
,cy
,cx1
,cy1
;
758 unsigned char type
,padding
;
762 STBTT_DEF
int stbtt_IsGlyphEmpty(const stbtt_fontinfo
*info
, int glyph_index
);
763 // returns non-zero if nothing is drawn for this glyph
765 STBTT_DEF
int stbtt_GetCodepointShape(const stbtt_fontinfo
*info
, int unicode_codepoint
, stbtt_vertex
**vertices
);
766 STBTT_DEF
int stbtt_GetGlyphShape(const stbtt_fontinfo
*info
, int glyph_index
, stbtt_vertex
**vertices
);
767 // returns # of vertices and fills *vertices with the pointer to them
768 // these are expressed in "unscaled" coordinates
770 // The shape is a series of countours. Each one starts with
771 // a STBTT_moveto, then consists of a series of mixed
772 // STBTT_lineto and STBTT_curveto segments. A lineto
773 // draws a line from previous endpoint to its x,y; a curveto
774 // draws a quadratic bezier from previous endpoint to
775 // its x,y, using cx,cy as the bezier control point.
777 STBTT_DEF
void stbtt_FreeShape(const stbtt_fontinfo
*info
, stbtt_vertex
*vertices
);
778 // frees the data allocated above
780 //////////////////////////////////////////////////////////////////////////////
785 STBTT_DEF
void stbtt_FreeBitmap(unsigned char *bitmap
, void *userdata
);
786 // frees the bitmap allocated below
788 STBTT_DEF
unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo
*info
, float scale_x
, float scale_y
, int codepoint
, int *width
, int *height
, int *xoff
, int *yoff
);
789 // allocates a large-enough single-channel 8bpp bitmap and renders the
790 // specified character/glyph at the specified scale into it, with
791 // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
792 // *width & *height are filled out with the width & height of the bitmap,
793 // which is stored left-to-right, top-to-bottom.
795 // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
797 STBTT_DEF
unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo
*info
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int codepoint
, int *width
, int *height
, int *xoff
, int *yoff
);
798 // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
799 // shift for the character
801 STBTT_DEF
void stbtt_MakeCodepointBitmap(const stbtt_fontinfo
*info
, unsigned char *output
, int out_w
, int out_h
, int out_stride
, float scale_x
, float scale_y
, int codepoint
);
802 // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
803 // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
804 // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
805 // width and height and positioning info for it first.
807 STBTT_DEF
void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo
*info
, unsigned char *output
, int out_w
, int out_h
, int out_stride
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int codepoint
);
808 // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
809 // shift for the character
811 STBTT_DEF
void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo
*font
, int codepoint
, float scale_x
, float scale_y
, int *ix0
, int *iy0
, int *ix1
, int *iy1
);
812 // get the bbox of the bitmap centered around the glyph origin; so the
813 // bitmap width is ix1-ix0, height is iy1-iy0, and location to place
814 // the bitmap top left is (leftSideBearing*scale,iy0).
815 // (Note that the bitmap uses y-increases-down, but the shape uses
816 // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
818 STBTT_DEF
void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo
*font
, int codepoint
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int *ix0
, int *iy0
, int *ix1
, int *iy1
);
819 // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
820 // shift for the character
822 // the following functions are equivalent to the above functions, but operate
823 // on glyph indices instead of Unicode codepoints (for efficiency)
824 STBTT_DEF
unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo
*info
, float scale_x
, float scale_y
, int glyph
, int *width
, int *height
, int *xoff
, int *yoff
);
825 STBTT_DEF
unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo
*info
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int glyph
, int *width
, int *height
, int *xoff
, int *yoff
);
826 STBTT_DEF
void stbtt_MakeGlyphBitmap(const stbtt_fontinfo
*info
, unsigned char *output
, int out_w
, int out_h
, int out_stride
, float scale_x
, float scale_y
, int glyph
);
827 STBTT_DEF
void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo
*info
, unsigned char *output
, int out_w
, int out_h
, int out_stride
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int glyph
);
828 STBTT_DEF
void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo
*font
, int glyph
, float scale_x
, float scale_y
, int *ix0
, int *iy0
, int *ix1
, int *iy1
);
829 STBTT_DEF
void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo
*font
, int glyph
, float scale_x
, float scale_y
,float shift_x
, float shift_y
, int *ix0
, int *iy0
, int *ix1
, int *iy1
);
832 // @TODO: don't expose this structure
836 unsigned char *pixels
;
839 // rasterize a shape with quadratic beziers into a bitmap
840 STBTT_DEF
void stbtt_Rasterize(stbtt__bitmap
*result
, // 1-channel bitmap to draw into
841 float flatness_in_pixels
, // allowable error of curve in pixels
842 stbtt_vertex
*vertices
, // array of vertices defining shape
843 int num_verts
, // number of vertices in above array
844 float scale_x
, float scale_y
, // scale applied to input vertices
845 float shift_x
, float shift_y
, // translation applied to input vertices
846 int x_off
, int y_off
, // another translation applied to input
847 int invert
, // if non-zero, vertically flip shape
848 void *userdata
); // context for to STBTT_MALLOC
850 //////////////////////////////////////////////////////////////////////////////
852 // Finding the right font...
854 // You should really just solve this offline, keep your own tables
855 // of what font is what, and don't try to get it out of the .ttf file.
856 // That's because getting it out of the .ttf file is really hard, because
857 // the names in the file can appear in many possible encodings, in many
858 // possible languages, and e.g. if you need a case-insensitive comparison,
859 // the details of that depend on the encoding & language in a complex way
860 // (actually underspecified in truetype, but also gigantic).
862 // But you can use the provided functions in two possible ways:
863 // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
864 // unicode-encoded names to try to find the font you want;
865 // you can run this before calling stbtt_InitFont()
867 // stbtt_GetFontNameString() lets you get any of the various strings
868 // from the file yourself and do your own comparisons on them.
869 // You have to have called stbtt_InitFont() first.
872 STBTT_DEF
int stbtt_FindMatchingFont(const unsigned char *fontdata
, const char *name
, int flags
);
873 // returns the offset (not index) of the font that matches, or -1 if none
874 // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
875 // if you use any other flag, use a font name like "Arial"; this checks
876 // the 'macStyle' header field; i don't know if fonts set this consistently
877 #define STBTT_MACSTYLE_DONTCARE 0
878 #define STBTT_MACSTYLE_BOLD 1
879 #define STBTT_MACSTYLE_ITALIC 2
880 #define STBTT_MACSTYLE_UNDERSCORE 4
881 #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0
883 STBTT_DEF
int stbtt_CompareUTF8toUTF16_bigendian(const char *s1
, int len1
, const char *s2
, int len2
);
884 // returns 1/0 whether the first string interpreted as utf8 is identical to
885 // the second string interpreted as big-endian utf16... useful for strings from next func
887 STBTT_DEF
const char *stbtt_GetFontNameString(const stbtt_fontinfo
*font
, int *length
, int platformID
, int encodingID
, int languageID
, int nameID
);
888 // returns the string (which may be big-endian double byte, e.g. for unicode)
889 // and puts the length in bytes in *length.
891 // some of the values for the IDs are below; for more see the truetype spec:
892 // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
893 // http://www.microsoft.com/typography/otspec/name.htm
896 STBTT_PLATFORM_ID_UNICODE
=0,
897 STBTT_PLATFORM_ID_MAC
=1,
898 STBTT_PLATFORM_ID_ISO
=2,
899 STBTT_PLATFORM_ID_MICROSOFT
=3
902 enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
903 STBTT_UNICODE_EID_UNICODE_1_0
=0,
904 STBTT_UNICODE_EID_UNICODE_1_1
=1,
905 STBTT_UNICODE_EID_ISO_10646
=2,
906 STBTT_UNICODE_EID_UNICODE_2_0_BMP
=3,
907 STBTT_UNICODE_EID_UNICODE_2_0_FULL
=4
910 enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
911 STBTT_MS_EID_SYMBOL
=0,
912 STBTT_MS_EID_UNICODE_BMP
=1,
913 STBTT_MS_EID_SHIFTJIS
=2,
914 STBTT_MS_EID_UNICODE_FULL
=10
917 enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
918 STBTT_MAC_EID_ROMAN
=0, STBTT_MAC_EID_ARABIC
=4,
919 STBTT_MAC_EID_JAPANESE
=1, STBTT_MAC_EID_HEBREW
=5,
920 STBTT_MAC_EID_CHINESE_TRAD
=2, STBTT_MAC_EID_GREEK
=6,
921 STBTT_MAC_EID_KOREAN
=3, STBTT_MAC_EID_RUSSIAN
=7
924 enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
925 // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
926 STBTT_MS_LANG_ENGLISH
=0x0409, STBTT_MS_LANG_ITALIAN
=0x0410,
927 STBTT_MS_LANG_CHINESE
=0x0804, STBTT_MS_LANG_JAPANESE
=0x0411,
928 STBTT_MS_LANG_DUTCH
=0x0413, STBTT_MS_LANG_KOREAN
=0x0412,
929 STBTT_MS_LANG_FRENCH
=0x040c, STBTT_MS_LANG_RUSSIAN
=0x0419,
930 STBTT_MS_LANG_GERMAN
=0x0407, STBTT_MS_LANG_SPANISH
=0x0409,
931 STBTT_MS_LANG_HEBREW
=0x040d, STBTT_MS_LANG_SWEDISH
=0x041D
934 enum { // languageID for STBTT_PLATFORM_ID_MAC
935 STBTT_MAC_LANG_ENGLISH
=0 , STBTT_MAC_LANG_JAPANESE
=11,
936 STBTT_MAC_LANG_ARABIC
=12, STBTT_MAC_LANG_KOREAN
=23,
937 STBTT_MAC_LANG_DUTCH
=4 , STBTT_MAC_LANG_RUSSIAN
=32,
938 STBTT_MAC_LANG_FRENCH
=1 , STBTT_MAC_LANG_SPANISH
=6 ,
939 STBTT_MAC_LANG_GERMAN
=2 , STBTT_MAC_LANG_SWEDISH
=5 ,
940 STBTT_MAC_LANG_HEBREW
=10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED
=33,
941 STBTT_MAC_LANG_ITALIAN
=3 , STBTT_MAC_LANG_CHINESE_TRAD
=19
948 #endif // __STB_INCLUDE_STB_TRUETYPE_H__
950 ///////////////////////////////////////////////////////////////////////////////
951 ///////////////////////////////////////////////////////////////////////////////
957 #ifdef STB_TRUETYPE_IMPLEMENTATION
959 #ifndef STBTT_MAX_OVERSAMPLE
960 #define STBTT_MAX_OVERSAMPLE 8
963 #if STBTT_MAX_OVERSAMPLE > 255
964 #error "STBTT_MAX_OVERSAMPLE cannot be > 255"
967 typedef int stbtt__test_oversample_pow2
[(STBTT_MAX_OVERSAMPLE
& (STBTT_MAX_OVERSAMPLE
-1)) == 0 ? 1 : -1];
969 #ifndef STBTT_RASTERIZER_VERSION
970 #define STBTT_RASTERIZER_VERSION 2
974 #define STBTT__NOTUSED(v) (void)(v)
976 #define STBTT__NOTUSED(v) (void)sizeof(v)
979 //////////////////////////////////////////////////////////////////////////
981 // stbtt__buf helpers to parse data from file
984 static stbtt_uint8
stbtt__buf_get8(stbtt__buf
*b
)
986 if (b
->cursor
>= b
->size
)
988 return b
->data
[b
->cursor
++];
991 static stbtt_uint8
stbtt__buf_peek8(stbtt__buf
*b
)
993 if (b
->cursor
>= b
->size
)
995 return b
->data
[b
->cursor
];
998 static void stbtt__buf_seek(stbtt__buf
*b
, int o
)
1000 STBTT_assert(!(o
> b
->size
|| o
< 0));
1001 b
->cursor
= (o
> b
->size
|| o
< 0) ? b
->size
: o
;
1004 static void stbtt__buf_skip(stbtt__buf
*b
, int o
)
1006 stbtt__buf_seek(b
, b
->cursor
+ o
);
1009 static stbtt_uint32
stbtt__buf_get(stbtt__buf
*b
, int n
)
1013 STBTT_assert(n
>= 1 && n
<= 4);
1014 for (i
= 0; i
< n
; i
++)
1015 v
= (v
<< 8) | stbtt__buf_get8(b
);
1019 static stbtt__buf
stbtt__new_buf(const void *p
, size_t size
)
1022 STBTT_assert(size
< 0x40000000);
1023 r
.data
= (stbtt_uint8
*) p
;
1024 r
.size
= (int) size
;
1029 #define stbtt__buf_get16(b) stbtt__buf_get((b), 2)
1030 #define stbtt__buf_get32(b) stbtt__buf_get((b), 4)
1032 static stbtt__buf
stbtt__buf_range(const stbtt__buf
*b
, int o
, int s
)
1034 stbtt__buf r
= stbtt__new_buf(NULL
, 0);
1035 if (o
< 0 || s
< 0 || o
> b
->size
|| s
> b
->size
- o
) return r
;
1036 r
.data
= b
->data
+ o
;
1041 static stbtt__buf
stbtt__cff_get_index(stbtt__buf
*b
)
1043 int count
, start
, offsize
;
1045 count
= stbtt__buf_get16(b
);
1047 offsize
= stbtt__buf_get8(b
);
1048 STBTT_assert(offsize
>= 1 && offsize
<= 4);
1049 stbtt__buf_skip(b
, offsize
* count
);
1050 stbtt__buf_skip(b
, stbtt__buf_get(b
, offsize
) - 1);
1052 return stbtt__buf_range(b
, start
, b
->cursor
- start
);
1055 static stbtt_uint32
stbtt__cff_int(stbtt__buf
*b
)
1057 int b0
= stbtt__buf_get8(b
);
1058 if (b0
>= 32 && b0
<= 246) return b0
- 139;
1059 else if (b0
>= 247 && b0
<= 250) return (b0
- 247)*256 + stbtt__buf_get8(b
) + 108;
1060 else if (b0
>= 251 && b0
<= 254) return -(b0
- 251)*256 - stbtt__buf_get8(b
) - 108;
1061 else if (b0
== 28) return stbtt__buf_get16(b
);
1062 else if (b0
== 29) return stbtt__buf_get32(b
);
1067 static void stbtt__cff_skip_operand(stbtt__buf
*b
) {
1068 int v
, b0
= stbtt__buf_peek8(b
);
1069 STBTT_assert(b0
>= 28);
1071 stbtt__buf_skip(b
, 1);
1072 while (b
->cursor
< b
->size
) {
1073 v
= stbtt__buf_get8(b
);
1074 if ((v
& 0xF) == 0xF || (v
>> 4) == 0xF)
1082 static stbtt__buf
stbtt__dict_get(stbtt__buf
*b
, int key
)
1084 stbtt__buf_seek(b
, 0);
1085 while (b
->cursor
< b
->size
) {
1086 int start
= b
->cursor
, end
, op
;
1087 while (stbtt__buf_peek8(b
) >= 28)
1088 stbtt__cff_skip_operand(b
);
1090 op
= stbtt__buf_get8(b
);
1091 if (op
== 12) op
= stbtt__buf_get8(b
) | 0x100;
1092 if (op
== key
) return stbtt__buf_range(b
, start
, end
-start
);
1094 return stbtt__buf_range(b
, 0, 0);
1097 static void stbtt__dict_get_ints(stbtt__buf
*b
, int key
, int outcount
, stbtt_uint32
*out
)
1100 stbtt__buf operands
= stbtt__dict_get(b
, key
);
1101 for (i
= 0; i
< outcount
&& operands
.cursor
< operands
.size
; i
++)
1102 out
[i
] = stbtt__cff_int(&operands
);
1105 static int stbtt__cff_index_count(stbtt__buf
*b
)
1107 stbtt__buf_seek(b
, 0);
1108 return stbtt__buf_get16(b
);
1111 static stbtt__buf
stbtt__cff_index_get(stbtt__buf b
, int i
)
1113 int count
, offsize
, start
, end
;
1114 stbtt__buf_seek(&b
, 0);
1115 count
= stbtt__buf_get16(&b
);
1116 offsize
= stbtt__buf_get8(&b
);
1117 STBTT_assert(i
>= 0 && i
< count
);
1118 STBTT_assert(offsize
>= 1 && offsize
<= 4);
1119 stbtt__buf_skip(&b
, i
*offsize
);
1120 start
= stbtt__buf_get(&b
, offsize
);
1121 end
= stbtt__buf_get(&b
, offsize
);
1122 return stbtt__buf_range(&b
, 2+(count
+1)*offsize
+start
, end
- start
);
1125 //////////////////////////////////////////////////////////////////////////
1127 // accessors to parse data from file
1130 // on platforms that don't allow misaligned reads, if we want to allow
1131 // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
1133 #define ttBYTE(p) (* (stbtt_uint8 *) (p))
1134 #define ttCHAR(p) (* (stbtt_int8 *) (p))
1135 #define ttFixed(p) ttLONG(p)
1137 static stbtt_uint16
ttUSHORT(stbtt_uint8
*p
) { return p
[0]*256 + p
[1]; }
1138 static stbtt_int16
ttSHORT(stbtt_uint8
*p
) { return p
[0]*256 + p
[1]; }
1139 static stbtt_uint32
ttULONG(stbtt_uint8
*p
) { return (p
[0]<<24) + (p
[1]<<16) + (p
[2]<<8) + p
[3]; }
1140 static stbtt_int32
ttLONG(stbtt_uint8
*p
) { return (p
[0]<<24) + (p
[1]<<16) + (p
[2]<<8) + p
[3]; }
1142 #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
1143 #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])
1145 static int stbtt__isfont(stbtt_uint8
*font
)
1147 // check the version number
1148 if (stbtt_tag4(font
, '1',0,0,0)) return 1; // TrueType 1
1149 if (stbtt_tag(font
, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!
1150 if (stbtt_tag(font
, "OTTO")) return 1; // OpenType with CFF
1151 if (stbtt_tag4(font
, 0,1,0,0)) return 1; // OpenType 1.0
1152 if (stbtt_tag(font
, "true")) return 1; // Apple specification for TrueType fonts
1156 // @OPTIMIZE: binary search
1157 static stbtt_uint32
stbtt__find_table(stbtt_uint8
*data
, stbtt_uint32 fontstart
, const char *tag
)
1159 stbtt_int32 num_tables
= ttUSHORT(data
+fontstart
+4);
1160 stbtt_uint32 tabledir
= fontstart
+ 12;
1162 for (i
=0; i
< num_tables
; ++i
) {
1163 stbtt_uint32 loc
= tabledir
+ 16*i
;
1164 if (stbtt_tag(data
+loc
+0, tag
))
1165 return ttULONG(data
+loc
+8);
1170 static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection
, int index
)
1172 // if it's just a font, there's only one valid index
1173 if (stbtt__isfont(font_collection
))
1174 return index
== 0 ? 0 : -1;
1176 // check if it's a TTC
1177 if (stbtt_tag(font_collection
, "ttcf")) {
1179 if (ttULONG(font_collection
+4) == 0x00010000 || ttULONG(font_collection
+4) == 0x00020000) {
1180 stbtt_int32 n
= ttLONG(font_collection
+8);
1183 return ttULONG(font_collection
+12+index
*4);
1189 static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection
)
1191 // if it's just a font, there's only one valid font
1192 if (stbtt__isfont(font_collection
))
1195 // check if it's a TTC
1196 if (stbtt_tag(font_collection
, "ttcf")) {
1198 if (ttULONG(font_collection
+4) == 0x00010000 || ttULONG(font_collection
+4) == 0x00020000) {
1199 return ttLONG(font_collection
+8);
1205 static stbtt__buf
stbtt__get_subrs(stbtt__buf cff
, stbtt__buf fontdict
)
1207 stbtt_uint32 subrsoff
= 0, private_loc
[2] = { 0, 0 };
1209 stbtt__dict_get_ints(&fontdict
, 18, 2, private_loc
);
1210 if (!private_loc
[1] || !private_loc
[0]) return stbtt__new_buf(NULL
, 0);
1211 pdict
= stbtt__buf_range(&cff
, private_loc
[1], private_loc
[0]);
1212 stbtt__dict_get_ints(&pdict
, 19, 1, &subrsoff
);
1213 if (!subrsoff
) return stbtt__new_buf(NULL
, 0);
1214 stbtt__buf_seek(&cff
, private_loc
[1]+subrsoff
);
1215 return stbtt__cff_get_index(&cff
);
1218 static int stbtt_InitFont_internal(stbtt_fontinfo
*info
, unsigned char *data
, int fontstart
)
1220 stbtt_uint32 cmap
, t
;
1221 stbtt_int32 i
,numTables
;
1224 info
->fontstart
= fontstart
;
1225 info
->cff
= stbtt__new_buf(NULL
, 0);
1227 cmap
= stbtt__find_table(data
, fontstart
, "cmap"); // required
1228 info
->loca
= stbtt__find_table(data
, fontstart
, "loca"); // required
1229 info
->head
= stbtt__find_table(data
, fontstart
, "head"); // required
1230 info
->glyf
= stbtt__find_table(data
, fontstart
, "glyf"); // required
1231 info
->hhea
= stbtt__find_table(data
, fontstart
, "hhea"); // required
1232 info
->hmtx
= stbtt__find_table(data
, fontstart
, "hmtx"); // required
1233 info
->kern
= stbtt__find_table(data
, fontstart
, "kern"); // not required
1235 if (!cmap
|| !info
->head
|| !info
->hhea
|| !info
->hmtx
)
1238 // required for truetype
1239 if (!info
->loca
) return 0;
1241 // initialization for CFF / Type2 fonts (OTF)
1242 stbtt__buf b
, topdict
, topdictidx
;
1243 stbtt_uint32 cstype
= 2, charstrings
= 0, fdarrayoff
= 0, fdselectoff
= 0;
1246 cff
= stbtt__find_table(data
, fontstart
, "CFF ");
1249 info
->fontdicts
= stbtt__new_buf(NULL
, 0);
1250 info
->fdselect
= stbtt__new_buf(NULL
, 0);
1252 // @TODO this should use size from table (not 512MB)
1253 info
->cff
= stbtt__new_buf(data
+cff
, 512*1024*1024);
1257 stbtt__buf_skip(&b
, 2);
1258 stbtt__buf_seek(&b
, stbtt__buf_get8(&b
)); // hdrsize
1260 // @TODO the name INDEX could list multiple fonts,
1261 // but we just use the first one.
1262 stbtt__cff_get_index(&b
); // name INDEX
1263 topdictidx
= stbtt__cff_get_index(&b
);
1264 topdict
= stbtt__cff_index_get(topdictidx
, 0);
1265 stbtt__cff_get_index(&b
); // string INDEX
1266 info
->gsubrs
= stbtt__cff_get_index(&b
);
1268 stbtt__dict_get_ints(&topdict
, 17, 1, &charstrings
);
1269 stbtt__dict_get_ints(&topdict
, 0x100 | 6, 1, &cstype
);
1270 stbtt__dict_get_ints(&topdict
, 0x100 | 36, 1, &fdarrayoff
);
1271 stbtt__dict_get_ints(&topdict
, 0x100 | 37, 1, &fdselectoff
);
1272 info
->subrs
= stbtt__get_subrs(b
, topdict
);
1274 // we only support Type 2 charstrings
1275 if (cstype
!= 2) return 0;
1276 if (charstrings
== 0) return 0;
1279 // looks like a CID font
1280 if (!fdselectoff
) return 0;
1281 stbtt__buf_seek(&b
, fdarrayoff
);
1282 info
->fontdicts
= stbtt__cff_get_index(&b
);
1283 info
->fdselect
= stbtt__buf_range(&b
, fdselectoff
, b
.size
-fdselectoff
);
1286 stbtt__buf_seek(&b
, charstrings
);
1287 info
->charstrings
= stbtt__cff_get_index(&b
);
1290 t
= stbtt__find_table(data
, fontstart
, "maxp");
1292 info
->numGlyphs
= ttUSHORT(data
+t
+4);
1294 info
->numGlyphs
= 0xffff;
1296 // find a cmap encoding table we understand *now* to avoid searching
1297 // later. (todo: could make this installable)
1298 // the same regardless of glyph.
1299 numTables
= ttUSHORT(data
+ cmap
+ 2);
1300 info
->index_map
= 0;
1301 for (i
=0; i
< numTables
; ++i
) {
1302 stbtt_uint32 encoding_record
= cmap
+ 4 + 8 * i
;
1303 // find an encoding we understand:
1304 switch(ttUSHORT(data
+encoding_record
)) {
1305 case STBTT_PLATFORM_ID_MICROSOFT
:
1306 switch (ttUSHORT(data
+encoding_record
+2)) {
1307 case STBTT_MS_EID_UNICODE_BMP
:
1308 case STBTT_MS_EID_UNICODE_FULL
:
1310 info
->index_map
= cmap
+ ttULONG(data
+encoding_record
+4);
1314 case STBTT_PLATFORM_ID_UNICODE
:
1315 // Mac/iOS has these
1316 // all the encodingIDs are unicode, so we don't bother to check it
1317 info
->index_map
= cmap
+ ttULONG(data
+encoding_record
+4);
1321 if (info
->index_map
== 0)
1324 info
->indexToLocFormat
= ttUSHORT(data
+info
->head
+ 50);
1328 STBTT_DEF
int stbtt_FindGlyphIndex(const stbtt_fontinfo
*info
, int unicode_codepoint
)
1330 stbtt_uint8
*data
= info
->data
;
1331 stbtt_uint32 index_map
= info
->index_map
;
1333 stbtt_uint16 format
= ttUSHORT(data
+ index_map
+ 0);
1334 if (format
== 0) { // apple byte encoding
1335 stbtt_int32 bytes
= ttUSHORT(data
+ index_map
+ 2);
1336 if (unicode_codepoint
< bytes
-6)
1337 return ttBYTE(data
+ index_map
+ 6 + unicode_codepoint
);
1339 } else if (format
== 6) {
1340 stbtt_uint32 first
= ttUSHORT(data
+ index_map
+ 6);
1341 stbtt_uint32 count
= ttUSHORT(data
+ index_map
+ 8);
1342 if ((stbtt_uint32
) unicode_codepoint
>= first
&& (stbtt_uint32
) unicode_codepoint
< first
+count
)
1343 return ttUSHORT(data
+ index_map
+ 10 + (unicode_codepoint
- first
)*2);
1345 } else if (format
== 2) {
1346 STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
1348 } else if (format
== 4) { // standard mapping for windows fonts: binary search collection of ranges
1349 stbtt_uint16 segcount
= ttUSHORT(data
+index_map
+6) >> 1;
1350 stbtt_uint16 searchRange
= ttUSHORT(data
+index_map
+8) >> 1;
1351 stbtt_uint16 entrySelector
= ttUSHORT(data
+index_map
+10);
1352 stbtt_uint16 rangeShift
= ttUSHORT(data
+index_map
+12) >> 1;
1354 // do a binary search of the segments
1355 stbtt_uint32 endCount
= index_map
+ 14;
1356 stbtt_uint32 search
= endCount
;
1358 if (unicode_codepoint
> 0xffff)
1361 // they lie from endCount .. endCount + segCount
1362 // but searchRange is the nearest power of two, so...
1363 if (unicode_codepoint
>= ttUSHORT(data
+ search
+ rangeShift
*2))
1364 search
+= rangeShift
*2;
1366 // now decrement to bias correctly to find smallest
1368 while (entrySelector
) {
1371 end
= ttUSHORT(data
+ search
+ searchRange
*2);
1372 if (unicode_codepoint
> end
)
1373 search
+= searchRange
*2;
1379 stbtt_uint16 offset
, start
;
1380 stbtt_uint16 item
= (stbtt_uint16
) ((search
- endCount
) >> 1);
1382 STBTT_assert(unicode_codepoint
<= ttUSHORT(data
+ endCount
+ 2*item
));
1383 start
= ttUSHORT(data
+ index_map
+ 14 + segcount
*2 + 2 + 2*item
);
1384 if (unicode_codepoint
< start
)
1387 offset
= ttUSHORT(data
+ index_map
+ 14 + segcount
*6 + 2 + 2*item
);
1389 return (stbtt_uint16
) (unicode_codepoint
+ ttSHORT(data
+ index_map
+ 14 + segcount
*4 + 2 + 2*item
));
1391 return ttUSHORT(data
+ offset
+ (unicode_codepoint
-start
)*2 + index_map
+ 14 + segcount
*6 + 2 + 2*item
);
1393 } else if (format
== 12 || format
== 13) {
1394 stbtt_uint32 ngroups
= ttULONG(data
+index_map
+12);
1395 stbtt_int32 low
,high
;
1396 low
= 0; high
= (stbtt_int32
)ngroups
;
1397 // Binary search the right group.
1398 while (low
< high
) {
1399 stbtt_int32 mid
= low
+ ((high
-low
) >> 1); // rounds down, so low <= mid < high
1400 stbtt_uint32 start_char
= ttULONG(data
+index_map
+16+mid
*12);
1401 stbtt_uint32 end_char
= ttULONG(data
+index_map
+16+mid
*12+4);
1402 if ((stbtt_uint32
) unicode_codepoint
< start_char
)
1404 else if ((stbtt_uint32
) unicode_codepoint
> end_char
)
1407 stbtt_uint32 start_glyph
= ttULONG(data
+index_map
+16+mid
*12+8);
1409 return start_glyph
+ unicode_codepoint
-start_char
;
1410 else // format == 13
1414 return 0; // not found
1421 STBTT_DEF
int stbtt_GetCodepointShape(const stbtt_fontinfo
*info
, int unicode_codepoint
, stbtt_vertex
**vertices
)
1423 return stbtt_GetGlyphShape(info
, stbtt_FindGlyphIndex(info
, unicode_codepoint
), vertices
);
1426 static void stbtt_setvertex(stbtt_vertex
*v
, stbtt_uint8 type
, stbtt_int32 x
, stbtt_int32 y
, stbtt_int32 cx
, stbtt_int32 cy
)
1429 v
->x
= (stbtt_int16
) x
;
1430 v
->y
= (stbtt_int16
) y
;
1431 v
->cx
= (stbtt_int16
) cx
;
1432 v
->cy
= (stbtt_int16
) cy
;
1435 static int stbtt__GetGlyfOffset(const stbtt_fontinfo
*info
, int glyph_index
)
1439 STBTT_assert(!info
->cff
.size
);
1441 if (glyph_index
>= info
->numGlyphs
) return -1; // glyph index out of range
1442 if (info
->indexToLocFormat
>= 2) return -1; // unknown index->glyph map format
1444 if (info
->indexToLocFormat
== 0) {
1445 g1
= info
->glyf
+ ttUSHORT(info
->data
+ info
->loca
+ glyph_index
* 2) * 2;
1446 g2
= info
->glyf
+ ttUSHORT(info
->data
+ info
->loca
+ glyph_index
* 2 + 2) * 2;
1448 g1
= info
->glyf
+ ttULONG (info
->data
+ info
->loca
+ glyph_index
* 4);
1449 g2
= info
->glyf
+ ttULONG (info
->data
+ info
->loca
+ glyph_index
* 4 + 4);
1452 return g1
==g2
? -1 : g1
; // if length is 0, return -1
1455 static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo
*info
, int glyph_index
, int *x0
, int *y0
, int *x1
, int *y1
);
1457 STBTT_DEF
int stbtt_GetGlyphBox(const stbtt_fontinfo
*info
, int glyph_index
, int *x0
, int *y0
, int *x1
, int *y1
)
1459 if (info
->cff
.size
) {
1460 stbtt__GetGlyphInfoT2(info
, glyph_index
, x0
, y0
, x1
, y1
);
1462 int g
= stbtt__GetGlyfOffset(info
, glyph_index
);
1463 if (g
< 0) return 0;
1465 if (x0
) *x0
= ttSHORT(info
->data
+ g
+ 2);
1466 if (y0
) *y0
= ttSHORT(info
->data
+ g
+ 4);
1467 if (x1
) *x1
= ttSHORT(info
->data
+ g
+ 6);
1468 if (y1
) *y1
= ttSHORT(info
->data
+ g
+ 8);
1473 STBTT_DEF
int stbtt_GetCodepointBox(const stbtt_fontinfo
*info
, int codepoint
, int *x0
, int *y0
, int *x1
, int *y1
)
1475 return stbtt_GetGlyphBox(info
, stbtt_FindGlyphIndex(info
,codepoint
), x0
,y0
,x1
,y1
);
1478 STBTT_DEF
int stbtt_IsGlyphEmpty(const stbtt_fontinfo
*info
, int glyph_index
)
1480 stbtt_int16 numberOfContours
;
1483 return stbtt__GetGlyphInfoT2(info
, glyph_index
, NULL
, NULL
, NULL
, NULL
) == 0;
1484 g
= stbtt__GetGlyfOffset(info
, glyph_index
);
1485 if (g
< 0) return 1;
1486 numberOfContours
= ttSHORT(info
->data
+ g
);
1487 return numberOfContours
== 0;
1490 static int stbtt__close_shape(stbtt_vertex
*vertices
, int num_vertices
, int was_off
, int start_off
,
1491 stbtt_int32 sx
, stbtt_int32 sy
, stbtt_int32 scx
, stbtt_int32 scy
, stbtt_int32 cx
, stbtt_int32 cy
)
1495 stbtt_setvertex(&vertices
[num_vertices
++], STBTT_vcurve
, (cx
+scx
)>>1, (cy
+scy
)>>1, cx
,cy
);
1496 stbtt_setvertex(&vertices
[num_vertices
++], STBTT_vcurve
, sx
,sy
,scx
,scy
);
1499 stbtt_setvertex(&vertices
[num_vertices
++], STBTT_vcurve
,sx
,sy
,cx
,cy
);
1501 stbtt_setvertex(&vertices
[num_vertices
++], STBTT_vline
,sx
,sy
,0,0);
1503 return num_vertices
;
1506 static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo
*info
, int glyph_index
, stbtt_vertex
**pvertices
)
1508 stbtt_int16 numberOfContours
;
1509 stbtt_uint8
*endPtsOfContours
;
1510 stbtt_uint8
*data
= info
->data
;
1511 stbtt_vertex
*vertices
=0;
1513 int g
= stbtt__GetGlyfOffset(info
, glyph_index
);
1517 if (g
< 0) return 0;
1519 numberOfContours
= ttSHORT(data
+ g
);
1521 if (numberOfContours
> 0) {
1522 stbtt_uint8 flags
=0,flagcount
;
1523 stbtt_int32 ins
, i
,j
=0,m
,n
, next_move
, was_off
=0, off
, start_off
=0;
1524 stbtt_int32 x
,y
,cx
,cy
,sx
,sy
, scx
,scy
;
1525 stbtt_uint8
*points
;
1526 endPtsOfContours
= (data
+ g
+ 10);
1527 ins
= ttUSHORT(data
+ g
+ 10 + numberOfContours
* 2);
1528 points
= data
+ g
+ 10 + numberOfContours
* 2 + 2 + ins
;
1530 n
= 1+ttUSHORT(endPtsOfContours
+ numberOfContours
*2-2);
1532 m
= n
+ 2*numberOfContours
; // a loose bound on how many vertices we might need
1533 vertices
= (stbtt_vertex
*) STBTT_malloc(m
* sizeof(vertices
[0]), info
->userdata
);
1540 // in first pass, we load uninterpreted data into the allocated array
1541 // above, shifted to the end of the array so we won't overwrite it when
1542 // we create our final data starting from the front
1544 off
= m
- n
; // starting offset for uninterpreted data, regardless of how m ends up being calculated
1548 for (i
=0; i
< n
; ++i
) {
1549 if (flagcount
== 0) {
1552 flagcount
= *points
++;
1555 vertices
[off
+i
].type
= flags
;
1558 // now load x coordinates
1560 for (i
=0; i
< n
; ++i
) {
1561 flags
= vertices
[off
+i
].type
;
1563 stbtt_int16 dx
= *points
++;
1564 x
+= (flags
& 16) ? dx
: -dx
; // ???
1566 if (!(flags
& 16)) {
1567 x
= x
+ (stbtt_int16
) (points
[0]*256 + points
[1]);
1571 vertices
[off
+i
].x
= (stbtt_int16
) x
;
1574 // now load y coordinates
1576 for (i
=0; i
< n
; ++i
) {
1577 flags
= vertices
[off
+i
].type
;
1579 stbtt_int16 dy
= *points
++;
1580 y
+= (flags
& 32) ? dy
: -dy
; // ???
1582 if (!(flags
& 32)) {
1583 y
= y
+ (stbtt_int16
) (points
[0]*256 + points
[1]);
1587 vertices
[off
+i
].y
= (stbtt_int16
) y
;
1590 // now convert them to our format
1592 sx
= sy
= cx
= cy
= scx
= scy
= 0;
1593 for (i
=0; i
< n
; ++i
) {
1594 flags
= vertices
[off
+i
].type
;
1595 x
= (stbtt_int16
) vertices
[off
+i
].x
;
1596 y
= (stbtt_int16
) vertices
[off
+i
].y
;
1598 if (next_move
== i
) {
1600 num_vertices
= stbtt__close_shape(vertices
, num_vertices
, was_off
, start_off
, sx
,sy
,scx
,scy
,cx
,cy
);
1602 // now start the new one
1603 start_off
= !(flags
& 1);
1605 // if we start off with an off-curve point, then when we need to find a point on the curve
1606 // where we can start, and we need to save some state for when we wraparound.
1609 if (!(vertices
[off
+i
+1].type
& 1)) {
1610 // next point is also a curve point, so interpolate an on-point curve
1611 sx
= (x
+ (stbtt_int32
) vertices
[off
+i
+1].x
) >> 1;
1612 sy
= (y
+ (stbtt_int32
) vertices
[off
+i
+1].y
) >> 1;
1614 // otherwise just use the next point as our start point
1615 sx
= (stbtt_int32
) vertices
[off
+i
+1].x
;
1616 sy
= (stbtt_int32
) vertices
[off
+i
+1].y
;
1617 ++i
; // we're using point i+1 as the starting point, so skip it
1623 stbtt_setvertex(&vertices
[num_vertices
++], STBTT_vmove
,sx
,sy
,0,0);
1625 next_move
= 1 + ttUSHORT(endPtsOfContours
+j
*2);
1628 if (!(flags
& 1)) { // if it's a curve
1629 if (was_off
) // two off-curve control points in a row means interpolate an on-curve midpoint
1630 stbtt_setvertex(&vertices
[num_vertices
++], STBTT_vcurve
, (cx
+x
)>>1, (cy
+y
)>>1, cx
, cy
);
1636 stbtt_setvertex(&vertices
[num_vertices
++], STBTT_vcurve
, x
,y
, cx
, cy
);
1638 stbtt_setvertex(&vertices
[num_vertices
++], STBTT_vline
, x
,y
,0,0);
1643 num_vertices
= stbtt__close_shape(vertices
, num_vertices
, was_off
, start_off
, sx
,sy
,scx
,scy
,cx
,cy
);
1644 } else if (numberOfContours
== -1) {
1647 stbtt_uint8
*comp
= data
+ g
+ 10;
1651 stbtt_uint16 flags
, gidx
;
1652 int comp_num_verts
= 0, i
;
1653 stbtt_vertex
*comp_verts
= 0, *tmp
= 0;
1654 float mtx
[6] = {1,0,0,1,0,0}, m
, n
;
1656 flags
= ttSHORT(comp
); comp
+=2;
1657 gidx
= ttSHORT(comp
); comp
+=2;
1659 if (flags
& 2) { // XY values
1660 if (flags
& 1) { // shorts
1661 mtx
[4] = ttSHORT(comp
); comp
+=2;
1662 mtx
[5] = ttSHORT(comp
); comp
+=2;
1664 mtx
[4] = ttCHAR(comp
); comp
+=1;
1665 mtx
[5] = ttCHAR(comp
); comp
+=1;
1669 // @TODO handle matching point
1672 if (flags
& (1<<3)) { // WE_HAVE_A_SCALE
1673 mtx
[0] = mtx
[3] = ttSHORT(comp
)/16384.0f
; comp
+=2;
1674 mtx
[1] = mtx
[2] = 0;
1675 } else if (flags
& (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
1676 mtx
[0] = ttSHORT(comp
)/16384.0f
; comp
+=2;
1677 mtx
[1] = mtx
[2] = 0;
1678 mtx
[3] = ttSHORT(comp
)/16384.0f
; comp
+=2;
1679 } else if (flags
& (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
1680 mtx
[0] = ttSHORT(comp
)/16384.0f
; comp
+=2;
1681 mtx
[1] = ttSHORT(comp
)/16384.0f
; comp
+=2;
1682 mtx
[2] = ttSHORT(comp
)/16384.0f
; comp
+=2;
1683 mtx
[3] = ttSHORT(comp
)/16384.0f
; comp
+=2;
1686 // Find transformation scales.
1687 m
= (float) STBTT_sqrt(mtx
[0]*mtx
[0] + mtx
[1]*mtx
[1]);
1688 n
= (float) STBTT_sqrt(mtx
[2]*mtx
[2] + mtx
[3]*mtx
[3]);
1690 // Get indexed glyph.
1691 comp_num_verts
= stbtt_GetGlyphShape(info
, gidx
, &comp_verts
);
1692 if (comp_num_verts
> 0) {
1693 // Transform vertices.
1694 for (i
= 0; i
< comp_num_verts
; ++i
) {
1695 stbtt_vertex
* v
= &comp_verts
[i
];
1696 stbtt_vertex_type x
,y
;
1698 v
->x
= (stbtt_vertex_type
)(m
* (mtx
[0]*x
+ mtx
[2]*y
+ mtx
[4]));
1699 v
->y
= (stbtt_vertex_type
)(n
* (mtx
[1]*x
+ mtx
[3]*y
+ mtx
[5]));
1701 v
->cx
= (stbtt_vertex_type
)(m
* (mtx
[0]*x
+ mtx
[2]*y
+ mtx
[4]));
1702 v
->cy
= (stbtt_vertex_type
)(n
* (mtx
[1]*x
+ mtx
[3]*y
+ mtx
[5]));
1705 tmp
= (stbtt_vertex
*)STBTT_malloc((num_vertices
+comp_num_verts
)*sizeof(stbtt_vertex
), info
->userdata
);
1707 if (vertices
) STBTT_free(vertices
, info
->userdata
);
1708 if (comp_verts
) STBTT_free(comp_verts
, info
->userdata
);
1711 if (num_vertices
> 0) STBTT_memcpy(tmp
, vertices
, num_vertices
*sizeof(stbtt_vertex
));
1712 STBTT_memcpy(tmp
+num_vertices
, comp_verts
, comp_num_verts
*sizeof(stbtt_vertex
));
1713 if (vertices
) STBTT_free(vertices
, info
->userdata
);
1715 STBTT_free(comp_verts
, info
->userdata
);
1716 num_vertices
+= comp_num_verts
;
1718 // More components ?
1719 more
= flags
& (1<<5);
1721 } else if (numberOfContours
< 0) {
1722 // @TODO other compound variations?
1725 // numberOfCounters == 0, do nothing
1728 *pvertices
= vertices
;
1729 return num_vertices
;
1736 float first_x
, first_y
;
1738 stbtt_int32 min_x
, max_x
, min_y
, max_y
;
1740 stbtt_vertex
*pvertices
;
1744 #define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}
1746 static void stbtt__track_vertex(stbtt__csctx
*c
, stbtt_int32 x
, stbtt_int32 y
)
1748 if (x
> c
->max_x
|| !c
->started
) c
->max_x
= x
;
1749 if (y
> c
->max_y
|| !c
->started
) c
->max_y
= y
;
1750 if (x
< c
->min_x
|| !c
->started
) c
->min_x
= x
;
1751 if (y
< c
->min_y
|| !c
->started
) c
->min_y
= y
;
1755 static void stbtt__csctx_v(stbtt__csctx
*c
, stbtt_uint8 type
, stbtt_int32 x
, stbtt_int32 y
, stbtt_int32 cx
, stbtt_int32 cy
, stbtt_int32 cx1
, stbtt_int32 cy1
)
1758 stbtt__track_vertex(c
, x
, y
);
1759 if (type
== STBTT_vcubic
) {
1760 stbtt__track_vertex(c
, cx
, cy
);
1761 stbtt__track_vertex(c
, cx1
, cy1
);
1764 stbtt_setvertex(&c
->pvertices
[c
->num_vertices
], type
, x
, y
, cx
, cy
);
1765 c
->pvertices
[c
->num_vertices
].cx1
= (stbtt_int16
) cx1
;
1766 c
->pvertices
[c
->num_vertices
].cy1
= (stbtt_int16
) cy1
;
1771 static void stbtt__csctx_close_shape(stbtt__csctx
*ctx
)
1773 if (ctx
->first_x
!= ctx
->x
|| ctx
->first_y
!= ctx
->y
)
1774 stbtt__csctx_v(ctx
, STBTT_vline
, (int)ctx
->first_x
, (int)ctx
->first_y
, 0, 0, 0, 0);
1777 static void stbtt__csctx_rmove_to(stbtt__csctx
*ctx
, float dx
, float dy
)
1779 stbtt__csctx_close_shape(ctx
);
1780 ctx
->first_x
= ctx
->x
= ctx
->x
+ dx
;
1781 ctx
->first_y
= ctx
->y
= ctx
->y
+ dy
;
1782 stbtt__csctx_v(ctx
, STBTT_vmove
, (int)ctx
->x
, (int)ctx
->y
, 0, 0, 0, 0);
1785 static void stbtt__csctx_rline_to(stbtt__csctx
*ctx
, float dx
, float dy
)
1789 stbtt__csctx_v(ctx
, STBTT_vline
, (int)ctx
->x
, (int)ctx
->y
, 0, 0, 0, 0);
1792 static void stbtt__csctx_rccurve_to(stbtt__csctx
*ctx
, float dx1
, float dy1
, float dx2
, float dy2
, float dx3
, float dy3
)
1794 float cx1
= ctx
->x
+ dx1
;
1795 float cy1
= ctx
->y
+ dy1
;
1796 float cx2
= cx1
+ dx2
;
1797 float cy2
= cy1
+ dy2
;
1800 stbtt__csctx_v(ctx
, STBTT_vcubic
, (int)ctx
->x
, (int)ctx
->y
, (int)cx1
, (int)cy1
, (int)cx2
, (int)cy2
);
1803 static stbtt__buf
stbtt__get_subr(stbtt__buf idx
, int n
)
1805 int count
= stbtt__cff_index_count(&idx
);
1809 else if (count
>= 1240)
1812 if (n
< 0 || n
>= count
)
1813 return stbtt__new_buf(NULL
, 0);
1814 return stbtt__cff_index_get(idx
, n
);
1817 static stbtt__buf
stbtt__cid_get_glyph_subrs(const stbtt_fontinfo
*info
, int glyph_index
)
1819 stbtt__buf fdselect
= info
->fdselect
;
1820 int nranges
, start
, end
, v
, fmt
, fdselector
= -1, i
;
1822 stbtt__buf_seek(&fdselect
, 0);
1823 fmt
= stbtt__buf_get8(&fdselect
);
1826 stbtt__buf_skip(&fdselect
, glyph_index
);
1827 fdselector
= stbtt__buf_get8(&fdselect
);
1828 } else if (fmt
== 3) {
1829 nranges
= stbtt__buf_get16(&fdselect
);
1830 start
= stbtt__buf_get16(&fdselect
);
1831 for (i
= 0; i
< nranges
; i
++) {
1832 v
= stbtt__buf_get8(&fdselect
);
1833 end
= stbtt__buf_get16(&fdselect
);
1834 if (glyph_index
>= start
&& glyph_index
< end
) {
1841 if (fdselector
== -1) stbtt__new_buf(NULL
, 0);
1842 return stbtt__get_subrs(info
->cff
, stbtt__cff_index_get(info
->fontdicts
, fdselector
));
1845 static int stbtt__run_charstring(const stbtt_fontinfo
*info
, int glyph_index
, stbtt__csctx
*c
)
1847 int in_header
= 1, maskbits
= 0, subr_stack_height
= 0, sp
= 0, v
, i
, b0
;
1848 int has_subrs
= 0, clear_stack
;
1850 stbtt__buf subr_stack
[10], subrs
= info
->subrs
, b
;
1853 #define STBTT__CSERR(s) (0)
1855 // this currently ignores the initial width value, which isn't needed if we have hmtx
1856 b
= stbtt__cff_index_get(info
->charstrings
, glyph_index
);
1857 while (b
.cursor
< b
.size
) {
1860 b0
= stbtt__buf_get8(&b
);
1862 // @TODO implement hinting
1863 case 0x13: // hintmask
1864 case 0x14: // cntrmask
1866 maskbits
+= (sp
/ 2); // implicit "vstem"
1868 stbtt__buf_skip(&b
, (maskbits
+ 7) / 8);
1873 case 0x12: // hstemhm
1874 case 0x17: // vstemhm
1875 maskbits
+= (sp
/ 2);
1878 case 0x15: // rmoveto
1880 if (sp
< 2) return STBTT__CSERR("rmoveto stack");
1881 stbtt__csctx_rmove_to(c
, s
[sp
-2], s
[sp
-1]);
1883 case 0x04: // vmoveto
1885 if (sp
< 1) return STBTT__CSERR("vmoveto stack");
1886 stbtt__csctx_rmove_to(c
, 0, s
[sp
-1]);
1888 case 0x16: // hmoveto
1890 if (sp
< 1) return STBTT__CSERR("hmoveto stack");
1891 stbtt__csctx_rmove_to(c
, s
[sp
-1], 0);
1894 case 0x05: // rlineto
1895 if (sp
< 2) return STBTT__CSERR("rlineto stack");
1896 for (; i
+ 1 < sp
; i
+= 2)
1897 stbtt__csctx_rline_to(c
, s
[i
], s
[i
+1]);
1900 // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical
1901 // starting from a different place.
1903 case 0x07: // vlineto
1904 if (sp
< 1) return STBTT__CSERR("vlineto stack");
1906 case 0x06: // hlineto
1907 if (sp
< 1) return STBTT__CSERR("hlineto stack");
1910 stbtt__csctx_rline_to(c
, s
[i
], 0);
1914 stbtt__csctx_rline_to(c
, 0, s
[i
]);
1919 case 0x1F: // hvcurveto
1920 if (sp
< 4) return STBTT__CSERR("hvcurveto stack");
1922 case 0x1E: // vhcurveto
1923 if (sp
< 4) return STBTT__CSERR("vhcurveto stack");
1925 if (i
+ 3 >= sp
) break;
1926 stbtt__csctx_rccurve_to(c
, 0, s
[i
], s
[i
+1], s
[i
+2], s
[i
+3], (sp
- i
== 5) ? s
[i
+ 4] : 0.0f
);
1929 if (i
+ 3 >= sp
) break;
1930 stbtt__csctx_rccurve_to(c
, s
[i
], 0, s
[i
+1], s
[i
+2], (sp
- i
== 5) ? s
[i
+4] : 0.0f
, s
[i
+3]);
1935 case 0x08: // rrcurveto
1936 if (sp
< 6) return STBTT__CSERR("rcurveline stack");
1937 for (; i
+ 5 < sp
; i
+= 6)
1938 stbtt__csctx_rccurve_to(c
, s
[i
], s
[i
+1], s
[i
+2], s
[i
+3], s
[i
+4], s
[i
+5]);
1941 case 0x18: // rcurveline
1942 if (sp
< 8) return STBTT__CSERR("rcurveline stack");
1943 for (; i
+ 5 < sp
- 2; i
+= 6)
1944 stbtt__csctx_rccurve_to(c
, s
[i
], s
[i
+1], s
[i
+2], s
[i
+3], s
[i
+4], s
[i
+5]);
1945 if (i
+ 1 >= sp
) return STBTT__CSERR("rcurveline stack");
1946 stbtt__csctx_rline_to(c
, s
[i
], s
[i
+1]);
1949 case 0x19: // rlinecurve
1950 if (sp
< 8) return STBTT__CSERR("rlinecurve stack");
1951 for (; i
+ 1 < sp
- 6; i
+= 2)
1952 stbtt__csctx_rline_to(c
, s
[i
], s
[i
+1]);
1953 if (i
+ 5 >= sp
) return STBTT__CSERR("rlinecurve stack");
1954 stbtt__csctx_rccurve_to(c
, s
[i
], s
[i
+1], s
[i
+2], s
[i
+3], s
[i
+4], s
[i
+5]);
1957 case 0x1A: // vvcurveto
1958 case 0x1B: // hhcurveto
1959 if (sp
< 4) return STBTT__CSERR("(vv|hh)curveto stack");
1961 if (sp
& 1) { f
= s
[i
]; i
++; }
1962 for (; i
+ 3 < sp
; i
+= 4) {
1964 stbtt__csctx_rccurve_to(c
, s
[i
], f
, s
[i
+1], s
[i
+2], s
[i
+3], 0.0);
1966 stbtt__csctx_rccurve_to(c
, f
, s
[i
], s
[i
+1], s
[i
+2], 0.0, s
[i
+3]);
1971 case 0x0A: // callsubr
1973 if (info
->fdselect
.size
)
1974 subrs
= stbtt__cid_get_glyph_subrs(info
, glyph_index
);
1978 case 0x1D: // callgsubr
1979 if (sp
< 1) return STBTT__CSERR("call(g|)subr stack");
1981 if (subr_stack_height
>= 10) return STBTT__CSERR("recursion limit");
1982 subr_stack
[subr_stack_height
++] = b
;
1983 b
= stbtt__get_subr(b0
== 0x0A ? subrs
: info
->gsubrs
, v
);
1984 if (b
.size
== 0) return STBTT__CSERR("subr not found");
1989 case 0x0B: // return
1990 if (subr_stack_height
<= 0) return STBTT__CSERR("return outside subr");
1991 b
= subr_stack
[--subr_stack_height
];
1995 case 0x0E: // endchar
1996 stbtt__csctx_close_shape(c
);
1999 case 0x0C: { // two-byte escape
2000 float dx1
, dx2
, dx3
, dx4
, dx5
, dx6
, dy1
, dy2
, dy3
, dy4
, dy5
, dy6
;
2002 int b1
= stbtt__buf_get8(&b
);
2004 // @TODO These "flex" implementations ignore the flex-depth and resolution,
2005 // and always draw beziers.
2007 if (sp
< 7) return STBTT__CSERR("hflex stack");
2015 stbtt__csctx_rccurve_to(c
, dx1
, 0, dx2
, dy2
, dx3
, 0);
2016 stbtt__csctx_rccurve_to(c
, dx4
, 0, dx5
, -dy2
, dx6
, 0);
2020 if (sp
< 13) return STBTT__CSERR("flex stack");
2034 stbtt__csctx_rccurve_to(c
, dx1
, dy1
, dx2
, dy2
, dx3
, dy3
);
2035 stbtt__csctx_rccurve_to(c
, dx4
, dy4
, dx5
, dy5
, dx6
, dy6
);
2038 case 0x24: // hflex1
2039 if (sp
< 9) return STBTT__CSERR("hflex1 stack");
2049 stbtt__csctx_rccurve_to(c
, dx1
, dy1
, dx2
, dy2
, dx3
, 0);
2050 stbtt__csctx_rccurve_to(c
, dx4
, 0, dx5
, dy5
, dx6
, -(dy1
+dy2
+dy5
));
2054 if (sp
< 11) return STBTT__CSERR("flex1 stack");
2066 dx
= dx1
+dx2
+dx3
+dx4
+dx5
;
2067 dy
= dy1
+dy2
+dy3
+dy4
+dy5
;
2068 if (STBTT_fabs(dx
) > STBTT_fabs(dy
))
2072 stbtt__csctx_rccurve_to(c
, dx1
, dy1
, dx2
, dy2
, dx3
, dy3
);
2073 stbtt__csctx_rccurve_to(c
, dx4
, dy4
, dx5
, dy5
, dx6
, dy6
);
2077 return STBTT__CSERR("unimplemented");
2082 if (b0
!= 255 && b0
!= 28 && (b0
< 32 || b0
> 254))
2083 return STBTT__CSERR("reserved operator");
2087 f
= (float)stbtt__buf_get32(&b
) / 0x10000;
2089 stbtt__buf_skip(&b
, -1);
2090 f
= (float)(stbtt_int16
)stbtt__cff_int(&b
);
2092 if (sp
>= 48) return STBTT__CSERR("push stack overflow");
2097 if (clear_stack
) sp
= 0;
2099 return STBTT__CSERR("no endchar");
2104 static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo
*info
, int glyph_index
, stbtt_vertex
**pvertices
)
2106 // runs the charstring twice, once to count and once to output (to avoid realloc)
2107 stbtt__csctx count_ctx
= STBTT__CSCTX_INIT(1);
2108 stbtt__csctx output_ctx
= STBTT__CSCTX_INIT(0);
2109 if (stbtt__run_charstring(info
, glyph_index
, &count_ctx
)) {
2110 *pvertices
= (stbtt_vertex
*)STBTT_malloc(count_ctx
.num_vertices
*sizeof(stbtt_vertex
), info
->userdata
);
2111 output_ctx
.pvertices
= *pvertices
;
2112 if (stbtt__run_charstring(info
, glyph_index
, &output_ctx
)) {
2113 STBTT_assert(output_ctx
.num_vertices
== count_ctx
.num_vertices
);
2114 return output_ctx
.num_vertices
;
2121 static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo
*info
, int glyph_index
, int *x0
, int *y0
, int *x1
, int *y1
)
2123 stbtt__csctx c
= STBTT__CSCTX_INIT(1);
2124 int r
= stbtt__run_charstring(info
, glyph_index
, &c
);
2126 *x0
= r
? c
.min_x
: 0;
2127 *y0
= r
? c
.min_y
: 0;
2128 *x1
= r
? c
.max_x
: 0;
2129 *y1
= r
? c
.max_y
: 0;
2131 return r
? c
.num_vertices
: 0;
2134 STBTT_DEF
int stbtt_GetGlyphShape(const stbtt_fontinfo
*info
, int glyph_index
, stbtt_vertex
**pvertices
)
2136 if (!info
->cff
.size
)
2137 return stbtt__GetGlyphShapeTT(info
, glyph_index
, pvertices
);
2139 return stbtt__GetGlyphShapeT2(info
, glyph_index
, pvertices
);
2142 STBTT_DEF
void stbtt_GetGlyphHMetrics(const stbtt_fontinfo
*info
, int glyph_index
, int *advanceWidth
, int *leftSideBearing
)
2144 stbtt_uint16 numOfLongHorMetrics
= ttUSHORT(info
->data
+info
->hhea
+ 34);
2145 if (glyph_index
< numOfLongHorMetrics
) {
2146 if (advanceWidth
) *advanceWidth
= ttSHORT(info
->data
+ info
->hmtx
+ 4*glyph_index
);
2147 if (leftSideBearing
) *leftSideBearing
= ttSHORT(info
->data
+ info
->hmtx
+ 4*glyph_index
+ 2);
2149 if (advanceWidth
) *advanceWidth
= ttSHORT(info
->data
+ info
->hmtx
+ 4*(numOfLongHorMetrics
-1));
2150 if (leftSideBearing
) *leftSideBearing
= ttSHORT(info
->data
+ info
->hmtx
+ 4*numOfLongHorMetrics
+ 2*(glyph_index
- numOfLongHorMetrics
));
2154 STBTT_DEF
int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo
*info
, int glyph1
, int glyph2
)
2156 stbtt_uint8
*data
= info
->data
+ info
->kern
;
2157 stbtt_uint32 needle
, straw
;
2160 // we only look at the first table. it must be 'horizontal' and format 0.
2163 if (ttUSHORT(data
+2) < 1) // number of tables, need at least 1
2165 if (ttUSHORT(data
+8) != 1) // horizontal flag must be set in format
2169 r
= ttUSHORT(data
+10) - 1;
2170 needle
= glyph1
<< 16 | glyph2
;
2173 straw
= ttULONG(data
+18+(m
*6)); // note: unaligned read
2176 else if (needle
> straw
)
2179 return ttSHORT(data
+22+(m
*6));
2184 STBTT_DEF
int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo
*info
, int ch1
, int ch2
)
2186 if (!info
->kern
) // if no kerning table, don't waste time looking up both codepoint->glyphs
2188 return stbtt_GetGlyphKernAdvance(info
, stbtt_FindGlyphIndex(info
,ch1
), stbtt_FindGlyphIndex(info
,ch2
));
2191 STBTT_DEF
void stbtt_GetCodepointHMetrics(const stbtt_fontinfo
*info
, int codepoint
, int *advanceWidth
, int *leftSideBearing
)
2193 stbtt_GetGlyphHMetrics(info
, stbtt_FindGlyphIndex(info
,codepoint
), advanceWidth
, leftSideBearing
);
2196 STBTT_DEF
void stbtt_GetFontVMetrics(const stbtt_fontinfo
*info
, int *ascent
, int *descent
, int *lineGap
)
2198 if (ascent
) *ascent
= ttSHORT(info
->data
+info
->hhea
+ 4);
2199 if (descent
) *descent
= ttSHORT(info
->data
+info
->hhea
+ 6);
2200 if (lineGap
) *lineGap
= ttSHORT(info
->data
+info
->hhea
+ 8);
2203 STBTT_DEF
void stbtt_GetFontBoundingBox(const stbtt_fontinfo
*info
, int *x0
, int *y0
, int *x1
, int *y1
)
2205 *x0
= ttSHORT(info
->data
+ info
->head
+ 36);
2206 *y0
= ttSHORT(info
->data
+ info
->head
+ 38);
2207 *x1
= ttSHORT(info
->data
+ info
->head
+ 40);
2208 *y1
= ttSHORT(info
->data
+ info
->head
+ 42);
2211 STBTT_DEF
float stbtt_ScaleForPixelHeight(const stbtt_fontinfo
*info
, float height
)
2213 int fheight
= ttSHORT(info
->data
+ info
->hhea
+ 4) - ttSHORT(info
->data
+ info
->hhea
+ 6);
2214 return (float) height
/ fheight
;
2217 STBTT_DEF
float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo
*info
, float pixels
)
2219 int unitsPerEm
= ttUSHORT(info
->data
+ info
->head
+ 18);
2220 return pixels
/ unitsPerEm
;
2223 STBTT_DEF
void stbtt_FreeShape(const stbtt_fontinfo
*info
, stbtt_vertex
*v
)
2225 STBTT_free(v
, info
->userdata
);
2228 //////////////////////////////////////////////////////////////////////////////
2230 // antialiasing software rasterizer
2233 STBTT_DEF
void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo
*font
, int glyph
, float scale_x
, float scale_y
,float shift_x
, float shift_y
, int *ix0
, int *iy0
, int *ix1
, int *iy1
)
2235 int x0
=0,y0
=0,x1
,y1
; // =0 suppresses compiler warning
2236 if (!stbtt_GetGlyphBox(font
, glyph
, &x0
,&y0
,&x1
,&y1
)) {
2237 // e.g. space character
2243 // move to integral bboxes (treating pixels as little squares, what pixels get touched)?
2244 if (ix0
) *ix0
= STBTT_ifloor( x0
* scale_x
+ shift_x
);
2245 if (iy0
) *iy0
= STBTT_ifloor(-y1
* scale_y
+ shift_y
);
2246 if (ix1
) *ix1
= STBTT_iceil ( x1
* scale_x
+ shift_x
);
2247 if (iy1
) *iy1
= STBTT_iceil (-y0
* scale_y
+ shift_y
);
2251 STBTT_DEF
void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo
*font
, int glyph
, float scale_x
, float scale_y
, int *ix0
, int *iy0
, int *ix1
, int *iy1
)
2253 stbtt_GetGlyphBitmapBoxSubpixel(font
, glyph
, scale_x
, scale_y
,0.0f
,0.0f
, ix0
, iy0
, ix1
, iy1
);
2256 STBTT_DEF
void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo
*font
, int codepoint
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int *ix0
, int *iy0
, int *ix1
, int *iy1
)
2258 stbtt_GetGlyphBitmapBoxSubpixel(font
, stbtt_FindGlyphIndex(font
,codepoint
), scale_x
, scale_y
,shift_x
,shift_y
, ix0
,iy0
,ix1
,iy1
);
2261 STBTT_DEF
void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo
*font
, int codepoint
, float scale_x
, float scale_y
, int *ix0
, int *iy0
, int *ix1
, int *iy1
)
2263 stbtt_GetCodepointBitmapBoxSubpixel(font
, codepoint
, scale_x
, scale_y
,0.0f
,0.0f
, ix0
,iy0
,ix1
,iy1
);
2266 //////////////////////////////////////////////////////////////////////////////
2270 typedef struct stbtt__hheap_chunk
2272 struct stbtt__hheap_chunk
*next
;
2273 } stbtt__hheap_chunk
;
2275 typedef struct stbtt__hheap
2277 struct stbtt__hheap_chunk
*head
;
2279 int num_remaining_in_head_chunk
;
2282 static void *stbtt__hheap_alloc(stbtt__hheap
*hh
, size_t size
, void *userdata
)
2284 if (hh
->first_free
) {
2285 void *p
= hh
->first_free
;
2286 hh
->first_free
= * (void **) p
;
2289 if (hh
->num_remaining_in_head_chunk
== 0) {
2290 int count
= (size
< 32 ? 2000 : size
< 128 ? 800 : 100);
2291 stbtt__hheap_chunk
*c
= (stbtt__hheap_chunk
*) STBTT_malloc(sizeof(stbtt__hheap_chunk
) + size
* count
, userdata
);
2296 hh
->num_remaining_in_head_chunk
= count
;
2298 --hh
->num_remaining_in_head_chunk
;
2299 return (char *) (hh
->head
) + size
* hh
->num_remaining_in_head_chunk
;
2303 static void stbtt__hheap_free(stbtt__hheap
*hh
, void *p
)
2305 *(void **) p
= hh
->first_free
;
2309 static void stbtt__hheap_cleanup(stbtt__hheap
*hh
, void *userdata
)
2311 stbtt__hheap_chunk
*c
= hh
->head
;
2313 stbtt__hheap_chunk
*n
= c
->next
;
2314 STBTT_free(c
, userdata
);
2319 typedef struct stbtt__edge
{
2325 typedef struct stbtt__active_edge
2327 struct stbtt__active_edge
*next
;
2328 #if STBTT_RASTERIZER_VERSION==1
2332 #elif STBTT_RASTERIZER_VERSION==2
2338 #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
2340 } stbtt__active_edge
;
2342 #if STBTT_RASTERIZER_VERSION == 1
2343 #define STBTT_FIXSHIFT 10
2344 #define STBTT_FIX (1 << STBTT_FIXSHIFT)
2345 #define STBTT_FIXMASK (STBTT_FIX-1)
2347 static stbtt__active_edge
*stbtt__new_active(stbtt__hheap
*hh
, stbtt__edge
*e
, int off_x
, float start_point
, void *userdata
)
2349 stbtt__active_edge
*z
= (stbtt__active_edge
*) stbtt__hheap_alloc(hh
, sizeof(*z
), userdata
);
2350 float dxdy
= (e
->x1
- e
->x0
) / (e
->y1
- e
->y0
);
2351 STBTT_assert(z
!= NULL
);
2354 // round dx down to avoid overshooting
2356 z
->dx
= -STBTT_ifloor(STBTT_FIX
* -dxdy
);
2358 z
->dx
= STBTT_ifloor(STBTT_FIX
* dxdy
);
2360 z
->x
= STBTT_ifloor(STBTT_FIX
* e
->x0
+ z
->dx
* (start_point
- e
->y0
)); // use z->dx so when we offset later it's by the same amount
2361 z
->x
-= off_x
* STBTT_FIX
;
2365 z
->direction
= e
->invert
? 1 : -1;
2368 #elif STBTT_RASTERIZER_VERSION == 2
2369 static stbtt__active_edge
*stbtt__new_active(stbtt__hheap
*hh
, stbtt__edge
*e
, int off_x
, float start_point
, void *userdata
)
2371 stbtt__active_edge
*z
= (stbtt__active_edge
*) stbtt__hheap_alloc(hh
, sizeof(*z
), userdata
);
2372 float dxdy
= (e
->x1
- e
->x0
) / (e
->y1
- e
->y0
);
2373 STBTT_assert(z
!= NULL
);
2374 //STBTT_assert(e->y0 <= start_point);
2377 z
->fdy
= dxdy
!= 0.0f
? (1.0f
/dxdy
) : 0.0f
;
2378 z
->fx
= e
->x0
+ dxdy
* (start_point
- e
->y0
);
2380 z
->direction
= e
->invert
? 1.0f
: -1.0f
;
2387 #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
2390 #if STBTT_RASTERIZER_VERSION == 1
2391 // note: this routine clips fills that extend off the edges... ideally this
2392 // wouldn't happen, but it could happen if the truetype glyph bounding boxes
2393 // are wrong, or if the user supplies a too-small bitmap
2394 static void stbtt__fill_active_edges(unsigned char *scanline
, int len
, stbtt__active_edge
*e
, int max_weight
)
2396 // non-zero winding fill
2401 // if we're currently at zero, we need to record the edge start point
2402 x0
= e
->x
; w
+= e
->direction
;
2404 int x1
= e
->x
; w
+= e
->direction
;
2405 // if we went to zero, we need to draw
2407 int i
= x0
>> STBTT_FIXSHIFT
;
2408 int j
= x1
>> STBTT_FIXSHIFT
;
2410 if (i
< len
&& j
>= 0) {
2412 // x0,x1 are the same pixel, so compute combined coverage
2413 scanline
[i
] = scanline
[i
] + (stbtt_uint8
) ((x1
- x0
) * max_weight
>> STBTT_FIXSHIFT
);
2415 if (i
>= 0) // add antialiasing for x0
2416 scanline
[i
] = scanline
[i
] + (stbtt_uint8
) (((STBTT_FIX
- (x0
& STBTT_FIXMASK
)) * max_weight
) >> STBTT_FIXSHIFT
);
2420 if (j
< len
) // add antialiasing for x1
2421 scanline
[j
] = scanline
[j
] + (stbtt_uint8
) (((x1
& STBTT_FIXMASK
) * max_weight
) >> STBTT_FIXSHIFT
);
2425 for (++i
; i
< j
; ++i
) // fill pixels between x0 and x1
2426 scanline
[i
] = scanline
[i
] + (stbtt_uint8
) max_weight
;
2436 static void stbtt__rasterize_sorted_edges(stbtt__bitmap
*result
, stbtt__edge
*e
, int n
, int vsubsample
, int off_x
, int off_y
, void *userdata
)
2438 stbtt__hheap hh
= { 0, 0, 0 };
2439 stbtt__active_edge
*active
= NULL
;
2441 int max_weight
= (255 / vsubsample
); // weight per vertical scanline
2442 int s
; // vertical subsample index
2443 unsigned char scanline_data
[512], *scanline
;
2445 if (result
->w
> 512)
2446 scanline
= (unsigned char *) STBTT_malloc(result
->w
, userdata
);
2448 scanline
= scanline_data
;
2450 y
= off_y
* vsubsample
;
2451 e
[n
].y0
= (off_y
+ result
->h
) * (float) vsubsample
+ 1;
2453 while (j
< result
->h
) {
2454 STBTT_memset(scanline
, 0, result
->w
);
2455 for (s
=0; s
< vsubsample
; ++s
) {
2456 // find center of pixel for this scanline
2457 float scan_y
= y
+ 0.5f
;
2458 stbtt__active_edge
**step
= &active
;
2460 // update all active edges;
2461 // remove all active edges that terminate before the center of this scanline
2463 stbtt__active_edge
* z
= *step
;
2464 if (z
->ey
<= scan_y
) {
2465 *step
= z
->next
; // delete from list
2466 STBTT_assert(z
->direction
);
2468 stbtt__hheap_free(&hh
, z
);
2470 z
->x
+= z
->dx
; // advance to position for current scanline
2471 step
= &((*step
)->next
); // advance through list
2475 // resort the list if needed
2479 while (*step
&& (*step
)->next
) {
2480 if ((*step
)->x
> (*step
)->next
->x
) {
2481 stbtt__active_edge
*t
= *step
;
2482 stbtt__active_edge
*q
= t
->next
;
2489 step
= &(*step
)->next
;
2491 if (!changed
) break;
2494 // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
2495 while (e
->y0
<= scan_y
) {
2496 if (e
->y1
> scan_y
) {
2497 stbtt__active_edge
*z
= stbtt__new_active(&hh
, e
, off_x
, scan_y
, userdata
);
2499 // find insertion point
2502 else if (z
->x
< active
->x
) {
2507 // find thing to insert AFTER
2508 stbtt__active_edge
*p
= active
;
2509 while (p
->next
&& p
->next
->x
< z
->x
)
2511 // at this point, p->next->x is NOT < z->x
2520 // now process all active edges in XOR fashion
2522 stbtt__fill_active_edges(scanline
, result
->w
, active
, max_weight
);
2526 STBTT_memcpy(result
->pixels
+ j
* result
->stride
, scanline
, result
->w
);
2530 stbtt__hheap_cleanup(&hh
, userdata
);
2532 if (scanline
!= scanline_data
)
2533 STBTT_free(scanline
, userdata
);
2536 #elif STBTT_RASTERIZER_VERSION == 2
2538 // the edge passed in here does not cross the vertical line at x or the vertical line at x+1
2539 // (i.e. it has already been clipped to those)
2540 static void stbtt__handle_clipped_edge(float *scanline
, int x
, stbtt__active_edge
*e
, float x0
, float y0
, float x1
, float y1
)
2542 if (y0
== y1
) return;
2543 STBTT_assert(y0
< y1
);
2544 STBTT_assert(e
->sy
<= e
->ey
);
2545 if (y0
> e
->ey
) return;
2546 if (y1
< e
->sy
) return;
2548 x0
+= (x1
-x0
) * (e
->sy
- y0
) / (y1
-y0
);
2552 x1
+= (x1
-x0
) * (e
->ey
- y1
) / (y1
-y0
);
2557 STBTT_assert(x1
<= x
+1);
2559 STBTT_assert(x1
>= x
);
2561 STBTT_assert(x1
<= x
);
2563 STBTT_assert(x1
>= x
+1);
2565 STBTT_assert(x1
>= x
&& x1
<= x
+1);
2567 if (x0
<= x
&& x1
<= x
)
2568 scanline
[x
] += e
->direction
* (y1
-y0
);
2569 else if (x0
>= x
+1 && x1
>= x
+1)
2572 STBTT_assert(x0
>= x
&& x0
<= x
+1 && x1
>= x
&& x1
<= x
+1);
2573 scanline
[x
] += e
->direction
* (y1
-y0
) * (1-((x0
-x
)+(x1
-x
))/2); // coverage = 1 - average x position
2577 static void stbtt__fill_active_edges_new(float *scanline
, float *scanline_fill
, int len
, stbtt__active_edge
*e
, float y_top
)
2579 float y_bottom
= y_top
+1;
2582 // brute force every pixel
2584 // compute intersection points with top & bottom
2585 STBTT_assert(e
->ey
>= y_top
);
2591 stbtt__handle_clipped_edge(scanline
,(int) x0
,e
, x0
,y_top
, x0
,y_bottom
);
2592 stbtt__handle_clipped_edge(scanline_fill
-1,(int) x0
+1,e
, x0
,y_top
, x0
,y_bottom
);
2594 stbtt__handle_clipped_edge(scanline_fill
-1,0,e
, x0
,y_top
, x0
,y_bottom
);
2601 float x_top
, x_bottom
;
2604 STBTT_assert(e
->sy
<= y_bottom
&& e
->ey
>= y_top
);
2606 // compute endpoints of line segment clipped to this scanline (if the
2607 // line segment starts on this scanline. x0 is the intersection of the
2608 // line with y_top, but that may be off the line segment.
2609 if (e
->sy
> y_top
) {
2610 x_top
= x0
+ dx
* (e
->sy
- y_top
);
2616 if (e
->ey
< y_bottom
) {
2617 x_bottom
= x0
+ dx
* (e
->ey
- y_top
);
2624 if (x_top
>= 0 && x_bottom
>= 0 && x_top
< len
&& x_bottom
< len
) {
2625 // from here on, we don't have to range check x values
2627 if ((int) x_top
== (int) x_bottom
) {
2629 // simple case, only spans one pixel
2630 int x
= (int) x_top
;
2632 STBTT_assert(x
>= 0 && x
< len
);
2633 scanline
[x
] += e
->direction
* (1-((x_top
- x
) + (x_bottom
-x
))/2) * height
;
2634 scanline_fill
[x
] += e
->direction
* height
; // everything right of this pixel is filled
2637 float y_crossing
, step
, sign
, area
;
2639 if (x_top
> x_bottom
) {
2640 // flip scanline vertically; signed area is the same
2642 sy0
= y_bottom
- (sy0
- y_top
);
2643 sy1
= y_bottom
- (sy1
- y_top
);
2644 t
= sy0
, sy0
= sy1
, sy1
= t
;
2645 t
= x_bottom
, x_bottom
= x_top
, x_top
= t
;
2648 t
= x0
, x0
= xb
, xb
= t
;
2652 x2
= (int) x_bottom
;
2653 // compute intersection with y axis at x1+1
2654 y_crossing
= (x1
+1 - x0
) * dy
+ y_top
;
2656 sign
= e
->direction
;
2657 // area of the rectangle covered from y0..y_crossing
2658 area
= sign
* (y_crossing
-sy0
);
2659 // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing)
2660 scanline
[x1
] += area
* (1-((x_top
- x1
)+(x1
+1-x1
))/2);
2663 for (x
= x1
+1; x
< x2
; ++x
) {
2664 scanline
[x
] += area
+ step
/2;
2667 y_crossing
+= dy
* (x2
- (x1
+1));
2669 STBTT_assert(STBTT_fabs(area
) <= 1.01f
);
2671 scanline
[x2
] += area
+ sign
* (1-((x2
-x2
)+(x_bottom
-x2
))/2) * (sy1
-y_crossing
);
2673 scanline_fill
[x2
] += sign
* (sy1
-sy0
);
2676 // if edge goes outside of box we're drawing, we require
2677 // clipping logic. since this does not match the intended use
2678 // of this library, we use a different, very slow brute
2679 // force implementation
2681 for (x
=0; x
< len
; ++x
) {
2684 // there can be up to two intersections with the pixel. any intersection
2685 // with left or right edges can be handled by splitting into two (or three)
2686 // regions. intersections with top & bottom do not necessitate case-wise logic.
2688 // the old way of doing this found the intersections with the left & right edges,
2689 // then used some simple logic to produce up to three segments in sorted order
2690 // from top-to-bottom. however, this had a problem: if an x edge was epsilon
2691 // across the x border, then the corresponding y position might not be distinct
2692 // from the other y segment, and it might ignored as an empty segment. to avoid
2693 // that, we need to explicitly produce segments based on x positions.
2695 // rename variables to clear pairs
2697 float x1
= (float) (x
);
2698 float x2
= (float) (x
+1);
2700 float y3
= y_bottom
;
2703 // x = e->x + e->dx * (y-y_top)
2704 // (y-y_top) = (x - e->x) / e->dx
2705 // y = (x - e->x) / e->dx + y_top
2706 y1
= (x
- x0
) / dx
+ y_top
;
2707 y2
= (x
+1 - x0
) / dx
+ y_top
;
2709 if (x0
< x1
&& x3
> x2
) { // three segments descending down-right
2710 stbtt__handle_clipped_edge(scanline
,x
,e
, x0
,y0
, x1
,y1
);
2711 stbtt__handle_clipped_edge(scanline
,x
,e
, x1
,y1
, x2
,y2
);
2712 stbtt__handle_clipped_edge(scanline
,x
,e
, x2
,y2
, x3
,y3
);
2713 } else if (x3
< x1
&& x0
> x2
) { // three segments descending down-left
2714 stbtt__handle_clipped_edge(scanline
,x
,e
, x0
,y0
, x2
,y2
);
2715 stbtt__handle_clipped_edge(scanline
,x
,e
, x2
,y2
, x1
,y1
);
2716 stbtt__handle_clipped_edge(scanline
,x
,e
, x1
,y1
, x3
,y3
);
2717 } else if (x0
< x1
&& x3
> x1
) { // two segments across x, down-right
2718 stbtt__handle_clipped_edge(scanline
,x
,e
, x0
,y0
, x1
,y1
);
2719 stbtt__handle_clipped_edge(scanline
,x
,e
, x1
,y1
, x3
,y3
);
2720 } else if (x3
< x1
&& x0
> x1
) { // two segments across x, down-left
2721 stbtt__handle_clipped_edge(scanline
,x
,e
, x0
,y0
, x1
,y1
);
2722 stbtt__handle_clipped_edge(scanline
,x
,e
, x1
,y1
, x3
,y3
);
2723 } else if (x0
< x2
&& x3
> x2
) { // two segments across x+1, down-right
2724 stbtt__handle_clipped_edge(scanline
,x
,e
, x0
,y0
, x2
,y2
);
2725 stbtt__handle_clipped_edge(scanline
,x
,e
, x2
,y2
, x3
,y3
);
2726 } else if (x3
< x2
&& x0
> x2
) { // two segments across x+1, down-left
2727 stbtt__handle_clipped_edge(scanline
,x
,e
, x0
,y0
, x2
,y2
);
2728 stbtt__handle_clipped_edge(scanline
,x
,e
, x2
,y2
, x3
,y3
);
2729 } else { // one segment
2730 stbtt__handle_clipped_edge(scanline
,x
,e
, x0
,y0
, x3
,y3
);
2739 // directly AA rasterize edges w/o supersampling
2740 static void stbtt__rasterize_sorted_edges(stbtt__bitmap
*result
, stbtt__edge
*e
, int n
, int vsubsample
, int off_x
, int off_y
, void *userdata
)
2742 stbtt__hheap hh
= { 0, 0, 0 };
2743 stbtt__active_edge
*active
= NULL
;
2745 float scanline_data
[129], *scanline
, *scanline2
;
2747 STBTT__NOTUSED(vsubsample
);
2750 scanline
= (float *) STBTT_malloc((result
->w
*2+1) * sizeof(float), userdata
);
2752 scanline
= scanline_data
;
2754 scanline2
= scanline
+ result
->w
;
2757 e
[n
].y0
= (float) (off_y
+ result
->h
) + 1;
2759 while (j
< result
->h
) {
2760 // find center of pixel for this scanline
2761 float scan_y_top
= y
+ 0.0f
;
2762 float scan_y_bottom
= y
+ 1.0f
;
2763 stbtt__active_edge
**step
= &active
;
2765 STBTT_memset(scanline
, 0, result
->w
*sizeof(scanline
[0]));
2766 STBTT_memset(scanline2
, 0, (result
->w
+1)*sizeof(scanline
[0]));
2768 // update all active edges;
2769 // remove all active edges that terminate before the top of this scanline
2771 stbtt__active_edge
* z
= *step
;
2772 if (z
->ey
<= scan_y_top
) {
2773 *step
= z
->next
; // delete from list
2774 STBTT_assert(z
->direction
);
2776 stbtt__hheap_free(&hh
, z
);
2778 step
= &((*step
)->next
); // advance through list
2782 // insert all edges that start before the bottom of this scanline
2783 while (e
->y0
<= scan_y_bottom
) {
2784 if (e
->y0
!= e
->y1
) {
2785 stbtt__active_edge
*z
= stbtt__new_active(&hh
, e
, off_x
, scan_y_top
, userdata
);
2787 STBTT_assert(z
->ey
>= scan_y_top
);
2796 // now process all active edges
2798 stbtt__fill_active_edges_new(scanline
, scanline2
+1, result
->w
, active
, scan_y_top
);
2802 for (i
=0; i
< result
->w
; ++i
) {
2805 sum
+= scanline2
[i
];
2806 k
= scanline
[i
] + sum
;
2807 k
= (float) STBTT_fabs(k
)*255 + 0.5f
;
2809 if (m
> 255) m
= 255;
2810 result
->pixels
[j
*result
->stride
+ i
] = (unsigned char) m
;
2813 // advance all the edges
2816 stbtt__active_edge
*z
= *step
;
2817 z
->fx
+= z
->fdx
; // advance to position for current scanline
2818 step
= &((*step
)->next
); // advance through list
2825 stbtt__hheap_cleanup(&hh
, userdata
);
2827 if (scanline
!= scanline_data
)
2828 STBTT_free(scanline
, userdata
);
2831 #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
2834 #define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0)
2836 static void stbtt__sort_edges_ins_sort(stbtt__edge
*p
, int n
)
2839 for (i
=1; i
< n
; ++i
) {
2840 stbtt__edge t
= p
[i
], *a
= &t
;
2843 stbtt__edge
*b
= &p
[j
-1];
2844 int c
= STBTT__COMPARE(a
,b
);
2854 static void stbtt__sort_edges_quicksort(stbtt__edge
*p
, int n
)
2856 /* threshhold for transitioning to insertion sort */
2859 int c01
,c12
,c
,m
,i
,j
;
2861 /* compute median of three */
2863 c01
= STBTT__COMPARE(&p
[0],&p
[m
]);
2864 c12
= STBTT__COMPARE(&p
[m
],&p
[n
-1]);
2865 /* if 0 >= mid >= end, or 0 < mid < end, then use mid */
2867 /* otherwise, we'll need to swap something else to middle */
2869 c
= STBTT__COMPARE(&p
[0],&p
[n
-1]);
2870 /* 0>mid && mid<n: 0>n => n; 0<n => 0 */
2871 /* 0<mid && mid>n: 0>n => 0; 0<n => n */
2872 z
= (c
== c12
) ? 0 : n
-1;
2877 /* now p[m] is the median-of-three */
2878 /* swap it to the beginning so it won't move around */
2883 /* partition loop */
2887 /* handling of equality is crucial here */
2888 /* for sentinels & efficiency with duplicates */
2890 if (!STBTT__COMPARE(&p
[i
], &p
[0])) break;
2893 if (!STBTT__COMPARE(&p
[0], &p
[j
])) break;
2895 /* make sure we haven't crossed */
2904 /* recurse on smaller side, iterate on larger */
2906 stbtt__sort_edges_quicksort(p
,j
);
2910 stbtt__sort_edges_quicksort(p
+i
, n
-i
);
2916 static void stbtt__sort_edges(stbtt__edge
*p
, int n
)
2918 stbtt__sort_edges_quicksort(p
, n
);
2919 stbtt__sort_edges_ins_sort(p
, n
);
2927 static void stbtt__rasterize(stbtt__bitmap
*result
, stbtt__point
*pts
, int *wcount
, int windings
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int off_x
, int off_y
, int invert
, void *userdata
)
2929 float y_scale_inv
= invert
? -scale_y
: scale_y
;
2932 #if STBTT_RASTERIZER_VERSION == 1
2933 int vsubsample
= result
->h
< 8 ? 15 : 5;
2934 #elif STBTT_RASTERIZER_VERSION == 2
2937 #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
2939 // vsubsample should divide 255 evenly; otherwise we won't reach full opacity
2941 // now we have to blow out the windings into explicit edge lists
2943 for (i
=0; i
< windings
; ++i
)
2946 e
= (stbtt__edge
*) STBTT_malloc(sizeof(*e
) * (n
+1), userdata
); // add an extra one as a sentinel
2951 for (i
=0; i
< windings
; ++i
) {
2952 stbtt__point
*p
= pts
+ m
;
2955 for (k
=0; k
< wcount
[i
]; j
=k
++) {
2957 // skip the edge if horizontal
2958 if (p
[j
].y
== p
[k
].y
)
2960 // add edge from j to k to the list
2962 if (invert
? p
[j
].y
> p
[k
].y
: p
[j
].y
< p
[k
].y
) {
2966 e
[n
].x0
= p
[a
].x
* scale_x
+ shift_x
;
2967 e
[n
].y0
= (p
[a
].y
* y_scale_inv
+ shift_y
) * vsubsample
;
2968 e
[n
].x1
= p
[b
].x
* scale_x
+ shift_x
;
2969 e
[n
].y1
= (p
[b
].y
* y_scale_inv
+ shift_y
) * vsubsample
;
2974 // now sort the edges by their highest point (should snap to integer, and then by x)
2975 //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
2976 stbtt__sort_edges(e
, n
);
2978 // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
2979 stbtt__rasterize_sorted_edges(result
, e
, n
, vsubsample
, off_x
, off_y
, userdata
);
2981 STBTT_free(e
, userdata
);
2984 static void stbtt__add_point(stbtt__point
*points
, int n
, float x
, float y
)
2986 if (!points
) return; // during first pass, it's unallocated
2991 // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching
2992 static int stbtt__tesselate_curve(stbtt__point
*points
, int *num_points
, float x0
, float y0
, float x1
, float y1
, float x2
, float y2
, float objspace_flatness_squared
, int n
)
2995 float mx
= (x0
+ 2*x1
+ x2
)/4;
2996 float my
= (y0
+ 2*y1
+ y2
)/4;
2997 // versus directly drawn line
2998 float dx
= (x0
+x2
)/2 - mx
;
2999 float dy
= (y0
+y2
)/2 - my
;
3000 if (n
> 16) // 65536 segments on one curve better be enough!
3002 if (dx
*dx
+dy
*dy
> objspace_flatness_squared
) { // half-pixel error allowed... need to be smaller if AA
3003 stbtt__tesselate_curve(points
, num_points
, x0
,y0
, (x0
+x1
)/2.0f
,(y0
+y1
)/2.0f
, mx
,my
, objspace_flatness_squared
,n
+1);
3004 stbtt__tesselate_curve(points
, num_points
, mx
,my
, (x1
+x2
)/2.0f
,(y1
+y2
)/2.0f
, x2
,y2
, objspace_flatness_squared
,n
+1);
3006 stbtt__add_point(points
, *num_points
,x2
,y2
);
3007 *num_points
= *num_points
+1;
3012 static void stbtt__tesselate_cubic(stbtt__point
*points
, int *num_points
, float x0
, float y0
, float x1
, float y1
, float x2
, float y2
, float x3
, float y3
, float objspace_flatness_squared
, int n
)
3014 // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough
3023 float longlen
= (float) (STBTT_sqrt(dx0
*dx0
+dy0
*dy0
)+STBTT_sqrt(dx1
*dx1
+dy1
*dy1
)+STBTT_sqrt(dx2
*dx2
+dy2
*dy2
));
3024 float shortlen
= (float) STBTT_sqrt(dx
*dx
+dy
*dy
);
3025 float flatness_squared
= longlen
*longlen
-shortlen
*shortlen
;
3027 if (n
> 16) // 65536 segments on one curve better be enough!
3030 if (flatness_squared
> objspace_flatness_squared
) {
3031 float x01
= (x0
+x1
)/2;
3032 float y01
= (y0
+y1
)/2;
3033 float x12
= (x1
+x2
)/2;
3034 float y12
= (y1
+y2
)/2;
3035 float x23
= (x2
+x3
)/2;
3036 float y23
= (y2
+y3
)/2;
3038 float xa
= (x01
+x12
)/2;
3039 float ya
= (y01
+y12
)/2;
3040 float xb
= (x12
+x23
)/2;
3041 float yb
= (y12
+y23
)/2;
3043 float mx
= (xa
+xb
)/2;
3044 float my
= (ya
+yb
)/2;
3046 stbtt__tesselate_cubic(points
, num_points
, x0
,y0
, x01
,y01
, xa
,ya
, mx
,my
, objspace_flatness_squared
,n
+1);
3047 stbtt__tesselate_cubic(points
, num_points
, mx
,my
, xb
,yb
, x23
,y23
, x3
,y3
, objspace_flatness_squared
,n
+1);
3049 stbtt__add_point(points
, *num_points
,x3
,y3
);
3050 *num_points
= *num_points
+1;
3054 // returns number of contours
3055 static stbtt__point
*stbtt_FlattenCurves(stbtt_vertex
*vertices
, int num_verts
, float objspace_flatness
, int **contour_lengths
, int *num_contours
, void *userdata
)
3057 stbtt__point
*points
=0;
3060 float objspace_flatness_squared
= objspace_flatness
* objspace_flatness
;
3061 int i
,n
=0,start
=0, pass
;
3063 // count how many "moves" there are to get the contour count
3064 for (i
=0; i
< num_verts
; ++i
)
3065 if (vertices
[i
].type
== STBTT_vmove
)
3069 if (n
== 0) return 0;
3071 *contour_lengths
= (int *) STBTT_malloc(sizeof(**contour_lengths
) * n
, userdata
);
3073 if (*contour_lengths
== 0) {
3078 // make two passes through the points so we don't need to realloc
3079 for (pass
=0; pass
< 2; ++pass
) {
3082 points
= (stbtt__point
*) STBTT_malloc(num_points
* sizeof(points
[0]), userdata
);
3083 if (points
== NULL
) goto error
;
3087 for (i
=0; i
< num_verts
; ++i
) {
3088 switch (vertices
[i
].type
) {
3090 // start the next contour
3092 (*contour_lengths
)[n
] = num_points
- start
;
3096 x
= vertices
[i
].x
, y
= vertices
[i
].y
;
3097 stbtt__add_point(points
, num_points
++, x
,y
);
3100 x
= vertices
[i
].x
, y
= vertices
[i
].y
;
3101 stbtt__add_point(points
, num_points
++, x
, y
);
3104 stbtt__tesselate_curve(points
, &num_points
, x
,y
,
3105 vertices
[i
].cx
, vertices
[i
].cy
,
3106 vertices
[i
].x
, vertices
[i
].y
,
3107 objspace_flatness_squared
, 0);
3108 x
= vertices
[i
].x
, y
= vertices
[i
].y
;
3111 stbtt__tesselate_cubic(points
, &num_points
, x
,y
,
3112 vertices
[i
].cx
, vertices
[i
].cy
,
3113 vertices
[i
].cx1
, vertices
[i
].cy1
,
3114 vertices
[i
].x
, vertices
[i
].y
,
3115 objspace_flatness_squared
, 0);
3116 x
= vertices
[i
].x
, y
= vertices
[i
].y
;
3120 (*contour_lengths
)[n
] = num_points
- start
;
3125 STBTT_free(points
, userdata
);
3126 STBTT_free(*contour_lengths
, userdata
);
3127 *contour_lengths
= 0;
3132 STBTT_DEF
void stbtt_Rasterize(stbtt__bitmap
*result
, float flatness_in_pixels
, stbtt_vertex
*vertices
, int num_verts
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int x_off
, int y_off
, int invert
, void *userdata
)
3134 float scale
= scale_x
> scale_y
? scale_y
: scale_x
;
3135 int winding_count
, *winding_lengths
;
3136 stbtt__point
*windings
= stbtt_FlattenCurves(vertices
, num_verts
, flatness_in_pixels
/ scale
, &winding_lengths
, &winding_count
, userdata
);
3138 stbtt__rasterize(result
, windings
, winding_lengths
, winding_count
, scale_x
, scale_y
, shift_x
, shift_y
, x_off
, y_off
, invert
, userdata
);
3139 STBTT_free(winding_lengths
, userdata
);
3140 STBTT_free(windings
, userdata
);
3144 STBTT_DEF
void stbtt_FreeBitmap(unsigned char *bitmap
, void *userdata
)
3146 STBTT_free(bitmap
, userdata
);
3149 STBTT_DEF
unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo
*info
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int glyph
, int *width
, int *height
, int *xoff
, int *yoff
)
3151 int ix0
,iy0
,ix1
,iy1
;
3153 stbtt_vertex
*vertices
;
3154 int num_verts
= stbtt_GetGlyphShape(info
, glyph
, &vertices
);
3156 if (scale_x
== 0) scale_x
= scale_y
;
3159 STBTT_free(vertices
, info
->userdata
);
3165 stbtt_GetGlyphBitmapBoxSubpixel(info
, glyph
, scale_x
, scale_y
, shift_x
, shift_y
, &ix0
,&iy0
,&ix1
,&iy1
);
3167 // now we get the size
3168 gbm
.w
= (ix1
- ix0
);
3169 gbm
.h
= (iy1
- iy0
);
3170 gbm
.pixels
= NULL
; // in case we error
3172 if (width
) *width
= gbm
.w
;
3173 if (height
) *height
= gbm
.h
;
3174 if (xoff
) *xoff
= ix0
;
3175 if (yoff
) *yoff
= iy0
;
3177 if (gbm
.w
&& gbm
.h
) {
3178 gbm
.pixels
= (unsigned char *) STBTT_malloc(gbm
.w
* gbm
.h
, info
->userdata
);
3182 stbtt_Rasterize(&gbm
, 0.35f
, vertices
, num_verts
, scale_x
, scale_y
, shift_x
, shift_y
, ix0
, iy0
, 1, info
->userdata
);
3185 STBTT_free(vertices
, info
->userdata
);
3189 STBTT_DEF
unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo
*info
, float scale_x
, float scale_y
, int glyph
, int *width
, int *height
, int *xoff
, int *yoff
)
3191 return stbtt_GetGlyphBitmapSubpixel(info
, scale_x
, scale_y
, 0.0f
, 0.0f
, glyph
, width
, height
, xoff
, yoff
);
3194 STBTT_DEF
void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo
*info
, unsigned char *output
, int out_w
, int out_h
, int out_stride
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int glyph
)
3197 stbtt_vertex
*vertices
;
3198 int num_verts
= stbtt_GetGlyphShape(info
, glyph
, &vertices
);
3201 stbtt_GetGlyphBitmapBoxSubpixel(info
, glyph
, scale_x
, scale_y
, shift_x
, shift_y
, &ix0
,&iy0
,0,0);
3202 gbm
.pixels
= output
;
3205 gbm
.stride
= out_stride
;
3208 stbtt_Rasterize(&gbm
, 0.35f
, vertices
, num_verts
, scale_x
, scale_y
, shift_x
, shift_y
, ix0
,iy0
, 1, info
->userdata
);
3210 STBTT_free(vertices
, info
->userdata
);
3213 STBTT_DEF
void stbtt_MakeGlyphBitmap(const stbtt_fontinfo
*info
, unsigned char *output
, int out_w
, int out_h
, int out_stride
, float scale_x
, float scale_y
, int glyph
)
3215 stbtt_MakeGlyphBitmapSubpixel(info
, output
, out_w
, out_h
, out_stride
, scale_x
, scale_y
, 0.0f
,0.0f
, glyph
);
3218 STBTT_DEF
unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo
*info
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int codepoint
, int *width
, int *height
, int *xoff
, int *yoff
)
3220 return stbtt_GetGlyphBitmapSubpixel(info
, scale_x
, scale_y
,shift_x
,shift_y
, stbtt_FindGlyphIndex(info
,codepoint
), width
,height
,xoff
,yoff
);
3223 STBTT_DEF
void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo
*info
, unsigned char *output
, int out_w
, int out_h
, int out_stride
, float scale_x
, float scale_y
, float shift_x
, float shift_y
, int codepoint
)
3225 stbtt_MakeGlyphBitmapSubpixel(info
, output
, out_w
, out_h
, out_stride
, scale_x
, scale_y
, shift_x
, shift_y
, stbtt_FindGlyphIndex(info
,codepoint
));
3228 STBTT_DEF
unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo
*info
, float scale_x
, float scale_y
, int codepoint
, int *width
, int *height
, int *xoff
, int *yoff
)
3230 return stbtt_GetCodepointBitmapSubpixel(info
, scale_x
, scale_y
, 0.0f
,0.0f
, codepoint
, width
,height
,xoff
,yoff
);
3233 STBTT_DEF
void stbtt_MakeCodepointBitmap(const stbtt_fontinfo
*info
, unsigned char *output
, int out_w
, int out_h
, int out_stride
, float scale_x
, float scale_y
, int codepoint
)
3235 stbtt_MakeCodepointBitmapSubpixel(info
, output
, out_w
, out_h
, out_stride
, scale_x
, scale_y
, 0.0f
,0.0f
, codepoint
);
3238 //////////////////////////////////////////////////////////////////////////////
3242 // This is SUPER-CRAPPY packing to keep source code small
3244 static int stbtt_BakeFontBitmap_internal(unsigned char *data
, int offset
, // font location (use offset=0 for plain .ttf)
3245 float pixel_height
, // height of font in pixels
3246 unsigned char *pixels
, int pw
, int ph
, // bitmap to be filled in
3247 int first_char
, int num_chars
, // characters to bake
3248 stbtt_bakedchar
*chardata
)
3251 int x
,y
,bottom_y
, i
;
3254 if (!stbtt_InitFont(&f
, data
, offset
))
3256 STBTT_memset(pixels
, 0, pw
*ph
); // background of 0 around pixels
3260 scale
= stbtt_ScaleForPixelHeight(&f
, pixel_height
);
3262 for (i
=0; i
< num_chars
; ++i
) {
3263 int advance
, lsb
, x0
,y0
,x1
,y1
,gw
,gh
;
3264 int g
= stbtt_FindGlyphIndex(&f
, first_char
+ i
);
3265 stbtt_GetGlyphHMetrics(&f
, g
, &advance
, &lsb
);
3266 stbtt_GetGlyphBitmapBox(&f
, g
, scale
,scale
, &x0
,&y0
,&x1
,&y1
);
3269 if (x
+ gw
+ 1 >= pw
)
3270 y
= bottom_y
, x
= 1; // advance to next row
3271 if (y
+ gh
+ 1 >= ph
) // check if it fits vertically AFTER potentially moving to next row
3273 STBTT_assert(x
+gw
< pw
);
3274 STBTT_assert(y
+gh
< ph
);
3275 stbtt_MakeGlyphBitmap(&f
, pixels
+x
+y
*pw
, gw
,gh
,pw
, scale
,scale
, g
);
3276 chardata
[i
].x0
= (stbtt_int16
) x
;
3277 chardata
[i
].y0
= (stbtt_int16
) y
;
3278 chardata
[i
].x1
= (stbtt_int16
) (x
+ gw
);
3279 chardata
[i
].y1
= (stbtt_int16
) (y
+ gh
);
3280 chardata
[i
].xadvance
= scale
* advance
;
3281 chardata
[i
].xoff
= (float) x0
;
3282 chardata
[i
].yoff
= (float) y0
;
3284 if (y
+gh
+1 > bottom_y
)
3290 STBTT_DEF
void stbtt_GetBakedQuad(stbtt_bakedchar
*chardata
, int pw
, int ph
, int char_index
, float *xpos
, float *ypos
, stbtt_aligned_quad
*q
, int opengl_fillrule
)
3292 float d3d_bias
= opengl_fillrule
? 0 : -0.5f
;
3293 float ipw
= 1.0f
/ pw
, iph
= 1.0f
/ ph
;
3294 stbtt_bakedchar
*b
= chardata
+ char_index
;
3295 int round_x
= STBTT_ifloor((*xpos
+ b
->xoff
) + 0.5f
);
3296 int round_y
= STBTT_ifloor((*ypos
+ b
->yoff
) + 0.5f
);
3298 q
->x0
= round_x
+ d3d_bias
;
3299 q
->y0
= round_y
+ d3d_bias
;
3300 q
->x1
= round_x
+ b
->x1
- b
->x0
+ d3d_bias
;
3301 q
->y1
= round_y
+ b
->y1
- b
->y0
+ d3d_bias
;
3303 q
->s0
= b
->x0
* ipw
;
3304 q
->t0
= b
->y0
* iph
;
3305 q
->s1
= b
->x1
* ipw
;
3306 q
->t1
= b
->y1
* iph
;
3308 *xpos
+= b
->xadvance
;
3311 //////////////////////////////////////////////////////////////////////////////
3313 // rectangle packing replacement routines if you don't have stb_rect_pack.h
3316 #ifndef STB_RECT_PACK_VERSION
3318 typedef int stbrp_coord
;
3320 ////////////////////////////////////////////////////////////////////////////////////
3323 // COMPILER WARNING ?!?!? //
3326 // if you get a compile warning due to these symbols being defined more than //
3327 // once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" //
3329 ////////////////////////////////////////////////////////////////////////////////////
3345 int id
,w
,h
,was_packed
;
3348 static void stbrp_init_target(stbrp_context
*con
, int pw
, int ph
, stbrp_node
*nodes
, int num_nodes
)
3355 STBTT__NOTUSED(nodes
);
3356 STBTT__NOTUSED(num_nodes
);
3359 static void stbrp_pack_rects(stbrp_context
*con
, stbrp_rect
*rects
, int num_rects
)
3362 for (i
=0; i
< num_rects
; ++i
) {
3363 if (con
->x
+ rects
[i
].w
> con
->width
) {
3365 con
->y
= con
->bottom_y
;
3367 if (con
->y
+ rects
[i
].h
> con
->height
)
3369 rects
[i
].x
= con
->x
;
3370 rects
[i
].y
= con
->y
;
3371 rects
[i
].was_packed
= 1;
3372 con
->x
+= rects
[i
].w
;
3373 if (con
->y
+ rects
[i
].h
> con
->bottom_y
)
3374 con
->bottom_y
= con
->y
+ rects
[i
].h
;
3376 for ( ; i
< num_rects
; ++i
)
3377 rects
[i
].was_packed
= 0;
3381 //////////////////////////////////////////////////////////////////////////////
3385 // This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If
3386 // stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.
3388 STBTT_DEF
int stbtt_PackBegin(stbtt_pack_context
*spc
, unsigned char *pixels
, int pw
, int ph
, int stride_in_bytes
, int padding
, void *alloc_context
)
3390 stbrp_context
*context
= (stbrp_context
*) STBTT_malloc(sizeof(*context
) ,alloc_context
);
3391 int num_nodes
= pw
- padding
;
3392 stbrp_node
*nodes
= (stbrp_node
*) STBTT_malloc(sizeof(*nodes
) * num_nodes
,alloc_context
);
3394 if (context
== NULL
|| nodes
== NULL
) {
3395 if (context
!= NULL
) STBTT_free(context
, alloc_context
);
3396 if (nodes
!= NULL
) STBTT_free(nodes
, alloc_context
);
3400 spc
->user_allocator_context
= alloc_context
;
3403 spc
->pixels
= pixels
;
3404 spc
->pack_info
= context
;
3406 spc
->padding
= padding
;
3407 spc
->stride_in_bytes
= stride_in_bytes
!= 0 ? stride_in_bytes
: pw
;
3408 spc
->h_oversample
= 1;
3409 spc
->v_oversample
= 1;
3411 stbrp_init_target(context
, pw
-padding
, ph
-padding
, nodes
, num_nodes
);
3414 STBTT_memset(pixels
, 0, pw
*ph
); // background of 0 around pixels
3419 STBTT_DEF
void stbtt_PackEnd (stbtt_pack_context
*spc
)
3421 STBTT_free(spc
->nodes
, spc
->user_allocator_context
);
3422 STBTT_free(spc
->pack_info
, spc
->user_allocator_context
);
3425 STBTT_DEF
void stbtt_PackSetOversampling(stbtt_pack_context
*spc
, unsigned int h_oversample
, unsigned int v_oversample
)
3427 STBTT_assert(h_oversample
<= STBTT_MAX_OVERSAMPLE
);
3428 STBTT_assert(v_oversample
<= STBTT_MAX_OVERSAMPLE
);
3429 if (h_oversample
<= STBTT_MAX_OVERSAMPLE
)
3430 spc
->h_oversample
= h_oversample
;
3431 if (v_oversample
<= STBTT_MAX_OVERSAMPLE
)
3432 spc
->v_oversample
= v_oversample
;
3435 #define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1)
3437 static void stbtt__h_prefilter(unsigned char *pixels
, int w
, int h
, int stride_in_bytes
, unsigned int kernel_width
)
3439 unsigned char buffer
[STBTT_MAX_OVERSAMPLE
];
3440 int safe_w
= w
- kernel_width
;
3442 STBTT_memset(buffer
, 0, STBTT_MAX_OVERSAMPLE
); // suppress bogus warning from VS2013 -analyze
3443 for (j
=0; j
< h
; ++j
) {
3446 STBTT_memset(buffer
, 0, kernel_width
);
3450 // make kernel_width a constant in common cases so compiler can optimize out the divide
3451 switch (kernel_width
) {
3453 for (i
=0; i
<= safe_w
; ++i
) {
3454 total
+= pixels
[i
] - buffer
[i
& STBTT__OVER_MASK
];
3455 buffer
[(i
+kernel_width
) & STBTT__OVER_MASK
] = pixels
[i
];
3456 pixels
[i
] = (unsigned char) (total
/ 2);
3460 for (i
=0; i
<= safe_w
; ++i
) {
3461 total
+= pixels
[i
] - buffer
[i
& STBTT__OVER_MASK
];
3462 buffer
[(i
+kernel_width
) & STBTT__OVER_MASK
] = pixels
[i
];
3463 pixels
[i
] = (unsigned char) (total
/ 3);
3467 for (i
=0; i
<= safe_w
; ++i
) {
3468 total
+= pixels
[i
] - buffer
[i
& STBTT__OVER_MASK
];
3469 buffer
[(i
+kernel_width
) & STBTT__OVER_MASK
] = pixels
[i
];
3470 pixels
[i
] = (unsigned char) (total
/ 4);
3474 for (i
=0; i
<= safe_w
; ++i
) {
3475 total
+= pixels
[i
] - buffer
[i
& STBTT__OVER_MASK
];
3476 buffer
[(i
+kernel_width
) & STBTT__OVER_MASK
] = pixels
[i
];
3477 pixels
[i
] = (unsigned char) (total
/ 5);
3481 for (i
=0; i
<= safe_w
; ++i
) {
3482 total
+= pixels
[i
] - buffer
[i
& STBTT__OVER_MASK
];
3483 buffer
[(i
+kernel_width
) & STBTT__OVER_MASK
] = pixels
[i
];
3484 pixels
[i
] = (unsigned char) (total
/ kernel_width
);
3489 for (; i
< w
; ++i
) {
3490 STBTT_assert(pixels
[i
] == 0);
3491 total
-= buffer
[i
& STBTT__OVER_MASK
];
3492 pixels
[i
] = (unsigned char) (total
/ kernel_width
);
3495 pixels
+= stride_in_bytes
;
3499 static void stbtt__v_prefilter(unsigned char *pixels
, int w
, int h
, int stride_in_bytes
, unsigned int kernel_width
)
3501 unsigned char buffer
[STBTT_MAX_OVERSAMPLE
];
3502 int safe_h
= h
- kernel_width
;
3504 STBTT_memset(buffer
, 0, STBTT_MAX_OVERSAMPLE
); // suppress bogus warning from VS2013 -analyze
3505 for (j
=0; j
< w
; ++j
) {
3508 STBTT_memset(buffer
, 0, kernel_width
);
3512 // make kernel_width a constant in common cases so compiler can optimize out the divide
3513 switch (kernel_width
) {
3515 for (i
=0; i
<= safe_h
; ++i
) {
3516 total
+= pixels
[i
*stride_in_bytes
] - buffer
[i
& STBTT__OVER_MASK
];
3517 buffer
[(i
+kernel_width
) & STBTT__OVER_MASK
] = pixels
[i
*stride_in_bytes
];
3518 pixels
[i
*stride_in_bytes
] = (unsigned char) (total
/ 2);
3522 for (i
=0; i
<= safe_h
; ++i
) {
3523 total
+= pixels
[i
*stride_in_bytes
] - buffer
[i
& STBTT__OVER_MASK
];
3524 buffer
[(i
+kernel_width
) & STBTT__OVER_MASK
] = pixels
[i
*stride_in_bytes
];
3525 pixels
[i
*stride_in_bytes
] = (unsigned char) (total
/ 3);
3529 for (i
=0; i
<= safe_h
; ++i
) {
3530 total
+= pixels
[i
*stride_in_bytes
] - buffer
[i
& STBTT__OVER_MASK
];
3531 buffer
[(i
+kernel_width
) & STBTT__OVER_MASK
] = pixels
[i
*stride_in_bytes
];
3532 pixels
[i
*stride_in_bytes
] = (unsigned char) (total
/ 4);
3536 for (i
=0; i
<= safe_h
; ++i
) {
3537 total
+= pixels
[i
*stride_in_bytes
] - buffer
[i
& STBTT__OVER_MASK
];
3538 buffer
[(i
+kernel_width
) & STBTT__OVER_MASK
] = pixels
[i
*stride_in_bytes
];
3539 pixels
[i
*stride_in_bytes
] = (unsigned char) (total
/ 5);
3543 for (i
=0; i
<= safe_h
; ++i
) {
3544 total
+= pixels
[i
*stride_in_bytes
] - buffer
[i
& STBTT__OVER_MASK
];
3545 buffer
[(i
+kernel_width
) & STBTT__OVER_MASK
] = pixels
[i
*stride_in_bytes
];
3546 pixels
[i
*stride_in_bytes
] = (unsigned char) (total
/ kernel_width
);
3551 for (; i
< h
; ++i
) {
3552 STBTT_assert(pixels
[i
*stride_in_bytes
] == 0);
3553 total
-= buffer
[i
& STBTT__OVER_MASK
];
3554 pixels
[i
*stride_in_bytes
] = (unsigned char) (total
/ kernel_width
);
3561 static float stbtt__oversample_shift(int oversample
)
3566 // The prefilter is a box filter of width "oversample",
3567 // which shifts phase by (oversample - 1)/2 pixels in
3568 // oversampled space. We want to shift in the opposite
3569 // direction to counter this.
3570 return (float)-(oversample
- 1) / (2.0f
* (float)oversample
);
3573 // rects array must be big enough to accommodate all characters in the given ranges
3574 STBTT_DEF
int stbtt_PackFontRangesGatherRects(stbtt_pack_context
*spc
, const stbtt_fontinfo
*info
, stbtt_pack_range
*ranges
, int num_ranges
, stbrp_rect
*rects
)
3579 for (i
=0; i
< num_ranges
; ++i
) {
3580 float fh
= ranges
[i
].font_size
;
3581 float scale
= fh
> 0 ? stbtt_ScaleForPixelHeight(info
, fh
) : stbtt_ScaleForMappingEmToPixels(info
, -fh
);
3582 ranges
[i
].h_oversample
= (unsigned char) spc
->h_oversample
;
3583 ranges
[i
].v_oversample
= (unsigned char) spc
->v_oversample
;
3584 for (j
=0; j
< ranges
[i
].num_chars
; ++j
) {
3586 int codepoint
= ranges
[i
].array_of_unicode_codepoints
== NULL
? ranges
[i
].first_unicode_codepoint_in_range
+ j
: ranges
[i
].array_of_unicode_codepoints
[j
];
3587 int glyph
= stbtt_FindGlyphIndex(info
, codepoint
);
3588 stbtt_GetGlyphBitmapBoxSubpixel(info
,glyph
,
3589 scale
* spc
->h_oversample
,
3590 scale
* spc
->v_oversample
,
3593 rects
[k
].w
= (stbrp_coord
) (x1
-x0
+ spc
->padding
+ spc
->h_oversample
-1);
3594 rects
[k
].h
= (stbrp_coord
) (y1
-y0
+ spc
->padding
+ spc
->v_oversample
-1);
3602 // rects array must be big enough to accommodate all characters in the given ranges
3603 STBTT_DEF
int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context
*spc
, const stbtt_fontinfo
*info
, stbtt_pack_range
*ranges
, int num_ranges
, stbrp_rect
*rects
)
3605 int i
,j
,k
, return_value
= 1;
3607 // save current values
3608 int old_h_over
= spc
->h_oversample
;
3609 int old_v_over
= spc
->v_oversample
;
3612 for (i
=0; i
< num_ranges
; ++i
) {
3613 float fh
= ranges
[i
].font_size
;
3614 float scale
= fh
> 0 ? stbtt_ScaleForPixelHeight(info
, fh
) : stbtt_ScaleForMappingEmToPixels(info
, -fh
);
3615 float recip_h
,recip_v
,sub_x
,sub_y
;
3616 spc
->h_oversample
= ranges
[i
].h_oversample
;
3617 spc
->v_oversample
= ranges
[i
].v_oversample
;
3618 recip_h
= 1.0f
/ spc
->h_oversample
;
3619 recip_v
= 1.0f
/ spc
->v_oversample
;
3620 sub_x
= stbtt__oversample_shift(spc
->h_oversample
);
3621 sub_y
= stbtt__oversample_shift(spc
->v_oversample
);
3622 for (j
=0; j
< ranges
[i
].num_chars
; ++j
) {
3623 stbrp_rect
*r
= &rects
[k
];
3624 if (r
->was_packed
) {
3625 stbtt_packedchar
*bc
= &ranges
[i
].chardata_for_range
[j
];
3626 int advance
, lsb
, x0
,y0
,x1
,y1
;
3627 int codepoint
= ranges
[i
].array_of_unicode_codepoints
== NULL
? ranges
[i
].first_unicode_codepoint_in_range
+ j
: ranges
[i
].array_of_unicode_codepoints
[j
];
3628 int glyph
= stbtt_FindGlyphIndex(info
, codepoint
);
3629 stbrp_coord pad
= (stbrp_coord
) spc
->padding
;
3631 // pad on left and top
3636 stbtt_GetGlyphHMetrics(info
, glyph
, &advance
, &lsb
);
3637 stbtt_GetGlyphBitmapBox(info
, glyph
,
3638 scale
* spc
->h_oversample
,
3639 scale
* spc
->v_oversample
,
3641 stbtt_MakeGlyphBitmapSubpixel(info
,
3642 spc
->pixels
+ r
->x
+ r
->y
*spc
->stride_in_bytes
,
3643 r
->w
- spc
->h_oversample
+1,
3644 r
->h
- spc
->v_oversample
+1,
3645 spc
->stride_in_bytes
,
3646 scale
* spc
->h_oversample
,
3647 scale
* spc
->v_oversample
,
3651 if (spc
->h_oversample
> 1)
3652 stbtt__h_prefilter(spc
->pixels
+ r
->x
+ r
->y
*spc
->stride_in_bytes
,
3653 r
->w
, r
->h
, spc
->stride_in_bytes
,
3656 if (spc
->v_oversample
> 1)
3657 stbtt__v_prefilter(spc
->pixels
+ r
->x
+ r
->y
*spc
->stride_in_bytes
,
3658 r
->w
, r
->h
, spc
->stride_in_bytes
,
3661 bc
->x0
= (stbtt_int16
) r
->x
;
3662 bc
->y0
= (stbtt_int16
) r
->y
;
3663 bc
->x1
= (stbtt_int16
) (r
->x
+ r
->w
);
3664 bc
->y1
= (stbtt_int16
) (r
->y
+ r
->h
);
3665 bc
->xadvance
= scale
* advance
;
3666 bc
->xoff
= (float) x0
* recip_h
+ sub_x
;
3667 bc
->yoff
= (float) y0
* recip_v
+ sub_y
;
3668 bc
->xoff2
= (x0
+ r
->w
) * recip_h
+ sub_x
;
3669 bc
->yoff2
= (y0
+ r
->h
) * recip_v
+ sub_y
;
3671 return_value
= 0; // if any fail, report failure
3678 // restore original values
3679 spc
->h_oversample
= old_h_over
;
3680 spc
->v_oversample
= old_v_over
;
3682 return return_value
;
3685 STBTT_DEF
void stbtt_PackFontRangesPackRects(stbtt_pack_context
*spc
, stbrp_rect
*rects
, int num_rects
)
3687 stbrp_pack_rects((stbrp_context
*) spc
->pack_info
, rects
, num_rects
);
3690 STBTT_DEF
int stbtt_PackFontRanges(stbtt_pack_context
*spc
, unsigned char *fontdata
, int font_index
, stbtt_pack_range
*ranges
, int num_ranges
)
3692 stbtt_fontinfo info
;
3693 int i
,j
,n
, return_value
= 1;
3694 //stbrp_context *context = (stbrp_context *) spc->pack_info;
3697 // flag all characters as NOT packed
3698 for (i
=0; i
< num_ranges
; ++i
)
3699 for (j
=0; j
< ranges
[i
].num_chars
; ++j
)
3700 ranges
[i
].chardata_for_range
[j
].x0
=
3701 ranges
[i
].chardata_for_range
[j
].y0
=
3702 ranges
[i
].chardata_for_range
[j
].x1
=
3703 ranges
[i
].chardata_for_range
[j
].y1
= 0;
3706 for (i
=0; i
< num_ranges
; ++i
)
3707 n
+= ranges
[i
].num_chars
;
3709 rects
= (stbrp_rect
*) STBTT_malloc(sizeof(*rects
) * n
, spc
->user_allocator_context
);
3713 info
.userdata
= spc
->user_allocator_context
;
3714 stbtt_InitFont(&info
, fontdata
, stbtt_GetFontOffsetForIndex(fontdata
,font_index
));
3716 n
= stbtt_PackFontRangesGatherRects(spc
, &info
, ranges
, num_ranges
, rects
);
3718 stbtt_PackFontRangesPackRects(spc
, rects
, n
);
3720 return_value
= stbtt_PackFontRangesRenderIntoRects(spc
, &info
, ranges
, num_ranges
, rects
);
3722 STBTT_free(rects
, spc
->user_allocator_context
);
3723 return return_value
;
3726 STBTT_DEF
int stbtt_PackFontRange(stbtt_pack_context
*spc
, unsigned char *fontdata
, int font_index
, float font_size
,
3727 int first_unicode_codepoint_in_range
, int num_chars_in_range
, stbtt_packedchar
*chardata_for_range
)
3729 stbtt_pack_range range
;
3730 range
.first_unicode_codepoint_in_range
= first_unicode_codepoint_in_range
;
3731 range
.array_of_unicode_codepoints
= NULL
;
3732 range
.num_chars
= num_chars_in_range
;
3733 range
.chardata_for_range
= chardata_for_range
;
3734 range
.font_size
= font_size
;
3735 return stbtt_PackFontRanges(spc
, fontdata
, font_index
, &range
, 1);
3738 STBTT_DEF
void stbtt_GetPackedQuad(stbtt_packedchar
*chardata
, int pw
, int ph
, int char_index
, float *xpos
, float *ypos
, stbtt_aligned_quad
*q
, int align_to_integer
)
3740 float ipw
= 1.0f
/ pw
, iph
= 1.0f
/ ph
;
3741 stbtt_packedchar
*b
= chardata
+ char_index
;
3743 if (align_to_integer
) {
3744 float x
= (float) STBTT_ifloor((*xpos
+ b
->xoff
) + 0.5f
);
3745 float y
= (float) STBTT_ifloor((*ypos
+ b
->yoff
) + 0.5f
);
3748 q
->x1
= x
+ b
->xoff2
- b
->xoff
;
3749 q
->y1
= y
+ b
->yoff2
- b
->yoff
;
3751 q
->x0
= *xpos
+ b
->xoff
;
3752 q
->y0
= *ypos
+ b
->yoff
;
3753 q
->x1
= *xpos
+ b
->xoff2
;
3754 q
->y1
= *ypos
+ b
->yoff2
;
3757 q
->s0
= b
->x0
* ipw
;
3758 q
->t0
= b
->y0
* iph
;
3759 q
->s1
= b
->x1
* ipw
;
3760 q
->t1
= b
->y1
* iph
;
3762 *xpos
+= b
->xadvance
;
3766 //////////////////////////////////////////////////////////////////////////////
3768 // font name matching -- recommended not to use this
3771 // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
3772 static stbtt_int32
stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8
*s1
, stbtt_int32 len1
, stbtt_uint8
*s2
, stbtt_int32 len2
)
3776 // convert utf16 to utf8 and compare the results while converting
3778 stbtt_uint16 ch
= s2
[0]*256 + s2
[1];
3780 if (i
>= len1
) return -1;
3781 if (s1
[i
++] != ch
) return -1;
3782 } else if (ch
< 0x800) {
3783 if (i
+1 >= len1
) return -1;
3784 if (s1
[i
++] != 0xc0 + (ch
>> 6)) return -1;
3785 if (s1
[i
++] != 0x80 + (ch
& 0x3f)) return -1;
3786 } else if (ch
>= 0xd800 && ch
< 0xdc00) {
3788 stbtt_uint16 ch2
= s2
[2]*256 + s2
[3];
3789 if (i
+3 >= len1
) return -1;
3790 c
= ((ch
- 0xd800) << 10) + (ch2
- 0xdc00) + 0x10000;
3791 if (s1
[i
++] != 0xf0 + (c
>> 18)) return -1;
3792 if (s1
[i
++] != 0x80 + ((c
>> 12) & 0x3f)) return -1;
3793 if (s1
[i
++] != 0x80 + ((c
>> 6) & 0x3f)) return -1;
3794 if (s1
[i
++] != 0x80 + ((c
) & 0x3f)) return -1;
3795 s2
+= 2; // plus another 2 below
3797 } else if (ch
>= 0xdc00 && ch
< 0xe000) {
3800 if (i
+2 >= len1
) return -1;
3801 if (s1
[i
++] != 0xe0 + (ch
>> 12)) return -1;
3802 if (s1
[i
++] != 0x80 + ((ch
>> 6) & 0x3f)) return -1;
3803 if (s1
[i
++] != 0x80 + ((ch
) & 0x3f)) return -1;
3811 static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1
, int len1
, char *s2
, int len2
)
3813 return len1
== stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8
*) s1
, len1
, (stbtt_uint8
*) s2
, len2
);
3816 // returns results in whatever encoding you request... but note that 2-byte encodings
3817 // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
3818 STBTT_DEF
const char *stbtt_GetFontNameString(const stbtt_fontinfo
*font
, int *length
, int platformID
, int encodingID
, int languageID
, int nameID
)
3820 stbtt_int32 i
,count
,stringOffset
;
3821 stbtt_uint8
*fc
= font
->data
;
3822 stbtt_uint32 offset
= font
->fontstart
;
3823 stbtt_uint32 nm
= stbtt__find_table(fc
, offset
, "name");
3824 if (!nm
) return NULL
;
3826 count
= ttUSHORT(fc
+nm
+2);
3827 stringOffset
= nm
+ ttUSHORT(fc
+nm
+4);
3828 for (i
=0; i
< count
; ++i
) {
3829 stbtt_uint32 loc
= nm
+ 6 + 12 * i
;
3830 if (platformID
== ttUSHORT(fc
+loc
+0) && encodingID
== ttUSHORT(fc
+loc
+2)
3831 && languageID
== ttUSHORT(fc
+loc
+4) && nameID
== ttUSHORT(fc
+loc
+6)) {
3832 *length
= ttUSHORT(fc
+loc
+8);
3833 return (const char *) (fc
+stringOffset
+ttUSHORT(fc
+loc
+10));
3839 static int stbtt__matchpair(stbtt_uint8
*fc
, stbtt_uint32 nm
, stbtt_uint8
*name
, stbtt_int32 nlen
, stbtt_int32 target_id
, stbtt_int32 next_id
)
3842 stbtt_int32 count
= ttUSHORT(fc
+nm
+2);
3843 stbtt_int32 stringOffset
= nm
+ ttUSHORT(fc
+nm
+4);
3845 for (i
=0; i
< count
; ++i
) {
3846 stbtt_uint32 loc
= nm
+ 6 + 12 * i
;
3847 stbtt_int32 id
= ttUSHORT(fc
+loc
+6);
3848 if (id
== target_id
) {
3849 // find the encoding
3850 stbtt_int32 platform
= ttUSHORT(fc
+loc
+0), encoding
= ttUSHORT(fc
+loc
+2), language
= ttUSHORT(fc
+loc
+4);
3852 // is this a Unicode encoding?
3853 if (platform
== 0 || (platform
== 3 && encoding
== 1) || (platform
== 3 && encoding
== 10)) {
3854 stbtt_int32 slen
= ttUSHORT(fc
+loc
+8);
3855 stbtt_int32 off
= ttUSHORT(fc
+loc
+10);
3857 // check if there's a prefix match
3858 stbtt_int32 matchlen
= stbtt__CompareUTF8toUTF16_bigendian_prefix(name
, nlen
, fc
+stringOffset
+off
,slen
);
3859 if (matchlen
>= 0) {
3860 // check for target_id+1 immediately following, with same encoding & language
3861 if (i
+1 < count
&& ttUSHORT(fc
+loc
+12+6) == next_id
&& ttUSHORT(fc
+loc
+12) == platform
&& ttUSHORT(fc
+loc
+12+2) == encoding
&& ttUSHORT(fc
+loc
+12+4) == language
) {
3862 slen
= ttUSHORT(fc
+loc
+12+8);
3863 off
= ttUSHORT(fc
+loc
+12+10);
3865 if (matchlen
== nlen
)
3867 } else if (matchlen
< nlen
&& name
[matchlen
] == ' ') {
3869 if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name
+matchlen
), nlen
-matchlen
, (char*)(fc
+stringOffset
+off
),slen
))
3873 // if nothing immediately following
3874 if (matchlen
== nlen
)
3880 // @TODO handle other encodings
3886 static int stbtt__matches(stbtt_uint8
*fc
, stbtt_uint32 offset
, stbtt_uint8
*name
, stbtt_int32 flags
)
3888 stbtt_int32 nlen
= (stbtt_int32
) STBTT_strlen((char *) name
);
3890 if (!stbtt__isfont(fc
+offset
)) return 0;
3892 // check italics/bold/underline flags in macStyle...
3894 hd
= stbtt__find_table(fc
, offset
, "head");
3895 if ((ttUSHORT(fc
+hd
+44) & 7) != (flags
& 7)) return 0;
3898 nm
= stbtt__find_table(fc
, offset
, "name");
3902 // if we checked the macStyle flags, then just check the family and ignore the subfamily
3903 if (stbtt__matchpair(fc
, nm
, name
, nlen
, 16, -1)) return 1;
3904 if (stbtt__matchpair(fc
, nm
, name
, nlen
, 1, -1)) return 1;
3905 if (stbtt__matchpair(fc
, nm
, name
, nlen
, 3, -1)) return 1;
3907 if (stbtt__matchpair(fc
, nm
, name
, nlen
, 16, 17)) return 1;
3908 if (stbtt__matchpair(fc
, nm
, name
, nlen
, 1, 2)) return 1;
3909 if (stbtt__matchpair(fc
, nm
, name
, nlen
, 3, -1)) return 1;
3915 static int stbtt_FindMatchingFont_internal(unsigned char *font_collection
, char *name_utf8
, stbtt_int32 flags
)
3919 stbtt_int32 off
= stbtt_GetFontOffsetForIndex(font_collection
, i
);
3920 if (off
< 0) return off
;
3921 if (stbtt__matches((stbtt_uint8
*) font_collection
, off
, (stbtt_uint8
*) name_utf8
, flags
))
3926 #if defined(__GNUC__) || defined(__clang__)
3927 #pragma GCC diagnostic push
3928 #pragma GCC diagnostic ignored "-Wcast-qual"
3931 STBTT_DEF
int stbtt_BakeFontBitmap(const unsigned char *data
, int offset
,
3932 float pixel_height
, unsigned char *pixels
, int pw
, int ph
,
3933 int first_char
, int num_chars
, stbtt_bakedchar
*chardata
)
3935 return stbtt_BakeFontBitmap_internal((unsigned char *) data
, offset
, pixel_height
, pixels
, pw
, ph
, first_char
, num_chars
, chardata
);
3938 STBTT_DEF
int stbtt_GetFontOffsetForIndex(const unsigned char *data
, int index
)
3940 return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data
, index
);
3943 STBTT_DEF
int stbtt_GetNumberOfFonts(const unsigned char *data
)
3945 return stbtt_GetNumberOfFonts_internal((unsigned char *) data
);
3948 STBTT_DEF
int stbtt_InitFont(stbtt_fontinfo
*info
, const unsigned char *data
, int offset
)
3950 return stbtt_InitFont_internal(info
, (unsigned char *) data
, offset
);
3953 STBTT_DEF
int stbtt_FindMatchingFont(const unsigned char *fontdata
, const char *name
, int flags
)
3955 return stbtt_FindMatchingFont_internal((unsigned char *) fontdata
, (char *) name
, flags
);
3958 STBTT_DEF
int stbtt_CompareUTF8toUTF16_bigendian(const char *s1
, int len1
, const char *s2
, int len2
)
3960 return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1
, len1
, (char *) s2
, len2
);
3963 #if defined(__GNUC__) || defined(__clang__)
3964 #pragma GCC diagnostic pop
3967 #endif // STB_TRUETYPE_IMPLEMENTATION
3970 // FULL VERSION HISTORY
3972 // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
3973 // 1.11 (2016-04-02) fix unused-variable warning
3974 // 1.10 (2016-04-02) allow user-defined fabs() replacement
3975 // fix memory leak if fontsize=0.0
3976 // fix warning from duplicate typedef
3977 // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges
3978 // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
3979 // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
3980 // allow PackFontRanges to pack and render in separate phases;
3981 // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
3982 // fixed an assert() bug in the new rasterizer
3983 // replace assert() with STBTT_assert() in new rasterizer
3984 // 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
3985 // also more precise AA rasterizer, except if shapes overlap
3986 // remove need for STBTT_sort
3987 // 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
3988 // 1.04 (2015-04-15) typo in example
3989 // 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
3990 // 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++
3991 // 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match
3992 // non-oversampled; STBTT_POINT_SIZE for packed case only
3993 // 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling
3994 // 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)
3995 // 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID
3996 // 0.8b (2014-07-07) fix a warning
3997 // 0.8 (2014-05-25) fix a few more warnings
3998 // 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
3999 // 0.6c (2012-07-24) improve documentation
4000 // 0.6b (2012-07-20) fix a few more warnings
4001 // 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
4002 // stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
4003 // 0.5 (2011-12-09) bugfixes:
4004 // subpixel glyph renderer computed wrong bounding box
4005 // first vertex of shape can be off-curve (FreeSans)
4006 // 0.4b (2011-12-03) fixed an error in the font baking example
4007 // 0.4 (2011-12-01) kerning, subpixel rendering (tor)
4009 // codepoint-to-glyph conversion using table fmt=12
4010 // codepoint-to-glyph conversion using table fmt=4
4011 // stbtt_GetBakedQuad with non-square texture (Zer)
4012 // updated Hello World! sample to use kerning and subpixel
4013 // fixed some warnings
4014 // 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)
4015 // userdata, malloc-from-userdata, non-zero fill (stb)
4016 // 0.2 (2009-03-11) Fix unsigned/signed char warnings
4017 // 0.1 (2009-03-09) First public release