tb_font_renderer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. // ================================================================================
  2. // == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
  3. // == See tb_core.h for more information. ==
  4. // ================================================================================
  5. #include "tb_font_renderer.h"
  6. #include "tb_renderer.h"
  7. #include "tb_system.h"
  8. #include <math.h>
  9. namespace tb {
  10. // ================================================================================================
  11. static void blurGlyph(unsigned char* src, int srcw, int srch, int srcStride, unsigned char* dst, int dstw, int dsth, int dstStride, float* temp, float* kernel, int kernelRadius)
  12. {
  13. for (int y = 0; y < srch; y++)
  14. {
  15. for (int x = 0; x < dstw; x++)
  16. {
  17. float val = 0;
  18. for (int k_ofs = -kernelRadius; k_ofs <= kernelRadius; k_ofs++)
  19. {
  20. if (x - kernelRadius + k_ofs >= 0 && x - kernelRadius + k_ofs < srcw)
  21. val += src[y * srcStride + x - kernelRadius + k_ofs] * kernel[k_ofs + kernelRadius];
  22. }
  23. temp[y * dstw + x] = val;
  24. }
  25. }
  26. for (int y = 0; y < dsth; y++)
  27. {
  28. for (int x = 0; x < dstw; x++)
  29. {
  30. float val = 0;
  31. for (int k_ofs = -kernelRadius; k_ofs <= kernelRadius; k_ofs++)
  32. {
  33. if (y - kernelRadius + k_ofs >= 0 && y - kernelRadius + k_ofs < srch)
  34. val += temp[(y - kernelRadius + k_ofs) * dstw + x] * kernel[k_ofs + kernelRadius];
  35. }
  36. dst[y * dstStride + x] = (unsigned char)(val + 0.5f);
  37. }
  38. }
  39. }
  40. // ================================================================================================
  41. TBFontEffect::TBFontEffect()
  42. : m_blur_radius(0)
  43. , m_tempBuffer(nullptr)
  44. , m_kernel(nullptr)
  45. {
  46. }
  47. TBFontEffect::~TBFontEffect()
  48. {
  49. delete [] m_tempBuffer;
  50. delete [] m_kernel;
  51. }
  52. void TBFontEffect::SetBlurRadius(int blur_radius)
  53. {
  54. assert(blur_radius >= 0);
  55. if (m_blur_radius == blur_radius)
  56. return;
  57. m_blur_radius = blur_radius;
  58. if (m_blur_radius > 0)
  59. {
  60. delete [] m_kernel;
  61. m_kernel = new float[m_blur_radius * 2 + 1];
  62. if (!m_kernel)
  63. {
  64. m_blur_radius = 0;
  65. return;
  66. }
  67. float stdDevSq2 = (float)m_blur_radius / 2.f;
  68. stdDevSq2 = 2.f * stdDevSq2 * stdDevSq2;
  69. float scale = 1.f / sqrt(3.1415f * stdDevSq2);
  70. float sum = 0;
  71. for (int k = 0; k < 2 * m_blur_radius + 1; k++)
  72. {
  73. float x = (float)(k - m_blur_radius);
  74. float kval = scale * exp(-(x * x / stdDevSq2));
  75. m_kernel[k] = kval;
  76. sum += kval;
  77. }
  78. for (int k = 0; k < 2 * m_blur_radius + 1; k++)
  79. m_kernel[k] /= sum;
  80. }
  81. }
  82. TBFontGlyphData *TBFontEffect::Render(TBGlyphMetrics *metrics, const TBFontGlyphData *src)
  83. {
  84. TBFontGlyphData *effect_glyph_data = nullptr;
  85. if (m_blur_radius > 0 && src->data8)
  86. {
  87. // Create a new TBFontGlyphData for the blurred glyph
  88. effect_glyph_data = new TBFontGlyphData;
  89. if (!effect_glyph_data)
  90. return nullptr;
  91. effect_glyph_data->w = src->w + m_blur_radius * 2;
  92. effect_glyph_data->h = src->h + m_blur_radius * 2;
  93. effect_glyph_data->stride = effect_glyph_data->w;
  94. effect_glyph_data->data8 = new unsigned char[effect_glyph_data->w * effect_glyph_data->h];
  95. // Reserve memory needed for blurring.
  96. if (!effect_glyph_data->data8 ||
  97. !m_blur_temp.Reserve(effect_glyph_data->w * effect_glyph_data->h * sizeof(float)))
  98. {
  99. delete effect_glyph_data;
  100. return nullptr;
  101. }
  102. // Blur!
  103. blurGlyph(src->data8, src->w, src->h, src->stride,
  104. effect_glyph_data->data8, effect_glyph_data->w, effect_glyph_data->h, effect_glyph_data->w,
  105. (float *)m_blur_temp.GetData(), m_kernel, m_blur_radius);
  106. // Adjust glyph position to compensate for larger size.
  107. metrics->x -= m_blur_radius;
  108. metrics->y -= m_blur_radius;
  109. }
  110. return effect_glyph_data;
  111. }
  112. // == TBFontGlyph =================================================================================
  113. TBFontGlyph::TBFontGlyph(const TBID &hash_id, UCS4 cp)
  114. : hash_id(hash_id)
  115. , cp(cp)
  116. , frag(nullptr)
  117. , has_rgb(false)
  118. {
  119. }
  120. // == TBFontGlyphCache ============================================================================
  121. TBFontGlyphCache::TBFontGlyphCache()
  122. {
  123. // Only use one map for the font face. The glyph cache will start forgetting
  124. // glyphs that haven't been used for a while if the map gets full.
  125. m_frag_manager.SetNumMapsLimit(1);
  126. m_frag_manager.SetDefaultMapSize(TB_GLYPH_CACHE_WIDTH, TB_GLYPH_CACHE_HEIGHT);
  127. g_renderer->AddListener(this);
  128. }
  129. TBFontGlyphCache::~TBFontGlyphCache()
  130. {
  131. g_renderer->RemoveListener(this);
  132. }
  133. TBFontGlyph *TBFontGlyphCache::GetGlyph(const TBID &hash_id, UCS4 cp)
  134. {
  135. if (TBFontGlyph *glyph = m_glyphs.Get(hash_id))
  136. {
  137. // Move the glyph to the end of m_all_rendered_glyphs so we maintain LRU (oldest first)
  138. if (m_all_rendered_glyphs.ContainsLink(glyph))
  139. {
  140. m_all_rendered_glyphs.Remove(glyph);
  141. m_all_rendered_glyphs.AddLast(glyph);
  142. }
  143. return glyph;
  144. }
  145. return nullptr;
  146. }
  147. TBFontGlyph *TBFontGlyphCache::CreateAndCacheGlyph(const TBID &hash_id, UCS4 cp)
  148. {
  149. assert(!GetGlyph(hash_id, cp));
  150. TBFontGlyph *glyph = new TBFontGlyph(hash_id, cp);
  151. if (glyph && m_glyphs.Add(glyph->hash_id, glyph))
  152. return glyph;
  153. delete glyph;
  154. return nullptr;
  155. }
  156. TBBitmapFragment *TBFontGlyphCache::CreateFragment(TBFontGlyph *glyph, int w, int h, int stride, uint32 *data)
  157. {
  158. assert(GetGlyph(glyph->hash_id, glyph->cp));
  159. // Don't bother if the requested glyph is too large.
  160. if (w > TB_GLYPH_CACHE_WIDTH || h > TB_GLYPH_CACHE_HEIGHT)
  161. return nullptr;
  162. bool try_drop_largest = true;
  163. bool dropped_large_enough_glyph = false;
  164. do
  165. {
  166. // Attempt creating a fragment for the rendered glyph data
  167. if (TBBitmapFragment *frag = m_frag_manager.CreateNewFragment(glyph->hash_id, false, w, h, stride, data))
  168. {
  169. glyph->frag = frag;
  170. m_all_rendered_glyphs.AddLast(glyph);
  171. return frag;
  172. }
  173. // Drop the oldest glyph that's large enough to free up the space we need.
  174. if (try_drop_largest)
  175. {
  176. const int check_limit = 20;
  177. int check_count = 0;
  178. for (TBFontGlyph *oldest = m_all_rendered_glyphs.GetFirst(); oldest && check_count < check_limit; oldest = oldest->GetNext())
  179. {
  180. if (oldest->frag->Width() >= w && oldest->frag->GetAllocatedHeight() >= h)
  181. {
  182. DropGlyphFragment(oldest);
  183. dropped_large_enough_glyph = true;
  184. break;
  185. }
  186. check_count++;
  187. }
  188. try_drop_largest = false;
  189. }
  190. // We had no large enough glyph so just drop the oldest one. We will likely
  191. // spin around the loop, fail and drop again a few times before we succeed.
  192. if (!dropped_large_enough_glyph)
  193. {
  194. if (TBFontGlyph *oldest = m_all_rendered_glyphs.GetFirst())
  195. DropGlyphFragment(oldest);
  196. else
  197. break;
  198. }
  199. } while (true);
  200. return nullptr;
  201. }
  202. void TBFontGlyphCache::DropGlyphFragment(TBFontGlyph *glyph)
  203. {
  204. assert(glyph->frag);
  205. m_frag_manager.FreeFragment(glyph->frag);
  206. glyph->frag = nullptr;
  207. m_all_rendered_glyphs.Remove(glyph);
  208. }
  209. #ifdef TB_RUNTIME_DEBUG_INFO
  210. void TBFontGlyphCache::Debug()
  211. {
  212. m_frag_manager.Debug();
  213. }
  214. #endif // TB_RUNTIME_DEBUG_INFO
  215. void TBFontGlyphCache::OnContextLost()
  216. {
  217. m_frag_manager.DeleteBitmaps();
  218. }
  219. void TBFontGlyphCache::OnContextRestored()
  220. {
  221. // No need to do anything. The bitmaps will be created when drawing.
  222. }
  223. // ================================================================================================
  224. TBFontFace::TBFontFace(TBFontGlyphCache *glyph_cache, TBFontRenderer *renderer, const TBFontDescription &font_desc)
  225. : m_glyph_cache(glyph_cache), m_font_renderer(renderer), m_font_desc(font_desc), m_bgFont(nullptr), m_bgX(0), m_bgY(0)
  226. {
  227. if (m_font_renderer)
  228. m_metrics = m_font_renderer->GetMetrics();
  229. else
  230. {
  231. // Invent some metrics for the test font
  232. int size = m_font_desc.GetSize();
  233. m_metrics.ascent = size - size / 4;
  234. m_metrics.descent = size / 4;
  235. m_metrics.height = size;
  236. }
  237. }
  238. TBFontFace::~TBFontFace()
  239. {
  240. // It would be nice to drop all glyphs we have live for this font face.
  241. // Now they only die when they get old and kicked out of the cache.
  242. // We currently don't drop any font faces either though (except on shutdown)
  243. delete m_font_renderer;
  244. }
  245. void TBFontFace::SetBackgroundFont(TBFontFace *font, const TBColor &col, int xofs, int yofs)
  246. {
  247. m_bgFont = font;
  248. m_bgX = xofs;
  249. m_bgY = yofs;
  250. m_bgColor = col;
  251. }
  252. bool TBFontFace::RenderGlyphs(const char *glyph_str, int glyph_str_len)
  253. {
  254. if (!m_font_renderer)
  255. return true; // This is the test font
  256. if (glyph_str_len == TB_ALL_TO_TERMINATION)
  257. glyph_str_len = strlen(glyph_str);
  258. bool has_all_glyphs = true;
  259. int i = 0;
  260. while (glyph_str[i] && i < glyph_str_len)
  261. {
  262. UCS4 cp = utf8::decode_next(glyph_str, &i, glyph_str_len);
  263. if (!GetGlyph(cp, true))
  264. has_all_glyphs = false;
  265. }
  266. return has_all_glyphs;
  267. }
  268. TBFontGlyph *TBFontFace::CreateAndCacheGlyph(UCS4 cp)
  269. {
  270. if (!m_font_renderer)
  271. return nullptr; // This is the test font
  272. // Create the new glyph
  273. TBFontGlyph *glyph = m_glyph_cache->CreateAndCacheGlyph(GetHashId(cp), cp);
  274. if (glyph)
  275. m_font_renderer->GetGlyphMetrics(&glyph->metrics, cp);
  276. return glyph;
  277. }
  278. void TBFontFace::RenderGlyph(TBFontGlyph *glyph)
  279. {
  280. assert(!glyph->frag);
  281. TBFontGlyphData glyph_data;
  282. if (m_font_renderer->RenderGlyph(&glyph_data, glyph->cp))
  283. {
  284. TBFontGlyphData *effect_glyph_data = m_effect.Render(&glyph->metrics, &glyph_data);
  285. TBFontGlyphData *result_glyph_data = effect_glyph_data ? effect_glyph_data : &glyph_data;
  286. // The glyph data may be in uint8 format, which we have to convert since we always
  287. // create fragments (and TBBitmap) in 32bit format.
  288. uint32 *glyph_dsta_src = result_glyph_data->data32;
  289. if (!glyph_dsta_src && result_glyph_data->data8)
  290. {
  291. if (m_temp_buffer.Reserve(result_glyph_data->w * result_glyph_data->h * sizeof(uint32)))
  292. {
  293. glyph_dsta_src = (uint32 *) m_temp_buffer.GetData();
  294. for (int y = 0; y < result_glyph_data->h; y++)
  295. for (int x = 0; x < result_glyph_data->w; x++)
  296. {
  297. #ifdef TB_PREMULTIPLIED_ALPHA
  298. uint8 opacity = result_glyph_data->data8[x + y * result_glyph_data->stride];
  299. glyph_dsta_src[x + y * result_glyph_data->w] = TBColor(opacity, opacity, opacity, opacity);
  300. #else
  301. glyph_dsta_src[x + y * result_glyph_data->w] = TBColor(255, 255, 255, result_glyph_data->data8[x + y * result_glyph_data->stride]);
  302. #endif
  303. }
  304. }
  305. }
  306. // Finally, the glyph data is ready and we can create a bitmap fragment.
  307. if (glyph_dsta_src)
  308. {
  309. glyph->has_rgb = result_glyph_data->rgb;
  310. m_glyph_cache->CreateFragment(glyph, result_glyph_data->w, result_glyph_data->h,
  311. result_glyph_data->stride, glyph_dsta_src);
  312. }
  313. delete effect_glyph_data;
  314. }
  315. #ifdef TB_RUNTIME_DEBUG_INFO
  316. //char glyph_str[9];
  317. //int len = utf8::encode(cp, glyph_str);
  318. //glyph_str[len] = 0;
  319. //TBStr info;
  320. //info.SetFormatted("Created glyph %d (\"%s\"). Cache contains %d glyphs (%d%% full) using %d bitmaps.\n", cp, glyph_str, m_all_glyphs.CountLinks(), m_frag_manager.GetUseRatio(), m_frag_manager.GetNumMaps());
  321. //TBDebugOut(info);
  322. #endif
  323. }
  324. TBID TBFontFace::GetHashId(UCS4 cp) const
  325. {
  326. return cp * 31 + m_font_desc.GetFontFaceID();
  327. }
  328. TBFontGlyph *TBFontFace::GetGlyph(UCS4 cp, bool render_if_needed)
  329. {
  330. TBFontGlyph *glyph = m_glyph_cache->GetGlyph(GetHashId(cp), cp);
  331. if (!glyph)
  332. glyph = CreateAndCacheGlyph(cp);
  333. if (glyph && !glyph->frag && render_if_needed)
  334. RenderGlyph(glyph);
  335. return glyph;
  336. }
  337. void TBFontFace::DrawString(int x, int y, const TBColor &color, const char *str, int len)
  338. {
  339. if (m_bgFont)
  340. m_bgFont->DrawString(x+m_bgX, y+m_bgY, m_bgColor, str, len);
  341. if (m_font_renderer)
  342. g_renderer->BeginBatchHint(TBRenderer::BATCH_HINT_DRAW_BITMAP_FRAGMENT);
  343. int i = 0;
  344. while (str[i] && i < len)
  345. {
  346. UCS4 cp = utf8::decode_next(str, &i, len);
  347. if (cp == 0xFFFF)
  348. continue;
  349. if (TBFontGlyph *glyph = GetGlyph(cp, true))
  350. {
  351. if (glyph->frag)
  352. {
  353. TBRect dst_rect(x + glyph->metrics.x, y + glyph->metrics.y + GetAscent(), glyph->frag->Width(), glyph->frag->Height());
  354. TBRect src_rect(0, 0, glyph->frag->Width(), glyph->frag->Height());
  355. if (glyph->has_rgb)
  356. g_renderer->DrawBitmap(dst_rect, src_rect, glyph->frag);
  357. else
  358. g_renderer->DrawBitmapColored(dst_rect, src_rect, color, glyph->frag);
  359. }
  360. x += glyph->metrics.advance;
  361. }
  362. else if (!m_font_renderer) // This is the test font. Use same glyph width as height and draw square.
  363. {
  364. g_renderer->DrawRect(TBRect(x, y, m_metrics.height / 3, m_metrics.height), color);
  365. x += m_metrics.height / 3 + 1;
  366. }
  367. }
  368. if (m_font_renderer)
  369. g_renderer->EndBatchHint();
  370. }
  371. int TBFontFace::GetStringWidth(const char *str, int len)
  372. {
  373. int width = 0;
  374. int i = 0;
  375. while (str[i] && i < len)
  376. {
  377. UCS4 cp = utf8::decode_next(str, &i, len);
  378. if (cp == 0xFFFF)
  379. continue;
  380. if (!m_font_renderer) // This is the test font. Use same glyph width as height.
  381. width += m_metrics.height / 3 + 1;
  382. else if (TBFontGlyph *glyph = GetGlyph(cp, false))
  383. width += glyph->metrics.advance;
  384. }
  385. return width;
  386. }
  387. #ifdef TB_RUNTIME_DEBUG_INFO
  388. void TBFontFace::Debug()
  389. {
  390. m_glyph_cache->Debug();
  391. }
  392. #endif // TB_RUNTIME_DEBUG_INFO
  393. // == TBFontManager ===============================================================================
  394. TBFontManager::TBFontManager()
  395. {
  396. // Add the test dummy font with empty name (Equals to ID 0)
  397. AddFontInfo("-test-font-dummy-", "");
  398. m_test_font_desc.SetSize(16);
  399. CreateFontFace(m_test_font_desc);
  400. // Use the test dummy font as default by default
  401. m_default_font_desc = m_test_font_desc;
  402. }
  403. TBFontManager::~TBFontManager()
  404. {
  405. }
  406. TBFontInfo *TBFontManager::AddFontInfo(const char *filename, const char *name)
  407. {
  408. if (TBFontInfo *fi = new TBFontInfo(filename, name))
  409. {
  410. if (m_font_info.Add(fi->GetID(), fi))
  411. return fi;
  412. delete fi;
  413. }
  414. return nullptr;
  415. }
  416. TBFontInfo *TBFontManager::GetFontInfo(const TBID &id) const
  417. {
  418. return m_font_info.Get(id);
  419. }
  420. bool TBFontManager::HasFontFace(const TBFontDescription &font_desc) const
  421. {
  422. return m_fonts.Get(font_desc.GetFontFaceID()) ? true : false;
  423. }
  424. TBFontFace *TBFontManager::GetFontFace(const TBFontDescription &font_desc)
  425. {
  426. if (TBFontFace *font = m_fonts.Get(font_desc.GetFontFaceID()))
  427. return font;
  428. if (TBFontFace *font = m_fonts.Get(GetDefaultFontDescription().GetFontFaceID()))
  429. return font;
  430. return m_fonts.Get(m_test_font_desc.GetFontFaceID());
  431. }
  432. TBFontFace *TBFontManager::CreateFontFace(const TBFontDescription &font_desc)
  433. {
  434. assert(!HasFontFace(font_desc)); // There is already a font added with this description!
  435. TBFontInfo *fi = GetFontInfo(font_desc.GetID());
  436. if (!fi)
  437. return nullptr;
  438. if (fi->GetID() == 0) // Is this the test dummy font
  439. {
  440. if (TBFontFace *font = new TBFontFace(&m_glyph_cache, nullptr, font_desc))
  441. {
  442. if (m_fonts.Add(font_desc.GetFontFaceID(), font))
  443. return font;
  444. delete font;
  445. }
  446. return nullptr;
  447. }
  448. // Iterate through font renderers until we find one capable of creating a font for this file.
  449. for (TBFontRenderer *fr = m_font_renderers.GetFirst(); fr; fr = fr->GetNext())
  450. {
  451. if (TBFontFace *font = fr->Create(this, fi->GetFilename(), font_desc))
  452. {
  453. if (m_fonts.Add(font_desc.GetFontFaceID(), font))
  454. return font;
  455. delete font;
  456. }
  457. }
  458. return nullptr;
  459. }
  460. }; // namespace tb