imstb_truetype.h 188 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903
  1. // [DEAR IMGUI]
  2. // This is a slightly modified version of stb_truetype.h 1.20.
  3. // Mostly fixing for compiler and static analyzer warnings.
  4. // Grep for [DEAR IMGUI] to find the changes.
  5. // stb_truetype.h - v1.20 - public domain
  6. // authored from 2009-2016 by Sean Barrett / RAD Game Tools
  7. //
  8. // This library processes TrueType files:
  9. // parse files
  10. // extract glyph metrics
  11. // extract glyph shapes
  12. // render glyphs to one-channel bitmaps with antialiasing (box filter)
  13. // render glyphs to one-channel SDF bitmaps (signed-distance field/function)
  14. //
  15. // Todo:
  16. // non-MS cmaps
  17. // crashproof on bad data
  18. // hinting? (no longer patented)
  19. // cleartype-style AA?
  20. // optimize: use simple memory allocator for intermediates
  21. // optimize: build edge-list directly from curves
  22. // optimize: rasterize directly from curves?
  23. //
  24. // ADDITIONAL CONTRIBUTORS
  25. //
  26. // Mikko Mononen: compound shape support, more cmap formats
  27. // Tor Andersson: kerning, subpixel rendering
  28. // Dougall Johnson: OpenType / Type 2 font handling
  29. // Daniel Ribeiro Maciel: basic GPOS-based kerning
  30. //
  31. // Misc other:
  32. // Ryan Gordon
  33. // Simon Glass
  34. // github:IntellectualKitty
  35. // Imanol Celaya
  36. // Daniel Ribeiro Maciel
  37. //
  38. // Bug/warning reports/fixes:
  39. // "Zer" on mollyrocket Fabian "ryg" Giesen
  40. // Cass Everitt Martins Mozeiko
  41. // stoiko (Haemimont Games) Cap Petschulat
  42. // Brian Hook Omar Cornut
  43. // Walter van Niftrik github:aloucks
  44. // David Gow Peter LaValle
  45. // David Given Sergey Popov
  46. // Ivan-Assen Ivanov Giumo X. Clanjor
  47. // Anthony Pesch Higor Euripedes
  48. // Johan Duparc Thomas Fields
  49. // Hou Qiming Derek Vinyard
  50. // Rob Loach Cort Stratton
  51. // Kenney Phillis Jr. github:oyvindjam
  52. // Brian Costabile github:vassvik
  53. //
  54. // VERSION HISTORY
  55. //
  56. // 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()
  57. // 1.19 (2018-02-11) GPOS kerning, STBTT_fmod
  58. // 1.18 (2018-01-29) add missing function
  59. // 1.17 (2017-07-23) make more arguments const; doc fix
  60. // 1.16 (2017-07-12) SDF support
  61. // 1.15 (2017-03-03) make more arguments const
  62. // 1.14 (2017-01-16) num-fonts-in-TTC function
  63. // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
  64. // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
  65. // 1.11 (2016-04-02) fix unused-variable warning
  66. // 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef
  67. // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly
  68. // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
  69. // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
  70. // variant PackFontRanges to pack and render in separate phases;
  71. // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
  72. // fixed an assert() bug in the new rasterizer
  73. // replace assert() with STBTT_assert() in new rasterizer
  74. //
  75. // Full history can be found at the end of this file.
  76. //
  77. // LICENSE
  78. //
  79. // See end of file for license information.
  80. //
  81. // USAGE
  82. //
  83. // Include this file in whatever places need to refer to it. In ONE C/C++
  84. // file, write:
  85. // #define STB_TRUETYPE_IMPLEMENTATION
  86. // before the #include of this file. This expands out the actual
  87. // implementation into that C/C++ file.
  88. //
  89. // To make the implementation private to the file that generates the implementation,
  90. // #define STBTT_STATIC
  91. //
  92. // Simple 3D API (don't ship this, but it's fine for tools and quick start)
  93. // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture
  94. // stbtt_GetBakedQuad() -- compute quad to draw for a given char
  95. //
  96. // Improved 3D API (more shippable):
  97. // #include "stb_rect_pack.h" -- optional, but you really want it
  98. // stbtt_PackBegin()
  99. // stbtt_PackSetOversampling() -- for improved quality on small fonts
  100. // stbtt_PackFontRanges() -- pack and renders
  101. // stbtt_PackEnd()
  102. // stbtt_GetPackedQuad()
  103. //
  104. // "Load" a font file from a memory buffer (you have to keep the buffer loaded)
  105. // stbtt_InitFont()
  106. // stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections
  107. // stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections
  108. //
  109. // Render a unicode codepoint to a bitmap
  110. // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
  111. // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide
  112. // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
  113. //
  114. // Character advance/positioning
  115. // stbtt_GetCodepointHMetrics()
  116. // stbtt_GetFontVMetrics()
  117. // stbtt_GetFontVMetricsOS2()
  118. // stbtt_GetCodepointKernAdvance()
  119. //
  120. // Starting with version 1.06, the rasterizer was replaced with a new,
  121. // faster and generally-more-precise rasterizer. The new rasterizer more
  122. // accurately measures pixel coverage for anti-aliasing, except in the case
  123. // where multiple shapes overlap, in which case it overestimates the AA pixel
  124. // coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If
  125. // this turns out to be a problem, you can re-enable the old rasterizer with
  126. // #define STBTT_RASTERIZER_VERSION 1
  127. // which will incur about a 15% speed hit.
  128. //
  129. // ADDITIONAL DOCUMENTATION
  130. //
  131. // Immediately after this block comment are a series of sample programs.
  132. //
  133. // After the sample programs is the "header file" section. This section
  134. // includes documentation for each API function.
  135. //
  136. // Some important concepts to understand to use this library:
  137. //
  138. // Codepoint
  139. // Characters are defined by unicode codepoints, e.g. 65 is
  140. // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
  141. // the hiragana for "ma".
  142. //
  143. // Glyph
  144. // A visual character shape (every codepoint is rendered as
  145. // some glyph)
  146. //
  147. // Glyph index
  148. // A font-specific integer ID representing a glyph
  149. //
  150. // Baseline
  151. // Glyph shapes are defined relative to a baseline, which is the
  152. // bottom of uppercase characters. Characters extend both above
  153. // and below the baseline.
  154. //
  155. // Current Point
  156. // As you draw text to the screen, you keep track of a "current point"
  157. // which is the origin of each character. The current point's vertical
  158. // position is the baseline. Even "baked fonts" use this model.
  159. //
  160. // Vertical Font Metrics
  161. // The vertical qualities of the font, used to vertically position
  162. // and space the characters. See docs for stbtt_GetFontVMetrics.
  163. //
  164. // Font Size in Pixels or Points
  165. // The preferred interface for specifying font sizes in stb_truetype
  166. // is to specify how tall the font's vertical extent should be in pixels.
  167. // If that sounds good enough, skip the next paragraph.
  168. //
  169. // Most font APIs instead use "points", which are a common typographic
  170. // measurement for describing font size, defined as 72 points per inch.
  171. // stb_truetype provides a point API for compatibility. However, true
  172. // "per inch" conventions don't make much sense on computer displays
  173. // since different monitors have different number of pixels per
  174. // inch. For example, Windows traditionally uses a convention that
  175. // there are 96 pixels per inch, thus making 'inch' measurements have
  176. // nothing to do with inches, and thus effectively defining a point to
  177. // be 1.333 pixels. Additionally, the TrueType font data provides
  178. // an explicit scale factor to scale a given font's glyphs to points,
  179. // but the author has observed that this scale factor is often wrong
  180. // for non-commercial fonts, thus making fonts scaled in points
  181. // according to the TrueType spec incoherently sized in practice.
  182. //
  183. // DETAILED USAGE:
  184. //
  185. // Scale:
  186. // Select how high you want the font to be, in points or pixels.
  187. // Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute
  188. // a scale factor SF that will be used by all other functions.
  189. //
  190. // Baseline:
  191. // You need to select a y-coordinate that is the baseline of where
  192. // your text will appear. Call GetFontBoundingBox to get the baseline-relative
  193. // bounding box for all characters. SF*-y0 will be the distance in pixels
  194. // that the worst-case character could extend above the baseline, so if
  195. // you want the top edge of characters to appear at the top of the
  196. // screen where y=0, then you would set the baseline to SF*-y0.
  197. //
  198. // Current point:
  199. // Set the current point where the first character will appear. The
  200. // first character could extend left of the current point; this is font
  201. // dependent. You can either choose a current point that is the leftmost
  202. // point and hope, or add some padding, or check the bounding box or
  203. // left-side-bearing of the first character to be displayed and set
  204. // the current point based on that.
  205. //
  206. // Displaying a character:
  207. // Compute the bounding box of the character. It will contain signed values
  208. // relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,
  209. // then the character should be displayed in the rectangle from
  210. // <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).
  211. //
  212. // Advancing for the next character:
  213. // Call GlyphHMetrics, and compute 'current_point += SF * advance'.
  214. //
  215. //
  216. // ADVANCED USAGE
  217. //
  218. // Quality:
  219. //
  220. // - Use the functions with Subpixel at the end to allow your characters
  221. // to have subpixel positioning. Since the font is anti-aliased, not
  222. // hinted, this is very import for quality. (This is not possible with
  223. // baked fonts.)
  224. //
  225. // - Kerning is now supported, and if you're supporting subpixel rendering
  226. // then kerning is worth using to give your text a polished look.
  227. //
  228. // Performance:
  229. //
  230. // - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
  231. // if you don't do this, stb_truetype is forced to do the conversion on
  232. // every call.
  233. //
  234. // - There are a lot of memory allocations. We should modify it to take
  235. // a temp buffer and allocate from the temp buffer (without freeing),
  236. // should help performance a lot.
  237. //
  238. // NOTES
  239. //
  240. // The system uses the raw data found in the .ttf file without changing it
  241. // and without building auxiliary data structures. This is a bit inefficient
  242. // on little-endian systems (the data is big-endian), but assuming you're
  243. // caching the bitmaps or glyph shapes this shouldn't be a big deal.
  244. //
  245. // It appears to be very hard to programmatically determine what font a
  246. // given file is in a general way. I provide an API for this, but I don't
  247. // recommend it.
  248. //
  249. //
  250. // SOURCE STATISTICS (based on v0.6c, 2050 LOC)
  251. //
  252. // Documentation & header file 520 LOC \___ 660 LOC documentation
  253. // Sample code 140 LOC /
  254. // Truetype parsing 620 LOC ---- 620 LOC TrueType
  255. // Software rasterization 240 LOC \.
  256. // Curve tessellation 120 LOC \__ 550 LOC Bitmap creation
  257. // Bitmap management 100 LOC /
  258. // Baked bitmap interface 70 LOC /
  259. // Font name matching & access 150 LOC ---- 150
  260. // C runtime library abstraction 60 LOC ---- 60
  261. //
  262. //
  263. // PERFORMANCE MEASUREMENTS FOR 1.06:
  264. //
  265. // 32-bit 64-bit
  266. // Previous release: 8.83 s 7.68 s
  267. // Pool allocations: 7.72 s 6.34 s
  268. // Inline sort : 6.54 s 5.65 s
  269. // New rasterizer : 5.63 s 5.00 s
  270. //////////////////////////////////////////////////////////////////////////////
  271. //////////////////////////////////////////////////////////////////////////////
  272. ////
  273. //// SAMPLE PROGRAMS
  274. ////
  275. //
  276. // Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
  277. //
  278. #if 0
  279. #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
  280. #include "stb_truetype.h"
  281. unsigned char ttf_buffer[1<<20];
  282. unsigned char temp_bitmap[512*512];
  283. stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
  284. GLuint ftex;
  285. void my_stbtt_initfont(void)
  286. {
  287. fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
  288. stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
  289. // can free ttf_buffer at this point
  290. glGenTextures(1, &ftex);
  291. glBindTexture(GL_TEXTURE_2D, ftex);
  292. glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
  293. // can free temp_bitmap at this point
  294. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  295. }
  296. void my_stbtt_print(float x, float y, char *text)
  297. {
  298. // assume orthographic projection with units = screen pixels, origin at top left
  299. glEnable(GL_TEXTURE_2D);
  300. glBindTexture(GL_TEXTURE_2D, ftex);
  301. glBegin(GL_QUADS);
  302. while (*text) {
  303. if (*text >= 32 && *text < 128) {
  304. stbtt_aligned_quad q;
  305. stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
  306. glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
  307. glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
  308. glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
  309. glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
  310. }
  311. ++text;
  312. }
  313. glEnd();
  314. }
  315. #endif
  316. //
  317. //
  318. //////////////////////////////////////////////////////////////////////////////
  319. //
  320. // Complete program (this compiles): get a single bitmap, print as ASCII art
  321. //
  322. #if 0
  323. #include <stdio.h>
  324. #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
  325. #include "stb_truetype.h"
  326. char ttf_buffer[1<<25];
  327. int main(int argc, char **argv)
  328. {
  329. stbtt_fontinfo font;
  330. unsigned char *bitmap;
  331. int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
  332. fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
  333. stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
  334. bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
  335. for (j=0; j < h; ++j) {
  336. for (i=0; i < w; ++i)
  337. putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
  338. putchar('\n');
  339. }
  340. return 0;
  341. }
  342. #endif
  343. //
  344. // Output:
  345. //
  346. // .ii.
  347. // @@@@@@.
  348. // V@Mio@@o
  349. // :i. V@V
  350. // :oM@@M
  351. // :@@@MM@M
  352. // @@o o@M
  353. // :@@. M@M
  354. // @@@o@@@@
  355. // :M@@V:@@.
  356. //
  357. //////////////////////////////////////////////////////////////////////////////
  358. //
  359. // Complete program: print "Hello World!" banner, with bugs
  360. //
  361. #if 0
  362. char buffer[24<<20];
  363. unsigned char screen[20][79];
  364. int main(int arg, char **argv)
  365. {
  366. stbtt_fontinfo font;
  367. int i,j,ascent,baseline,ch=0;
  368. float scale, xpos=2; // leave a little padding in case the character extends left
  369. char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness
  370. fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
  371. stbtt_InitFont(&font, buffer, 0);
  372. scale = stbtt_ScaleForPixelHeight(&font, 15);
  373. stbtt_GetFontVMetrics(&font, &ascent,0,0);
  374. baseline = (int) (ascent*scale);
  375. while (text[ch]) {
  376. int advance,lsb,x0,y0,x1,y1;
  377. float x_shift = xpos - (float) floor(xpos);
  378. stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
  379. stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
  380. stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
  381. // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
  382. // because this API is really for baking character bitmaps into textures. if you want to render
  383. // a sequence of characters, you really need to render each bitmap to a temp buffer, then
  384. // "alpha blend" that into the working buffer
  385. xpos += (advance * scale);
  386. if (text[ch+1])
  387. xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
  388. ++ch;
  389. }
  390. for (j=0; j < 20; ++j) {
  391. for (i=0; i < 78; ++i)
  392. putchar(" .:ioVM@"[screen[j][i]>>5]);
  393. putchar('\n');
  394. }
  395. return 0;
  396. }
  397. #endif
  398. //////////////////////////////////////////////////////////////////////////////
  399. //////////////////////////////////////////////////////////////////////////////
  400. ////
  401. //// INTEGRATION WITH YOUR CODEBASE
  402. ////
  403. //// The following sections allow you to supply alternate definitions
  404. //// of C library functions used by stb_truetype, e.g. if you don't
  405. //// link with the C runtime library.
  406. #ifdef STB_TRUETYPE_IMPLEMENTATION
  407. // #define your own (u)stbtt_int8/16/32 before including to override this
  408. #ifndef stbtt_uint8
  409. typedef unsigned char stbtt_uint8;
  410. typedef signed char stbtt_int8;
  411. typedef unsigned short stbtt_uint16;
  412. typedef signed short stbtt_int16;
  413. typedef unsigned int stbtt_uint32;
  414. typedef signed int stbtt_int32;
  415. #endif
  416. typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
  417. typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
  418. // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
  419. #ifndef STBTT_ifloor
  420. #include <math.h>
  421. #define STBTT_ifloor(x) ((int) floor(x))
  422. #define STBTT_iceil(x) ((int) ceil(x))
  423. #endif
  424. #ifndef STBTT_sqrt
  425. #include <math.h>
  426. #define STBTT_sqrt(x) sqrt(x)
  427. #define STBTT_pow(x,y) pow(x,y)
  428. #endif
  429. #ifndef STBTT_fmod
  430. #include <math.h>
  431. #define STBTT_fmod(x,y) fmod(x,y)
  432. #endif
  433. #ifndef STBTT_cos
  434. #include <math.h>
  435. #define STBTT_cos(x) cos(x)
  436. #define STBTT_acos(x) acos(x)
  437. #endif
  438. #ifndef STBTT_fabs
  439. #include <math.h>
  440. #define STBTT_fabs(x) fabs(x)
  441. #endif
  442. // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
  443. #ifndef STBTT_malloc
  444. #include <stdlib.h>
  445. #define STBTT_malloc(x,u) ((void)(u),malloc(x))
  446. #define STBTT_free(x,u) ((void)(u),free(x))
  447. #endif
  448. #ifndef STBTT_assert
  449. #include <assert.h>
  450. #define STBTT_assert(x) assert(x)
  451. #endif
  452. #ifndef STBTT_strlen
  453. #include <string.h>
  454. #define STBTT_strlen(x) strlen(x)
  455. #endif
  456. #ifndef STBTT_memcpy
  457. #include <string.h>
  458. #define STBTT_memcpy memcpy
  459. #define STBTT_memset memset
  460. #endif
  461. #endif
  462. ///////////////////////////////////////////////////////////////////////////////
  463. ///////////////////////////////////////////////////////////////////////////////
  464. ////
  465. //// INTERFACE
  466. ////
  467. ////
  468. #ifndef __STB_INCLUDE_STB_TRUETYPE_H__
  469. #define __STB_INCLUDE_STB_TRUETYPE_H__
  470. #ifdef STBTT_STATIC
  471. #define STBTT_DEF static
  472. #else
  473. #define STBTT_DEF extern
  474. #endif
  475. #ifdef __cplusplus
  476. extern "C" {
  477. #endif
  478. // private structure
  479. typedef struct
  480. {
  481. unsigned char *data;
  482. int cursor;
  483. int size;
  484. } stbtt__buf;
  485. //////////////////////////////////////////////////////////////////////////////
  486. //
  487. // TEXTURE BAKING API
  488. //
  489. // If you use this API, you only have to call two functions ever.
  490. //
  491. typedef struct
  492. {
  493. unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
  494. float xoff,yoff,xadvance;
  495. } stbtt_bakedchar;
  496. STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
  497. float pixel_height, // height of font in pixels
  498. unsigned char *pixels, int pw, int ph, // bitmap to be filled in
  499. int first_char, int num_chars, // characters to bake
  500. stbtt_bakedchar *chardata); // you allocate this, it's num_chars long
  501. // if return is positive, the first unused row of the bitmap
  502. // if return is negative, returns the negative of the number of characters that fit
  503. // if return is 0, no characters fit and no rows were used
  504. // This uses a very crappy packing.
  505. typedef struct
  506. {
  507. float x0,y0,s0,t0; // top-left
  508. float x1,y1,s1,t1; // bottom-right
  509. } stbtt_aligned_quad;
  510. STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above
  511. int char_index, // character to display
  512. float *xpos, float *ypos, // pointers to current position in screen pixel space
  513. stbtt_aligned_quad *q, // output: quad to draw
  514. int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier
  515. // Call GetBakedQuad with char_index = 'character - first_char', and it
  516. // creates the quad you need to draw and advances the current position.
  517. //
  518. // The coordinate system used assumes y increases downwards.
  519. //
  520. // Characters will extend both above and below the current position;
  521. // see discussion of "BASELINE" above.
  522. //
  523. // It's inefficient; you might want to c&p it and optimize it.
  524. STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap);
  525. // Query the font vertical metrics without having to create a font first.
  526. //////////////////////////////////////////////////////////////////////////////
  527. //
  528. // NEW TEXTURE BAKING API
  529. //
  530. // This provides options for packing multiple fonts into one atlas, not
  531. // perfectly but better than nothing.
  532. typedef struct
  533. {
  534. unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
  535. float xoff,yoff,xadvance;
  536. float xoff2,yoff2;
  537. } stbtt_packedchar;
  538. typedef struct stbtt_pack_context stbtt_pack_context;
  539. typedef struct stbtt_fontinfo stbtt_fontinfo;
  540. #ifndef STB_RECT_PACK_VERSION
  541. typedef struct stbrp_rect stbrp_rect;
  542. #endif
  543. STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);
  544. // Initializes a packing context stored in the passed-in stbtt_pack_context.
  545. // Future calls using this context will pack characters into the bitmap passed
  546. // in here: a 1-channel bitmap that is width * height. stride_in_bytes is
  547. // the distance from one row to the next (or 0 to mean they are packed tightly
  548. // together). "padding" is the amount of padding to leave between each
  549. // character (normally you want '1' for bitmaps you'll use as textures with
  550. // bilinear filtering).
  551. //
  552. // Returns 0 on failure, 1 on success.
  553. STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc);
  554. // Cleans up the packing context and frees all memory.
  555. #define STBTT_POINT_SIZE(x) (-(x))
  556. STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
  557. int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);
  558. // Creates character bitmaps from the font_index'th font found in fontdata (use
  559. // font_index=0 if you don't know what that is). It creates num_chars_in_range
  560. // bitmaps for characters with unicode values starting at first_unicode_char_in_range
  561. // and increasing. Data for how to render them is stored in chardata_for_range;
  562. // pass these to stbtt_GetPackedQuad to get back renderable quads.
  563. //
  564. // font_size is the full height of the character from ascender to descender,
  565. // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed
  566. // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()
  567. // and pass that result as 'font_size':
  568. // ..., 20 , ... // font max minus min y is 20 pixels tall
  569. // ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall
  570. typedef struct
  571. {
  572. float font_size;
  573. int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint
  574. int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints
  575. int num_chars;
  576. stbtt_packedchar *chardata_for_range; // output
  577. unsigned char h_oversample, v_oversample; // don't set these, they're used internally
  578. } stbtt_pack_range;
  579. STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
  580. // Creates character bitmaps from multiple ranges of characters stored in
  581. // ranges. This will usually create a better-packed bitmap than multiple
  582. // calls to stbtt_PackFontRange. Note that you can call this multiple
  583. // times within a single PackBegin/PackEnd.
  584. STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);
  585. // Oversampling a font increases the quality by allowing higher-quality subpixel
  586. // positioning, and is especially valuable at smaller text sizes.
  587. //
  588. // This function sets the amount of oversampling for all following calls to
  589. // stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given
  590. // pack context. The default (no oversampling) is achieved by h_oversample=1
  591. // and v_oversample=1. The total number of pixels required is
  592. // h_oversample*v_oversample larger than the default; for example, 2x2
  593. // oversampling requires 4x the storage of 1x1. For best results, render
  594. // oversampled textures with bilinear filtering. Look at the readme in
  595. // stb/tests/oversample for information about oversampled fonts
  596. //
  597. // To use with PackFontRangesGather etc., you must set it before calls
  598. // call to PackFontRangesGatherRects.
  599. STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip);
  600. // If skip != 0, this tells stb_truetype to skip any codepoints for which
  601. // there is no corresponding glyph. If skip=0, which is the default, then
  602. // codepoints without a glyph recived the font's "missing character" glyph,
  603. // typically an empty box by convention.
  604. STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above
  605. int char_index, // character to display
  606. float *xpos, float *ypos, // pointers to current position in screen pixel space
  607. stbtt_aligned_quad *q, // output: quad to draw
  608. int align_to_integer);
  609. STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
  610. STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);
  611. STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
  612. // Calling these functions in sequence is roughly equivalent to calling
  613. // stbtt_PackFontRanges(). If you more control over the packing of multiple
  614. // fonts, or if you want to pack custom data into a font texture, take a look
  615. // at the source to of stbtt_PackFontRanges() and create a custom version
  616. // using these functions, e.g. call GatherRects multiple times,
  617. // building up a single array of rects, then call PackRects once,
  618. // then call RenderIntoRects repeatedly. This may result in a
  619. // better packing than calling PackFontRanges multiple times
  620. // (or it may not).
  621. // this is an opaque structure that you shouldn't mess with which holds
  622. // all the context needed from PackBegin to PackEnd.
  623. struct stbtt_pack_context {
  624. void *user_allocator_context;
  625. void *pack_info;
  626. int width;
  627. int height;
  628. int stride_in_bytes;
  629. int padding;
  630. int skip_missing;
  631. unsigned int h_oversample, v_oversample;
  632. unsigned char *pixels;
  633. void *nodes;
  634. };
  635. //////////////////////////////////////////////////////////////////////////////
  636. //
  637. // FONT LOADING
  638. //
  639. //
  640. STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data);
  641. // This function will determine the number of fonts in a font file. TrueType
  642. // collection (.ttc) files may contain multiple fonts, while TrueType font
  643. // (.ttf) files only contain one font. The number of fonts can be used for
  644. // indexing with the previous function where the index is between zero and one
  645. // less than the total fonts. If an error occurs, -1 is returned.
  646. STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
  647. // Each .ttf/.ttc file may have more than one font. Each font has a sequential
  648. // index number starting from 0. Call this function to get the font offset for
  649. // a given index; it returns -1 if the index is out of range. A regular .ttf
  650. // file will only define one font and it always be at offset 0, so it will
  651. // return '0' for index 0, and -1 for all other indices.
  652. // The following structure is defined publicly so you can declare one on
  653. // the stack or as a global or etc, but you should treat it as opaque.
  654. struct stbtt_fontinfo
  655. {
  656. void * userdata;
  657. unsigned char * data; // pointer to .ttf file
  658. int fontstart; // offset of start of font
  659. int numGlyphs; // number of glyphs, needed for range checking
  660. int loca,head,glyf,hhea,hmtx,kern,gpos; // table locations as offset from start of .ttf
  661. int index_map; // a cmap mapping for our chosen character encoding
  662. int indexToLocFormat; // format needed to map from glyph index to glyph
  663. stbtt__buf cff; // cff font data
  664. stbtt__buf charstrings; // the charstring index
  665. stbtt__buf gsubrs; // global charstring subroutines index
  666. stbtt__buf subrs; // private charstring subroutines index
  667. stbtt__buf fontdicts; // array of font dicts
  668. stbtt__buf fdselect; // map from glyph to fontdict
  669. };
  670. STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
  671. // Given an offset into the file that defines a font, this function builds
  672. // the necessary cached info for the rest of the system. You must allocate
  673. // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
  674. // need to do anything special to free it, because the contents are pure
  675. // value data with no additional data structures. Returns 0 on failure.
  676. //////////////////////////////////////////////////////////////////////////////
  677. //
  678. // CHARACTER TO GLYPH-INDEX CONVERSIOn
  679. STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
  680. // If you're going to perform multiple operations on the same character
  681. // and you want a speed-up, call this function with the character you're
  682. // going to process, then use glyph-based functions instead of the
  683. // codepoint-based functions.
  684. // Returns 0 if the character codepoint is not defined in the font.
  685. //////////////////////////////////////////////////////////////////////////////
  686. //
  687. // CHARACTER PROPERTIES
  688. //
  689. STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
  690. // computes a scale factor to produce a font whose "height" is 'pixels' tall.
  691. // Height is measured as the distance from the highest ascender to the lowest
  692. // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
  693. // and computing:
  694. // scale = pixels / (ascent - descent)
  695. // so if you prefer to measure height by the ascent only, use a similar calculation.
  696. STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
  697. // computes a scale factor to produce a font whose EM size is mapped to
  698. // 'pixels' tall. This is probably what traditional APIs compute, but
  699. // I'm not positive.
  700. STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
  701. // ascent is the coordinate above the baseline the font extends; descent
  702. // is the coordinate below the baseline the font extends (i.e. it is typically negative)
  703. // lineGap is the spacing between one row's descent and the next row's ascent...
  704. // so you should advance the vertical position by "*ascent - *descent + *lineGap"
  705. // these are expressed in unscaled coordinates, so you must multiply by
  706. // the scale factor for a given size
  707. STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap);
  708. // analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2
  709. // table (specific to MS/Windows TTF files).
  710. //
  711. // Returns 1 on success (table present), 0 on failure.
  712. STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
  713. // the bounding box around all possible characters
  714. STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
  715. // leftSideBearing is the offset from the current horizontal position to the left edge of the character
  716. // advanceWidth is the offset from the current horizontal position to the next horizontal position
  717. // these are expressed in unscaled coordinates
  718. STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
  719. // an additional amount to add to the 'advance' value between ch1 and ch2
  720. STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
  721. // Gets the bounding box of the visible part of the glyph, in unscaled coordinates
  722. STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
  723. STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
  724. STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
  725. // as above, but takes one or more glyph indices for greater efficiency
  726. //////////////////////////////////////////////////////////////////////////////
  727. //
  728. // GLYPH SHAPES (you probably don't need these, but they have to go before
  729. // the bitmaps for C declaration-order reasons)
  730. //
  731. #ifndef STBTT_vmove // you can predefine these to use different values (but why?)
  732. enum {
  733. STBTT_vmove=1,
  734. STBTT_vline,
  735. STBTT_vcurve,
  736. STBTT_vcubic
  737. };
  738. #endif
  739. #ifndef stbtt_vertex // you can predefine this to use different values
  740. // (we share this with other code at RAD)
  741. #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
  742. typedef struct
  743. {
  744. stbtt_vertex_type x,y,cx,cy,cx1,cy1;
  745. unsigned char type,padding;
  746. } stbtt_vertex;
  747. #endif
  748. STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
  749. // returns non-zero if nothing is drawn for this glyph
  750. STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
  751. STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
  752. // returns # of vertices and fills *vertices with the pointer to them
  753. // these are expressed in "unscaled" coordinates
  754. //
  755. // The shape is a series of contours. Each one starts with
  756. // a STBTT_moveto, then consists of a series of mixed
  757. // STBTT_lineto and STBTT_curveto segments. A lineto
  758. // draws a line from previous endpoint to its x,y; a curveto
  759. // draws a quadratic bezier from previous endpoint to
  760. // its x,y, using cx,cy as the bezier control point.
  761. STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
  762. // frees the data allocated above
  763. //////////////////////////////////////////////////////////////////////////////
  764. //
  765. // BITMAP RENDERING
  766. //
  767. STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
  768. // frees the bitmap allocated below
  769. STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
  770. // allocates a large-enough single-channel 8bpp bitmap and renders the
  771. // specified character/glyph at the specified scale into it, with
  772. // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
  773. // *width & *height are filled out with the width & height of the bitmap,
  774. // which is stored left-to-right, top-to-bottom.
  775. //
  776. // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
  777. STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
  778. // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
  779. // shift for the character
  780. STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint);
  781. // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
  782. // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
  783. // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
  784. // width and height and positioning info for it first.
  785. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint);
  786. // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
  787. // shift for the character
  788. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(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 oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint);
  789. // same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering
  790. // is performed (see stbtt_PackSetOversampling)
  791. STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
  792. // get the bbox of the bitmap centered around the glyph origin; so the
  793. // bitmap width is ix1-ix0, height is iy1-iy0, and location to place
  794. // the bitmap top left is (leftSideBearing*scale,iy0).
  795. // (Note that the bitmap uses y-increases-down, but the shape uses
  796. // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
  797. STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
  798. // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
  799. // shift for the character
  800. // the following functions are equivalent to the above functions, but operate
  801. // on glyph indices instead of Unicode codepoints (for efficiency)
  802. STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);
  803. STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff);
  804. STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);
  805. STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);
  806. STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(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 oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph);
  807. STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
  808. STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
  809. // @TODO: don't expose this structure
  810. typedef struct
  811. {
  812. int w,h,stride;
  813. unsigned char *pixels;
  814. } stbtt__bitmap;
  815. // rasterize a shape with quadratic beziers into a bitmap
  816. STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into
  817. float flatness_in_pixels, // allowable error of curve in pixels
  818. stbtt_vertex *vertices, // array of vertices defining shape
  819. int num_verts, // number of vertices in above array
  820. float scale_x, float scale_y, // scale applied to input vertices
  821. float shift_x, float shift_y, // translation applied to input vertices
  822. int x_off, int y_off, // another translation applied to input
  823. int invert, // if non-zero, vertically flip shape
  824. void *userdata); // context for to STBTT_MALLOC
  825. //////////////////////////////////////////////////////////////////////////////
  826. //
  827. // Signed Distance Function (or Field) rendering
  828. STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata);
  829. // frees the SDF bitmap allocated below
  830. STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
  831. STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
  832. // These functions compute a discretized SDF field for a single character, suitable for storing
  833. // in a single-channel texture, sampling with bilinear filtering, and testing against
  834. // larger than some threshold to produce scalable fonts.
  835. // info -- the font
  836. // scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap
  837. // glyph/codepoint -- the character to generate the SDF for
  838. // padding -- extra "pixels" around the character which are filled with the distance to the character (not 0),
  839. // which allows effects like bit outlines
  840. // onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character)
  841. // pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale)
  842. // if positive, > onedge_value is inside; if negative, < onedge_value is inside
  843. // width,height -- output height & width of the SDF bitmap (including padding)
  844. // xoff,yoff -- output origin of the character
  845. // return value -- a 2D array of bytes 0..255, width*height in size
  846. //
  847. // pixel_dist_scale & onedge_value are a scale & bias that allows you to make
  848. // optimal use of the limited 0..255 for your application, trading off precision
  849. // and special effects. SDF values outside the range 0..255 are clamped to 0..255.
  850. //
  851. // Example:
  852. // scale = stbtt_ScaleForPixelHeight(22)
  853. // padding = 5
  854. // onedge_value = 180
  855. // pixel_dist_scale = 180/5.0 = 36.0
  856. //
  857. // This will create an SDF bitmap in which the character is about 22 pixels
  858. // high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled
  859. // shape, sample the SDF at each pixel and fill the pixel if the SDF value
  860. // is greater than or equal to 180/255. (You'll actually want to antialias,
  861. // which is beyond the scope of this example.) Additionally, you can compute
  862. // offset outlines (e.g. to stroke the character border inside & outside,
  863. // or only outside). For example, to fill outside the character up to 3 SDF
  864. // pixels, you would compare against (180-36.0*3)/255 = 72/255. The above
  865. // choice of variables maps a range from 5 pixels outside the shape to
  866. // 2 pixels inside the shape to 0..255; this is intended primarily for apply
  867. // outside effects only (the interior range is needed to allow proper
  868. // antialiasing of the font at *smaller* sizes)
  869. //
  870. // The function computes the SDF analytically at each SDF pixel, not by e.g.
  871. // building a higher-res bitmap and approximating it. In theory the quality
  872. // should be as high as possible for an SDF of this size & representation, but
  873. // unclear if this is true in practice (perhaps building a higher-res bitmap
  874. // and computing from that can allow drop-out prevention).
  875. //
  876. // The algorithm has not been optimized at all, so expect it to be slow
  877. // if computing lots of characters or very large sizes.
  878. //////////////////////////////////////////////////////////////////////////////
  879. //
  880. // Finding the right font...
  881. //
  882. // You should really just solve this offline, keep your own tables
  883. // of what font is what, and don't try to get it out of the .ttf file.
  884. // That's because getting it out of the .ttf file is really hard, because
  885. // the names in the file can appear in many possible encodings, in many
  886. // possible languages, and e.g. if you need a case-insensitive comparison,
  887. // the details of that depend on the encoding & language in a complex way
  888. // (actually underspecified in truetype, but also gigantic).
  889. //
  890. // But you can use the provided functions in two possible ways:
  891. // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
  892. // unicode-encoded names to try to find the font you want;
  893. // you can run this before calling stbtt_InitFont()
  894. //
  895. // stbtt_GetFontNameString() lets you get any of the various strings
  896. // from the file yourself and do your own comparisons on them.
  897. // You have to have called stbtt_InitFont() first.
  898. STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
  899. // returns the offset (not index) of the font that matches, or -1 if none
  900. // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
  901. // if you use any other flag, use a font name like "Arial"; this checks
  902. // the 'macStyle' header field; i don't know if fonts set this consistently
  903. #define STBTT_MACSTYLE_DONTCARE 0
  904. #define STBTT_MACSTYLE_BOLD 1
  905. #define STBTT_MACSTYLE_ITALIC 2
  906. #define STBTT_MACSTYLE_UNDERSCORE 4
  907. #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0
  908. STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
  909. // returns 1/0 whether the first string interpreted as utf8 is identical to
  910. // the second string interpreted as big-endian utf16... useful for strings from next func
  911. STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
  912. // returns the string (which may be big-endian double byte, e.g. for unicode)
  913. // and puts the length in bytes in *length.
  914. //
  915. // some of the values for the IDs are below; for more see the truetype spec:
  916. // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
  917. // http://www.microsoft.com/typography/otspec/name.htm
  918. enum { // platformID
  919. STBTT_PLATFORM_ID_UNICODE =0,
  920. STBTT_PLATFORM_ID_MAC =1,
  921. STBTT_PLATFORM_ID_ISO =2,
  922. STBTT_PLATFORM_ID_MICROSOFT =3
  923. };
  924. enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
  925. STBTT_UNICODE_EID_UNICODE_1_0 =0,
  926. STBTT_UNICODE_EID_UNICODE_1_1 =1,
  927. STBTT_UNICODE_EID_ISO_10646 =2,
  928. STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
  929. STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
  930. };
  931. enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
  932. STBTT_MS_EID_SYMBOL =0,
  933. STBTT_MS_EID_UNICODE_BMP =1,
  934. STBTT_MS_EID_SHIFTJIS =2,
  935. STBTT_MS_EID_UNICODE_FULL =10
  936. };
  937. enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
  938. STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4,
  939. STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5,
  940. STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6,
  941. STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7
  942. };
  943. enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
  944. // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
  945. STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410,
  946. STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411,
  947. STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412,
  948. STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419,
  949. STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409,
  950. STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D
  951. };
  952. enum { // languageID for STBTT_PLATFORM_ID_MAC
  953. STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11,
  954. STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23,
  955. STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32,
  956. STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 ,
  957. STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 ,
  958. STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
  959. STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19
  960. };
  961. #ifdef __cplusplus
  962. }
  963. #endif
  964. #endif // __STB_INCLUDE_STB_TRUETYPE_H__
  965. ///////////////////////////////////////////////////////////////////////////////
  966. ///////////////////////////////////////////////////////////////////////////////
  967. ////
  968. //// IMPLEMENTATION
  969. ////
  970. ////
  971. #ifdef STB_TRUETYPE_IMPLEMENTATION
  972. #ifndef STBTT_MAX_OVERSAMPLE
  973. #define STBTT_MAX_OVERSAMPLE 8
  974. #endif
  975. #if STBTT_MAX_OVERSAMPLE > 255
  976. #error "STBTT_MAX_OVERSAMPLE cannot be > 255"
  977. #endif
  978. typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];
  979. #ifndef STBTT_RASTERIZER_VERSION
  980. #define STBTT_RASTERIZER_VERSION 2
  981. #endif
  982. #ifdef _MSC_VER
  983. #define STBTT__NOTUSED(v) (void)(v)
  984. #else
  985. #define STBTT__NOTUSED(v) (void)sizeof(v)
  986. #endif
  987. //////////////////////////////////////////////////////////////////////////
  988. //
  989. // stbtt__buf helpers to parse data from file
  990. //
  991. static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b)
  992. {
  993. if (b->cursor >= b->size)
  994. return 0;
  995. return b->data[b->cursor++];
  996. }
  997. static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b)
  998. {
  999. if (b->cursor >= b->size)
  1000. return 0;
  1001. return b->data[b->cursor];
  1002. }
  1003. static void stbtt__buf_seek(stbtt__buf *b, int o)
  1004. {
  1005. STBTT_assert(!(o > b->size || o < 0));
  1006. b->cursor = (o > b->size || o < 0) ? b->size : o;
  1007. }
  1008. static void stbtt__buf_skip(stbtt__buf *b, int o)
  1009. {
  1010. stbtt__buf_seek(b, b->cursor + o);
  1011. }
  1012. static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n)
  1013. {
  1014. stbtt_uint32 v = 0;
  1015. int i;
  1016. STBTT_assert(n >= 1 && n <= 4);
  1017. for (i = 0; i < n; i++)
  1018. v = (v << 8) | stbtt__buf_get8(b);
  1019. return v;
  1020. }
  1021. static stbtt__buf stbtt__new_buf(const void *p, size_t size)
  1022. {
  1023. stbtt__buf r;
  1024. STBTT_assert(size < 0x40000000);
  1025. r.data = (stbtt_uint8*) p;
  1026. r.size = (int) size;
  1027. r.cursor = 0;
  1028. return r;
  1029. }
  1030. #define stbtt__buf_get16(b) stbtt__buf_get((b), 2)
  1031. #define stbtt__buf_get32(b) stbtt__buf_get((b), 4)
  1032. static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s)
  1033. {
  1034. stbtt__buf r = stbtt__new_buf(NULL, 0);
  1035. if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r;
  1036. r.data = b->data + o;
  1037. r.size = s;
  1038. return r;
  1039. }
  1040. static stbtt__buf stbtt__cff_get_index(stbtt__buf *b)
  1041. {
  1042. int count, start, offsize;
  1043. start = b->cursor;
  1044. count = stbtt__buf_get16(b);
  1045. if (count) {
  1046. offsize = stbtt__buf_get8(b);
  1047. STBTT_assert(offsize >= 1 && offsize <= 4);
  1048. stbtt__buf_skip(b, offsize * count);
  1049. stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);
  1050. }
  1051. return stbtt__buf_range(b, start, b->cursor - start);
  1052. }
  1053. static stbtt_uint32 stbtt__cff_int(stbtt__buf *b)
  1054. {
  1055. int b0 = stbtt__buf_get8(b);
  1056. if (b0 >= 32 && b0 <= 246) return b0 - 139;
  1057. else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108;
  1058. else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108;
  1059. else if (b0 == 28) return stbtt__buf_get16(b);
  1060. else if (b0 == 29) return stbtt__buf_get32(b);
  1061. STBTT_assert(0);
  1062. return 0;
  1063. }
  1064. static void stbtt__cff_skip_operand(stbtt__buf *b) {
  1065. int v, b0 = stbtt__buf_peek8(b);
  1066. STBTT_assert(b0 >= 28);
  1067. if (b0 == 30) {
  1068. stbtt__buf_skip(b, 1);
  1069. while (b->cursor < b->size) {
  1070. v = stbtt__buf_get8(b);
  1071. if ((v & 0xF) == 0xF || (v >> 4) == 0xF)
  1072. break;
  1073. }
  1074. } else {
  1075. stbtt__cff_int(b);
  1076. }
  1077. }
  1078. static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key)
  1079. {
  1080. stbtt__buf_seek(b, 0);
  1081. while (b->cursor < b->size) {
  1082. int start = b->cursor, end, op;
  1083. while (stbtt__buf_peek8(b) >= 28)
  1084. stbtt__cff_skip_operand(b);
  1085. end = b->cursor;
  1086. op = stbtt__buf_get8(b);
  1087. if (op == 12) op = stbtt__buf_get8(b) | 0x100;
  1088. if (op == key) return stbtt__buf_range(b, start, end-start);
  1089. }
  1090. return stbtt__buf_range(b, 0, 0);
  1091. }
  1092. static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out)
  1093. {
  1094. int i;
  1095. stbtt__buf operands = stbtt__dict_get(b, key);
  1096. for (i = 0; i < outcount && operands.cursor < operands.size; i++)
  1097. out[i] = stbtt__cff_int(&operands);
  1098. }
  1099. static int stbtt__cff_index_count(stbtt__buf *b)
  1100. {
  1101. stbtt__buf_seek(b, 0);
  1102. return stbtt__buf_get16(b);
  1103. }
  1104. static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)
  1105. {
  1106. int count, offsize, start, end;
  1107. stbtt__buf_seek(&b, 0);
  1108. count = stbtt__buf_get16(&b);
  1109. offsize = stbtt__buf_get8(&b);
  1110. STBTT_assert(i >= 0 && i < count);
  1111. STBTT_assert(offsize >= 1 && offsize <= 4);
  1112. stbtt__buf_skip(&b, i*offsize);
  1113. start = stbtt__buf_get(&b, offsize);
  1114. end = stbtt__buf_get(&b, offsize);
  1115. return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start);
  1116. }
  1117. //////////////////////////////////////////////////////////////////////////
  1118. //
  1119. // accessors to parse data from file
  1120. //
  1121. // on platforms that don't allow misaligned reads, if we want to allow
  1122. // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
  1123. #define ttBYTE(p) (* (stbtt_uint8 *) (p))
  1124. #define ttCHAR(p) (* (stbtt_int8 *) (p))
  1125. #define ttFixed(p) ttLONG(p)
  1126. static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }
  1127. static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }
  1128. static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
  1129. static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
  1130. #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
  1131. #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])
  1132. static int stbtt__isfont(stbtt_uint8 *font)
  1133. {
  1134. // check the version number
  1135. if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1
  1136. if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!
  1137. if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF
  1138. if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
  1139. if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts
  1140. return 0;
  1141. }
  1142. // @OPTIMIZE: binary search
  1143. static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
  1144. {
  1145. stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
  1146. stbtt_uint32 tabledir = fontstart + 12;
  1147. stbtt_int32 i;
  1148. for (i=0; i < num_tables; ++i) {
  1149. stbtt_uint32 loc = tabledir + 16*i;
  1150. if (stbtt_tag(data+loc+0, tag))
  1151. return ttULONG(data+loc+8);
  1152. }
  1153. return 0;
  1154. }
  1155. static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index)
  1156. {
  1157. // if it's just a font, there's only one valid index
  1158. if (stbtt__isfont(font_collection))
  1159. return index == 0 ? 0 : -1;
  1160. // check if it's a TTC
  1161. if (stbtt_tag(font_collection, "ttcf")) {
  1162. // version 1?
  1163. if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
  1164. stbtt_int32 n = ttLONG(font_collection+8);
  1165. if (index >= n)
  1166. return -1;
  1167. return ttULONG(font_collection+12+index*4);
  1168. }
  1169. }
  1170. return -1;
  1171. }
  1172. static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection)
  1173. {
  1174. // if it's just a font, there's only one valid font
  1175. if (stbtt__isfont(font_collection))
  1176. return 1;
  1177. // check if it's a TTC
  1178. if (stbtt_tag(font_collection, "ttcf")) {
  1179. // version 1?
  1180. if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
  1181. return ttLONG(font_collection+8);
  1182. }
  1183. }
  1184. return 0;
  1185. }
  1186. static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)
  1187. {
  1188. stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };
  1189. stbtt__buf pdict;
  1190. stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);
  1191. if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);
  1192. pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);
  1193. stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);
  1194. if (!subrsoff) return stbtt__new_buf(NULL, 0);
  1195. stbtt__buf_seek(&cff, private_loc[1]+subrsoff);
  1196. return stbtt__cff_get_index(&cff);
  1197. }
  1198. static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart)
  1199. {
  1200. stbtt_uint32 cmap, t;
  1201. stbtt_int32 i,numTables;
  1202. info->data = data;
  1203. info->fontstart = fontstart;
  1204. info->cff = stbtt__new_buf(NULL, 0);
  1205. cmap = stbtt__find_table(data, fontstart, "cmap"); // required
  1206. info->loca = stbtt__find_table(data, fontstart, "loca"); // required
  1207. info->head = stbtt__find_table(data, fontstart, "head"); // required
  1208. info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
  1209. info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
  1210. info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
  1211. info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
  1212. info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required
  1213. if (!cmap || !info->head || !info->hhea || !info->hmtx)
  1214. return 0;
  1215. if (info->glyf) {
  1216. // required for truetype
  1217. if (!info->loca) return 0;
  1218. } else {
  1219. // initialization for CFF / Type2 fonts (OTF)
  1220. stbtt__buf b, topdict, topdictidx;
  1221. stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;
  1222. stbtt_uint32 cff;
  1223. cff = stbtt__find_table(data, fontstart, "CFF ");
  1224. if (!cff) return 0;
  1225. info->fontdicts = stbtt__new_buf(NULL, 0);
  1226. info->fdselect = stbtt__new_buf(NULL, 0);
  1227. // @TODO this should use size from table (not 512MB)
  1228. info->cff = stbtt__new_buf(data+cff, 512*1024*1024);
  1229. b = info->cff;
  1230. // read the header
  1231. stbtt__buf_skip(&b, 2);
  1232. stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize
  1233. // @TODO the name INDEX could list multiple fonts,
  1234. // but we just use the first one.
  1235. stbtt__cff_get_index(&b); // name INDEX
  1236. topdictidx = stbtt__cff_get_index(&b);
  1237. topdict = stbtt__cff_index_get(topdictidx, 0);
  1238. stbtt__cff_get_index(&b); // string INDEX
  1239. info->gsubrs = stbtt__cff_get_index(&b);
  1240. stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);
  1241. stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);
  1242. stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);
  1243. stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);
  1244. info->subrs = stbtt__get_subrs(b, topdict);
  1245. // we only support Type 2 charstrings
  1246. if (cstype != 2) return 0;
  1247. if (charstrings == 0) return 0;
  1248. if (fdarrayoff) {
  1249. // looks like a CID font
  1250. if (!fdselectoff) return 0;
  1251. stbtt__buf_seek(&b, fdarrayoff);
  1252. info->fontdicts = stbtt__cff_get_index(&b);
  1253. info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff);
  1254. }
  1255. stbtt__buf_seek(&b, charstrings);
  1256. info->charstrings = stbtt__cff_get_index(&b);
  1257. }
  1258. t = stbtt__find_table(data, fontstart, "maxp");
  1259. if (t)
  1260. info->numGlyphs = ttUSHORT(data+t+4);
  1261. else
  1262. info->numGlyphs = 0xffff;
  1263. // find a cmap encoding table we understand *now* to avoid searching
  1264. // later. (todo: could make this installable)
  1265. // the same regardless of glyph.
  1266. numTables = ttUSHORT(data + cmap + 2);
  1267. info->index_map = 0;
  1268. for (i=0; i < numTables; ++i) {
  1269. stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
  1270. // find an encoding we understand:
  1271. switch(ttUSHORT(data+encoding_record)) {
  1272. case STBTT_PLATFORM_ID_MICROSOFT:
  1273. switch (ttUSHORT(data+encoding_record+2)) {
  1274. case STBTT_MS_EID_UNICODE_BMP:
  1275. case STBTT_MS_EID_UNICODE_FULL:
  1276. // MS/Unicode
  1277. info->index_map = cmap + ttULONG(data+encoding_record+4);
  1278. break;
  1279. }
  1280. break;
  1281. case STBTT_PLATFORM_ID_UNICODE:
  1282. // Mac/iOS has these
  1283. // all the encodingIDs are unicode, so we don't bother to check it
  1284. info->index_map = cmap + ttULONG(data+encoding_record+4);
  1285. break;
  1286. }
  1287. }
  1288. if (info->index_map == 0)
  1289. return 0;
  1290. info->indexToLocFormat = ttUSHORT(data+info->head + 50);
  1291. return 1;
  1292. }
  1293. STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
  1294. {
  1295. stbtt_uint8 *data = info->data;
  1296. stbtt_uint32 index_map = info->index_map;
  1297. stbtt_uint16 format = ttUSHORT(data + index_map + 0);
  1298. if (format == 0) { // apple byte encoding
  1299. stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
  1300. if (unicode_codepoint < bytes-6)
  1301. return ttBYTE(data + index_map + 6 + unicode_codepoint);
  1302. return 0;
  1303. } else if (format == 6) {
  1304. stbtt_uint32 first = ttUSHORT(data + index_map + 6);
  1305. stbtt_uint32 count = ttUSHORT(data + index_map + 8);
  1306. if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
  1307. return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
  1308. return 0;
  1309. } else if (format == 2) {
  1310. STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
  1311. return 0;
  1312. } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges
  1313. stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
  1314. stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
  1315. stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
  1316. stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
  1317. // do a binary search of the segments
  1318. stbtt_uint32 endCount = index_map + 14;
  1319. stbtt_uint32 search = endCount;
  1320. if (unicode_codepoint > 0xffff)
  1321. return 0;
  1322. // they lie from endCount .. endCount + segCount
  1323. // but searchRange is the nearest power of two, so...
  1324. if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
  1325. search += rangeShift*2;
  1326. // now decrement to bias correctly to find smallest
  1327. search -= 2;
  1328. while (entrySelector) {
  1329. stbtt_uint16 end;
  1330. searchRange >>= 1;
  1331. end = ttUSHORT(data + search + searchRange*2);
  1332. if (unicode_codepoint > end)
  1333. search += searchRange*2;
  1334. --entrySelector;
  1335. }
  1336. search += 2;
  1337. {
  1338. stbtt_uint16 offset, start;
  1339. stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);
  1340. STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
  1341. start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
  1342. if (unicode_codepoint < start)
  1343. return 0;
  1344. offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
  1345. if (offset == 0)
  1346. return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
  1347. return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
  1348. }
  1349. } else if (format == 12 || format == 13) {
  1350. stbtt_uint32 ngroups = ttULONG(data+index_map+12);
  1351. stbtt_int32 low,high;
  1352. low = 0; high = (stbtt_int32)ngroups;
  1353. // Binary search the right group.
  1354. while (low < high) {
  1355. stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high
  1356. stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
  1357. stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
  1358. if ((stbtt_uint32) unicode_codepoint < start_char)
  1359. high = mid;
  1360. else if ((stbtt_uint32) unicode_codepoint > end_char)
  1361. low = mid+1;
  1362. else {
  1363. stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
  1364. if (format == 12)
  1365. return start_glyph + unicode_codepoint-start_char;
  1366. else // format == 13
  1367. return start_glyph;
  1368. }
  1369. }
  1370. return 0; // not found
  1371. }
  1372. // @TODO
  1373. STBTT_assert(0);
  1374. return 0;
  1375. }
  1376. STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
  1377. {
  1378. return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
  1379. }
  1380. static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
  1381. {
  1382. v->type = type;
  1383. v->x = (stbtt_int16) x;
  1384. v->y = (stbtt_int16) y;
  1385. v->cx = (stbtt_int16) cx;
  1386. v->cy = (stbtt_int16) cy;
  1387. }
  1388. static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
  1389. {
  1390. int g1,g2;
  1391. STBTT_assert(!info->cff.size);
  1392. if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
  1393. if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format
  1394. if (info->indexToLocFormat == 0) {
  1395. g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
  1396. g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
  1397. } else {
  1398. g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
  1399. g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
  1400. }
  1401. return g1==g2 ? -1 : g1; // if length is 0, return -1
  1402. }
  1403. static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
  1404. STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
  1405. {
  1406. if (info->cff.size) {
  1407. stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);
  1408. } else {
  1409. int g = stbtt__GetGlyfOffset(info, glyph_index);
  1410. if (g < 0) return 0;
  1411. if (x0) *x0 = ttSHORT(info->data + g + 2);
  1412. if (y0) *y0 = ttSHORT(info->data + g + 4);
  1413. if (x1) *x1 = ttSHORT(info->data + g + 6);
  1414. if (y1) *y1 = ttSHORT(info->data + g + 8);
  1415. }
  1416. return 1;
  1417. }
  1418. STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
  1419. {
  1420. return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
  1421. }
  1422. STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
  1423. {
  1424. stbtt_int16 numberOfContours;
  1425. int g;
  1426. if (info->cff.size)
  1427. return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;
  1428. g = stbtt__GetGlyfOffset(info, glyph_index);
  1429. if (g < 0) return 1;
  1430. numberOfContours = ttSHORT(info->data + g);
  1431. return numberOfContours == 0;
  1432. }
  1433. static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
  1434. stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
  1435. {
  1436. if (start_off) {
  1437. if (was_off)
  1438. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
  1439. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
  1440. } else {
  1441. if (was_off)
  1442. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
  1443. else
  1444. stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
  1445. }
  1446. return num_vertices;
  1447. }
  1448. static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
  1449. {
  1450. stbtt_int16 numberOfContours;
  1451. stbtt_uint8 *endPtsOfContours;
  1452. stbtt_uint8 *data = info->data;
  1453. stbtt_vertex *vertices=0;
  1454. int num_vertices=0;
  1455. int g = stbtt__GetGlyfOffset(info, glyph_index);
  1456. *pvertices = NULL;
  1457. if (g < 0) return 0;
  1458. numberOfContours = ttSHORT(data + g);
  1459. if (numberOfContours > 0) {
  1460. stbtt_uint8 flags=0,flagcount;
  1461. stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
  1462. stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
  1463. stbtt_uint8 *points;
  1464. endPtsOfContours = (data + g + 10);
  1465. ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
  1466. points = data + g + 10 + numberOfContours * 2 + 2 + ins;
  1467. n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
  1468. m = n + 2*numberOfContours; // a loose bound on how many vertices we might need
  1469. vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
  1470. if (vertices == 0)
  1471. return 0;
  1472. next_move = 0;
  1473. flagcount=0;
  1474. // in first pass, we load uninterpreted data into the allocated array
  1475. // above, shifted to the end of the array so we won't overwrite it when
  1476. // we create our final data starting from the front
  1477. off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
  1478. // first load flags
  1479. for (i=0; i < n; ++i) {
  1480. if (flagcount == 0) {
  1481. flags = *points++;
  1482. if (flags & 8)
  1483. flagcount = *points++;
  1484. } else
  1485. --flagcount;
  1486. vertices[off+i].type = flags;
  1487. }
  1488. // now load x coordinates
  1489. x=0;
  1490. for (i=0; i < n; ++i) {
  1491. flags = vertices[off+i].type;
  1492. if (flags & 2) {
  1493. stbtt_int16 dx = *points++;
  1494. x += (flags & 16) ? dx : -dx; // ???
  1495. } else {
  1496. if (!(flags & 16)) {
  1497. x = x + (stbtt_int16) (points[0]*256 + points[1]);
  1498. points += 2;
  1499. }
  1500. }
  1501. vertices[off+i].x = (stbtt_int16) x;
  1502. }
  1503. // now load y coordinates
  1504. y=0;
  1505. for (i=0; i < n; ++i) {
  1506. flags = vertices[off+i].type;
  1507. if (flags & 4) {
  1508. stbtt_int16 dy = *points++;
  1509. y += (flags & 32) ? dy : -dy; // ???
  1510. } else {
  1511. if (!(flags & 32)) {
  1512. y = y + (stbtt_int16) (points[0]*256 + points[1]);
  1513. points += 2;
  1514. }
  1515. }
  1516. vertices[off+i].y = (stbtt_int16) y;
  1517. }
  1518. // now convert them to our format
  1519. num_vertices=0;
  1520. sx = sy = cx = cy = scx = scy = 0;
  1521. for (i=0; i < n; ++i) {
  1522. flags = vertices[off+i].type;
  1523. x = (stbtt_int16) vertices[off+i].x;
  1524. y = (stbtt_int16) vertices[off+i].y;
  1525. if (next_move == i) {
  1526. if (i != 0)
  1527. num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
  1528. // now start the new one
  1529. start_off = !(flags & 1);
  1530. if (start_off) {
  1531. // if we start off with an off-curve point, then when we need to find a point on the curve
  1532. // where we can start, and we need to save some state for when we wraparound.
  1533. scx = x;
  1534. scy = y;
  1535. if (!(vertices[off+i+1].type & 1)) {
  1536. // next point is also a curve point, so interpolate an on-point curve
  1537. sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
  1538. sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
  1539. } else {
  1540. // otherwise just use the next point as our start point
  1541. sx = (stbtt_int32) vertices[off+i+1].x;
  1542. sy = (stbtt_int32) vertices[off+i+1].y;
  1543. ++i; // we're using point i+1 as the starting point, so skip it
  1544. }
  1545. } else {
  1546. sx = x;
  1547. sy = y;
  1548. }
  1549. stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
  1550. was_off = 0;
  1551. next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
  1552. ++j;
  1553. } else {
  1554. if (!(flags & 1)) { // if it's a curve
  1555. if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
  1556. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
  1557. cx = x;
  1558. cy = y;
  1559. was_off = 1;
  1560. } else {
  1561. if (was_off)
  1562. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
  1563. else
  1564. stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
  1565. was_off = 0;
  1566. }
  1567. }
  1568. }
  1569. num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
  1570. } else if (numberOfContours == -1) {
  1571. // Compound shapes.
  1572. int more = 1;
  1573. stbtt_uint8 *comp = data + g + 10;
  1574. num_vertices = 0;
  1575. vertices = 0;
  1576. while (more) {
  1577. stbtt_uint16 flags, gidx;
  1578. int comp_num_verts = 0, i;
  1579. stbtt_vertex *comp_verts = 0, *tmp = 0;
  1580. float mtx[6] = {1,0,0,1,0,0}, m, n;
  1581. flags = ttSHORT(comp); comp+=2;
  1582. gidx = ttSHORT(comp); comp+=2;
  1583. if (flags & 2) { // XY values
  1584. if (flags & 1) { // shorts
  1585. mtx[4] = ttSHORT(comp); comp+=2;
  1586. mtx[5] = ttSHORT(comp); comp+=2;
  1587. } else {
  1588. mtx[4] = ttCHAR(comp); comp+=1;
  1589. mtx[5] = ttCHAR(comp); comp+=1;
  1590. }
  1591. }
  1592. else {
  1593. // @TODO handle matching point
  1594. STBTT_assert(0);
  1595. }
  1596. if (flags & (1<<3)) { // WE_HAVE_A_SCALE
  1597. mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1598. mtx[1] = mtx[2] = 0;
  1599. } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
  1600. mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
  1601. mtx[1] = mtx[2] = 0;
  1602. mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1603. } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
  1604. mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
  1605. mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
  1606. mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
  1607. mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1608. }
  1609. // Find transformation scales.
  1610. m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
  1611. n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
  1612. // Get indexed glyph.
  1613. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
  1614. if (comp_num_verts > 0) {
  1615. // Transform vertices.
  1616. for (i = 0; i < comp_num_verts; ++i) {
  1617. stbtt_vertex* v = &comp_verts[i];
  1618. stbtt_vertex_type x,y;
  1619. x=v->x; y=v->y;
  1620. v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
  1621. v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
  1622. x=v->cx; y=v->cy;
  1623. v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
  1624. v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
  1625. }
  1626. // Append vertices.
  1627. tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
  1628. if (!tmp) {
  1629. if (vertices) STBTT_free(vertices, info->userdata);
  1630. if (comp_verts) STBTT_free(comp_verts, info->userdata);
  1631. return 0;
  1632. }
  1633. if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); //-V595
  1634. STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
  1635. if (vertices) STBTT_free(vertices, info->userdata);
  1636. vertices = tmp;
  1637. STBTT_free(comp_verts, info->userdata);
  1638. num_vertices += comp_num_verts;
  1639. }
  1640. // More components ?
  1641. more = flags & (1<<5);
  1642. }
  1643. } else if (numberOfContours < 0) {
  1644. // @TODO other compound variations?
  1645. STBTT_assert(0);
  1646. } else {
  1647. // numberOfCounters == 0, do nothing
  1648. }
  1649. *pvertices = vertices;
  1650. return num_vertices;
  1651. }
  1652. typedef struct
  1653. {
  1654. int bounds;
  1655. int started;
  1656. float first_x, first_y;
  1657. float x, y;
  1658. stbtt_int32 min_x, max_x, min_y, max_y;
  1659. stbtt_vertex *pvertices;
  1660. int num_vertices;
  1661. } stbtt__csctx;
  1662. #define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}
  1663. static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y)
  1664. {
  1665. if (x > c->max_x || !c->started) c->max_x = x;
  1666. if (y > c->max_y || !c->started) c->max_y = y;
  1667. if (x < c->min_x || !c->started) c->min_x = x;
  1668. if (y < c->min_y || !c->started) c->min_y = y;
  1669. c->started = 1;
  1670. }
  1671. static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)
  1672. {
  1673. if (c->bounds) {
  1674. stbtt__track_vertex(c, x, y);
  1675. if (type == STBTT_vcubic) {
  1676. stbtt__track_vertex(c, cx, cy);
  1677. stbtt__track_vertex(c, cx1, cy1);
  1678. }
  1679. } else {
  1680. stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);
  1681. c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1;
  1682. c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1;
  1683. }
  1684. c->num_vertices++;
  1685. }
  1686. static void stbtt__csctx_close_shape(stbtt__csctx *ctx)
  1687. {
  1688. if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)
  1689. stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);
  1690. }
  1691. static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy)
  1692. {
  1693. stbtt__csctx_close_shape(ctx);
  1694. ctx->first_x = ctx->x = ctx->x + dx;
  1695. ctx->first_y = ctx->y = ctx->y + dy;
  1696. stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
  1697. }
  1698. static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy)
  1699. {
  1700. ctx->x += dx;
  1701. ctx->y += dy;
  1702. stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
  1703. }
  1704. static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)
  1705. {
  1706. float cx1 = ctx->x + dx1;
  1707. float cy1 = ctx->y + dy1;
  1708. float cx2 = cx1 + dx2;
  1709. float cy2 = cy1 + dy2;
  1710. ctx->x = cx2 + dx3;
  1711. ctx->y = cy2 + dy3;
  1712. stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);
  1713. }
  1714. static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)
  1715. {
  1716. int count = stbtt__cff_index_count(&idx);
  1717. int bias = 107;
  1718. if (count >= 33900)
  1719. bias = 32768;
  1720. else if (count >= 1240)
  1721. bias = 1131;
  1722. n += bias;
  1723. if (n < 0 || n >= count)
  1724. return stbtt__new_buf(NULL, 0);
  1725. return stbtt__cff_index_get(idx, n);
  1726. }
  1727. static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index)
  1728. {
  1729. stbtt__buf fdselect = info->fdselect;
  1730. int nranges, start, end, v, fmt, fdselector = -1, i;
  1731. stbtt__buf_seek(&fdselect, 0);
  1732. fmt = stbtt__buf_get8(&fdselect);
  1733. if (fmt == 0) {
  1734. // untested
  1735. stbtt__buf_skip(&fdselect, glyph_index);
  1736. fdselector = stbtt__buf_get8(&fdselect);
  1737. } else if (fmt == 3) {
  1738. nranges = stbtt__buf_get16(&fdselect);
  1739. start = stbtt__buf_get16(&fdselect);
  1740. for (i = 0; i < nranges; i++) {
  1741. v = stbtt__buf_get8(&fdselect);
  1742. end = stbtt__buf_get16(&fdselect);
  1743. if (glyph_index >= start && glyph_index < end) {
  1744. fdselector = v;
  1745. break;
  1746. }
  1747. start = end;
  1748. }
  1749. }
  1750. if (fdselector == -1) stbtt__new_buf(NULL, 0);
  1751. return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));
  1752. }
  1753. static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c)
  1754. {
  1755. int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;
  1756. int has_subrs = 0, clear_stack;
  1757. float s[48];
  1758. stbtt__buf subr_stack[10], subrs = info->subrs, b;
  1759. float f;
  1760. #define STBTT__CSERR(s) (0)
  1761. // this currently ignores the initial width value, which isn't needed if we have hmtx
  1762. b = stbtt__cff_index_get(info->charstrings, glyph_index);
  1763. while (b.cursor < b.size) {
  1764. i = 0;
  1765. clear_stack = 1;
  1766. b0 = stbtt__buf_get8(&b);
  1767. switch (b0) {
  1768. // @TODO implement hinting
  1769. case 0x13: // hintmask
  1770. case 0x14: // cntrmask
  1771. if (in_header)
  1772. maskbits += (sp / 2); // implicit "vstem"
  1773. in_header = 0;
  1774. stbtt__buf_skip(&b, (maskbits + 7) / 8);
  1775. break;
  1776. case 0x01: // hstem
  1777. case 0x03: // vstem
  1778. case 0x12: // hstemhm
  1779. case 0x17: // vstemhm
  1780. maskbits += (sp / 2);
  1781. break;
  1782. case 0x15: // rmoveto
  1783. in_header = 0;
  1784. if (sp < 2) return STBTT__CSERR("rmoveto stack");
  1785. stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]);
  1786. break;
  1787. case 0x04: // vmoveto
  1788. in_header = 0;
  1789. if (sp < 1) return STBTT__CSERR("vmoveto stack");
  1790. stbtt__csctx_rmove_to(c, 0, s[sp-1]);
  1791. break;
  1792. case 0x16: // hmoveto
  1793. in_header = 0;
  1794. if (sp < 1) return STBTT__CSERR("hmoveto stack");
  1795. stbtt__csctx_rmove_to(c, s[sp-1], 0);
  1796. break;
  1797. case 0x05: // rlineto
  1798. if (sp < 2) return STBTT__CSERR("rlineto stack");
  1799. for (; i + 1 < sp; i += 2)
  1800. stbtt__csctx_rline_to(c, s[i], s[i+1]);
  1801. break;
  1802. // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical
  1803. // starting from a different place.
  1804. case 0x07: // vlineto
  1805. if (sp < 1) return STBTT__CSERR("vlineto stack");
  1806. goto vlineto;
  1807. case 0x06: // hlineto
  1808. if (sp < 1) return STBTT__CSERR("hlineto stack");
  1809. for (;;) {
  1810. if (i >= sp) break;
  1811. stbtt__csctx_rline_to(c, s[i], 0);
  1812. i++;
  1813. vlineto:
  1814. if (i >= sp) break;
  1815. stbtt__csctx_rline_to(c, 0, s[i]);
  1816. i++;
  1817. }
  1818. break;
  1819. case 0x1F: // hvcurveto
  1820. if (sp < 4) return STBTT__CSERR("hvcurveto stack");
  1821. goto hvcurveto;
  1822. case 0x1E: // vhcurveto
  1823. if (sp < 4) return STBTT__CSERR("vhcurveto stack");
  1824. for (;;) {
  1825. if (i + 3 >= sp) break;
  1826. stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f);
  1827. i += 4;
  1828. hvcurveto:
  1829. if (i + 3 >= sp) break;
  1830. stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]);
  1831. i += 4;
  1832. }
  1833. break;
  1834. case 0x08: // rrcurveto
  1835. if (sp < 6) return STBTT__CSERR("rcurveline stack");
  1836. for (; i + 5 < sp; i += 6)
  1837. stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
  1838. break;
  1839. case 0x18: // rcurveline
  1840. if (sp < 8) return STBTT__CSERR("rcurveline stack");
  1841. for (; i + 5 < sp - 2; i += 6)
  1842. stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
  1843. if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack");
  1844. stbtt__csctx_rline_to(c, s[i], s[i+1]);
  1845. break;
  1846. case 0x19: // rlinecurve
  1847. if (sp < 8) return STBTT__CSERR("rlinecurve stack");
  1848. for (; i + 1 < sp - 6; i += 2)
  1849. stbtt__csctx_rline_to(c, s[i], s[i+1]);
  1850. if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack");
  1851. stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
  1852. break;
  1853. case 0x1A: // vvcurveto
  1854. case 0x1B: // hhcurveto
  1855. if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack");
  1856. f = 0.0;
  1857. if (sp & 1) { f = s[i]; i++; }
  1858. for (; i + 3 < sp; i += 4) {
  1859. if (b0 == 0x1B)
  1860. stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0);
  1861. else
  1862. stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]);
  1863. f = 0.0;
  1864. }
  1865. break;
  1866. case 0x0A: // callsubr
  1867. if (!has_subrs) {
  1868. if (info->fdselect.size)
  1869. subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);
  1870. has_subrs = 1;
  1871. }
  1872. // fallthrough
  1873. case 0x1D: // callgsubr
  1874. if (sp < 1) return STBTT__CSERR("call(g|)subr stack");
  1875. v = (int) s[--sp];
  1876. if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit");
  1877. subr_stack[subr_stack_height++] = b;
  1878. b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);
  1879. if (b.size == 0) return STBTT__CSERR("subr not found");
  1880. b.cursor = 0;
  1881. clear_stack = 0;
  1882. break;
  1883. case 0x0B: // return
  1884. if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr");
  1885. b = subr_stack[--subr_stack_height];
  1886. clear_stack = 0;
  1887. break;
  1888. case 0x0E: // endchar
  1889. stbtt__csctx_close_shape(c);
  1890. return 1;
  1891. case 0x0C: { // two-byte escape
  1892. float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;
  1893. float dx, dy;
  1894. int b1 = stbtt__buf_get8(&b);
  1895. switch (b1) {
  1896. // @TODO These "flex" implementations ignore the flex-depth and resolution,
  1897. // and always draw beziers.
  1898. case 0x22: // hflex
  1899. if (sp < 7) return STBTT__CSERR("hflex stack");
  1900. dx1 = s[0];
  1901. dx2 = s[1];
  1902. dy2 = s[2];
  1903. dx3 = s[3];
  1904. dx4 = s[4];
  1905. dx5 = s[5];
  1906. dx6 = s[6];
  1907. stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);
  1908. stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);
  1909. break;
  1910. case 0x23: // flex
  1911. if (sp < 13) return STBTT__CSERR("flex stack");
  1912. dx1 = s[0];
  1913. dy1 = s[1];
  1914. dx2 = s[2];
  1915. dy2 = s[3];
  1916. dx3 = s[4];
  1917. dy3 = s[5];
  1918. dx4 = s[6];
  1919. dy4 = s[7];
  1920. dx5 = s[8];
  1921. dy5 = s[9];
  1922. dx6 = s[10];
  1923. dy6 = s[11];
  1924. //fd is s[12]
  1925. stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
  1926. stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
  1927. break;
  1928. case 0x24: // hflex1
  1929. if (sp < 9) return STBTT__CSERR("hflex1 stack");
  1930. dx1 = s[0];
  1931. dy1 = s[1];
  1932. dx2 = s[2];
  1933. dy2 = s[3];
  1934. dx3 = s[4];
  1935. dx4 = s[5];
  1936. dx5 = s[6];
  1937. dy5 = s[7];
  1938. dx6 = s[8];
  1939. stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);
  1940. stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5));
  1941. break;
  1942. case 0x25: // flex1
  1943. if (sp < 11) return STBTT__CSERR("flex1 stack");
  1944. dx1 = s[0];
  1945. dy1 = s[1];
  1946. dx2 = s[2];
  1947. dy2 = s[3];
  1948. dx3 = s[4];
  1949. dy3 = s[5];
  1950. dx4 = s[6];
  1951. dy4 = s[7];
  1952. dx5 = s[8];
  1953. dy5 = s[9];
  1954. dx6 = dy6 = s[10];
  1955. dx = dx1+dx2+dx3+dx4+dx5;
  1956. dy = dy1+dy2+dy3+dy4+dy5;
  1957. if (STBTT_fabs(dx) > STBTT_fabs(dy))
  1958. dy6 = -dy;
  1959. else
  1960. dx6 = -dx;
  1961. stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
  1962. stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
  1963. break;
  1964. default:
  1965. return STBTT__CSERR("unimplemented");
  1966. }
  1967. } break;
  1968. default:
  1969. if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254)) //-V560
  1970. return STBTT__CSERR("reserved operator");
  1971. // push immediate
  1972. if (b0 == 255) {
  1973. f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000;
  1974. } else {
  1975. stbtt__buf_skip(&b, -1);
  1976. f = (float)(stbtt_int16)stbtt__cff_int(&b);
  1977. }
  1978. if (sp >= 48) return STBTT__CSERR("push stack overflow");
  1979. s[sp++] = f;
  1980. clear_stack = 0;
  1981. break;
  1982. }
  1983. if (clear_stack) sp = 0;
  1984. }
  1985. return STBTT__CSERR("no endchar");
  1986. #undef STBTT__CSERR
  1987. }
  1988. static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
  1989. {
  1990. // runs the charstring twice, once to count and once to output (to avoid realloc)
  1991. stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);
  1992. stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);
  1993. if (stbtt__run_charstring(info, glyph_index, &count_ctx)) {
  1994. *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata);
  1995. output_ctx.pvertices = *pvertices;
  1996. if (stbtt__run_charstring(info, glyph_index, &output_ctx)) {
  1997. STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);
  1998. return output_ctx.num_vertices;
  1999. }
  2000. }
  2001. *pvertices = NULL;
  2002. return 0;
  2003. }
  2004. static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
  2005. {
  2006. stbtt__csctx c = STBTT__CSCTX_INIT(1);
  2007. int r = stbtt__run_charstring(info, glyph_index, &c);
  2008. if (x0) *x0 = r ? c.min_x : 0;
  2009. if (y0) *y0 = r ? c.min_y : 0;
  2010. if (x1) *x1 = r ? c.max_x : 0;
  2011. if (y1) *y1 = r ? c.max_y : 0;
  2012. return r ? c.num_vertices : 0;
  2013. }
  2014. STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
  2015. {
  2016. if (!info->cff.size)
  2017. return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);
  2018. else
  2019. return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);
  2020. }
  2021. STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
  2022. {
  2023. stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
  2024. if (glyph_index < numOfLongHorMetrics) {
  2025. if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index);
  2026. if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
  2027. } else {
  2028. if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
  2029. if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
  2030. }
  2031. }
  2032. static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
  2033. {
  2034. stbtt_uint8 *data = info->data + info->kern;
  2035. stbtt_uint32 needle, straw;
  2036. int l, r, m;
  2037. // we only look at the first table. it must be 'horizontal' and format 0.
  2038. if (!info->kern)
  2039. return 0;
  2040. if (ttUSHORT(data+2) < 1) // number of tables, need at least 1
  2041. return 0;
  2042. if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format
  2043. return 0;
  2044. l = 0;
  2045. r = ttUSHORT(data+10) - 1;
  2046. needle = glyph1 << 16 | glyph2;
  2047. while (l <= r) {
  2048. m = (l + r) >> 1;
  2049. straw = ttULONG(data+18+(m*6)); // note: unaligned read
  2050. if (needle < straw)
  2051. r = m - 1;
  2052. else if (needle > straw)
  2053. l = m + 1;
  2054. else
  2055. return ttSHORT(data+22+(m*6));
  2056. }
  2057. return 0;
  2058. }
  2059. static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph)
  2060. {
  2061. stbtt_uint16 coverageFormat = ttUSHORT(coverageTable);
  2062. switch(coverageFormat) {
  2063. case 1: {
  2064. stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2);
  2065. // Binary search.
  2066. stbtt_int32 l=0, r=glyphCount-1, m;
  2067. int straw, needle=glyph;
  2068. while (l <= r) {
  2069. stbtt_uint8 *glyphArray = coverageTable + 4;
  2070. stbtt_uint16 glyphID;
  2071. m = (l + r) >> 1;
  2072. glyphID = ttUSHORT(glyphArray + 2 * m);
  2073. straw = glyphID;
  2074. if (needle < straw)
  2075. r = m - 1;
  2076. else if (needle > straw)
  2077. l = m + 1;
  2078. else {
  2079. return m;
  2080. }
  2081. }
  2082. } break;
  2083. case 2: {
  2084. stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2);
  2085. stbtt_uint8 *rangeArray = coverageTable + 4;
  2086. // Binary search.
  2087. stbtt_int32 l=0, r=rangeCount-1, m;
  2088. int strawStart, strawEnd, needle=glyph;
  2089. while (l <= r) {
  2090. stbtt_uint8 *rangeRecord;
  2091. m = (l + r) >> 1;
  2092. rangeRecord = rangeArray + 6 * m;
  2093. strawStart = ttUSHORT(rangeRecord);
  2094. strawEnd = ttUSHORT(rangeRecord + 2);
  2095. if (needle < strawStart)
  2096. r = m - 1;
  2097. else if (needle > strawEnd)
  2098. l = m + 1;
  2099. else {
  2100. stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4);
  2101. return startCoverageIndex + glyph - strawStart;
  2102. }
  2103. }
  2104. } break;
  2105. default: {
  2106. // There are no other cases.
  2107. STBTT_assert(0);
  2108. } break;
  2109. }
  2110. return -1;
  2111. }
  2112. static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph)
  2113. {
  2114. stbtt_uint16 classDefFormat = ttUSHORT(classDefTable);
  2115. switch(classDefFormat)
  2116. {
  2117. case 1: {
  2118. stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2);
  2119. stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4);
  2120. stbtt_uint8 *classDef1ValueArray = classDefTable + 6;
  2121. if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount)
  2122. return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID));
  2123. // [DEAR IMGUI] Commented to fix static analyzer warning
  2124. //classDefTable = classDef1ValueArray + 2 * glyphCount;
  2125. } break;
  2126. case 2: {
  2127. stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2);
  2128. stbtt_uint8 *classRangeRecords = classDefTable + 4;
  2129. // Binary search.
  2130. stbtt_int32 l=0, r=classRangeCount-1, m;
  2131. int strawStart, strawEnd, needle=glyph;
  2132. while (l <= r) {
  2133. stbtt_uint8 *classRangeRecord;
  2134. m = (l + r) >> 1;
  2135. classRangeRecord = classRangeRecords + 6 * m;
  2136. strawStart = ttUSHORT(classRangeRecord);
  2137. strawEnd = ttUSHORT(classRangeRecord + 2);
  2138. if (needle < strawStart)
  2139. r = m - 1;
  2140. else if (needle > strawEnd)
  2141. l = m + 1;
  2142. else
  2143. return (stbtt_int32)ttUSHORT(classRangeRecord + 4);
  2144. }
  2145. // [DEAR IMGUI] Commented to fix static analyzer warning
  2146. //classDefTable = classRangeRecords + 6 * classRangeCount;
  2147. } break;
  2148. default: {
  2149. // There are no other cases.
  2150. STBTT_assert(0);
  2151. } break;
  2152. }
  2153. return -1;
  2154. }
  2155. // Define to STBTT_assert(x) if you want to break on unimplemented formats.
  2156. #define STBTT_GPOS_TODO_assert(x)
  2157. static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
  2158. {
  2159. stbtt_uint16 lookupListOffset;
  2160. stbtt_uint8 *lookupList;
  2161. stbtt_uint16 lookupCount;
  2162. stbtt_uint8 *data;
  2163. stbtt_int32 i;
  2164. if (!info->gpos) return 0;
  2165. data = info->data + info->gpos;
  2166. if (ttUSHORT(data+0) != 1) return 0; // Major version 1
  2167. if (ttUSHORT(data+2) != 0) return 0; // Minor version 0
  2168. lookupListOffset = ttUSHORT(data+8);
  2169. lookupList = data + lookupListOffset;
  2170. lookupCount = ttUSHORT(lookupList);
  2171. for (i=0; i<lookupCount; ++i) {
  2172. stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i);
  2173. stbtt_uint8 *lookupTable = lookupList + lookupOffset;
  2174. stbtt_uint16 lookupType = ttUSHORT(lookupTable);
  2175. stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4);
  2176. stbtt_uint8 *subTableOffsets = lookupTable + 6;
  2177. switch(lookupType) {
  2178. case 2: { // Pair Adjustment Positioning Subtable
  2179. stbtt_int32 sti;
  2180. for (sti=0; sti<subTableCount; sti++) {
  2181. stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti);
  2182. stbtt_uint8 *table = lookupTable + subtableOffset;
  2183. stbtt_uint16 posFormat = ttUSHORT(table);
  2184. stbtt_uint16 coverageOffset = ttUSHORT(table + 2);
  2185. stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1);
  2186. if (coverageIndex == -1) continue;
  2187. switch (posFormat) {
  2188. case 1: {
  2189. stbtt_int32 l, r, m;
  2190. int straw, needle;
  2191. stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
  2192. stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
  2193. stbtt_int32 valueRecordPairSizeInBytes = 2;
  2194. stbtt_uint16 pairSetCount = ttUSHORT(table + 8);
  2195. stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex);
  2196. stbtt_uint8 *pairValueTable = table + pairPosOffset;
  2197. stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable);
  2198. stbtt_uint8 *pairValueArray = pairValueTable + 2;
  2199. // TODO: Support more formats.
  2200. STBTT_GPOS_TODO_assert(valueFormat1 == 4);
  2201. if (valueFormat1 != 4) return 0;
  2202. STBTT_GPOS_TODO_assert(valueFormat2 == 0);
  2203. if (valueFormat2 != 0) return 0;
  2204. STBTT_assert(coverageIndex < pairSetCount);
  2205. STBTT__NOTUSED(pairSetCount);
  2206. needle=glyph2;
  2207. r=pairValueCount-1;
  2208. l=0;
  2209. // Binary search.
  2210. while (l <= r) {
  2211. stbtt_uint16 secondGlyph;
  2212. stbtt_uint8 *pairValue;
  2213. m = (l + r) >> 1;
  2214. pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m;
  2215. secondGlyph = ttUSHORT(pairValue);
  2216. straw = secondGlyph;
  2217. if (needle < straw)
  2218. r = m - 1;
  2219. else if (needle > straw)
  2220. l = m + 1;
  2221. else {
  2222. stbtt_int16 xAdvance = ttSHORT(pairValue + 2);
  2223. return xAdvance;
  2224. }
  2225. }
  2226. } break;
  2227. case 2: {
  2228. stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
  2229. stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
  2230. stbtt_uint16 classDef1Offset = ttUSHORT(table + 8);
  2231. stbtt_uint16 classDef2Offset = ttUSHORT(table + 10);
  2232. int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1);
  2233. int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2);
  2234. stbtt_uint16 class1Count = ttUSHORT(table + 12);
  2235. stbtt_uint16 class2Count = ttUSHORT(table + 14);
  2236. STBTT_assert(glyph1class < class1Count);
  2237. STBTT_assert(glyph2class < class2Count);
  2238. // TODO: Support more formats.
  2239. STBTT_GPOS_TODO_assert(valueFormat1 == 4);
  2240. if (valueFormat1 != 4) return 0;
  2241. STBTT_GPOS_TODO_assert(valueFormat2 == 0);
  2242. if (valueFormat2 != 0) return 0;
  2243. if (glyph1class >= 0 && glyph1class < class1Count && glyph2class >= 0 && glyph2class < class2Count) {
  2244. stbtt_uint8 *class1Records = table + 16;
  2245. stbtt_uint8 *class2Records = class1Records + 2 * (glyph1class * class2Count);
  2246. stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class);
  2247. return xAdvance;
  2248. }
  2249. } break;
  2250. default: {
  2251. // There are no other cases.
  2252. STBTT_assert(0);
  2253. break;
  2254. } // [DEAR IMGUI] removed ;
  2255. }
  2256. }
  2257. break;
  2258. } // [DEAR IMGUI] removed ;
  2259. default:
  2260. // TODO: Implement other stuff.
  2261. break;
  2262. }
  2263. }
  2264. return 0;
  2265. }
  2266. STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2)
  2267. {
  2268. int xAdvance = 0;
  2269. if (info->gpos)
  2270. xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);
  2271. if (info->kern)
  2272. xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);
  2273. return xAdvance;
  2274. }
  2275. STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
  2276. {
  2277. if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs
  2278. return 0;
  2279. return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
  2280. }
  2281. STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
  2282. {
  2283. stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
  2284. }
  2285. STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
  2286. {
  2287. if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4);
  2288. if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
  2289. if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
  2290. }
  2291. STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap)
  2292. {
  2293. int tab = stbtt__find_table(info->data, info->fontstart, "OS/2");
  2294. if (!tab)
  2295. return 0;
  2296. if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68);
  2297. if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70);
  2298. if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72);
  2299. return 1;
  2300. }
  2301. STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
  2302. {
  2303. *x0 = ttSHORT(info->data + info->head + 36);
  2304. *y0 = ttSHORT(info->data + info->head + 38);
  2305. *x1 = ttSHORT(info->data + info->head + 40);
  2306. *y1 = ttSHORT(info->data + info->head + 42);
  2307. }
  2308. STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
  2309. {
  2310. int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
  2311. return (float) height / fheight;
  2312. }
  2313. STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
  2314. {
  2315. int unitsPerEm = ttUSHORT(info->data + info->head + 18);
  2316. return pixels / unitsPerEm;
  2317. }
  2318. STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
  2319. {
  2320. STBTT_free(v, info->userdata);
  2321. }
  2322. //////////////////////////////////////////////////////////////////////////////
  2323. //
  2324. // antialiasing software rasterizer
  2325. //
  2326. STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
  2327. {
  2328. int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning
  2329. if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {
  2330. // e.g. space character
  2331. if (ix0) *ix0 = 0;
  2332. if (iy0) *iy0 = 0;
  2333. if (ix1) *ix1 = 0;
  2334. if (iy1) *iy1 = 0;
  2335. } else {
  2336. // move to integral bboxes (treating pixels as little squares, what pixels get touched)?
  2337. if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);
  2338. if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);
  2339. if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);
  2340. if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);
  2341. }
  2342. }
  2343. STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
  2344. {
  2345. stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
  2346. }
  2347. STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
  2348. {
  2349. stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
  2350. }
  2351. STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
  2352. {
  2353. stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
  2354. }
  2355. //////////////////////////////////////////////////////////////////////////////
  2356. //
  2357. // Rasterizer
  2358. typedef struct stbtt__hheap_chunk
  2359. {
  2360. struct stbtt__hheap_chunk *next;
  2361. } stbtt__hheap_chunk;
  2362. typedef struct stbtt__hheap
  2363. {
  2364. struct stbtt__hheap_chunk *head;
  2365. void *first_free;
  2366. int num_remaining_in_head_chunk;
  2367. } stbtt__hheap;
  2368. static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)
  2369. {
  2370. if (hh->first_free) {
  2371. void *p = hh->first_free;
  2372. hh->first_free = * (void **) p;
  2373. return p;
  2374. } else {
  2375. if (hh->num_remaining_in_head_chunk == 0) {
  2376. int count = (size < 32 ? 2000 : size < 128 ? 800 : 100);
  2377. stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);
  2378. if (c == NULL)
  2379. return NULL;
  2380. c->next = hh->head;
  2381. hh->head = c;
  2382. hh->num_remaining_in_head_chunk = count;
  2383. }
  2384. --hh->num_remaining_in_head_chunk;
  2385. return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk;
  2386. }
  2387. }
  2388. static void stbtt__hheap_free(stbtt__hheap *hh, void *p)
  2389. {
  2390. *(void **) p = hh->first_free;
  2391. hh->first_free = p;
  2392. }
  2393. static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata)
  2394. {
  2395. stbtt__hheap_chunk *c = hh->head;
  2396. while (c) {
  2397. stbtt__hheap_chunk *n = c->next;
  2398. STBTT_free(c, userdata);
  2399. c = n;
  2400. }
  2401. }
  2402. typedef struct stbtt__edge {
  2403. float x0,y0, x1,y1;
  2404. int invert;
  2405. } stbtt__edge;
  2406. typedef struct stbtt__active_edge
  2407. {
  2408. struct stbtt__active_edge *next;
  2409. #if STBTT_RASTERIZER_VERSION==1
  2410. int x,dx;
  2411. float ey;
  2412. int direction;
  2413. #elif STBTT_RASTERIZER_VERSION==2
  2414. float fx,fdx,fdy;
  2415. float direction;
  2416. float sy;
  2417. float ey;
  2418. #else
  2419. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2420. #endif
  2421. } stbtt__active_edge;
  2422. #if STBTT_RASTERIZER_VERSION == 1
  2423. #define STBTT_FIXSHIFT 10
  2424. #define STBTT_FIX (1 << STBTT_FIXSHIFT)
  2425. #define STBTT_FIXMASK (STBTT_FIX-1)
  2426. static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
  2427. {
  2428. stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
  2429. float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
  2430. STBTT_assert(z != NULL);
  2431. if (!z) return z;
  2432. // round dx down to avoid overshooting
  2433. if (dxdy < 0)
  2434. z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);
  2435. else
  2436. z->dx = STBTT_ifloor(STBTT_FIX * dxdy);
  2437. z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount
  2438. z->x -= off_x * STBTT_FIX;
  2439. z->ey = e->y1;
  2440. z->next = 0;
  2441. z->direction = e->invert ? 1 : -1;
  2442. return z;
  2443. }
  2444. #elif STBTT_RASTERIZER_VERSION == 2
  2445. static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
  2446. {
  2447. stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
  2448. float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
  2449. STBTT_assert(z != NULL);
  2450. //STBTT_assert(e->y0 <= start_point);
  2451. if (!z) return z;
  2452. z->fdx = dxdy;
  2453. z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f;
  2454. z->fx = e->x0 + dxdy * (start_point - e->y0);
  2455. z->fx -= off_x;
  2456. z->direction = e->invert ? 1.0f : -1.0f;
  2457. z->sy = e->y0;
  2458. z->ey = e->y1;
  2459. z->next = 0;
  2460. return z;
  2461. }
  2462. #else
  2463. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2464. #endif
  2465. #if STBTT_RASTERIZER_VERSION == 1
  2466. // note: this routine clips fills that extend off the edges... ideally this
  2467. // wouldn't happen, but it could happen if the truetype glyph bounding boxes
  2468. // are wrong, or if the user supplies a too-small bitmap
  2469. static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
  2470. {
  2471. // non-zero winding fill
  2472. int x0=0, w=0;
  2473. while (e) {
  2474. if (w == 0) {
  2475. // if we're currently at zero, we need to record the edge start point
  2476. x0 = e->x; w += e->direction;
  2477. } else {
  2478. int x1 = e->x; w += e->direction;
  2479. // if we went to zero, we need to draw
  2480. if (w == 0) {
  2481. int i = x0 >> STBTT_FIXSHIFT;
  2482. int j = x1 >> STBTT_FIXSHIFT;
  2483. if (i < len && j >= 0) {
  2484. if (i == j) {
  2485. // x0,x1 are the same pixel, so compute combined coverage
  2486. scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT);
  2487. } else {
  2488. if (i >= 0) // add antialiasing for x0
  2489. scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);
  2490. else
  2491. i = -1; // clip
  2492. if (j < len) // add antialiasing for x1
  2493. scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);
  2494. else
  2495. j = len; // clip
  2496. for (++i; i < j; ++i) // fill pixels between x0 and x1
  2497. scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
  2498. }
  2499. }
  2500. }
  2501. }
  2502. e = e->next;
  2503. }
  2504. }
  2505. static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
  2506. {
  2507. stbtt__hheap hh = { 0, 0, 0 };
  2508. stbtt__active_edge *active = NULL;
  2509. int y,j=0;
  2510. int max_weight = (255 / vsubsample); // weight per vertical scanline
  2511. int s; // vertical subsample index
  2512. unsigned char scanline_data[512], *scanline;
  2513. if (result->w > 512)
  2514. scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
  2515. else
  2516. scanline = scanline_data;
  2517. y = off_y * vsubsample;
  2518. e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
  2519. while (j < result->h) {
  2520. STBTT_memset(scanline, 0, result->w);
  2521. for (s=0; s < vsubsample; ++s) {
  2522. // find center of pixel for this scanline
  2523. float scan_y = y + 0.5f;
  2524. stbtt__active_edge **step = &active;
  2525. // update all active edges;
  2526. // remove all active edges that terminate before the center of this scanline
  2527. while (*step) {
  2528. stbtt__active_edge * z = *step;
  2529. if (z->ey <= scan_y) {
  2530. *step = z->next; // delete from list
  2531. STBTT_assert(z->direction);
  2532. z->direction = 0;
  2533. stbtt__hheap_free(&hh, z);
  2534. } else {
  2535. z->x += z->dx; // advance to position for current scanline
  2536. step = &((*step)->next); // advance through list
  2537. }
  2538. }
  2539. // resort the list if needed
  2540. for(;;) {
  2541. int changed=0;
  2542. step = &active;
  2543. while (*step && (*step)->next) {
  2544. if ((*step)->x > (*step)->next->x) {
  2545. stbtt__active_edge *t = *step;
  2546. stbtt__active_edge *q = t->next;
  2547. t->next = q->next;
  2548. q->next = t;
  2549. *step = q;
  2550. changed = 1;
  2551. }
  2552. step = &(*step)->next;
  2553. }
  2554. if (!changed) break;
  2555. }
  2556. // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
  2557. while (e->y0 <= scan_y) {
  2558. if (e->y1 > scan_y) {
  2559. stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);
  2560. if (z != NULL) {
  2561. // find insertion point
  2562. if (active == NULL)
  2563. active = z;
  2564. else if (z->x < active->x) {
  2565. // insert at front
  2566. z->next = active;
  2567. active = z;
  2568. } else {
  2569. // find thing to insert AFTER
  2570. stbtt__active_edge *p = active;
  2571. while (p->next && p->next->x < z->x)
  2572. p = p->next;
  2573. // at this point, p->next->x is NOT < z->x
  2574. z->next = p->next;
  2575. p->next = z;
  2576. }
  2577. }
  2578. }
  2579. ++e;
  2580. }
  2581. // now process all active edges in XOR fashion
  2582. if (active)
  2583. stbtt__fill_active_edges(scanline, result->w, active, max_weight);
  2584. ++y;
  2585. }
  2586. STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
  2587. ++j;
  2588. }
  2589. stbtt__hheap_cleanup(&hh, userdata);
  2590. if (scanline != scanline_data)
  2591. STBTT_free(scanline, userdata);
  2592. }
  2593. #elif STBTT_RASTERIZER_VERSION == 2
  2594. // the edge passed in here does not cross the vertical line at x or the vertical line at x+1
  2595. // (i.e. it has already been clipped to those)
  2596. static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1)
  2597. {
  2598. if (y0 == y1) return;
  2599. STBTT_assert(y0 < y1);
  2600. STBTT_assert(e->sy <= e->ey);
  2601. if (y0 > e->ey) return;
  2602. if (y1 < e->sy) return;
  2603. if (y0 < e->sy) {
  2604. x0 += (x1-x0) * (e->sy - y0) / (y1-y0);
  2605. y0 = e->sy;
  2606. }
  2607. if (y1 > e->ey) {
  2608. x1 += (x1-x0) * (e->ey - y1) / (y1-y0);
  2609. y1 = e->ey;
  2610. }
  2611. if (x0 == x)
  2612. STBTT_assert(x1 <= x+1);
  2613. else if (x0 == x+1)
  2614. STBTT_assert(x1 >= x);
  2615. else if (x0 <= x)
  2616. STBTT_assert(x1 <= x);
  2617. else if (x0 >= x+1)
  2618. STBTT_assert(x1 >= x+1);
  2619. else
  2620. STBTT_assert(x1 >= x && x1 <= x+1);
  2621. if (x0 <= x && x1 <= x)
  2622. scanline[x] += e->direction * (y1-y0);
  2623. else if (x0 >= x+1 && x1 >= x+1)
  2624. ;
  2625. else {
  2626. STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1);
  2627. scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position
  2628. }
  2629. }
  2630. static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top)
  2631. {
  2632. float y_bottom = y_top+1;
  2633. while (e) {
  2634. // brute force every pixel
  2635. // compute intersection points with top & bottom
  2636. STBTT_assert(e->ey >= y_top);
  2637. if (e->fdx == 0) {
  2638. float x0 = e->fx;
  2639. if (x0 < len) {
  2640. if (x0 >= 0) {
  2641. stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom);
  2642. stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom);
  2643. } else {
  2644. stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom);
  2645. }
  2646. }
  2647. } else {
  2648. float x0 = e->fx;
  2649. float dx = e->fdx;
  2650. float xb = x0 + dx;
  2651. float x_top, x_bottom;
  2652. float sy0,sy1;
  2653. float dy = e->fdy;
  2654. STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);
  2655. // compute endpoints of line segment clipped to this scanline (if the
  2656. // line segment starts on this scanline. x0 is the intersection of the
  2657. // line with y_top, but that may be off the line segment.
  2658. if (e->sy > y_top) {
  2659. x_top = x0 + dx * (e->sy - y_top);
  2660. sy0 = e->sy;
  2661. } else {
  2662. x_top = x0;
  2663. sy0 = y_top;
  2664. }
  2665. if (e->ey < y_bottom) {
  2666. x_bottom = x0 + dx * (e->ey - y_top);
  2667. sy1 = e->ey;
  2668. } else {
  2669. x_bottom = xb;
  2670. sy1 = y_bottom;
  2671. }
  2672. if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {
  2673. // from here on, we don't have to range check x values
  2674. if ((int) x_top == (int) x_bottom) {
  2675. float height;
  2676. // simple case, only spans one pixel
  2677. int x = (int) x_top;
  2678. height = sy1 - sy0;
  2679. STBTT_assert(x >= 0 && x < len);
  2680. scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height;
  2681. scanline_fill[x] += e->direction * height; // everything right of this pixel is filled
  2682. } else {
  2683. int x,x1,x2;
  2684. float y_crossing, step, sign, area;
  2685. // covers 2+ pixels
  2686. if (x_top > x_bottom) {
  2687. // flip scanline vertically; signed area is the same
  2688. float t;
  2689. sy0 = y_bottom - (sy0 - y_top);
  2690. sy1 = y_bottom - (sy1 - y_top);
  2691. t = sy0, sy0 = sy1, sy1 = t;
  2692. t = x_bottom, x_bottom = x_top, x_top = t;
  2693. dx = -dx;
  2694. dy = -dy;
  2695. t = x0, x0 = xb, xb = t;
  2696. // [DEAR IMGUI] Fix static analyzer warning
  2697. (void)dx; // [ImGui: fix static analyzer warning]
  2698. }
  2699. x1 = (int) x_top;
  2700. x2 = (int) x_bottom;
  2701. // compute intersection with y axis at x1+1
  2702. y_crossing = (x1+1 - x0) * dy + y_top;
  2703. sign = e->direction;
  2704. // area of the rectangle covered from y0..y_crossing
  2705. area = sign * (y_crossing-sy0);
  2706. // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing)
  2707. scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2);
  2708. step = sign * dy;
  2709. for (x = x1+1; x < x2; ++x) {
  2710. scanline[x] += area + step/2;
  2711. area += step;
  2712. }
  2713. y_crossing += dy * (x2 - (x1+1));
  2714. STBTT_assert(STBTT_fabs(area) <= 1.01f);
  2715. scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing);
  2716. scanline_fill[x2] += sign * (sy1-sy0);
  2717. }
  2718. } else {
  2719. // if edge goes outside of box we're drawing, we require
  2720. // clipping logic. since this does not match the intended use
  2721. // of this library, we use a different, very slow brute
  2722. // force implementation
  2723. int x;
  2724. for (x=0; x < len; ++x) {
  2725. // cases:
  2726. //
  2727. // there can be up to two intersections with the pixel. any intersection
  2728. // with left or right edges can be handled by splitting into two (or three)
  2729. // regions. intersections with top & bottom do not necessitate case-wise logic.
  2730. //
  2731. // the old way of doing this found the intersections with the left & right edges,
  2732. // then used some simple logic to produce up to three segments in sorted order
  2733. // from top-to-bottom. however, this had a problem: if an x edge was epsilon
  2734. // across the x border, then the corresponding y position might not be distinct
  2735. // from the other y segment, and it might ignored as an empty segment. to avoid
  2736. // that, we need to explicitly produce segments based on x positions.
  2737. // rename variables to clearly-defined pairs
  2738. float y0 = y_top;
  2739. float x1 = (float) (x);
  2740. float x2 = (float) (x+1);
  2741. float x3 = xb;
  2742. float y3 = y_bottom;
  2743. // x = e->x + e->dx * (y-y_top)
  2744. // (y-y_top) = (x - e->x) / e->dx
  2745. // y = (x - e->x) / e->dx + y_top
  2746. float y1 = (x - x0) / dx + y_top;
  2747. float y2 = (x+1 - x0) / dx + y_top;
  2748. if (x0 < x1 && x3 > x2) { // three segments descending down-right
  2749. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
  2750. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2);
  2751. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
  2752. } else if (x3 < x1 && x0 > x2) { // three segments descending down-left
  2753. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
  2754. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1);
  2755. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
  2756. } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right
  2757. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
  2758. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
  2759. } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left
  2760. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
  2761. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
  2762. } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right
  2763. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
  2764. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
  2765. } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left
  2766. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
  2767. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
  2768. } else { // one segment
  2769. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3);
  2770. }
  2771. }
  2772. }
  2773. }
  2774. e = e->next;
  2775. }
  2776. }
  2777. // directly AA rasterize edges w/o supersampling
  2778. static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
  2779. {
  2780. stbtt__hheap hh = { 0, 0, 0 };
  2781. stbtt__active_edge *active = NULL;
  2782. int y,j=0, i;
  2783. float scanline_data[129], *scanline, *scanline2;
  2784. STBTT__NOTUSED(vsubsample);
  2785. if (result->w > 64)
  2786. scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata);
  2787. else
  2788. scanline = scanline_data;
  2789. scanline2 = scanline + result->w;
  2790. y = off_y;
  2791. e[n].y0 = (float) (off_y + result->h) + 1;
  2792. while (j < result->h) {
  2793. // find center of pixel for this scanline
  2794. float scan_y_top = y + 0.0f;
  2795. float scan_y_bottom = y + 1.0f;
  2796. stbtt__active_edge **step = &active;
  2797. STBTT_memset(scanline , 0, result->w*sizeof(scanline[0]));
  2798. STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0]));
  2799. // update all active edges;
  2800. // remove all active edges that terminate before the top of this scanline
  2801. while (*step) {
  2802. stbtt__active_edge * z = *step;
  2803. if (z->ey <= scan_y_top) {
  2804. *step = z->next; // delete from list
  2805. STBTT_assert(z->direction);
  2806. z->direction = 0;
  2807. stbtt__hheap_free(&hh, z);
  2808. } else {
  2809. step = &((*step)->next); // advance through list
  2810. }
  2811. }
  2812. // insert all edges that start before the bottom of this scanline
  2813. while (e->y0 <= scan_y_bottom) {
  2814. if (e->y0 != e->y1) {
  2815. stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);
  2816. if (z != NULL) {
  2817. if (j == 0 && off_y != 0) {
  2818. if (z->ey < scan_y_top) {
  2819. // this can happen due to subpixel positioning and some kind of fp rounding error i think
  2820. z->ey = scan_y_top;
  2821. }
  2822. }
  2823. STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds
  2824. // insert at front
  2825. z->next = active;
  2826. active = z;
  2827. }
  2828. }
  2829. ++e;
  2830. }
  2831. // now process all active edges
  2832. if (active)
  2833. stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top);
  2834. {
  2835. float sum = 0;
  2836. for (i=0; i < result->w; ++i) {
  2837. float k;
  2838. int m;
  2839. sum += scanline2[i];
  2840. k = scanline[i] + sum;
  2841. k = (float) STBTT_fabs(k)*255 + 0.5f;
  2842. m = (int) k;
  2843. if (m > 255) m = 255;
  2844. result->pixels[j*result->stride + i] = (unsigned char) m;
  2845. }
  2846. }
  2847. // advance all the edges
  2848. step = &active;
  2849. while (*step) {
  2850. stbtt__active_edge *z = *step;
  2851. z->fx += z->fdx; // advance to position for current scanline
  2852. step = &((*step)->next); // advance through list
  2853. }
  2854. ++y;
  2855. ++j;
  2856. }
  2857. stbtt__hheap_cleanup(&hh, userdata);
  2858. if (scanline != scanline_data)
  2859. STBTT_free(scanline, userdata);
  2860. }
  2861. #else
  2862. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2863. #endif
  2864. #define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0)
  2865. static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n)
  2866. {
  2867. int i,j;
  2868. for (i=1; i < n; ++i) {
  2869. stbtt__edge t = p[i], *a = &t;
  2870. j = i;
  2871. while (j > 0) {
  2872. stbtt__edge *b = &p[j-1];
  2873. int c = STBTT__COMPARE(a,b);
  2874. if (!c) break;
  2875. p[j] = p[j-1];
  2876. --j;
  2877. }
  2878. if (i != j)
  2879. p[j] = t;
  2880. }
  2881. }
  2882. static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n)
  2883. {
  2884. /* threshold for transitioning to insertion sort */
  2885. while (n > 12) {
  2886. stbtt__edge t;
  2887. int c01,c12,c,m,i,j;
  2888. /* compute median of three */
  2889. m = n >> 1;
  2890. c01 = STBTT__COMPARE(&p[0],&p[m]);
  2891. c12 = STBTT__COMPARE(&p[m],&p[n-1]);
  2892. /* if 0 >= mid >= end, or 0 < mid < end, then use mid */
  2893. if (c01 != c12) {
  2894. /* otherwise, we'll need to swap something else to middle */
  2895. int z;
  2896. c = STBTT__COMPARE(&p[0],&p[n-1]);
  2897. /* 0>mid && mid<n: 0>n => n; 0<n => 0 */
  2898. /* 0<mid && mid>n: 0>n => 0; 0<n => n */
  2899. z = (c == c12) ? 0 : n-1;
  2900. t = p[z];
  2901. p[z] = p[m];
  2902. p[m] = t;
  2903. }
  2904. /* now p[m] is the median-of-three */
  2905. /* swap it to the beginning so it won't move around */
  2906. t = p[0];
  2907. p[0] = p[m];
  2908. p[m] = t;
  2909. /* partition loop */
  2910. i=1;
  2911. j=n-1;
  2912. for(;;) {
  2913. /* handling of equality is crucial here */
  2914. /* for sentinels & efficiency with duplicates */
  2915. for (;;++i) {
  2916. if (!STBTT__COMPARE(&p[i], &p[0])) break;
  2917. }
  2918. for (;;--j) {
  2919. if (!STBTT__COMPARE(&p[0], &p[j])) break;
  2920. }
  2921. /* make sure we haven't crossed */
  2922. if (i >= j) break;
  2923. t = p[i];
  2924. p[i] = p[j];
  2925. p[j] = t;
  2926. ++i;
  2927. --j;
  2928. }
  2929. /* recurse on smaller side, iterate on larger */
  2930. if (j < (n-i)) {
  2931. stbtt__sort_edges_quicksort(p,j);
  2932. p = p+i;
  2933. n = n-i;
  2934. } else {
  2935. stbtt__sort_edges_quicksort(p+i, n-i);
  2936. n = j;
  2937. }
  2938. }
  2939. }
  2940. static void stbtt__sort_edges(stbtt__edge *p, int n)
  2941. {
  2942. stbtt__sort_edges_quicksort(p, n);
  2943. stbtt__sort_edges_ins_sort(p, n);
  2944. }
  2945. typedef struct
  2946. {
  2947. float x,y;
  2948. } stbtt__point;
  2949. 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)
  2950. {
  2951. float y_scale_inv = invert ? -scale_y : scale_y;
  2952. stbtt__edge *e;
  2953. int n,i,j,k,m;
  2954. #if STBTT_RASTERIZER_VERSION == 1
  2955. int vsubsample = result->h < 8 ? 15 : 5;
  2956. #elif STBTT_RASTERIZER_VERSION == 2
  2957. int vsubsample = 1;
  2958. #else
  2959. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2960. #endif
  2961. // vsubsample should divide 255 evenly; otherwise we won't reach full opacity
  2962. // now we have to blow out the windings into explicit edge lists
  2963. n = 0;
  2964. for (i=0; i < windings; ++i)
  2965. n += wcount[i];
  2966. e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel
  2967. if (e == 0) return;
  2968. n = 0;
  2969. m=0;
  2970. for (i=0; i < windings; ++i) {
  2971. stbtt__point *p = pts + m;
  2972. m += wcount[i];
  2973. j = wcount[i]-1;
  2974. for (k=0; k < wcount[i]; j=k++) {
  2975. int a=k,b=j;
  2976. // skip the edge if horizontal
  2977. if (p[j].y == p[k].y)
  2978. continue;
  2979. // add edge from j to k to the list
  2980. e[n].invert = 0;
  2981. if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
  2982. e[n].invert = 1;
  2983. a=j,b=k;
  2984. }
  2985. e[n].x0 = p[a].x * scale_x + shift_x;
  2986. e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;
  2987. e[n].x1 = p[b].x * scale_x + shift_x;
  2988. e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;
  2989. ++n;
  2990. }
  2991. }
  2992. // now sort the edges by their highest point (should snap to integer, and then by x)
  2993. //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
  2994. stbtt__sort_edges(e, n);
  2995. // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
  2996. stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
  2997. STBTT_free(e, userdata);
  2998. }
  2999. static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
  3000. {
  3001. if (!points) return; // during first pass, it's unallocated
  3002. points[n].x = x;
  3003. points[n].y = y;
  3004. }
  3005. // tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching
  3006. 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)
  3007. {
  3008. // midpoint
  3009. float mx = (x0 + 2*x1 + x2)/4;
  3010. float my = (y0 + 2*y1 + y2)/4;
  3011. // versus directly drawn line
  3012. float dx = (x0+x2)/2 - mx;
  3013. float dy = (y0+y2)/2 - my;
  3014. if (n > 16) // 65536 segments on one curve better be enough!
  3015. return 1;
  3016. if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
  3017. stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
  3018. stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
  3019. } else {
  3020. stbtt__add_point(points, *num_points,x2,y2);
  3021. *num_points = *num_points+1;
  3022. }
  3023. return 1;
  3024. }
  3025. static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n)
  3026. {
  3027. // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough
  3028. float dx0 = x1-x0;
  3029. float dy0 = y1-y0;
  3030. float dx1 = x2-x1;
  3031. float dy1 = y2-y1;
  3032. float dx2 = x3-x2;
  3033. float dy2 = y3-y2;
  3034. float dx = x3-x0;
  3035. float dy = y3-y0;
  3036. float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2));
  3037. float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy);
  3038. float flatness_squared = longlen*longlen-shortlen*shortlen;
  3039. if (n > 16) // 65536 segments on one curve better be enough!
  3040. return;
  3041. if (flatness_squared > objspace_flatness_squared) {
  3042. float x01 = (x0+x1)/2;
  3043. float y01 = (y0+y1)/2;
  3044. float x12 = (x1+x2)/2;
  3045. float y12 = (y1+y2)/2;
  3046. float x23 = (x2+x3)/2;
  3047. float y23 = (y2+y3)/2;
  3048. float xa = (x01+x12)/2;
  3049. float ya = (y01+y12)/2;
  3050. float xb = (x12+x23)/2;
  3051. float yb = (y12+y23)/2;
  3052. float mx = (xa+xb)/2;
  3053. float my = (ya+yb)/2;
  3054. stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1);
  3055. stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1);
  3056. } else {
  3057. stbtt__add_point(points, *num_points,x3,y3);
  3058. *num_points = *num_points+1;
  3059. }
  3060. }
  3061. // returns number of contours
  3062. static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
  3063. {
  3064. stbtt__point *points=0;
  3065. int num_points=0;
  3066. float objspace_flatness_squared = objspace_flatness * objspace_flatness;
  3067. int i,n=0,start=0, pass;
  3068. // count how many "moves" there are to get the contour count
  3069. for (i=0; i < num_verts; ++i)
  3070. if (vertices[i].type == STBTT_vmove)
  3071. ++n;
  3072. *num_contours = n;
  3073. if (n == 0) return 0;
  3074. *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
  3075. if (*contour_lengths == 0) {
  3076. *num_contours = 0;
  3077. return 0;
  3078. }
  3079. // make two passes through the points so we don't need to realloc
  3080. for (pass=0; pass < 2; ++pass) {
  3081. float x=0,y=0;
  3082. if (pass == 1) {
  3083. points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
  3084. if (points == NULL) goto error;
  3085. }
  3086. num_points = 0;
  3087. n= -1;
  3088. for (i=0; i < num_verts; ++i) {
  3089. switch (vertices[i].type) {
  3090. case STBTT_vmove:
  3091. // start the next contour
  3092. if (n >= 0)
  3093. (*contour_lengths)[n] = num_points - start;
  3094. ++n;
  3095. start = num_points;
  3096. x = vertices[i].x, y = vertices[i].y;
  3097. stbtt__add_point(points, num_points++, x,y);
  3098. break;
  3099. case STBTT_vline:
  3100. x = vertices[i].x, y = vertices[i].y;
  3101. stbtt__add_point(points, num_points++, x, y);
  3102. break;
  3103. case STBTT_vcurve:
  3104. stbtt__tesselate_curve(points, &num_points, x,y,
  3105. vertices[i].cx, vertices[i].cy,
  3106. vertices[i].x, vertices[i].y,
  3107. objspace_flatness_squared, 0);
  3108. x = vertices[i].x, y = vertices[i].y;
  3109. break;
  3110. case STBTT_vcubic:
  3111. stbtt__tesselate_cubic(points, &num_points, x,y,
  3112. vertices[i].cx, vertices[i].cy,
  3113. vertices[i].cx1, vertices[i].cy1,
  3114. vertices[i].x, vertices[i].y,
  3115. objspace_flatness_squared, 0);
  3116. x = vertices[i].x, y = vertices[i].y;
  3117. break;
  3118. }
  3119. }
  3120. (*contour_lengths)[n] = num_points - start;
  3121. }
  3122. return points;
  3123. error:
  3124. STBTT_free(points, userdata);
  3125. STBTT_free(*contour_lengths, userdata);
  3126. *contour_lengths = 0;
  3127. *num_contours = 0;
  3128. return NULL;
  3129. }
  3130. STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata)
  3131. {
  3132. float scale = scale_x > scale_y ? scale_y : scale_x;
  3133. int winding_count = 0;
  3134. int *winding_lengths = NULL;
  3135. stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
  3136. if (windings) {
  3137. stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
  3138. STBTT_free(winding_lengths, userdata);
  3139. STBTT_free(windings, userdata);
  3140. }
  3141. }
  3142. STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
  3143. {
  3144. STBTT_free(bitmap, userdata);
  3145. }
  3146. STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff)
  3147. {
  3148. int ix0,iy0,ix1,iy1;
  3149. stbtt__bitmap gbm;
  3150. stbtt_vertex *vertices;
  3151. int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
  3152. if (scale_x == 0) scale_x = scale_y;
  3153. if (scale_y == 0) {
  3154. if (scale_x == 0) {
  3155. STBTT_free(vertices, info->userdata);
  3156. return NULL;
  3157. }
  3158. scale_y = scale_x;
  3159. }
  3160. stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
  3161. // now we get the size
  3162. gbm.w = (ix1 - ix0);
  3163. gbm.h = (iy1 - iy0);
  3164. gbm.pixels = NULL; // in case we error
  3165. if (width ) *width = gbm.w;
  3166. if (height) *height = gbm.h;
  3167. if (xoff ) *xoff = ix0;
  3168. if (yoff ) *yoff = iy0;
  3169. if (gbm.w && gbm.h) {
  3170. gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
  3171. if (gbm.pixels) {
  3172. gbm.stride = gbm.w;
  3173. stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
  3174. }
  3175. }
  3176. STBTT_free(vertices, info->userdata);
  3177. return gbm.pixels;
  3178. }
  3179. STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)
  3180. {
  3181. return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
  3182. }
  3183. STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph)
  3184. {
  3185. int ix0,iy0;
  3186. stbtt_vertex *vertices;
  3187. int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
  3188. stbtt__bitmap gbm;
  3189. stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
  3190. gbm.pixels = output;
  3191. gbm.w = out_w;
  3192. gbm.h = out_h;
  3193. gbm.stride = out_stride;
  3194. if (gbm.w && gbm.h)
  3195. stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
  3196. STBTT_free(vertices, info->userdata);
  3197. }
  3198. STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph)
  3199. {
  3200. stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
  3201. }
  3202. STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
  3203. {
  3204. return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
  3205. }
  3206. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(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 oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint)
  3207. {
  3208. stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint));
  3209. }
  3210. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint)
  3211. {
  3212. stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
  3213. }
  3214. STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
  3215. {
  3216. return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
  3217. }
  3218. STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint)
  3219. {
  3220. stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
  3221. }
  3222. //////////////////////////////////////////////////////////////////////////////
  3223. //
  3224. // bitmap baking
  3225. //
  3226. // This is SUPER-CRAPPY packing to keep source code small
  3227. static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
  3228. float pixel_height, // height of font in pixels
  3229. unsigned char *pixels, int pw, int ph, // bitmap to be filled in
  3230. int first_char, int num_chars, // characters to bake
  3231. stbtt_bakedchar *chardata)
  3232. {
  3233. float scale;
  3234. int x,y,bottom_y, i;
  3235. stbtt_fontinfo f;
  3236. f.userdata = NULL;
  3237. if (!stbtt_InitFont(&f, data, offset))
  3238. return -1;
  3239. STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
  3240. x=y=1;
  3241. bottom_y = 1;
  3242. scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
  3243. for (i=0; i < num_chars; ++i) {
  3244. int advance, lsb, x0,y0,x1,y1,gw,gh;
  3245. int g = stbtt_FindGlyphIndex(&f, first_char + i);
  3246. stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
  3247. stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
  3248. gw = x1-x0;
  3249. gh = y1-y0;
  3250. if (x + gw + 1 >= pw)
  3251. y = bottom_y, x = 1; // advance to next row
  3252. if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
  3253. return -i;
  3254. STBTT_assert(x+gw < pw);
  3255. STBTT_assert(y+gh < ph);
  3256. stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
  3257. chardata[i].x0 = (stbtt_int16) x;
  3258. chardata[i].y0 = (stbtt_int16) y;
  3259. chardata[i].x1 = (stbtt_int16) (x + gw);
  3260. chardata[i].y1 = (stbtt_int16) (y + gh);
  3261. chardata[i].xadvance = scale * advance;
  3262. chardata[i].xoff = (float) x0;
  3263. chardata[i].yoff = (float) y0;
  3264. x = x + gw + 1;
  3265. if (y+gh+1 > bottom_y)
  3266. bottom_y = y+gh+1;
  3267. }
  3268. return bottom_y;
  3269. }
  3270. STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
  3271. {
  3272. float d3d_bias = opengl_fillrule ? 0 : -0.5f;
  3273. float ipw = 1.0f / pw, iph = 1.0f / ph;
  3274. const stbtt_bakedchar *b = chardata + char_index;
  3275. int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);
  3276. int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);
  3277. q->x0 = round_x + d3d_bias;
  3278. q->y0 = round_y + d3d_bias;
  3279. q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
  3280. q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
  3281. q->s0 = b->x0 * ipw;
  3282. q->t0 = b->y0 * iph;
  3283. q->s1 = b->x1 * ipw;
  3284. q->t1 = b->y1 * iph;
  3285. *xpos += b->xadvance;
  3286. }
  3287. //////////////////////////////////////////////////////////////////////////////
  3288. //
  3289. // rectangle packing replacement routines if you don't have stb_rect_pack.h
  3290. //
  3291. #ifndef STB_RECT_PACK_VERSION
  3292. typedef int stbrp_coord;
  3293. ////////////////////////////////////////////////////////////////////////////////////
  3294. // //
  3295. // //
  3296. // COMPILER WARNING ?!?!? //
  3297. // //
  3298. // //
  3299. // if you get a compile warning due to these symbols being defined more than //
  3300. // once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" //
  3301. // //
  3302. ////////////////////////////////////////////////////////////////////////////////////
  3303. typedef struct
  3304. {
  3305. int width,height;
  3306. int x,y,bottom_y;
  3307. } stbrp_context;
  3308. typedef struct
  3309. {
  3310. unsigned char x;
  3311. } stbrp_node;
  3312. struct stbrp_rect
  3313. {
  3314. stbrp_coord x,y;
  3315. int id,w,h,was_packed;
  3316. };
  3317. static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)
  3318. {
  3319. con->width = pw;
  3320. con->height = ph;
  3321. con->x = 0;
  3322. con->y = 0;
  3323. con->bottom_y = 0;
  3324. STBTT__NOTUSED(nodes);
  3325. STBTT__NOTUSED(num_nodes);
  3326. }
  3327. static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)
  3328. {
  3329. int i;
  3330. for (i=0; i < num_rects; ++i) {
  3331. if (con->x + rects[i].w > con->width) {
  3332. con->x = 0;
  3333. con->y = con->bottom_y;
  3334. }
  3335. if (con->y + rects[i].h > con->height)
  3336. break;
  3337. rects[i].x = con->x;
  3338. rects[i].y = con->y;
  3339. rects[i].was_packed = 1;
  3340. con->x += rects[i].w;
  3341. if (con->y + rects[i].h > con->bottom_y)
  3342. con->bottom_y = con->y + rects[i].h;
  3343. }
  3344. for ( ; i < num_rects; ++i)
  3345. rects[i].was_packed = 0;
  3346. }
  3347. #endif
  3348. //////////////////////////////////////////////////////////////////////////////
  3349. //
  3350. // bitmap baking
  3351. //
  3352. // This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If
  3353. // stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.
  3354. STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context)
  3355. {
  3356. stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context);
  3357. int num_nodes = pw - padding;
  3358. stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context);
  3359. if (context == NULL || nodes == NULL) {
  3360. if (context != NULL) STBTT_free(context, alloc_context);
  3361. if (nodes != NULL) STBTT_free(nodes , alloc_context);
  3362. return 0;
  3363. }
  3364. spc->user_allocator_context = alloc_context;
  3365. spc->width = pw;
  3366. spc->height = ph;
  3367. spc->pixels = pixels;
  3368. spc->pack_info = context;
  3369. spc->nodes = nodes;
  3370. spc->padding = padding;
  3371. spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;
  3372. spc->h_oversample = 1;
  3373. spc->v_oversample = 1;
  3374. spc->skip_missing = 0;
  3375. stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);
  3376. if (pixels)
  3377. STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
  3378. return 1;
  3379. }
  3380. STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc)
  3381. {
  3382. STBTT_free(spc->nodes , spc->user_allocator_context);
  3383. STBTT_free(spc->pack_info, spc->user_allocator_context);
  3384. }
  3385. STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)
  3386. {
  3387. STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);
  3388. STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);
  3389. if (h_oversample <= STBTT_MAX_OVERSAMPLE)
  3390. spc->h_oversample = h_oversample;
  3391. if (v_oversample <= STBTT_MAX_OVERSAMPLE)
  3392. spc->v_oversample = v_oversample;
  3393. }
  3394. STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip)
  3395. {
  3396. spc->skip_missing = skip;
  3397. }
  3398. #define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1)
  3399. static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
  3400. {
  3401. unsigned char buffer[STBTT_MAX_OVERSAMPLE];
  3402. int safe_w = w - kernel_width;
  3403. int j;
  3404. STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
  3405. for (j=0; j < h; ++j) {
  3406. int i;
  3407. unsigned int total;
  3408. STBTT_memset(buffer, 0, kernel_width);
  3409. total = 0;
  3410. // make kernel_width a constant in common cases so compiler can optimize out the divide
  3411. switch (kernel_width) {
  3412. case 2:
  3413. for (i=0; i <= safe_w; ++i) {
  3414. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3415. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3416. pixels[i] = (unsigned char) (total / 2);
  3417. }
  3418. break;
  3419. case 3:
  3420. for (i=0; i <= safe_w; ++i) {
  3421. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3422. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3423. pixels[i] = (unsigned char) (total / 3);
  3424. }
  3425. break;
  3426. case 4:
  3427. for (i=0; i <= safe_w; ++i) {
  3428. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3429. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3430. pixels[i] = (unsigned char) (total / 4);
  3431. }
  3432. break;
  3433. case 5:
  3434. for (i=0; i <= safe_w; ++i) {
  3435. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3436. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3437. pixels[i] = (unsigned char) (total / 5);
  3438. }
  3439. break;
  3440. default:
  3441. for (i=0; i <= safe_w; ++i) {
  3442. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3443. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3444. pixels[i] = (unsigned char) (total / kernel_width);
  3445. }
  3446. break;
  3447. }
  3448. for (; i < w; ++i) {
  3449. STBTT_assert(pixels[i] == 0);
  3450. total -= buffer[i & STBTT__OVER_MASK];
  3451. pixels[i] = (unsigned char) (total / kernel_width);
  3452. }
  3453. pixels += stride_in_bytes;
  3454. }
  3455. }
  3456. static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
  3457. {
  3458. unsigned char buffer[STBTT_MAX_OVERSAMPLE];
  3459. int safe_h = h - kernel_width;
  3460. int j;
  3461. STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
  3462. for (j=0; j < w; ++j) {
  3463. int i;
  3464. unsigned int total;
  3465. STBTT_memset(buffer, 0, kernel_width);
  3466. total = 0;
  3467. // make kernel_width a constant in common cases so compiler can optimize out the divide
  3468. switch (kernel_width) {
  3469. case 2:
  3470. for (i=0; i <= safe_h; ++i) {
  3471. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3472. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3473. pixels[i*stride_in_bytes] = (unsigned char) (total / 2);
  3474. }
  3475. break;
  3476. case 3:
  3477. for (i=0; i <= safe_h; ++i) {
  3478. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3479. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3480. pixels[i*stride_in_bytes] = (unsigned char) (total / 3);
  3481. }
  3482. break;
  3483. case 4:
  3484. for (i=0; i <= safe_h; ++i) {
  3485. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3486. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3487. pixels[i*stride_in_bytes] = (unsigned char) (total / 4);
  3488. }
  3489. break;
  3490. case 5:
  3491. for (i=0; i <= safe_h; ++i) {
  3492. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3493. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3494. pixels[i*stride_in_bytes] = (unsigned char) (total / 5);
  3495. }
  3496. break;
  3497. default:
  3498. for (i=0; i <= safe_h; ++i) {
  3499. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3500. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3501. pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
  3502. }
  3503. break;
  3504. }
  3505. for (; i < h; ++i) {
  3506. STBTT_assert(pixels[i*stride_in_bytes] == 0);
  3507. total -= buffer[i & STBTT__OVER_MASK];
  3508. pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
  3509. }
  3510. pixels += 1;
  3511. }
  3512. }
  3513. static float stbtt__oversample_shift(int oversample)
  3514. {
  3515. if (!oversample)
  3516. return 0.0f;
  3517. // The prefilter is a box filter of width "oversample",
  3518. // which shifts phase by (oversample - 1)/2 pixels in
  3519. // oversampled space. We want to shift in the opposite
  3520. // direction to counter this.
  3521. return (float)-(oversample - 1) / (2.0f * (float)oversample);
  3522. }
  3523. // rects array must be big enough to accommodate all characters in the given ranges
  3524. STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
  3525. {
  3526. int i,j,k;
  3527. k=0;
  3528. for (i=0; i < num_ranges; ++i) {
  3529. float fh = ranges[i].font_size;
  3530. float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
  3531. ranges[i].h_oversample = (unsigned char) spc->h_oversample;
  3532. ranges[i].v_oversample = (unsigned char) spc->v_oversample;
  3533. for (j=0; j < ranges[i].num_chars; ++j) {
  3534. int x0,y0,x1,y1;
  3535. int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
  3536. int glyph = stbtt_FindGlyphIndex(info, codepoint);
  3537. if (glyph == 0 && spc->skip_missing) {
  3538. rects[k].w = rects[k].h = 0;
  3539. } else {
  3540. stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,
  3541. scale * spc->h_oversample,
  3542. scale * spc->v_oversample,
  3543. 0,0,
  3544. &x0,&y0,&x1,&y1);
  3545. rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);
  3546. rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);
  3547. }
  3548. ++k;
  3549. }
  3550. }
  3551. return k;
  3552. }
  3553. STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(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 prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph)
  3554. {
  3555. stbtt_MakeGlyphBitmapSubpixel(info,
  3556. output,
  3557. out_w - (prefilter_x - 1),
  3558. out_h - (prefilter_y - 1),
  3559. out_stride,
  3560. scale_x,
  3561. scale_y,
  3562. shift_x,
  3563. shift_y,
  3564. glyph);
  3565. if (prefilter_x > 1)
  3566. stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x);
  3567. if (prefilter_y > 1)
  3568. stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y);
  3569. *sub_x = stbtt__oversample_shift(prefilter_x);
  3570. *sub_y = stbtt__oversample_shift(prefilter_y);
  3571. }
  3572. // rects array must be big enough to accommodate all characters in the given ranges
  3573. STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
  3574. {
  3575. int i,j,k, return_value = 1;
  3576. // save current values
  3577. int old_h_over = spc->h_oversample;
  3578. int old_v_over = spc->v_oversample;
  3579. k = 0;
  3580. for (i=0; i < num_ranges; ++i) {
  3581. float fh = ranges[i].font_size;
  3582. float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
  3583. float recip_h,recip_v,sub_x,sub_y;
  3584. spc->h_oversample = ranges[i].h_oversample;
  3585. spc->v_oversample = ranges[i].v_oversample;
  3586. recip_h = 1.0f / spc->h_oversample;
  3587. recip_v = 1.0f / spc->v_oversample;
  3588. sub_x = stbtt__oversample_shift(spc->h_oversample);
  3589. sub_y = stbtt__oversample_shift(spc->v_oversample);
  3590. for (j=0; j < ranges[i].num_chars; ++j) {
  3591. stbrp_rect *r = &rects[k];
  3592. if (r->was_packed && r->w != 0 && r->h != 0) {
  3593. stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];
  3594. int advance, lsb, x0,y0,x1,y1;
  3595. int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
  3596. int glyph = stbtt_FindGlyphIndex(info, codepoint);
  3597. stbrp_coord pad = (stbrp_coord) spc->padding;
  3598. // pad on left and top
  3599. r->x += pad;
  3600. r->y += pad;
  3601. r->w -= pad;
  3602. r->h -= pad;
  3603. stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);
  3604. stbtt_GetGlyphBitmapBox(info, glyph,
  3605. scale * spc->h_oversample,
  3606. scale * spc->v_oversample,
  3607. &x0,&y0,&x1,&y1);
  3608. stbtt_MakeGlyphBitmapSubpixel(info,
  3609. spc->pixels + r->x + r->y*spc->stride_in_bytes,
  3610. r->w - spc->h_oversample+1,
  3611. r->h - spc->v_oversample+1,
  3612. spc->stride_in_bytes,
  3613. scale * spc->h_oversample,
  3614. scale * spc->v_oversample,
  3615. 0,0,
  3616. glyph);
  3617. if (spc->h_oversample > 1)
  3618. stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
  3619. r->w, r->h, spc->stride_in_bytes,
  3620. spc->h_oversample);
  3621. if (spc->v_oversample > 1)
  3622. stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
  3623. r->w, r->h, spc->stride_in_bytes,
  3624. spc->v_oversample);
  3625. bc->x0 = (stbtt_int16) r->x;
  3626. bc->y0 = (stbtt_int16) r->y;
  3627. bc->x1 = (stbtt_int16) (r->x + r->w);
  3628. bc->y1 = (stbtt_int16) (r->y + r->h);
  3629. bc->xadvance = scale * advance;
  3630. bc->xoff = (float) x0 * recip_h + sub_x;
  3631. bc->yoff = (float) y0 * recip_v + sub_y;
  3632. bc->xoff2 = (x0 + r->w) * recip_h + sub_x;
  3633. bc->yoff2 = (y0 + r->h) * recip_v + sub_y;
  3634. } else {
  3635. return_value = 0; // if any fail, report failure
  3636. }
  3637. ++k;
  3638. }
  3639. }
  3640. // restore original values
  3641. spc->h_oversample = old_h_over;
  3642. spc->v_oversample = old_v_over;
  3643. return return_value;
  3644. }
  3645. STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects)
  3646. {
  3647. stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);
  3648. }
  3649. STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)
  3650. {
  3651. stbtt_fontinfo info;
  3652. int i,j,n, return_value; // [DEAR IMGUI] removed = 1
  3653. //stbrp_context *context = (stbrp_context *) spc->pack_info;
  3654. stbrp_rect *rects;
  3655. // flag all characters as NOT packed
  3656. for (i=0; i < num_ranges; ++i)
  3657. for (j=0; j < ranges[i].num_chars; ++j)
  3658. ranges[i].chardata_for_range[j].x0 =
  3659. ranges[i].chardata_for_range[j].y0 =
  3660. ranges[i].chardata_for_range[j].x1 =
  3661. ranges[i].chardata_for_range[j].y1 = 0;
  3662. n = 0;
  3663. for (i=0; i < num_ranges; ++i)
  3664. n += ranges[i].num_chars;
  3665. rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
  3666. if (rects == NULL)
  3667. return 0;
  3668. info.userdata = spc->user_allocator_context;
  3669. stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));
  3670. n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);
  3671. stbtt_PackFontRangesPackRects(spc, rects, n);
  3672. return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);
  3673. STBTT_free(rects, spc->user_allocator_context);
  3674. return return_value;
  3675. }
  3676. STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
  3677. int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)
  3678. {
  3679. stbtt_pack_range range;
  3680. range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;
  3681. range.array_of_unicode_codepoints = NULL;
  3682. range.num_chars = num_chars_in_range;
  3683. range.chardata_for_range = chardata_for_range;
  3684. range.font_size = font_size;
  3685. return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
  3686. }
  3687. STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap)
  3688. {
  3689. int i_ascent, i_descent, i_lineGap;
  3690. float scale;
  3691. stbtt_fontinfo info;
  3692. stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index));
  3693. scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size);
  3694. stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap);
  3695. *ascent = (float) i_ascent * scale;
  3696. *descent = (float) i_descent * scale;
  3697. *lineGap = (float) i_lineGap * scale;
  3698. }
  3699. STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)
  3700. {
  3701. float ipw = 1.0f / pw, iph = 1.0f / ph;
  3702. const stbtt_packedchar *b = chardata + char_index;
  3703. if (align_to_integer) {
  3704. float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);
  3705. float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f);
  3706. q->x0 = x;
  3707. q->y0 = y;
  3708. q->x1 = x + b->xoff2 - b->xoff;
  3709. q->y1 = y + b->yoff2 - b->yoff;
  3710. } else {
  3711. q->x0 = *xpos + b->xoff;
  3712. q->y0 = *ypos + b->yoff;
  3713. q->x1 = *xpos + b->xoff2;
  3714. q->y1 = *ypos + b->yoff2;
  3715. }
  3716. q->s0 = b->x0 * ipw;
  3717. q->t0 = b->y0 * iph;
  3718. q->s1 = b->x1 * ipw;
  3719. q->t1 = b->y1 * iph;
  3720. *xpos += b->xadvance;
  3721. }
  3722. //////////////////////////////////////////////////////////////////////////////
  3723. //
  3724. // sdf computation
  3725. //
  3726. #define STBTT_min(a,b) ((a) < (b) ? (a) : (b))
  3727. #define STBTT_max(a,b) ((a) < (b) ? (b) : (a))
  3728. static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2])
  3729. {
  3730. float q0perp = q0[1]*ray[0] - q0[0]*ray[1];
  3731. float q1perp = q1[1]*ray[0] - q1[0]*ray[1];
  3732. float q2perp = q2[1]*ray[0] - q2[0]*ray[1];
  3733. float roperp = orig[1]*ray[0] - orig[0]*ray[1];
  3734. float a = q0perp - 2*q1perp + q2perp;
  3735. float b = q1perp - q0perp;
  3736. float c = q0perp - roperp;
  3737. float s0 = 0., s1 = 0.;
  3738. int num_s = 0;
  3739. if (a != 0.0) {
  3740. float discr = b*b - a*c;
  3741. if (discr > 0.0) {
  3742. float rcpna = -1 / a;
  3743. float d = (float) STBTT_sqrt(discr);
  3744. s0 = (b+d) * rcpna;
  3745. s1 = (b-d) * rcpna;
  3746. if (s0 >= 0.0 && s0 <= 1.0)
  3747. num_s = 1;
  3748. if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) {
  3749. if (num_s == 0) s0 = s1;
  3750. ++num_s;
  3751. }
  3752. }
  3753. } else {
  3754. // 2*b*s + c = 0
  3755. // s = -c / (2*b)
  3756. s0 = c / (-2 * b);
  3757. if (s0 >= 0.0 && s0 <= 1.0)
  3758. num_s = 1;
  3759. }
  3760. if (num_s == 0)
  3761. return 0;
  3762. else {
  3763. float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]);
  3764. float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2;
  3765. float q0d = q0[0]*rayn_x + q0[1]*rayn_y;
  3766. float q1d = q1[0]*rayn_x + q1[1]*rayn_y;
  3767. float q2d = q2[0]*rayn_x + q2[1]*rayn_y;
  3768. float rod = orig[0]*rayn_x + orig[1]*rayn_y;
  3769. float q10d = q1d - q0d;
  3770. float q20d = q2d - q0d;
  3771. float q0rd = q0d - rod;
  3772. hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d;
  3773. hits[0][1] = a*s0+b;
  3774. if (num_s > 1) {
  3775. hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d;
  3776. hits[1][1] = a*s1+b;
  3777. return 2;
  3778. } else {
  3779. return 1;
  3780. }
  3781. }
  3782. }
  3783. static int equal(float *a, float *b)
  3784. {
  3785. return (a[0] == b[0] && a[1] == b[1]);
  3786. }
  3787. static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts)
  3788. {
  3789. int i;
  3790. float orig[2], ray[2] = { 1, 0 };
  3791. float y_frac;
  3792. int winding = 0;
  3793. orig[0] = x;
  3794. //orig[1] = y; // [DEAR IMGUI] commmented double assignment
  3795. // make sure y never passes through a vertex of the shape
  3796. y_frac = (float) STBTT_fmod(y, 1.0f);
  3797. if (y_frac < 0.01f)
  3798. y += 0.01f;
  3799. else if (y_frac > 0.99f)
  3800. y -= 0.01f;
  3801. orig[1] = y;
  3802. // test a ray from (-infinity,y) to (x,y)
  3803. for (i=0; i < nverts; ++i) {
  3804. if (verts[i].type == STBTT_vline) {
  3805. int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y;
  3806. int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y;
  3807. if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
  3808. float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
  3809. if (x_inter < x)
  3810. winding += (y0 < y1) ? 1 : -1;
  3811. }
  3812. }
  3813. if (verts[i].type == STBTT_vcurve) {
  3814. int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ;
  3815. int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy;
  3816. int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ;
  3817. int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2));
  3818. int by = STBTT_max(y0,STBTT_max(y1,y2));
  3819. if (y > ay && y < by && x > ax) {
  3820. float q0[2],q1[2],q2[2];
  3821. float hits[2][2];
  3822. q0[0] = (float)x0;
  3823. q0[1] = (float)y0;
  3824. q1[0] = (float)x1;
  3825. q1[1] = (float)y1;
  3826. q2[0] = (float)x2;
  3827. q2[1] = (float)y2;
  3828. if (equal(q0,q1) || equal(q1,q2)) {
  3829. x0 = (int)verts[i-1].x;
  3830. y0 = (int)verts[i-1].y;
  3831. x1 = (int)verts[i ].x;
  3832. y1 = (int)verts[i ].y;
  3833. if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
  3834. float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
  3835. if (x_inter < x)
  3836. winding += (y0 < y1) ? 1 : -1;
  3837. }
  3838. } else {
  3839. int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits);
  3840. if (num_hits >= 1)
  3841. if (hits[0][0] < 0)
  3842. winding += (hits[0][1] < 0 ? -1 : 1);
  3843. if (num_hits >= 2)
  3844. if (hits[1][0] < 0)
  3845. winding += (hits[1][1] < 0 ? -1 : 1);
  3846. }
  3847. }
  3848. }
  3849. }
  3850. return winding;
  3851. }
  3852. static float stbtt__cuberoot( float x )
  3853. {
  3854. if (x<0)
  3855. return -(float) STBTT_pow(-x,1.0f/3.0f);
  3856. else
  3857. return (float) STBTT_pow( x,1.0f/3.0f);
  3858. }
  3859. // x^3 + c*x^2 + b*x + a = 0
  3860. static int stbtt__solve_cubic(float a, float b, float c, float* r)
  3861. {
  3862. float s = -a / 3;
  3863. float p = b - a*a / 3;
  3864. float q = a * (2*a*a - 9*b) / 27 + c;
  3865. float p3 = p*p*p;
  3866. float d = q*q + 4*p3 / 27;
  3867. if (d >= 0) {
  3868. float z = (float) STBTT_sqrt(d);
  3869. float u = (-q + z) / 2;
  3870. float v = (-q - z) / 2;
  3871. u = stbtt__cuberoot(u);
  3872. v = stbtt__cuberoot(v);
  3873. r[0] = s + u + v;
  3874. return 1;
  3875. } else {
  3876. float u = (float) STBTT_sqrt(-p/3);
  3877. float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative
  3878. float m = (float) STBTT_cos(v);
  3879. float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f;
  3880. r[0] = s + u * 2 * m;
  3881. r[1] = s - u * (m + n);
  3882. r[2] = s - u * (m - n);
  3883. //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe?
  3884. //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f);
  3885. //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f);
  3886. return 3;
  3887. }
  3888. }
  3889. STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
  3890. {
  3891. float scale_x = scale, scale_y = scale;
  3892. int ix0,iy0,ix1,iy1;
  3893. int w,h;
  3894. unsigned char *data;
  3895. // if one scale is 0, use same scale for both
  3896. if (scale_x == 0) scale_x = scale_y;
  3897. if (scale_y == 0) {
  3898. if (scale_x == 0) return NULL; // if both scales are 0, return NULL
  3899. scale_y = scale_x;
  3900. }
  3901. stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1);
  3902. // if empty, return NULL
  3903. if (ix0 == ix1 || iy0 == iy1)
  3904. return NULL;
  3905. ix0 -= padding;
  3906. iy0 -= padding;
  3907. ix1 += padding;
  3908. iy1 += padding;
  3909. w = (ix1 - ix0);
  3910. h = (iy1 - iy0);
  3911. if (width ) *width = w;
  3912. if (height) *height = h;
  3913. if (xoff ) *xoff = ix0;
  3914. if (yoff ) *yoff = iy0;
  3915. // invert for y-downwards bitmaps
  3916. scale_y = -scale_y;
  3917. {
  3918. int x,y,i,j;
  3919. float *precompute;
  3920. stbtt_vertex *verts;
  3921. int num_verts = stbtt_GetGlyphShape(info, glyph, &verts);
  3922. data = (unsigned char *) STBTT_malloc(w * h, info->userdata);
  3923. precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata);
  3924. for (i=0,j=num_verts-1; i < num_verts; j=i++) {
  3925. if (verts[i].type == STBTT_vline) {
  3926. float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
  3927. float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y;
  3928. float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));
  3929. precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist;
  3930. } else if (verts[i].type == STBTT_vcurve) {
  3931. float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y;
  3932. float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y;
  3933. float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y;
  3934. float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
  3935. float len2 = bx*bx + by*by;
  3936. if (len2 != 0.0f)
  3937. precompute[i] = 1.0f / (bx*bx + by*by);
  3938. else
  3939. precompute[i] = 0.0f;
  3940. } else
  3941. precompute[i] = 0.0f;
  3942. }
  3943. for (y=iy0; y < iy1; ++y) {
  3944. for (x=ix0; x < ix1; ++x) {
  3945. float val;
  3946. float min_dist = 999999.0f;
  3947. float sx = (float) x + 0.5f;
  3948. float sy = (float) y + 0.5f;
  3949. float x_gspace = (sx / scale_x);
  3950. float y_gspace = (sy / scale_y);
  3951. int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path
  3952. for (i=0; i < num_verts; ++i) {
  3953. float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
  3954. // check against every point here rather than inside line/curve primitives -- @TODO: wrong if multiple 'moves' in a row produce a garbage point, and given culling, probably more efficient to do within line/curve
  3955. float dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);
  3956. if (dist2 < min_dist*min_dist)
  3957. min_dist = (float) STBTT_sqrt(dist2);
  3958. if (verts[i].type == STBTT_vline) {
  3959. float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y;
  3960. // coarse culling against bbox
  3961. //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist &&
  3962. // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist)
  3963. float dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i];
  3964. STBTT_assert(i != 0);
  3965. if (dist < min_dist) {
  3966. // check position along line
  3967. // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0)
  3968. // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy)
  3969. float dx = x1-x0, dy = y1-y0;
  3970. float px = x0-sx, py = y0-sy;
  3971. // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy
  3972. // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve
  3973. float t = -(px*dx + py*dy) / (dx*dx + dy*dy);
  3974. if (t >= 0.0f && t <= 1.0f)
  3975. min_dist = dist;
  3976. }
  3977. } else if (verts[i].type == STBTT_vcurve) {
  3978. float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y;
  3979. float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y;
  3980. float box_x0 = STBTT_min(STBTT_min(x0,x1),x2);
  3981. float box_y0 = STBTT_min(STBTT_min(y0,y1),y2);
  3982. float box_x1 = STBTT_max(STBTT_max(x0,x1),x2);
  3983. float box_y1 = STBTT_max(STBTT_max(y0,y1),y2);
  3984. // coarse culling against bbox to avoid computing cubic unnecessarily
  3985. if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) {
  3986. int num=0;
  3987. float ax = x1-x0, ay = y1-y0;
  3988. float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
  3989. float mx = x0 - sx, my = y0 - sy;
  3990. float res[3],px,py,t,it;
  3991. float a_inv = precompute[i];
  3992. if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula
  3993. float a = 3*(ax*bx + ay*by);
  3994. float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by);
  3995. float c = mx*ax+my*ay;
  3996. if (a == 0.0) { // if a is 0, it's linear
  3997. if (b != 0.0) {
  3998. res[num++] = -c/b;
  3999. }
  4000. } else {
  4001. float discriminant = b*b - 4*a*c;
  4002. if (discriminant < 0)
  4003. num = 0;
  4004. else {
  4005. float root = (float) STBTT_sqrt(discriminant);
  4006. res[0] = (-b - root)/(2*a);
  4007. res[1] = (-b + root)/(2*a);
  4008. num = 2; // don't bother distinguishing 1-solution case, as code below will still work
  4009. }
  4010. }
  4011. } else {
  4012. float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point
  4013. float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv;
  4014. float d = (mx*ax+my*ay) * a_inv;
  4015. num = stbtt__solve_cubic(b, c, d, res);
  4016. }
  4017. if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) {
  4018. t = res[0], it = 1.0f - t;
  4019. px = it*it*x0 + 2*t*it*x1 + t*t*x2;
  4020. py = it*it*y0 + 2*t*it*y1 + t*t*y2;
  4021. dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
  4022. if (dist2 < min_dist * min_dist)
  4023. min_dist = (float) STBTT_sqrt(dist2);
  4024. }
  4025. if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) {
  4026. t = res[1], it = 1.0f - t;
  4027. px = it*it*x0 + 2*t*it*x1 + t*t*x2;
  4028. py = it*it*y0 + 2*t*it*y1 + t*t*y2;
  4029. dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
  4030. if (dist2 < min_dist * min_dist)
  4031. min_dist = (float) STBTT_sqrt(dist2);
  4032. }
  4033. if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) {
  4034. t = res[2], it = 1.0f - t;
  4035. px = it*it*x0 + 2*t*it*x1 + t*t*x2;
  4036. py = it*it*y0 + 2*t*it*y1 + t*t*y2;
  4037. dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
  4038. if (dist2 < min_dist * min_dist)
  4039. min_dist = (float) STBTT_sqrt(dist2);
  4040. }
  4041. }
  4042. }
  4043. }
  4044. if (winding == 0)
  4045. min_dist = -min_dist; // if outside the shape, value is negative
  4046. val = onedge_value + pixel_dist_scale * min_dist;
  4047. if (val < 0)
  4048. val = 0;
  4049. else if (val > 255)
  4050. val = 255;
  4051. data[(y-iy0)*w+(x-ix0)] = (unsigned char) val;
  4052. }
  4053. }
  4054. STBTT_free(precompute, info->userdata);
  4055. STBTT_free(verts, info->userdata);
  4056. }
  4057. return data;
  4058. }
  4059. STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
  4060. {
  4061. return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff);
  4062. }
  4063. STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata)
  4064. {
  4065. STBTT_free(bitmap, userdata);
  4066. }
  4067. //////////////////////////////////////////////////////////////////////////////
  4068. //
  4069. // font name matching -- recommended not to use this
  4070. //
  4071. // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
  4072. static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2)
  4073. {
  4074. stbtt_int32 i=0;
  4075. // convert utf16 to utf8 and compare the results while converting
  4076. while (len2) {
  4077. stbtt_uint16 ch = s2[0]*256 + s2[1];
  4078. if (ch < 0x80) {
  4079. if (i >= len1) return -1;
  4080. if (s1[i++] != ch) return -1;
  4081. } else if (ch < 0x800) {
  4082. if (i+1 >= len1) return -1;
  4083. if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
  4084. if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
  4085. } else if (ch >= 0xd800 && ch < 0xdc00) {
  4086. stbtt_uint32 c;
  4087. stbtt_uint16 ch2 = s2[2]*256 + s2[3];
  4088. if (i+3 >= len1) return -1;
  4089. c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
  4090. if (s1[i++] != 0xf0 + (c >> 18)) return -1;
  4091. if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
  4092. if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1;
  4093. if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1;
  4094. s2 += 2; // plus another 2 below
  4095. len2 -= 2;
  4096. } else if (ch >= 0xdc00 && ch < 0xe000) {
  4097. return -1;
  4098. } else {
  4099. if (i+2 >= len1) return -1;
  4100. if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
  4101. if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
  4102. if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1;
  4103. }
  4104. s2 += 2;
  4105. len2 -= 2;
  4106. }
  4107. return i;
  4108. }
  4109. static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2)
  4110. {
  4111. return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2);
  4112. }
  4113. // returns results in whatever encoding you request... but note that 2-byte encodings
  4114. // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
  4115. STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
  4116. {
  4117. stbtt_int32 i,count,stringOffset;
  4118. stbtt_uint8 *fc = font->data;
  4119. stbtt_uint32 offset = font->fontstart;
  4120. stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
  4121. if (!nm) return NULL;
  4122. count = ttUSHORT(fc+nm+2);
  4123. stringOffset = nm + ttUSHORT(fc+nm+4);
  4124. for (i=0; i < count; ++i) {
  4125. stbtt_uint32 loc = nm + 6 + 12 * i;
  4126. if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
  4127. && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
  4128. *length = ttUSHORT(fc+loc+8);
  4129. return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
  4130. }
  4131. }
  4132. return NULL;
  4133. }
  4134. static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
  4135. {
  4136. stbtt_int32 i;
  4137. stbtt_int32 count = ttUSHORT(fc+nm+2);
  4138. stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
  4139. for (i=0; i < count; ++i) {
  4140. stbtt_uint32 loc = nm + 6 + 12 * i;
  4141. stbtt_int32 id = ttUSHORT(fc+loc+6);
  4142. if (id == target_id) {
  4143. // find the encoding
  4144. stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
  4145. // is this a Unicode encoding?
  4146. if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
  4147. stbtt_int32 slen = ttUSHORT(fc+loc+8);
  4148. stbtt_int32 off = ttUSHORT(fc+loc+10);
  4149. // check if there's a prefix match
  4150. stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
  4151. if (matchlen >= 0) {
  4152. // check for target_id+1 immediately following, with same encoding & language
  4153. 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) {
  4154. slen = ttUSHORT(fc+loc+12+8);
  4155. off = ttUSHORT(fc+loc+12+10);
  4156. if (slen == 0) {
  4157. if (matchlen == nlen)
  4158. return 1;
  4159. } else if (matchlen < nlen && name[matchlen] == ' ') {
  4160. ++matchlen;
  4161. if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
  4162. return 1;
  4163. }
  4164. } else {
  4165. // if nothing immediately following
  4166. if (matchlen == nlen)
  4167. return 1;
  4168. }
  4169. }
  4170. }
  4171. // @TODO handle other encodings
  4172. }
  4173. }
  4174. return 0;
  4175. }
  4176. static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
  4177. {
  4178. stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
  4179. stbtt_uint32 nm,hd;
  4180. if (!stbtt__isfont(fc+offset)) return 0;
  4181. // check italics/bold/underline flags in macStyle...
  4182. if (flags) {
  4183. hd = stbtt__find_table(fc, offset, "head");
  4184. if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
  4185. }
  4186. nm = stbtt__find_table(fc, offset, "name");
  4187. if (!nm) return 0;
  4188. if (flags) {
  4189. // if we checked the macStyle flags, then just check the family and ignore the subfamily
  4190. if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1;
  4191. if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1;
  4192. if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
  4193. } else {
  4194. if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1;
  4195. if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1;
  4196. if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
  4197. }
  4198. return 0;
  4199. }
  4200. static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags)
  4201. {
  4202. stbtt_int32 i;
  4203. for (i=0;;++i) {
  4204. stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
  4205. if (off < 0) return off;
  4206. if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
  4207. return off;
  4208. }
  4209. }
  4210. #if defined(__GNUC__) || defined(__clang__)
  4211. #pragma GCC diagnostic push
  4212. #pragma GCC diagnostic ignored "-Wcast-qual"
  4213. #endif
  4214. STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,
  4215. float pixel_height, unsigned char *pixels, int pw, int ph,
  4216. int first_char, int num_chars, stbtt_bakedchar *chardata)
  4217. {
  4218. return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata);
  4219. }
  4220. STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index)
  4221. {
  4222. return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index);
  4223. }
  4224. STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data)
  4225. {
  4226. return stbtt_GetNumberOfFonts_internal((unsigned char *) data);
  4227. }
  4228. STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset)
  4229. {
  4230. return stbtt_InitFont_internal(info, (unsigned char *) data, offset);
  4231. }
  4232. STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags)
  4233. {
  4234. return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags);
  4235. }
  4236. STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
  4237. {
  4238. return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2);
  4239. }
  4240. #if defined(__GNUC__) || defined(__clang__)
  4241. #pragma GCC diagnostic pop
  4242. #endif
  4243. #endif // STB_TRUETYPE_IMPLEMENTATION
  4244. // FULL VERSION HISTORY
  4245. //
  4246. // 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod
  4247. // 1.18 (2018-01-29) add missing function
  4248. // 1.17 (2017-07-23) make more arguments const; doc fix
  4249. // 1.16 (2017-07-12) SDF support
  4250. // 1.15 (2017-03-03) make more arguments const
  4251. // 1.14 (2017-01-16) num-fonts-in-TTC function
  4252. // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
  4253. // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
  4254. // 1.11 (2016-04-02) fix unused-variable warning
  4255. // 1.10 (2016-04-02) allow user-defined fabs() replacement
  4256. // fix memory leak if fontsize=0.0
  4257. // fix warning from duplicate typedef
  4258. // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges
  4259. // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
  4260. // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
  4261. // allow PackFontRanges to pack and render in separate phases;
  4262. // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
  4263. // fixed an assert() bug in the new rasterizer
  4264. // replace assert() with STBTT_assert() in new rasterizer
  4265. // 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
  4266. // also more precise AA rasterizer, except if shapes overlap
  4267. // remove need for STBTT_sort
  4268. // 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
  4269. // 1.04 (2015-04-15) typo in example
  4270. // 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
  4271. // 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++
  4272. // 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match
  4273. // non-oversampled; STBTT_POINT_SIZE for packed case only
  4274. // 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling
  4275. // 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)
  4276. // 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID
  4277. // 0.8b (2014-07-07) fix a warning
  4278. // 0.8 (2014-05-25) fix a few more warnings
  4279. // 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
  4280. // 0.6c (2012-07-24) improve documentation
  4281. // 0.6b (2012-07-20) fix a few more warnings
  4282. // 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
  4283. // stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
  4284. // 0.5 (2011-12-09) bugfixes:
  4285. // subpixel glyph renderer computed wrong bounding box
  4286. // first vertex of shape can be off-curve (FreeSans)
  4287. // 0.4b (2011-12-03) fixed an error in the font baking example
  4288. // 0.4 (2011-12-01) kerning, subpixel rendering (tor)
  4289. // bugfixes for:
  4290. // codepoint-to-glyph conversion using table fmt=12
  4291. // codepoint-to-glyph conversion using table fmt=4
  4292. // stbtt_GetBakedQuad with non-square texture (Zer)
  4293. // updated Hello World! sample to use kerning and subpixel
  4294. // fixed some warnings
  4295. // 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)
  4296. // userdata, malloc-from-userdata, non-zero fill (stb)
  4297. // 0.2 (2009-03-11) Fix unsigned/signed char warnings
  4298. // 0.1 (2009-03-09) First public release
  4299. //
  4300. /*
  4301. ------------------------------------------------------------------------------
  4302. This software is available under 2 licenses -- choose whichever you prefer.
  4303. ------------------------------------------------------------------------------
  4304. ALTERNATIVE A - MIT License
  4305. Copyright (c) 2017 Sean Barrett
  4306. Permission is hereby granted, free of charge, to any person obtaining a copy of
  4307. this software and associated documentation files (the "Software"), to deal in
  4308. the Software without restriction, including without limitation the rights to
  4309. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  4310. of the Software, and to permit persons to whom the Software is furnished to do
  4311. so, subject to the following conditions:
  4312. The above copyright notice and this permission notice shall be included in all
  4313. copies or substantial portions of the Software.
  4314. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4315. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4316. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4317. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4318. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4319. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4320. SOFTWARE.
  4321. ------------------------------------------------------------------------------
  4322. ALTERNATIVE B - Public Domain (www.unlicense.org)
  4323. This is free and unencumbered software released into the public domain.
  4324. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  4325. software, either in source code form or as a compiled binary, for any purpose,
  4326. commercial or non-commercial, and by any means.
  4327. In jurisdictions that recognize copyright laws, the author or authors of this
  4328. software dedicate any and all copyright interest in the software to the public
  4329. domain. We make this dedication for the benefit of the public at large and to
  4330. the detriment of our heirs and successors. We intend this dedication to be an
  4331. overt act of relinquishment in perpetuity of all present and future rights to
  4332. this software under copyright law.
  4333. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4334. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4335. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4336. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  4337. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  4338. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  4339. ------------------------------------------------------------------------------
  4340. */