Font.cpp 33 KB

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