Font.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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 "Context.h"
  24. #include "Deserializer.h"
  25. #include "FileSystem.h"
  26. #include "Font.h"
  27. #include "Graphics.h"
  28. #include "Log.h"
  29. #include "MemoryBuffer.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "StringUtils.h"
  33. #include "Texture2D.h"
  34. #include "UI.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. MutableGlyph::MutableGlyph() :
  67. glyphIndex_(M_MAX_UNSIGNED)
  68. {
  69. }
  70. FontGlyph::FontGlyph() :
  71. used_(false),
  72. page_(M_MAX_UNSIGNED)
  73. {
  74. }
  75. FontFace::FontFace(Font* font) :
  76. font_(font),
  77. face_(0),
  78. hasKerning_(false),
  79. bitmapSize_(0)
  80. {
  81. }
  82. FontFace::~FontFace()
  83. {
  84. if (face_)
  85. {
  86. FT_Done_Face((FT_Face)face_);
  87. face_ = 0;
  88. }
  89. if (font_)
  90. {
  91. // When a face is unloaded, deduct the used texture data size from the parent font
  92. unsigned totalTextureSize = 0;
  93. for (unsigned i = 0; i < textures_.Size(); ++i)
  94. totalTextureSize += textures_[i]->GetWidth() * textures_[i]->GetHeight();
  95. font_->SetMemoryUse(font_->GetMemoryUse() - totalTextureSize);
  96. }
  97. for (List<MutableGlyph*>::Iterator i = mutableGlyphs_.Begin(); i != mutableGlyphs_.End(); ++i)
  98. delete *i;
  99. mutableGlyphs_.Clear();
  100. }
  101. const FontGlyph* FontFace::GetGlyph(unsigned c)
  102. {
  103. HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Find(c);
  104. if (i != glyphMapping_.End())
  105. {
  106. FontGlyph& glyph = glyphs_[i->second_];
  107. // Render glyph if not yet resident in a page texture
  108. if (glyph.page_ == M_MAX_UNSIGNED)
  109. RenderGlyph(i->second_);
  110. // If mutable glyphs in use, move to the front of the list
  111. if (mutableGlyphs_.Size() && glyph.iterator_ != mutableGlyphs_.End())
  112. {
  113. MutableGlyph* mutableGlyph = *glyph.iterator_;
  114. mutableGlyphs_.Erase(glyph.iterator_);
  115. mutableGlyphs_.PushFront(mutableGlyph);
  116. glyph.iterator_ = mutableGlyphs_.Begin();
  117. }
  118. glyph.used_ = true;
  119. return &glyph;
  120. }
  121. else
  122. return 0;
  123. }
  124. short FontFace::GetKerning(unsigned c, unsigned d) const
  125. {
  126. if (!hasKerning_)
  127. return 0;
  128. if (c == '\n' || d == '\n')
  129. return 0;
  130. unsigned leftIndex = 0;
  131. unsigned rightIndex = 0;
  132. HashMap<unsigned, unsigned>::ConstIterator leftIt = glyphMapping_.Find(c);
  133. if (leftIt != glyphMapping_.End())
  134. leftIndex = leftIt->second_;
  135. else
  136. return 0;
  137. HashMap<unsigned, unsigned>::ConstIterator rightIt = glyphMapping_.Find(d);
  138. if (rightIt != glyphMapping_.End())
  139. rightIndex = rightIt->second_;
  140. else
  141. return 0;
  142. HashMap<unsigned, unsigned>::ConstIterator kerningIt = glyphs_[leftIndex].kerning_.Find(rightIndex);
  143. if (kerningIt != glyphs_[leftIndex].kerning_.End())
  144. return kerningIt->second_;
  145. else
  146. return 0;
  147. }
  148. bool FontFace::IsDataLost() const
  149. {
  150. for (unsigned i = 0; i < textures_.Size(); ++i)
  151. {
  152. if (textures_[i]->IsDataLost())
  153. return true;
  154. }
  155. return false;
  156. }
  157. bool FontFace::RenderAllGlyphs(int maxWidth, int maxHeight)
  158. {
  159. assert(font_ && face_ && textures_.Empty());
  160. allocator_ = AreaAllocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxWidth, maxHeight);
  161. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  162. {
  163. if (glyphs_[i].width_ && glyphs_[i].height_)
  164. {
  165. int x, y;
  166. // Reserve an empty border between glyphs for filtering
  167. if (allocator_.Allocate(glyphs_[i].width_ + 1, glyphs_[i].height_ + 1, x, y))
  168. {
  169. glyphs_[i].x_ = x;
  170. glyphs_[i].y_ = y;
  171. glyphs_[i].page_ = 0;
  172. }
  173. else
  174. {
  175. // When allocation fails, reset the page of all glyphs allocated so far
  176. for (unsigned j = 0; j <= i; ++j)
  177. glyphs_[j].page_ = M_MAX_UNSIGNED;
  178. return false;
  179. }
  180. }
  181. else
  182. {
  183. glyphs_[i].x_ = 0;
  184. glyphs_[i].y_ = 0;
  185. glyphs_[i].page_ = 0;
  186. }
  187. }
  188. // Create image for rendering all the glyphs, clear to black
  189. SharedPtr<Image> image(new Image(font_->GetContext()));
  190. image->SetSize(allocator_.GetWidth(), allocator_.GetHeight(), 1);
  191. unsigned char* imageData = image->GetData();
  192. memset(imageData, 0, image->GetWidth() * image->GetHeight());
  193. // Render glyphs
  194. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  195. RenderGlyphBitmap(i, imageData + glyphs_[i].y_ * image->GetWidth() + glyphs_[i].x_, image->GetWidth());
  196. // Load image into a texture, increment memory usage of the parent font
  197. SharedPtr<Texture2D> texture = font_->LoadFaceTexture(image);
  198. if (!texture)
  199. {
  200. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  201. glyphs_[i].page_ = M_MAX_UNSIGNED;
  202. return false;
  203. }
  204. textures_.Push(texture);
  205. font_->SetMemoryUse(font_->GetMemoryUse() + image->GetWidth() * image->GetHeight());
  206. LOGDEBUG(ToString("Font face %s (%dpt) uses a static page texture of size %dx%d", GetFileName(font_->GetName()).CString(), pointSize_,
  207. texture->GetWidth(), texture->GetHeight()));
  208. return true;
  209. }
  210. void FontFace::RenderGlyph(unsigned index)
  211. {
  212. assert(font_ && face_);
  213. FontGlyph& glyph = glyphs_[index];
  214. // If glyph is empty, just set the current page
  215. if (!glyph.width_ || !glyph.height_)
  216. {
  217. glyph.x_ = 0;
  218. glyph.y_ = 0;
  219. glyph.page_ = textures_.Size() - 1;
  220. return;
  221. }
  222. if (!mutableGlyphs_.Size())
  223. {
  224. // Not using mutable glyphs: try to allocate from current page, reserve next page if fails
  225. int x, y;
  226. if (!allocator_.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  227. {
  228. SetupNextTexture(textures_[0]->GetWidth(), textures_[0]->GetHeight());
  229. // This always succeeds, as it is the first allocation of an empty page
  230. allocator_.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y);
  231. }
  232. glyph.x_ = x;
  233. glyph.y_ = y;
  234. glyph.page_ = textures_.Size() - 1;
  235. if (!bitmap_ || (int)bitmapSize_ < glyph.width_ * glyph.height_)
  236. {
  237. bitmapSize_ = glyph.width_ * glyph.height_;
  238. bitmap_ = new unsigned char[bitmapSize_];
  239. }
  240. RenderGlyphBitmap(index, bitmap_.Get(), glyph.width_);
  241. textures_.Back()->SetData(0, glyph.x_, glyph.y_, glyph.width_, glyph.height_, bitmap_.Get());
  242. }
  243. else
  244. {
  245. // Using mutable glyphs: overwrite the least recently used glyph
  246. List<MutableGlyph*>::Iterator it = --mutableGlyphs_.End();
  247. MutableGlyph* mutableGlyph = *it;
  248. if (mutableGlyph->glyphIndex_ != M_MAX_UNSIGNED)
  249. glyphs_[mutableGlyph->glyphIndex_].page_ = M_MAX_UNSIGNED;
  250. glyph.x_ = mutableGlyph->x_;
  251. glyph.y_ = mutableGlyph->y_;
  252. glyph.page_ = 0;
  253. glyph.iterator_ = it;
  254. mutableGlyph->glyphIndex_ = index;
  255. if (!bitmap_)
  256. {
  257. bitmapSize_ = cellWidth_ * cellHeight_;
  258. bitmap_ = new unsigned char[bitmapSize_];
  259. }
  260. // Clear the cell bitmap before rendering to ensure padding
  261. memset(bitmap_.Get(), 0, cellWidth_ * cellHeight_);
  262. RenderGlyphBitmap(index, bitmap_.Get(), cellWidth_);
  263. textures_[0]->SetData(0, glyph.x_, glyph.y_, cellWidth_, cellHeight_, bitmap_.Get());
  264. }
  265. }
  266. void FontFace::RenderGlyphBitmap(unsigned index, unsigned char* dest, unsigned pitch)
  267. {
  268. const FontGlyph& glyph = glyphs_[index];
  269. if (!glyph.width_ || !glyph.height_)
  270. return;
  271. FT_Face face = (FT_Face)face_;
  272. FT_GlyphSlot slot = face->glyph;
  273. FT_Load_Glyph(face, index, FT_LOAD_DEFAULT);
  274. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  275. if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO)
  276. {
  277. for (int y = 0; y < glyph.height_; ++y)
  278. {
  279. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  280. unsigned char* rowDest = dest + y * pitch;
  281. for (int x = 0; x < glyph.width_; ++x)
  282. rowDest[x] = (src[x >> 3] & (0x80 >> (x & 7))) ? 255 : 0;
  283. }
  284. }
  285. else
  286. {
  287. for (int y = 0; y < glyph.height_; ++y)
  288. {
  289. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  290. unsigned char* rowDest = dest + y * pitch;
  291. for (int x = 0; x < glyph.width_; ++x)
  292. rowDest[x] = src[x];
  293. }
  294. }
  295. }
  296. void FontFace::SetupNextTexture(int width, int height)
  297. {
  298. // If several dynamic textures are needed, use the maximum size to pack as many as possible to one texture
  299. allocator_ = AreaAllocator(width, height);
  300. SharedPtr<Texture2D> texture = font_->CreateFaceTexture();
  301. texture->SetSize(width, height, Graphics::GetAlphaFormat());
  302. SharedArrayPtr<unsigned char> emptyBitmap(new unsigned char[width * height]);
  303. memset(emptyBitmap.Get(), 0, width * height);
  304. texture->SetData(0, 0, 0, width, height, emptyBitmap.Get());
  305. textures_.Push(texture);
  306. font_->SetMemoryUse(font_->GetMemoryUse() + width * height);
  307. LOGDEBUG(ToString("Font face %s (%dpt) is using %d dynamic page textures of size %dx%d", GetFileName(font_->GetName()).CString(),
  308. pointSize_, textures_.Size(), width, height));
  309. }
  310. void FontFace::SetupMutableGlyphs(int textureWidth, int textureHeight, int maxWidth, int maxHeight)
  311. {
  312. assert(mutableGlyphs_.Empty());
  313. SetupNextTexture(textureWidth, textureHeight);
  314. cellWidth_ = maxWidth + 1;
  315. cellHeight_ = maxHeight + 1;
  316. // Allocate as many mutable glyphs as possible
  317. int x, y;
  318. while (allocator_.Allocate(cellWidth_, cellHeight_, x, y))
  319. {
  320. MutableGlyph* glyph = new MutableGlyph();
  321. glyph->x_ = x;
  322. glyph->y_ = y;
  323. mutableGlyphs_.Push(glyph);
  324. }
  325. LOGDEBUG(ToString("Font face %s (%dpt) is using %d mutable glyphs", GetFileName(font_->GetName()).CString(), pointSize_,
  326. mutableGlyphs_.Size()));
  327. }
  328. Font::Font(Context* context) :
  329. Resource(context),
  330. fontDataSize_(0),
  331. fontType_(FONT_NONE)
  332. {
  333. }
  334. Font::~Font()
  335. {
  336. // To ensure FreeType deallocates properly, first clear all faces, then release the raw font data
  337. faces_.Clear();
  338. fontData_.Reset();
  339. }
  340. void Font::RegisterObject(Context* context)
  341. {
  342. context->RegisterFactory<Font>();
  343. }
  344. bool Font::Load(Deserializer& source)
  345. {
  346. PROFILE(LoadFont);
  347. // In headless mode, do not actually load, just return success
  348. Graphics* graphics = GetSubsystem<Graphics>();
  349. if (!graphics)
  350. return true;
  351. faces_.Clear();
  352. fontDataSize_ = source.GetSize();
  353. if (fontDataSize_)
  354. {
  355. fontData_ = new unsigned char[fontDataSize_];
  356. if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
  357. return false;
  358. }
  359. else
  360. {
  361. fontData_.Reset();
  362. return false;
  363. }
  364. String ext = GetExtension(GetName());
  365. if (ext == ".ttf" || ext == ".otf" || ext == ".woff")
  366. fontType_ = FONT_FREETYPE;
  367. else if (ext == ".xml" || ext == ".fnt")
  368. fontType_ = FONT_BITMAP;
  369. SetMemoryUse(fontDataSize_);
  370. return true;
  371. }
  372. bool Font::SaveXML(Serializer& dest, int pointSize, bool usedGlyphs)
  373. {
  374. FontFace* fontFace = GetFace(pointSize);
  375. if (!fontFace)
  376. return false;
  377. PROFILE(FontSaveXML);
  378. SharedPtr<FontFace> packedFontFace;
  379. if (usedGlyphs)
  380. {
  381. // Save used glyphs only, try to pack them first
  382. packedFontFace = Pack(fontFace);
  383. if (packedFontFace)
  384. fontFace = packedFontFace;
  385. else
  386. return false;
  387. }
  388. SharedPtr<XMLFile> xml(new XMLFile(context_));
  389. XMLElement rootElem = xml->CreateRoot("font");
  390. // Information
  391. XMLElement childElem = rootElem.CreateChild("info");
  392. String fileName = GetFileName(GetName());
  393. childElem.SetAttribute("face", fileName);
  394. childElem.SetAttribute("size", String(pointSize));
  395. // Common
  396. childElem = rootElem.CreateChild("common");
  397. childElem.SetInt("lineHeight", fontFace->rowHeight_);
  398. unsigned pages = fontFace->textures_.Size();
  399. childElem.SetInt("pages", pages);
  400. // Construct the path to store the texture
  401. String pathName;
  402. File* file = dynamic_cast<File*>(&dest);
  403. if (file)
  404. // If serialize to file, use the file's path
  405. pathName = GetPath(file->GetName());
  406. else
  407. // Otherwise, use the font resource's path
  408. pathName = "Data/" + GetPath(GetName());
  409. // Pages
  410. childElem = rootElem.CreateChild("pages");
  411. for (unsigned i = 0; i < pages; ++i)
  412. {
  413. XMLElement pageElem = childElem.CreateChild("page");
  414. pageElem.SetInt("id", i);
  415. String texFileName = fileName + "_" + String(i) + ".png";
  416. pageElem.SetAttribute("file", texFileName);
  417. // Save the font face texture to image file
  418. SaveFaceTexture(fontFace->textures_[i], pathName + texFileName);
  419. }
  420. // Chars and kernings
  421. XMLElement charsElem = rootElem.CreateChild("chars");
  422. unsigned numGlyphs = fontFace->glyphs_.Size();
  423. charsElem.SetInt("count", numGlyphs);
  424. XMLElement kerningsElem;
  425. bool hasKerning = fontFace->hasKerning_;
  426. if (hasKerning)
  427. kerningsElem = rootElem.CreateChild("kernings");
  428. for (HashMap<unsigned, unsigned>::ConstIterator i = fontFace->glyphMapping_.Begin(); i != fontFace->glyphMapping_.End(); ++i)
  429. {
  430. // Char
  431. XMLElement charElem = charsElem.CreateChild("char");
  432. charElem.SetInt("id", i->first_);
  433. FontGlyph glyph = fontFace->glyphs_[i->second_];
  434. charElem.SetInt("x", glyph.x_);
  435. charElem.SetInt("y", glyph.y_);
  436. charElem.SetInt("width", glyph.width_);
  437. charElem.SetInt("height", glyph.height_);
  438. charElem.SetInt("xoffset", glyph.offsetX_);
  439. charElem.SetInt("yoffset", glyph.offsetY_);
  440. charElem.SetInt("xadvance", glyph.advanceX_);
  441. charElem.SetInt("page", glyph.page_);
  442. // Kerning
  443. if (hasKerning)
  444. {
  445. for (HashMap<unsigned, unsigned>::ConstIterator j = glyph.kerning_.Begin(); j != glyph.kerning_.End(); ++j)
  446. {
  447. // To conserve space, only write when amount is non zero
  448. if (j->second_ == 0)
  449. continue;
  450. XMLElement kerningElem = kerningsElem.CreateChild("kerning");
  451. kerningElem.SetInt("first", i->first_);
  452. kerningElem.SetInt("second", j->first_);
  453. kerningElem.SetInt("amount", j->second_);
  454. }
  455. }
  456. }
  457. return xml->Save(dest);
  458. }
  459. FontFace* Font::GetFace(int pointSize)
  460. {
  461. // In headless mode, always return null
  462. Graphics* graphics = GetSubsystem<Graphics>();
  463. if (!graphics)
  464. return 0;
  465. // For bitmap font type, always return the same font face provided by the font's bitmap file regardless of the actual requested point size
  466. if (fontType_ == FONT_BITMAP)
  467. pointSize = 0;
  468. else
  469. pointSize = Clamp(pointSize, MIN_POINT_SIZE, MAX_POINT_SIZE);
  470. HashMap<int, SharedPtr<FontFace> >::Iterator i = faces_.Find(pointSize);
  471. if (i != faces_.End())
  472. {
  473. if (!i->second_->IsDataLost())
  474. return i->second_;
  475. else
  476. {
  477. // Erase and reload face if texture data lost (OpenGL mode only)
  478. faces_.Erase(i);
  479. }
  480. }
  481. PROFILE(GetFontFace);
  482. switch (fontType_)
  483. {
  484. case FONT_FREETYPE:
  485. return GetFaceTTF(pointSize);
  486. case FONT_BITMAP:
  487. return GetFaceBitmap(pointSize);
  488. default:
  489. return 0;
  490. }
  491. }
  492. SharedPtr<Texture2D> Font::CreateFaceTexture()
  493. {
  494. SharedPtr<Texture2D> texture(new Texture2D(context_));
  495. texture->SetMipsToSkip(QUALITY_LOW, 0); // No quality reduction
  496. texture->SetNumLevels(1); // No mipmaps
  497. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  498. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  499. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  500. return texture;
  501. }
  502. SharedPtr<Texture2D> Font::LoadFaceTexture(SharedPtr<Image> image)
  503. {
  504. SharedPtr<Texture2D> texture = CreateFaceTexture();
  505. if (!texture->Load(image, true))
  506. {
  507. LOGERROR("Could not load texture from image resource");
  508. return SharedPtr<Texture2D>();
  509. }
  510. return texture;
  511. }
  512. FontFace* Font::GetFaceTTF(int pointSize)
  513. {
  514. // Create & initialize FreeType library if it does not exist yet
  515. FreeTypeLibrary* freeType = GetSubsystem<FreeTypeLibrary>();
  516. if (!freeType)
  517. context_->RegisterSubsystem(freeType = new FreeTypeLibrary(context_));
  518. // Ensure the FreeType library is kept alive as long as TTF font resources exist
  519. freeType_ = freeType;
  520. UI* ui = GetSubsystem<UI>();
  521. int maxTextureSize = ui->GetMaxFontTextureSize();
  522. FT_Face face;
  523. FT_Error error;
  524. FT_Library library = freeType->GetLibrary();
  525. if (pointSize <= 0)
  526. {
  527. LOGERROR("Zero or negative point size");
  528. return 0;
  529. }
  530. if (!fontDataSize_)
  531. {
  532. LOGERROR("Font not loaded");
  533. return 0;
  534. }
  535. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  536. if (error)
  537. {
  538. LOGERROR("Could not create font face");
  539. return 0;
  540. }
  541. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  542. if (error)
  543. {
  544. FT_Done_Face(face);
  545. LOGERROR("Could not set font point size " + String(pointSize));
  546. return 0;
  547. }
  548. SharedPtr<FontFace> newFace(new FontFace(this));
  549. newFace->face_ = face;
  550. FT_GlyphSlot slot = face->glyph;
  551. unsigned numGlyphs = 0;
  552. // Build glyph mapping
  553. FT_UInt glyphIndex;
  554. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  555. while (glyphIndex != 0)
  556. {
  557. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  558. newFace->glyphMapping_[charCode] = glyphIndex;
  559. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  560. }
  561. LOGDEBUG(ToString("Font face %s (%dpt) has %d glyphs", GetFileName(GetName()).CString(), pointSize, numGlyphs));
  562. // Load each of the glyphs to see the sizes & store other information
  563. int maxWidth = 0;
  564. int maxHeight = 0;
  565. FT_Pos ascender = face->size->metrics.ascender;
  566. newFace->glyphs_.Reserve(numGlyphs);
  567. for (unsigned i = 0; i < numGlyphs; ++i)
  568. {
  569. FontGlyph newGlyph;
  570. error = FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  571. if (!error)
  572. {
  573. // Note: position within texture will be filled later
  574. newGlyph.width_ = (short)((slot->metrics.width) >> 6);
  575. newGlyph.height_ = (short)((slot->metrics.height) >> 6);
  576. newGlyph.offsetX_ = (short)((slot->metrics.horiBearingX) >> 6);
  577. newGlyph.offsetY_ = (short)((ascender - slot->metrics.horiBearingY) >> 6);
  578. newGlyph.advanceX_ = (short)((slot->metrics.horiAdvance) >> 6);
  579. maxWidth = Max(maxWidth, newGlyph.width_);
  580. maxHeight = Max(maxHeight, newGlyph.height_);
  581. }
  582. else
  583. {
  584. newGlyph.width_ = 0;
  585. newGlyph.height_ = 0;
  586. newGlyph.offsetX_ = 0;
  587. newGlyph.offsetY_ = 0;
  588. newGlyph.advanceX_ = 0;
  589. }
  590. newFace->glyphs_.Push(newGlyph);
  591. }
  592. // Store kerning if face has kerning information
  593. if (FT_HAS_KERNING(face))
  594. {
  595. newFace->hasKerning_ = true;
  596. for (unsigned i = 0; i < numGlyphs; ++i)
  597. {
  598. for (unsigned j = 0; j < numGlyphs; ++j)
  599. {
  600. FT_Vector vector;
  601. FT_Get_Kerning(face, i, j, FT_KERNING_DEFAULT, &vector);
  602. newFace->glyphs_[i].kerning_[j] = (short)(vector.x >> 6);
  603. }
  604. }
  605. }
  606. // Store point size and the height of a row. Use the height of the tallest font if taller than the specified row height
  607. newFace->pointSize_ = pointSize;
  608. newFace->rowHeight_ = Max((face->size->metrics.height + 63) >> 6, maxHeight);
  609. // Now try to pack into the smallest possible texture. If face does not fit into one texture, enable dynamic mode where
  610. // glyphs are only created as necessary
  611. if (newFace->RenderAllGlyphs(maxTextureSize, maxTextureSize))
  612. {
  613. FT_Done_Face(face);
  614. newFace->face_ = 0;
  615. }
  616. else
  617. {
  618. if (ui->GetUseMutableGlyphs())
  619. newFace->SetupMutableGlyphs(maxTextureSize, maxTextureSize, maxWidth, maxHeight);
  620. else
  621. newFace->SetupNextTexture(maxTextureSize, maxTextureSize);
  622. }
  623. faces_[pointSize] = newFace;
  624. return newFace;
  625. }
  626. FontFace* Font::GetFaceBitmap(int pointSize)
  627. {
  628. SharedPtr<XMLFile> xmlReader(new XMLFile(context_));
  629. MemoryBuffer memoryBuffer(fontData_, fontDataSize_);
  630. if (!xmlReader->Load(memoryBuffer))
  631. {
  632. LOGERROR("Could not load XML file");
  633. return 0;
  634. }
  635. XMLElement root = xmlReader->GetRoot("font");
  636. if (root.IsNull())
  637. {
  638. LOGERROR("Could not find Font element");
  639. return 0;
  640. }
  641. XMLElement pagesElem = root.GetChild("pages");
  642. if (pagesElem.IsNull())
  643. {
  644. LOGERROR("Could not find Pages element");
  645. return 0;
  646. }
  647. SharedPtr<FontFace> newFace(new FontFace(this));
  648. XMLElement infoElem = root.GetChild("info");
  649. if (!infoElem.IsNull())
  650. newFace->pointSize_ = infoElem.GetInt("size");
  651. XMLElement commonElem = root.GetChild("common");
  652. newFace->rowHeight_ = commonElem.GetInt("lineHeight");
  653. unsigned pages = commonElem.GetInt("pages");
  654. newFace->textures_.Reserve(pages);
  655. ResourceCache* resourceCache = GetSubsystem<ResourceCache>();
  656. String fontPath = GetPath(GetName());
  657. unsigned totalTextureSize = 0;
  658. XMLElement pageElem = pagesElem.GetChild("page");
  659. for (unsigned i = 0; i < pages; ++i)
  660. {
  661. if (pageElem.IsNull())
  662. {
  663. LOGERROR("Could not find Page element for page: " + String(i));
  664. return 0;
  665. }
  666. // Assume the font image is in the same directory as the font description file
  667. String textureFile = fontPath + pageElem.GetAttribute("file");
  668. // Load texture manually to allow controlling the alpha channel mode
  669. SharedPtr<File> fontFile = resourceCache->GetFile(textureFile);
  670. SharedPtr<Image> fontImage(new Image(context_));
  671. if (!fontFile || !fontImage->Load(*fontFile))
  672. {
  673. LOGERROR("Failed to load font image file");
  674. return 0;
  675. }
  676. SharedPtr<Texture2D> texture = LoadFaceTexture(fontImage);
  677. if (!texture)
  678. return 0;
  679. newFace->textures_.Push(texture);
  680. totalTextureSize += fontImage->GetWidth() * fontImage->GetHeight() * fontImage->GetComponents();
  681. pageElem = pageElem.GetNext("page");
  682. }
  683. XMLElement charsElem = root.GetChild("chars");
  684. int count = charsElem.GetInt("count");
  685. newFace->glyphs_.Reserve(count);
  686. unsigned index = 0;
  687. XMLElement charElem = charsElem.GetChild("char");
  688. while (!charElem.IsNull())
  689. {
  690. int id = charElem.GetInt("id");
  691. FontGlyph glyph;
  692. glyph.x_ = charElem.GetInt("x");
  693. glyph.y_ = charElem.GetInt("y");
  694. glyph.width_ = charElem.GetInt("width");
  695. glyph.height_ = charElem.GetInt("height");
  696. glyph.offsetX_ = charElem.GetInt("xoffset");
  697. glyph.offsetY_ = charElem.GetInt("yoffset");
  698. glyph.advanceX_ = charElem.GetInt("xadvance");
  699. glyph.page_ = charElem.GetInt("page");
  700. newFace->glyphs_.Push(glyph);
  701. newFace->glyphMapping_[id] = index++;
  702. charElem = charElem.GetNext("char");
  703. }
  704. XMLElement kerningsElem = root.GetChild("kernings");
  705. if (kerningsElem.IsNull())
  706. newFace->hasKerning_ = false;
  707. else
  708. {
  709. XMLElement kerningElem = kerningsElem.GetChild("kerning");
  710. while (!kerningElem.IsNull())
  711. {
  712. int first = kerningElem.GetInt("first");
  713. HashMap<unsigned, unsigned>::Iterator i = newFace->glyphMapping_.Find(first);
  714. if (i != newFace->glyphMapping_.End())
  715. {
  716. int second = kerningElem.GetInt("second");
  717. int amount = kerningElem.GetInt("amount");
  718. FontGlyph& glyph = newFace->glyphs_[i->second_];
  719. glyph.kerning_[second] = amount;
  720. }
  721. kerningElem = kerningElem.GetNext("kerning");
  722. }
  723. }
  724. LOGDEBUG(ToString("Bitmap font face %s has %d glyphs", GetFileName(GetName()).CString(), count));
  725. SetMemoryUse(GetMemoryUse() + totalTextureSize);
  726. faces_[pointSize] = newFace;
  727. return newFace;
  728. }
  729. unsigned Font::ConvertFormatToNumComponents(unsigned format)
  730. {
  731. if (format == Graphics::GetRGBAFormat())
  732. return 4;
  733. else if (format == Graphics::GetRGBFormat())
  734. return 3;
  735. else if (format == Graphics::GetLuminanceAlphaFormat())
  736. return 2;
  737. else
  738. return 1;
  739. }
  740. SharedPtr<FontFace> Font::Pack(FontFace* fontFace)
  741. {
  742. // Set parent font as null for the packed face so that it does not attempt to manage the font's total memory use
  743. SharedPtr<FontFace> packedFontFace(new FontFace((Font*)0));
  744. int maxTextureSize = GetSubsystem<UI>()->GetMaxFontTextureSize();
  745. // Clone properties
  746. packedFontFace->pointSize_ = fontFace->pointSize_;
  747. packedFontFace->rowHeight_ = fontFace->rowHeight_;
  748. packedFontFace->hasKerning_ = fontFace->hasKerning_;
  749. // Assume that format is the same for all textures and that bitmap font type may have more than one component
  750. unsigned components = ConvertFormatToNumComponents(fontFace->textures_[0]->GetFormat());
  751. // Save the existing textures as image resources
  752. Vector<SharedPtr<Image> > images(fontFace->textures_.Size());
  753. for (unsigned i = 0; i < fontFace->textures_.Size(); ++i)
  754. images[i] = SaveFaceTexture(fontFace->textures_[i]);
  755. // Reallocate used glyphs to new texture(s)
  756. unsigned page = 0;
  757. unsigned index = 0;
  758. unsigned startIndex = 0;
  759. HashMap<unsigned, unsigned>::ConstIterator startIter = fontFace->glyphMapping_.Begin();
  760. HashMap<unsigned, unsigned>::ConstIterator i;
  761. while (startIter != fontFace->glyphMapping_.End())
  762. {
  763. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxTextureSize, maxTextureSize);
  764. for (i = startIter; i != fontFace->glyphMapping_.End(); ++i)
  765. {
  766. FontGlyph glyph = fontFace->glyphs_[i->second_];
  767. if (!glyph.used_)
  768. continue;
  769. if (glyph.width_ && glyph.height_)
  770. {
  771. int x, y;
  772. // Reserve an empty border between glyphs for filtering
  773. if (allocator.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  774. {
  775. glyph.x_ = x;
  776. glyph.y_ = y;
  777. glyph.page_ = page;
  778. }
  779. else
  780. break;
  781. }
  782. packedFontFace->glyphs_.Push(glyph);
  783. packedFontFace->glyphMapping_[i->first_] = index++;
  784. }
  785. int texWidth = allocator.GetWidth();
  786. int texHeight = allocator.GetHeight();
  787. // Create the image for rendering the fonts
  788. SharedPtr<Image> image(new Image(context_));
  789. image->SetSize(texWidth, texHeight, components);
  790. // First clear the whole image
  791. unsigned char* imageData = image->GetData();
  792. for (int y = 0; y < texHeight; ++y)
  793. {
  794. unsigned char* dest = imageData + components * texWidth * y;
  795. memset(dest, 0, components * texWidth);
  796. }
  797. // Then render the glyphs into new image
  798. for (HashMap<unsigned, unsigned>::ConstIterator j = startIter; j != i; ++j)
  799. {
  800. FontGlyph glyph = fontFace->glyphs_[j->second_];
  801. if (!glyph.used_)
  802. continue;
  803. if (!glyph.width_ || !glyph.height_)
  804. {
  805. ++startIndex;
  806. continue;
  807. }
  808. FontGlyph packedGlyph = packedFontFace->glyphs_[startIndex++];
  809. Image* image = images[glyph.page_];
  810. unsigned char* source = image->GetData() + components * (image->GetWidth() * glyph.y_ + glyph.x_);
  811. unsigned char* destination = imageData + components * (texWidth * packedGlyph.y_ + packedGlyph.x_);
  812. for (int i = 0; i < glyph.height_; ++i)
  813. {
  814. memcpy(destination, source, components * glyph.width_);
  815. source += components * image->GetWidth();
  816. destination += components * texWidth;
  817. }
  818. }
  819. // Finally load image into the texture
  820. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  821. if (!texture)
  822. return SharedPtr<FontFace>();
  823. packedFontFace->textures_.Push(texture);
  824. ++page;
  825. startIter = i;
  826. assert(index == startIndex);
  827. }
  828. return packedFontFace;
  829. }
  830. SharedPtr<Image> Font::SaveFaceTexture(Texture2D* texture)
  831. {
  832. Image* image = new Image(context_);
  833. image->SetSize(texture->GetWidth(), texture->GetHeight(), ConvertFormatToNumComponents(texture->GetFormat()));
  834. if (!static_cast<Texture2D*>(texture)->GetData(0, image->GetData()))
  835. {
  836. delete image;
  837. LOGERROR("Could not save texture to image resource");
  838. return SharedPtr<Image>();
  839. }
  840. return SharedPtr<Image>(image);
  841. }
  842. bool Font::SaveFaceTexture(Texture2D* texture, const String& fileName)
  843. {
  844. SharedPtr<Image> image = SaveFaceTexture(texture);
  845. return image ? image->SavePNG(fileName) : false;
  846. }
  847. }