Font.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 "Deserializer.h"
  25. #include "Font.h"
  26. #include "Profiler.h"
  27. #include "Renderer.h"
  28. #include "RendererImpl.h"
  29. #include "StringUtils.h"
  30. #include "Texture2D.h"
  31. #include <stb_truetype.h>
  32. #include <windows.h>
  33. #include "DebugNew.h"
  34. Font::Font(Renderer* renderer, const std::string& name) :
  35. Resource(name),
  36. mRenderer(renderer),
  37. mFontDataSize(0)
  38. {
  39. }
  40. Font::~Font()
  41. {
  42. }
  43. void Font::load(Deserializer& source, ResourceCache* cache)
  44. {
  45. mFaces.clear();
  46. mFontDataSize = source.getSize();
  47. if (source.getSize())
  48. {
  49. mFontData = new unsigned char[mFontDataSize];
  50. source.read(&mFontData[0], source.getSize());
  51. }
  52. else
  53. mFontData.reset();
  54. setMemoryUse(mFontDataSize);
  55. }
  56. const FontFace* Font::getFace(int pointSize)
  57. {
  58. std::map<int, FontFace>::const_iterator i = mFaces.find(pointSize);
  59. if (i != mFaces.end())
  60. return &i->second;
  61. PROFILE(Font_GetFace);
  62. if (pointSize <= 0)
  63. EXCEPTION("Zero or negative point size");
  64. if (!mFontData)
  65. EXCEPTION("Font not loaded");
  66. FontFace newFace;
  67. stbtt_fontinfo fontInfo;
  68. // Assume 1 font per file for now
  69. if (!stbtt_InitFont(&fontInfo, &mFontData[0], 0))
  70. EXCEPTION("Could not initialize font");
  71. std::vector<bool> glyphUsed;
  72. glyphUsed.resize(fontInfo.numGlyphs);
  73. for (int i = 0; i < fontInfo.numGlyphs; ++i)
  74. glyphUsed[i] = false;
  75. // Build glyph mapping and mark used glyphs
  76. for (int i = 0; i < MAX_FONT_CHARS; ++i)
  77. {
  78. newFace.mGlyphIndex[i] = stbtt_FindGlyphIndex(&fontInfo, i);
  79. glyphUsed[newFace.mGlyphIndex[i]] = true;
  80. }
  81. // Get row height
  82. int ascent, descent, lineGap;
  83. stbtt_GetFontVMetrics(&fontInfo, &ascent, &descent, &lineGap);
  84. // Calculate scale (use ascent only)
  85. float scale = (float)pointSize / ascent;
  86. // Go through glyphs to get their dimensions & offsets
  87. for (int i = 0; i < fontInfo.numGlyphs; ++i)
  88. {
  89. FontGlyph newGlyph;
  90. int ix0, iy0, ix1, iy1;
  91. int advanceWidth, leftSideBearing;
  92. if (glyphUsed[i])
  93. {
  94. stbtt_GetGlyphBitmapBox(&fontInfo, i, scale, scale, &ix0, &iy0, &ix1, &iy1);
  95. stbtt_GetGlyphHMetrics(&fontInfo, i, &advanceWidth, &leftSideBearing);
  96. newGlyph.mWidth = ix1 - ix0;
  97. newGlyph.mHeight = iy1 - iy0;
  98. newGlyph.mOffsetX = (int)(leftSideBearing * scale);
  99. newGlyph.mOffsetY = iy0;
  100. newGlyph.mAdvanceX = (int)(advanceWidth * scale);
  101. }
  102. else
  103. {
  104. newGlyph.mWidth = 0;
  105. newGlyph.mHeight = 0;
  106. newGlyph.mOffsetX = 0;
  107. newGlyph.mOffsetY = 0;
  108. newGlyph.mAdvanceX = 0;
  109. }
  110. newFace.mGlyphs.push_back(newGlyph);
  111. }
  112. // Adjust the Y-offset so that the fonts are top-aligned
  113. int scaledAscent = (int)(scale * ascent);
  114. for (int i = 0; i < fontInfo.numGlyphs; ++i)
  115. {
  116. if (glyphUsed[i])
  117. newFace.mGlyphs[i].mOffsetY += scaledAscent;
  118. }
  119. // Calculate row advance
  120. newFace.mRowHeight = (int)(scale * (ascent - descent + lineGap));
  121. // Now try to pack into the smallest possible texture
  122. int texWidth = FONT_TEXTURE_MIN_SIZE;
  123. int texHeight = FONT_TEXTURE_MIN_SIZE;
  124. bool doubleHorizontal = true;
  125. for (;;)
  126. {
  127. bool success = true;
  128. // Check first for theoretical possible fit. If it fails, there is no need to try to fit
  129. int totalArea = 0;
  130. for (int i = 0; i < fontInfo.numGlyphs; ++i)
  131. {
  132. if ((newFace.mGlyphs[i].mWidth) && (newFace.mGlyphs[i].mHeight))
  133. totalArea += (newFace.mGlyphs[i].mWidth + 1) * (newFace.mGlyphs[i].mHeight + 1);
  134. }
  135. if (totalArea > texWidth * texHeight)
  136. success = false;
  137. else
  138. {
  139. PROFILE(Font_FitToTexture);
  140. AreaAllocator allocator(texWidth, texHeight);
  141. for (int i = 0; i < fontInfo.numGlyphs; ++i)
  142. {
  143. if ((newFace.mGlyphs[i].mWidth) && (newFace.mGlyphs[i].mHeight))
  144. {
  145. int x, y;
  146. // Reserve an empty border between glyphs for filtering
  147. if (!allocator.reserve(newFace.mGlyphs[i].mWidth + 1, newFace.mGlyphs[i].mHeight + 1, x, y))
  148. {
  149. success = false;
  150. break;
  151. }
  152. else
  153. {
  154. newFace.mGlyphs[i].mX = x;
  155. newFace.mGlyphs[i].mY = y;
  156. }
  157. }
  158. else
  159. {
  160. newFace.mGlyphs[i].mX = 0;
  161. newFace.mGlyphs[i].mY = 0;
  162. }
  163. }
  164. }
  165. if (!success)
  166. {
  167. // Alternate between doubling the horizontal and the vertical dimension
  168. if (doubleHorizontal)
  169. texWidth <<= 1;
  170. else
  171. texHeight <<= 1;
  172. if ((texWidth > FONT_TEXTURE_MAX_SIZE) || (texHeight > FONT_TEXTURE_MAX_SIZE))
  173. EXCEPTION("Font face could not be fit into the largest possible texture");
  174. doubleHorizontal = !doubleHorizontal;
  175. }
  176. else
  177. break;
  178. }
  179. // Create the texture
  180. if (mRenderer)
  181. {
  182. SharedPtr<Texture2D> texture(new Texture2D(mRenderer, TEXTURE_STATIC));
  183. texture->setNumLevels(1); // No mipmaps
  184. texture->setAddressMode(COORD_U, ADDRESS_BORDER);
  185. texture->setAddressMode(COORD_V, ADDRESS_BORDER),
  186. texture->setBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  187. texture->setSize(texWidth, texHeight, D3DFMT_A8);
  188. D3DLOCKED_RECT hwRect;
  189. texture->lock(0, 0, &hwRect);
  190. // First clear the whole texture
  191. for (int y = 0; y < texHeight; ++y)
  192. {
  193. unsigned char* dest = (unsigned char*)hwRect.pBits + hwRect.Pitch * y;
  194. memset(dest, 0, texWidth);
  195. }
  196. // Render glyphs into texture, and find out a scaling value in case font uses less than full opacity (thin outlines)
  197. int sumOpacity = 0;
  198. int nonEmptyGlyphs = 0;
  199. for (int i = 0; i < fontInfo.numGlyphs; ++i)
  200. {
  201. if ((newFace.mGlyphs[i].mWidth) && (newFace.mGlyphs[i].mHeight))
  202. {
  203. stbtt_MakeGlyphBitmap(&fontInfo, (unsigned char*)hwRect.pBits + hwRect.Pitch * newFace.mGlyphs[i].mY + newFace.mGlyphs[i].mX, newFace.mGlyphs[i].mWidth, newFace.mGlyphs[i].mHeight, hwRect.Pitch, scale, scale, i);
  204. int glyphMaxOpacity = 0;
  205. for (int y = 0; y < newFace.mGlyphs[i].mHeight; ++y)
  206. {
  207. unsigned char* pixels = (unsigned char*)hwRect.pBits + hwRect.Pitch * (y + newFace.mGlyphs[i].mY) + newFace.mGlyphs[i].mX;
  208. for (int x = 0; x < newFace.mGlyphs[i].mWidth; ++x)
  209. glyphMaxOpacity = max(glyphMaxOpacity, pixels[x]);
  210. }
  211. if (glyphMaxOpacity > 0)
  212. {
  213. sumOpacity += glyphMaxOpacity;
  214. ++nonEmptyGlyphs;
  215. }
  216. }
  217. }
  218. // Apply the scaling if necessary
  219. int avgOpacity = nonEmptyGlyphs ? sumOpacity / nonEmptyGlyphs : 255;
  220. if (avgOpacity < 255)
  221. {
  222. float scale = 255.0f / avgOpacity;
  223. for (int i = 0; i < fontInfo.numGlyphs; ++i)
  224. {
  225. for (int y = 0; y < newFace.mGlyphs[i].mHeight; ++y)
  226. {
  227. unsigned char* dest = (unsigned char*)hwRect.pBits + hwRect.Pitch * (y + newFace.mGlyphs[i].mY) + newFace.mGlyphs[i].mX;
  228. for (int x = 0; x < newFace.mGlyphs[i].mWidth; ++x)
  229. {
  230. int pixel = dest[x];
  231. dest[x] = min((int)(pixel * scale), 255);
  232. }
  233. }
  234. }
  235. }
  236. texture->unlock();
  237. setMemoryUse(getMemoryUse() + texWidth * texHeight);
  238. newFace.mTexture = staticCast<Texture>(texture);
  239. }
  240. mFaces[pointSize] = newFace;
  241. return &mFaces[pointSize];
  242. }
  243. std::string getSystemFontDirectory()
  244. {
  245. char expandedSystemPath[256];
  246. if (!ExpandEnvironmentStrings("%WinDir%", expandedSystemPath, 256))
  247. return std::string();
  248. return std::string(expandedSystemPath) + "\\Fonts";
  249. }