Font.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 "Font.h"
  27. #include "Graphics.h"
  28. #include "Log.h"
  29. #include "Profiler.h"
  30. #include "Texture2D.h"
  31. #include <ft2build.h>
  32. #include FT_FREETYPE_H
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. /// FreeType library subsystem.
  37. class FreeTypeLibrary : public Object
  38. {
  39. OBJECT(FreeTypeLibrary);
  40. public:
  41. /// Construct.
  42. FreeTypeLibrary(Context* context) :
  43. Object(context)
  44. {
  45. FT_Error error = FT_Init_FreeType(&mLibrary);
  46. if (error)
  47. LOGERROR("Could not initialize FreeType library");
  48. }
  49. /// Destruct.
  50. virtual ~FreeTypeLibrary()
  51. {
  52. FT_Done_FreeType(mLibrary);
  53. }
  54. FT_Library getLibrary() const { return mLibrary; }
  55. private:
  56. /// FreeType library.
  57. FT_Library mLibrary;
  58. };
  59. FontFace::FontFace() :
  60. hasKerning_(false)
  61. {
  62. }
  63. FontFace::~FontFace()
  64. {
  65. }
  66. const FontGlyph& FontFace::GetGlyph(unsigned c) const
  67. {
  68. HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Find(c);
  69. if (i != glyphMapping_.End())
  70. return glyphs_[i->second_];
  71. else
  72. return glyphs_[0];
  73. }
  74. short FontFace::GetKerning(unsigned c, unsigned d) const
  75. {
  76. if (!hasKerning_)
  77. return 0;
  78. if (c == '\n' || d == '\n')
  79. return 0;
  80. unsigned leftIndex = 0;
  81. unsigned rightIndex = 0;
  82. HashMap<unsigned, unsigned>::ConstIterator leftIt = glyphMapping_.Find(c);
  83. HashMap<unsigned, unsigned>::ConstIterator rightIt = glyphMapping_.Find(d);
  84. if (leftIt != glyphMapping_.End())
  85. leftIndex = leftIt->second_;
  86. if (rightIt != glyphMapping_.End())
  87. rightIndex = rightIt->second_;
  88. HashMap<unsigned, unsigned>::ConstIterator kerningIt = glyphs_[leftIndex].kerning_.Find(rightIndex);
  89. if (kerningIt != glyphs_[leftIndex].kerning_.End())
  90. return kerningIt->second_;
  91. else
  92. return 0;
  93. }
  94. OBJECTTYPESTATIC(FreeTypeLibrary);
  95. OBJECTTYPESTATIC(Font);
  96. Font::Font(Context* context) :
  97. Resource(context),
  98. fontDataSize_(0)
  99. {
  100. // Create & initialize FreeType library if it does not exist yet
  101. if (!GetSubsystem<FreeTypeLibrary>())
  102. context_->RegisterSubsystem(new FreeTypeLibrary(context_));
  103. }
  104. Font::~Font()
  105. {
  106. }
  107. void Font::RegisterObject(Context* context)
  108. {
  109. context->RegisterFactory<Font>();
  110. }
  111. bool Font::Load(Deserializer& source)
  112. {
  113. PROFILE(LoadFont);
  114. faces_.Clear();
  115. fontDataSize_ = source.GetSize();
  116. if (fontDataSize_)
  117. {
  118. fontData_ = new unsigned char[fontDataSize_];
  119. if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
  120. return false;
  121. }
  122. else
  123. {
  124. fontData_.Reset();
  125. return false;
  126. }
  127. SetMemoryUse(fontDataSize_);
  128. return true;
  129. }
  130. const FontFace* Font::GetFace(int pointSize)
  131. {
  132. HashMap<int, SharedPtr<FontFace> >::ConstIterator i = faces_.Find(pointSize);
  133. if (i != faces_.End())
  134. {
  135. if (!i->second_->texture_->IsDataLost())
  136. return i->second_;
  137. else
  138. {
  139. // Erase and reload face if texture data lost (OpenGL mode only)
  140. faces_.Erase(pointSize);
  141. }
  142. }
  143. PROFILE(GetFontFace);
  144. FT_Face face;
  145. FT_Error error;
  146. FT_Library library = GetSubsystem<FreeTypeLibrary>()->getLibrary();
  147. if (pointSize <= 0)
  148. {
  149. LOGERROR("Zero or negative point size");
  150. return 0;
  151. }
  152. if (!fontDataSize_)
  153. {
  154. LOGERROR("Font not loaded");
  155. return 0;
  156. }
  157. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  158. if (error)
  159. {
  160. LOGERROR("Could not create font face");
  161. return 0;
  162. }
  163. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  164. if (error)
  165. {
  166. FT_Done_Face(face);
  167. LOGERROR("Could not set font point size " + String(pointSize));
  168. return 0;
  169. }
  170. SharedPtr<FontFace> newFace(new FontFace());
  171. FT_GlyphSlot slot = face->glyph;
  172. unsigned numGlyphs = 0;
  173. // Build glyph mapping
  174. FT_UInt glyphIndex;
  175. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  176. while (glyphIndex != 0)
  177. {
  178. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  179. newFace->glyphMapping_[charCode] = glyphIndex;
  180. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  181. }
  182. LOGDEBUG("Font face has " + String(numGlyphs) + " glyphs");
  183. // Load each of the glyphs to see the sizes & store other information
  184. int maxOffsetY = 0;
  185. int maxHeight = 0;
  186. FT_Pos ascender = face->size->metrics.ascender;
  187. newFace->glyphs_.Reserve(numGlyphs);
  188. for (unsigned i = 0; i < numGlyphs; ++i)
  189. {
  190. FontGlyph newGlyph;
  191. error = FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  192. if (!error)
  193. {
  194. // Note: position within texture will be filled later
  195. newGlyph.width_ = (short)((slot->metrics.width) >> 6);
  196. newGlyph.height_ = (short)((slot->metrics.height) >> 6);
  197. newGlyph.offsetX_ = (short)((slot->metrics.horiBearingX) >> 6);
  198. newGlyph.offsetY_ = (short)((ascender - slot->metrics.horiBearingY) >> 6);
  199. newGlyph.advanceX_ = (short)((slot->metrics.horiAdvance) >> 6);
  200. maxOffsetY = Max(maxOffsetY, newGlyph.offsetY_);
  201. maxHeight = Max(maxHeight, newGlyph.height_);
  202. }
  203. else
  204. {
  205. newGlyph.width_ = 0;
  206. newGlyph.height_ = 0;
  207. newGlyph.offsetX_ = 0;
  208. newGlyph.offsetY_ = 0;
  209. newGlyph.advanceX_ = 0;
  210. }
  211. newFace->glyphs_.Push(newGlyph);
  212. }
  213. // Store kerning if face has kerning information
  214. if (FT_HAS_KERNING(face))
  215. {
  216. newFace->hasKerning_ = true;
  217. for (unsigned i = 0; i < numGlyphs; ++i)
  218. {
  219. for (unsigned j = 0; j < numGlyphs; ++j)
  220. {
  221. FT_Vector vector;
  222. FT_Get_Kerning(face, i, j, FT_KERNING_DEFAULT, &vector);
  223. newFace->glyphs_[i].kerning_[j] = (short)(vector.x >> 6);
  224. }
  225. }
  226. }
  227. // Store point size and the height of a row. Use the height of the tallest font if taller than the specified row height
  228. newFace->pointSize_ = pointSize;
  229. newFace->rowHeight_ = Max((face->size->metrics.height + 63) >> 6, maxHeight);
  230. // Now try to pack into the smallest possible texture
  231. int texWidth = FONT_TEXTURE_MIN_SIZE;
  232. int texHeight = FONT_TEXTURE_MIN_SIZE;
  233. bool doubleHorizontal = true;
  234. for (;;)
  235. {
  236. bool success = true;
  237. // Check first for theoretical possible fit. If it fails, there is no need to try to fit
  238. int totalArea = 0;
  239. for (unsigned i = 0; i < numGlyphs; ++i)
  240. totalArea += (newFace->glyphs_[i].width_ + 1) * (newFace->glyphs_[i].height_ + 1);
  241. if (totalArea > texWidth * texHeight)
  242. success = false;
  243. else
  244. {
  245. AreaAllocator allocator(texWidth, texHeight);
  246. for (unsigned i = 0; i < numGlyphs; ++i)
  247. {
  248. if (newFace->glyphs_[i].width_ && newFace->glyphs_[i].height_)
  249. {
  250. int x, y;
  251. // Reserve an empty border between glyphs for filtering
  252. if (!allocator.Allocate(newFace->glyphs_[i].width_ + 1, newFace->glyphs_[i].height_ + 1, x, y))
  253. {
  254. success = false;
  255. break;
  256. }
  257. else
  258. {
  259. newFace->glyphs_[i].x_ = x;
  260. newFace->glyphs_[i].y_ = y;
  261. }
  262. }
  263. else
  264. {
  265. newFace->glyphs_[i].x_ = 0;
  266. newFace->glyphs_[i].y_ = 0;
  267. }
  268. }
  269. }
  270. if (!success)
  271. {
  272. // Alternate between doubling the horizontal and the vertical dimension
  273. if (doubleHorizontal)
  274. texWidth <<= 1;
  275. else
  276. texHeight <<= 1;
  277. if (texWidth > FONT_TEXTURE_MAX_SIZE || texHeight > FONT_TEXTURE_MAX_SIZE)
  278. {
  279. FT_Done_Face(face);
  280. LOGERROR("Font face could not be fit into the largest possible texture");
  281. return 0;
  282. }
  283. doubleHorizontal = !doubleHorizontal;
  284. }
  285. else
  286. break;
  287. }
  288. // Create the image for rendering the fonts
  289. SharedPtr<Image> image(new Image(context_));
  290. image->SetSize(texWidth, texHeight, 1);
  291. // First clear the whole image
  292. unsigned char* imageData = image->GetData();
  293. for (int y = 0; y < texHeight; ++y)
  294. {
  295. unsigned char* dest = imageData + texWidth * y;
  296. memset(dest, 0, texWidth);
  297. }
  298. // Render glyphs into texture, and find out a scaling value in case font uses less than full opacity (thin outlines)
  299. unsigned char avgMaxOpacity = 255;
  300. unsigned sumMaxOpacity = 0;
  301. unsigned samples = 0;
  302. for (unsigned i = 0; i < numGlyphs; ++i)
  303. {
  304. if (!newFace->glyphs_[i].width_ || !newFace->glyphs_[i].height_)
  305. continue;
  306. FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  307. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  308. unsigned char glyphOpacity = 0;
  309. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  310. {
  311. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  312. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  313. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  314. {
  315. dest[x] = src[x];
  316. glyphOpacity = Max(glyphOpacity, src[x]);
  317. }
  318. }
  319. if (glyphOpacity)
  320. {
  321. sumMaxOpacity += glyphOpacity;
  322. ++samples;
  323. }
  324. }
  325. // Clamp the minimum possible value to avoid overbrightening
  326. if (samples)
  327. avgMaxOpacity = Max(sumMaxOpacity / samples, 128);
  328. if (avgMaxOpacity < 255)
  329. {
  330. // Apply the scaling value if necessary
  331. float scale = 255.0f / avgMaxOpacity;
  332. for (unsigned i = 0; i < numGlyphs; ++i)
  333. {
  334. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  335. {
  336. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  337. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  338. {
  339. int pixel = dest[x];
  340. dest[x] = Min((int)(pixel * scale), 255);
  341. }
  342. }
  343. }
  344. }
  345. FT_Done_Face(face);
  346. // Create the texture and load the image into it
  347. SharedPtr<Texture2D> texture(new Texture2D(context_));
  348. texture->SetNumLevels(1); // No mipmaps
  349. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  350. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  351. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  352. if (!texture->SetSize(texWidth, texHeight, Graphics::GetAlphaFormat()) || !texture->Load(image, true))
  353. return 0;
  354. SetMemoryUse(GetMemoryUse() + texWidth * texHeight);
  355. newFace->texture_ = StaticCast<Texture>(texture);
  356. faces_[pointSize] = newFace;
  357. return newFace;
  358. }
  359. }