FontFace.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "Deserializer.h"
  25. #include "FileSystem.h"
  26. #include "Font.h"
  27. #include "FontFace.h"
  28. #include "Graphics.h"
  29. #include "Log.h"
  30. #include "MemoryBuffer.h"
  31. #include "Profiler.h"
  32. #include "ResourceCache.h"
  33. #include "Texture2D.h"
  34. #include "UI.h"
  35. #include "XMLFile.h"
  36. #include <ft2build.h>
  37. #include FT_FREETYPE_H
  38. #include FT_TRUETYPE_TABLES_H
  39. #include "DebugNew.h"
  40. namespace Urho3D
  41. {
  42. static const int MIN_POINT_SIZE = 1;
  43. static const int MAX_POINT_SIZE = 96;
  44. /// FreeType library subsystem.
  45. class FreeTypeLibrary : public Object
  46. {
  47. OBJECT(FreeTypeLibrary);
  48. public:
  49. /// Construct.
  50. FreeTypeLibrary(Context* context) :
  51. Object(context)
  52. {
  53. FT_Error error = FT_Init_FreeType(&library_);
  54. if (error)
  55. LOGERROR("Could not initialize FreeType library");
  56. }
  57. /// Destruct.
  58. virtual ~FreeTypeLibrary()
  59. {
  60. FT_Done_FreeType(library_);
  61. }
  62. FT_Library GetLibrary() const { return library_; }
  63. private:
  64. /// FreeType library.
  65. FT_Library library_;
  66. };
  67. MutableGlyph::MutableGlyph() :
  68. glyphIndex_(M_MAX_UNSIGNED)
  69. {
  70. }
  71. FontGlyph::FontGlyph() :
  72. used_(false),
  73. page_(M_MAX_UNSIGNED)
  74. {
  75. }
  76. FontFace::FontFace(Font* font) :
  77. font_(font),
  78. face_(0),
  79. hasKerning_(false),
  80. bitmapSize_(0)
  81. {
  82. }
  83. FontFace::~FontFace()
  84. {
  85. if (face_)
  86. {
  87. FT_Done_Face((FT_Face)face_);
  88. face_ = 0;
  89. }
  90. if (font_)
  91. {
  92. // When a face is unloaded, deduct the used texture data size from the parent font
  93. unsigned totalTextureSize = 0;
  94. for (unsigned i = 0; i < textures_.Size(); ++i)
  95. totalTextureSize += textures_[i]->GetWidth() * textures_[i]->GetHeight();
  96. font_->SetMemoryUse(font_->GetMemoryUse() - totalTextureSize);
  97. }
  98. for (List<MutableGlyph*>::Iterator i = mutableGlyphs_.Begin(); i != mutableGlyphs_.End(); ++i)
  99. delete *i;
  100. mutableGlyphs_.Clear();
  101. }
  102. const FontGlyph* FontFace::GetGlyph(unsigned c)
  103. {
  104. HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Find(c);
  105. if (i != glyphMapping_.End())
  106. {
  107. FontGlyph& glyph = glyphs_[i->second_];
  108. // Render glyph if not yet resident in a page texture (FreeType mode only)
  109. if (glyph.page_ == M_MAX_UNSIGNED)
  110. RenderGlyph(i->second_);
  111. // If mutable glyphs in use, move to the front of the list
  112. if (mutableGlyphs_.Size() && glyph.iterator_ != mutableGlyphs_.End())
  113. {
  114. MutableGlyph* mutableGlyph = *glyph.iterator_;
  115. mutableGlyphs_.Erase(glyph.iterator_);
  116. mutableGlyphs_.PushFront(mutableGlyph);
  117. glyph.iterator_ = mutableGlyphs_.Begin();
  118. }
  119. glyph.used_ = true;
  120. return &glyph;
  121. }
  122. else
  123. return 0;
  124. }
  125. short FontFace::GetKerning(unsigned c, unsigned d) const
  126. {
  127. if (!hasKerning_)
  128. return 0;
  129. if (c == '\n' || d == '\n')
  130. return 0;
  131. unsigned leftIndex = 0;
  132. unsigned rightIndex = 0;
  133. HashMap<unsigned, unsigned>::ConstIterator leftIt = glyphMapping_.Find(c);
  134. if (leftIt != glyphMapping_.End())
  135. leftIndex = leftIt->second_;
  136. else
  137. return 0;
  138. HashMap<unsigned, unsigned>::ConstIterator rightIt = glyphMapping_.Find(d);
  139. if (rightIt != glyphMapping_.End())
  140. rightIndex = rightIt->second_;
  141. else
  142. return 0;
  143. HashMap<unsigned, unsigned>::ConstIterator kerningIt = glyphs_[leftIndex].kerning_.Find(rightIndex);
  144. if (kerningIt != glyphs_[leftIndex].kerning_.End())
  145. return kerningIt->second_;
  146. else
  147. return 0;
  148. }
  149. bool FontFace::IsDataLost() const
  150. {
  151. for (unsigned i = 0; i < textures_.Size(); ++i)
  152. {
  153. if (textures_[i]->IsDataLost())
  154. return true;
  155. }
  156. return false;
  157. }
  158. bool FontFace::RenderAllGlyphs(int maxWidth, int maxHeight)
  159. {
  160. assert(font_ && face_ && textures_.Empty());
  161. allocator_ = AreaAllocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxWidth, maxHeight);
  162. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  163. {
  164. if (glyphs_[i].width_ && glyphs_[i].height_)
  165. {
  166. int x, y;
  167. // Reserve an empty border between glyphs for filtering
  168. if (allocator_.Allocate(glyphs_[i].width_ + 1, glyphs_[i].height_ + 1, x, y))
  169. {
  170. glyphs_[i].x_ = x;
  171. glyphs_[i].y_ = y;
  172. glyphs_[i].page_ = 0;
  173. }
  174. else
  175. {
  176. // When allocation fails, reset the page of all glyphs allocated so far
  177. for (unsigned j = 0; j <= i; ++j)
  178. glyphs_[j].page_ = M_MAX_UNSIGNED;
  179. return false;
  180. }
  181. }
  182. else
  183. {
  184. glyphs_[i].x_ = 0;
  185. glyphs_[i].y_ = 0;
  186. glyphs_[i].page_ = 0;
  187. }
  188. }
  189. // Create image for rendering all the glyphs, clear to black
  190. SharedPtr<Image> image(new Image(font_->GetContext()));
  191. image->SetSize(allocator_.GetWidth(), allocator_.GetHeight(), 1);
  192. unsigned char* imageData = image->GetData();
  193. memset(imageData, 0, image->GetWidth() * image->GetHeight());
  194. int loadMode = font_->GetSubsystem<UI>()->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  195. // Render glyphs
  196. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  197. RenderGlyphBitmap(i, imageData + glyphs_[i].y_ * image->GetWidth() + glyphs_[i].x_, image->GetWidth(), loadMode);
  198. // Load image into a texture, increment memory usage of the parent font
  199. SharedPtr<Texture2D> texture = font_->LoadFaceTexture(image);
  200. if (!texture)
  201. {
  202. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  203. glyphs_[i].page_ = M_MAX_UNSIGNED;
  204. return false;
  205. }
  206. textures_.Push(texture);
  207. font_->SetMemoryUse(font_->GetMemoryUse() + image->GetWidth() * image->GetHeight());
  208. LOGDEBUGF("Font face %s (%dpt) uses a static page texture of size %dx%d", GetFileName(font_->GetName()).CString(), pointSize_, texture->GetWidth(), texture->GetHeight());
  209. return true;
  210. }
  211. void FontFace::RenderGlyph(unsigned index)
  212. {
  213. assert(font_ && face_);
  214. FontGlyph& glyph = glyphs_[index];
  215. // If glyph is empty, just set the current page
  216. if (!glyph.width_ || !glyph.height_)
  217. {
  218. glyph.x_ = 0;
  219. glyph.y_ = 0;
  220. glyph.page_ = textures_.Size() - 1;
  221. return;
  222. }
  223. int loadMode = font_->GetSubsystem<UI>()->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  224. if (!mutableGlyphs_.Size())
  225. {
  226. // Not using mutable glyphs: try to allocate from current page, reserve next page if fails
  227. int x, y;
  228. if (!allocator_.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  229. {
  230. SetupNextTexture(textures_[0]->GetWidth(), textures_[0]->GetHeight());
  231. // This always succeeds, as it is the first allocation of an empty page
  232. allocator_.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y);
  233. }
  234. glyph.x_ = x;
  235. glyph.y_ = y;
  236. glyph.page_ = textures_.Size() - 1;
  237. if (!bitmap_ || (int)bitmapSize_ < glyph.width_ * glyph.height_)
  238. {
  239. bitmapSize_ = glyph.width_ * glyph.height_;
  240. bitmap_ = new unsigned char[bitmapSize_];
  241. }
  242. RenderGlyphBitmap(index, bitmap_.Get(), glyph.width_, loadMode);
  243. textures_.Back()->SetData(0, glyph.x_, glyph.y_, glyph.width_, glyph.height_, bitmap_.Get());
  244. }
  245. else
  246. {
  247. // Using mutable glyphs: overwrite the least recently used glyph
  248. List<MutableGlyph*>::Iterator it = --mutableGlyphs_.End();
  249. MutableGlyph* mutableGlyph = *it;
  250. if (mutableGlyph->glyphIndex_ != M_MAX_UNSIGNED)
  251. glyphs_[mutableGlyph->glyphIndex_].page_ = M_MAX_UNSIGNED;
  252. glyph.x_ = mutableGlyph->x_;
  253. glyph.y_ = mutableGlyph->y_;
  254. glyph.page_ = 0;
  255. glyph.iterator_ = it;
  256. mutableGlyph->glyphIndex_ = index;
  257. if (!bitmap_)
  258. {
  259. bitmapSize_ = cellWidth_ * cellHeight_;
  260. bitmap_ = new unsigned char[bitmapSize_];
  261. }
  262. // Clear the cell bitmap before rendering to ensure padding
  263. memset(bitmap_.Get(), 0, cellWidth_ * cellHeight_);
  264. RenderGlyphBitmap(index, bitmap_.Get(), cellWidth_, loadMode);
  265. textures_[0]->SetData(0, glyph.x_, glyph.y_, cellWidth_, cellHeight_, bitmap_.Get());
  266. }
  267. }
  268. void FontFace::RenderGlyphBitmap(unsigned index, unsigned char* dest, unsigned pitch, int loadMode)
  269. {
  270. const FontGlyph& glyph = glyphs_[index];
  271. if (!glyph.width_ || !glyph.height_)
  272. return;
  273. FT_Face face = (FT_Face)face_;
  274. FT_GlyphSlot slot = face->glyph;
  275. FT_Load_Glyph(face, index, loadMode);
  276. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  277. if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO)
  278. {
  279. for (int y = 0; y < slot->bitmap.rows; ++y)
  280. {
  281. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  282. unsigned char* rowDest = dest + y * pitch;
  283. for (int x = 0; x < slot->bitmap.width; ++x)
  284. rowDest[x] = (src[x >> 3] & (0x80 >> (x & 7))) ? 255 : 0;
  285. }
  286. }
  287. else
  288. {
  289. for (int y = 0; y < slot->bitmap.rows; ++y)
  290. {
  291. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  292. unsigned char* rowDest = dest + y * pitch;
  293. for (int x = 0; x < slot->bitmap.width; ++x)
  294. rowDest[x] = src[x];
  295. }
  296. }
  297. }
  298. void FontFace::SetupNextTexture(int width, int height)
  299. {
  300. // If several dynamic textures are needed, use the maximum size to pack as many as possible to one texture
  301. allocator_ = AreaAllocator(width, height);
  302. SharedPtr<Texture2D> texture = font_->CreateFaceTexture();
  303. texture->SetSize(width, height, Graphics::GetAlphaFormat());
  304. SharedArrayPtr<unsigned char> emptyBitmap(new unsigned char[width * height]);
  305. memset(emptyBitmap.Get(), 0, width * height);
  306. texture->SetData(0, 0, 0, width, height, emptyBitmap.Get());
  307. textures_.Push(texture);
  308. font_->SetMemoryUse(font_->GetMemoryUse() + width * height);
  309. LOGDEBUGF("Font face %s (%dpt) is using %d dynamic page textures of size %dx%d", GetFileName(font_->GetName()).CString(), pointSize_, textures_.Size(), width, height);
  310. }
  311. void FontFace::SetupMutableGlyphs(int textureWidth, int textureHeight, int maxWidth, int maxHeight)
  312. {
  313. assert(mutableGlyphs_.Empty());
  314. SetupNextTexture(textureWidth, textureHeight);
  315. cellWidth_ = maxWidth + 1;
  316. cellHeight_ = maxHeight + 1;
  317. // Allocate as many mutable glyphs as possible
  318. int x, y;
  319. while (allocator_.Allocate(cellWidth_, cellHeight_, x, y))
  320. {
  321. MutableGlyph* glyph = new MutableGlyph();
  322. glyph->x_ = x;
  323. glyph->y_ = y;
  324. mutableGlyphs_.Push(glyph);
  325. }
  326. LOGDEBUGF("Font face %s (%dpt) is using %d mutable glyphs", GetFileName(font_->GetName()).CString(), pointSize_, mutableGlyphs_.Size());
  327. }
  328. }