Font.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 "GraphicsImpl.h"
  30. #include "Log.h"
  31. #include "Profiler.h"
  32. #include "Texture2D.h"
  33. #include "ft2build.h"
  34. #include FT_FREETYPE_H
  35. #include "DebugNew.h"
  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. OBJECTTYPESTATIC(FreeTypeLibrary);
  60. OBJECTTYPESTATIC(Font);
  61. Font::Font(Context* context) :
  62. Resource(context),
  63. fontDataSize_(0)
  64. {
  65. // Create & initialize FreeType library if it does not exist yet
  66. if (!GetSubsystem<FreeTypeLibrary>())
  67. context_->RegisterSubsystem(new FreeTypeLibrary(context_));
  68. }
  69. Font::~Font()
  70. {
  71. }
  72. void Font::RegisterObject(Context* context)
  73. {
  74. context->RegisterFactory<Font>();
  75. }
  76. bool Font::Load(Deserializer& source)
  77. {
  78. PROFILE(LoadFont);
  79. faces_.Clear();
  80. fontDataSize_ = source.GetSize();
  81. if (fontDataSize_)
  82. {
  83. fontData_ = new unsigned char[fontDataSize_];
  84. if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
  85. return false;
  86. }
  87. else
  88. {
  89. fontData_.Reset();
  90. return false;
  91. }
  92. SetMemoryUse(fontDataSize_);
  93. return true;
  94. }
  95. const FontFace* Font::GetFace(int pointSize)
  96. {
  97. Map<int, FontFace>::ConstIterator i = faces_.Find(pointSize);
  98. if (i != faces_.End())
  99. return &i->second_;
  100. PROFILE(GetFontFace);
  101. FT_Face face;
  102. FT_Error error;
  103. FT_Library library = GetSubsystem<FreeTypeLibrary>()->getLibrary();
  104. if (pointSize <= 0)
  105. {
  106. LOGERROR("Zero or negative point size");
  107. return 0;
  108. }
  109. if (!fontDataSize_)
  110. {
  111. LOGERROR("Font not loaded");
  112. return 0;
  113. }
  114. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  115. if (error)
  116. {
  117. LOGERROR("Could not create font face");
  118. return 0;
  119. }
  120. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  121. if (error)
  122. {
  123. FT_Done_Face(face);
  124. LOGERROR("Could not set font point size " + pointSize);
  125. return 0;
  126. }
  127. FontFace newFace;
  128. FT_GlyphSlot slot = face->glyph;
  129. unsigned freeIndex = 0;
  130. Map<unsigned, unsigned> toRemapped;
  131. Vector<unsigned> toOriginal;
  132. // Build glyph mapping. Only render the glyphs needed by the charset
  133. for (unsigned i = 0; i < MAX_FONT_CHARS; ++i)
  134. {
  135. unsigned index = FT_Get_Char_Index(face, i);
  136. if (toRemapped.Find(index) == toRemapped.End())
  137. {
  138. newFace.glyphIndex_[i] = freeIndex;
  139. toRemapped[index] = freeIndex;
  140. toOriginal.Push(index);
  141. ++freeIndex;
  142. }
  143. else
  144. newFace.glyphIndex_[i] = toRemapped[index];
  145. }
  146. // Load each of the glyphs to see the sizes & store other information
  147. int maxOffsetY = 0;
  148. int maxHeight = 0;
  149. for (unsigned i = 0; i < toOriginal.Size(); ++i)
  150. {
  151. FontGlyph newGlyph;
  152. error = FT_Load_Glyph(face, toOriginal[i], FT_LOAD_DEFAULT);
  153. if (!error)
  154. {
  155. // Note: position within texture will be filled later
  156. newGlyph.width_ = (short)((slot->metrics.width) >> 6);
  157. newGlyph.height_ = (short)((slot->metrics.height) >> 6);
  158. newGlyph.offsetX_ = (short)((slot->metrics.horiBearingX) >> 6);
  159. newGlyph.offsetY_ = (short)((face->size->metrics.ascender - slot->metrics.horiBearingY) >> 6);
  160. newGlyph.advanceX_ = (short)((slot->metrics.horiAdvance) >> 6);
  161. maxOffsetY = Max(maxOffsetY, newGlyph.offsetY_);
  162. maxHeight = Max(maxHeight, newGlyph.height_);
  163. }
  164. else
  165. {
  166. newGlyph.width_ = 0;
  167. newGlyph.height_ = 0;
  168. newGlyph.offsetX_ = 0;
  169. newGlyph.offsetY_ = 0;
  170. newGlyph.advanceX_ = 0;
  171. }
  172. newFace.glyphs_.Push(newGlyph);
  173. }
  174. // Store point size and the height of a row
  175. newFace.pointSize_ = pointSize;
  176. newFace.rowHeight_ = (face->size->metrics.height + 63) >> 6;
  177. // Now try to pack into the smallest possible texture
  178. int texWidth = FONT_TEXTURE_MIN_SIZE;
  179. int texHeight = FONT_TEXTURE_MIN_SIZE;
  180. bool doubleHorizontal = true;
  181. for (;;)
  182. {
  183. bool success = true;
  184. // Check first for theoretical possible fit. If it fails, there is no need to try to fit
  185. int totalArea = 0;
  186. for (unsigned i = 0; i < newFace.glyphs_.Size(); ++i)
  187. totalArea += (newFace.glyphs_[i].width_ + 1) * (newFace.glyphs_[i].height_ + 1);
  188. if (totalArea > texWidth * texHeight)
  189. success = false;
  190. else
  191. {
  192. AreaAllocator allocator(texWidth, texHeight);
  193. for (unsigned i = 0; i < newFace.glyphs_.Size(); ++i)
  194. {
  195. if ((newFace.glyphs_[i].width_) && (newFace.glyphs_[i].height_))
  196. {
  197. int x, y;
  198. // Reserve an empty border between glyphs for filtering
  199. if (!allocator.Allocate(newFace.glyphs_[i].width_ + 1, newFace.glyphs_[i].height_ + 1, x, y))
  200. {
  201. success = false;
  202. break;
  203. }
  204. else
  205. {
  206. newFace.glyphs_[i].x_ = x;
  207. newFace.glyphs_[i].y_ = y;
  208. }
  209. }
  210. else
  211. {
  212. newFace.glyphs_[i].x_ = 0;
  213. newFace.glyphs_[i].y_ = 0;
  214. }
  215. }
  216. }
  217. if (!success)
  218. {
  219. // Alternate between doubling the horizontal and the vertical dimension
  220. if (doubleHorizontal)
  221. texWidth <<= 1;
  222. else
  223. texHeight <<= 1;
  224. if ((texWidth > FONT_TEXTURE_MAX_SIZE) || (texHeight > FONT_TEXTURE_MAX_SIZE))
  225. {
  226. FT_Done_Face(face);
  227. LOGERROR("Font face could not be fit into the largest possible texture");
  228. return 0;
  229. }
  230. doubleHorizontal = !doubleHorizontal;
  231. }
  232. else
  233. break;
  234. }
  235. // Create the texture
  236. SharedPtr<Texture2D> texture(new Texture2D(context_));
  237. texture->SetNumLevels(1); // No mipmaps
  238. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  239. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  240. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  241. if (!texture->SetSize(texWidth, texHeight, D3DFMT_A8))
  242. {
  243. FT_Done_Face(face);
  244. return 0;
  245. }
  246. D3DLOCKED_RECT hwRect;
  247. if (!texture->Lock(0, 0, &hwRect))
  248. {
  249. FT_Done_Face(face);
  250. return 0;
  251. }
  252. // First clear the whole texture
  253. for (int y = 0; y < texHeight; ++y)
  254. {
  255. unsigned char* dest = (unsigned char*)hwRect.pBits + hwRect.Pitch * y;
  256. memset(dest, 0, texWidth);
  257. }
  258. // Render glyphs into texture, and find out a scaling value in case font uses less than full opacity (thin outlines)
  259. unsigned char avgMaxOpacity = 255;
  260. unsigned sumax_Opacity = 0;
  261. unsigned samples = 0;
  262. for (unsigned i = 0; i < newFace.glyphs_.Size(); ++i)
  263. {
  264. FT_Load_Glyph(face, toOriginal[i], FT_LOAD_DEFAULT);
  265. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  266. unsigned char glyphOpacity = 0;
  267. for (int y = 0; y < newFace.glyphs_[i].height_; ++y)
  268. {
  269. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  270. unsigned char* dest = (unsigned char*)hwRect.pBits + hwRect.Pitch * (y + newFace.glyphs_[i].y_) + newFace.glyphs_[i].x_;
  271. for (int x = 0; x < newFace.glyphs_[i].width_; ++x)
  272. {
  273. dest[x] = src[x];
  274. glyphOpacity = Max(glyphOpacity, src[x]);
  275. }
  276. }
  277. if (glyphOpacity)
  278. {
  279. sumax_Opacity += glyphOpacity;
  280. ++samples;
  281. }
  282. }
  283. // Clamp the minimum possible value to avoid overbrightening
  284. if (samples)
  285. avgMaxOpacity = Max(sumax_Opacity / samples, 128);
  286. if (avgMaxOpacity < 255)
  287. {
  288. // Apply the scaling value if necessary
  289. float scale = 255.0f / avgMaxOpacity;
  290. for (unsigned i = 0; i < newFace.glyphs_.Size(); ++i)
  291. {
  292. for (int y = 0; y < newFace.glyphs_[i].height_; ++y)
  293. {
  294. unsigned char* dest = (unsigned char*)hwRect.pBits + hwRect.Pitch * (y + newFace.glyphs_[i].y_) + newFace.glyphs_[i].x_;
  295. for (int x = 0; x < newFace.glyphs_[i].width_; ++x)
  296. {
  297. int pixel = dest[x];
  298. dest[x] = Min((int)(pixel * scale), 255);
  299. }
  300. }
  301. }
  302. }
  303. texture->Unlock();
  304. FT_Done_Face(face);
  305. SetMemoryUse(GetMemoryUse() + texWidth * texHeight);
  306. newFace.texture_ = StaticCast<Texture>(texture);
  307. faces_[pointSize] = newFace;
  308. return &faces_[pointSize];
  309. }