imgui_freetype.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. // dear imgui: FreeType font builder (used as a replacement for the stb_truetype builder)
  2. // (code)
  3. // Get the latest version at https://github.com/ocornut/imgui/tree/master/misc/freetype
  4. // Original code by @vuhdo (Aleksei Skriabin). Improvements by @mikesart. Maintained since 2019 by @ocornut.
  5. // CHANGELOG
  6. // (minor and older changes stripped away, please see git history for details)
  7. // 2024/10/17: added plutosvg support for SVG Fonts (seems faster/better than lunasvg). Enable by using '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG'. (#7927)
  8. // 2023/11/13: added support for ImFontConfig::RasterizationDensity field for scaling render density without scaling metrics.
  9. // 2023/08/01: added support for SVG fonts, enable by using '#define IMGUI_ENABLE_FREETYPE_LUNASVG'. (#6591)
  10. // 2023/01/04: fixed a packing issue which in some occurrences would prevent large amount of glyphs from being packed correctly.
  11. // 2021/08/23: fixed crash when FT_Render_Glyph() fails to render a glyph and returns nullptr.
  12. // 2021/03/05: added ImGuiFreeTypeBuilderFlags_Bitmap to load bitmap glyphs.
  13. // 2021/03/02: set 'atlas->TexPixelsUseColors = true' to help some backends with deciding of a preferred texture format.
  14. // 2021/01/28: added support for color-layered glyphs via ImGuiFreeTypeBuilderFlags_LoadColor (require Freetype 2.10+).
  15. // 2021/01/26: simplified integration by using '#define IMGUI_ENABLE_FREETYPE'. renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API. removed ImGuiFreeType::BuildFontAtlas().
  16. // 2020/06/04: fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails.
  17. // 2019/02/09: added RasterizerFlags::Monochrome flag to disable font anti-aliasing (combine with ::MonoHinting for best results!)
  18. // 2019/01/15: added support for imgui allocators + added FreeType only override function SetAllocatorFunctions().
  19. // 2019/01/10: re-factored to match big update in STB builder. fixed texture height waste. fixed redundant glyphs when merging. support for glyph padding.
  20. // 2018/06/08: added support for ImFontConfig::GlyphMinAdvanceX, GlyphMaxAdvanceX.
  21. // 2018/02/04: moved to main imgui repository (away from http://www.github.com/ocornut/imgui_club)
  22. // 2018/01/22: fix for addition of ImFontAtlas::TexUvscale member.
  23. // 2017/10/22: minor inconsequential change to match change in master (removed an unnecessary statement).
  24. // 2017/09/26: fixes for imgui internal changes.
  25. // 2017/08/26: cleanup, optimizations, support for ImFontConfig::RasterizerFlags, ImFontConfig::RasterizerMultiply.
  26. // 2017/08/16: imported from https://github.com/Vuhdo/imgui_freetype into http://www.github.com/ocornut/imgui_club, updated for latest changes in ImFontAtlas, minor tweaks.
  27. // About Gamma Correct Blending:
  28. // - FreeType assumes blending in linear space rather than gamma space.
  29. // - See https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_Render_Glyph
  30. // - For correct results you need to be using sRGB and convert to linear space in the pixel shader output.
  31. // - The default dear imgui styles will be impacted by this change (alpha values will need tweaking).
  32. // FIXME: cfg.OversampleH, OversampleV are not supported, but generally not necessary with this rasterizer because Hinting makes everything look better.
  33. #include "imgui.h"
  34. #ifndef IMGUI_DISABLE
  35. #include "imgui_freetype.h"
  36. #include "imgui_internal.h" // ImMin,ImMax,ImFontAtlasBuild*,
  37. #include <stdint.h>
  38. #include <ft2build.h>
  39. #include FT_FREETYPE_H // <freetype/freetype.h>
  40. #include FT_MODULE_H // <freetype/ftmodapi.h>
  41. #include FT_GLYPH_H // <freetype/ftglyph.h>
  42. #include FT_SYNTHESIS_H // <freetype/ftsynth.h>
  43. // Handle LunaSVG and PlutoSVG
  44. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) && defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  45. #error "Cannot enable both IMGUI_ENABLE_FREETYPE_LUNASVG and IMGUI_ENABLE_FREETYPE_PLUTOSVG"
  46. #endif
  47. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  48. #include FT_OTSVG_H // <freetype/otsvg.h>
  49. #include FT_BBOX_H // <freetype/ftbbox.h>
  50. #include <lunasvg.h>
  51. #endif
  52. #ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG
  53. #include <plutosvg.h>
  54. #endif
  55. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined (IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  56. #if !((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
  57. #error IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG requires FreeType version >= 2.12
  58. #endif
  59. #endif
  60. #ifdef _MSC_VER
  61. #pragma warning (push)
  62. #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
  63. #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
  64. #endif
  65. #ifdef __GNUC__
  66. #pragma GCC diagnostic push
  67. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
  68. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  69. #ifndef __clang__
  70. #pragma GCC diagnostic ignored "-Wsubobject-linkage" // warning: 'xxxx' has a field 'xxxx' whose type uses the anonymous namespace
  71. #endif
  72. #endif
  73. //-------------------------------------------------------------------------
  74. // Data
  75. //-------------------------------------------------------------------------
  76. // Default memory allocators
  77. static void* ImGuiFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); }
  78. static void ImGuiFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); }
  79. // Current memory allocators
  80. static void* (*GImGuiFreeTypeAllocFunc)(size_t size, void* user_data) = ImGuiFreeTypeDefaultAllocFunc;
  81. static void (*GImGuiFreeTypeFreeFunc)(void* ptr, void* user_data) = ImGuiFreeTypeDefaultFreeFunc;
  82. static void* GImGuiFreeTypeAllocatorUserData = nullptr;
  83. // Lunasvg support
  84. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  85. static FT_Error ImGuiLunasvgPortInit(FT_Pointer* state);
  86. static void ImGuiLunasvgPortFree(FT_Pointer* state);
  87. static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state);
  88. static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_Pointer* _state);
  89. #endif
  90. //-------------------------------------------------------------------------
  91. // Code
  92. //-------------------------------------------------------------------------
  93. #define FT_CEIL(X) (((X + 63) & -64) / 64) // From SDL_ttf: Handy routines for converting from fixed point
  94. #define FT_SCALEFACTOR 64.0f
  95. namespace
  96. {
  97. // Glyph metrics:
  98. // --------------
  99. //
  100. // xmin xmax
  101. // | |
  102. // |<-------- width -------->|
  103. // | |
  104. // | +-------------------------+----------------- ymax
  105. // | | ggggggggg ggggg | ^ ^
  106. // | | g:::::::::ggg::::g | | |
  107. // | | g:::::::::::::::::g | | |
  108. // | | g::::::ggggg::::::gg | | |
  109. // | | g:::::g g:::::g | | |
  110. // offsetX -|-------->| g:::::g g:::::g | offsetY |
  111. // | | g:::::g g:::::g | | |
  112. // | | g::::::g g:::::g | | |
  113. // | | g:::::::ggggg:::::g | | |
  114. // | | g::::::::::::::::g | | height
  115. // | | gg::::::::::::::g | | |
  116. // baseline ---*---------|---- gggggggg::::::g-----*-------- |
  117. // / | | g:::::g | |
  118. // origin | | gggggg g:::::g | |
  119. // | | g:::::gg gg:::::g | |
  120. // | | g::::::ggg:::::::g | |
  121. // | | gg:::::::::::::g | |
  122. // | | ggg::::::ggg | |
  123. // | | gggggg | v
  124. // | +-------------------------+----------------- ymin
  125. // | |
  126. // |------------- advanceX ----------->|
  127. // A structure that describe a glyph.
  128. struct GlyphInfo
  129. {
  130. int Width; // Glyph's width in pixels.
  131. int Height; // Glyph's height in pixels.
  132. FT_Int OffsetX; // The distance from the origin ("pen position") to the left of the glyph.
  133. FT_Int OffsetY; // The distance from the origin to the top of the glyph. This is usually a value < 0.
  134. float AdvanceX; // The distance from the origin to the origin of the next glyph. This is usually a value > 0.
  135. bool IsColored; // The glyph is colored
  136. };
  137. // Font parameters and metrics.
  138. struct FontInfo
  139. {
  140. uint32_t PixelHeight; // Size this font was generated with.
  141. float Ascender; // The pixel extents above the baseline in pixels (typically positive).
  142. float Descender; // The extents below the baseline in pixels (typically negative).
  143. float LineSpacing; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate.
  144. float LineGap; // The spacing in pixels between one row's descent and the next row's ascent.
  145. float MaxAdvanceWidth; // This field gives the maximum horizontal cursor advance for all glyphs in the font.
  146. };
  147. // FreeType glyph rasterizer.
  148. // NB: No ctor/dtor, explicitly call Init()/Shutdown()
  149. struct FreeTypeFont
  150. {
  151. bool InitFont(FT_Library ft_library, const ImFontConfig& src, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime.
  152. void CloseFont();
  153. void SetPixelHeight(int pixel_height); // Change font pixel size. All following calls to RasterizeGlyph() will use this size
  154. const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint);
  155. const FT_Bitmap* RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info);
  156. void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = nullptr);
  157. FreeTypeFont() { memset((void*)this, 0, sizeof(*this)); }
  158. ~FreeTypeFont() { CloseFont(); }
  159. // [Internals]
  160. FontInfo Info; // Font descriptor of the current font.
  161. FT_Face Face;
  162. unsigned int UserFlags; // = ImFontConfig::RasterizerFlags
  163. FT_Int32 LoadFlags;
  164. FT_Render_Mode RenderMode;
  165. float RasterizationDensity;
  166. float InvRasterizationDensity;
  167. };
  168. bool FreeTypeFont::InitFont(FT_Library ft_library, const ImFontConfig& src, unsigned int extra_font_builder_flags)
  169. {
  170. FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src.FontData, (uint32_t)src.FontDataSize, (uint32_t)src.FontNo, &Face);
  171. if (error != 0)
  172. return false;
  173. error = FT_Select_Charmap(Face, FT_ENCODING_UNICODE);
  174. if (error != 0)
  175. return false;
  176. // Convert to FreeType flags (NB: Bold and Oblique are processed separately)
  177. UserFlags = src.FontBuilderFlags | extra_font_builder_flags;
  178. LoadFlags = 0;
  179. if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0)
  180. LoadFlags |= FT_LOAD_NO_BITMAP;
  181. if (UserFlags & ImGuiFreeTypeBuilderFlags_NoHinting)
  182. LoadFlags |= FT_LOAD_NO_HINTING;
  183. if (UserFlags & ImGuiFreeTypeBuilderFlags_NoAutoHint)
  184. LoadFlags |= FT_LOAD_NO_AUTOHINT;
  185. if (UserFlags & ImGuiFreeTypeBuilderFlags_ForceAutoHint)
  186. LoadFlags |= FT_LOAD_FORCE_AUTOHINT;
  187. if (UserFlags & ImGuiFreeTypeBuilderFlags_LightHinting)
  188. LoadFlags |= FT_LOAD_TARGET_LIGHT;
  189. else if (UserFlags & ImGuiFreeTypeBuilderFlags_MonoHinting)
  190. LoadFlags |= FT_LOAD_TARGET_MONO;
  191. else
  192. LoadFlags |= FT_LOAD_TARGET_NORMAL;
  193. if (UserFlags & ImGuiFreeTypeBuilderFlags_Monochrome)
  194. RenderMode = FT_RENDER_MODE_MONO;
  195. else
  196. RenderMode = FT_RENDER_MODE_NORMAL;
  197. if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor)
  198. LoadFlags |= FT_LOAD_COLOR;
  199. RasterizationDensity = src.RasterizerDensity;
  200. InvRasterizationDensity = 1.0f / RasterizationDensity;
  201. memset(&Info, 0, sizeof(Info));
  202. SetPixelHeight((uint32_t)src.SizePixels);
  203. return true;
  204. }
  205. void FreeTypeFont::CloseFont()
  206. {
  207. if (Face)
  208. {
  209. FT_Done_Face(Face);
  210. Face = nullptr;
  211. }
  212. }
  213. void FreeTypeFont::SetPixelHeight(int pixel_height)
  214. {
  215. // Vuhdo: I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height'
  216. // is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me.
  217. // NB: FT_Set_Pixel_Sizes() doesn't seem to get us the same result.
  218. FT_Size_RequestRec req;
  219. req.type = (UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM;
  220. req.width = 0;
  221. req.height = (uint32_t)(pixel_height * 64 * RasterizationDensity);
  222. req.horiResolution = 0;
  223. req.vertResolution = 0;
  224. FT_Request_Size(Face, &req);
  225. // Update font info
  226. FT_Size_Metrics metrics = Face->size->metrics;
  227. Info.PixelHeight = (uint32_t)(pixel_height * InvRasterizationDensity);
  228. Info.Ascender = (float)FT_CEIL(metrics.ascender) * InvRasterizationDensity;
  229. Info.Descender = (float)FT_CEIL(metrics.descender) * InvRasterizationDensity;
  230. Info.LineSpacing = (float)FT_CEIL(metrics.height) * InvRasterizationDensity;
  231. Info.LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * InvRasterizationDensity;
  232. Info.MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * InvRasterizationDensity;
  233. }
  234. const FT_Glyph_Metrics* FreeTypeFont::LoadGlyph(uint32_t codepoint)
  235. {
  236. uint32_t glyph_index = FT_Get_Char_Index(Face, codepoint);
  237. if (glyph_index == 0)
  238. return nullptr;
  239. // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts.
  240. // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076
  241. // - https://github.com/ocornut/imgui/issues/4567
  242. // - https://github.com/ocornut/imgui/issues/4566
  243. // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version.
  244. FT_Error error = FT_Load_Glyph(Face, glyph_index, LoadFlags);
  245. if (error)
  246. return nullptr;
  247. // Need an outline for this to work
  248. FT_GlyphSlot slot = Face->glyph;
  249. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  250. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG);
  251. #else
  252. #if ((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
  253. IM_ASSERT(slot->format != FT_GLYPH_FORMAT_SVG && "The font contains SVG glyphs, you'll need to enable IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG in imconfig.h and install required libraries in order to use this font");
  254. #endif
  255. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP);
  256. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  257. // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting)
  258. if (UserFlags & ImGuiFreeTypeBuilderFlags_Bold)
  259. FT_GlyphSlot_Embolden(slot);
  260. if (UserFlags & ImGuiFreeTypeBuilderFlags_Oblique)
  261. {
  262. FT_GlyphSlot_Oblique(slot);
  263. //FT_BBox bbox;
  264. //FT_Outline_Get_BBox(&slot->outline, &bbox);
  265. //slot->metrics.width = bbox.xMax - bbox.xMin;
  266. //slot->metrics.height = bbox.yMax - bbox.yMin;
  267. }
  268. return &slot->metrics;
  269. }
  270. const FT_Bitmap* FreeTypeFont::RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info)
  271. {
  272. FT_GlyphSlot slot = Face->glyph;
  273. FT_Error error = FT_Render_Glyph(slot, RenderMode);
  274. if (error != 0)
  275. return nullptr;
  276. FT_Bitmap* ft_bitmap = &Face->glyph->bitmap;
  277. out_glyph_info->Width = (int)ft_bitmap->width;
  278. out_glyph_info->Height = (int)ft_bitmap->rows;
  279. out_glyph_info->OffsetX = Face->glyph->bitmap_left;
  280. out_glyph_info->OffsetY = -Face->glyph->bitmap_top;
  281. out_glyph_info->AdvanceX = (float)slot->advance.x / FT_SCALEFACTOR;
  282. out_glyph_info->IsColored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA);
  283. return ft_bitmap;
  284. }
  285. void FreeTypeFont::BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table)
  286. {
  287. IM_ASSERT(ft_bitmap != nullptr);
  288. const uint32_t w = ft_bitmap->width;
  289. const uint32_t h = ft_bitmap->rows;
  290. const uint8_t* src = ft_bitmap->buffer;
  291. const uint32_t src_pitch = ft_bitmap->pitch;
  292. switch (ft_bitmap->pixel_mode)
  293. {
  294. case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel.
  295. {
  296. if (multiply_table == nullptr)
  297. {
  298. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  299. for (uint32_t x = 0; x < w; x++)
  300. dst[x] = IM_COL32(255, 255, 255, src[x]);
  301. }
  302. else
  303. {
  304. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  305. for (uint32_t x = 0; x < w; x++)
  306. dst[x] = IM_COL32(255, 255, 255, multiply_table[src[x]]);
  307. }
  308. break;
  309. }
  310. case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB.
  311. {
  312. uint8_t color0 = multiply_table ? multiply_table[0] : 0;
  313. uint8_t color1 = multiply_table ? multiply_table[255] : 255;
  314. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  315. {
  316. uint8_t bits = 0;
  317. const uint8_t* bits_ptr = src;
  318. for (uint32_t x = 0; x < w; x++, bits <<= 1)
  319. {
  320. if ((x & 7) == 0)
  321. bits = *bits_ptr++;
  322. dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? color1 : color0);
  323. }
  324. }
  325. break;
  326. }
  327. case FT_PIXEL_MODE_BGRA:
  328. {
  329. // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good.
  330. #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u)
  331. if (multiply_table == nullptr)
  332. {
  333. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  334. for (uint32_t x = 0; x < w; x++)
  335. {
  336. uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3];
  337. dst[x] = IM_COL32(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a);
  338. }
  339. }
  340. else
  341. {
  342. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  343. {
  344. for (uint32_t x = 0; x < w; x++)
  345. {
  346. uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3];
  347. dst[x] = IM_COL32(multiply_table[DE_MULTIPLY(r, a)], multiply_table[DE_MULTIPLY(g, a)], multiply_table[DE_MULTIPLY(b, a)], multiply_table[a]);
  348. }
  349. }
  350. }
  351. #undef DE_MULTIPLY
  352. break;
  353. }
  354. default:
  355. IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!");
  356. }
  357. }
  358. } // namespace
  359. #ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
  360. #ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
  361. #define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0)
  362. #define STBRP_STATIC
  363. #define STB_RECT_PACK_IMPLEMENTATION
  364. #endif
  365. #ifdef IMGUI_STB_RECT_PACK_FILENAME
  366. #include IMGUI_STB_RECT_PACK_FILENAME
  367. #else
  368. #include "imstb_rectpack.h"
  369. #endif
  370. #endif
  371. struct ImFontBuildSrcGlyphFT
  372. {
  373. GlyphInfo Info;
  374. uint32_t Codepoint;
  375. unsigned int* BitmapData; // Point within one of the dst_tmp_bitmap_buffers[] array
  376. ImFontBuildSrcGlyphFT() { memset((void*)this, 0, sizeof(*this)); }
  377. };
  378. struct ImFontBuildSrcDataFT
  379. {
  380. FreeTypeFont Font;
  381. stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position.
  382. const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF)
  383. int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[]
  384. int GlyphsHighest; // Highest requested codepoint
  385. int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font)
  386. ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB)
  387. ImVector<ImFontBuildSrcGlyphFT> GlyphsList;
  388. };
  389. // Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont)
  390. struct ImFontBuildDstDataFT
  391. {
  392. int SrcCount; // Number of source fonts targeting this destination font.
  393. int GlyphsHighest;
  394. int GlyphsCount;
  395. ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font.
  396. };
  397. bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, unsigned int extra_flags)
  398. {
  399. IM_ASSERT(atlas->Sources.Size > 0);
  400. ImFontAtlasBuildInit(atlas);
  401. // Clear atlas
  402. atlas->TexID = 0;
  403. atlas->TexWidth = atlas->TexHeight = 0;
  404. atlas->TexUvScale = ImVec2(0.0f, 0.0f);
  405. atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
  406. atlas->ClearTexData();
  407. // Temporary storage for building
  408. bool src_load_color = false;
  409. ImVector<ImFontBuildSrcDataFT> src_tmp_array;
  410. ImVector<ImFontBuildDstDataFT> dst_tmp_array;
  411. src_tmp_array.resize(atlas->Sources.Size);
  412. dst_tmp_array.resize(atlas->Fonts.Size);
  413. memset((void*)src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes());
  414. memset((void*)dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes());
  415. // 1. Initialize font loading structure, check font data validity
  416. for (int src_i = 0; src_i < atlas->Sources.Size; src_i++)
  417. {
  418. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  419. ImFontConfig& src = atlas->Sources[src_i];
  420. FreeTypeFont& font_face = src_tmp.Font;
  421. IM_ASSERT(src.DstFont && (!src.DstFont->IsLoaded() || src.DstFont->ContainerAtlas == atlas));
  422. // Find index from src.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices)
  423. src_tmp.DstIndex = -1;
  424. for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++)
  425. if (src.DstFont == atlas->Fonts[output_i])
  426. src_tmp.DstIndex = output_i;
  427. IM_ASSERT(src_tmp.DstIndex != -1); // src.DstFont not pointing within atlas->Fonts[] array?
  428. if (src_tmp.DstIndex == -1)
  429. return false;
  430. // Load font
  431. if (!font_face.InitFont(ft_library, src, extra_flags))
  432. return false;
  433. // Measure highest codepoints
  434. src_load_color |= (src.FontBuilderFlags & ImGuiFreeTypeBuilderFlags_LoadColor) != 0;
  435. ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
  436. src_tmp.SrcRanges = src.GlyphRanges ? src.GlyphRanges : atlas->GetGlyphRangesDefault();
  437. for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
  438. {
  439. // Check for valid range. This may also help detect *some* dangling pointers, because a common
  440. // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent,
  441. // or to forget to zero-terminate the glyph range array.
  442. IM_ASSERT(src_range[0] <= src_range[1] && "Invalid range: is your glyph range array persistent? it is zero-terminated?");
  443. src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]);
  444. }
  445. dst_tmp.SrcCount++;
  446. dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest);
  447. }
  448. // 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs.
  449. int total_glyphs_count = 0;
  450. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  451. {
  452. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  453. ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
  454. src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1);
  455. if (dst_tmp.GlyphsSet.Storage.empty())
  456. dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1);
  457. for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
  458. for (int codepoint = src_range[0]; codepoint <= (int)src_range[1]; codepoint++)
  459. {
  460. if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite)
  461. continue;
  462. uint32_t glyph_index = FT_Get_Char_Index(src_tmp.Font.Face, codepoint); // It is actually in the font? (FIXME-OPT: We are not storing the glyph_index..)
  463. if (glyph_index == 0)
  464. continue;
  465. // Add to avail set/counters
  466. src_tmp.GlyphsCount++;
  467. dst_tmp.GlyphsCount++;
  468. src_tmp.GlyphsSet.SetBit(codepoint);
  469. dst_tmp.GlyphsSet.SetBit(codepoint);
  470. total_glyphs_count++;
  471. }
  472. }
  473. // 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another)
  474. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  475. {
  476. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  477. src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount);
  478. IM_ASSERT(sizeof(src_tmp.GlyphsSet.Storage.Data[0]) == sizeof(ImU32));
  479. const ImU32* it_begin = src_tmp.GlyphsSet.Storage.begin();
  480. const ImU32* it_end = src_tmp.GlyphsSet.Storage.end();
  481. for (const ImU32* it = it_begin; it < it_end; it++)
  482. if (ImU32 entries_32 = *it)
  483. for (ImU32 bit_n = 0; bit_n < 32; bit_n++)
  484. if (entries_32 & ((ImU32)1 << bit_n))
  485. {
  486. ImFontBuildSrcGlyphFT src_glyph;
  487. src_glyph.Codepoint = (ImWchar)(((it - it_begin) << 5) + bit_n);
  488. //src_glyph.GlyphIndex = 0; // FIXME-OPT: We had this info in the previous step and lost it..
  489. src_tmp.GlyphsList.push_back(src_glyph);
  490. }
  491. src_tmp.GlyphsSet.Clear();
  492. IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount);
  493. }
  494. for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++)
  495. dst_tmp_array[dst_i].GlyphsSet.Clear();
  496. dst_tmp_array.clear();
  497. // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)
  498. // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity)
  499. ImVector<stbrp_rect> buf_rects;
  500. buf_rects.resize(total_glyphs_count);
  501. memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes());
  502. // Allocate temporary rasterization data buffers.
  503. // We could not find a way to retrieve accurate glyph size without rendering them.
  504. // (e.g. slot->metrics->width not always matching bitmap->width, especially considering the Oblique transform)
  505. // We allocate in chunks of 256 KB to not waste too much extra memory ahead. Hopefully users of FreeType won't mind the temporary allocations.
  506. const int BITMAP_BUFFERS_CHUNK_SIZE = 256 * 1024;
  507. int buf_bitmap_current_used_bytes = 0;
  508. ImVector<unsigned char*> buf_bitmap_buffers;
  509. buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
  510. // 4. Gather glyphs sizes so we can pack them in our virtual canvas.
  511. // 8. Render/rasterize font characters into the texture
  512. int total_surface = 0;
  513. int buf_rects_out_n = 0;
  514. const int pack_padding = atlas->TexGlyphPadding;
  515. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  516. {
  517. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  518. ImFontConfig& src = atlas->Sources[src_i];
  519. if (src_tmp.GlyphsCount == 0)
  520. continue;
  521. src_tmp.Rects = &buf_rects[buf_rects_out_n];
  522. buf_rects_out_n += src_tmp.GlyphsCount;
  523. // Compute multiply table if requested
  524. const bool multiply_enabled = (src.RasterizerMultiply != 1.0f);
  525. unsigned char multiply_table[256];
  526. if (multiply_enabled)
  527. ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, src.RasterizerMultiply);
  528. // Gather the sizes of all rectangles we will need to pack
  529. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)
  530. {
  531. ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
  532. const FT_Glyph_Metrics* metrics = src_tmp.Font.LoadGlyph(src_glyph.Codepoint);
  533. if (metrics == nullptr)
  534. continue;
  535. // Render glyph into a bitmap (currently held by FreeType)
  536. const FT_Bitmap* ft_bitmap = src_tmp.Font.RenderGlyphAndGetInfo(&src_glyph.Info);
  537. if (ft_bitmap == nullptr)
  538. continue;
  539. // Allocate new temporary chunk if needed
  540. const int bitmap_size_in_bytes = src_glyph.Info.Width * src_glyph.Info.Height * 4;
  541. if (buf_bitmap_current_used_bytes + bitmap_size_in_bytes > BITMAP_BUFFERS_CHUNK_SIZE)
  542. {
  543. buf_bitmap_current_used_bytes = 0;
  544. buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
  545. }
  546. IM_ASSERT(buf_bitmap_current_used_bytes + bitmap_size_in_bytes <= BITMAP_BUFFERS_CHUNK_SIZE); // We could probably allocate custom-sized buffer instead.
  547. // Blit rasterized pixels to our temporary buffer and keep a pointer to it.
  548. src_glyph.BitmapData = (unsigned int*)(buf_bitmap_buffers.back() + buf_bitmap_current_used_bytes);
  549. buf_bitmap_current_used_bytes += bitmap_size_in_bytes;
  550. src_tmp.Font.BlitGlyph(ft_bitmap, src_glyph.BitmapData, src_glyph.Info.Width, multiply_enabled ? multiply_table : nullptr);
  551. src_tmp.Rects[glyph_i].w = (stbrp_coord)(src_glyph.Info.Width + pack_padding);
  552. src_tmp.Rects[glyph_i].h = (stbrp_coord)(src_glyph.Info.Height + pack_padding);
  553. total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;
  554. }
  555. }
  556. for (int i = 0; i < atlas->CustomRects.Size; i++)
  557. total_surface += (atlas->CustomRects[i].Width + pack_padding) * (atlas->CustomRects[i].Height + pack_padding);
  558. // We need a width for the skyline algorithm, any width!
  559. // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
  560. // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface.
  561. const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1;
  562. atlas->TexHeight = 0;
  563. if (atlas->TexDesiredWidth > 0)
  564. atlas->TexWidth = atlas->TexDesiredWidth;
  565. else
  566. atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512;
  567. // 5. Start packing
  568. // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
  569. const int TEX_HEIGHT_MAX = 1024 * 32;
  570. const int num_nodes_for_packing_algorithm = atlas->TexWidth - atlas->TexGlyphPadding;
  571. ImVector<stbrp_node> pack_nodes;
  572. pack_nodes.resize(num_nodes_for_packing_algorithm);
  573. stbrp_context pack_context;
  574. stbrp_init_target(&pack_context, atlas->TexWidth - atlas->TexGlyphPadding, TEX_HEIGHT_MAX - atlas->TexGlyphPadding, pack_nodes.Data, pack_nodes.Size);
  575. ImFontAtlasBuildPackCustomRects(atlas, &pack_context);
  576. // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point.
  577. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  578. {
  579. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  580. if (src_tmp.GlyphsCount == 0)
  581. continue;
  582. stbrp_pack_rects(&pack_context, src_tmp.Rects, src_tmp.GlyphsCount);
  583. // Extend texture height and mark missing glyphs as non-packed so we won't render them.
  584. // FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?)
  585. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
  586. if (src_tmp.Rects[glyph_i].was_packed)
  587. atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h);
  588. }
  589. // 7. Allocate texture
  590. atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight);
  591. atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
  592. if (src_load_color)
  593. {
  594. size_t tex_size = (size_t)atlas->TexWidth * atlas->TexHeight * 4;
  595. atlas->TexPixelsRGBA32 = (unsigned int*)IM_ALLOC(tex_size);
  596. memset(atlas->TexPixelsRGBA32, 0, tex_size);
  597. }
  598. else
  599. {
  600. size_t tex_size = (size_t)atlas->TexWidth * atlas->TexHeight * 1;
  601. atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(tex_size);
  602. memset(atlas->TexPixelsAlpha8, 0, tex_size);
  603. }
  604. // 8. Copy rasterized font characters back into the main texture
  605. // 9. Setup ImFont and glyphs for runtime
  606. bool tex_use_colors = false;
  607. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  608. {
  609. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  610. // When merging fonts with MergeMode=true:
  611. // - We can have multiple input fonts writing into a same destination font.
  612. // - dst_font->Sources is != from src which is our source configuration.
  613. ImFontConfig& src = atlas->Sources[src_i];
  614. ImFont* dst_font = src.DstFont;
  615. const float ascent = src_tmp.Font.Info.Ascender;
  616. const float descent = src_tmp.Font.Info.Descender;
  617. ImFontAtlasBuildSetupFont(atlas, dst_font, &src, ascent, descent);
  618. if (src_tmp.GlyphsCount == 0)
  619. continue;
  620. const float font_off_x = src.GlyphOffset.x;
  621. const float font_off_y = src.GlyphOffset.y + IM_ROUND(dst_font->Ascent);
  622. const int padding = atlas->TexGlyphPadding;
  623. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
  624. {
  625. ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
  626. stbrp_rect& pack_rect = src_tmp.Rects[glyph_i];
  627. IM_ASSERT(pack_rect.was_packed);
  628. if (pack_rect.w == 0 && pack_rect.h == 0)
  629. continue;
  630. GlyphInfo& info = src_glyph.Info;
  631. IM_ASSERT(info.Width + padding <= pack_rect.w);
  632. IM_ASSERT(info.Height + padding <= pack_rect.h);
  633. const int tx = pack_rect.x + padding;
  634. const int ty = pack_rect.y + padding;
  635. // Register glyph
  636. float x0 = info.OffsetX * src_tmp.Font.InvRasterizationDensity + font_off_x;
  637. float y0 = info.OffsetY * src_tmp.Font.InvRasterizationDensity + font_off_y;
  638. float x1 = x0 + info.Width * src_tmp.Font.InvRasterizationDensity;
  639. float y1 = y0 + info.Height * src_tmp.Font.InvRasterizationDensity;
  640. float u0 = (tx) / (float)atlas->TexWidth;
  641. float v0 = (ty) / (float)atlas->TexHeight;
  642. float u1 = (tx + info.Width) / (float)atlas->TexWidth;
  643. float v1 = (ty + info.Height) / (float)atlas->TexHeight;
  644. dst_font->AddGlyph(&src, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX * src_tmp.Font.InvRasterizationDensity);
  645. ImFontGlyph* dst_glyph = &dst_font->Glyphs.back();
  646. IM_ASSERT(dst_glyph->Codepoint == src_glyph.Codepoint);
  647. if (src_glyph.Info.IsColored)
  648. dst_glyph->Colored = tex_use_colors = true;
  649. // Blit from temporary buffer to final texture
  650. size_t blit_src_stride = (size_t)src_glyph.Info.Width;
  651. size_t blit_dst_stride = (size_t)atlas->TexWidth;
  652. unsigned int* blit_src = src_glyph.BitmapData;
  653. if (atlas->TexPixelsAlpha8 != nullptr)
  654. {
  655. unsigned char* blit_dst = atlas->TexPixelsAlpha8 + (ty * blit_dst_stride) + tx;
  656. for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride)
  657. for (int x = 0; x < info.Width; x++)
  658. blit_dst[x] = (unsigned char)((blit_src[x] >> IM_COL32_A_SHIFT) & 0xFF);
  659. }
  660. else
  661. {
  662. unsigned int* blit_dst = atlas->TexPixelsRGBA32 + (ty * blit_dst_stride) + tx;
  663. for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride)
  664. for (int x = 0; x < info.Width; x++)
  665. blit_dst[x] = blit_src[x];
  666. }
  667. }
  668. src_tmp.Rects = nullptr;
  669. }
  670. atlas->TexPixelsUseColors = tex_use_colors;
  671. // Cleanup
  672. for (int buf_i = 0; buf_i < buf_bitmap_buffers.Size; buf_i++)
  673. IM_FREE(buf_bitmap_buffers[buf_i]);
  674. src_tmp_array.clear_destruct();
  675. ImFontAtlasBuildFinish(atlas);
  676. return true;
  677. }
  678. // FreeType memory allocation callbacks
  679. static void* FreeType_Alloc(FT_Memory /*memory*/, long size)
  680. {
  681. return GImGuiFreeTypeAllocFunc((size_t)size, GImGuiFreeTypeAllocatorUserData);
  682. }
  683. static void FreeType_Free(FT_Memory /*memory*/, void* block)
  684. {
  685. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  686. }
  687. static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size, void* block)
  688. {
  689. // Implement realloc() as we don't ask user to provide it.
  690. if (block == nullptr)
  691. return GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  692. if (new_size == 0)
  693. {
  694. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  695. return nullptr;
  696. }
  697. if (new_size > cur_size)
  698. {
  699. void* new_block = GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  700. memcpy(new_block, block, (size_t)cur_size);
  701. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  702. return new_block;
  703. }
  704. return block;
  705. }
  706. static bool ImFontAtlasBuildWithFreeType(ImFontAtlas* atlas)
  707. {
  708. // FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html
  709. FT_MemoryRec_ memory_rec = {};
  710. memory_rec.user = nullptr;
  711. memory_rec.alloc = &FreeType_Alloc;
  712. memory_rec.free = &FreeType_Free;
  713. memory_rec.realloc = &FreeType_Realloc;
  714. // https://www.freetype.org/freetype2/docs/reference/ft2-module_management.html#FT_New_Library
  715. FT_Library ft_library;
  716. FT_Error error = FT_New_Library(&memory_rec, &ft_library);
  717. if (error != 0)
  718. return false;
  719. // If you don't call FT_Add_Default_Modules() the rest of code may work, but FreeType won't use our custom allocator.
  720. FT_Add_Default_Modules(ft_library);
  721. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  722. // Install svg hooks for FreeType
  723. // https://freetype.org/freetype2/docs/reference/ft2-properties.html#svg-hooks
  724. // https://freetype.org/freetype2/docs/reference/ft2-svg_fonts.html#svg_fonts
  725. SVG_RendererHooks hooks = { ImGuiLunasvgPortInit, ImGuiLunasvgPortFree, ImGuiLunasvgPortRender, ImGuiLunasvgPortPresetSlot };
  726. FT_Property_Set(ft_library, "ot-svg", "svg-hooks", &hooks);
  727. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  728. #ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG
  729. // With plutosvg, use provided hooks
  730. FT_Property_Set(ft_library, "ot-svg", "svg-hooks", plutosvg_ft_svg_hooks());
  731. #endif // IMGUI_ENABLE_FREETYPE_PLUTOSVG
  732. bool ret = ImFontAtlasBuildWithFreeTypeEx(ft_library, atlas, atlas->FontBuilderFlags);
  733. FT_Done_Library(ft_library);
  734. return ret;
  735. }
  736. const ImFontBuilderIO* ImGuiFreeType::GetBuilderForFreeType()
  737. {
  738. static ImFontBuilderIO io;
  739. io.FontBuilder_Build = ImFontAtlasBuildWithFreeType;
  740. return &io;
  741. }
  742. void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
  743. {
  744. GImGuiFreeTypeAllocFunc = alloc_func;
  745. GImGuiFreeTypeFreeFunc = free_func;
  746. GImGuiFreeTypeAllocatorUserData = user_data;
  747. }
  748. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  749. // For more details, see https://gitlab.freedesktop.org/freetype/freetype-demos/-/blob/master/src/rsvg-port.c
  750. // The original code from the demo is licensed under CeCILL-C Free Software License Agreement (https://gitlab.freedesktop.org/freetype/freetype/-/blob/master/LICENSE.TXT)
  751. struct LunasvgPortState
  752. {
  753. FT_Error err = FT_Err_Ok;
  754. lunasvg::Matrix matrix;
  755. std::unique_ptr<lunasvg::Document> svg = nullptr;
  756. };
  757. static FT_Error ImGuiLunasvgPortInit(FT_Pointer* _state)
  758. {
  759. *_state = IM_NEW(LunasvgPortState)();
  760. return FT_Err_Ok;
  761. }
  762. static void ImGuiLunasvgPortFree(FT_Pointer* _state)
  763. {
  764. IM_DELETE(*(LunasvgPortState**)_state);
  765. }
  766. static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state)
  767. {
  768. LunasvgPortState* state = *(LunasvgPortState**)_state;
  769. // If there was an error while loading the svg in ImGuiLunasvgPortPresetSlot(), the renderer hook still get called, so just returns the error.
  770. if (state->err != FT_Err_Ok)
  771. return state->err;
  772. // rows is height, pitch (or stride) equals to width * sizeof(int32)
  773. lunasvg::Bitmap bitmap((uint8_t*)slot->bitmap.buffer, slot->bitmap.width, slot->bitmap.rows, slot->bitmap.pitch);
  774. state->svg->setMatrix(state->svg->matrix().identity()); // Reset the svg matrix to the default value
  775. state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated
  776. state->err = FT_Err_Ok;
  777. return state->err;
  778. }
  779. static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_Pointer* _state)
  780. {
  781. FT_SVG_Document document = (FT_SVG_Document)slot->other;
  782. LunasvgPortState* state = *(LunasvgPortState**)_state;
  783. FT_Size_Metrics& metrics = document->metrics;
  784. // This function is called twice, once in the FT_Load_Glyph() and another right before ImGuiLunasvgPortRender().
  785. // If it's the latter, don't do anything because it's // already done in the former.
  786. if (cache)
  787. return state->err;
  788. state->svg = lunasvg::Document::loadFromData((const char*)document->svg_document, document->svg_document_length);
  789. if (state->svg == nullptr)
  790. {
  791. state->err = FT_Err_Invalid_SVG_Document;
  792. return state->err;
  793. }
  794. lunasvg::Box box = state->svg->box();
  795. double scale = std::min(metrics.x_ppem / box.w, metrics.y_ppem / box.h);
  796. double xx = (double)document->transform.xx / (1 << 16);
  797. double xy = -(double)document->transform.xy / (1 << 16);
  798. double yx = -(double)document->transform.yx / (1 << 16);
  799. double yy = (double)document->transform.yy / (1 << 16);
  800. double x0 = (double)document->delta.x / 64 * box.w / metrics.x_ppem;
  801. double y0 = -(double)document->delta.y / 64 * box.h / metrics.y_ppem;
  802. // Scale and transform, we don't translate the svg yet
  803. state->matrix.identity();
  804. state->matrix.scale(scale, scale);
  805. state->matrix.transform(xx, xy, yx, yy, x0, y0);
  806. state->svg->setMatrix(state->matrix);
  807. // Pre-translate the matrix for the rendering step
  808. state->matrix.translate(-box.x, -box.y);
  809. // Get the box again after the transformation
  810. box = state->svg->box();
  811. // Calculate the bitmap size
  812. slot->bitmap_left = FT_Int(box.x);
  813. slot->bitmap_top = FT_Int(-box.y);
  814. slot->bitmap.rows = (unsigned int)(ImCeil((float)box.h));
  815. slot->bitmap.width = (unsigned int)(ImCeil((float)box.w));
  816. slot->bitmap.pitch = slot->bitmap.width * 4;
  817. slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
  818. // Compute all the bearings and set them correctly. The outline is scaled already, we just need to use the bounding box.
  819. double metrics_width = box.w;
  820. double metrics_height = box.h;
  821. double horiBearingX = box.x;
  822. double horiBearingY = -box.y;
  823. double vertBearingX = slot->metrics.horiBearingX / 64.0 - slot->metrics.horiAdvance / 64.0 / 2.0;
  824. double vertBearingY = (slot->metrics.vertAdvance / 64.0 - slot->metrics.height / 64.0) / 2.0;
  825. slot->metrics.width = FT_Pos(IM_ROUND(metrics_width * 64.0)); // Using IM_ROUND() assume width and height are positive
  826. slot->metrics.height = FT_Pos(IM_ROUND(metrics_height * 64.0));
  827. slot->metrics.horiBearingX = FT_Pos(horiBearingX * 64);
  828. slot->metrics.horiBearingY = FT_Pos(horiBearingY * 64);
  829. slot->metrics.vertBearingX = FT_Pos(vertBearingX * 64);
  830. slot->metrics.vertBearingY = FT_Pos(vertBearingY * 64);
  831. if (slot->metrics.vertAdvance == 0)
  832. slot->metrics.vertAdvance = FT_Pos(metrics_height * 1.2 * 64.0);
  833. state->err = FT_Err_Ok;
  834. return state->err;
  835. }
  836. #endif // #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  837. //-----------------------------------------------------------------------------
  838. #ifdef __GNUC__
  839. #pragma GCC diagnostic pop
  840. #endif
  841. #ifdef _MSC_VER
  842. #pragma warning (pop)
  843. #endif
  844. #endif // #ifndef IMGUI_DISABLE