Font.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. //
  2. // Copyright (c) 2008-2013 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 "AreaAllocator.h"
  24. #include "Context.h"
  25. #include "Deserializer.h"
  26. #include "FileSystem.h"
  27. #include "Font.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 "XMLFile.h"
  35. #include <ft2build.h>
  36. #include FT_FREETYPE_H
  37. #include "DebugNew.h"
  38. namespace Urho3D
  39. {
  40. static const int MIN_POINT_SIZE = 1;
  41. static const int MAX_POINT_SIZE = 96;
  42. /// FreeType library subsystem.
  43. class FreeTypeLibrary : public Object
  44. {
  45. OBJECT(FreeTypeLibrary);
  46. public:
  47. /// Construct.
  48. FreeTypeLibrary(Context* context) :
  49. Object(context)
  50. {
  51. FT_Error error = FT_Init_FreeType(&library_);
  52. if (error)
  53. LOGERROR("Could not initialize FreeType library");
  54. }
  55. /// Destruct.
  56. virtual ~FreeTypeLibrary()
  57. {
  58. FT_Done_FreeType(library_);
  59. }
  60. FT_Library GetLibrary() const { return library_; }
  61. private:
  62. /// FreeType library.
  63. FT_Library library_;
  64. };
  65. FontGlyph::FontGlyph() :
  66. used_(false)
  67. {
  68. }
  69. FontFace::FontFace() :
  70. hasKerning_(false)
  71. {
  72. }
  73. FontFace::~FontFace()
  74. {
  75. }
  76. const FontGlyph* FontFace::GetGlyph(unsigned c) const
  77. {
  78. HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Find(c);
  79. if (i != glyphMapping_.End())
  80. {
  81. const FontGlyph& glyph = glyphs_[i->second_];
  82. glyph.used_ = true;
  83. return &glyph;
  84. }
  85. else
  86. return NULL;
  87. }
  88. short FontFace::GetKerning(unsigned c, unsigned d) const
  89. {
  90. if (!hasKerning_)
  91. return 0;
  92. if (c == '\n' || d == '\n')
  93. return 0;
  94. unsigned leftIndex = 0;
  95. unsigned rightIndex = 0;
  96. HashMap<unsigned, unsigned>::ConstIterator leftIt = glyphMapping_.Find(c);
  97. if (leftIt != glyphMapping_.End())
  98. leftIndex = leftIt->second_;
  99. else
  100. return 0;
  101. HashMap<unsigned, unsigned>::ConstIterator rightIt = glyphMapping_.Find(d);
  102. if (rightIt != glyphMapping_.End())
  103. rightIndex = rightIt->second_;
  104. else
  105. return 0;
  106. HashMap<unsigned, unsigned>::ConstIterator kerningIt = glyphs_[leftIndex].kerning_.Find(rightIndex);
  107. if (kerningIt != glyphs_[leftIndex].kerning_.End())
  108. return kerningIt->second_;
  109. else
  110. return 0;
  111. }
  112. bool FontFace::IsDataLost() const
  113. {
  114. for (unsigned i = 0; i < textures_.Size(); ++i)
  115. {
  116. if (textures_[i]->IsDataLost())
  117. return true;
  118. }
  119. return false;
  120. }
  121. OBJECTTYPESTATIC(FreeTypeLibrary);
  122. OBJECTTYPESTATIC(Font);
  123. Font::Font(Context* context) :
  124. Resource(context),
  125. fontDataSize_(0),
  126. fontType_(FONT_NONE)
  127. {
  128. }
  129. Font::~Font()
  130. {
  131. }
  132. void Font::RegisterObject(Context* context)
  133. {
  134. context->RegisterFactory<Font>();
  135. }
  136. bool Font::Load(Deserializer& source)
  137. {
  138. PROFILE(LoadFont);
  139. // In headless mode, do not actually load, just return success
  140. Graphics* graphics = GetSubsystem<Graphics>();
  141. if (!graphics)
  142. return true;
  143. faces_.Clear();
  144. fontDataSize_ = source.GetSize();
  145. if (fontDataSize_)
  146. {
  147. fontData_ = new unsigned char[fontDataSize_];
  148. if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
  149. return false;
  150. }
  151. else
  152. {
  153. fontData_.Reset();
  154. return false;
  155. }
  156. String ext = GetExtension(GetName()).ToLower();
  157. if (ext == ".ttf")
  158. fontType_ = FONT_TTF;
  159. else if (ext == ".xml" || ext == ".fnt")
  160. fontType_ = FONT_BITMAP;
  161. SetMemoryUse(fontDataSize_);
  162. return true;
  163. }
  164. bool Font::SaveXML(Serializer& dest, int pointSize, bool usedGlyphs)
  165. {
  166. const FontFace* fontFace = GetFace(pointSize);
  167. if (!fontFace)
  168. return false;
  169. PROFILE(FontSaveXML);
  170. SharedPtr<FontFace> packedFontFace;
  171. if (usedGlyphs)
  172. {
  173. // Save used glyphs only, try to pack them first
  174. packedFontFace = Pack(fontFace);
  175. if (packedFontFace)
  176. fontFace = packedFontFace;
  177. else
  178. return false;
  179. }
  180. SharedPtr<XMLFile> xml(new XMLFile(context_));
  181. XMLElement rootElem = xml->CreateRoot("font");
  182. // Information
  183. XMLElement childElem = rootElem.CreateChild("info");
  184. String fileName = GetFileName(GetName());
  185. childElem.SetAttribute("face", fileName);
  186. childElem.SetAttribute("size", String(pointSize));
  187. // Common
  188. childElem = rootElem.CreateChild("common");
  189. childElem.SetInt("lineHeight", fontFace->rowHeight_);
  190. unsigned pages = fontFace->textures_.Size();
  191. childElem.SetInt("pages", pages);
  192. // Construct the path to store the texture
  193. String pathName;
  194. File* file = dynamic_cast<File*>(&dest);
  195. if (file)
  196. // If serialize to file, use the file's path
  197. pathName = GetPath(file->GetName());
  198. else
  199. // Otherwise, use the font resource's path
  200. pathName = "Data/" + GetPath(GetName());
  201. // Pages
  202. childElem = rootElem.CreateChild("pages");
  203. for (unsigned i = 0; i < pages; ++i)
  204. {
  205. XMLElement pageElem = childElem.CreateChild("page");
  206. pageElem.SetInt("id", i);
  207. String texFileName = fileName + "_" + String(i) + ".png";
  208. pageElem.SetAttribute("file", texFileName);
  209. // Save the font face texture to image file
  210. SaveFaceTexture(fontFace->textures_[i], pathName + texFileName);
  211. }
  212. // Chars and kernings
  213. XMLElement charsElem = rootElem.CreateChild("chars");
  214. unsigned numGlyphs = fontFace->glyphs_.Size();
  215. charsElem.SetInt("count", numGlyphs);
  216. XMLElement kerningsElem;
  217. bool hasKerning = fontFace->hasKerning_;
  218. if (hasKerning)
  219. kerningsElem = rootElem.CreateChild("kernings");
  220. for (HashMap<unsigned, unsigned>::ConstIterator i = fontFace->glyphMapping_.Begin(); i != fontFace->glyphMapping_.End(); ++i)
  221. {
  222. // Char
  223. XMLElement charElem = charsElem.CreateChild("char");
  224. charElem.SetInt("id", i->first_);
  225. FontGlyph glyph = fontFace->glyphs_[i->second_];
  226. charElem.SetInt("x", glyph.x_);
  227. charElem.SetInt("y", glyph.y_);
  228. charElem.SetInt("width", glyph.width_);
  229. charElem.SetInt("height", glyph.height_);
  230. charElem.SetInt("xoffset", glyph.offsetX_);
  231. charElem.SetInt("yoffset", glyph.offsetY_);
  232. charElem.SetInt("xadvance", glyph.advanceX_);
  233. charElem.SetInt("page", glyph.page_);
  234. // Kerning
  235. if (hasKerning)
  236. {
  237. for (HashMap<unsigned, unsigned>::ConstIterator j = glyph.kerning_.Begin(); j != glyph.kerning_.End(); ++j)
  238. {
  239. // To conserve space, only write when amount is non zero
  240. if (j->second_ == 0)
  241. continue;
  242. XMLElement kerningElem = kerningsElem.CreateChild("kerning");
  243. kerningElem.SetInt("first", i->first_);
  244. kerningElem.SetInt("second", j->first_);
  245. kerningElem.SetInt("amount", j->second_);
  246. }
  247. }
  248. }
  249. return xml->Save(dest);
  250. }
  251. const FontFace* Font::GetFace(int pointSize)
  252. {
  253. // In headless mode, always return null
  254. Graphics* graphics = GetSubsystem<Graphics>();
  255. if (!graphics)
  256. return 0;
  257. // For bitmap font type, always return the same font face provided by the font's bitmap file regardless of the actual requested point size
  258. if (fontType_ == FONT_BITMAP)
  259. pointSize = 0;
  260. else
  261. pointSize = Clamp(pointSize, MIN_POINT_SIZE, MAX_POINT_SIZE);
  262. HashMap<int, SharedPtr<FontFace> >::Iterator i = faces_.Find(pointSize);
  263. if (i != faces_.End())
  264. {
  265. if (!i->second_->IsDataLost())
  266. return i->second_;
  267. else
  268. {
  269. // Erase and reload face if texture data lost (OpenGL mode only)
  270. faces_.Erase(i);
  271. }
  272. }
  273. PROFILE(GetFontFace);
  274. switch (fontType_)
  275. {
  276. case FONT_TTF:
  277. return GetFaceTTF(pointSize);
  278. case FONT_BITMAP:
  279. return GetFaceBitmap(pointSize);
  280. default:
  281. return 0;
  282. }
  283. }
  284. const FontFace* Font::GetFaceTTF(int pointSize)
  285. {
  286. // Create & initialize FreeType library if it does not exist yet
  287. FreeTypeLibrary* freeType = GetSubsystem<FreeTypeLibrary>();
  288. if (!freeType)
  289. context_->RegisterSubsystem(freeType = new FreeTypeLibrary(context_));
  290. FT_Face face;
  291. FT_Error error;
  292. FT_Library library = freeType->GetLibrary();
  293. if (pointSize <= 0)
  294. {
  295. LOGERROR("Zero or negative point size");
  296. return 0;
  297. }
  298. if (!fontDataSize_)
  299. {
  300. LOGERROR("Font not loaded");
  301. return 0;
  302. }
  303. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  304. if (error)
  305. {
  306. LOGERROR("Could not create font face");
  307. return 0;
  308. }
  309. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  310. if (error)
  311. {
  312. FT_Done_Face(face);
  313. LOGERROR("Could not set font point size " + String(pointSize));
  314. return 0;
  315. }
  316. SharedPtr<FontFace> newFace(new FontFace());
  317. FT_GlyphSlot slot = face->glyph;
  318. unsigned numGlyphs = 0;
  319. // Build glyph mapping
  320. FT_UInt glyphIndex;
  321. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  322. while (glyphIndex != 0)
  323. {
  324. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  325. newFace->glyphMapping_[charCode] = glyphIndex;
  326. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  327. }
  328. LOGDEBUG("Font face has " + String(numGlyphs) + " glyphs");
  329. // Load each of the glyphs to see the sizes & store other information
  330. int maxHeight = 0;
  331. FT_Pos ascender = face->size->metrics.ascender;
  332. newFace->glyphs_.Reserve(numGlyphs);
  333. for (unsigned i = 0; i < numGlyphs; ++i)
  334. {
  335. FontGlyph newGlyph;
  336. error = FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  337. if (!error)
  338. {
  339. // Note: position within texture will be filled later
  340. newGlyph.width_ = (short)((slot->metrics.width) >> 6);
  341. newGlyph.height_ = (short)((slot->metrics.height) >> 6);
  342. newGlyph.offsetX_ = (short)((slot->metrics.horiBearingX) >> 6);
  343. newGlyph.offsetY_ = (short)((ascender - slot->metrics.horiBearingY) >> 6);
  344. newGlyph.advanceX_ = (short)((slot->metrics.horiAdvance) >> 6);
  345. maxHeight = Max(maxHeight, newGlyph.height_);
  346. }
  347. else
  348. {
  349. newGlyph.width_ = 0;
  350. newGlyph.height_ = 0;
  351. newGlyph.offsetX_ = 0;
  352. newGlyph.offsetY_ = 0;
  353. newGlyph.advanceX_ = 0;
  354. }
  355. newFace->glyphs_.Push(newGlyph);
  356. }
  357. // Store kerning if face has kerning information
  358. if (FT_HAS_KERNING(face))
  359. {
  360. newFace->hasKerning_ = true;
  361. for (unsigned i = 0; i < numGlyphs; ++i)
  362. {
  363. for (unsigned j = 0; j < numGlyphs; ++j)
  364. {
  365. FT_Vector vector;
  366. FT_Get_Kerning(face, i, j, FT_KERNING_DEFAULT, &vector);
  367. newFace->glyphs_[i].kerning_[j] = (short)(vector.x >> 6);
  368. }
  369. }
  370. }
  371. // Store point size and the height of a row. Use the height of the tallest font if taller than the specified row height
  372. newFace->pointSize_ = pointSize;
  373. newFace->rowHeight_ = Max((face->size->metrics.height + 63) >> 6, maxHeight);
  374. // Now try to pack into the smallest possible texture(s)
  375. Vector<SharedPtr<Image> > images;
  376. unsigned totalTextureSize = 0;
  377. unsigned page = 0;
  378. unsigned startIndex = 0;
  379. unsigned index;
  380. unsigned sumMaxOpacity = 0;
  381. unsigned samples = 0;
  382. while (startIndex < numGlyphs)
  383. {
  384. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MAX_SIZE, FONT_TEXTURE_MAX_SIZE);
  385. for (index = startIndex; index < numGlyphs; ++index)
  386. {
  387. if (newFace->glyphs_[index].width_ && newFace->glyphs_[index].height_)
  388. {
  389. int x, y;
  390. // Reserve an empty border between glyphs for filtering
  391. if (allocator.Allocate(newFace->glyphs_[index].width_ + 1, newFace->glyphs_[index].height_ + 1, x, y))
  392. {
  393. newFace->glyphs_[index].x_ = x;
  394. newFace->glyphs_[index].y_ = y;
  395. newFace->glyphs_[index].page_ = page;
  396. }
  397. else
  398. break;
  399. }
  400. else
  401. {
  402. newFace->glyphs_[index].x_ = 0;
  403. newFace->glyphs_[index].y_ = 0;
  404. newFace->glyphs_[index].page_ = 0;
  405. }
  406. }
  407. int texWidth = allocator.GetWidth();
  408. int texHeight = allocator.GetHeight();
  409. // Create the image for rendering the fonts
  410. SharedPtr<Image> image(new Image(context_));
  411. images.Push(image);
  412. image->SetSize(texWidth, texHeight, 1);
  413. // First clear the whole image
  414. unsigned char* imageData = image->GetData();
  415. for (int y = 0; y < texHeight; ++y)
  416. {
  417. unsigned char* dest = imageData + texWidth * y;
  418. memset(dest, 0, texWidth);
  419. }
  420. // Render glyphs into texture, and find out a scaling value in case font uses less than full opacity (thin outlines)
  421. for (unsigned i = startIndex; i < index; ++i)
  422. {
  423. if (!newFace->glyphs_[i].width_ || !newFace->glyphs_[i].height_)
  424. continue;
  425. FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  426. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  427. unsigned char glyphOpacity = 0;
  428. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  429. {
  430. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  431. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  432. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  433. {
  434. dest[x] = src[x];
  435. glyphOpacity = Max(glyphOpacity, src[x]);
  436. }
  437. }
  438. if (glyphOpacity)
  439. {
  440. sumMaxOpacity += glyphOpacity;
  441. ++samples;
  442. }
  443. }
  444. ++page;
  445. startIndex = index;
  446. }
  447. // Clamp the minimum possible value to avoid overbrightening
  448. unsigned char avgMaxOpacity = 255;
  449. if (samples)
  450. avgMaxOpacity = Max(sumMaxOpacity / samples, 128);
  451. if (avgMaxOpacity < 255)
  452. {
  453. // Apply the scaling value if necessary
  454. float scale = 255.0f / avgMaxOpacity;
  455. for (unsigned i = 0; i < numGlyphs; ++i)
  456. {
  457. Image* image = images[newFace->glyphs_[i].page_];
  458. unsigned char* imageData = image->GetData();
  459. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  460. {
  461. unsigned char* dest = imageData + image->GetWidth() * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  462. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  463. {
  464. int pixel = dest[x];
  465. dest[x] = Min((int)(pixel * scale), 255);
  466. }
  467. }
  468. }
  469. }
  470. // Create the texture and load the image into it
  471. for (Vector<SharedPtr<Image> >::ConstIterator i = images.Begin(); i != images.End(); ++i)
  472. {
  473. int texWidth = i->Get()->GetWidth();
  474. int texHeight = i->Get()->GetHeight();
  475. SharedPtr<Texture> texture = LoadFaceTexture(*i);
  476. if (!texture)
  477. return 0;
  478. newFace->textures_.Push(texture);
  479. totalTextureSize += texWidth * texHeight;
  480. }
  481. FT_Done_Face(face);
  482. SetMemoryUse(GetMemoryUse() + totalTextureSize);
  483. faces_[pointSize] = newFace;
  484. return newFace;
  485. }
  486. const FontFace* Font::GetFaceBitmap(int pointSize)
  487. {
  488. SharedPtr<XMLFile> xmlReader(new XMLFile(context_));
  489. MemoryBuffer memoryBuffer(fontData_, fontDataSize_);
  490. if (!xmlReader->Load(memoryBuffer))
  491. {
  492. LOGERROR("Could not load XML file");
  493. return 0;
  494. }
  495. XMLElement root = xmlReader->GetRoot("font");
  496. if (root.IsNull())
  497. {
  498. LOGERROR("Could not find Font element");
  499. return 0;
  500. }
  501. XMLElement pagesElem = root.GetChild("pages");
  502. if (pagesElem.IsNull())
  503. {
  504. LOGERROR("Could not find Pages element");
  505. return 0;
  506. }
  507. SharedPtr<FontFace> newFace(new FontFace());
  508. XMLElement infoElem = root.GetChild("info");
  509. if (!infoElem.IsNull())
  510. newFace->pointSize_ = infoElem.GetInt("size");
  511. XMLElement commonElem = root.GetChild("common");
  512. newFace->rowHeight_ = commonElem.GetInt("lineHeight");
  513. unsigned pages = commonElem.GetInt("pages");
  514. newFace->textures_.Reserve(pages);
  515. ResourceCache* resourceCache = GetSubsystem<ResourceCache>();
  516. String fontPath = GetPath(GetName());
  517. unsigned totalTextureSize = 0;
  518. XMLElement pageElem = pagesElem.GetChild("page");
  519. for (unsigned i = 0; i < pages; ++i)
  520. {
  521. if (pageElem.IsNull())
  522. {
  523. LOGERROR("Could not find Page element for page: " + String(i));
  524. return 0;
  525. }
  526. // Assume the font image is in the same directory as the font description file
  527. String textureFile = fontPath + pageElem.GetAttribute("file");
  528. // Load texture manually to allow controlling the alpha channel mode
  529. SharedPtr<File> fontFile = resourceCache->GetFile(textureFile);
  530. SharedPtr<Image> fontImage(new Image(context_));
  531. if (!fontFile || !fontImage->Load(*fontFile))
  532. {
  533. LOGERROR("Failed to load font image file");
  534. return 0;
  535. }
  536. SharedPtr<Texture> texture = LoadFaceTexture(fontImage);
  537. if (!texture)
  538. return 0;
  539. newFace->textures_.Push(texture);
  540. totalTextureSize += fontImage->GetWidth() * fontImage->GetHeight() * fontImage->GetComponents();
  541. pageElem = pageElem.GetNext("page");
  542. }
  543. XMLElement charsElem = root.GetChild("chars");
  544. int count = charsElem.GetInt("count");
  545. newFace->glyphs_.Reserve(count);
  546. unsigned index = 0;
  547. XMLElement charElem = charsElem.GetChild("char");
  548. while (!charElem.IsNull())
  549. {
  550. int id = charElem.GetInt("id");
  551. FontGlyph glyph;
  552. glyph.x_ = charElem.GetInt("x");
  553. glyph.y_ = charElem.GetInt("y");
  554. glyph.width_ = charElem.GetInt("width");
  555. glyph.height_ = charElem.GetInt("height");
  556. glyph.offsetX_ = charElem.GetInt("xoffset");
  557. glyph.offsetY_ = charElem.GetInt("yoffset");
  558. glyph.advanceX_ = charElem.GetInt("xadvance");
  559. glyph.page_ = charElem.GetInt("page");
  560. newFace->glyphs_.Push(glyph);
  561. newFace->glyphMapping_[id] = index++;
  562. charElem = charElem.GetNext("char");
  563. }
  564. XMLElement kerningsElem = root.GetChild("kernings");
  565. if (kerningsElem.IsNull())
  566. newFace->hasKerning_ = false;
  567. else
  568. {
  569. XMLElement kerningElem = kerningsElem.GetChild("kerning");
  570. while (!kerningElem.IsNull())
  571. {
  572. int first = kerningElem.GetInt("first");
  573. HashMap<unsigned, unsigned>::Iterator i = newFace->glyphMapping_.Find(first);
  574. if (i != newFace->glyphMapping_.End())
  575. {
  576. int second = kerningElem.GetInt("second");
  577. int amount = kerningElem.GetInt("amount");
  578. FontGlyph& glyph = newFace->glyphs_[i->second_];
  579. glyph.kerning_[second] = amount;
  580. }
  581. kerningElem = kerningElem.GetNext("kerning");
  582. }
  583. }
  584. SetMemoryUse(GetMemoryUse() + totalTextureSize);
  585. faces_[pointSize] = newFace;
  586. return newFace;
  587. }
  588. unsigned Font::ConvertFormatToNumComponents(unsigned format)
  589. {
  590. if (format == Graphics::GetRGBAFormat())
  591. return 4;
  592. else if (format == Graphics::GetRGBFormat())
  593. return 3;
  594. else if (format == Graphics::GetLuminanceAlphaFormat())
  595. return 2;
  596. else
  597. return 1;
  598. }
  599. SharedPtr<FontFace> Font::Pack(const FontFace* fontFace)
  600. {
  601. SharedPtr<FontFace> packedFontFace(new FontFace());
  602. // Clone properties
  603. packedFontFace->pointSize_ = fontFace->pointSize_;
  604. packedFontFace->rowHeight_ = fontFace->rowHeight_;
  605. packedFontFace->hasKerning_ = fontFace->hasKerning_;
  606. // Assume that format is the same for all textures and that bitmap font type may have more than one component
  607. unsigned components = ConvertFormatToNumComponents(fontFace->textures_[0]->GetFormat());
  608. // Save the existing textures as image resources
  609. Vector<SharedPtr<Image> > images(fontFace->textures_.Size());
  610. for (unsigned i = 0; i < fontFace->textures_.Size(); ++i)
  611. images[i] = SaveFaceTexture(fontFace->textures_[i]);
  612. // Reallocate used glyphs to new texture(s)
  613. unsigned page = 0;
  614. unsigned index = 0;
  615. unsigned startIndex = 0;
  616. HashMap<unsigned, unsigned>::ConstIterator startIter = fontFace->glyphMapping_.Begin();
  617. HashMap<unsigned, unsigned>::ConstIterator i;
  618. while (startIter != fontFace->glyphMapping_.End())
  619. {
  620. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MAX_SIZE, FONT_TEXTURE_MAX_SIZE);
  621. for (i = startIter; i != fontFace->glyphMapping_.End(); ++i)
  622. {
  623. FontGlyph glyph = fontFace->glyphs_[i->second_];
  624. if (!glyph.used_)
  625. continue;
  626. if (glyph.width_ && glyph.height_)
  627. {
  628. int x, y;
  629. // Reserve an empty border between glyphs for filtering
  630. if (allocator.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  631. {
  632. glyph.x_ = x;
  633. glyph.y_ = y;
  634. glyph.page_ = page;
  635. }
  636. else
  637. break;
  638. }
  639. packedFontFace->glyphs_.Push(glyph);
  640. packedFontFace->glyphMapping_[i->first_] = index++;
  641. }
  642. int texWidth = allocator.GetWidth();
  643. int texHeight = allocator.GetHeight();
  644. // Create the image for rendering the fonts
  645. SharedPtr<Image> image(new Image(context_));
  646. image->SetSize(texWidth, texHeight, components);
  647. // First clear the whole image
  648. unsigned char* imageData = image->GetData();
  649. for (int y = 0; y < texHeight; ++y)
  650. {
  651. unsigned char* dest = imageData + components * texWidth * y;
  652. memset(dest, 0, components * texWidth);
  653. }
  654. // Then render the glyphs into new image
  655. for (HashMap<unsigned, unsigned>::ConstIterator j = startIter; j != i; ++j)
  656. {
  657. FontGlyph glyph = fontFace->glyphs_[j->second_];
  658. if (!glyph.used_)
  659. continue;
  660. if (!glyph.width_ || !glyph.height_)
  661. {
  662. ++startIndex;
  663. continue;
  664. }
  665. FontGlyph packedGlyph = packedFontFace->glyphs_[startIndex++];
  666. Image* image = images[glyph.page_];
  667. unsigned char* source = image->GetData() + components * (image->GetWidth() * glyph.y_ + glyph.x_);
  668. unsigned char* destination = imageData + components * (texWidth * packedGlyph.y_ + packedGlyph.x_);
  669. for (int i = 0; i < glyph.height_; ++i)
  670. {
  671. memcpy(destination, source, components * glyph.width_);
  672. source += components * image->GetWidth();
  673. destination += components * texWidth;
  674. }
  675. }
  676. // Finally load image into the texture
  677. SharedPtr<Texture> texture = LoadFaceTexture(image);
  678. if (!texture)
  679. return SharedPtr<FontFace>();
  680. packedFontFace->textures_.Push(texture);
  681. ++page;
  682. startIter = i;
  683. assert(index == startIndex);
  684. }
  685. return packedFontFace;
  686. }
  687. SharedPtr<Texture> Font::LoadFaceTexture(SharedPtr<Image> image)
  688. {
  689. Texture2D* texture = new Texture2D(context_);
  690. texture->SetNumLevels(1); // No mipmaps
  691. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  692. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  693. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  694. if (!texture->Load(image, true))
  695. {
  696. delete texture;
  697. LOGERROR("Could not load texture from image resource");
  698. return SharedPtr<Texture>();
  699. }
  700. return SharedPtr<Texture>(texture);
  701. }
  702. SharedPtr<Image> Font::SaveFaceTexture(Texture* texture)
  703. {
  704. Image* image = new Image(context_);
  705. image->SetSize(texture->GetWidth(), texture->GetHeight(), ConvertFormatToNumComponents(texture->GetFormat()));
  706. if (!static_cast<Texture2D*>(texture)->GetData(0, image->GetData()))
  707. {
  708. delete image;
  709. LOGERROR("Could not save texture to image resource");
  710. return SharedPtr<Image>();
  711. }
  712. return SharedPtr<Image>(image);
  713. }
  714. bool Font::SaveFaceTexture(Texture* texture, const String& fileName)
  715. {
  716. SharedPtr<Image> image = SaveFaceTexture(texture);
  717. return image ? image->SavePNG(fileName) : false;
  718. }
  719. }