font_manager.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. /*
  2. * Copyright 2013 Jeremie Roy. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #define USE_EDTAA3 0
  6. #include <bx/macros.h>
  7. #if BX_COMPILER_MSVC
  8. # define generic GenericFromFreeType // WinRT language extensions see "generic" as a keyword... this is stupid
  9. #endif // BX_COMPILER_MSVC
  10. BX_PRAGMA_DIAGNOSTIC_PUSH();
  11. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4245) // error C4245: '=' : conversion from 'int' to 'FT_UInt', signed/unsigned mismatch
  12. #if BX_COMPILER_MSVC || BX_COMPILER_GCC >= 40300
  13. #pragma push_macro("interface")
  14. #endif
  15. #undef interface
  16. #include <freetype/freetype.h>
  17. #if BX_COMPILER_MSVC || BX_COMPILER_GCC >= 40300
  18. #pragma pop_macro("interface")
  19. #endif
  20. BX_PRAGMA_DIAGNOSTIC_POP();
  21. #include "../common.h"
  22. #include <bgfx/bgfx.h>
  23. #include <math.h>
  24. #if USE_EDTAA3
  25. # include <edtaa3/edtaa3func.cpp>
  26. #else
  27. # define SDF_IMPLEMENTATION
  28. # include <sdf/sdf.h>
  29. #endif // USE_EDTAA3
  30. #include <wchar.h> // wcslen
  31. #include <tinystl/allocator.h>
  32. #include <tinystl/unordered_map.h>
  33. namespace stl = tinystl;
  34. #include "font_manager.h"
  35. #include "../cube_atlas.h"
  36. struct FTHolder
  37. {
  38. FT_Library library;
  39. FT_Face face;
  40. };
  41. class TrueTypeFont
  42. {
  43. public:
  44. TrueTypeFont();
  45. ~TrueTypeFont();
  46. /// Initialize from an external buffer
  47. /// @remark The ownership of the buffer is external, and you must ensure it stays valid up to this object lifetime
  48. /// @return true if the initialization succeed
  49. bool init(const uint8_t* _buffer, uint32_t _bufferSize, int32_t _fontIndex, uint32_t _pixelHeight);
  50. /// return the font descriptor of the current font
  51. FontInfo getFontInfo();
  52. /// raster a glyph as 8bit alpha to a memory buffer
  53. /// update the GlyphInfo according to the raster strategy
  54. /// @ remark buffer min size: glyphInfo.m_width * glyphInfo * height * sizeof(char)
  55. bool bakeGlyphAlpha(CodePoint _codePoint, GlyphInfo& _outGlyphInfo, uint8_t* _outBuffer);
  56. /// raster a glyph as 32bit subpixel rgba to a memory buffer
  57. /// update the GlyphInfo according to the raster strategy
  58. /// @ remark buffer min size: glyphInfo.m_width * glyphInfo * height * sizeof(uint32_t)
  59. bool bakeGlyphSubpixel(CodePoint _codePoint, GlyphInfo& _outGlyphInfo, uint8_t* _outBuffer);
  60. /// raster a glyph as 8bit signed distance to a memory buffer
  61. /// update the GlyphInfo according to the raster strategy
  62. /// @ remark buffer min size: glyphInfo.m_width * glyphInfo * height * sizeof(char)
  63. bool bakeGlyphDistance(CodePoint _codePoint, GlyphInfo& _outGlyphInfo, uint8_t* _outBuffer);
  64. private:
  65. FTHolder* m_font;
  66. };
  67. TrueTypeFont::TrueTypeFont() : m_font(NULL)
  68. {
  69. }
  70. TrueTypeFont::~TrueTypeFont()
  71. {
  72. if (NULL != m_font)
  73. {
  74. FT_Done_Face(m_font->face);
  75. FT_Done_FreeType(m_font->library);
  76. delete m_font;
  77. m_font = NULL;
  78. }
  79. }
  80. bool TrueTypeFont::init(const uint8_t* _buffer, uint32_t _bufferSize, int32_t _fontIndex, uint32_t _pixelHeight)
  81. {
  82. BX_CHECK(m_font == NULL, "TrueTypeFont already initialized");
  83. BX_CHECK( (_bufferSize > 256 && _bufferSize < 100000000), "TrueType buffer size is suspicious");
  84. BX_CHECK( (_pixelHeight > 4 && _pixelHeight < 128), "TrueType buffer size is suspicious");
  85. FTHolder* holder = new FTHolder;
  86. FT_Error error = FT_Init_FreeType(&holder->library);
  87. BX_WARN(!error, "FT_Init_FreeType failed.");
  88. if (error)
  89. {
  90. goto err0;
  91. }
  92. error = FT_New_Memory_Face(holder->library, _buffer, _bufferSize, _fontIndex, &holder->face);
  93. BX_WARN(!error, "FT_Init_FreeType failed.");
  94. if (error)
  95. {
  96. if (FT_Err_Unknown_File_Format == error)
  97. {
  98. goto err0;
  99. }
  100. goto err1;
  101. }
  102. error = FT_Select_Charmap(holder->face, FT_ENCODING_UNICODE);
  103. BX_WARN(!error, "FT_Init_FreeType failed.");
  104. if (error)
  105. {
  106. goto err2;
  107. }
  108. error = FT_Set_Pixel_Sizes(holder->face, 0, _pixelHeight);
  109. BX_WARN(!error, "FT_Init_FreeType failed.");
  110. if (error)
  111. {
  112. goto err2;
  113. }
  114. m_font = holder;
  115. return true;
  116. err2:
  117. FT_Done_Face(holder->face);
  118. err1:
  119. FT_Done_FreeType(holder->library);
  120. err0:
  121. delete holder;
  122. return false;
  123. }
  124. FontInfo TrueTypeFont::getFontInfo()
  125. {
  126. BX_CHECK(m_font != NULL, "TrueTypeFont not initialized");
  127. BX_CHECK(FT_IS_SCALABLE(m_font->face), "Font is unscalable");
  128. FT_Size_Metrics metrics = m_font->face->size->metrics;
  129. FontInfo outFontInfo;
  130. outFontInfo.scale = 1.0f;
  131. outFontInfo.ascender = metrics.ascender / 64.0f;
  132. outFontInfo.descender = metrics.descender / 64.0f;
  133. outFontInfo.lineGap = (metrics.height - metrics.ascender + metrics.descender) / 64.0f;
  134. outFontInfo.maxAdvanceWidth = metrics.max_advance/ 64.0f;
  135. outFontInfo.underlinePosition = FT_MulFix(m_font->face->underline_position, metrics.y_scale) / 64.0f;
  136. outFontInfo.underlineThickness = FT_MulFix(m_font->face->underline_thickness, metrics.y_scale) / 64.0f;
  137. return outFontInfo;
  138. }
  139. static void glyphInfoInit(GlyphInfo& _glyphInfo, FT_BitmapGlyph _bitmap, FT_GlyphSlot _slot, uint8_t* _dst, uint32_t _bpp)
  140. {
  141. int32_t xx = _bitmap->left;
  142. int32_t yy = -_bitmap->top;
  143. int32_t ww = _bitmap->bitmap.width;
  144. int32_t hh = _bitmap->bitmap.rows;
  145. _glyphInfo.offset_x = (float)xx;
  146. _glyphInfo.offset_y = (float)yy;
  147. _glyphInfo.width = (float)ww;
  148. _glyphInfo.height = (float)hh;
  149. _glyphInfo.advance_x = (float)_slot->advance.x / 64.0f;
  150. _glyphInfo.advance_y = (float)_slot->advance.y / 64.0f;
  151. uint32_t dstPitch = ww * _bpp;
  152. uint8_t* src = _bitmap->bitmap.buffer;
  153. uint32_t srcPitch = _bitmap->bitmap.pitch;
  154. for (int32_t ii = 0; ii < hh; ++ii)
  155. {
  156. memcpy(_dst, src, dstPitch);
  157. _dst += dstPitch;
  158. src += srcPitch;
  159. }
  160. }
  161. bool TrueTypeFont::bakeGlyphAlpha(CodePoint _codePoint, GlyphInfo& _glyphInfo, uint8_t* _outBuffer)
  162. {
  163. BX_CHECK(m_font != NULL, "TrueTypeFont not initialized");
  164. _glyphInfo.glyphIndex = FT_Get_Char_Index(m_font->face, _codePoint);
  165. FT_GlyphSlot slot = m_font->face->glyph;
  166. FT_Error error = FT_Load_Glyph(m_font->face, _glyphInfo.glyphIndex, FT_LOAD_DEFAULT);
  167. if (error)
  168. {
  169. return false;
  170. }
  171. FT_Glyph glyph;
  172. error = FT_Get_Glyph(slot, &glyph);
  173. if (error)
  174. {
  175. return false;
  176. }
  177. error = FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1);
  178. if (error)
  179. {
  180. return false;
  181. }
  182. FT_BitmapGlyph bitmap = (FT_BitmapGlyph)glyph;
  183. glyphInfoInit(_glyphInfo, bitmap, slot, _outBuffer, 1);
  184. FT_Done_Glyph(glyph);
  185. return true;
  186. }
  187. bool TrueTypeFont::bakeGlyphSubpixel(CodePoint _codePoint, GlyphInfo& _glyphInfo, uint8_t* _outBuffer)
  188. {
  189. BX_CHECK(m_font != NULL, "TrueTypeFont not initialized");
  190. _glyphInfo.glyphIndex = FT_Get_Char_Index(m_font->face, _codePoint);
  191. FT_GlyphSlot slot = m_font->face->glyph;
  192. FT_Error error = FT_Load_Glyph(m_font->face, _glyphInfo.glyphIndex, FT_LOAD_DEFAULT);
  193. if (error)
  194. {
  195. return false;
  196. }
  197. FT_Glyph glyph;
  198. error = FT_Get_Glyph(slot, &glyph);
  199. if (error)
  200. {
  201. return false;
  202. }
  203. error = FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_LCD, 0, 1);
  204. if (error)
  205. {
  206. return false;
  207. }
  208. FT_BitmapGlyph bitmap = (FT_BitmapGlyph)glyph;
  209. glyphInfoInit(_glyphInfo, bitmap, slot, _outBuffer, 3);
  210. FT_Done_Glyph(glyph);
  211. return true;
  212. }
  213. static void makeDistanceMap(const uint8_t* _img, uint8_t* _outImg, uint32_t _width, uint32_t _height)
  214. {
  215. #if USE_EDTAA3
  216. int16_t* xdist = (int16_t*)malloc(_width * _height * sizeof(int16_t) );
  217. int16_t* ydist = (int16_t*)malloc(_width * _height * sizeof(int16_t) );
  218. double* gx = (double*)calloc(_width * _height, sizeof(double) );
  219. double* gy = (double*)calloc(_width * _height, sizeof(double) );
  220. double* data = (double*)calloc(_width * _height, sizeof(double) );
  221. double* outside = (double*)calloc(_width * _height, sizeof(double) );
  222. double* inside = (double*)calloc(_width * _height, sizeof(double) );
  223. uint32_t ii;
  224. // Convert img into double (data)
  225. double img_min = 255, img_max = -255;
  226. for (ii = 0; ii < _width * _height; ++ii)
  227. {
  228. double v = _img[ii];
  229. data[ii] = v;
  230. if (v > img_max)
  231. {
  232. img_max = v;
  233. }
  234. if (v < img_min)
  235. {
  236. img_min = v;
  237. }
  238. }
  239. // Rescale image levels between 0 and 1
  240. for (ii = 0; ii < _width * _height; ++ii)
  241. {
  242. data[ii] = (_img[ii] - img_min) / (img_max - img_min);
  243. }
  244. // Compute outside = edtaa3(bitmap); % Transform background (0's)
  245. computegradient(data, _width, _height, gx, gy);
  246. edtaa3(data, gx, gy, _width, _height, xdist, ydist, outside);
  247. for (ii = 0; ii < _width * _height; ++ii)
  248. {
  249. if (outside[ii] < 0)
  250. {
  251. outside[ii] = 0.0;
  252. }
  253. }
  254. // Compute inside = edtaa3(1-bitmap); % Transform foreground (1's)
  255. memset(gx, 0, sizeof(double) * _width * _height);
  256. memset(gy, 0, sizeof(double) * _width * _height);
  257. for (ii = 0; ii < _width * _height; ++ii)
  258. {
  259. data[ii] = 1.0 - data[ii];
  260. }
  261. computegradient(data, _width, _height, gx, gy);
  262. edtaa3(data, gx, gy, _width, _height, xdist, ydist, inside);
  263. for (ii = 0; ii < _width * _height; ++ii)
  264. {
  265. if (inside[ii] < 0)
  266. {
  267. inside[ii] = 0.0;
  268. }
  269. }
  270. // distmap = outside - inside; % Bipolar distance field
  271. uint8_t* out = _outImg;
  272. for (ii = 0; ii < _width * _height; ++ii)
  273. {
  274. outside[ii] -= inside[ii];
  275. outside[ii] = 128 + outside[ii] * 16;
  276. if (outside[ii] < 0)
  277. {
  278. outside[ii] = 0;
  279. }
  280. if (outside[ii] > 255)
  281. {
  282. outside[ii] = 255;
  283. }
  284. out[ii] = 255 - (uint8_t) outside[ii];
  285. }
  286. free(xdist);
  287. free(ydist);
  288. free(gx);
  289. free(gy);
  290. free(data);
  291. free(outside);
  292. free(inside);
  293. #else
  294. sdfBuild(_outImg, _width, 8.0f, _img, _width, _height, _width);
  295. #endif // USE_EDTAA3
  296. }
  297. bool TrueTypeFont::bakeGlyphDistance(CodePoint _codePoint, GlyphInfo& _glyphInfo, uint8_t* _outBuffer)
  298. {
  299. BX_CHECK(m_font != NULL, "TrueTypeFont not initialized");
  300. _glyphInfo.glyphIndex = FT_Get_Char_Index(m_font->face, _codePoint);
  301. FT_Int32 loadMode = FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING;
  302. FT_Render_Mode renderMode = FT_RENDER_MODE_NORMAL;
  303. FT_GlyphSlot slot = m_font->face->glyph;
  304. FT_Error error = FT_Load_Glyph(m_font->face, _glyphInfo.glyphIndex, loadMode);
  305. if (error)
  306. {
  307. return false;
  308. }
  309. FT_Glyph glyph;
  310. error = FT_Get_Glyph(slot, &glyph);
  311. if (error)
  312. {
  313. return false;
  314. }
  315. error = FT_Glyph_To_Bitmap(&glyph, renderMode, 0, 1);
  316. if (error)
  317. {
  318. return false;
  319. }
  320. FT_BitmapGlyph bitmap = (FT_BitmapGlyph)glyph;
  321. int32_t ww = bitmap->bitmap.width;
  322. int32_t hh = bitmap->bitmap.rows;
  323. glyphInfoInit(_glyphInfo, bitmap, slot, _outBuffer, 1);
  324. FT_Done_Glyph(glyph);
  325. if (ww * hh > 0)
  326. {
  327. uint32_t dw = 6;
  328. uint32_t dh = 6;
  329. uint32_t nw = ww + dw * 2;
  330. uint32_t nh = hh + dh * 2;
  331. BX_CHECK(nw * nh < 128 * 128, "Buffer overflow (size %d)", nw * nh);
  332. uint32_t buffSize = nw * nh * sizeof(uint8_t);
  333. uint8_t* alphaImg = (uint8_t*)malloc(buffSize);
  334. memset(alphaImg, 0, nw * nh * sizeof(uint8_t) );
  335. //copy the original buffer to the temp one
  336. for (uint32_t ii = dh; ii < nh - dh; ++ii)
  337. {
  338. memcpy(alphaImg + ii * nw + dw, _outBuffer + (ii - dh) * ww, ww);
  339. }
  340. makeDistanceMap(alphaImg, _outBuffer, nw, nh);
  341. free(alphaImg);
  342. _glyphInfo.offset_x -= (float)dw;
  343. _glyphInfo.offset_y -= (float)dh;
  344. _glyphInfo.width = (float)nw;
  345. _glyphInfo.height = (float)nh;
  346. }
  347. return true;
  348. }
  349. typedef stl::unordered_map<CodePoint, GlyphInfo> GlyphHashMap;
  350. // cache font data
  351. struct FontManager::CachedFont
  352. {
  353. CachedFont()
  354. : trueTypeFont(NULL)
  355. {
  356. masterFontHandle.idx = bx::HandleAlloc::invalid;
  357. }
  358. FontInfo fontInfo;
  359. GlyphHashMap cachedGlyphs;
  360. TrueTypeFont* trueTypeFont;
  361. // an handle to a master font in case of sub distance field font
  362. FontHandle masterFontHandle;
  363. int16_t padding;
  364. };
  365. #define MAX_FONT_BUFFER_SIZE (512 * 512 * 4)
  366. FontManager::FontManager(Atlas* _atlas)
  367. : m_ownAtlas(false)
  368. , m_atlas(_atlas)
  369. {
  370. init();
  371. }
  372. FontManager::FontManager(uint32_t _textureSideWidth)
  373. : m_ownAtlas(true)
  374. , m_atlas(new Atlas(_textureSideWidth) )
  375. {
  376. init();
  377. }
  378. void FontManager::init()
  379. {
  380. m_cachedFiles = new CachedFile[MAX_OPENED_FILES];
  381. m_cachedFonts = new CachedFont[MAX_OPENED_FONT];
  382. m_buffer = new uint8_t[MAX_FONT_BUFFER_SIZE];
  383. const uint32_t W = 3;
  384. // Create filler rectangle
  385. uint8_t buffer[W * W * 4];
  386. memset(buffer, 255, W * W * 4);
  387. m_blackGlyph.width = W;
  388. m_blackGlyph.height = W;
  389. ///make sure the black glyph doesn't bleed by using a one pixel inner outline
  390. m_blackGlyph.regionIndex = m_atlas->addRegion(W, W, buffer, AtlasRegion::TYPE_GRAY, 1);
  391. }
  392. FontManager::~FontManager()
  393. {
  394. BX_CHECK(m_fontHandles.getNumHandles() == 0, "All the fonts must be destroyed before destroying the manager");
  395. delete [] m_cachedFonts;
  396. BX_CHECK(m_filesHandles.getNumHandles() == 0, "All the font files must be destroyed before destroying the manager");
  397. delete [] m_cachedFiles;
  398. delete [] m_buffer;
  399. if (m_ownAtlas)
  400. {
  401. delete m_atlas;
  402. }
  403. }
  404. TrueTypeHandle FontManager::createTtf(const uint8_t* _buffer, uint32_t _size)
  405. {
  406. uint16_t id = m_filesHandles.alloc();
  407. BX_CHECK(id != bx::HandleAlloc::invalid, "Invalid handle used");
  408. m_cachedFiles[id].buffer = new uint8_t[_size];
  409. m_cachedFiles[id].bufferSize = _size;
  410. memcpy(m_cachedFiles[id].buffer, _buffer, _size);
  411. TrueTypeHandle ret = { id };
  412. return ret;
  413. }
  414. void FontManager::destroyTtf(TrueTypeHandle _handle)
  415. {
  416. BX_CHECK(bgfx::isValid(_handle), "Invalid handle used");
  417. delete m_cachedFiles[_handle.idx].buffer;
  418. m_cachedFiles[_handle.idx].bufferSize = 0;
  419. m_cachedFiles[_handle.idx].buffer = NULL;
  420. m_filesHandles.free(_handle.idx);
  421. }
  422. FontHandle FontManager::createFontByPixelSize(TrueTypeHandle _ttfHandle, uint32_t _typefaceIndex, uint32_t _pixelSize, uint32_t _fontType)
  423. {
  424. BX_CHECK(bgfx::isValid(_ttfHandle), "Invalid handle used");
  425. TrueTypeFont* ttf = new TrueTypeFont();
  426. if (!ttf->init(m_cachedFiles[_ttfHandle.idx].buffer, m_cachedFiles[_ttfHandle.idx].bufferSize, _typefaceIndex, _pixelSize) )
  427. {
  428. delete ttf;
  429. FontHandle invalid = { bx::HandleAlloc::invalid };
  430. return invalid;
  431. }
  432. uint16_t fontIdx = m_fontHandles.alloc();
  433. BX_CHECK(fontIdx != bx::HandleAlloc::invalid, "Invalid handle used");
  434. CachedFont& font = m_cachedFonts[fontIdx];
  435. font.trueTypeFont = ttf;
  436. font.fontInfo = ttf->getFontInfo();
  437. font.fontInfo.fontType = _fontType;
  438. font.fontInfo.pixelSize = _pixelSize;
  439. font.cachedGlyphs.clear();
  440. font.masterFontHandle.idx = bx::HandleAlloc::invalid;
  441. FontHandle handle = { fontIdx };
  442. return handle;
  443. }
  444. FontHandle FontManager::createScaledFontToPixelSize(FontHandle _baseFontHandle, uint32_t _pixelSize)
  445. {
  446. BX_CHECK(bgfx::isValid(_baseFontHandle), "Invalid handle used");
  447. CachedFont& baseFont = m_cachedFonts[_baseFontHandle.idx];
  448. FontInfo& fontInfo = baseFont.fontInfo;
  449. FontInfo newFontInfo = fontInfo;
  450. newFontInfo.pixelSize = _pixelSize;
  451. newFontInfo.scale = (float)_pixelSize / (float) fontInfo.pixelSize;
  452. newFontInfo.ascender = (newFontInfo.ascender * newFontInfo.scale);
  453. newFontInfo.descender = (newFontInfo.descender * newFontInfo.scale);
  454. newFontInfo.lineGap = (newFontInfo.lineGap * newFontInfo.scale);
  455. newFontInfo.maxAdvanceWidth = (newFontInfo.maxAdvanceWidth * newFontInfo.scale);
  456. newFontInfo.underlineThickness = (newFontInfo.underlineThickness * newFontInfo.scale);
  457. newFontInfo.underlinePosition = (newFontInfo.underlinePosition * newFontInfo.scale);
  458. uint16_t fontIdx = m_fontHandles.alloc();
  459. BX_CHECK(fontIdx != bx::HandleAlloc::invalid, "Invalid handle used");
  460. CachedFont& font = m_cachedFonts[fontIdx];
  461. font.cachedGlyphs.clear();
  462. font.fontInfo = newFontInfo;
  463. font.trueTypeFont = NULL;
  464. font.masterFontHandle = _baseFontHandle;
  465. FontHandle handle = { fontIdx };
  466. return handle;
  467. }
  468. void FontManager::destroyFont(FontHandle _handle)
  469. {
  470. BX_CHECK(bgfx::isValid(_handle), "Invalid handle used");
  471. CachedFont& font = m_cachedFonts[_handle.idx];
  472. if (font.trueTypeFont != NULL)
  473. {
  474. delete font.trueTypeFont;
  475. font.trueTypeFont = NULL;
  476. }
  477. font.cachedGlyphs.clear();
  478. m_fontHandles.free(_handle.idx);
  479. }
  480. bool FontManager::preloadGlyph(FontHandle _handle, const wchar_t* _string)
  481. {
  482. BX_CHECK(bgfx::isValid(_handle), "Invalid handle used");
  483. CachedFont& font = m_cachedFonts[_handle.idx];
  484. if (NULL == font.trueTypeFont)
  485. {
  486. return false;
  487. }
  488. for (uint32_t ii = 0, end = (uint32_t)wcslen(_string); ii < end; ++ii)
  489. {
  490. CodePoint codePoint = _string[ii];
  491. if (!preloadGlyph(_handle, codePoint) )
  492. {
  493. return false;
  494. }
  495. }
  496. return true;
  497. }
  498. bool FontManager::preloadGlyph(FontHandle _handle, CodePoint _codePoint)
  499. {
  500. BX_CHECK(bgfx::isValid(_handle), "Invalid handle used");
  501. CachedFont& font = m_cachedFonts[_handle.idx];
  502. FontInfo& fontInfo = font.fontInfo;
  503. GlyphHashMap::iterator iter = font.cachedGlyphs.find(_codePoint);
  504. if (iter != font.cachedGlyphs.end() )
  505. {
  506. return true;
  507. }
  508. if (NULL != font.trueTypeFont)
  509. {
  510. GlyphInfo glyphInfo;
  511. switch (font.fontInfo.fontType)
  512. {
  513. case FONT_TYPE_ALPHA:
  514. font.trueTypeFont->bakeGlyphAlpha(_codePoint, glyphInfo, m_buffer);
  515. break;
  516. case FONT_TYPE_DISTANCE:
  517. font.trueTypeFont->bakeGlyphDistance(_codePoint, glyphInfo, m_buffer);
  518. break;
  519. case FONT_TYPE_DISTANCE_SUBPIXEL:
  520. font.trueTypeFont->bakeGlyphDistance(_codePoint, glyphInfo, m_buffer);
  521. break;
  522. default:
  523. BX_CHECK(false, "TextureType not supported yet");
  524. }
  525. if (!addBitmap(glyphInfo, m_buffer) )
  526. {
  527. return false;
  528. }
  529. glyphInfo.advance_x = (glyphInfo.advance_x * fontInfo.scale);
  530. glyphInfo.advance_y = (glyphInfo.advance_y * fontInfo.scale);
  531. glyphInfo.offset_x = (glyphInfo.offset_x * fontInfo.scale);
  532. glyphInfo.offset_y = (glyphInfo.offset_y * fontInfo.scale);
  533. glyphInfo.height = (glyphInfo.height * fontInfo.scale);
  534. glyphInfo.width = (glyphInfo.width * fontInfo.scale);
  535. font.cachedGlyphs[_codePoint] = glyphInfo;
  536. return true;
  537. }
  538. if (isValid(font.masterFontHandle)
  539. && preloadGlyph(font.masterFontHandle, _codePoint) )
  540. {
  541. const GlyphInfo* glyph = getGlyphInfo(font.masterFontHandle, _codePoint);
  542. GlyphInfo glyphInfo = *glyph;
  543. glyphInfo.advance_x = (glyphInfo.advance_x * fontInfo.scale);
  544. glyphInfo.advance_y = (glyphInfo.advance_y * fontInfo.scale);
  545. glyphInfo.offset_x = (glyphInfo.offset_x * fontInfo.scale);
  546. glyphInfo.offset_y = (glyphInfo.offset_y * fontInfo.scale);
  547. glyphInfo.height = (glyphInfo.height * fontInfo.scale);
  548. glyphInfo.width = (glyphInfo.width * fontInfo.scale);
  549. font.cachedGlyphs[_codePoint] = glyphInfo;
  550. return true;
  551. }
  552. return false;
  553. }
  554. const FontInfo& FontManager::getFontInfo(FontHandle _handle) const
  555. {
  556. BX_CHECK(bgfx::isValid(_handle), "Invalid handle used");
  557. return m_cachedFonts[_handle.idx].fontInfo;
  558. }
  559. const GlyphInfo* FontManager::getGlyphInfo(FontHandle _handle, CodePoint _codePoint)
  560. {
  561. const GlyphHashMap& cachedGlyphs = m_cachedFonts[_handle.idx].cachedGlyphs;
  562. GlyphHashMap::const_iterator it = cachedGlyphs.find(_codePoint);
  563. if (it == cachedGlyphs.end() )
  564. {
  565. if (!preloadGlyph(_handle, _codePoint) )
  566. {
  567. return NULL;
  568. }
  569. it = cachedGlyphs.find(_codePoint);
  570. }
  571. BX_CHECK(it != cachedGlyphs.end(), "Failed to preload glyph.");
  572. return &it->second;
  573. }
  574. bool FontManager::addBitmap(GlyphInfo& _glyphInfo, const uint8_t* _data)
  575. {
  576. _glyphInfo.regionIndex = m_atlas->addRegion( (uint16_t) ceil(_glyphInfo.width), (uint16_t) ceil(_glyphInfo.height), _data, AtlasRegion::TYPE_GRAY);
  577. return true;
  578. }