Font.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. fontType_ = FONT_NONE;
  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 GetFaceFreeType(pointSize);
  486. case FONT_BITMAP:
  487. return GetFaceBitmap(pointSize);
  488. default:
  489. return 0;
  490. }
  491. }
  492. void Font::ReleaseFaces()
  493. {
  494. faces_.Clear();
  495. }
  496. SharedPtr<Texture2D> Font::CreateFaceTexture()
  497. {
  498. SharedPtr<Texture2D> texture(new Texture2D(context_));
  499. texture->SetMipsToSkip(QUALITY_LOW, 0); // No quality reduction
  500. texture->SetNumLevels(1); // No mipmaps
  501. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  502. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  503. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  504. return texture;
  505. }
  506. SharedPtr<Texture2D> Font::LoadFaceTexture(SharedPtr<Image> image)
  507. {
  508. SharedPtr<Texture2D> texture = CreateFaceTexture();
  509. if (!texture->Load(image, true))
  510. {
  511. LOGERROR("Could not load texture from image resource");
  512. return SharedPtr<Texture2D>();
  513. }
  514. return texture;
  515. }
  516. FontFace* Font::GetFaceFreeType(int pointSize)
  517. {
  518. // Create & initialize FreeType library if it does not exist yet
  519. FreeTypeLibrary* freeType = GetSubsystem<FreeTypeLibrary>();
  520. if (!freeType)
  521. context_->RegisterSubsystem(freeType = new FreeTypeLibrary(context_));
  522. // Ensure the FreeType library is kept alive as long as TTF font resources exist
  523. freeType_ = freeType;
  524. UI* ui = GetSubsystem<UI>();
  525. int maxTextureSize = ui->GetMaxFontTextureSize();
  526. FT_Face face;
  527. FT_Error error;
  528. FT_Library library = freeType->GetLibrary();
  529. if (pointSize <= 0)
  530. {
  531. LOGERROR("Zero or negative point size");
  532. return 0;
  533. }
  534. if (!fontDataSize_)
  535. {
  536. LOGERROR("Could not create font face from zero size data");
  537. return 0;
  538. }
  539. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  540. if (error)
  541. {
  542. LOGERROR("Could not create font face");
  543. return 0;
  544. }
  545. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  546. if (error)
  547. {
  548. FT_Done_Face(face);
  549. LOGERROR("Could not set font point size " + String(pointSize));
  550. return 0;
  551. }
  552. SharedPtr<FontFace> newFace(new FontFace(this));
  553. newFace->face_ = face;
  554. FT_GlyphSlot slot = face->glyph;
  555. unsigned numGlyphs = 0;
  556. // Build glyph mapping
  557. FT_UInt glyphIndex;
  558. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  559. while (glyphIndex != 0)
  560. {
  561. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  562. newFace->glyphMapping_[charCode] = glyphIndex;
  563. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  564. }
  565. LOGDEBUGF("Font face %s (%dpt) has %d glyphs", GetFileName(GetName()).CString(), pointSize, numGlyphs);
  566. // Load each of the glyphs to see the sizes & store other information
  567. int maxWidth = 0;
  568. int maxHeight = 0;
  569. int loadMode = ui->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  570. int ascender = face->size->metrics.ascender >> 6;
  571. int descender = face->size->metrics.descender >> 6;
  572. // Check if the font's OS/2 info gives different (larger) values for ascender & descender
  573. TT_OS2* os2Info = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
  574. if (os2Info)
  575. {
  576. ascender = Max(ascender, os2Info->usWinAscent * face->size->metrics.y_ppem / face->units_per_EM);
  577. ascender = Max(ascender, os2Info->sTypoAscender * face->size->metrics.y_ppem / face->units_per_EM);
  578. descender = Max(descender, os2Info->usWinDescent * face->size->metrics.y_ppem / face->units_per_EM);
  579. descender = Max(descender, os2Info->sTypoDescender * face->size->metrics.y_ppem / face->units_per_EM);
  580. }
  581. // Store point size and row height. Use the maximum of ascender + descender, or the face's stored default row height
  582. newFace->pointSize_ = pointSize;
  583. newFace->rowHeight_ = Max(ascender + descender, face->size->metrics.height >> 6);
  584. newFace->glyphs_.Reserve(numGlyphs);
  585. for (unsigned i = 0; i < numGlyphs; ++i)
  586. {
  587. FontGlyph newGlyph;
  588. error = FT_Load_Glyph(face, i, loadMode);
  589. if (!error)
  590. {
  591. // Note: position within texture will be filled later
  592. newGlyph.width_ = (short)Max(slot->metrics.width >> 6, slot->bitmap.width);
  593. newGlyph.height_ = (short)Max(slot->metrics.height >> 6, slot->bitmap.rows);
  594. newGlyph.offsetX_ = (short)(slot->metrics.horiBearingX >> 6);
  595. newGlyph.offsetY_ = (short)(ascender - (slot->metrics.horiBearingY >> 6));
  596. newGlyph.advanceX_ = (short)(slot->metrics.horiAdvance >> 6);
  597. maxWidth = Max(maxWidth, newGlyph.width_);
  598. maxHeight = Max(maxHeight, newGlyph.height_);
  599. }
  600. else
  601. {
  602. newGlyph.width_ = 0;
  603. newGlyph.height_ = 0;
  604. newGlyph.offsetX_ = 0;
  605. newGlyph.offsetY_ = 0;
  606. newGlyph.advanceX_ = 0;
  607. }
  608. newFace->glyphs_.Push(newGlyph);
  609. }
  610. // Store kerning if face has kerning information
  611. if (FT_HAS_KERNING(face))
  612. {
  613. newFace->hasKerning_ = true;
  614. for (unsigned i = 0; i < numGlyphs; ++i)
  615. {
  616. for (unsigned j = 0; j < numGlyphs; ++j)
  617. {
  618. FT_Vector vector;
  619. FT_Get_Kerning(face, i, j, FT_KERNING_DEFAULT, &vector);
  620. newFace->glyphs_[i].kerning_[j] = (short)(vector.x >> 6);
  621. }
  622. }
  623. }
  624. // Now try to pack into the smallest possible texture. If face does not fit into one texture, enable dynamic mode where
  625. // glyphs are only created as necessary
  626. if (newFace->RenderAllGlyphs(maxTextureSize, maxTextureSize))
  627. {
  628. FT_Done_Face(face);
  629. newFace->face_ = 0;
  630. }
  631. else
  632. {
  633. if (ui->GetUseMutableGlyphs())
  634. newFace->SetupMutableGlyphs(maxTextureSize, maxTextureSize, maxWidth, maxHeight);
  635. else
  636. newFace->SetupNextTexture(maxTextureSize, maxTextureSize);
  637. }
  638. faces_[pointSize] = newFace;
  639. return newFace;
  640. }
  641. FontFace* Font::GetFaceBitmap(int pointSize)
  642. {
  643. SharedPtr<XMLFile> xmlReader(new XMLFile(context_));
  644. MemoryBuffer memoryBuffer(fontData_, fontDataSize_);
  645. if (!xmlReader->Load(memoryBuffer))
  646. {
  647. LOGERROR("Could not load XML file");
  648. return 0;
  649. }
  650. XMLElement root = xmlReader->GetRoot("font");
  651. if (root.IsNull())
  652. {
  653. LOGERROR("Could not find Font element");
  654. return 0;
  655. }
  656. XMLElement pagesElem = root.GetChild("pages");
  657. if (pagesElem.IsNull())
  658. {
  659. LOGERROR("Could not find Pages element");
  660. return 0;
  661. }
  662. SharedPtr<FontFace> newFace(new FontFace(this));
  663. XMLElement infoElem = root.GetChild("info");
  664. if (!infoElem.IsNull())
  665. newFace->pointSize_ = infoElem.GetInt("size");
  666. XMLElement commonElem = root.GetChild("common");
  667. newFace->rowHeight_ = commonElem.GetInt("lineHeight");
  668. unsigned pages = commonElem.GetInt("pages");
  669. newFace->textures_.Reserve(pages);
  670. ResourceCache* resourceCache = GetSubsystem<ResourceCache>();
  671. String fontPath = GetPath(GetName());
  672. unsigned totalTextureSize = 0;
  673. XMLElement pageElem = pagesElem.GetChild("page");
  674. for (unsigned i = 0; i < pages; ++i)
  675. {
  676. if (pageElem.IsNull())
  677. {
  678. LOGERROR("Could not find Page element for page: " + String(i));
  679. return 0;
  680. }
  681. // Assume the font image is in the same directory as the font description file
  682. String textureFile = fontPath + pageElem.GetAttribute("file");
  683. // Load texture manually to allow controlling the alpha channel mode
  684. SharedPtr<File> fontFile = resourceCache->GetFile(textureFile);
  685. SharedPtr<Image> fontImage(new Image(context_));
  686. if (!fontFile || !fontImage->Load(*fontFile))
  687. {
  688. LOGERROR("Failed to load font image file");
  689. return 0;
  690. }
  691. SharedPtr<Texture2D> texture = LoadFaceTexture(fontImage);
  692. if (!texture)
  693. return 0;
  694. newFace->textures_.Push(texture);
  695. totalTextureSize += fontImage->GetWidth() * fontImage->GetHeight() * fontImage->GetComponents();
  696. pageElem = pageElem.GetNext("page");
  697. }
  698. XMLElement charsElem = root.GetChild("chars");
  699. int count = charsElem.GetInt("count");
  700. newFace->glyphs_.Reserve(count);
  701. unsigned index = 0;
  702. XMLElement charElem = charsElem.GetChild("char");
  703. while (!charElem.IsNull())
  704. {
  705. int id = charElem.GetInt("id");
  706. FontGlyph glyph;
  707. glyph.x_ = charElem.GetInt("x");
  708. glyph.y_ = charElem.GetInt("y");
  709. glyph.width_ = charElem.GetInt("width");
  710. glyph.height_ = charElem.GetInt("height");
  711. glyph.offsetX_ = charElem.GetInt("xoffset");
  712. glyph.offsetY_ = charElem.GetInt("yoffset");
  713. glyph.advanceX_ = charElem.GetInt("xadvance");
  714. glyph.page_ = charElem.GetInt("page");
  715. newFace->glyphs_.Push(glyph);
  716. newFace->glyphMapping_[id] = index++;
  717. charElem = charElem.GetNext("char");
  718. }
  719. XMLElement kerningsElem = root.GetChild("kernings");
  720. if (kerningsElem.IsNull())
  721. newFace->hasKerning_ = false;
  722. else
  723. {
  724. XMLElement kerningElem = kerningsElem.GetChild("kerning");
  725. while (!kerningElem.IsNull())
  726. {
  727. int first = kerningElem.GetInt("first");
  728. HashMap<unsigned, unsigned>::Iterator i = newFace->glyphMapping_.Find(first);
  729. if (i != newFace->glyphMapping_.End())
  730. {
  731. int second = kerningElem.GetInt("second");
  732. int amount = kerningElem.GetInt("amount");
  733. FontGlyph& glyph = newFace->glyphs_[i->second_];
  734. glyph.kerning_[second] = amount;
  735. }
  736. kerningElem = kerningElem.GetNext("kerning");
  737. }
  738. }
  739. LOGDEBUGF("Bitmap font face %s has %d glyphs", GetFileName(GetName()).CString(), count);
  740. SetMemoryUse(GetMemoryUse() + totalTextureSize);
  741. faces_[pointSize] = newFace;
  742. return newFace;
  743. }
  744. unsigned Font::ConvertFormatToNumComponents(unsigned format)
  745. {
  746. if (format == Graphics::GetRGBAFormat())
  747. return 4;
  748. else if (format == Graphics::GetRGBFormat())
  749. return 3;
  750. else if (format == Graphics::GetLuminanceAlphaFormat())
  751. return 2;
  752. else
  753. return 1;
  754. }
  755. SharedPtr<FontFace> Font::Pack(FontFace* fontFace)
  756. {
  757. // Set parent font as null for the packed face so that it does not attempt to manage the font's total memory use
  758. SharedPtr<FontFace> packedFontFace(new FontFace((Font*)0));
  759. int maxTextureSize = GetSubsystem<UI>()->GetMaxFontTextureSize();
  760. // Clone properties
  761. packedFontFace->pointSize_ = fontFace->pointSize_;
  762. packedFontFace->rowHeight_ = fontFace->rowHeight_;
  763. packedFontFace->hasKerning_ = fontFace->hasKerning_;
  764. // Assume that format is the same for all textures and that bitmap font type may have more than one component
  765. unsigned components = ConvertFormatToNumComponents(fontFace->textures_[0]->GetFormat());
  766. // Save the existing textures as image resources
  767. Vector<SharedPtr<Image> > images(fontFace->textures_.Size());
  768. for (unsigned i = 0; i < fontFace->textures_.Size(); ++i)
  769. images[i] = SaveFaceTexture(fontFace->textures_[i]);
  770. // Reallocate used glyphs to new texture(s)
  771. unsigned page = 0;
  772. unsigned index = 0;
  773. unsigned startIndex = 0;
  774. HashMap<unsigned, unsigned>::ConstIterator startIter = fontFace->glyphMapping_.Begin();
  775. HashMap<unsigned, unsigned>::ConstIterator i;
  776. while (startIter != fontFace->glyphMapping_.End())
  777. {
  778. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxTextureSize, maxTextureSize);
  779. for (i = startIter; i != fontFace->glyphMapping_.End(); ++i)
  780. {
  781. FontGlyph glyph = fontFace->glyphs_[i->second_];
  782. if (!glyph.used_)
  783. continue;
  784. if (glyph.width_ && glyph.height_)
  785. {
  786. int x, y;
  787. // Reserve an empty border between glyphs for filtering
  788. if (allocator.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  789. {
  790. glyph.x_ = x;
  791. glyph.y_ = y;
  792. glyph.page_ = page;
  793. }
  794. else
  795. break;
  796. }
  797. packedFontFace->glyphs_.Push(glyph);
  798. packedFontFace->glyphMapping_[i->first_] = index++;
  799. }
  800. int texWidth = allocator.GetWidth();
  801. int texHeight = allocator.GetHeight();
  802. // Create the image for rendering the fonts
  803. SharedPtr<Image> image(new Image(context_));
  804. image->SetSize(texWidth, texHeight, components);
  805. // First clear the whole image
  806. unsigned char* imageData = image->GetData();
  807. for (int y = 0; y < texHeight; ++y)
  808. {
  809. unsigned char* dest = imageData + components * texWidth * y;
  810. memset(dest, 0, components * texWidth);
  811. }
  812. // Then render the glyphs into new image
  813. for (HashMap<unsigned, unsigned>::ConstIterator j = startIter; j != i; ++j)
  814. {
  815. FontGlyph glyph = fontFace->glyphs_[j->second_];
  816. if (!glyph.used_)
  817. continue;
  818. if (!glyph.width_ || !glyph.height_)
  819. {
  820. ++startIndex;
  821. continue;
  822. }
  823. FontGlyph packedGlyph = packedFontFace->glyphs_[startIndex++];
  824. Image* image = images[glyph.page_];
  825. unsigned char* source = image->GetData() + components * (image->GetWidth() * glyph.y_ + glyph.x_);
  826. unsigned char* destination = imageData + components * (texWidth * packedGlyph.y_ + packedGlyph.x_);
  827. for (int i = 0; i < glyph.height_; ++i)
  828. {
  829. memcpy(destination, source, components * glyph.width_);
  830. source += components * image->GetWidth();
  831. destination += components * texWidth;
  832. }
  833. }
  834. // Finally load image into the texture
  835. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  836. if (!texture)
  837. return SharedPtr<FontFace>();
  838. packedFontFace->textures_.Push(texture);
  839. ++page;
  840. startIter = i;
  841. assert(index == startIndex);
  842. }
  843. return packedFontFace;
  844. }
  845. SharedPtr<Image> Font::SaveFaceTexture(Texture2D* texture)
  846. {
  847. Image* image = new Image(context_);
  848. image->SetSize(texture->GetWidth(), texture->GetHeight(), ConvertFormatToNumComponents(texture->GetFormat()));
  849. if (!static_cast<Texture2D*>(texture)->GetData(0, image->GetData()))
  850. {
  851. delete image;
  852. LOGERROR("Could not save texture to image resource");
  853. return SharedPtr<Image>();
  854. }
  855. return SharedPtr<Image>(image);
  856. }
  857. bool Font::SaveFaceTexture(Texture2D* texture, const String& fileName)
  858. {
  859. SharedPtr<Image> image = SaveFaceTexture(texture);
  860. return image ? image->SavePNG(fileName) : false;
  861. }
  862. }