imgui_freetype.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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, const 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, const ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_font_loader_flags)
  156. {
  157. FT_Error error = FT_New_Memory_Face(ft_library, (const FT_Byte*)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. if (UserFlags & ImGuiFreeTypeLoaderFlags_NoAutoHint)
  171. LoadFlags |= FT_LOAD_NO_AUTOHINT;
  172. if (UserFlags & ImGuiFreeTypeLoaderFlags_ForceAutoHint)
  173. LoadFlags |= FT_LOAD_FORCE_AUTOHINT;
  174. if (UserFlags & ImGuiFreeTypeLoaderFlags_LightHinting)
  175. LoadFlags |= FT_LOAD_TARGET_LIGHT;
  176. else if (UserFlags & ImGuiFreeTypeLoaderFlags_MonoHinting)
  177. LoadFlags |= FT_LOAD_TARGET_MONO;
  178. else
  179. LoadFlags |= FT_LOAD_TARGET_NORMAL;
  180. if (UserFlags & ImGuiFreeTypeLoaderFlags_LoadColor)
  181. LoadFlags |= FT_LOAD_COLOR;
  182. return true;
  183. }
  184. void ImGui_ImplFreeType_FontSrcData::CloseFont()
  185. {
  186. if (FtFace)
  187. {
  188. FT_Done_Face(FtFace);
  189. FtFace = nullptr;
  190. }
  191. }
  192. static const FT_Glyph_Metrics* ImGui_ImplFreeType_LoadGlyph(ImGui_ImplFreeType_FontSrcData* src_data, uint32_t codepoint)
  193. {
  194. uint32_t glyph_index = FT_Get_Char_Index(src_data->FtFace, codepoint);
  195. if (glyph_index == 0)
  196. return nullptr;
  197. // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts.
  198. // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076
  199. // - https://github.com/ocornut/imgui/issues/4567
  200. // - https://github.com/ocornut/imgui/issues/4566
  201. // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version.
  202. FT_Error error = FT_Load_Glyph(src_data->FtFace, glyph_index, src_data->LoadFlags);
  203. if (error)
  204. return nullptr;
  205. // Need an outline for this to work
  206. FT_GlyphSlot slot = src_data->FtFace->glyph;
  207. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  208. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG);
  209. #else
  210. #if ((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
  211. 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");
  212. #endif
  213. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP);
  214. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  215. // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting)
  216. if (src_data->UserFlags & ImGuiFreeTypeLoaderFlags_Bold)
  217. FT_GlyphSlot_Embolden(slot);
  218. if (src_data->UserFlags & ImGuiFreeTypeLoaderFlags_Oblique)
  219. {
  220. FT_GlyphSlot_Oblique(slot);
  221. //FT_BBox bbox;
  222. //FT_Outline_Get_BBox(&slot->outline, &bbox);
  223. //slot->metrics.width = bbox.xMax - bbox.xMin;
  224. //slot->metrics.height = bbox.yMax - bbox.yMin;
  225. }
  226. return &slot->metrics;
  227. }
  228. static void ImGui_ImplFreeType_BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch)
  229. {
  230. IM_ASSERT(ft_bitmap != nullptr);
  231. const uint32_t w = ft_bitmap->width;
  232. const uint32_t h = ft_bitmap->rows;
  233. const uint8_t* src = ft_bitmap->buffer;
  234. const uint32_t src_pitch = ft_bitmap->pitch;
  235. switch (ft_bitmap->pixel_mode)
  236. {
  237. case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel.
  238. {
  239. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  240. for (uint32_t x = 0; x < w; x++)
  241. dst[x] = IM_COL32(255, 255, 255, src[x]);
  242. break;
  243. }
  244. case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB.
  245. {
  246. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  247. {
  248. uint8_t bits = 0;
  249. const uint8_t* bits_ptr = src;
  250. for (uint32_t x = 0; x < w; x++, bits <<= 1)
  251. {
  252. if ((x & 7) == 0)
  253. bits = *bits_ptr++;
  254. dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? 255 : 0);
  255. }
  256. }
  257. break;
  258. }
  259. case FT_PIXEL_MODE_BGRA:
  260. {
  261. // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good.
  262. #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u)
  263. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  264. for (uint32_t x = 0; x < w; x++)
  265. {
  266. uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3];
  267. dst[x] = IM_COL32(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a);
  268. }
  269. #undef DE_MULTIPLY
  270. break;
  271. }
  272. default:
  273. IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!");
  274. }
  275. }
  276. // FreeType memory allocation callbacks
  277. static void* FreeType_Alloc(FT_Memory /*memory*/, long size)
  278. {
  279. return GImGuiFreeTypeAllocFunc((size_t)size, GImGuiFreeTypeAllocatorUserData);
  280. }
  281. static void FreeType_Free(FT_Memory /*memory*/, void* block)
  282. {
  283. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  284. }
  285. static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size, void* block)
  286. {
  287. // Implement realloc() as we don't ask user to provide it.
  288. if (block == nullptr)
  289. return GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  290. if (new_size == 0)
  291. {
  292. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  293. return nullptr;
  294. }
  295. if (new_size > cur_size)
  296. {
  297. void* new_block = GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  298. memcpy(new_block, block, (size_t)cur_size);
  299. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  300. return new_block;
  301. }
  302. return block;
  303. }
  304. static bool ImGui_ImplFreeType_LoaderInit(ImFontAtlas* atlas)
  305. {
  306. IM_ASSERT(atlas->FontLoaderData == nullptr);
  307. ImGui_ImplFreeType_Data* bd = IM_NEW(ImGui_ImplFreeType_Data)();
  308. // FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html
  309. bd->MemoryManager.user = nullptr;
  310. bd->MemoryManager.alloc = &FreeType_Alloc;
  311. bd->MemoryManager.free = &FreeType_Free;
  312. bd->MemoryManager.realloc = &FreeType_Realloc;
  313. // https://www.freetype.org/freetype2/docs/reference/ft2-module_management.html#FT_New_Library
  314. FT_Error error = FT_New_Library(&bd->MemoryManager, &bd->Library);
  315. if (error != 0)
  316. {
  317. IM_DELETE(bd);
  318. return false;
  319. }
  320. // If you don't call FT_Add_Default_Modules() the rest of code may work, but FreeType won't use our custom allocator.
  321. FT_Add_Default_Modules(bd->Library);
  322. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  323. // Install svg hooks for FreeType
  324. // https://freetype.org/freetype2/docs/reference/ft2-properties.html#svg-hooks
  325. // https://freetype.org/freetype2/docs/reference/ft2-svg_fonts.html#svg_fonts
  326. SVG_RendererHooks hooks = { ImGuiLunasvgPortInit, ImGuiLunasvgPortFree, ImGuiLunasvgPortRender, ImGuiLunasvgPortPresetSlot };
  327. FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", &hooks);
  328. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  329. #ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG
  330. // With plutosvg, use provided hooks
  331. FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", plutosvg_ft_svg_hooks());
  332. #endif // IMGUI_ENABLE_FREETYPE_PLUTOSVG
  333. // Store our data
  334. atlas->FontLoaderData = (void*)bd;
  335. return true;
  336. }
  337. static void ImGui_ImplFreeType_LoaderShutdown(ImFontAtlas* atlas)
  338. {
  339. ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData;
  340. IM_ASSERT(bd != nullptr);
  341. FT_Done_Library(bd->Library);
  342. IM_DELETE(bd);
  343. atlas->FontLoaderData = nullptr;
  344. }
  345. static bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src)
  346. {
  347. ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData;
  348. ImGui_ImplFreeType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplFreeType_FontSrcData);
  349. IM_ASSERT(src->FontLoaderData == nullptr);
  350. src->FontLoaderData = bd_font_data;
  351. if (!bd_font_data->InitFont(bd->Library, src, (ImGuiFreeTypeLoaderFlags)atlas->FontLoaderFlags))
  352. {
  353. IM_DELETE(bd_font_data);
  354. src->FontLoaderData = nullptr;
  355. return false;
  356. }
  357. return true;
  358. }
  359. static void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src)
  360. {
  361. IM_UNUSED(atlas);
  362. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  363. IM_DELETE(bd_font_data);
  364. src->FontLoaderData = nullptr;
  365. }
  366. static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src)
  367. {
  368. IM_UNUSED(atlas);
  369. float size = baked->Size;
  370. if (src->MergeMode && src->SizePixels != 0.0f)
  371. size *= (src->SizePixels / baked->OwnerFont->Sources[0]->SizePixels);
  372. size *= src->ExtraSizeScale;
  373. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  374. bd_font_data->BakedLastActivated = baked;
  375. // We use one FT_Size per (source + baked) combination.
  376. ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src;
  377. IM_ASSERT(bd_baked_data != nullptr);
  378. IM_PLACEMENT_NEW(bd_baked_data) ImGui_ImplFreeType_FontSrcBakedData();
  379. FT_New_Size(bd_font_data->FtFace, &bd_baked_data->FtSize);
  380. FT_Activate_Size(bd_baked_data->FtSize);
  381. // 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'
  382. // 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.
  383. // FT_Set_Pixel_Sizes() doesn't seem to get us the same result."
  384. // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL)
  385. const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity;
  386. FT_Size_RequestRec req;
  387. req.type = (bd_font_data->UserFlags & ImGuiFreeTypeLoaderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM;
  388. req.width = 0;
  389. req.height = (uint32_t)(size * 64 * rasterizer_density);
  390. req.horiResolution = 0;
  391. req.vertResolution = 0;
  392. FT_Request_Size(bd_font_data->FtFace, &req);
  393. // Output
  394. if (src->MergeMode == false)
  395. {
  396. // Read metrics
  397. FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics;
  398. const float scale = 1.0f / (rasterizer_density * src->ExtraSizeScale);
  399. baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive).
  400. baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative).
  401. //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.
  402. //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.
  403. //MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * scale; // This field gives the maximum horizontal cursor advance for all glyphs in the font.
  404. }
  405. return true;
  406. }
  407. static void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src)
  408. {
  409. IM_UNUSED(atlas);
  410. IM_UNUSED(baked);
  411. IM_UNUSED(src);
  412. ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src;
  413. IM_ASSERT(bd_baked_data != nullptr);
  414. FT_Done_Size(bd_baked_data->FtSize);
  415. bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE()
  416. }
  417. static 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)
  418. {
  419. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  420. uint32_t glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint);
  421. if (glyph_index == 0)
  422. return false;
  423. if (bd_font_data->BakedLastActivated != baked) // <-- could use id
  424. {
  425. // Activate current size
  426. ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src;
  427. FT_Activate_Size(bd_baked_data->FtSize);
  428. bd_font_data->BakedLastActivated = baked;
  429. }
  430. const FT_Glyph_Metrics* metrics = ImGui_ImplFreeType_LoadGlyph(bd_font_data, codepoint);
  431. if (metrics == nullptr)
  432. return false;
  433. FT_Face face = bd_font_data->FtFace;
  434. FT_GlyphSlot slot = face->glyph;
  435. const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity;
  436. // Load metrics only mode
  437. const float advance_x = (slot->advance.x / FT_SCALEFACTOR) / rasterizer_density;
  438. if (out_advance_x != NULL)
  439. {
  440. IM_ASSERT(out_glyph == NULL);
  441. *out_advance_x = advance_x;
  442. return true;
  443. }
  444. // Render glyph into a bitmap (currently held by FreeType)
  445. FT_Render_Mode render_mode = (bd_font_data->UserFlags & ImGuiFreeTypeLoaderFlags_Monochrome) ? FT_RENDER_MODE_MONO : FT_RENDER_MODE_NORMAL;
  446. FT_Error error = FT_Render_Glyph(slot, render_mode);
  447. const FT_Bitmap* ft_bitmap = &slot->bitmap;
  448. if (error != 0 || ft_bitmap == nullptr)
  449. return false;
  450. const int w = (int)ft_bitmap->width;
  451. const int h = (int)ft_bitmap->rows;
  452. const bool is_visible = (w != 0 && h != 0);
  453. // Prepare glyph
  454. out_glyph->Codepoint = codepoint;
  455. out_glyph->AdvanceX = advance_x;
  456. // Pack and retrieve position inside texture atlas
  457. if (is_visible)
  458. {
  459. ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h);
  460. if (pack_id == ImFontAtlasRectId_Invalid)
  461. {
  462. // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?)
  463. IM_ASSERT(pack_id != ImFontAtlasRectId_Invalid && "Out of texture memory.");
  464. return false;
  465. }
  466. ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id);
  467. // Render pixels to our temporary buffer
  468. atlas->Builder->TempBuffer.resize(w * h * 4);
  469. uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data;
  470. ImGui_ImplFreeType_BlitGlyph(ft_bitmap, temp_buffer, w);
  471. const float ref_size = baked->OwnerFont->Sources[0]->SizePixels;
  472. const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f;
  473. float font_off_x = ImFloor(src->GlyphOffset.x * offsets_scale + 0.5f); // Snap scaled offset.
  474. float font_off_y = ImFloor(src->GlyphOffset.y * offsets_scale + 0.5f) + baked->Ascent;
  475. float recip_h = 1.0f / rasterizer_density;
  476. float recip_v = 1.0f / rasterizer_density;
  477. // Register glyph
  478. float glyph_off_x = (float)face->glyph->bitmap_left;
  479. float glyph_off_y = (float)-face->glyph->bitmap_top;
  480. out_glyph->X0 = glyph_off_x * recip_h + font_off_x;
  481. out_glyph->Y0 = glyph_off_y * recip_v + font_off_y;
  482. out_glyph->X1 = (glyph_off_x + w) * recip_h + font_off_x;
  483. out_glyph->Y1 = (glyph_off_y + h) * recip_v + font_off_y;
  484. out_glyph->Visible = true;
  485. out_glyph->Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA);
  486. out_glyph->PackId = pack_id;
  487. ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, out_glyph, r, (const unsigned char*)temp_buffer, ImTextureFormat_RGBA32, w * 4);
  488. }
  489. return true;
  490. }
  491. static bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint)
  492. {
  493. IM_UNUSED(atlas);
  494. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  495. int glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint);
  496. return glyph_index != 0;
  497. }
  498. const ImFontLoader* ImGuiFreeType::GetFontLoader()
  499. {
  500. static ImFontLoader loader;
  501. loader.Name = "FreeType";
  502. loader.LoaderInit = ImGui_ImplFreeType_LoaderInit;
  503. loader.LoaderShutdown = ImGui_ImplFreeType_LoaderShutdown;
  504. loader.FontSrcInit = ImGui_ImplFreeType_FontSrcInit;
  505. loader.FontSrcDestroy = ImGui_ImplFreeType_FontSrcDestroy;
  506. loader.FontSrcContainsGlyph = ImGui_ImplFreetype_FontSrcContainsGlyph;
  507. loader.FontBakedInit = ImGui_ImplFreeType_FontBakedInit;
  508. loader.FontBakedDestroy = ImGui_ImplFreeType_FontBakedDestroy;
  509. loader.FontBakedLoadGlyph = ImGui_ImplFreeType_FontBakedLoadGlyph;
  510. loader.FontBakedSrcLoaderDataSize = sizeof(ImGui_ImplFreeType_FontSrcBakedData);
  511. return &loader;
  512. }
  513. void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
  514. {
  515. GImGuiFreeTypeAllocFunc = alloc_func;
  516. GImGuiFreeTypeFreeFunc = free_func;
  517. GImGuiFreeTypeAllocatorUserData = user_data;
  518. }
  519. bool ImGuiFreeType::DebugEditFontLoaderFlags(unsigned int* p_font_loader_flags)
  520. {
  521. bool edited = false;
  522. edited |= ImGui::CheckboxFlags("NoHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_NoHinting);
  523. edited |= ImGui::CheckboxFlags("NoAutoHint", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_NoAutoHint);
  524. edited |= ImGui::CheckboxFlags("ForceAutoHint",p_font_loader_flags, ImGuiFreeTypeLoaderFlags_ForceAutoHint);
  525. edited |= ImGui::CheckboxFlags("LightHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_LightHinting);
  526. edited |= ImGui::CheckboxFlags("MonoHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_MonoHinting);
  527. edited |= ImGui::CheckboxFlags("Bold", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Bold);
  528. edited |= ImGui::CheckboxFlags("Oblique", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Oblique);
  529. edited |= ImGui::CheckboxFlags("Monochrome", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Monochrome);
  530. edited |= ImGui::CheckboxFlags("LoadColor", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_LoadColor);
  531. edited |= ImGui::CheckboxFlags("Bitmap", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Bitmap);
  532. return edited;
  533. }
  534. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  535. // For more details, see https://gitlab.freedesktop.org/freetype/freetype-demos/-/blob/master/src/rsvg-port.c
  536. // 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)
  537. struct LunasvgPortState
  538. {
  539. FT_Error err = FT_Err_Ok;
  540. lunasvg::Matrix matrix;
  541. std::unique_ptr<lunasvg::Document> svg = nullptr;
  542. };
  543. static FT_Error ImGuiLunasvgPortInit(FT_Pointer* _state)
  544. {
  545. *_state = IM_NEW(LunasvgPortState)();
  546. return FT_Err_Ok;
  547. }
  548. static void ImGuiLunasvgPortFree(FT_Pointer* _state)
  549. {
  550. IM_DELETE(*(LunasvgPortState**)_state);
  551. }
  552. static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state)
  553. {
  554. LunasvgPortState* state = *(LunasvgPortState**)_state;
  555. // If there was an error while loading the svg in ImGuiLunasvgPortPresetSlot(), the renderer hook still get called, so just returns the error.
  556. if (state->err != FT_Err_Ok)
  557. return state->err;
  558. // rows is height, pitch (or stride) equals to width * sizeof(int32)
  559. lunasvg::Bitmap bitmap((uint8_t*)slot->bitmap.buffer, slot->bitmap.width, slot->bitmap.rows, slot->bitmap.pitch);
  560. #if LUNASVG_VERSION_MAJOR >= 3
  561. state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated
  562. #else
  563. state->svg->setMatrix(state->svg->matrix().identity()); // Reset the svg matrix to the default value
  564. state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated
  565. #endif
  566. state->err = FT_Err_Ok;
  567. return state->err;
  568. }
  569. static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_Pointer* _state)
  570. {
  571. FT_SVG_Document document = (FT_SVG_Document)slot->other;
  572. LunasvgPortState* state = *(LunasvgPortState**)_state;
  573. FT_Size_Metrics& metrics = document->metrics;
  574. // This function is called twice, once in the FT_Load_Glyph() and another right before ImGuiLunasvgPortRender().
  575. // If it's the latter, don't do anything because it's // already done in the former.
  576. if (cache)
  577. return state->err;
  578. state->svg = lunasvg::Document::loadFromData((const char*)document->svg_document, document->svg_document_length);
  579. if (state->svg == nullptr)
  580. {
  581. state->err = FT_Err_Invalid_SVG_Document;
  582. return state->err;
  583. }
  584. #if LUNASVG_VERSION_MAJOR >= 3
  585. lunasvg::Box box = state->svg->boundingBox();
  586. #else
  587. lunasvg::Box box = state->svg->box();
  588. #endif
  589. double scale = std::min(metrics.x_ppem / box.w, metrics.y_ppem / box.h);
  590. double xx = (double)document->transform.xx / (1 << 16);
  591. double xy = -(double)document->transform.xy / (1 << 16);
  592. double yx = -(double)document->transform.yx / (1 << 16);
  593. double yy = (double)document->transform.yy / (1 << 16);
  594. double x0 = (double)document->delta.x / 64 * box.w / metrics.x_ppem;
  595. double y0 = -(double)document->delta.y / 64 * box.h / metrics.y_ppem;
  596. #if LUNASVG_VERSION_MAJOR >= 3
  597. // Scale, transform and pre-translate the matrix for the rendering step
  598. state->matrix = lunasvg::Matrix::translated(-box.x, -box.y);
  599. state->matrix.multiply(lunasvg::Matrix(xx, xy, yx, yy, x0, y0));
  600. state->matrix.scale(scale, scale);
  601. // Apply updated transformation to the bounding box
  602. box.transform(state->matrix);
  603. #else
  604. // Scale and transform, we don't translate the svg yet
  605. state->matrix.identity();
  606. state->matrix.scale(scale, scale);
  607. state->matrix.transform(xx, xy, yx, yy, x0, y0);
  608. state->svg->setMatrix(state->matrix);
  609. // Pre-translate the matrix for the rendering step
  610. state->matrix.translate(-box.x, -box.y);
  611. // Get the box again after the transformation
  612. box = state->svg->box();
  613. #endif
  614. // Calculate the bitmap size
  615. slot->bitmap_left = FT_Int(box.x);
  616. slot->bitmap_top = FT_Int(-box.y);
  617. slot->bitmap.rows = (unsigned int)(ImCeil((float)box.h));
  618. slot->bitmap.width = (unsigned int)(ImCeil((float)box.w));
  619. slot->bitmap.pitch = slot->bitmap.width * 4;
  620. slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
  621. // Compute all the bearings and set them correctly. The outline is scaled already, we just need to use the bounding box.
  622. double metrics_width = box.w;
  623. double metrics_height = box.h;
  624. double horiBearingX = box.x;
  625. double horiBearingY = -box.y;
  626. double vertBearingX = slot->metrics.horiBearingX / 64.0 - slot->metrics.horiAdvance / 64.0 / 2.0;
  627. double vertBearingY = (slot->metrics.vertAdvance / 64.0 - slot->metrics.height / 64.0) / 2.0;
  628. slot->metrics.width = FT_Pos(IM_ROUND(metrics_width * 64.0)); // Using IM_ROUND() assume width and height are positive
  629. slot->metrics.height = FT_Pos(IM_ROUND(metrics_height * 64.0));
  630. slot->metrics.horiBearingX = FT_Pos(horiBearingX * 64);
  631. slot->metrics.horiBearingY = FT_Pos(horiBearingY * 64);
  632. slot->metrics.vertBearingX = FT_Pos(vertBearingX * 64);
  633. slot->metrics.vertBearingY = FT_Pos(vertBearingY * 64);
  634. if (slot->metrics.vertAdvance == 0)
  635. slot->metrics.vertAdvance = FT_Pos(metrics_height * 1.2 * 64.0);
  636. state->err = FT_Err_Ok;
  637. return state->err;
  638. }
  639. #endif // #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  640. //-----------------------------------------------------------------------------
  641. #ifdef __GNUC__
  642. #pragma GCC diagnostic pop
  643. #endif
  644. #ifdef _MSC_VER
  645. #pragma warning (pop)
  646. #endif
  647. #endif // #ifndef IMGUI_DISABLE