golang/freetype

Fallback fonts

CamilleScholtz opened this issue · 2 comments

How would I go about handling fallback fonts? Say I want to "write" a string with both japanese and latin characters, but the font I loaded only contains loaded characters. Would it somehow be possible to merge two truetype.Fonts into one?

If following outside of FreeType internal, I have made next way:

  • register every loading font face into global array of loaded fonts (use mutex if your app is multi-threaded) (as example, std::unordered_set<FT_Face> (a container that stores unique objects without sorting) where you doing insert on loading each font and erase when you removing that font).
  • Use FT_Get_Char_Index with wished font to get ID of a glypth. If it returns zero, fetch your array of fonts and try to use FT_Get_Char_Index for each font you have.
  • When you got non-zero character index, break the loop, then use FT_Set_Pixel_Sizes if needed, and FT_Load_Glyph with pointer to current (or fallback-detected) to load glyph itself to use it
  • For better performance, you can add the std::unordered_map (some sort of "dictionary" to map key to some value) which will map char32_t into structure which contains a pointer to necessary font face and the glyph index. (On adding/deleting of any font you must clear the cache or selectively clear entries related to deleting font, but when you adding a new font, you must clear it in case you adding font that adds missing glyphs, etc.). Then, before to dig for a glyph between of multiple fonts, check the cache first.