imgui_freetype.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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) in 2017, with improvements by @mikesart.
  5. // Maintained since 2019 by @ocornut.
  6. // CHANGELOG
  7. // (minor and older changes stripped away, please see git history for details)
  8. // 2025/06/11: refactored for the new ImFontLoader architecture, and ImGuiBackendFlags_RendererHasTextures support.
  9. // 2024/10/17: added plutosvg support for SVG Fonts (seems faster/better than lunasvg). Enable by using '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG'. (#7927)
  10. // 2023/11/13: added support for ImFontConfig::RasterizationDensity field for scaling render density without scaling metrics.
  11. // 2023/08/01: added support for SVG fonts, enable by using '#define IMGUI_ENABLE_FREETYPE_LUNASVG'. (#6591)
  12. // 2023/01/04: fixed a packing issue which in some occurrences would prevent large amount of glyphs from being packed correctly.
  13. // 2021/08/23: fixed crash when FT_Render_Glyph() fails to render a glyph and returns nullptr.
  14. // 2021/03/05: added ImGuiFreeTypeBuilderFlags_Bitmap to load bitmap glyphs.
  15. // 2021/03/02: set 'atlas->TexPixelsUseColors = true' to help some backends with deciding of a preferred texture format.
  16. // 2021/01/28: added support for color-layered glyphs via ImGuiFreeTypeBuilderFlags_LoadColor (require Freetype 2.10+).
  17. // 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().
  18. // 2020/06/04: fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails.
  19. // 2019/02/09: added RasterizerFlags::Monochrome flag to disable font anti-aliasing (combine with ::MonoHinting for best results!)
  20. // 2019/01/15: added support for imgui allocators + added FreeType only override function SetAllocatorFunctions().
  21. // 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.
  22. // 2018/06/08: added support for ImFontConfig::GlyphMinAdvanceX, GlyphMaxAdvanceX.
  23. // 2018/02/04: moved to main imgui repository (away from http://www.github.com/ocornut/imgui_club)
  24. // 2018/01/22: fix for addition of ImFontAtlas::TexUvscale member.
  25. // 2017/10/22: minor inconsequential change to match change in master (removed an unnecessary statement).
  26. // 2017/09/26: fixes for imgui internal changes.
  27. // 2017/08/26: cleanup, optimizations, support for ImFontConfig::RasterizerFlags, ImFontConfig::RasterizerMultiply.
  28. // 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.
  29. // About Gamma Correct Blending:
  30. // - FreeType assumes blending in linear space rather than gamma space.
  31. // - See https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_Render_Glyph
  32. // - For correct results you need to be using sRGB and convert to linear space in the pixel shader output.
  33. // - The default dear imgui styles will be impacted by this change (alpha values will need tweaking).
  34. // FIXME: cfg.OversampleH, OversampleV are not supported, but generally not necessary with this rasterizer because Hinting makes everything look better.
  35. #include "imgui.h"
  36. #ifndef IMGUI_DISABLE
  37. #include "imgui_freetype.h"
  38. #include "imgui_internal.h" // ImMin,ImMax,ImFontAtlasBuild*,
  39. #include <stdint.h>
  40. #include <ft2build.h>
  41. #include FT_FREETYPE_H // <freetype/freetype.h>
  42. #include FT_MODULE_H // <freetype/ftmodapi.h>
  43. #include FT_GLYPH_H // <freetype/ftglyph.h>
  44. #include FT_SIZES_H // <freetype/ftsizes.h>
  45. #include FT_SYNTHESIS_H // <freetype/ftsynth.h>
  46. // Handle LunaSVG and PlutoSVG
  47. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) && defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  48. #error "Cannot enable both IMGUI_ENABLE_FREETYPE_LUNASVG and IMGUI_ENABLE_FREETYPE_PLUTOSVG"
  49. #endif
  50. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  51. #include FT_OTSVG_H // <freetype/otsvg.h>
  52. #include FT_BBOX_H // <freetype/ftbbox.h>
  53. #include <lunasvg.h>
  54. #endif
  55. #ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG
  56. #include <plutosvg.h>
  57. #endif
  58. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined (IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  59. #if !((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
  60. #error IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG requires FreeType version >= 2.12
  61. #endif
  62. #endif
  63. #ifdef _MSC_VER
  64. #pragma warning (push)
  65. #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
  66. #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
  67. #endif
  68. #ifdef __GNUC__
  69. #pragma GCC diagnostic push
  70. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
  71. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  72. #ifndef __clang__
  73. #pragma GCC diagnostic ignored "-Wsubobject-linkage" // warning: 'xxxx' has a field 'xxxx' whose type uses the anonymous namespace
  74. #endif
  75. #endif
  76. //-------------------------------------------------------------------------
  77. // Data
  78. //-------------------------------------------------------------------------
  79. // Default memory allocators
  80. static void* ImGuiFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); }
  81. static void ImGuiFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); }
  82. // Current memory allocators
  83. static void* (*GImGuiFreeTypeAllocFunc)(size_t size, void* user_data) = ImGuiFreeTypeDefaultAllocFunc;
  84. static void (*GImGuiFreeTypeFreeFunc)(void* ptr, void* user_data) = ImGuiFreeTypeDefaultFreeFunc;
  85. static void* GImGuiFreeTypeAllocatorUserData = nullptr;
  86. // Lunasvg support
  87. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  88. static FT_Error ImGuiLunasvgPortInit(FT_Pointer* state);
  89. static void ImGuiLunasvgPortFree(FT_Pointer* state);
  90. static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state);
  91. static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_Pointer* _state);
  92. #endif
  93. //-------------------------------------------------------------------------
  94. // Code
  95. //-------------------------------------------------------------------------
  96. #define FT_CEIL(X) (((X + 63) & -64) / 64) // From SDL_ttf: Handy routines for converting from fixed point
  97. #define FT_SCALEFACTOR 64.0f
  98. // Glyph metrics:
  99. // --------------
  100. //
  101. // xmin xmax
  102. // | |
  103. // |<-------- width -------->|
  104. // | |
  105. // | +-------------------------+----------------- ymax
  106. // | | ggggggggg ggggg | ^ ^
  107. // | | g:::::::::ggg::::g | | |
  108. // | | g:::::::::::::::::g | | |
  109. // | | g::::::ggggg::::::gg | | |
  110. // | | g:::::g g:::::g | | |
  111. // offsetX -|-------->| g:::::g g:::::g | offsetY |
  112. // | | g:::::g g:::::g | | |
  113. // | | g::::::g g:::::g | | |
  114. // | | g:::::::ggggg:::::g | | |
  115. // | | g::::::::::::::::g | | height
  116. // | | gg::::::::::::::g | | |
  117. // baseline ---*---------|---- gggggggg::::::g-----*-------- |
  118. // / | | g:::::g | |
  119. // origin | | gggggg g:::::g | |
  120. // | | g:::::gg gg:::::g | |
  121. // | | g::::::ggg:::::::g | |
  122. // | | gg:::::::::::::g | |
  123. // | | ggg::::::ggg | |
  124. // | | gggggg | v
  125. // | +-------------------------+----------------- ymin
  126. // | |
  127. // |------------- advanceX ----------->|
  128. // Stored in ImFontAtlas::FontLoaderData. ALLOCATED BY US.
  129. struct ImGui_ImplFreeType_Data
  130. {
  131. FT_Library Library;
  132. FT_MemoryRec_ MemoryManager;
  133. ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); }
  134. };
  135. // Stored in ImFontConfig::FontLoaderData. ALLOCATED BY US.
  136. struct ImGui_ImplFreeType_FontSrcData
  137. {
  138. // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime.
  139. bool InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_user_flags);
  140. void CloseFont();
  141. ImGui_ImplFreeType_FontSrcData() { memset((void*)this, 0, sizeof(*this)); }
  142. ~ImGui_ImplFreeType_FontSrcData() { CloseFont(); }
  143. // Members
  144. FT_Face FtFace;
  145. ImGuiFreeTypeLoaderFlags UserFlags; // = ImFontConfig::FontLoaderFlags
  146. FT_Int32 LoadFlags;
  147. ImFontBaked* BakedLastActivated;
  148. };
  149. // Stored in ImFontBaked::FontLoaderDatas: pointer to SourcesCount instances of this. ALLOCATED BY CORE.
  150. struct ImGui_ImplFreeType_FontSrcBakedData
  151. {
  152. FT_Size FtSize; // This represent a FT_Face with a given size.
  153. ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); }
  154. };
  155. bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_font_loader_flags)
  156. {
  157. FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (FT_Long)src->FontDataSize, (FT_Long)src->FontNo, &FtFace);
  158. if (error != 0)
  159. return false;
  160. error = FT_Select_Charmap(FtFace, FT_ENCODING_UNICODE);
  161. if (error != 0)
  162. return false;
  163. // Convert to FreeType flags (NB: Bold and Oblique are processed separately)
  164. UserFlags = (ImGuiFreeTypeLoaderFlags)(src->FontLoaderFlags | extra_font_loader_flags);
  165. LoadFlags = 0;
  166. if ((UserFlags & ImGuiFreeTypeLoaderFlags_Bitmap) == 0)
  167. LoadFlags |= FT_LOAD_NO_BITMAP;
  168. if (UserFlags & ImGuiFreeTypeLoaderFlags_NoHinting)
  169. LoadFlags |= FT_LOAD_NO_HINTING;
  170. else
  171. src->PixelSnapH = true; // FIXME: A bit weird to do this this way.
  172. if (UserFlags & ImGuiFreeTypeLoaderFlags_NoAutoHint)
  173. LoadFlags |= FT_LOAD_NO_AUTOHINT;
  174. if (UserFlags & ImGuiFreeTypeLoaderFlags_ForceAutoHint)
  175. LoadFlags |= FT_LOAD_FORCE_AUTOHINT;
  176. if (UserFlags & ImGuiFreeTypeLoaderFlags_LightHinting)
  177. LoadFlags |= FT_LOAD_TARGET_LIGHT;
  178. else if (UserFlags & ImGuiFreeTypeLoaderFlags_MonoHinting)
  179. LoadFlags |= FT_LOAD_TARGET_MONO;
  180. else
  181. LoadFlags |= FT_LOAD_TARGET_NORMAL;
  182. if (UserFlags & ImGuiFreeTypeLoaderFlags_LoadColor)
  183. LoadFlags |= FT_LOAD_COLOR;
  184. return true;
  185. }
  186. void ImGui_ImplFreeType_FontSrcData::CloseFont()
  187. {
  188. if (FtFace)
  189. {
  190. FT_Done_Face(FtFace);
  191. FtFace = nullptr;
  192. }
  193. }
  194. static const FT_Glyph_Metrics* ImGui_ImplFreeType_LoadGlyph(ImGui_ImplFreeType_FontSrcData* src_data, uint32_t codepoint)
  195. {
  196. uint32_t glyph_index = FT_Get_Char_Index(src_data->FtFace, codepoint);
  197. if (glyph_index == 0)
  198. return nullptr;
  199. // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts.
  200. // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076
  201. // - https://github.com/ocornut/imgui/issues/4567
  202. // - https://github.com/ocornut/imgui/issues/4566
  203. // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version.
  204. FT_Error error = FT_Load_Glyph(src_data->FtFace, glyph_index, src_data->LoadFlags);
  205. if (error)
  206. return nullptr;
  207. // Need an outline for this to work
  208. FT_GlyphSlot slot = src_data->FtFace->glyph;
  209. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  210. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG);
  211. #else
  212. #if ((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
  213. 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");
  214. #endif
  215. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP);
  216. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  217. // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting)
  218. if (src_data->UserFlags & ImGuiFreeTypeLoaderFlags_Bold)
  219. FT_GlyphSlot_Embolden(slot);
  220. if (src_data->UserFlags & ImGuiFreeTypeLoaderFlags_Oblique)
  221. {
  222. FT_GlyphSlot_Oblique(slot);
  223. //FT_BBox bbox;
  224. //FT_Outline_Get_BBox(&slot->outline, &bbox);
  225. //slot->metrics.width = bbox.xMax - bbox.xMin;
  226. //slot->metrics.height = bbox.yMax - bbox.yMin;
  227. }
  228. return &slot->metrics;
  229. }
  230. static void ImGui_ImplFreeType_BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch)
  231. {
  232. IM_ASSERT(ft_bitmap != nullptr);
  233. const uint32_t w = ft_bitmap->width;
  234. const uint32_t h = ft_bitmap->rows;
  235. const uint8_t* src = ft_bitmap->buffer;
  236. const uint32_t src_pitch = ft_bitmap->pitch;
  237. switch (ft_bitmap->pixel_mode)
  238. {
  239. case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel.
  240. {
  241. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  242. for (uint32_t x = 0; x < w; x++)
  243. dst[x] = IM_COL32(255, 255, 255, src[x]);
  244. break;
  245. }
  246. case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB.
  247. {
  248. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  249. {
  250. uint8_t bits = 0;
  251. const uint8_t* bits_ptr = src;
  252. for (uint32_t x = 0; x < w; x++, bits <<= 1)
  253. {
  254. if ((x & 7) == 0)
  255. bits = *bits_ptr++;
  256. dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? 255 : 0);
  257. }
  258. }
  259. break;
  260. }
  261. case FT_PIXEL_MODE_BGRA:
  262. {
  263. // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good.
  264. #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u)
  265. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  266. for (uint32_t x = 0; x < w; x++)
  267. {
  268. uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3];
  269. dst[x] = IM_COL32(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a);
  270. }
  271. #undef DE_MULTIPLY
  272. break;
  273. }
  274. default:
  275. IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!");
  276. }
  277. }
  278. // FreeType memory allocation callbacks
  279. static void* FreeType_Alloc(FT_Memory /*memory*/, long size)
  280. {
  281. return GImGuiFreeTypeAllocFunc((size_t)size, GImGuiFreeTypeAllocatorUserData);
  282. }
  283. static void FreeType_Free(FT_Memory /*memory*/, void* block)
  284. {
  285. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  286. }
  287. static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size, void* block)
  288. {
  289. // Implement realloc() as we don't ask user to provide it.
  290. if (block == nullptr)
  291. return GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  292. if (new_size == 0)
  293. {
  294. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  295. return nullptr;
  296. }
  297. if (new_size > cur_size)
  298. {
  299. void* new_block = GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  300. memcpy(new_block, block, (size_t)cur_size);
  301. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  302. return new_block;
  303. }
  304. return block;
  305. }
  306. bool ImGui_ImplFreeType_LoaderInit(ImFontAtlas* atlas)
  307. {
  308. IM_ASSERT(atlas->FontLoaderData == nullptr);
  309. ImGui_ImplFreeType_Data* bd = IM_NEW(ImGui_ImplFreeType_Data)();
  310. // FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html
  311. bd->MemoryManager.user = nullptr;
  312. bd->MemoryManager.alloc = &FreeType_Alloc;
  313. bd->MemoryManager.free = &FreeType_Free;
  314. bd->MemoryManager.realloc = &FreeType_Realloc;
  315. // https://www.freetype.org/freetype2/docs/reference/ft2-module_management.html#FT_New_Library
  316. FT_Error error = FT_New_Library(&bd->MemoryManager, &bd->Library);
  317. if (error != 0)
  318. {
  319. IM_DELETE(bd);
  320. return false;
  321. }
  322. // If you don't call FT_Add_Default_Modules() the rest of code may work, but FreeType won't use our custom allocator.
  323. FT_Add_Default_Modules(bd->Library);
  324. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  325. // Install svg hooks for FreeType
  326. // https://freetype.org/freetype2/docs/reference/ft2-properties.html#svg-hooks
  327. // https://freetype.org/freetype2/docs/reference/ft2-svg_fonts.html#svg_fonts
  328. SVG_RendererHooks hooks = { ImGuiLunasvgPortInit, ImGuiLunasvgPortFree, ImGuiLunasvgPortRender, ImGuiLunasvgPortPresetSlot };
  329. FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", &hooks);
  330. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  331. #ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG
  332. // With plutosvg, use provided hooks
  333. FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", plutosvg_ft_svg_hooks());
  334. #endif // IMGUI_ENABLE_FREETYPE_PLUTOSVG
  335. // Store our data
  336. atlas->FontLoaderData = (void*)bd;
  337. return true;
  338. }
  339. void ImGui_ImplFreeType_LoaderShutdown(ImFontAtlas* atlas)
  340. {
  341. ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData;
  342. IM_ASSERT(bd != nullptr);
  343. FT_Done_Library(bd->Library);
  344. IM_DELETE(bd);
  345. atlas->FontLoaderData = nullptr;
  346. }
  347. bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src)
  348. {
  349. ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData;
  350. ImGui_ImplFreeType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplFreeType_FontSrcData);
  351. IM_ASSERT(src->FontLoaderData == nullptr);
  352. src->FontLoaderData = bd_font_data;
  353. if (!bd_font_data->InitFont(bd->Library, src, (ImGuiFreeTypeLoaderFlags)atlas->FontLoaderFlags))
  354. {
  355. IM_DELETE(bd_font_data);
  356. src->FontLoaderData = nullptr;
  357. return false;
  358. }
  359. return true;
  360. }
  361. void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src)
  362. {
  363. IM_UNUSED(atlas);
  364. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  365. IM_DELETE(bd_font_data);
  366. src->FontLoaderData = nullptr;
  367. }
  368. bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src)
  369. {
  370. IM_UNUSED(atlas);
  371. float size = baked->Size;
  372. if (src->MergeMode && src->SizePixels != 0.0f)
  373. size *= (src->SizePixels / baked->ContainerFont->Sources[0]->SizePixels);
  374. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  375. bd_font_data->BakedLastActivated = baked;
  376. // We use one FT_Size per (source + baked) combination.
  377. ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src;
  378. IM_ASSERT(bd_baked_data != nullptr);
  379. IM_PLACEMENT_NEW(bd_baked_data) ImGui_ImplFreeType_FontSrcBakedData();
  380. FT_New_Size(bd_font_data->FtFace, &bd_baked_data->FtSize);
  381. FT_Activate_Size(bd_baked_data->FtSize);
  382. // Vuhdo 2017: "I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height'
  383. // 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.
  384. // FT_Set_Pixel_Sizes() doesn't seem to get us the same result."
  385. // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL)
  386. const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity;
  387. FT_Size_RequestRec req;
  388. req.type = (bd_font_data->UserFlags & ImGuiFreeTypeLoaderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM;
  389. req.width = 0;
  390. req.height = (uint32_t)(size * 64 * rasterizer_density);
  391. req.horiResolution = 0;
  392. req.vertResolution = 0;
  393. FT_Request_Size(bd_font_data->FtFace, &req);
  394. // Output
  395. if (src->MergeMode == false)
  396. {
  397. // Read metrics
  398. FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics;
  399. const float scale = 1.0f / rasterizer_density;
  400. baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive).
  401. baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative).
  402. //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // 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.
  403. //LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * scale; // The spacing in pixels between one row's descent and the next row's ascent.
  404. //MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * scale; // This field gives the maximum horizontal cursor advance for all glyphs in the font.
  405. }
  406. return true;
  407. }
  408. void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src)
  409. {
  410. IM_UNUSED(atlas);
  411. IM_UNUSED(baked);
  412. IM_UNUSED(src);
  413. ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src;
  414. IM_ASSERT(bd_baked_data != nullptr);
  415. FT_Done_Size(bd_baked_data->FtSize);
  416. bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE()
  417. }
  418. bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x)
  419. {
  420. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  421. uint32_t glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint);
  422. if (glyph_index == 0)
  423. return false;
  424. if (bd_font_data->BakedLastActivated != baked) // <-- could use id
  425. {
  426. // Activate current size
  427. ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src;
  428. FT_Activate_Size(bd_baked_data->FtSize);
  429. bd_font_data->BakedLastActivated = baked;
  430. }
  431. const FT_Glyph_Metrics* metrics = ImGui_ImplFreeType_LoadGlyph(bd_font_data, codepoint);
  432. if (metrics == nullptr)
  433. return false;
  434. FT_Face face = bd_font_data->FtFace;
  435. FT_GlyphSlot slot = face->glyph;
  436. const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity;
  437. // Load metrics only mode
  438. const float advance_x = (slot->advance.x / FT_SCALEFACTOR) / rasterizer_density;
  439. if (out_advance_x != NULL)
  440. {
  441. IM_ASSERT(out_glyph == NULL);
  442. *out_advance_x = advance_x;
  443. return true;
  444. }
  445. // Render glyph into a bitmap (currently held by FreeType)
  446. FT_Render_Mode render_mode = (bd_font_data->UserFlags & ImGuiFreeTypeLoaderFlags_Monochrome) ? FT_RENDER_MODE_MONO : FT_RENDER_MODE_NORMAL;
  447. FT_Error error = FT_Render_Glyph(slot, render_mode);
  448. const FT_Bitmap* ft_bitmap = &slot->bitmap;
  449. if (error != 0 || ft_bitmap == nullptr)
  450. return false;
  451. const int w = (int)ft_bitmap->width;
  452. const int h = (int)ft_bitmap->rows;
  453. const bool is_visible = (w != 0 && h != 0);
  454. // Prepare glyph
  455. out_glyph->Codepoint = codepoint;
  456. out_glyph->AdvanceX = advance_x;
  457. // Pack and retrieve position inside texture atlas
  458. if (is_visible)
  459. {
  460. ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h);
  461. if (pack_id == ImFontAtlasRectId_Invalid)
  462. {
  463. // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?)
  464. IM_ASSERT(pack_id != ImFontAtlasRectId_Invalid && "Out of texture memory.");
  465. return false;
  466. }
  467. ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id);
  468. // Render pixels to our temporary buffer
  469. atlas->Builder->TempBuffer.resize(w * h * 4);
  470. uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data;
  471. ImGui_ImplFreeType_BlitGlyph(ft_bitmap, temp_buffer, w);
  472. const float ref_size = baked->ContainerFont->Sources[0]->SizePixels;
  473. const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f;
  474. float font_off_x = (src->GlyphOffset.x * offsets_scale);
  475. float font_off_y = (src->GlyphOffset.y * offsets_scale) + baked->Ascent;
  476. if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome.
  477. font_off_x = IM_ROUND(font_off_x);
  478. if (src->PixelSnapV)
  479. font_off_y = IM_ROUND(font_off_y);
  480. float recip_h = 1.0f / rasterizer_density;
  481. float recip_v = 1.0f / rasterizer_density;
  482. // Register glyph
  483. float glyph_off_x = (float)face->glyph->bitmap_left;
  484. float glyph_off_y = (float)-face->glyph->bitmap_top;
  485. out_glyph->X0 = glyph_off_x * recip_h + font_off_x;
  486. out_glyph->Y0 = glyph_off_y * recip_v + font_off_y;
  487. out_glyph->X1 = (glyph_off_x + w) * recip_h + font_off_x;
  488. out_glyph->Y1 = (glyph_off_y + h) * recip_v + font_off_y;
  489. out_glyph->Visible = true;
  490. out_glyph->Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA);
  491. out_glyph->PackId = pack_id;
  492. ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, out_glyph, r, (const unsigned char*)temp_buffer, ImTextureFormat_RGBA32, w * 4);
  493. }
  494. return true;
  495. }
  496. bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint)
  497. {
  498. IM_UNUSED(atlas);
  499. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  500. int glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint);
  501. return glyph_index != 0;
  502. }
  503. const ImFontLoader* ImGuiFreeType::GetFontLoader()
  504. {
  505. static ImFontLoader loader;
  506. loader.Name = "FreeType";
  507. loader.LoaderInit = ImGui_ImplFreeType_LoaderInit;
  508. loader.LoaderShutdown = ImGui_ImplFreeType_LoaderShutdown;
  509. loader.FontSrcInit = ImGui_ImplFreeType_FontSrcInit;
  510. loader.FontSrcDestroy = ImGui_ImplFreeType_FontSrcDestroy;
  511. loader.FontSrcContainsGlyph = ImGui_ImplFreetype_FontSrcContainsGlyph;
  512. loader.FontBakedInit = ImGui_ImplFreeType_FontBakedInit;
  513. loader.FontBakedDestroy = ImGui_ImplFreeType_FontBakedDestroy;
  514. loader.FontBakedLoadGlyph = ImGui_ImplFreeType_FontBakedLoadGlyph;
  515. loader.FontBakedSrcLoaderDataSize = sizeof(ImGui_ImplFreeType_FontSrcBakedData);
  516. return &loader;
  517. }
  518. void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
  519. {
  520. GImGuiFreeTypeAllocFunc = alloc_func;
  521. GImGuiFreeTypeFreeFunc = free_func;
  522. GImGuiFreeTypeAllocatorUserData = user_data;
  523. }
  524. bool ImGuiFreeType::DebugEditFontLoaderFlags(unsigned int* p_font_loader_flags)
  525. {
  526. bool edited = false;
  527. edited |= ImGui::CheckboxFlags("NoHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_NoHinting);
  528. edited |= ImGui::CheckboxFlags("NoAutoHint", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_NoAutoHint);
  529. edited |= ImGui::CheckboxFlags("ForceAutoHint",p_font_loader_flags, ImGuiFreeTypeLoaderFlags_ForceAutoHint);
  530. edited |= ImGui::CheckboxFlags("LightHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_LightHinting);
  531. edited |= ImGui::CheckboxFlags("MonoHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_MonoHinting);
  532. edited |= ImGui::CheckboxFlags("Bold", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Bold);
  533. edited |= ImGui::CheckboxFlags("Oblique", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Oblique);
  534. edited |= ImGui::CheckboxFlags("Monochrome", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Monochrome);
  535. edited |= ImGui::CheckboxFlags("LoadColor", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_LoadColor);
  536. edited |= ImGui::CheckboxFlags("Bitmap", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Bitmap);
  537. return edited;
  538. }
  539. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  540. // For more details, see https://gitlab.freedesktop.org/freetype/freetype-demos/-/blob/master/src/rsvg-port.c
  541. // 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)
  542. struct LunasvgPortState
  543. {
  544. FT_Error err = FT_Err_Ok;
  545. lunasvg::Matrix matrix;
  546. std::unique_ptr<lunasvg::Document> svg = nullptr;
  547. };
  548. static FT_Error ImGuiLunasvgPortInit(FT_Pointer* _state)
  549. {
  550. *_state = IM_NEW(LunasvgPortState)();
  551. return FT_Err_Ok;
  552. }
  553. static void ImGuiLunasvgPortFree(FT_Pointer* _state)
  554. {
  555. IM_DELETE(*(LunasvgPortState**)_state);
  556. }
  557. static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state)
  558. {
  559. LunasvgPortState* state = *(LunasvgPortState**)_state;
  560. // If there was an error while loading the svg in ImGuiLunasvgPortPresetSlot(), the renderer hook still get called, so just returns the error.
  561. if (state->err != FT_Err_Ok)
  562. return state->err;
  563. // rows is height, pitch (or stride) equals to width * sizeof(int32)
  564. lunasvg::Bitmap bitmap((uint8_t*)slot->bitmap.buffer, slot->bitmap.width, slot->bitmap.rows, slot->bitmap.pitch);
  565. #if LUNASVG_VERSION_MAJOR >= 3
  566. state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated
  567. #else
  568. state->svg->setMatrix(state->svg->matrix().identity()); // Reset the svg matrix to the default value
  569. state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated
  570. #endif
  571. state->err = FT_Err_Ok;
  572. return state->err;
  573. }
  574. static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_Pointer* _state)
  575. {
  576. FT_SVG_Document document = (FT_SVG_Document)slot->other;
  577. LunasvgPortState* state = *(LunasvgPortState**)_state;
  578. FT_Size_Metrics& metrics = document->metrics;
  579. // This function is called twice, once in the FT_Load_Glyph() and another right before ImGuiLunasvgPortRender().
  580. // If it's the latter, don't do anything because it's // already done in the former.
  581. if (cache)
  582. return state->err;
  583. state->svg = lunasvg::Document::loadFromData((const char*)document->svg_document, document->svg_document_length);
  584. if (state->svg == nullptr)
  585. {
  586. state->err = FT_Err_Invalid_SVG_Document;
  587. return state->err;
  588. }
  589. #if LUNASVG_VERSION_MAJOR >= 3
  590. lunasvg::Box box = state->svg->boundingBox();
  591. #else
  592. lunasvg::Box box = state->svg->box();
  593. #endif
  594. double scale = std::min(metrics.x_ppem / box.w, metrics.y_ppem / box.h);
  595. double xx = (double)document->transform.xx / (1 << 16);
  596. double xy = -(double)document->transform.xy / (1 << 16);
  597. double yx = -(double)document->transform.yx / (1 << 16);
  598. double yy = (double)document->transform.yy / (1 << 16);
  599. double x0 = (double)document->delta.x / 64 * box.w / metrics.x_ppem;
  600. double y0 = -(double)document->delta.y / 64 * box.h / metrics.y_ppem;
  601. #if LUNASVG_VERSION_MAJOR >= 3
  602. // Scale, transform and pre-translate the matrix for the rendering step
  603. state->matrix = lunasvg::Matrix::translated(-box.x, -box.y);
  604. state->matrix.multiply(lunasvg::Matrix(xx, xy, yx, yy, x0, y0));
  605. state->matrix.scale(scale, scale);
  606. // Apply updated transformation to the bounding box
  607. box.transform(state->matrix);
  608. #else
  609. // Scale and transform, we don't translate the svg yet
  610. state->matrix.identity();
  611. state->matrix.scale(scale, scale);
  612. state->matrix.transform(xx, xy, yx, yy, x0, y0);
  613. state->svg->setMatrix(state->matrix);
  614. // Pre-translate the matrix for the rendering step
  615. state->matrix.translate(-box.x, -box.y);
  616. // Get the box again after the transformation
  617. box = state->svg->box();
  618. #endif
  619. // Calculate the bitmap size
  620. slot->bitmap_left = FT_Int(box.x);
  621. slot->bitmap_top = FT_Int(-box.y);
  622. slot->bitmap.rows = (unsigned int)(ImCeil((float)box.h));
  623. slot->bitmap.width = (unsigned int)(ImCeil((float)box.w));
  624. slot->bitmap.pitch = slot->bitmap.width * 4;
  625. slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
  626. // Compute all the bearings and set them correctly. The outline is scaled already, we just need to use the bounding box.
  627. double metrics_width = box.w;
  628. double metrics_height = box.h;
  629. double horiBearingX = box.x;
  630. double horiBearingY = -box.y;
  631. double vertBearingX = slot->metrics.horiBearingX / 64.0 - slot->metrics.horiAdvance / 64.0 / 2.0;
  632. double vertBearingY = (slot->metrics.vertAdvance / 64.0 - slot->metrics.height / 64.0) / 2.0;
  633. slot->metrics.width = FT_Pos(IM_ROUND(metrics_width * 64.0)); // Using IM_ROUND() assume width and height are positive
  634. slot->metrics.height = FT_Pos(IM_ROUND(metrics_height * 64.0));
  635. slot->metrics.horiBearingX = FT_Pos(horiBearingX * 64);
  636. slot->metrics.horiBearingY = FT_Pos(horiBearingY * 64);
  637. slot->metrics.vertBearingX = FT_Pos(vertBearingX * 64);
  638. slot->metrics.vertBearingY = FT_Pos(vertBearingY * 64);
  639. if (slot->metrics.vertAdvance == 0)
  640. slot->metrics.vertAdvance = FT_Pos(metrics_height * 1.2 * 64.0);
  641. state->err = FT_Err_Ok;
  642. return state->err;
  643. }
  644. #endif // #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  645. //-----------------------------------------------------------------------------
  646. #ifdef __GNUC__
  647. #pragma GCC diagnostic pop
  648. #endif
  649. #ifdef _MSC_VER
  650. #pragma warning (pop)
  651. #endif
  652. #endif // #ifndef IMGUI_DISABLE