Font.cpp 13 KB

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