AkiraWendell

imgui_freetype.cpp

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