Open Source Tomb Raider Engine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

stb_truetype.h 102KB

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