imgui_freetype.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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/XX/XX: 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_SYNTHESIS_H // <freetype/ftsynth.h>
  45. // Handle LunaSVG and PlutoSVG
  46. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) && defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  47. #error "Cannot enable both IMGUI_ENABLE_FREETYPE_LUNASVG and IMGUI_ENABLE_FREETYPE_PLUTOSVG"
  48. #endif
  49. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  50. #include FT_OTSVG_H // <freetype/otsvg.h>
  51. #include FT_BBOX_H // <freetype/ftbbox.h>
  52. #include <lunasvg.h>
  53. #endif
  54. #ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG
  55. #include <plutosvg.h>
  56. #endif
  57. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined (IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  58. #if !((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
  59. #error IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG requires FreeType version >= 2.12
  60. #endif
  61. #endif
  62. #ifdef _MSC_VER
  63. #pragma warning (push)
  64. #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
  65. #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
  66. #endif
  67. #ifdef __GNUC__
  68. #pragma GCC diagnostic push
  69. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
  70. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  71. #ifndef __clang__
  72. #pragma GCC diagnostic ignored "-Wsubobject-linkage" // warning: 'xxxx' has a field 'xxxx' whose type uses the anonymous namespace
  73. #endif
  74. #endif
  75. //-------------------------------------------------------------------------
  76. // Data
  77. //-------------------------------------------------------------------------
  78. // Default memory allocators
  79. static void* ImGuiFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); }
  80. static void ImGuiFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); }
  81. // Current memory allocators
  82. static void* (*GImGuiFreeTypeAllocFunc)(size_t size, void* user_data) = ImGuiFreeTypeDefaultAllocFunc;
  83. static void (*GImGuiFreeTypeFreeFunc)(void* ptr, void* user_data) = ImGuiFreeTypeDefaultFreeFunc;
  84. static void* GImGuiFreeTypeAllocatorUserData = nullptr;
  85. // Lunasvg support
  86. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  87. static FT_Error ImGuiLunasvgPortInit(FT_Pointer* state);
  88. static void ImGuiLunasvgPortFree(FT_Pointer* state);
  89. static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state);
  90. static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_Pointer* _state);
  91. #endif
  92. //-------------------------------------------------------------------------
  93. // Code
  94. //-------------------------------------------------------------------------
  95. #define FT_CEIL(X) (((X + 63) & -64) / 64) // From SDL_ttf: Handy routines for converting from fixed point
  96. #define FT_SCALEFACTOR 64.0f
  97. namespace
  98. {
  99. // Glyph metrics:
  100. // --------------
  101. //
  102. // xmin xmax
  103. // | |
  104. // |<-------- width -------->|
  105. // | |
  106. // | +-------------------------+----------------- ymax
  107. // | | ggggggggg ggggg | ^ ^
  108. // | | g:::::::::ggg::::g | | |
  109. // | | g:::::::::::::::::g | | |
  110. // | | g::::::ggggg::::::gg | | |
  111. // | | g:::::g g:::::g | | |
  112. // offsetX -|-------->| g:::::g g:::::g | offsetY |
  113. // | | g:::::g g:::::g | | |
  114. // | | g::::::g g:::::g | | |
  115. // | | g:::::::ggggg:::::g | | |
  116. // | | g::::::::::::::::g | | height
  117. // | | gg::::::::::::::g | | |
  118. // baseline ---*---------|---- gggggggg::::::g-----*-------- |
  119. // / | | g:::::g | |
  120. // origin | | gggggg g:::::g | |
  121. // | | g:::::gg gg:::::g | |
  122. // | | g::::::ggg:::::::g | |
  123. // | | gg:::::::::::::g | |
  124. // | | ggg::::::ggg | |
  125. // | | gggggg | v
  126. // | +-------------------------+----------------- ymin
  127. // | |
  128. // |------------- advanceX ----------->|
  129. // A structure that describe a glyph.
  130. struct GlyphInfo
  131. {
  132. int Width; // Glyph's width in pixels.
  133. int Height; // Glyph's height in pixels.
  134. FT_Int OffsetX; // The distance from the origin ("pen position") to the left of the glyph.
  135. FT_Int OffsetY; // The distance from the origin to the top of the glyph. This is usually a value < 0.
  136. float AdvanceX; // The distance from the origin to the origin of the next glyph. This is usually a value > 0.
  137. bool IsColored; // The glyph is colored
  138. };
  139. // Stored in ImFontAtlas::FontLoaderData
  140. struct ImGui_ImplFreeType_Data
  141. {
  142. FT_Library Library;
  143. FT_MemoryRec_ MemoryManager;
  144. ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); }
  145. };
  146. // Font parameters and metrics.
  147. struct ImGui_ImplFreeType_FontInfo
  148. {
  149. float PixelHeight; // Size this font was generated with.
  150. float Ascender; // The pixel extents above the baseline in pixels (typically positive).
  151. float Descender; // The extents below the baseline in pixels (typically negative).
  152. 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.
  153. float LineGap; // The spacing in pixels between one row's descent and the next row's ascent.
  154. float MaxAdvanceWidth; // This field gives the maximum horizontal cursor advance for all glyphs in the font.
  155. };
  156. // Stored in ImFontConfig::FontLoaderData
  157. struct ImGui_ImplFreeType_FontSrcData
  158. {
  159. bool InitFont(FT_Library ft_library, 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.
  160. void CloseFont();
  161. void SetPixelHeight(float pixel_height); // Change font pixel size.
  162. const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint);
  163. const FT_Bitmap* RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info);
  164. void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = nullptr);
  165. ImGui_ImplFreeType_FontSrcData() { memset((void*)this, 0, sizeof(*this)); }
  166. ~ImGui_ImplFreeType_FontSrcData() { CloseFont(); }
  167. // Members
  168. ImGui_ImplFreeType_FontInfo Info; // Font descriptor of the current font.
  169. FT_Face FtFace;
  170. unsigned int UserFlags; // = ImFontConfig::RasterizerFlags
  171. FT_Int32 LoadFlags;
  172. FT_Render_Mode RenderMode;
  173. float RasterizationDensity;
  174. float InvRasterizationDensity;
  175. };
  176. bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, unsigned int extra_font_builder_flags)
  177. {
  178. FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (uint32_t)src->FontDataSize, (uint32_t)src->FontNo, &FtFace);
  179. if (error != 0)
  180. return false;
  181. error = FT_Select_Charmap(FtFace, FT_ENCODING_UNICODE);
  182. if (error != 0)
  183. return false;
  184. // Convert to FreeType flags (NB: Bold and Oblique are processed separately)
  185. UserFlags = src->FontBuilderFlags | extra_font_builder_flags;
  186. LoadFlags = 0;
  187. if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0)
  188. LoadFlags |= FT_LOAD_NO_BITMAP;
  189. if (UserFlags & ImGuiFreeTypeBuilderFlags_NoHinting)
  190. LoadFlags |= FT_LOAD_NO_HINTING;
  191. if (UserFlags & ImGuiFreeTypeBuilderFlags_NoAutoHint)
  192. LoadFlags |= FT_LOAD_NO_AUTOHINT;
  193. if (UserFlags & ImGuiFreeTypeBuilderFlags_ForceAutoHint)
  194. LoadFlags |= FT_LOAD_FORCE_AUTOHINT;
  195. if (UserFlags & ImGuiFreeTypeBuilderFlags_LightHinting)
  196. LoadFlags |= FT_LOAD_TARGET_LIGHT;
  197. else if (UserFlags & ImGuiFreeTypeBuilderFlags_MonoHinting)
  198. LoadFlags |= FT_LOAD_TARGET_MONO;
  199. else
  200. LoadFlags |= FT_LOAD_TARGET_NORMAL;
  201. if (UserFlags & ImGuiFreeTypeBuilderFlags_Monochrome)
  202. RenderMode = FT_RENDER_MODE_MONO;
  203. else
  204. RenderMode = FT_RENDER_MODE_NORMAL;
  205. if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor)
  206. LoadFlags |= FT_LOAD_COLOR;
  207. RasterizationDensity = src->RasterizerDensity;
  208. InvRasterizationDensity = 1.0f / RasterizationDensity;
  209. memset(&Info, 0, sizeof(Info));
  210. SetPixelHeight(src->SizePixels);
  211. return true;
  212. }
  213. void ImGui_ImplFreeType_FontSrcData::CloseFont()
  214. {
  215. if (FtFace)
  216. {
  217. FT_Done_Face(FtFace);
  218. FtFace = nullptr;
  219. }
  220. }
  221. void ImGui_ImplFreeType_FontSrcData::SetPixelHeight(float pixel_height)
  222. {
  223. // 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'
  224. // 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.
  225. // FT_Set_Pixel_Sizes() doesn't seem to get us the same result."
  226. // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL)
  227. FT_Size_RequestRec req;
  228. req.type = (UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM;
  229. req.width = 0;
  230. req.height = (uint32_t)(pixel_height * 64 * RasterizationDensity);
  231. req.horiResolution = 0;
  232. req.vertResolution = 0;
  233. FT_Request_Size(FtFace, &req);
  234. // Note: To handle multiple sizes later, we may need to use FT_New_Size(), FT_Activate_Size()
  235. // Update font info
  236. FT_Size_Metrics metrics = FtFace->size->metrics;
  237. Info.PixelHeight = pixel_height * InvRasterizationDensity;
  238. Info.Ascender = (float)FT_CEIL(metrics.ascender) * InvRasterizationDensity;
  239. Info.Descender = (float)FT_CEIL(metrics.descender) * InvRasterizationDensity;
  240. Info.LineSpacing = (float)FT_CEIL(metrics.height) * InvRasterizationDensity;
  241. Info.LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * InvRasterizationDensity;
  242. Info.MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * InvRasterizationDensity;
  243. }
  244. const FT_Glyph_Metrics* ImGui_ImplFreeType_FontSrcData::LoadGlyph(uint32_t codepoint)
  245. {
  246. uint32_t glyph_index = FT_Get_Char_Index(FtFace, codepoint);
  247. if (glyph_index == 0)
  248. return nullptr;
  249. // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts.
  250. // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076
  251. // - https://github.com/ocornut/imgui/issues/4567
  252. // - https://github.com/ocornut/imgui/issues/4566
  253. // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version.
  254. FT_Error error = FT_Load_Glyph(FtFace, glyph_index, LoadFlags);
  255. if (error)
  256. return nullptr;
  257. // Need an outline for this to work
  258. FT_GlyphSlot slot = FtFace->glyph;
  259. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  260. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG);
  261. #else
  262. #if ((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
  263. 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");
  264. #endif
  265. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP);
  266. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  267. // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting)
  268. if (UserFlags & ImGuiFreeTypeBuilderFlags_Bold)
  269. FT_GlyphSlot_Embolden(slot);
  270. if (UserFlags & ImGuiFreeTypeBuilderFlags_Oblique)
  271. {
  272. FT_GlyphSlot_Oblique(slot);
  273. //FT_BBox bbox;
  274. //FT_Outline_Get_BBox(&slot->outline, &bbox);
  275. //slot->metrics.width = bbox.xMax - bbox.xMin;
  276. //slot->metrics.height = bbox.yMax - bbox.yMin;
  277. }
  278. return &slot->metrics;
  279. }
  280. const FT_Bitmap* ImGui_ImplFreeType_FontSrcData::RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info)
  281. {
  282. FT_GlyphSlot slot = FtFace->glyph;
  283. FT_Error error = FT_Render_Glyph(slot, RenderMode);
  284. if (error != 0)
  285. return nullptr;
  286. FT_Bitmap* ft_bitmap = &FtFace->glyph->bitmap;
  287. out_glyph_info->Width = (int)ft_bitmap->width;
  288. out_glyph_info->Height = (int)ft_bitmap->rows;
  289. out_glyph_info->OffsetX = FtFace->glyph->bitmap_left;
  290. out_glyph_info->OffsetY = -FtFace->glyph->bitmap_top;
  291. out_glyph_info->AdvanceX = (float)slot->advance.x / FT_SCALEFACTOR;
  292. out_glyph_info->IsColored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA);
  293. return ft_bitmap;
  294. }
  295. void ImGui_ImplFreeType_FontSrcData::BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table)
  296. {
  297. IM_ASSERT(ft_bitmap != nullptr);
  298. const uint32_t w = ft_bitmap->width;
  299. const uint32_t h = ft_bitmap->rows;
  300. const uint8_t* src = ft_bitmap->buffer;
  301. const uint32_t src_pitch = ft_bitmap->pitch;
  302. switch (ft_bitmap->pixel_mode)
  303. {
  304. case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel.
  305. {
  306. if (multiply_table == nullptr)
  307. {
  308. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  309. for (uint32_t x = 0; x < w; x++)
  310. dst[x] = IM_COL32(255, 255, 255, src[x]);
  311. }
  312. else
  313. {
  314. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  315. for (uint32_t x = 0; x < w; x++)
  316. dst[x] = IM_COL32(255, 255, 255, multiply_table[src[x]]);
  317. }
  318. break;
  319. }
  320. case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB.
  321. {
  322. uint8_t color0 = multiply_table ? multiply_table[0] : 0;
  323. uint8_t color1 = multiply_table ? multiply_table[255] : 255;
  324. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  325. {
  326. uint8_t bits = 0;
  327. const uint8_t* bits_ptr = src;
  328. for (uint32_t x = 0; x < w; x++, bits <<= 1)
  329. {
  330. if ((x & 7) == 0)
  331. bits = *bits_ptr++;
  332. dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? color1 : color0);
  333. }
  334. }
  335. break;
  336. }
  337. case FT_PIXEL_MODE_BGRA:
  338. {
  339. // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good.
  340. #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u)
  341. if (multiply_table == nullptr)
  342. {
  343. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  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(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a);
  348. }
  349. }
  350. else
  351. {
  352. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  353. {
  354. for (uint32_t x = 0; x < w; x++)
  355. {
  356. uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3];
  357. 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]);
  358. }
  359. }
  360. }
  361. #undef DE_MULTIPLY
  362. break;
  363. }
  364. default:
  365. IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!");
  366. }
  367. }
  368. } // namespace
  369. #if 0
  370. #ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
  371. #ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
  372. #define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0)
  373. #define STBRP_STATIC
  374. #define STB_RECT_PACK_IMPLEMENTATION
  375. #endif
  376. #ifdef IMGUI_STB_RECT_PACK_FILENAME
  377. #include IMGUI_STB_RECT_PACK_FILENAME
  378. #else
  379. #include "imstb_rectpack.h"
  380. #endif
  381. #endif
  382. struct ImFontBuildSrcGlyphFT
  383. {
  384. GlyphInfo Info;
  385. uint32_t Codepoint;
  386. unsigned int* BitmapData; // Point within one of the dst_tmp_bitmap_buffers[] array
  387. ImFontBuildSrcGlyphFT() { memset((void*)this, 0, sizeof(*this)); }
  388. };
  389. struct ImFontBuildSrcDataFT
  390. {
  391. FreeTypeFont Font;
  392. stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position.
  393. const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF)
  394. int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[]
  395. int GlyphsHighest; // Highest requested codepoint
  396. int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font)
  397. ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB)
  398. ImVector<ImFontBuildSrcGlyphFT> GlyphsList;
  399. };
  400. // Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont)
  401. struct ImFontBuildDstDataFT
  402. {
  403. int SrcCount; // Number of source fonts targeting this destination font.
  404. int GlyphsHighest;
  405. int GlyphsCount;
  406. ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font.
  407. };
  408. bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, unsigned int extra_flags)
  409. {
  410. IM_ASSERT(atlas->Sources.Size > 0);
  411. ImFontAtlasBuildInit(atlas);
  412. // Clear atlas
  413. atlas->TexID._TexID = 0;
  414. atlas->TexWidth = atlas->TexHeight = 0;
  415. atlas->TexUvScale = ImVec2(0.0f, 0.0f);
  416. atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
  417. atlas->ClearTexData();
  418. // Temporary storage for building
  419. bool src_load_color = false;
  420. ImVector<ImFontBuildSrcDataFT> src_tmp_array;
  421. ImVector<ImFontBuildDstDataFT> dst_tmp_array;
  422. src_tmp_array.resize(atlas->Sources.Size);
  423. dst_tmp_array.resize(atlas->Fonts.Size);
  424. memset((void*)src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes());
  425. memset((void*)dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes());
  426. // 1. Initialize font loading structure, check font data validity
  427. for (int src_i = 0; src_i < atlas->Sources.Size; src_i++)
  428. {
  429. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  430. ImFontConfig& src = atlas->Sources[src_i];
  431. FreeTypeFont& font_face = src_tmp.Font;
  432. IM_ASSERT(src.DstFont && (!src.DstFont->IsLoaded() || src.DstFont->ContainerAtlas == atlas));
  433. // Find index from src.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices)
  434. src_tmp.DstIndex = -1;
  435. for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++)
  436. if (src.DstFont == atlas->Fonts[output_i])
  437. src_tmp.DstIndex = output_i;
  438. IM_ASSERT(src_tmp.DstIndex != -1); // src.DstFont not pointing within atlas->Fonts[] array?
  439. if (src_tmp.DstIndex == -1)
  440. return false;
  441. // Load font
  442. if (!font_face.InitFont(ft_library, src, extra_flags))
  443. return false;
  444. // Measure highest codepoints
  445. src_load_color |= (src.FontBuilderFlags & ImGuiFreeTypeBuilderFlags_LoadColor) != 0;
  446. ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
  447. src_tmp.SrcRanges = src.GlyphRanges ? src.GlyphRanges : atlas->GetGlyphRangesDefault();
  448. for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
  449. {
  450. // Check for valid range. This may also help detect *some* dangling pointers, because a common
  451. // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent,
  452. // or to forget to zero-terminate the glyph range array.
  453. IM_ASSERT(src_range[0] <= src_range[1] && "Invalid range: is your glyph range array persistent? it is zero-terminated?");
  454. src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]);
  455. }
  456. dst_tmp.SrcCount++;
  457. dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest);
  458. }
  459. // 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.
  460. int total_glyphs_count = 0;
  461. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  462. {
  463. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  464. ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
  465. src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1);
  466. if (dst_tmp.GlyphsSet.Storage.empty())
  467. dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1);
  468. for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
  469. for (int codepoint = src_range[0]; codepoint <= (int)src_range[1]; codepoint++)
  470. {
  471. if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite)
  472. continue;
  473. 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..)
  474. if (glyph_index == 0)
  475. continue;
  476. // Add to avail set/counters
  477. src_tmp.GlyphsCount++;
  478. dst_tmp.GlyphsCount++;
  479. src_tmp.GlyphsSet.SetBit(codepoint);
  480. dst_tmp.GlyphsSet.SetBit(codepoint);
  481. total_glyphs_count++;
  482. }
  483. }
  484. // 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)
  485. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  486. {
  487. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  488. src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount);
  489. IM_ASSERT(sizeof(src_tmp.GlyphsSet.Storage.Data[0]) == sizeof(ImU32));
  490. const ImU32* it_begin = src_tmp.GlyphsSet.Storage.begin();
  491. const ImU32* it_end = src_tmp.GlyphsSet.Storage.end();
  492. for (const ImU32* it = it_begin; it < it_end; it++)
  493. if (ImU32 entries_32 = *it)
  494. for (ImU32 bit_n = 0; bit_n < 32; bit_n++)
  495. if (entries_32 & ((ImU32)1 << bit_n))
  496. {
  497. ImFontBuildSrcGlyphFT src_glyph;
  498. src_glyph.Codepoint = (ImWchar)(((it - it_begin) << 5) + bit_n);
  499. //src_glyph.GlyphIndex = 0; // FIXME-OPT: We had this info in the previous step and lost it..
  500. src_tmp.GlyphsList.push_back(src_glyph);
  501. }
  502. src_tmp.GlyphsSet.Clear();
  503. IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount);
  504. }
  505. for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++)
  506. dst_tmp_array[dst_i].GlyphsSet.Clear();
  507. dst_tmp_array.clear();
  508. // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)
  509. // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity)
  510. ImVector<stbrp_rect> buf_rects;
  511. buf_rects.resize(total_glyphs_count);
  512. memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes());
  513. // Allocate temporary rasterization data buffers.
  514. // We could not find a way to retrieve accurate glyph size without rendering them.
  515. // (e.g. slot->metrics->width not always matching bitmap->width, especially considering the Oblique transform)
  516. // 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.
  517. const int BITMAP_BUFFERS_CHUNK_SIZE = 256 * 1024;
  518. int buf_bitmap_current_used_bytes = 0;
  519. ImVector<unsigned char*> buf_bitmap_buffers;
  520. buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
  521. // 4. Gather glyphs sizes so we can pack them in our virtual canvas.
  522. // 8. Render/rasterize font characters into the texture
  523. int total_surface = 0;
  524. int buf_rects_out_n = 0;
  525. const int pack_padding = atlas->TexGlyphPadding;
  526. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  527. {
  528. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  529. ImFontConfig& src = atlas->Sources[src_i];
  530. if (src_tmp.GlyphsCount == 0)
  531. continue;
  532. src_tmp.Rects = &buf_rects[buf_rects_out_n];
  533. buf_rects_out_n += src_tmp.GlyphsCount;
  534. // Compute multiply table if requested
  535. const bool multiply_enabled = (src.RasterizerMultiply != 1.0f);
  536. unsigned char multiply_table[256];
  537. if (multiply_enabled)
  538. ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, src.RasterizerMultiply);
  539. // Gather the sizes of all rectangles we will need to pack
  540. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)
  541. {
  542. ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
  543. const FT_Glyph_Metrics* metrics = src_tmp.Font.LoadGlyph(src_glyph.Codepoint);
  544. if (metrics == nullptr)
  545. continue;
  546. // Render glyph into a bitmap (currently held by FreeType)
  547. const FT_Bitmap* ft_bitmap = src_tmp.Font.RenderGlyphAndGetInfo(&src_glyph.Info);
  548. if (ft_bitmap == nullptr)
  549. continue;
  550. // Allocate new temporary chunk if needed
  551. const int bitmap_size_in_bytes = src_glyph.Info.Width * src_glyph.Info.Height * 4;
  552. if (buf_bitmap_current_used_bytes + bitmap_size_in_bytes > BITMAP_BUFFERS_CHUNK_SIZE)
  553. {
  554. buf_bitmap_current_used_bytes = 0;
  555. buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
  556. }
  557. IM_ASSERT(buf_bitmap_current_used_bytes + bitmap_size_in_bytes <= BITMAP_BUFFERS_CHUNK_SIZE); // We could probably allocate custom-sized buffer instead.
  558. // Blit rasterized pixels to our temporary buffer and keep a pointer to it.
  559. src_glyph.BitmapData = (unsigned int*)(buf_bitmap_buffers.back() + buf_bitmap_current_used_bytes);
  560. buf_bitmap_current_used_bytes += bitmap_size_in_bytes;
  561. src_tmp.Font.BlitGlyph(ft_bitmap, src_glyph.BitmapData, src_glyph.Info.Width, multiply_enabled ? multiply_table : nullptr);
  562. src_tmp.Rects[glyph_i].w = (stbrp_coord)(src_glyph.Info.Width + pack_padding);
  563. src_tmp.Rects[glyph_i].h = (stbrp_coord)(src_glyph.Info.Height + pack_padding);
  564. total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;
  565. }
  566. }
  567. for (int i = 0; i < atlas->CustomRects.Size; i++)
  568. total_surface += (atlas->CustomRects[i].Width + pack_padding) * (atlas->CustomRects[i].Height + pack_padding);
  569. // We need a width for the skyline algorithm, any width!
  570. // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
  571. // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface.
  572. const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1;
  573. atlas->TexHeight = 0;
  574. if (atlas->TexDesiredWidth > 0)
  575. atlas->TexWidth = atlas->TexDesiredWidth;
  576. else
  577. atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512;
  578. // 5. Start packing
  579. // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
  580. const int TEX_HEIGHT_MAX = 1024 * 32;
  581. const int num_nodes_for_packing_algorithm = atlas->TexWidth - atlas->TexGlyphPadding;
  582. ImVector<stbrp_node> pack_nodes;
  583. pack_nodes.resize(num_nodes_for_packing_algorithm);
  584. stbrp_context pack_context;
  585. stbrp_init_target(&pack_context, atlas->TexWidth - atlas->TexGlyphPadding, TEX_HEIGHT_MAX - atlas->TexGlyphPadding, pack_nodes.Data, pack_nodes.Size);
  586. ImFontAtlasBuildPackCustomRects(atlas, &pack_context);
  587. // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point.
  588. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  589. {
  590. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  591. if (src_tmp.GlyphsCount == 0)
  592. continue;
  593. stbrp_pack_rects(&pack_context, src_tmp.Rects, src_tmp.GlyphsCount);
  594. // Extend texture height and mark missing glyphs as non-packed so we won't render them.
  595. // 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?)
  596. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
  597. if (src_tmp.Rects[glyph_i].was_packed)
  598. atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h);
  599. }
  600. // 7. Allocate texture
  601. atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight);
  602. atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
  603. if (src_load_color)
  604. {
  605. size_t tex_size = (size_t)atlas->TexWidth * atlas->TexHeight * 4;
  606. atlas->TexPixelsRGBA32 = (unsigned int*)IM_ALLOC(tex_size);
  607. memset(atlas->TexPixelsRGBA32, 0, tex_size);
  608. }
  609. else
  610. {
  611. size_t tex_size = (size_t)atlas->TexWidth * atlas->TexHeight * 1;
  612. atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(tex_size);
  613. memset(atlas->TexPixelsAlpha8, 0, tex_size);
  614. }
  615. // 8. Copy rasterized font characters back into the main texture
  616. // 9. Setup ImFont and glyphs for runtime
  617. bool tex_use_colors = false;
  618. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  619. {
  620. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  621. // When merging fonts with MergeMode=true:
  622. // - We can have multiple input fonts writing into a same destination font.
  623. // - dst_font->Sources is != from src which is our source configuration.
  624. ImFontConfig& src = atlas->Sources[src_i];
  625. ImFont* dst_font = src.DstFont;
  626. const float ascent = src_tmp.Font.Info.Ascender;
  627. const float descent = src_tmp.Font.Info.Descender;
  628. ImFontAtlasBuildSetupFont(atlas, dst_font, &src, ascent, descent);
  629. if (src_tmp.GlyphsCount == 0)
  630. continue;
  631. const float font_off_x = src.GlyphOffset.x;
  632. const float font_off_y = src.GlyphOffset.y + IM_ROUND(dst_font->Ascent);
  633. const int padding = atlas->TexGlyphPadding;
  634. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
  635. {
  636. ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
  637. stbrp_rect& pack_rect = src_tmp.Rects[glyph_i];
  638. IM_ASSERT(pack_rect.was_packed);
  639. if (pack_rect.w == 0 && pack_rect.h == 0)
  640. continue;
  641. GlyphInfo& info = src_glyph.Info;
  642. IM_ASSERT(info.Width + padding <= pack_rect.w);
  643. IM_ASSERT(info.Height + padding <= pack_rect.h);
  644. const int tx = pack_rect.x + padding;
  645. const int ty = pack_rect.y + padding;
  646. // Register glyph
  647. float x0 = info.OffsetX * src_tmp.Font.InvRasterizationDensity + font_off_x;
  648. float y0 = info.OffsetY * src_tmp.Font.InvRasterizationDensity + font_off_y;
  649. float x1 = x0 + info.Width * src_tmp.Font.InvRasterizationDensity;
  650. float y1 = y0 + info.Height * src_tmp.Font.InvRasterizationDensity;
  651. float u0 = (tx) / (float)atlas->TexWidth;
  652. float v0 = (ty) / (float)atlas->TexHeight;
  653. float u1 = (tx + info.Width) / (float)atlas->TexWidth;
  654. float v1 = (ty + info.Height) / (float)atlas->TexHeight;
  655. dst_font->AddGlyph(&src, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX * src_tmp.Font.InvRasterizationDensity);
  656. ImFontGlyph* dst_glyph = &dst_font->Glyphs.back();
  657. IM_ASSERT(dst_glyph->Codepoint == src_glyph.Codepoint);
  658. if (src_glyph.Info.IsColored)
  659. dst_glyph->Colored = tex_use_colors = true;
  660. // Blit from temporary buffer to final texture
  661. size_t blit_src_stride = (size_t)src_glyph.Info.Width;
  662. size_t blit_dst_stride = (size_t)atlas->TexWidth;
  663. unsigned int* blit_src = src_glyph.BitmapData;
  664. if (atlas->TexPixelsAlpha8 != nullptr)
  665. {
  666. unsigned char* blit_dst = atlas->TexPixelsAlpha8 + (ty * blit_dst_stride) + tx;
  667. for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride)
  668. for (int x = 0; x < info.Width; x++)
  669. blit_dst[x] = (unsigned char)((blit_src[x] >> IM_COL32_A_SHIFT) & 0xFF);
  670. }
  671. else
  672. {
  673. unsigned int* blit_dst = atlas->TexPixelsRGBA32 + (ty * blit_dst_stride) + tx;
  674. for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride)
  675. for (int x = 0; x < info.Width; x++)
  676. blit_dst[x] = blit_src[x];
  677. }
  678. }
  679. src_tmp.Rects = nullptr;
  680. }
  681. atlas->TexPixelsUseColors = tex_use_colors;
  682. // Cleanup
  683. for (int buf_i = 0; buf_i < buf_bitmap_buffers.Size; buf_i++)
  684. IM_FREE(buf_bitmap_buffers[buf_i]);
  685. src_tmp_array.clear_destruct();
  686. ImFontAtlasBuildFinish(atlas);
  687. return true;
  688. }
  689. #endif
  690. // FreeType memory allocation callbacks
  691. static void* FreeType_Alloc(FT_Memory /*memory*/, long size)
  692. {
  693. return GImGuiFreeTypeAllocFunc((size_t)size, GImGuiFreeTypeAllocatorUserData);
  694. }
  695. static void FreeType_Free(FT_Memory /*memory*/, void* block)
  696. {
  697. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  698. }
  699. static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size, void* block)
  700. {
  701. // Implement realloc() as we don't ask user to provide it.
  702. if (block == nullptr)
  703. return GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  704. if (new_size == 0)
  705. {
  706. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  707. return nullptr;
  708. }
  709. if (new_size > cur_size)
  710. {
  711. void* new_block = GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  712. memcpy(new_block, block, (size_t)cur_size);
  713. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  714. return new_block;
  715. }
  716. return block;
  717. }
  718. bool ImGui_ImplFreeType_LoaderInit(ImFontAtlas* atlas)
  719. {
  720. IM_ASSERT(atlas->FontLoaderData == NULL);
  721. ImGui_ImplFreeType_Data* bd = IM_NEW(ImGui_ImplFreeType_Data)();
  722. // FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html
  723. bd->MemoryManager.user = nullptr;
  724. bd->MemoryManager.alloc = &FreeType_Alloc;
  725. bd->MemoryManager.free = &FreeType_Free;
  726. bd->MemoryManager.realloc = &FreeType_Realloc;
  727. // https://www.freetype.org/freetype2/docs/reference/ft2-module_management.html#FT_New_Library
  728. FT_Error error = FT_New_Library(&bd->MemoryManager, &bd->Library);
  729. if (error != 0)
  730. {
  731. IM_DELETE(bd);
  732. return false;
  733. }
  734. // If you don't call FT_Add_Default_Modules() the rest of code may work, but FreeType won't use our custom allocator.
  735. FT_Add_Default_Modules(bd->Library);
  736. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  737. // Install svg hooks for FreeType
  738. // https://freetype.org/freetype2/docs/reference/ft2-properties.html#svg-hooks
  739. // https://freetype.org/freetype2/docs/reference/ft2-svg_fonts.html#svg_fonts
  740. SVG_RendererHooks hooks = { ImGuiLunasvgPortInit, ImGuiLunasvgPortFree, ImGuiLunasvgPortRender, ImGuiLunasvgPortPresetSlot };
  741. FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", &hooks);
  742. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  743. #ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG
  744. // With plutosvg, use provided hooks
  745. FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", plutosvg_ft_svg_hooks());
  746. #endif // IMGUI_ENABLE_FREETYPE_PLUTOSVG
  747. // Store our data
  748. atlas->FontLoaderData = (void*)bd;
  749. return true;
  750. }
  751. void ImGui_ImplFreeType_LoaderShutdown(ImFontAtlas* atlas)
  752. {
  753. ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData;
  754. IM_ASSERT(bd != NULL);
  755. FT_Done_Library(bd->Library);
  756. IM_DELETE(bd);
  757. atlas->FontLoaderData = NULL;
  758. }
  759. bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src)
  760. {
  761. ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData;
  762. ImGui_ImplFreeType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplFreeType_FontSrcData);
  763. IM_ASSERT(src->FontLoaderData == NULL);
  764. src->FontLoaderData = bd_font_data;
  765. if (!bd_font_data->InitFont(bd->Library, src, atlas->FontBuilderFlags))
  766. return false;
  767. if (src->MergeMode == false)
  768. {
  769. ImFont* font = src->DstFont;
  770. font->Ascent = bd_font_data->Info.Ascender;
  771. font->Descent = bd_font_data->Info.Descender;
  772. }
  773. return true;
  774. }
  775. void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src)
  776. {
  777. IM_UNUSED(atlas);
  778. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  779. IM_DELETE(bd_font_data);
  780. src->FontLoaderData = NULL;
  781. }
  782. bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* srcs, int srcs_count, ImWchar codepoint)
  783. {
  784. // Search for first font which has the glyph
  785. ImGui_ImplFreeType_FontSrcData* bd_font_data = NULL;
  786. ImFontConfig* src = NULL;
  787. uint32_t glyph_index = 0;
  788. for (int src_n = 0; src_n < srcs_count; src_n++)
  789. {
  790. src = &srcs[src_n];
  791. bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  792. glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint);
  793. if (glyph_index != 0)
  794. break;
  795. }
  796. if (glyph_index == 0)
  797. return false; // Not found
  798. const FT_Glyph_Metrics* metrics = bd_font_data->LoadGlyph(codepoint);
  799. if (metrics == NULL)
  800. return false;
  801. // Render glyph into a bitmap (currently held by FreeType)
  802. FT_Face face = bd_font_data->FtFace;
  803. FT_GlyphSlot slot = face->glyph;
  804. FT_Error error = FT_Render_Glyph(slot, bd_font_data->RenderMode);
  805. if (error != 0)
  806. return false;
  807. const FT_Bitmap* ft_bitmap = &slot->bitmap;
  808. if (ft_bitmap == nullptr)
  809. return false;
  810. const int w = (int)ft_bitmap->width;
  811. const int h = (int)ft_bitmap->rows;
  812. const bool is_visible = (w != 0 && h != 0);
  813. // Prepare glyph
  814. ImFontGlyph glyph = {};
  815. glyph.Codepoint = codepoint;
  816. glyph.AdvanceX = (slot->advance.x / FT_SCALEFACTOR) * bd_font_data->InvRasterizationDensity;
  817. // Pack and retrieve position inside texture atlas
  818. if (is_visible)
  819. {
  820. ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h);
  821. ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id);
  822. font->MetricsTotalSurface += w * h;
  823. // Render pixels to our temporary buffer
  824. atlas->Builder->TempBuffer.resize(w * h * 4);
  825. uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data;
  826. bd_font_data->BlitGlyph(ft_bitmap, temp_buffer, w, nullptr);// multiply_enabled ? multiply_table : nullptr);
  827. float font_off_x = src->GlyphOffset.x;
  828. float font_off_y = src->GlyphOffset.y + IM_ROUND(font->Ascent);
  829. float recip_h = 1.0f / src->RasterizerDensity;
  830. float recip_v = 1.0f / src->RasterizerDensity;
  831. // Register glyph
  832. float glyph_off_x = (float)face->glyph->bitmap_left;
  833. float glyph_off_y = (float)-face->glyph->bitmap_top;
  834. glyph.X0 = glyph_off_x * recip_h + font_off_x;
  835. glyph.Y0 = glyph_off_y * recip_v + font_off_y;
  836. glyph.X1 = (glyph_off_x + w) * recip_h + font_off_x;
  837. glyph.Y1 = (glyph_off_y + h) * recip_v + font_off_y;
  838. glyph.U0 = (r->x) * atlas->TexUvScale.x;
  839. glyph.V0 = (r->y) * atlas->TexUvScale.y;
  840. glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x;
  841. glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y;
  842. glyph.PackId = pack_id;
  843. glyph.Visible = true;
  844. glyph.Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA);
  845. font->BuildRegisterGlyph(src, &glyph);
  846. // Copy to texture, post-process and queue update for backend
  847. ImTextureData* tex = atlas->TexData;
  848. IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height);
  849. ImFontAtlasTextureBlockConvertAndPostProcess(atlas, font, src, &font->Glyphs.back(),
  850. temp_buffer, ImTextureFormat_RGBA32, w * 4, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h);
  851. ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h);
  852. }
  853. else
  854. {
  855. font->BuildRegisterGlyph(src, &glyph);
  856. }
  857. return true;
  858. }
  859. bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint)
  860. {
  861. IM_UNUSED(atlas);
  862. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  863. int glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint);
  864. return glyph_index != 0;
  865. }
  866. const ImFontLoader* ImGuiFreeType::GetFontLoader()
  867. {
  868. static ImFontLoader loader;
  869. loader.Name = "freetype";
  870. loader.LoaderInit = ImGui_ImplFreeType_LoaderInit;
  871. loader.LoaderShutdown = ImGui_ImplFreeType_LoaderShutdown;
  872. loader.FontSrcInit = ImGui_ImplFreeType_FontSrcInit;
  873. loader.FontSrcDestroy = ImGui_ImplFreeType_FontSrcDestroy;
  874. loader.FontSrcContainsGlyph = ImGui_ImplFreetype_FontSrcContainsGlyph;
  875. loader.FontAddGlyph = ImGui_ImplFreeType_FontAddGlyph;
  876. return &loader;
  877. }
  878. void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
  879. {
  880. GImGuiFreeTypeAllocFunc = alloc_func;
  881. GImGuiFreeTypeFreeFunc = free_func;
  882. GImGuiFreeTypeAllocatorUserData = user_data;
  883. }
  884. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  885. // For more details, see https://gitlab.freedesktop.org/freetype/freetype-demos/-/blob/master/src/rsvg-port.c
  886. // 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)
  887. struct LunasvgPortState
  888. {
  889. FT_Error err = FT_Err_Ok;
  890. lunasvg::Matrix matrix;
  891. std::unique_ptr<lunasvg::Document> svg = nullptr;
  892. };
  893. static FT_Error ImGuiLunasvgPortInit(FT_Pointer* _state)
  894. {
  895. *_state = IM_NEW(LunasvgPortState)();
  896. return FT_Err_Ok;
  897. }
  898. static void ImGuiLunasvgPortFree(FT_Pointer* _state)
  899. {
  900. IM_DELETE(*(LunasvgPortState**)_state);
  901. }
  902. static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state)
  903. {
  904. LunasvgPortState* state = *(LunasvgPortState**)_state;
  905. // If there was an error while loading the svg in ImGuiLunasvgPortPresetSlot(), the renderer hook still get called, so just returns the error.
  906. if (state->err != FT_Err_Ok)
  907. return state->err;
  908. // rows is height, pitch (or stride) equals to width * sizeof(int32)
  909. lunasvg::Bitmap bitmap((uint8_t*)slot->bitmap.buffer, slot->bitmap.width, slot->bitmap.rows, slot->bitmap.pitch);
  910. #if LUNASVG_VERSION_MAJOR >= 3
  911. state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated
  912. #else
  913. state->svg->setMatrix(state->svg->matrix().identity()); // Reset the svg matrix to the default value
  914. state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated
  915. #endif
  916. state->err = FT_Err_Ok;
  917. return state->err;
  918. }
  919. static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_Pointer* _state)
  920. {
  921. FT_SVG_Document document = (FT_SVG_Document)slot->other;
  922. LunasvgPortState* state = *(LunasvgPortState**)_state;
  923. FT_Size_Metrics& metrics = document->metrics;
  924. // This function is called twice, once in the FT_Load_Glyph() and another right before ImGuiLunasvgPortRender().
  925. // If it's the latter, don't do anything because it's // already done in the former.
  926. if (cache)
  927. return state->err;
  928. state->svg = lunasvg::Document::loadFromData((const char*)document->svg_document, document->svg_document_length);
  929. if (state->svg == nullptr)
  930. {
  931. state->err = FT_Err_Invalid_SVG_Document;
  932. return state->err;
  933. }
  934. #if LUNASVG_VERSION_MAJOR >= 3
  935. lunasvg::Box box = state->svg->boundingBox();
  936. #else
  937. lunasvg::Box box = state->svg->box();
  938. #endif
  939. double scale = std::min(metrics.x_ppem / box.w, metrics.y_ppem / box.h);
  940. double xx = (double)document->transform.xx / (1 << 16);
  941. double xy = -(double)document->transform.xy / (1 << 16);
  942. double yx = -(double)document->transform.yx / (1 << 16);
  943. double yy = (double)document->transform.yy / (1 << 16);
  944. double x0 = (double)document->delta.x / 64 * box.w / metrics.x_ppem;
  945. double y0 = -(double)document->delta.y / 64 * box.h / metrics.y_ppem;
  946. #if LUNASVG_VERSION_MAJOR >= 3
  947. // Scale, transform and pre-translate the matrix for the rendering step
  948. state->matrix = lunasvg::Matrix::translated(-box.x, -box.y);
  949. state->matrix.multiply(lunasvg::Matrix(xx, xy, yx, yy, x0, y0));
  950. state->matrix.scale(scale, scale);
  951. // Apply updated transformation to the bounding box
  952. box.transform(state->matrix);
  953. #else
  954. // Scale and transform, we don't translate the svg yet
  955. state->matrix.identity();
  956. state->matrix.scale(scale, scale);
  957. state->matrix.transform(xx, xy, yx, yy, x0, y0);
  958. state->svg->setMatrix(state->matrix);
  959. // Pre-translate the matrix for the rendering step
  960. state->matrix.translate(-box.x, -box.y);
  961. // Get the box again after the transformation
  962. box = state->svg->box();
  963. #endif
  964. // Calculate the bitmap size
  965. slot->bitmap_left = FT_Int(box.x);
  966. slot->bitmap_top = FT_Int(-box.y);
  967. slot->bitmap.rows = (unsigned int)(ImCeil((float)box.h));
  968. slot->bitmap.width = (unsigned int)(ImCeil((float)box.w));
  969. slot->bitmap.pitch = slot->bitmap.width * 4;
  970. slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
  971. // Compute all the bearings and set them correctly. The outline is scaled already, we just need to use the bounding box.
  972. double metrics_width = box.w;
  973. double metrics_height = box.h;
  974. double horiBearingX = box.x;
  975. double horiBearingY = -box.y;
  976. double vertBearingX = slot->metrics.horiBearingX / 64.0 - slot->metrics.horiAdvance / 64.0 / 2.0;
  977. double vertBearingY = (slot->metrics.vertAdvance / 64.0 - slot->metrics.height / 64.0) / 2.0;
  978. slot->metrics.width = FT_Pos(IM_ROUND(metrics_width * 64.0)); // Using IM_ROUND() assume width and height are positive
  979. slot->metrics.height = FT_Pos(IM_ROUND(metrics_height * 64.0));
  980. slot->metrics.horiBearingX = FT_Pos(horiBearingX * 64);
  981. slot->metrics.horiBearingY = FT_Pos(horiBearingY * 64);
  982. slot->metrics.vertBearingX = FT_Pos(vertBearingX * 64);
  983. slot->metrics.vertBearingY = FT_Pos(vertBearingY * 64);
  984. if (slot->metrics.vertAdvance == 0)
  985. slot->metrics.vertAdvance = FT_Pos(metrics_height * 1.2 * 64.0);
  986. state->err = FT_Err_Ok;
  987. return state->err;
  988. }
  989. #endif // #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  990. //-----------------------------------------------------------------------------
  991. #ifdef __GNUC__
  992. #pragma GCC diagnostic pop
  993. #endif
  994. #ifdef _MSC_VER
  995. #pragma warning (pop)
  996. #endif
  997. #endif // #ifndef IMGUI_DISABLE