FontFaceFreeType.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. {
  66. }
  67. FontFaceFreeType::~FontFaceFreeType()
  68. {
  69. if (face_)
  70. {
  71. FT_Done_Face((FT_Face)face_);
  72. face_ = 0;
  73. }
  74. }
  75. bool FontFaceFreeType::Load(const unsigned char* fontData, unsigned fontDataSize, int pointSize)
  76. {
  77. Context* context = font_->GetContext();
  78. // Create & initialize FreeType library if it does not exist yet
  79. FreeTypeLibrary* freeType = font_->GetSubsystem<FreeTypeLibrary>();
  80. if (!freeType)
  81. context->RegisterSubsystem(freeType = new FreeTypeLibrary(context));
  82. // Ensure the FreeType library is kept alive as long as TTF font resources exist
  83. freeType_ = freeType;
  84. UI* ui = font_->GetSubsystem<UI>();
  85. int maxTextureSize = ui->GetMaxFontTextureSize();
  86. FT_Face face;
  87. FT_Error error;
  88. FT_Library library = freeType->GetLibrary();
  89. if (pointSize <= 0)
  90. {
  91. LOGERROR("Zero or negative point size");
  92. return false;
  93. }
  94. if (!fontDataSize)
  95. {
  96. LOGERROR("Could not create font face from zero size data");
  97. return false;
  98. }
  99. error = FT_New_Memory_Face(library, fontData, fontDataSize, 0, &face);
  100. if (error)
  101. {
  102. LOGERROR("Could not create font face");
  103. return false;
  104. }
  105. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  106. if (error)
  107. {
  108. FT_Done_Face(face);
  109. LOGERROR("Could not set font point size " + String(pointSize));
  110. return false;
  111. }
  112. face_ = face;
  113. FT_GlyphSlot slot = face->glyph;
  114. FT_UInt glyphIndex;
  115. unsigned numGlyphs = 0;
  116. HashMap<unsigned, unsigned> indexToCharMapping;
  117. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  118. while (glyphIndex != 0)
  119. {
  120. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  121. indexToCharMapping[glyphIndex] = charCode;
  122. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  123. }
  124. LOGDEBUGF("Font face %s (%dpt) has %d glyphs", GetFileName(font_->GetName()).CString(), pointSize, numGlyphs);
  125. // Load each of the glyphs to see the sizes & store other information
  126. int maxWidth = 0;
  127. int maxHeight = 0;
  128. int loadMode = ui->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  129. ascender_ = face->size->metrics.ascender >> 6;
  130. int descender = face->size->metrics.descender >> 6;
  131. // Check if the font's OS/2 info gives different (larger) values for ascender & descender
  132. TT_OS2* os2Info = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
  133. if (os2Info)
  134. {
  135. ascender_ = Max(ascender_, os2Info->usWinAscent * face->size->metrics.y_ppem / face->units_per_EM);
  136. ascender_ = Max(ascender_, os2Info->sTypoAscender * face->size->metrics.y_ppem / face->units_per_EM);
  137. descender = Max(descender, os2Info->usWinDescent * face->size->metrics.y_ppem / face->units_per_EM);
  138. descender = Max(descender, os2Info->sTypoDescender * face->size->metrics.y_ppem / face->units_per_EM);
  139. }
  140. // Store point size and row height. Use the maximum of ascender + descender, or the face's stored default row height
  141. pointSize_ = pointSize;
  142. rowHeight_ = Max(ascender_ + descender, face->size->metrics.height >> 6);
  143. int textureWidth = maxTextureSize;
  144. int textureHeight = maxTextureSize;
  145. bool loadAllGlyphs = CanLoadAllGlyphs(numGlyphs, loadMode, textureWidth, textureHeight);
  146. SharedPtr<Image> image(new Image(font_->GetContext()));
  147. image->SetSize(textureWidth, textureHeight, 1);
  148. unsigned char* imageData = image->GetData();
  149. memset(imageData, 0, image->GetWidth() * image->GetHeight());
  150. allocator_ = AreaAllocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, textureWidth, textureHeight);
  151. for (unsigned i = 0; i < numGlyphs; ++i)
  152. {
  153. unsigned charCode = indexToCharMapping[i];
  154. if (!loadAllGlyphs && (charCode > 0xff))
  155. break;
  156. if (!LoadCharGlyph(charCode, image))
  157. return false;
  158. }
  159. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  160. if (!texture)
  161. return false;
  162. textures_.Push(texture);
  163. font_->SetMemoryUse(font_->GetMemoryUse() + textureWidth * textureHeight);
  164. // Store kerning if face has kerning information
  165. if (FT_HAS_KERNING(face))
  166. {
  167. // Read kerning manually to be more efficient and avoid out of memory crash when use large font file, for example there
  168. // are 29354 glyphs in msyh.ttf
  169. FT_ULong tag = FT_MAKE_TAG('k', 'e', 'r', 'n');
  170. FT_ULong kerningTableSize = 0;
  171. FT_Error error = FT_Load_Sfnt_Table(face, tag, 0, NULL, &kerningTableSize);
  172. if (error)
  173. {
  174. LOGERROR("Could not get kerning table length");
  175. return false;
  176. }
  177. SharedArrayPtr<unsigned char> kerningTable(new unsigned char[kerningTableSize]);
  178. error = FT_Load_Sfnt_Table(face, tag, 0, kerningTable, &kerningTableSize);
  179. if (error)
  180. {
  181. LOGERROR("Could not load kerning table");
  182. return false;
  183. }
  184. // Convert big endian to little endian
  185. for (unsigned i = 0; i < kerningTableSize; i += 2)
  186. Swap(kerningTable[i], kerningTable[i + 1]);
  187. MemoryBuffer deserializer(kerningTable, kerningTableSize);
  188. unsigned short version = deserializer.ReadUShort();
  189. if (version == 0)
  190. {
  191. unsigned numKerningTables = deserializer.ReadUShort();
  192. for (unsigned i = 0; i < numKerningTables; ++i)
  193. {
  194. unsigned short version = deserializer.ReadUShort();
  195. unsigned short length = deserializer.ReadUShort();
  196. unsigned short coverage = deserializer.ReadUShort();
  197. if (version == 0 && coverage == 1)
  198. {
  199. unsigned numKerningPairs = deserializer.ReadUShort();
  200. // Skip searchRange, entrySelector and rangeShift
  201. deserializer.Seek(deserializer.GetPosition() + 3 * sizeof(unsigned short));
  202. for (unsigned j = 0; j < numKerningPairs; ++j)
  203. {
  204. unsigned leftIndex = deserializer.ReadUShort();
  205. unsigned rightIndex = deserializer.ReadUShort();
  206. short amount = (short)(deserializer.ReadShort() >> 6);
  207. HashMap<unsigned, unsigned>::ConstIterator leftIter = indexToCharMapping.Find(leftIndex);
  208. HashMap<unsigned, unsigned>::ConstIterator rightIter = indexToCharMapping.Find(rightIndex);
  209. if (leftIter != indexToCharMapping.End() && rightIter != indexToCharMapping.End())
  210. {
  211. unsigned value = (leftIter->second_ << 16) + rightIter->second_;
  212. kerningMapping_[value] = amount;
  213. }
  214. else
  215. LOGWARNING("Out of range glyph index in kerning information");
  216. }
  217. }
  218. else
  219. {
  220. // Kerning table contains information we do not support; skip and move to the next (length includes header)
  221. deserializer.Seek(deserializer.GetPosition() + length - 3 * sizeof(unsigned short));
  222. }
  223. }
  224. }
  225. else
  226. LOGWARNING("Can not read kerning information: not version 0");
  227. }
  228. if (loadAllGlyphs)
  229. {
  230. FT_Done_Face(face);
  231. face_ = 0;
  232. hasMutableGlyph_ = false;
  233. }
  234. else
  235. hasMutableGlyph_ = true;
  236. return true;
  237. }
  238. const FontGlyph* FontFaceFreeType::GetGlyph(unsigned c)
  239. {
  240. HashMap<unsigned, FontGlyph>::Iterator i = glyphMapping_.Find(c);
  241. if (i != glyphMapping_.End())
  242. {
  243. FontGlyph& glyph = i->second_;
  244. glyph.used_ = true;
  245. return &glyph;
  246. }
  247. if (LoadCharGlyph(c))
  248. {
  249. HashMap<unsigned, FontGlyph>::Iterator i = glyphMapping_.Find(c);
  250. if (i != glyphMapping_.End())
  251. {
  252. FontGlyph& glyph = i->second_;
  253. glyph.used_ = true;
  254. return &glyph;
  255. }
  256. }
  257. return 0;
  258. }
  259. bool FontFaceFreeType::CanLoadAllGlyphs(unsigned numGlyphs, int loadMode, int& textureWidth, int& textureHeight) const
  260. {
  261. FT_Face face = (FT_Face)face_;
  262. FT_GlyphSlot slot = face->glyph;
  263. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, textureWidth, textureHeight);
  264. for (unsigned i = 0; i < numGlyphs; ++i)
  265. {
  266. FT_Error error = FT_Load_Glyph(face, i, loadMode);
  267. if (!error)
  268. {
  269. int width = Max(slot->metrics.width >> 6, slot->bitmap.width);
  270. int height = Max(slot->metrics.height >> 6, slot->bitmap.rows);
  271. int x, y;
  272. if (!allocator.Allocate(width + 1, height + 1, x, y))
  273. return false;
  274. }
  275. }
  276. textureWidth = allocator.GetWidth();
  277. textureHeight = allocator.GetHeight();
  278. return true;
  279. }
  280. bool FontFaceFreeType::SetupNextTexture(int textureWidth, int textureHeight)
  281. {
  282. SharedPtr<Image> image(new Image(font_->GetContext()));
  283. image->SetSize(textureWidth, textureHeight, 1);
  284. unsigned char* imageData = image->GetData();
  285. memset(imageData, 0, image->GetWidth() * image->GetHeight());
  286. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  287. if (!texture)
  288. return false;
  289. textures_.Push(texture);
  290. allocator_ = AreaAllocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, textureWidth, textureHeight);
  291. font_->SetMemoryUse(font_->GetMemoryUse() + textureWidth * textureHeight);
  292. return true;
  293. }
  294. bool FontFaceFreeType::LoadCharGlyph(unsigned charCode, Image* image)
  295. {
  296. if (!face_)
  297. return false;
  298. FT_Face face = (FT_Face)face_;
  299. FT_GlyphSlot slot = face->glyph;
  300. UI* ui = font_->GetSubsystem<UI>();
  301. int loadMode = ui->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  302. FontGlyph fontGlyph;
  303. FT_Error error = FT_Load_Char(face, charCode, loadMode);
  304. if (!error)
  305. {
  306. // Note: position within texture will be filled later
  307. fontGlyph.width_ = (short)Max(slot->metrics.width >> 6, slot->bitmap.width);
  308. fontGlyph.height_ = (short)Max(slot->metrics.height >> 6, slot->bitmap.rows);
  309. fontGlyph.offsetX_ = (short)(slot->metrics.horiBearingX >> 6);
  310. fontGlyph.offsetY_ = (short)(ascender_ - (slot->metrics.horiBearingY >> 6));
  311. fontGlyph.advanceX_ = (short)(slot->metrics.horiAdvance >> 6);
  312. if (fontGlyph.width_ > 0 && fontGlyph.height_ > 0)
  313. {
  314. int x, y;
  315. if (!allocator_.Allocate(fontGlyph.width_ + 1, fontGlyph.height_ + 1, x, y))
  316. {
  317. int textureSize = ui->GetMaxFontTextureSize();
  318. if (!SetupNextTexture(textureSize, textureSize))
  319. return false;
  320. if (!allocator_.Allocate(fontGlyph.width_ + 1, fontGlyph.height_ + 1, x, y))
  321. return false;
  322. }
  323. fontGlyph.x_ = x;
  324. fontGlyph.y_ = y;
  325. unsigned char* dest = 0;
  326. unsigned pitch = 0;
  327. if (image)
  328. {
  329. fontGlyph.page_ = 0;
  330. dest = image->GetData() + fontGlyph.y_ * image->GetWidth() + fontGlyph.x_;
  331. pitch = image->GetWidth();
  332. }
  333. else
  334. {
  335. fontGlyph.page_ = textures_.Size() - 1;
  336. dest = new unsigned char[fontGlyph.width_ * fontGlyph.height_];
  337. pitch = fontGlyph.width_;
  338. }
  339. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  340. if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO)
  341. {
  342. for (int y = 0; y < slot->bitmap.rows; ++y)
  343. {
  344. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  345. unsigned char* rowDest = dest + y * pitch;
  346. for (int x = 0; x < slot->bitmap.width; ++x)
  347. rowDest[x] = (src[x >> 3] & (0x80 >> (x & 7))) ? 255 : 0;
  348. }
  349. }
  350. else
  351. {
  352. for (int y = 0; y < slot->bitmap.rows; ++y)
  353. {
  354. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  355. unsigned char* rowDest = dest + y * pitch;
  356. for (int x = 0; x < slot->bitmap.width; ++x)
  357. rowDest[x] = src[x];
  358. }
  359. }
  360. if (!image)
  361. {
  362. textures_.Back()->SetData(0, fontGlyph.x_, fontGlyph.y_, fontGlyph.width_, fontGlyph.height_, dest);
  363. delete [] dest;
  364. }
  365. }
  366. else
  367. {
  368. fontGlyph.x_ = 0;
  369. fontGlyph.y_ = 0;
  370. fontGlyph.page_ = 0;
  371. }
  372. }
  373. else
  374. {
  375. fontGlyph.width_ = 0;
  376. fontGlyph.height_ = 0;
  377. fontGlyph.offsetX_ = 0;
  378. fontGlyph.offsetY_ = 0;
  379. fontGlyph.advanceX_ = 0;
  380. fontGlyph.page_ = 0;
  381. }
  382. glyphMapping_[charCode] = fontGlyph;
  383. return true;
  384. }
  385. }