Font.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "Deserializer.h"
  25. #include "FileSystem.h"
  26. #include "Font.h"
  27. #include "Graphics.h"
  28. #include "Log.h"
  29. #include "MemoryBuffer.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "Texture2D.h"
  33. #include "UI.h"
  34. #include "XMLFile.h"
  35. #include <ft2build.h>
  36. #include FT_FREETYPE_H
  37. #include FT_TRUETYPE_TABLES_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 (FreeType mode only)
  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. int loadMode = font_->GetSubsystem<UI>()->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  194. // Render glyphs
  195. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  196. RenderGlyphBitmap(i, imageData + glyphs_[i].y_ * image->GetWidth() + glyphs_[i].x_, image->GetWidth(), loadMode);
  197. // Load image into a texture, increment memory usage of the parent font
  198. SharedPtr<Texture2D> texture = font_->LoadFaceTexture(image);
  199. if (!texture)
  200. {
  201. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  202. glyphs_[i].page_ = M_MAX_UNSIGNED;
  203. return false;
  204. }
  205. textures_.Push(texture);
  206. font_->SetMemoryUse(font_->GetMemoryUse() + image->GetWidth() * image->GetHeight());
  207. LOGDEBUGF("Font face %s (%dpt) uses a static page texture of size %dx%d", GetFileName(font_->GetName()).CString(), pointSize_, 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. int loadMode = font_->GetSubsystem<UI>()->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  223. if (!mutableGlyphs_.Size())
  224. {
  225. // Not using mutable glyphs: try to allocate from current page, reserve next page if fails
  226. int x, y;
  227. if (!allocator_.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  228. {
  229. SetupNextTexture(textures_[0]->GetWidth(), textures_[0]->GetHeight());
  230. // This always succeeds, as it is the first allocation of an empty page
  231. allocator_.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y);
  232. }
  233. glyph.x_ = x;
  234. glyph.y_ = y;
  235. glyph.page_ = textures_.Size() - 1;
  236. if (!bitmap_ || (int)bitmapSize_ < glyph.width_ * glyph.height_)
  237. {
  238. bitmapSize_ = glyph.width_ * glyph.height_;
  239. bitmap_ = new unsigned char[bitmapSize_];
  240. }
  241. RenderGlyphBitmap(index, bitmap_.Get(), glyph.width_, loadMode);
  242. textures_.Back()->SetData(0, glyph.x_, glyph.y_, glyph.width_, glyph.height_, bitmap_.Get());
  243. }
  244. else
  245. {
  246. // Using mutable glyphs: overwrite the least recently used glyph
  247. List<MutableGlyph*>::Iterator it = --mutableGlyphs_.End();
  248. MutableGlyph* mutableGlyph = *it;
  249. if (mutableGlyph->glyphIndex_ != M_MAX_UNSIGNED)
  250. glyphs_[mutableGlyph->glyphIndex_].page_ = M_MAX_UNSIGNED;
  251. glyph.x_ = mutableGlyph->x_;
  252. glyph.y_ = mutableGlyph->y_;
  253. glyph.page_ = 0;
  254. glyph.iterator_ = it;
  255. mutableGlyph->glyphIndex_ = index;
  256. if (!bitmap_)
  257. {
  258. bitmapSize_ = cellWidth_ * cellHeight_;
  259. bitmap_ = new unsigned char[bitmapSize_];
  260. }
  261. // Clear the cell bitmap before rendering to ensure padding
  262. memset(bitmap_.Get(), 0, cellWidth_ * cellHeight_);
  263. RenderGlyphBitmap(index, bitmap_.Get(), cellWidth_, loadMode);
  264. textures_[0]->SetData(0, glyph.x_, glyph.y_, cellWidth_, cellHeight_, bitmap_.Get());
  265. }
  266. }
  267. void FontFace::RenderGlyphBitmap(unsigned index, unsigned char* dest, unsigned pitch, int loadMode)
  268. {
  269. const FontGlyph& glyph = glyphs_[index];
  270. if (!glyph.width_ || !glyph.height_)
  271. return;
  272. FT_Face face = (FT_Face)face_;
  273. FT_GlyphSlot slot = face->glyph;
  274. FT_Load_Glyph(face, index, loadMode);
  275. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  276. if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO)
  277. {
  278. for (int y = 0; y < slot->bitmap.rows; ++y)
  279. {
  280. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  281. unsigned char* rowDest = dest + y * pitch;
  282. for (int x = 0; x < slot->bitmap.width; ++x)
  283. rowDest[x] = (src[x >> 3] & (0x80 >> (x & 7))) ? 255 : 0;
  284. }
  285. }
  286. else
  287. {
  288. for (int y = 0; y < slot->bitmap.rows; ++y)
  289. {
  290. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  291. unsigned char* rowDest = dest + y * pitch;
  292. for (int x = 0; x < slot->bitmap.width; ++x)
  293. rowDest[x] = src[x];
  294. }
  295. }
  296. }
  297. void FontFace::SetupNextTexture(int width, int height)
  298. {
  299. // If several dynamic textures are needed, use the maximum size to pack as many as possible to one texture
  300. allocator_ = AreaAllocator(width, height);
  301. SharedPtr<Texture2D> texture = font_->CreateFaceTexture();
  302. texture->SetSize(width, height, Graphics::GetAlphaFormat());
  303. SharedArrayPtr<unsigned char> emptyBitmap(new unsigned char[width * height]);
  304. memset(emptyBitmap.Get(), 0, width * height);
  305. texture->SetData(0, 0, 0, width, height, emptyBitmap.Get());
  306. textures_.Push(texture);
  307. font_->SetMemoryUse(font_->GetMemoryUse() + width * height);
  308. LOGDEBUGF("Font face %s (%dpt) is using %d dynamic page textures of size %dx%d", GetFileName(font_->GetName()).CString(), 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. LOGDEBUGF("Font face %s (%dpt) is using %d mutable glyphs", GetFileName(font_->GetName()).CString(), pointSize_, mutableGlyphs_.Size());
  326. }
  327. Font::Font(Context* context) :
  328. Resource(context),
  329. fontDataSize_(0),
  330. fontType_(FONT_NONE)
  331. {
  332. }
  333. Font::~Font()
  334. {
  335. // To ensure FreeType deallocates properly, first clear all faces, then release the raw font data
  336. ReleaseFaces();
  337. fontData_.Reset();
  338. }
  339. void Font::RegisterObject(Context* context)
  340. {
  341. context->RegisterFactory<Font>();
  342. }
  343. bool Font::Load(Deserializer& source)
  344. {
  345. PROFILE(LoadFont);
  346. // In headless mode, do not actually load, just return success
  347. Graphics* graphics = GetSubsystem<Graphics>();
  348. if (!graphics)
  349. return true;
  350. faces_.Clear();
  351. fontDataSize_ = source.GetSize();
  352. if (fontDataSize_)
  353. {
  354. fontData_ = new unsigned char[fontDataSize_];
  355. if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
  356. return false;
  357. }
  358. else
  359. {
  360. fontData_.Reset();
  361. return false;
  362. }
  363. String ext = GetExtension(GetName());
  364. if (ext == ".ttf" || ext == ".otf" || ext == ".woff")
  365. fontType_ = FONT_FREETYPE;
  366. else if (ext == ".xml" || ext == ".fnt")
  367. fontType_ = FONT_BITMAP;
  368. SetMemoryUse(fontDataSize_);
  369. return true;
  370. }
  371. bool Font::SaveXML(Serializer& dest, int pointSize, bool usedGlyphs)
  372. {
  373. FontFace* fontFace = GetFace(pointSize);
  374. if (!fontFace)
  375. return false;
  376. PROFILE(FontSaveXML);
  377. SharedPtr<FontFace> packedFontFace;
  378. if (usedGlyphs)
  379. {
  380. // Save used glyphs only, try to pack them first
  381. packedFontFace = Pack(fontFace);
  382. if (packedFontFace)
  383. fontFace = packedFontFace;
  384. else
  385. return false;
  386. }
  387. SharedPtr<XMLFile> xml(new XMLFile(context_));
  388. XMLElement rootElem = xml->CreateRoot("font");
  389. // Information
  390. XMLElement childElem = rootElem.CreateChild("info");
  391. String fileName = GetFileName(GetName());
  392. childElem.SetAttribute("face", fileName);
  393. childElem.SetAttribute("size", String(pointSize));
  394. // Common
  395. childElem = rootElem.CreateChild("common");
  396. childElem.SetInt("lineHeight", fontFace->rowHeight_);
  397. unsigned pages = fontFace->textures_.Size();
  398. childElem.SetInt("pages", pages);
  399. // Construct the path to store the texture
  400. String pathName;
  401. File* file = dynamic_cast<File*>(&dest);
  402. if (file)
  403. // If serialize to file, use the file's path
  404. pathName = GetPath(file->GetName());
  405. else
  406. // Otherwise, use the font resource's path
  407. pathName = "Data/" + GetPath(GetName());
  408. // Pages
  409. childElem = rootElem.CreateChild("pages");
  410. for (unsigned i = 0; i < pages; ++i)
  411. {
  412. XMLElement pageElem = childElem.CreateChild("page");
  413. pageElem.SetInt("id", i);
  414. String texFileName = fileName + "_" + String(i) + ".png";
  415. pageElem.SetAttribute("file", texFileName);
  416. // Save the font face texture to image file
  417. SaveFaceTexture(fontFace->textures_[i], pathName + texFileName);
  418. }
  419. // Chars and kernings
  420. XMLElement charsElem = rootElem.CreateChild("chars");
  421. unsigned numGlyphs = fontFace->glyphs_.Size();
  422. charsElem.SetInt("count", numGlyphs);
  423. XMLElement kerningsElem;
  424. bool hasKerning = fontFace->hasKerning_;
  425. if (hasKerning)
  426. kerningsElem = rootElem.CreateChild("kernings");
  427. for (HashMap<unsigned, unsigned>::ConstIterator i = fontFace->glyphMapping_.Begin(); i != fontFace->glyphMapping_.End(); ++i)
  428. {
  429. // Char
  430. XMLElement charElem = charsElem.CreateChild("char");
  431. charElem.SetInt("id", i->first_);
  432. FontGlyph glyph = fontFace->glyphs_[i->second_];
  433. charElem.SetInt("x", glyph.x_);
  434. charElem.SetInt("y", glyph.y_);
  435. charElem.SetInt("width", glyph.width_);
  436. charElem.SetInt("height", glyph.height_);
  437. charElem.SetInt("xoffset", glyph.offsetX_);
  438. charElem.SetInt("yoffset", glyph.offsetY_);
  439. charElem.SetInt("xadvance", glyph.advanceX_);
  440. charElem.SetInt("page", glyph.page_);
  441. // Kerning
  442. if (hasKerning)
  443. {
  444. for (HashMap<unsigned, unsigned>::ConstIterator j = glyph.kerning_.Begin(); j != glyph.kerning_.End(); ++j)
  445. {
  446. // To conserve space, only write when amount is non zero
  447. if (j->second_ == 0)
  448. continue;
  449. XMLElement kerningElem = kerningsElem.CreateChild("kerning");
  450. kerningElem.SetInt("first", i->first_);
  451. kerningElem.SetInt("second", j->first_);
  452. kerningElem.SetInt("amount", j->second_);
  453. }
  454. }
  455. }
  456. return xml->Save(dest);
  457. }
  458. FontFace* Font::GetFace(int pointSize)
  459. {
  460. // In headless mode, always return null
  461. Graphics* graphics = GetSubsystem<Graphics>();
  462. if (!graphics)
  463. return 0;
  464. // For bitmap font type, always return the same font face provided by the font's bitmap file regardless of the actual requested point size
  465. if (fontType_ == FONT_BITMAP)
  466. pointSize = 0;
  467. else
  468. pointSize = Clamp(pointSize, MIN_POINT_SIZE, MAX_POINT_SIZE);
  469. HashMap<int, SharedPtr<FontFace> >::Iterator i = faces_.Find(pointSize);
  470. if (i != faces_.End())
  471. {
  472. if (!i->second_->IsDataLost())
  473. return i->second_;
  474. else
  475. {
  476. // Erase and reload face if texture data lost (OpenGL mode only)
  477. faces_.Erase(i);
  478. }
  479. }
  480. PROFILE(GetFontFace);
  481. switch (fontType_)
  482. {
  483. case FONT_FREETYPE:
  484. return GetFaceFreeType(pointSize);
  485. case FONT_BITMAP:
  486. return GetFaceBitmap(pointSize);
  487. default:
  488. return 0;
  489. }
  490. }
  491. void Font::ReleaseFaces()
  492. {
  493. faces_.Clear();
  494. }
  495. SharedPtr<Texture2D> Font::CreateFaceTexture()
  496. {
  497. SharedPtr<Texture2D> texture(new Texture2D(context_));
  498. texture->SetMipsToSkip(QUALITY_LOW, 0); // No quality reduction
  499. texture->SetNumLevels(1); // No mipmaps
  500. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  501. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  502. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  503. return texture;
  504. }
  505. SharedPtr<Texture2D> Font::LoadFaceTexture(SharedPtr<Image> image)
  506. {
  507. SharedPtr<Texture2D> texture = CreateFaceTexture();
  508. if (!texture->Load(image, true))
  509. {
  510. LOGERROR("Could not load texture from image resource");
  511. return SharedPtr<Texture2D>();
  512. }
  513. return texture;
  514. }
  515. FontFace* Font::GetFaceFreeType(int pointSize)
  516. {
  517. // Create & initialize FreeType library if it does not exist yet
  518. FreeTypeLibrary* freeType = GetSubsystem<FreeTypeLibrary>();
  519. if (!freeType)
  520. context_->RegisterSubsystem(freeType = new FreeTypeLibrary(context_));
  521. // Ensure the FreeType library is kept alive as long as TTF font resources exist
  522. freeType_ = freeType;
  523. UI* ui = GetSubsystem<UI>();
  524. int maxTextureSize = ui->GetMaxFontTextureSize();
  525. FT_Face face;
  526. FT_Error error;
  527. FT_Library library = freeType->GetLibrary();
  528. if (pointSize <= 0)
  529. {
  530. LOGERROR("Zero or negative point size");
  531. return 0;
  532. }
  533. if (!fontDataSize_)
  534. {
  535. LOGERROR("Font not loaded");
  536. return 0;
  537. }
  538. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  539. if (error)
  540. {
  541. LOGERROR("Could not create font face");
  542. return 0;
  543. }
  544. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  545. if (error)
  546. {
  547. FT_Done_Face(face);
  548. LOGERROR("Could not set font point size " + String(pointSize));
  549. return 0;
  550. }
  551. SharedPtr<FontFace> newFace(new FontFace(this));
  552. newFace->face_ = face;
  553. FT_GlyphSlot slot = face->glyph;
  554. unsigned numGlyphs = 0;
  555. // Build glyph mapping
  556. FT_UInt glyphIndex;
  557. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  558. while (glyphIndex != 0)
  559. {
  560. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  561. newFace->glyphMapping_[charCode] = glyphIndex;
  562. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  563. }
  564. LOGDEBUGF("Font face %s (%dpt) has %d glyphs", GetFileName(GetName()).CString(), pointSize, numGlyphs);
  565. // Load each of the glyphs to see the sizes & store other information
  566. int maxWidth = 0;
  567. int maxHeight = 0;
  568. int loadMode = ui->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  569. int ascender = face->size->metrics.ascender >> 6;
  570. int descender = face->size->metrics.descender >> 6;
  571. // Check if the font's OS/2 info gives different (larger) values for ascender & descender
  572. TT_OS2* os2Info = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
  573. if (os2Info)
  574. {
  575. ascender = Max(ascender, os2Info->usWinAscent * face->size->metrics.y_ppem / face->units_per_EM);
  576. ascender = Max(ascender, os2Info->sTypoAscender * face->size->metrics.y_ppem / face->units_per_EM);
  577. descender = Max(descender, os2Info->usWinDescent * face->size->metrics.y_ppem / face->units_per_EM);
  578. descender = Max(descender, os2Info->sTypoDescender * face->size->metrics.y_ppem / face->units_per_EM);
  579. }
  580. // Store point size and row height. Use the maximum of ascender + descender, or the face's stored default row height
  581. newFace->pointSize_ = pointSize;
  582. newFace->rowHeight_ = Max(ascender + descender, face->size->metrics.height >> 6);
  583. newFace->glyphs_.Reserve(numGlyphs);
  584. for (unsigned i = 0; i < numGlyphs; ++i)
  585. {
  586. FontGlyph newGlyph;
  587. error = FT_Load_Glyph(face, i, loadMode);
  588. if (!error)
  589. {
  590. // Note: position within texture will be filled later
  591. newGlyph.width_ = (short)Max(slot->metrics.width >> 6, slot->bitmap.width);
  592. newGlyph.height_ = (short)Max(slot->metrics.height >> 6, slot->bitmap.rows);
  593. newGlyph.offsetX_ = (short)(slot->metrics.horiBearingX >> 6);
  594. newGlyph.offsetY_ = (short)(ascender - (slot->metrics.horiBearingY >> 6));
  595. newGlyph.advanceX_ = (short)(slot->metrics.horiAdvance >> 6);
  596. maxWidth = Max(maxWidth, newGlyph.width_);
  597. maxHeight = Max(maxHeight, newGlyph.height_);
  598. }
  599. else
  600. {
  601. newGlyph.width_ = 0;
  602. newGlyph.height_ = 0;
  603. newGlyph.offsetX_ = 0;
  604. newGlyph.offsetY_ = 0;
  605. newGlyph.advanceX_ = 0;
  606. }
  607. newFace->glyphs_.Push(newGlyph);
  608. }
  609. // Store kerning if face has kerning information
  610. if (FT_HAS_KERNING(face))
  611. {
  612. newFace->hasKerning_ = true;
  613. for (unsigned i = 0; i < numGlyphs; ++i)
  614. {
  615. for (unsigned j = 0; j < numGlyphs; ++j)
  616. {
  617. FT_Vector vector;
  618. FT_Get_Kerning(face, i, j, FT_KERNING_DEFAULT, &vector);
  619. newFace->glyphs_[i].kerning_[j] = (short)(vector.x >> 6);
  620. }
  621. }
  622. }
  623. // Now try to pack into the smallest possible texture. If face does not fit into one texture, enable dynamic mode where
  624. // glyphs are only created as necessary
  625. if (newFace->RenderAllGlyphs(maxTextureSize, maxTextureSize))
  626. {
  627. FT_Done_Face(face);
  628. newFace->face_ = 0;
  629. }
  630. else
  631. {
  632. if (ui->GetUseMutableGlyphs())
  633. newFace->SetupMutableGlyphs(maxTextureSize, maxTextureSize, maxWidth, maxHeight);
  634. else
  635. newFace->SetupNextTexture(maxTextureSize, maxTextureSize);
  636. }
  637. faces_[pointSize] = newFace;
  638. return newFace;
  639. }
  640. FontFace* Font::GetFaceBitmap(int pointSize)
  641. {
  642. SharedPtr<XMLFile> xmlReader(new XMLFile(context_));
  643. MemoryBuffer memoryBuffer(fontData_, fontDataSize_);
  644. if (!xmlReader->Load(memoryBuffer))
  645. {
  646. LOGERROR("Could not load XML file");
  647. return 0;
  648. }
  649. XMLElement root = xmlReader->GetRoot("font");
  650. if (root.IsNull())
  651. {
  652. LOGERROR("Could not find Font element");
  653. return 0;
  654. }
  655. XMLElement pagesElem = root.GetChild("pages");
  656. if (pagesElem.IsNull())
  657. {
  658. LOGERROR("Could not find Pages element");
  659. return 0;
  660. }
  661. SharedPtr<FontFace> newFace(new FontFace(this));
  662. XMLElement infoElem = root.GetChild("info");
  663. if (!infoElem.IsNull())
  664. newFace->pointSize_ = infoElem.GetInt("size");
  665. XMLElement commonElem = root.GetChild("common");
  666. newFace->rowHeight_ = commonElem.GetInt("lineHeight");
  667. unsigned pages = commonElem.GetInt("pages");
  668. newFace->textures_.Reserve(pages);
  669. ResourceCache* resourceCache = GetSubsystem<ResourceCache>();
  670. String fontPath = GetPath(GetName());
  671. unsigned totalTextureSize = 0;
  672. XMLElement pageElem = pagesElem.GetChild("page");
  673. for (unsigned i = 0; i < pages; ++i)
  674. {
  675. if (pageElem.IsNull())
  676. {
  677. LOGERROR("Could not find Page element for page: " + String(i));
  678. return 0;
  679. }
  680. // Assume the font image is in the same directory as the font description file
  681. String textureFile = fontPath + pageElem.GetAttribute("file");
  682. // Load texture manually to allow controlling the alpha channel mode
  683. SharedPtr<File> fontFile = resourceCache->GetFile(textureFile);
  684. SharedPtr<Image> fontImage(new Image(context_));
  685. if (!fontFile || !fontImage->Load(*fontFile))
  686. {
  687. LOGERROR("Failed to load font image file");
  688. return 0;
  689. }
  690. SharedPtr<Texture2D> texture = LoadFaceTexture(fontImage);
  691. if (!texture)
  692. return 0;
  693. newFace->textures_.Push(texture);
  694. totalTextureSize += fontImage->GetWidth() * fontImage->GetHeight() * fontImage->GetComponents();
  695. pageElem = pageElem.GetNext("page");
  696. }
  697. XMLElement charsElem = root.GetChild("chars");
  698. int count = charsElem.GetInt("count");
  699. newFace->glyphs_.Reserve(count);
  700. unsigned index = 0;
  701. XMLElement charElem = charsElem.GetChild("char");
  702. while (!charElem.IsNull())
  703. {
  704. int id = charElem.GetInt("id");
  705. FontGlyph glyph;
  706. glyph.x_ = charElem.GetInt("x");
  707. glyph.y_ = charElem.GetInt("y");
  708. glyph.width_ = charElem.GetInt("width");
  709. glyph.height_ = charElem.GetInt("height");
  710. glyph.offsetX_ = charElem.GetInt("xoffset");
  711. glyph.offsetY_ = charElem.GetInt("yoffset");
  712. glyph.advanceX_ = charElem.GetInt("xadvance");
  713. glyph.page_ = charElem.GetInt("page");
  714. newFace->glyphs_.Push(glyph);
  715. newFace->glyphMapping_[id] = index++;
  716. charElem = charElem.GetNext("char");
  717. }
  718. XMLElement kerningsElem = root.GetChild("kernings");
  719. if (kerningsElem.IsNull())
  720. newFace->hasKerning_ = false;
  721. else
  722. {
  723. XMLElement kerningElem = kerningsElem.GetChild("kerning");
  724. while (!kerningElem.IsNull())
  725. {
  726. int first = kerningElem.GetInt("first");
  727. HashMap<unsigned, unsigned>::Iterator i = newFace->glyphMapping_.Find(first);
  728. if (i != newFace->glyphMapping_.End())
  729. {
  730. int second = kerningElem.GetInt("second");
  731. int amount = kerningElem.GetInt("amount");
  732. FontGlyph& glyph = newFace->glyphs_[i->second_];
  733. glyph.kerning_[second] = amount;
  734. }
  735. kerningElem = kerningElem.GetNext("kerning");
  736. }
  737. }
  738. LOGDEBUGF("Bitmap font face %s has %d glyphs", GetFileName(GetName()).CString(), count);
  739. SetMemoryUse(GetMemoryUse() + totalTextureSize);
  740. faces_[pointSize] = newFace;
  741. return newFace;
  742. }
  743. unsigned Font::ConvertFormatToNumComponents(unsigned format)
  744. {
  745. if (format == Graphics::GetRGBAFormat())
  746. return 4;
  747. else if (format == Graphics::GetRGBFormat())
  748. return 3;
  749. else if (format == Graphics::GetLuminanceAlphaFormat())
  750. return 2;
  751. else
  752. return 1;
  753. }
  754. SharedPtr<FontFace> Font::Pack(FontFace* fontFace)
  755. {
  756. // Set parent font as null for the packed face so that it does not attempt to manage the font's total memory use
  757. SharedPtr<FontFace> packedFontFace(new FontFace((Font*)0));
  758. int maxTextureSize = GetSubsystem<UI>()->GetMaxFontTextureSize();
  759. // Clone properties
  760. packedFontFace->pointSize_ = fontFace->pointSize_;
  761. packedFontFace->rowHeight_ = fontFace->rowHeight_;
  762. packedFontFace->hasKerning_ = fontFace->hasKerning_;
  763. // Assume that format is the same for all textures and that bitmap font type may have more than one component
  764. unsigned components = ConvertFormatToNumComponents(fontFace->textures_[0]->GetFormat());
  765. // Save the existing textures as image resources
  766. Vector<SharedPtr<Image> > images(fontFace->textures_.Size());
  767. for (unsigned i = 0; i < fontFace->textures_.Size(); ++i)
  768. images[i] = SaveFaceTexture(fontFace->textures_[i]);
  769. // Reallocate used glyphs to new texture(s)
  770. unsigned page = 0;
  771. unsigned index = 0;
  772. unsigned startIndex = 0;
  773. HashMap<unsigned, unsigned>::ConstIterator startIter = fontFace->glyphMapping_.Begin();
  774. HashMap<unsigned, unsigned>::ConstIterator i;
  775. while (startIter != fontFace->glyphMapping_.End())
  776. {
  777. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxTextureSize, maxTextureSize);
  778. for (i = startIter; i != fontFace->glyphMapping_.End(); ++i)
  779. {
  780. FontGlyph glyph = fontFace->glyphs_[i->second_];
  781. if (!glyph.used_)
  782. continue;
  783. if (glyph.width_ && glyph.height_)
  784. {
  785. int x, y;
  786. // Reserve an empty border between glyphs for filtering
  787. if (allocator.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  788. {
  789. glyph.x_ = x;
  790. glyph.y_ = y;
  791. glyph.page_ = page;
  792. }
  793. else
  794. break;
  795. }
  796. packedFontFace->glyphs_.Push(glyph);
  797. packedFontFace->glyphMapping_[i->first_] = index++;
  798. }
  799. int texWidth = allocator.GetWidth();
  800. int texHeight = allocator.GetHeight();
  801. // Create the image for rendering the fonts
  802. SharedPtr<Image> image(new Image(context_));
  803. image->SetSize(texWidth, texHeight, components);
  804. // First clear the whole image
  805. unsigned char* imageData = image->GetData();
  806. for (int y = 0; y < texHeight; ++y)
  807. {
  808. unsigned char* dest = imageData + components * texWidth * y;
  809. memset(dest, 0, components * texWidth);
  810. }
  811. // Then render the glyphs into new image
  812. for (HashMap<unsigned, unsigned>::ConstIterator j = startIter; j != i; ++j)
  813. {
  814. FontGlyph glyph = fontFace->glyphs_[j->second_];
  815. if (!glyph.used_)
  816. continue;
  817. if (!glyph.width_ || !glyph.height_)
  818. {
  819. ++startIndex;
  820. continue;
  821. }
  822. FontGlyph packedGlyph = packedFontFace->glyphs_[startIndex++];
  823. Image* image = images[glyph.page_];
  824. unsigned char* source = image->GetData() + components * (image->GetWidth() * glyph.y_ + glyph.x_);
  825. unsigned char* destination = imageData + components * (texWidth * packedGlyph.y_ + packedGlyph.x_);
  826. for (int i = 0; i < glyph.height_; ++i)
  827. {
  828. memcpy(destination, source, components * glyph.width_);
  829. source += components * image->GetWidth();
  830. destination += components * texWidth;
  831. }
  832. }
  833. // Finally load image into the texture
  834. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  835. if (!texture)
  836. return SharedPtr<FontFace>();
  837. packedFontFace->textures_.Push(texture);
  838. ++page;
  839. startIter = i;
  840. assert(index == startIndex);
  841. }
  842. return packedFontFace;
  843. }
  844. SharedPtr<Image> Font::SaveFaceTexture(Texture2D* texture)
  845. {
  846. Image* image = new Image(context_);
  847. image->SetSize(texture->GetWidth(), texture->GetHeight(), ConvertFormatToNumComponents(texture->GetFormat()));
  848. if (!static_cast<Texture2D*>(texture)->GetData(0, image->GetData()))
  849. {
  850. delete image;
  851. LOGERROR("Could not save texture to image resource");
  852. return SharedPtr<Image>();
  853. }
  854. return SharedPtr<Image>(image);
  855. }
  856. bool Font::SaveFaceTexture(Texture2D* texture, const String& fileName)
  857. {
  858. SharedPtr<Image> image = SaveFaceTexture(texture);
  859. return image ? image->SavePNG(fileName) : false;
  860. }
  861. }