Font.cpp 26 KB

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