Font.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "AreaAllocator.h"
  24. #include "Context.h"
  25. #include "Deserializer.h"
  26. #include "FileSystem.h"
  27. #include "Font.h"
  28. #include "Graphics.h"
  29. #include "Log.h"
  30. #include "MemoryBuffer.h"
  31. #include "Profiler.h"
  32. #include "ResourceCache.h"
  33. #include "Texture2D.h"
  34. #include "XMLFile.h"
  35. #include <ft2build.h>
  36. #include FT_FREETYPE_H
  37. #include "DebugNew.h"
  38. namespace Urho3D
  39. {
  40. /// FreeType library subsystem.
  41. class FreeTypeLibrary : public Object
  42. {
  43. OBJECT(FreeTypeLibrary);
  44. public:
  45. /// Construct.
  46. FreeTypeLibrary(Context* context) :
  47. Object(context)
  48. {
  49. FT_Error error = FT_Init_FreeType(&mLibrary);
  50. if (error)
  51. LOGERROR("Could not initialize FreeType library");
  52. }
  53. /// Destruct.
  54. virtual ~FreeTypeLibrary()
  55. {
  56. FT_Done_FreeType(mLibrary);
  57. }
  58. FT_Library getLibrary() const { return mLibrary; }
  59. private:
  60. /// FreeType library.
  61. FT_Library mLibrary;
  62. };
  63. FontFace::FontFace() :
  64. hasKerning_(false)
  65. {
  66. }
  67. FontFace::~FontFace()
  68. {
  69. }
  70. const FontGlyph& FontFace::GetGlyph(unsigned c) const
  71. {
  72. HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Find(c);
  73. if (i != glyphMapping_.End())
  74. return glyphs_[i->second_];
  75. else
  76. return glyphs_[0];
  77. }
  78. short FontFace::GetKerning(unsigned c, unsigned d) const
  79. {
  80. if (!hasKerning_)
  81. return 0;
  82. if (c == '\n' || d == '\n')
  83. return 0;
  84. unsigned leftIndex = 0;
  85. unsigned rightIndex = 0;
  86. HashMap<unsigned, unsigned>::ConstIterator leftIt = glyphMapping_.Find(c);
  87. HashMap<unsigned, unsigned>::ConstIterator rightIt = glyphMapping_.Find(d);
  88. if (leftIt != glyphMapping_.End())
  89. leftIndex = leftIt->second_;
  90. if (rightIt != glyphMapping_.End())
  91. rightIndex = rightIt->second_;
  92. HashMap<unsigned, unsigned>::ConstIterator kerningIt = glyphs_[leftIndex].kerning_.Find(rightIndex);
  93. if (kerningIt != glyphs_[leftIndex].kerning_.End())
  94. return kerningIt->second_;
  95. else
  96. return 0;
  97. }
  98. bool FontFace::IsDataLost() const
  99. {
  100. for (unsigned i = 0; i < textures_.Size(); ++i)
  101. {
  102. if (textures_[i]->IsDataLost())
  103. return true;
  104. }
  105. return false;
  106. }
  107. OBJECTTYPESTATIC(FreeTypeLibrary);
  108. OBJECTTYPESTATIC(Font);
  109. Font::Font(Context* context) :
  110. Resource(context),
  111. fontDataSize_(0),
  112. fontType_(FONT_NONE)
  113. {
  114. }
  115. Font::~Font()
  116. {
  117. }
  118. void Font::RegisterObject(Context* context)
  119. {
  120. context->RegisterFactory<Font>();
  121. }
  122. bool Font::Load(Deserializer& source)
  123. {
  124. PROFILE(LoadFont);
  125. faces_.Clear();
  126. pathName_.Clear();
  127. fontDataSize_ = source.GetSize();
  128. if (fontDataSize_)
  129. {
  130. fontData_ = new unsigned char[fontDataSize_];
  131. if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
  132. return false;
  133. }
  134. else
  135. {
  136. fontData_.Reset();
  137. return false;
  138. }
  139. pathName_ = source.GetName();
  140. String ext = GetExtension(pathName_).ToLower();
  141. if (ext == ".ttf")
  142. fontType_ = FONT_TTF;
  143. else if (ext == ".xml" || ext == ".fnt")
  144. fontType_ = FONT_BITMAP;
  145. SetMemoryUse(fontDataSize_);
  146. return true;
  147. }
  148. const FontFace* Font::GetFace(int pointSize)
  149. {
  150. // Always return the same font face provided by the font's bitmap file regardless of the actual requested point size
  151. if (fontType_ == FONT_BITMAP)
  152. pointSize = 0;
  153. HashMap<int, SharedPtr<FontFace> >::Iterator i = faces_.Find(pointSize);
  154. if (i != faces_.End())
  155. {
  156. if (!i->second_->IsDataLost())
  157. return i->second_;
  158. else
  159. {
  160. // Erase and reload face if texture data lost (OpenGL mode only)
  161. faces_.Erase(i);
  162. }
  163. }
  164. PROFILE(GetFontFace);
  165. switch (fontType_)
  166. {
  167. case FONT_TTF:
  168. return GetFaceTTF(pointSize);
  169. case FONT_BITMAP:
  170. return GetFaceBitmap(pointSize);
  171. default:
  172. return 0;
  173. }
  174. }
  175. const FontFace* Font::GetFaceTTF(int pointSize)
  176. {
  177. // Create & initialize FreeType library if it does not exist yet
  178. FreeTypeLibrary* freeType = GetSubsystem<FreeTypeLibrary>();
  179. if (!freeType)
  180. context_->RegisterSubsystem(freeType = new FreeTypeLibrary(context_));
  181. FT_Face face;
  182. FT_Error error;
  183. FT_Library library = freeType->getLibrary();
  184. if (pointSize <= 0)
  185. {
  186. LOGERROR("Zero or negative point size");
  187. return 0;
  188. }
  189. if (!fontDataSize_)
  190. {
  191. LOGERROR("Font not loaded");
  192. return 0;
  193. }
  194. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  195. if (error)
  196. {
  197. LOGERROR("Could not create font face");
  198. return 0;
  199. }
  200. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  201. if (error)
  202. {
  203. FT_Done_Face(face);
  204. LOGERROR("Could not set font point size " + String(pointSize));
  205. return 0;
  206. }
  207. SharedPtr<FontFace> newFace(new FontFace());
  208. FT_GlyphSlot slot = face->glyph;
  209. unsigned numGlyphs = 0;
  210. // Build glyph mapping
  211. FT_UInt glyphIndex;
  212. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  213. while (glyphIndex != 0)
  214. {
  215. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  216. newFace->glyphMapping_[charCode] = glyphIndex;
  217. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  218. }
  219. LOGDEBUG("Font face has " + String(numGlyphs) + " glyphs");
  220. // Load each of the glyphs to see the sizes & store other information
  221. int maxOffsetY = 0;
  222. int maxHeight = 0;
  223. FT_Pos ascender = face->size->metrics.ascender;
  224. newFace->glyphs_.Reserve(numGlyphs);
  225. for (unsigned i = 0; i < numGlyphs; ++i)
  226. {
  227. FontGlyph newGlyph;
  228. error = FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  229. if (!error)
  230. {
  231. // Note: position within texture will be filled later
  232. newGlyph.width_ = (short)((slot->metrics.width) >> 6);
  233. newGlyph.height_ = (short)((slot->metrics.height) >> 6);
  234. newGlyph.offsetX_ = (short)((slot->metrics.horiBearingX) >> 6);
  235. newGlyph.offsetY_ = (short)((ascender - slot->metrics.horiBearingY) >> 6);
  236. newGlyph.advanceX_ = (short)((slot->metrics.horiAdvance) >> 6);
  237. maxOffsetY = Max(maxOffsetY, newGlyph.offsetY_);
  238. maxHeight = Max(maxHeight, newGlyph.height_);
  239. }
  240. else
  241. {
  242. newGlyph.width_ = 0;
  243. newGlyph.height_ = 0;
  244. newGlyph.offsetX_ = 0;
  245. newGlyph.offsetY_ = 0;
  246. newGlyph.advanceX_ = 0;
  247. }
  248. newFace->glyphs_.Push(newGlyph);
  249. }
  250. // Store kerning if face has kerning information
  251. if (FT_HAS_KERNING(face))
  252. {
  253. newFace->hasKerning_ = true;
  254. for (unsigned i = 0; i < numGlyphs; ++i)
  255. {
  256. for (unsigned j = 0; j < numGlyphs; ++j)
  257. {
  258. FT_Vector vector;
  259. FT_Get_Kerning(face, i, j, FT_KERNING_DEFAULT, &vector);
  260. newFace->glyphs_[i].kerning_[j] = (short)(vector.x >> 6);
  261. }
  262. }
  263. }
  264. // Store point size and the height of a row. Use the height of the tallest font if taller than the specified row height
  265. newFace->pointSize_ = pointSize;
  266. newFace->rowHeight_ = Max((face->size->metrics.height + 63) >> 6, maxHeight);
  267. // Now try to pack into the smallest possible texture(s)
  268. unsigned totalTextureSize = 0;
  269. unsigned page = 0;
  270. unsigned startIndex = 0;
  271. unsigned index;
  272. while (startIndex < numGlyphs)
  273. {
  274. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MAX_SIZE, FONT_TEXTURE_MAX_SIZE);
  275. for (index = startIndex; index < numGlyphs; ++index)
  276. {
  277. if (newFace->glyphs_[index].width_ && newFace->glyphs_[index].height_)
  278. {
  279. int x, y;
  280. // Reserve an empty border between glyphs for filtering
  281. if (allocator.Allocate(newFace->glyphs_[index].width_ + 1, newFace->glyphs_[index].height_ + 1, x, y))
  282. {
  283. newFace->glyphs_[index].x_ = x;
  284. newFace->glyphs_[index].y_ = y;
  285. newFace->glyphs_[index].page_ = page;
  286. }
  287. else
  288. break;
  289. }
  290. else
  291. {
  292. newFace->glyphs_[index].x_ = 0;
  293. newFace->glyphs_[index].y_ = 0;
  294. newFace->glyphs_[index].page_ = 0;
  295. }
  296. }
  297. int texWidth = allocator.GetSize().x_;
  298. int texHeight = allocator.GetSize().y_;
  299. // Create the image for rendering the fonts
  300. SharedPtr<Image> image(new Image(context_));
  301. image->SetSize(texWidth, texHeight, 1);
  302. // First clear the whole image
  303. unsigned char* imageData = image->GetData();
  304. for (int y = 0; y < texHeight; ++y)
  305. {
  306. unsigned char* dest = imageData + texWidth * y;
  307. memset(dest, 0, texWidth);
  308. }
  309. // Render glyphs into texture, and find out a scaling value in case font uses less than full opacity (thin outlines)
  310. unsigned char avgMaxOpacity = 255;
  311. unsigned sumMaxOpacity = 0;
  312. unsigned samples = 0;
  313. for (unsigned i = startIndex; i < index; ++i)
  314. {
  315. if (!newFace->glyphs_[i].width_ || !newFace->glyphs_[i].height_)
  316. continue;
  317. FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  318. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  319. unsigned char glyphOpacity = 0;
  320. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  321. {
  322. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  323. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  324. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  325. {
  326. dest[x] = src[x];
  327. glyphOpacity = Max(glyphOpacity, src[x]);
  328. }
  329. }
  330. if (glyphOpacity)
  331. {
  332. sumMaxOpacity += glyphOpacity;
  333. ++samples;
  334. }
  335. }
  336. // Clamp the minimum possible value to avoid overbrightening
  337. if (samples)
  338. avgMaxOpacity = Max(sumMaxOpacity / samples, 128);
  339. if (avgMaxOpacity < 255)
  340. {
  341. // Apply the scaling value if necessary
  342. float scale = 255.0f / avgMaxOpacity;
  343. for (unsigned i = 0; i < numGlyphs; ++i)
  344. {
  345. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  346. {
  347. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  348. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  349. {
  350. int pixel = dest[x];
  351. dest[x] = Min((int)(pixel * scale), 255);
  352. }
  353. }
  354. }
  355. }
  356. // Create the texture and load the image into it
  357. Texture2D* texture = new Texture2D(context_);
  358. texture->SetNumLevels(1); // No mipmaps
  359. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  360. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  361. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  362. if (!texture->SetSize(texWidth, texHeight, Graphics::GetAlphaFormat()) || !texture->Load(image, true))
  363. {
  364. delete texture;
  365. LOGERROR("Could not set texture to the required size");
  366. return 0;
  367. }
  368. newFace->textures_.Push(SharedPtr<Texture>(texture)); // Pass the texture ownership to FontFace
  369. totalTextureSize += texWidth * texHeight;
  370. ++page;
  371. startIndex = index;
  372. }
  373. FT_Done_Face(face);
  374. SetMemoryUse(GetMemoryUse() + totalTextureSize);
  375. faces_[pointSize] = newFace;
  376. return newFace;
  377. }
  378. const FontFace* Font::GetFaceBitmap(int pointSize)
  379. {
  380. SharedPtr<XMLFile> xmlReader(new XMLFile(context_));
  381. MemoryBuffer memoryBuffer(fontData_, fontDataSize_);
  382. if (!xmlReader->Load(memoryBuffer))
  383. {
  384. LOGERROR("Could not load XML file");
  385. return 0;
  386. }
  387. XMLElement root = xmlReader->GetRoot("font");
  388. if (root.IsNull())
  389. {
  390. LOGERROR("Could not find Font element");
  391. return 0;
  392. }
  393. XMLElement pagesElem = root.GetChild("pages");
  394. if (pagesElem.IsNull())
  395. {
  396. LOGERROR("Could not find Pages element");
  397. return 0;
  398. }
  399. SharedPtr<FontFace> newFace(new FontFace());
  400. XMLElement commonElem = root.GetChild("common");
  401. newFace->rowHeight_ = commonElem.GetInt("lineHeight");
  402. unsigned pages = commonElem.GetInt("pages");
  403. ResourceCache* resourceCache = GetSubsystem<ResourceCache>();
  404. String fontPath = GetPath(pathName_);
  405. unsigned totalTextureSize = 0;
  406. for (unsigned i = 0; i < pages; ++i)
  407. {
  408. XMLElement pageElem = pagesElem.GetChild("page");
  409. if (pageElem.IsNull())
  410. {
  411. LOGERROR("Could not find Page element for page: " + String(i));
  412. return 0;
  413. }
  414. // Assume the font image is in the same directory as the font description file
  415. String textureFile = fontPath + pageElem.GetAttribute("file");
  416. // Load texture manually to allow controlling the alpha channel mode
  417. SharedPtr<File> fontFile = resourceCache->GetFile(textureFile);
  418. SharedPtr<Image> fontImage(new Image(context_));
  419. if (!fontFile || !fontImage->Load(*fontFile))
  420. {
  421. LOGERROR("Failed to load font image file");
  422. return 0;
  423. }
  424. Texture2D* texture = new Texture2D(context_);
  425. if (!texture->Load(fontImage, true))
  426. {
  427. delete texture;
  428. LOGERROR("Failed to create font texture");
  429. return 0;
  430. }
  431. newFace->textures_.Push(SharedPtr<Texture>(texture));
  432. totalTextureSize += fontImage->GetWidth() * fontImage->GetHeight() * fontImage->GetComponents();
  433. }
  434. XMLElement charsElem = root.GetChild("chars");
  435. int count = charsElem.GetInt("count");
  436. newFace->glyphs_.Reserve(count);
  437. unsigned index = 0;
  438. XMLElement charElem = charsElem.GetChild("char");
  439. while (!charElem.IsNull())
  440. {
  441. int id = charElem.GetInt("id");
  442. FontGlyph glyph;
  443. glyph.x_ = charElem.GetInt("x");
  444. glyph.y_ = charElem.GetInt("y");
  445. glyph.width_ = charElem.GetInt("width");
  446. glyph.height_ = charElem.GetInt("height");
  447. glyph.offsetX_ = charElem.GetInt("xoffset");
  448. glyph.offsetY_ = charElem.GetInt("yoffset");
  449. glyph.advanceX_ = charElem.GetInt("xadvance");
  450. glyph.page_ = charElem.GetInt("page");
  451. newFace->glyphs_.Push(glyph);
  452. newFace->glyphMapping_[id] = index++;
  453. charElem = charElem.GetNext("char");
  454. }
  455. XMLElement kerningsElem = root.GetChild("kernings");
  456. if (kerningsElem.IsNull())
  457. newFace->hasKerning_ = false;
  458. else
  459. {
  460. XMLElement kerningElem = kerningsElem.GetChild("kerning");
  461. while (!kerningElem.IsNull())
  462. {
  463. int first = kerningElem.GetInt("first");
  464. HashMap<unsigned, unsigned>::Iterator i = newFace->glyphMapping_.Find(first);
  465. if (i != newFace->glyphMapping_.End())
  466. {
  467. int second = kerningElem.GetInt("second");
  468. int amount = kerningElem.GetInt("amount");
  469. FontGlyph& fg = newFace->glyphs_[i->second_];
  470. fg.kerning_[second] = amount;
  471. }
  472. kerningElem = kerningElem.GetNext("kerning");
  473. }
  474. }
  475. SetMemoryUse(GetMemoryUse() + totalTextureSize);
  476. faces_[pointSize] = newFace;
  477. return newFace;
  478. }
  479. }