Font.cpp 28 KB

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