Font.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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. Font::Font(Context* context) :
  68. Resource(context),
  69. fontDataSize_(0),
  70. fontType_(FONT_NONE)
  71. {
  72. }
  73. Font::~Font()
  74. {
  75. // To ensure FreeType deallocates properly, first clear all faces, then release the raw font data
  76. ReleaseFaces();
  77. fontData_.Reset();
  78. }
  79. void Font::RegisterObject(Context* context)
  80. {
  81. context->RegisterFactory<Font>();
  82. }
  83. bool Font::Load(Deserializer& source)
  84. {
  85. PROFILE(LoadFont);
  86. // In headless mode, do not actually load, just return success
  87. Graphics* graphics = GetSubsystem<Graphics>();
  88. if (!graphics)
  89. return true;
  90. fontType_ = FONT_NONE;
  91. faces_.Clear();
  92. fontDataSize_ = source.GetSize();
  93. if (fontDataSize_)
  94. {
  95. fontData_ = new unsigned char[fontDataSize_];
  96. if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
  97. return false;
  98. }
  99. else
  100. {
  101. fontData_.Reset();
  102. return false;
  103. }
  104. String ext = GetExtension(GetName());
  105. if (ext == ".ttf" || ext == ".otf" || ext == ".woff")
  106. fontType_ = FONT_FREETYPE;
  107. else if (ext == ".xml" || ext == ".fnt")
  108. fontType_ = FONT_BITMAP;
  109. SetMemoryUse(fontDataSize_);
  110. return true;
  111. }
  112. bool Font::SaveXML(Serializer& dest, int pointSize, bool usedGlyphs)
  113. {
  114. FontFace* fontFace = GetFace(pointSize);
  115. if (!fontFace)
  116. return false;
  117. PROFILE(FontSaveXML);
  118. SharedPtr<FontFace> packedFontFace;
  119. if (usedGlyphs)
  120. {
  121. // Save used glyphs only, try to pack them first
  122. packedFontFace = Pack(fontFace);
  123. if (packedFontFace)
  124. fontFace = packedFontFace;
  125. else
  126. return false;
  127. }
  128. SharedPtr<XMLFile> xml(new XMLFile(context_));
  129. XMLElement rootElem = xml->CreateRoot("font");
  130. // Information
  131. XMLElement childElem = rootElem.CreateChild("info");
  132. String fileName = GetFileName(GetName());
  133. childElem.SetAttribute("face", fileName);
  134. childElem.SetAttribute("size", String(pointSize));
  135. // Common
  136. childElem = rootElem.CreateChild("common");
  137. childElem.SetInt("lineHeight", fontFace->rowHeight_);
  138. unsigned pages = fontFace->textures_.Size();
  139. childElem.SetInt("pages", pages);
  140. // Construct the path to store the texture
  141. String pathName;
  142. File* file = dynamic_cast<File*>(&dest);
  143. if (file)
  144. // If serialize to file, use the file's path
  145. pathName = GetPath(file->GetName());
  146. else
  147. // Otherwise, use the font resource's path
  148. pathName = "Data/" + GetPath(GetName());
  149. // Pages
  150. childElem = rootElem.CreateChild("pages");
  151. for (unsigned i = 0; i < pages; ++i)
  152. {
  153. XMLElement pageElem = childElem.CreateChild("page");
  154. pageElem.SetInt("id", i);
  155. String texFileName = fileName + "_" + String(i) + ".png";
  156. pageElem.SetAttribute("file", texFileName);
  157. // Save the font face texture to image file
  158. SaveFaceTexture(fontFace->textures_[i], pathName + texFileName);
  159. }
  160. // Chars and kernings
  161. XMLElement charsElem = rootElem.CreateChild("chars");
  162. unsigned numGlyphs = fontFace->glyphs_.Size();
  163. charsElem.SetInt("count", numGlyphs);
  164. XMLElement kerningsElem;
  165. bool hasKerning = fontFace->hasKerning_;
  166. if (hasKerning)
  167. kerningsElem = rootElem.CreateChild("kernings");
  168. for (HashMap<unsigned, unsigned>::ConstIterator i = fontFace->glyphMapping_.Begin(); i != fontFace->glyphMapping_.End(); ++i)
  169. {
  170. // Char
  171. XMLElement charElem = charsElem.CreateChild("char");
  172. charElem.SetInt("id", i->first_);
  173. FontGlyph glyph = fontFace->glyphs_[i->second_];
  174. charElem.SetInt("x", glyph.x_);
  175. charElem.SetInt("y", glyph.y_);
  176. charElem.SetInt("width", glyph.width_);
  177. charElem.SetInt("height", glyph.height_);
  178. charElem.SetInt("xoffset", glyph.offsetX_);
  179. charElem.SetInt("yoffset", glyph.offsetY_);
  180. charElem.SetInt("xadvance", glyph.advanceX_);
  181. charElem.SetInt("page", glyph.page_);
  182. // Kerning
  183. if (hasKerning)
  184. {
  185. for (HashMap<unsigned, unsigned>::ConstIterator j = glyph.kerning_.Begin(); j != glyph.kerning_.End(); ++j)
  186. {
  187. // To conserve space, only write when amount is non zero
  188. if (j->second_ == 0)
  189. continue;
  190. XMLElement kerningElem = kerningsElem.CreateChild("kerning");
  191. kerningElem.SetInt("first", i->first_);
  192. kerningElem.SetInt("second", j->first_);
  193. kerningElem.SetInt("amount", j->second_);
  194. }
  195. }
  196. }
  197. return xml->Save(dest);
  198. }
  199. FontFace* Font::GetFace(int pointSize)
  200. {
  201. // In headless mode, always return null
  202. Graphics* graphics = GetSubsystem<Graphics>();
  203. if (!graphics)
  204. return 0;
  205. // For bitmap font type, always return the same font face provided by the font's bitmap file regardless of the actual requested point size
  206. if (fontType_ == FONT_BITMAP)
  207. pointSize = 0;
  208. else
  209. pointSize = Clamp(pointSize, MIN_POINT_SIZE, MAX_POINT_SIZE);
  210. HashMap<int, SharedPtr<FontFace> >::Iterator i = faces_.Find(pointSize);
  211. if (i != faces_.End())
  212. {
  213. if (!i->second_->IsDataLost())
  214. return i->second_;
  215. else
  216. {
  217. // Erase and reload face if texture data lost (OpenGL mode only)
  218. faces_.Erase(i);
  219. }
  220. }
  221. PROFILE(GetFontFace);
  222. switch (fontType_)
  223. {
  224. case FONT_FREETYPE:
  225. return GetFaceFreeType(pointSize);
  226. case FONT_BITMAP:
  227. return GetFaceBitmap(pointSize);
  228. default:
  229. return 0;
  230. }
  231. }
  232. void Font::ReleaseFaces()
  233. {
  234. faces_.Clear();
  235. }
  236. SharedPtr<Texture2D> Font::CreateFaceTexture()
  237. {
  238. SharedPtr<Texture2D> texture(new Texture2D(context_));
  239. texture->SetMipsToSkip(QUALITY_LOW, 0); // No quality reduction
  240. texture->SetNumLevels(1); // No mipmaps
  241. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  242. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  243. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  244. return texture;
  245. }
  246. SharedPtr<Texture2D> Font::LoadFaceTexture(SharedPtr<Image> image)
  247. {
  248. SharedPtr<Texture2D> texture = CreateFaceTexture();
  249. if (!texture->Load(image, true))
  250. {
  251. LOGERROR("Could not load texture from image resource");
  252. return SharedPtr<Texture2D>();
  253. }
  254. return texture;
  255. }
  256. FontFace* Font::GetFaceFreeType(int pointSize)
  257. {
  258. // Create & initialize FreeType library if it does not exist yet
  259. FreeTypeLibrary* freeType = GetSubsystem<FreeTypeLibrary>();
  260. if (!freeType)
  261. context_->RegisterSubsystem(freeType = new FreeTypeLibrary(context_));
  262. // Ensure the FreeType library is kept alive as long as TTF font resources exist
  263. freeType_ = freeType;
  264. UI* ui = GetSubsystem<UI>();
  265. int maxTextureSize = ui->GetMaxFontTextureSize();
  266. FT_Face face;
  267. FT_Error error;
  268. FT_Library library = freeType->GetLibrary();
  269. if (pointSize <= 0)
  270. {
  271. LOGERROR("Zero or negative point size");
  272. return 0;
  273. }
  274. if (!fontDataSize_)
  275. {
  276. LOGERROR("Could not create font face from zero size data");
  277. return 0;
  278. }
  279. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  280. if (error)
  281. {
  282. LOGERROR("Could not create font face");
  283. return 0;
  284. }
  285. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  286. if (error)
  287. {
  288. FT_Done_Face(face);
  289. LOGERROR("Could not set font point size " + String(pointSize));
  290. return 0;
  291. }
  292. SharedPtr<FontFace> newFace(new FontFace(this));
  293. newFace->face_ = face;
  294. FT_GlyphSlot slot = face->glyph;
  295. unsigned numGlyphs = 0;
  296. // Build glyph mapping
  297. FT_UInt glyphIndex;
  298. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  299. while (glyphIndex != 0)
  300. {
  301. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  302. newFace->glyphMapping_[charCode] = glyphIndex;
  303. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  304. }
  305. LOGDEBUGF("Font face %s (%dpt) has %d glyphs", GetFileName(GetName()).CString(), pointSize, numGlyphs);
  306. // Load each of the glyphs to see the sizes & store other information
  307. int maxWidth = 0;
  308. int maxHeight = 0;
  309. int loadMode = ui->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  310. int ascender = face->size->metrics.ascender >> 6;
  311. int descender = face->size->metrics.descender >> 6;
  312. // Check if the font's OS/2 info gives different (larger) values for ascender & descender
  313. TT_OS2* os2Info = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
  314. if (os2Info)
  315. {
  316. ascender = Max(ascender, os2Info->usWinAscent * face->size->metrics.y_ppem / face->units_per_EM);
  317. ascender = Max(ascender, os2Info->sTypoAscender * face->size->metrics.y_ppem / face->units_per_EM);
  318. descender = Max(descender, os2Info->usWinDescent * face->size->metrics.y_ppem / face->units_per_EM);
  319. descender = Max(descender, os2Info->sTypoDescender * face->size->metrics.y_ppem / face->units_per_EM);
  320. }
  321. // Store point size and row height. Use the maximum of ascender + descender, or the face's stored default row height
  322. newFace->pointSize_ = pointSize;
  323. newFace->rowHeight_ = Max(ascender + descender, face->size->metrics.height >> 6);
  324. newFace->glyphs_.Reserve(numGlyphs);
  325. for (unsigned i = 0; i < numGlyphs; ++i)
  326. {
  327. FontGlyph newGlyph;
  328. error = FT_Load_Glyph(face, i, loadMode);
  329. if (!error)
  330. {
  331. // Note: position within texture will be filled later
  332. newGlyph.width_ = (short)Max(slot->metrics.width >> 6, slot->bitmap.width);
  333. newGlyph.height_ = (short)Max(slot->metrics.height >> 6, slot->bitmap.rows);
  334. newGlyph.offsetX_ = (short)(slot->metrics.horiBearingX >> 6);
  335. newGlyph.offsetY_ = (short)(ascender - (slot->metrics.horiBearingY >> 6));
  336. newGlyph.advanceX_ = (short)(slot->metrics.horiAdvance >> 6);
  337. maxWidth = Max(maxWidth, newGlyph.width_);
  338. maxHeight = Max(maxHeight, newGlyph.height_);
  339. }
  340. else
  341. {
  342. newGlyph.width_ = 0;
  343. newGlyph.height_ = 0;
  344. newGlyph.offsetX_ = 0;
  345. newGlyph.offsetY_ = 0;
  346. newGlyph.advanceX_ = 0;
  347. }
  348. newFace->glyphs_.Push(newGlyph);
  349. }
  350. // Store kerning if face has kerning information
  351. if (FT_HAS_KERNING(face))
  352. {
  353. newFace->hasKerning_ = true;
  354. // Read kerning manually to be more efficient and avoid out of memory crash when use large font file, for example there
  355. // are 29354 glyphs in msyh.ttf
  356. FT_ULong tag = FT_MAKE_TAG('k', 'e', 'r', 'n');
  357. FT_ULong kerningTableSize = 0;
  358. FT_Error error = FT_Load_Sfnt_Table(face, tag, 0, NULL, &kerningTableSize);
  359. if (error)
  360. {
  361. LOGERROR("Could not get kerning table length");
  362. return 0;
  363. }
  364. SharedArrayPtr<unsigned char> kerningTable(new unsigned char[kerningTableSize]);
  365. error = FT_Load_Sfnt_Table(face, tag, 0, kerningTable, &kerningTableSize);
  366. if (error)
  367. {
  368. LOGERROR("Could not load kerning table");
  369. return 0;
  370. }
  371. // Convert big endian to little endian
  372. for (unsigned i = 0; i < kerningTableSize; i += 2)
  373. Swap(kerningTable[i], kerningTable[i + 1]);
  374. MemoryBuffer deserializer(kerningTable, kerningTableSize);
  375. unsigned short version = deserializer.ReadUShort();
  376. if (version == 0)
  377. {
  378. unsigned numKerningTables = deserializer.ReadUShort();
  379. for (unsigned i = 0; i < numKerningTables; ++i)
  380. {
  381. unsigned short version = deserializer.ReadUShort();
  382. unsigned short length = deserializer.ReadUShort();
  383. unsigned short coverage = deserializer.ReadUShort();
  384. if (version == 0 && coverage == 1)
  385. {
  386. unsigned numKerningPairs = deserializer.ReadUShort();
  387. // Skip searchRange, entrySelector and rangeShift
  388. deserializer.Seek(deserializer.GetPosition() + 3 * sizeof(unsigned short));
  389. for (unsigned j = 0; j < numKerningPairs; ++j)
  390. {
  391. unsigned leftIndex = deserializer.ReadUShort();
  392. unsigned rightIndex = deserializer.ReadUShort();
  393. short amount = (short)(deserializer.ReadShort() >> 6);
  394. if (leftIndex < numGlyphs && rightIndex < numGlyphs)
  395. newFace->glyphs_[leftIndex].kerning_[rightIndex] = amount;
  396. else
  397. LOGWARNING("Out of range glyph index in kerning information");
  398. }
  399. }
  400. else
  401. {
  402. // Kerning table contains information we do not support; skip and move to the next (length includes header)
  403. deserializer.Seek(deserializer.GetPosition() + length - 3 * sizeof(unsigned short));
  404. }
  405. }
  406. }
  407. else
  408. LOGWARNING("Can not read kerning information: not version 0");
  409. }
  410. // Now try to pack into the smallest possible texture. If face does not fit into one texture, enable dynamic mode where
  411. // glyphs are only created as necessary
  412. if (newFace->RenderAllGlyphs(maxTextureSize, maxTextureSize))
  413. {
  414. FT_Done_Face(face);
  415. newFace->face_ = 0;
  416. }
  417. else
  418. {
  419. if (ui->GetUseMutableGlyphs())
  420. newFace->SetupMutableGlyphs(maxTextureSize, maxTextureSize, maxWidth, maxHeight);
  421. else
  422. newFace->SetupNextTexture(maxTextureSize, maxTextureSize);
  423. }
  424. faces_[pointSize] = newFace;
  425. return newFace;
  426. }
  427. FontFace* Font::GetFaceBitmap(int pointSize)
  428. {
  429. SharedPtr<XMLFile> xmlReader(new XMLFile(context_));
  430. MemoryBuffer memoryBuffer(fontData_, fontDataSize_);
  431. if (!xmlReader->Load(memoryBuffer))
  432. {
  433. LOGERROR("Could not load XML file");
  434. return 0;
  435. }
  436. XMLElement root = xmlReader->GetRoot("font");
  437. if (root.IsNull())
  438. {
  439. LOGERROR("Could not find Font element");
  440. return 0;
  441. }
  442. XMLElement pagesElem = root.GetChild("pages");
  443. if (pagesElem.IsNull())
  444. {
  445. LOGERROR("Could not find Pages element");
  446. return 0;
  447. }
  448. SharedPtr<FontFace> newFace(new FontFace(this));
  449. XMLElement infoElem = root.GetChild("info");
  450. if (!infoElem.IsNull())
  451. newFace->pointSize_ = infoElem.GetInt("size");
  452. XMLElement commonElem = root.GetChild("common");
  453. newFace->rowHeight_ = commonElem.GetInt("lineHeight");
  454. unsigned pages = commonElem.GetInt("pages");
  455. newFace->textures_.Reserve(pages);
  456. ResourceCache* resourceCache = GetSubsystem<ResourceCache>();
  457. String fontPath = GetPath(GetName());
  458. unsigned totalTextureSize = 0;
  459. XMLElement pageElem = pagesElem.GetChild("page");
  460. for (unsigned i = 0; i < pages; ++i)
  461. {
  462. if (pageElem.IsNull())
  463. {
  464. LOGERROR("Could not find Page element for page: " + String(i));
  465. return 0;
  466. }
  467. // Assume the font image is in the same directory as the font description file
  468. String textureFile = fontPath + pageElem.GetAttribute("file");
  469. // Load texture manually to allow controlling the alpha channel mode
  470. SharedPtr<File> fontFile = resourceCache->GetFile(textureFile);
  471. SharedPtr<Image> fontImage(new Image(context_));
  472. if (!fontFile || !fontImage->Load(*fontFile))
  473. {
  474. LOGERROR("Failed to load font image file");
  475. return 0;
  476. }
  477. SharedPtr<Texture2D> texture = LoadFaceTexture(fontImage);
  478. if (!texture)
  479. return 0;
  480. newFace->textures_.Push(texture);
  481. totalTextureSize += fontImage->GetWidth() * fontImage->GetHeight() * fontImage->GetComponents();
  482. pageElem = pageElem.GetNext("page");
  483. }
  484. XMLElement charsElem = root.GetChild("chars");
  485. int count = charsElem.GetInt("count");
  486. newFace->glyphs_.Reserve(count);
  487. unsigned index = 0;
  488. XMLElement charElem = charsElem.GetChild("char");
  489. while (!charElem.IsNull())
  490. {
  491. int id = charElem.GetInt("id");
  492. FontGlyph glyph;
  493. glyph.x_ = charElem.GetInt("x");
  494. glyph.y_ = charElem.GetInt("y");
  495. glyph.width_ = charElem.GetInt("width");
  496. glyph.height_ = charElem.GetInt("height");
  497. glyph.offsetX_ = charElem.GetInt("xoffset");
  498. glyph.offsetY_ = charElem.GetInt("yoffset");
  499. glyph.advanceX_ = charElem.GetInt("xadvance");
  500. glyph.page_ = charElem.GetInt("page");
  501. newFace->glyphs_.Push(glyph);
  502. newFace->glyphMapping_[id] = index++;
  503. charElem = charElem.GetNext("char");
  504. }
  505. XMLElement kerningsElem = root.GetChild("kernings");
  506. if (kerningsElem.IsNull())
  507. newFace->hasKerning_ = false;
  508. else
  509. {
  510. XMLElement kerningElem = kerningsElem.GetChild("kerning");
  511. while (!kerningElem.IsNull())
  512. {
  513. int first = kerningElem.GetInt("first");
  514. HashMap<unsigned, unsigned>::Iterator i = newFace->glyphMapping_.Find(first);
  515. if (i != newFace->glyphMapping_.End())
  516. {
  517. int second = kerningElem.GetInt("second");
  518. int amount = kerningElem.GetInt("amount");
  519. FontGlyph& glyph = newFace->glyphs_[i->second_];
  520. glyph.kerning_[second] = amount;
  521. }
  522. kerningElem = kerningElem.GetNext("kerning");
  523. }
  524. }
  525. LOGDEBUGF("Bitmap font face %s has %d glyphs", GetFileName(GetName()).CString(), count);
  526. SetMemoryUse(GetMemoryUse() + totalTextureSize);
  527. faces_[pointSize] = newFace;
  528. return newFace;
  529. }
  530. unsigned Font::ConvertFormatToNumComponents(unsigned format)
  531. {
  532. if (format == Graphics::GetRGBAFormat())
  533. return 4;
  534. else if (format == Graphics::GetRGBFormat())
  535. return 3;
  536. else if (format == Graphics::GetLuminanceAlphaFormat())
  537. return 2;
  538. else
  539. return 1;
  540. }
  541. SharedPtr<FontFace> Font::Pack(FontFace* fontFace)
  542. {
  543. // Set parent font as null for the packed face so that it does not attempt to manage the font's total memory use
  544. SharedPtr<FontFace> packedFontFace(new FontFace((Font*)0));
  545. int maxTextureSize = GetSubsystem<UI>()->GetMaxFontTextureSize();
  546. // Clone properties
  547. packedFontFace->pointSize_ = fontFace->pointSize_;
  548. packedFontFace->rowHeight_ = fontFace->rowHeight_;
  549. packedFontFace->hasKerning_ = fontFace->hasKerning_;
  550. // Assume that format is the same for all textures and that bitmap font type may have more than one component
  551. unsigned components = ConvertFormatToNumComponents(fontFace->textures_[0]->GetFormat());
  552. // Save the existing textures as image resources
  553. Vector<SharedPtr<Image> > images(fontFace->textures_.Size());
  554. for (unsigned i = 0; i < fontFace->textures_.Size(); ++i)
  555. images[i] = SaveFaceTexture(fontFace->textures_[i]);
  556. // Reallocate used glyphs to new texture(s)
  557. unsigned page = 0;
  558. unsigned index = 0;
  559. unsigned startIndex = 0;
  560. HashMap<unsigned, unsigned>::ConstIterator startIter = fontFace->glyphMapping_.Begin();
  561. HashMap<unsigned, unsigned>::ConstIterator i;
  562. while (startIter != fontFace->glyphMapping_.End())
  563. {
  564. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxTextureSize, maxTextureSize);
  565. for (i = startIter; i != fontFace->glyphMapping_.End(); ++i)
  566. {
  567. FontGlyph glyph = fontFace->glyphs_[i->second_];
  568. if (!glyph.used_)
  569. continue;
  570. if (glyph.width_ && glyph.height_)
  571. {
  572. int x, y;
  573. // Reserve an empty border between glyphs for filtering
  574. if (allocator.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  575. {
  576. glyph.x_ = x;
  577. glyph.y_ = y;
  578. glyph.page_ = page;
  579. }
  580. else
  581. break;
  582. }
  583. packedFontFace->glyphs_.Push(glyph);
  584. packedFontFace->glyphMapping_[i->first_] = index++;
  585. }
  586. int texWidth = allocator.GetWidth();
  587. int texHeight = allocator.GetHeight();
  588. // Create the image for rendering the fonts
  589. SharedPtr<Image> image(new Image(context_));
  590. image->SetSize(texWidth, texHeight, components);
  591. // First clear the whole image
  592. unsigned char* imageData = image->GetData();
  593. for (int y = 0; y < texHeight; ++y)
  594. {
  595. unsigned char* dest = imageData + components * texWidth * y;
  596. memset(dest, 0, components * texWidth);
  597. }
  598. // Then render the glyphs into new image
  599. for (HashMap<unsigned, unsigned>::ConstIterator j = startIter; j != i; ++j)
  600. {
  601. FontGlyph glyph = fontFace->glyphs_[j->second_];
  602. if (!glyph.used_)
  603. continue;
  604. if (!glyph.width_ || !glyph.height_)
  605. {
  606. ++startIndex;
  607. continue;
  608. }
  609. FontGlyph packedGlyph = packedFontFace->glyphs_[startIndex++];
  610. Image* image = images[glyph.page_];
  611. unsigned char* source = image->GetData() + components * (image->GetWidth() * glyph.y_ + glyph.x_);
  612. unsigned char* destination = imageData + components * (texWidth * packedGlyph.y_ + packedGlyph.x_);
  613. for (int i = 0; i < glyph.height_; ++i)
  614. {
  615. memcpy(destination, source, components * glyph.width_);
  616. source += components * image->GetWidth();
  617. destination += components * texWidth;
  618. }
  619. }
  620. // Finally load image into the texture
  621. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  622. if (!texture)
  623. return SharedPtr<FontFace>();
  624. packedFontFace->textures_.Push(texture);
  625. ++page;
  626. startIter = i;
  627. assert(index == startIndex);
  628. }
  629. return packedFontFace;
  630. }
  631. SharedPtr<Image> Font::SaveFaceTexture(Texture2D* texture)
  632. {
  633. Image* image = new Image(context_);
  634. image->SetSize(texture->GetWidth(), texture->GetHeight(), ConvertFormatToNumComponents(texture->GetFormat()));
  635. if (!static_cast<Texture2D*>(texture)->GetData(0, image->GetData()))
  636. {
  637. delete image;
  638. LOGERROR("Could not save texture to image resource");
  639. return SharedPtr<Image>();
  640. }
  641. return SharedPtr<Image>(image);
  642. }
  643. bool Font::SaveFaceTexture(Texture2D* texture, const String& fileName)
  644. {
  645. SharedPtr<Image> image = SaveFaceTexture(texture);
  646. return image ? image->SavePNG(fileName) : false;
  647. }
  648. }