FontFaceFreeType.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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 "FileSystem.h"
  25. #include "Font.h"
  26. #include "FontFaceFreeType.h"
  27. #include "Graphics.h"
  28. #include "Image.h"
  29. #include "Log.h"
  30. #include "MemoryBuffer.h"
  31. #include "Texture2D.h"
  32. #include "UI.h"
  33. #include <ft2build.h>
  34. #include FT_FREETYPE_H
  35. #include FT_TRUETYPE_TABLES_H
  36. #include "DebugNew.h"
  37. namespace Urho3D
  38. {
  39. /// FreeType library subsystem.
  40. class FreeTypeLibrary : public Object
  41. {
  42. OBJECT(FreeTypeLibrary);
  43. public:
  44. /// Construct.
  45. FreeTypeLibrary(Context* context) :
  46. Object(context)
  47. {
  48. FT_Error error = FT_Init_FreeType(&library_);
  49. if (error)
  50. LOGERROR("Could not initialize FreeType library");
  51. }
  52. /// Destruct.
  53. virtual ~FreeTypeLibrary()
  54. {
  55. FT_Done_FreeType(library_);
  56. }
  57. FT_Library GetLibrary() const { return library_; }
  58. private:
  59. /// FreeType library.
  60. FT_Library library_;
  61. };
  62. FontFaceFreeType::FontFaceFreeType(Font* font) :
  63. FontFace(font),
  64. face_(0),
  65. bitmapSize_(0)
  66. {
  67. }
  68. FontFaceFreeType::~FontFaceFreeType()
  69. {
  70. if (face_)
  71. {
  72. FT_Done_Face((FT_Face)face_);
  73. face_ = 0;
  74. }
  75. for (List<MutableGlyph*>::Iterator i = mutableGlyphs_.Begin(); i != mutableGlyphs_.End(); ++i)
  76. delete *i;
  77. mutableGlyphs_.Clear();
  78. }
  79. bool FontFaceFreeType::Load(const unsigned char* fontData, unsigned fontDataSize, int pointSize)
  80. {
  81. Context* context = font_->GetContext();
  82. // Create & initialize FreeType library if it does not exist yet
  83. FreeTypeLibrary* freeType = font_->GetSubsystem<FreeTypeLibrary>();
  84. if (!freeType)
  85. context->RegisterSubsystem(freeType = new FreeTypeLibrary(context));
  86. // Ensure the FreeType library is kept alive as long as TTF font resources exist
  87. freeType_ = freeType;
  88. UI* ui = font_->GetSubsystem<UI>();
  89. int maxTextureSize = ui->GetMaxFontTextureSize();
  90. FT_Face face;
  91. FT_Error error;
  92. FT_Library library = freeType->GetLibrary();
  93. if (pointSize <= 0)
  94. {
  95. LOGERROR("Zero or negative point size");
  96. return false;
  97. }
  98. if (!fontDataSize)
  99. {
  100. LOGERROR("Could not create font face from zero size data");
  101. return false;
  102. }
  103. error = FT_New_Memory_Face(library, fontData, fontDataSize, 0, &face);
  104. if (error)
  105. {
  106. LOGERROR("Could not create font face");
  107. return false;
  108. }
  109. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  110. if (error)
  111. {
  112. FT_Done_Face(face);
  113. LOGERROR("Could not set font point size " + String(pointSize));
  114. return false;
  115. }
  116. face_ = face;
  117. FT_GlyphSlot slot = face->glyph;
  118. unsigned numGlyphs = 0;
  119. // Build glyph mapping
  120. FT_UInt glyphIndex;
  121. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  122. while (glyphIndex != 0)
  123. {
  124. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  125. glyphMapping_[charCode] = glyphIndex;
  126. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  127. }
  128. LOGDEBUGF("Font face %s (%dpt) has %d glyphs", GetFileName(font_->GetName()).CString(), pointSize, numGlyphs);
  129. // Load each of the glyphs to see the sizes & store other information
  130. int maxWidth = 0;
  131. int maxHeight = 0;
  132. int loadMode = ui->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  133. int ascender = face->size->metrics.ascender >> 6;
  134. int descender = face->size->metrics.descender >> 6;
  135. // Check if the font's OS/2 info gives different (larger) values for ascender & descender
  136. TT_OS2* os2Info = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
  137. if (os2Info)
  138. {
  139. ascender = Max(ascender, os2Info->usWinAscent * face->size->metrics.y_ppem / face->units_per_EM);
  140. ascender = Max(ascender, os2Info->sTypoAscender * face->size->metrics.y_ppem / face->units_per_EM);
  141. descender = Max(descender, os2Info->usWinDescent * face->size->metrics.y_ppem / face->units_per_EM);
  142. descender = Max(descender, os2Info->sTypoDescender * face->size->metrics.y_ppem / face->units_per_EM);
  143. }
  144. // Store point size and row height. Use the maximum of ascender + descender, or the face's stored default row height
  145. pointSize_ = pointSize;
  146. rowHeight_ = Max(ascender + descender, face->size->metrics.height >> 6);
  147. glyphs_.Reserve(numGlyphs);
  148. for (unsigned i = 0; i < numGlyphs; ++i)
  149. {
  150. FontGlyph newGlyph;
  151. error = FT_Load_Glyph(face, i, loadMode);
  152. if (!error)
  153. {
  154. // Note: position within texture will be filled later
  155. newGlyph.width_ = (short)Max(slot->metrics.width >> 6, slot->bitmap.width);
  156. newGlyph.height_ = (short)Max(slot->metrics.height >> 6, slot->bitmap.rows);
  157. newGlyph.offsetX_ = (short)(slot->metrics.horiBearingX >> 6);
  158. newGlyph.offsetY_ = (short)(ascender - (slot->metrics.horiBearingY >> 6));
  159. newGlyph.advanceX_ = (short)(slot->metrics.horiAdvance >> 6);
  160. maxWidth = Max(maxWidth, newGlyph.width_);
  161. maxHeight = Max(maxHeight, newGlyph.height_);
  162. }
  163. else
  164. {
  165. newGlyph.width_ = 0;
  166. newGlyph.height_ = 0;
  167. newGlyph.offsetX_ = 0;
  168. newGlyph.offsetY_ = 0;
  169. newGlyph.advanceX_ = 0;
  170. }
  171. glyphs_.Push(newGlyph);
  172. }
  173. // Store kerning if face has kerning information
  174. if (FT_HAS_KERNING(face))
  175. {
  176. hasKerning_ = true;
  177. // Read kerning manually to be more efficient and avoid out of memory crash when use large font file, for example there
  178. // are 29354 glyphs in msyh.ttf
  179. FT_ULong tag = FT_MAKE_TAG('k', 'e', 'r', 'n');
  180. FT_ULong kerningTableSize = 0;
  181. FT_Error error = FT_Load_Sfnt_Table(face, tag, 0, NULL, &kerningTableSize);
  182. if (error)
  183. {
  184. LOGERROR("Could not get kerning table length");
  185. return false;
  186. }
  187. SharedArrayPtr<unsigned char> kerningTable(new unsigned char[kerningTableSize]);
  188. error = FT_Load_Sfnt_Table(face, tag, 0, kerningTable, &kerningTableSize);
  189. if (error)
  190. {
  191. LOGERROR("Could not load kerning table");
  192. return false;
  193. }
  194. // Convert big endian to little endian
  195. for (unsigned i = 0; i < kerningTableSize; i += 2)
  196. Swap(kerningTable[i], kerningTable[i + 1]);
  197. MemoryBuffer deserializer(kerningTable, kerningTableSize);
  198. unsigned short version = deserializer.ReadUShort();
  199. if (version == 0)
  200. {
  201. unsigned numKerningTables = deserializer.ReadUShort();
  202. for (unsigned i = 0; i < numKerningTables; ++i)
  203. {
  204. unsigned short version = deserializer.ReadUShort();
  205. unsigned short length = deserializer.ReadUShort();
  206. unsigned short coverage = deserializer.ReadUShort();
  207. if (version == 0 && coverage == 1)
  208. {
  209. unsigned numKerningPairs = deserializer.ReadUShort();
  210. // Skip searchRange, entrySelector and rangeShift
  211. deserializer.Seek(deserializer.GetPosition() + 3 * sizeof(unsigned short));
  212. for (unsigned j = 0; j < numKerningPairs; ++j)
  213. {
  214. unsigned leftIndex = deserializer.ReadUShort();
  215. unsigned rightIndex = deserializer.ReadUShort();
  216. short amount = (short)(deserializer.ReadShort() >> 6);
  217. if (leftIndex < numGlyphs && rightIndex < numGlyphs)
  218. glyphs_[leftIndex].kerning_[rightIndex] = amount;
  219. else
  220. LOGWARNING("Out of range glyph index in kerning information");
  221. }
  222. }
  223. else
  224. {
  225. // Kerning table contains information we do not support; skip and move to the next (length includes header)
  226. deserializer.Seek(deserializer.GetPosition() + length - 3 * sizeof(unsigned short));
  227. }
  228. }
  229. }
  230. else
  231. LOGWARNING("Can not read kerning information: not version 0");
  232. }
  233. // Now try to pack into the smallest possible texture. If face does not fit into one texture, enable dynamic mode where
  234. // glyphs are only created as necessary
  235. if (RenderAllGlyphs(maxTextureSize, maxTextureSize))
  236. {
  237. FT_Done_Face(face);
  238. face_ = 0;
  239. }
  240. else
  241. {
  242. if (ui->GetUseMutableGlyphs())
  243. SetupMutableGlyphs(maxTextureSize, maxTextureSize, maxWidth, maxHeight);
  244. else
  245. SetupNextTexture(maxTextureSize, maxTextureSize);
  246. }
  247. return true;
  248. }
  249. const FontGlyph* FontFaceFreeType::GetGlyph(unsigned c)
  250. {
  251. HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Find(c);
  252. if (i != glyphMapping_.End())
  253. {
  254. FontGlyph& glyph = glyphs_[i->second_];
  255. // Render glyph if not yet resident in a page texture (FreeType mode only)
  256. if (glyph.page_ == M_MAX_UNSIGNED)
  257. RenderGlyph(i->second_);
  258. // If mutable glyphs in use, move to the front of the list
  259. if (mutableGlyphs_.Size() && glyph.iterator_ != mutableGlyphs_.End())
  260. {
  261. MutableGlyph* mutableGlyph = *glyph.iterator_;
  262. mutableGlyphs_.Erase(glyph.iterator_);
  263. mutableGlyphs_.PushFront(mutableGlyph);
  264. glyph.iterator_ = mutableGlyphs_.Begin();
  265. }
  266. glyph.used_ = true;
  267. return &glyph;
  268. }
  269. else
  270. return 0;
  271. }
  272. bool FontFaceFreeType::RenderAllGlyphs(int maxWidth, int maxHeight)
  273. {
  274. assert(font_ && face_ && textures_.Empty());
  275. allocator_ = AreaAllocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxWidth, maxHeight);
  276. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  277. {
  278. if (glyphs_[i].width_ && glyphs_[i].height_)
  279. {
  280. int x, y;
  281. // Reserve an empty border between glyphs for filtering
  282. if (allocator_.Allocate(glyphs_[i].width_ + 1, glyphs_[i].height_ + 1, x, y))
  283. {
  284. glyphs_[i].x_ = x;
  285. glyphs_[i].y_ = y;
  286. glyphs_[i].page_ = 0;
  287. }
  288. else
  289. {
  290. // When allocation fails, reset the page of all glyphs allocated so far
  291. for (unsigned j = 0; j <= i; ++j)
  292. glyphs_[j].page_ = M_MAX_UNSIGNED;
  293. return false;
  294. }
  295. }
  296. else
  297. {
  298. glyphs_[i].x_ = 0;
  299. glyphs_[i].y_ = 0;
  300. glyphs_[i].page_ = 0;
  301. }
  302. }
  303. // Create image for rendering all the glyphs, clear to black
  304. SharedPtr<Image> image(new Image(font_->GetContext()));
  305. image->SetSize(allocator_.GetWidth(), allocator_.GetHeight(), 1);
  306. unsigned char* imageData = image->GetData();
  307. memset(imageData, 0, image->GetWidth() * image->GetHeight());
  308. int loadMode = font_->GetSubsystem<UI>()->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  309. // Render glyphs
  310. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  311. RenderGlyphBitmap(i, imageData + glyphs_[i].y_ * image->GetWidth() + glyphs_[i].x_, image->GetWidth(), loadMode);
  312. // Load image into a texture, increment memory usage of the parent font
  313. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  314. if (!texture)
  315. {
  316. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  317. glyphs_[i].page_ = M_MAX_UNSIGNED;
  318. return false;
  319. }
  320. textures_.Push(texture);
  321. font_->SetMemoryUse(font_->GetMemoryUse() + image->GetWidth() * image->GetHeight());
  322. LOGDEBUGF("Font face %s (%dpt) uses a static page texture of size %dx%d", GetFileName(font_->GetName()).CString(), pointSize_, texture->GetWidth(), texture->GetHeight());
  323. return true;
  324. }
  325. void FontFaceFreeType::RenderGlyph(unsigned index)
  326. {
  327. assert(font_ && face_);
  328. FontGlyph& glyph = glyphs_[index];
  329. // If glyph is empty, just set the current page
  330. if (!glyph.width_ || !glyph.height_)
  331. {
  332. glyph.x_ = 0;
  333. glyph.y_ = 0;
  334. glyph.page_ = textures_.Size() - 1;
  335. return;
  336. }
  337. int loadMode = font_->GetSubsystem<UI>()->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  338. if (!mutableGlyphs_.Size())
  339. {
  340. // Not using mutable glyphs: try to allocate from current page, reserve next page if fails
  341. int x, y;
  342. if (!allocator_.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  343. {
  344. SetupNextTexture(textures_[0]->GetWidth(), textures_[0]->GetHeight());
  345. // This always succeeds, as it is the first allocation of an empty page
  346. allocator_.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y);
  347. }
  348. glyph.x_ = x;
  349. glyph.y_ = y;
  350. glyph.page_ = textures_.Size() - 1;
  351. if (!bitmap_ || (int)bitmapSize_ < glyph.width_ * glyph.height_)
  352. {
  353. bitmapSize_ = glyph.width_ * glyph.height_;
  354. bitmap_ = new unsigned char[bitmapSize_];
  355. }
  356. RenderGlyphBitmap(index, bitmap_.Get(), glyph.width_, loadMode);
  357. textures_.Back()->SetData(0, glyph.x_, glyph.y_, glyph.width_, glyph.height_, bitmap_.Get());
  358. }
  359. else
  360. {
  361. // Using mutable glyphs: overwrite the least recently used glyph
  362. List<MutableGlyph*>::Iterator it = --mutableGlyphs_.End();
  363. MutableGlyph* mutableGlyph = *it;
  364. if (mutableGlyph->glyphIndex_ != M_MAX_UNSIGNED)
  365. glyphs_[mutableGlyph->glyphIndex_].page_ = M_MAX_UNSIGNED;
  366. glyph.x_ = mutableGlyph->x_;
  367. glyph.y_ = mutableGlyph->y_;
  368. glyph.page_ = 0;
  369. glyph.iterator_ = it;
  370. mutableGlyph->glyphIndex_ = index;
  371. if (!bitmap_)
  372. {
  373. bitmapSize_ = cellWidth_ * cellHeight_;
  374. bitmap_ = new unsigned char[bitmapSize_];
  375. }
  376. // Clear the cell bitmap before rendering to ensure padding
  377. memset(bitmap_.Get(), 0, cellWidth_ * cellHeight_);
  378. RenderGlyphBitmap(index, bitmap_.Get(), cellWidth_, loadMode);
  379. textures_[0]->SetData(0, glyph.x_, glyph.y_, cellWidth_, cellHeight_, bitmap_.Get());
  380. }
  381. }
  382. void FontFaceFreeType::RenderGlyphBitmap(unsigned index, unsigned char* dest, unsigned pitch, int loadMode)
  383. {
  384. const FontGlyph& glyph = glyphs_[index];
  385. if (!glyph.width_ || !glyph.height_)
  386. return;
  387. FT_Face face = (FT_Face)face_;
  388. FT_GlyphSlot slot = face->glyph;
  389. FT_Load_Glyph(face, index, loadMode);
  390. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  391. if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO)
  392. {
  393. for (int y = 0; y < slot->bitmap.rows; ++y)
  394. {
  395. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  396. unsigned char* rowDest = dest + y * pitch;
  397. for (int x = 0; x < slot->bitmap.width; ++x)
  398. rowDest[x] = (src[x >> 3] & (0x80 >> (x & 7))) ? 255 : 0;
  399. }
  400. }
  401. else
  402. {
  403. for (int y = 0; y < slot->bitmap.rows; ++y)
  404. {
  405. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  406. unsigned char* rowDest = dest + y * pitch;
  407. for (int x = 0; x < slot->bitmap.width; ++x)
  408. rowDest[x] = src[x];
  409. }
  410. }
  411. }
  412. void FontFaceFreeType::SetupNextTexture(int width, int height)
  413. {
  414. // If several dynamic textures are needed, use the maximum size to pack as many as possible to one texture
  415. allocator_ = AreaAllocator(width, height);
  416. SharedPtr<Texture2D> texture = CreateFaceTexture();
  417. texture->SetSize(width, height, Graphics::GetAlphaFormat());
  418. SharedArrayPtr<unsigned char> emptyBitmap(new unsigned char[width * height]);
  419. memset(emptyBitmap.Get(), 0, width * height);
  420. texture->SetData(0, 0, 0, width, height, emptyBitmap.Get());
  421. textures_.Push(texture);
  422. font_->SetMemoryUse(font_->GetMemoryUse() + width * height);
  423. LOGDEBUGF("Font face %s (%dpt) is using %d dynamic page textures of size %dx%d", GetFileName(font_->GetName()).CString(), pointSize_, textures_.Size(), width, height);
  424. }
  425. void FontFaceFreeType::SetupMutableGlyphs(int textureWidth, int textureHeight, int maxWidth, int maxHeight)
  426. {
  427. assert(mutableGlyphs_.Empty());
  428. SetupNextTexture(textureWidth, textureHeight);
  429. cellWidth_ = maxWidth + 1;
  430. cellHeight_ = maxHeight + 1;
  431. // Allocate as many mutable glyphs as possible
  432. int x, y;
  433. while (allocator_.Allocate(cellWidth_, cellHeight_, x, y))
  434. {
  435. MutableGlyph* glyph = new MutableGlyph();
  436. glyph->x_ = x;
  437. glyph->y_ = y;
  438. mutableGlyphs_.Push(glyph);
  439. }
  440. LOGDEBUGF("Font face %s (%dpt) is using %d mutable glyphs", GetFileName(font_->GetName()).CString(), pointSize_, mutableGlyphs_.Size());
  441. }
  442. }