BsFontImporter.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. #include "BsFontImporter.h"
  2. #include "BsFontImportOptions.h"
  3. #include "BsPixelData.h"
  4. #include "BsTexture.h"
  5. #include "BsResources.h"
  6. #include "BsDebug.h"
  7. #include "BsTexAtlasGenerator.h"
  8. #include "BsCoreApplication.h"
  9. #include "BsCoreThread.h"
  10. #include "BsCoreThreadAccessor.h"
  11. #include <ft2build.h>
  12. #include <freetype/freetype.h>
  13. #include FT_FREETYPE_H
  14. using namespace std::placeholders;
  15. namespace BansheeEngine
  16. {
  17. FontImporter::FontImporter()
  18. :SpecificImporter()
  19. {
  20. mExtensions.push_back(L"ttf");
  21. mExtensions.push_back(L"otf");
  22. }
  23. FontImporter::~FontImporter()
  24. {
  25. }
  26. bool FontImporter::isExtensionSupported(const WString& ext) const
  27. {
  28. WString lowerCaseExt = ext;
  29. StringUtil::toLowerCase(lowerCaseExt);
  30. return find(mExtensions.begin(), mExtensions.end(), lowerCaseExt) != mExtensions.end();
  31. }
  32. bool FontImporter::isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const
  33. {
  34. // TODO
  35. return false;
  36. }
  37. ImportOptionsPtr FontImporter::createImportOptions() const
  38. {
  39. return bs_shared_ptr_new<FontImportOptions>();
  40. }
  41. ResourcePtr FontImporter::import(const Path& filePath, ConstImportOptionsPtr importOptions)
  42. {
  43. const FontImportOptions* fontImportOptions = static_cast<const FontImportOptions*>(importOptions.get());
  44. FT_Library library;
  45. FT_Error error = FT_Init_FreeType(&library);
  46. if (error)
  47. BS_EXCEPT(InternalErrorException, "Error occurred during FreeType library initialization.");
  48. FT_Face face;
  49. error = FT_New_Face(library, filePath.toString().c_str(), 0, &face);
  50. if (error == FT_Err_Unknown_File_Format)
  51. {
  52. BS_EXCEPT(InternalErrorException, "Failed to load font file: " + filePath.toString() + ". Unsupported file format.");
  53. }
  54. else if (error)
  55. {
  56. BS_EXCEPT(InternalErrorException, "Failed to load font file: " + filePath.toString() + ". Unknown error.");
  57. }
  58. Vector<std::pair<UINT32, UINT32>> charIndexRanges = fontImportOptions->getCharIndexRanges();
  59. Vector<UINT32> fontSizes = fontImportOptions->getFontSizes();
  60. UINT32 dpi = fontImportOptions->getDPI();
  61. FT_Int32 loadFlags;
  62. switch (fontImportOptions->getRenderMode())
  63. {
  64. case FontRenderMode::Smooth:
  65. loadFlags = FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING;
  66. break;
  67. case FontRenderMode::Raster:
  68. loadFlags = FT_LOAD_TARGET_MONO | FT_LOAD_NO_HINTING;
  69. break;
  70. case FontRenderMode::HintedSmooth:
  71. loadFlags = FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_AUTOHINT;
  72. break;
  73. case FontRenderMode::HintedRaster:
  74. loadFlags = FT_LOAD_TARGET_MONO | FT_LOAD_NO_AUTOHINT;
  75. break;
  76. default:
  77. loadFlags = FT_LOAD_TARGET_NORMAL;
  78. break;
  79. }
  80. FT_Render_Mode renderMode = FT_LOAD_TARGET_MODE(loadFlags);
  81. Vector<SPtr<FontBitmap>> dataPerSize;
  82. for(size_t i = 0; i < fontSizes.size(); i++)
  83. {
  84. // Note: Disabled as its not working and I have bigger issues to handle than to figure this out atm
  85. //FT_Matrix m;
  86. //if (fontImportOptions->getBold())
  87. // m.xx = (long)(1.25f * (1 << 16));
  88. //else
  89. // m.xx = (long)(1 * (1 << 16));
  90. //if (fontImportOptions->getItalic())
  91. // m.xy = (long)(0.25f * (1 << 16));
  92. //else
  93. // m.xy = (long)(0 * (1 << 16));
  94. //m.yx = (long)(0 * (1 << 16));
  95. //m.yy = (long)(1 * (1 << 16));
  96. //FT_Set_Transform(face, &m, nullptr);
  97. FT_F26Dot6 ftSize = (FT_F26Dot6)(fontSizes[i] * (1 << 6));
  98. if (FT_Set_Char_Size(face, ftSize, 0, dpi, dpi))
  99. BS_EXCEPT(InternalErrorException, "Could not set character size.");
  100. SPtr<FontBitmap> fontData = bs_shared_ptr_new<FontBitmap>();
  101. // Get all char sizes so we can generate texture layout
  102. Vector<TexAtlasElementDesc> atlasElements;
  103. Map<UINT32, UINT32> seqIdxToCharIdx;
  104. for(auto iter = charIndexRanges.begin(); iter != charIndexRanges.end(); ++iter)
  105. {
  106. for(UINT32 charIdx = iter->first; charIdx <= iter->second; charIdx++)
  107. {
  108. error = FT_Load_Char(face, (FT_ULong)charIdx, loadFlags);
  109. if(error)
  110. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  111. FT_Render_Glyph(face->glyph, renderMode);
  112. if (error)
  113. BS_EXCEPT(InternalErrorException, "Failed to render a character");
  114. FT_GlyphSlot slot = face->glyph;
  115. TexAtlasElementDesc atlasElement;
  116. atlasElement.input.width = slot->bitmap.width;
  117. atlasElement.input.height = slot->bitmap.rows;
  118. atlasElements.push_back(atlasElement);
  119. seqIdxToCharIdx[(UINT32)atlasElements.size() - 1] = charIdx;
  120. }
  121. }
  122. // Add missing glyph
  123. {
  124. error = FT_Load_Glyph(face, (FT_ULong)0, loadFlags);
  125. if(error)
  126. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  127. FT_Render_Glyph(face->glyph, renderMode);
  128. if (error)
  129. BS_EXCEPT(InternalErrorException, "Failed to render a character");
  130. FT_GlyphSlot slot = face->glyph;
  131. TexAtlasElementDesc atlasElement;
  132. atlasElement.input.width = slot->bitmap.width;
  133. atlasElement.input.height = slot->bitmap.rows;
  134. atlasElements.push_back(atlasElement);
  135. }
  136. // Create an optimal layout for character bitmaps
  137. TexAtlasGenerator texAtlasGen(false, MAXIMUM_TEXTURE_SIZE, MAXIMUM_TEXTURE_SIZE);
  138. Vector<TexAtlasPageDesc> pages = texAtlasGen.createAtlasLayout(atlasElements);
  139. INT32 baselineOffset = 0;
  140. UINT32 lineHeight = 0;
  141. // Create char bitmap atlas textures and load character information
  142. UINT32 pageIdx = 0;
  143. for(auto pageIter = pages.begin(); pageIter != pages.end(); ++pageIter)
  144. {
  145. UINT32 bufferSize = pageIter->width * pageIter->height * 2;
  146. // TODO - I don't actually need a 2 channel texture
  147. PixelDataPtr pixelData = bs_shared_ptr_new<PixelData>(pageIter->width, pageIter->height, 1, PF_R8G8);
  148. pixelData->allocateInternalBuffer();
  149. UINT8* pixelBuffer = pixelData->getData();
  150. memset(pixelBuffer, 0, bufferSize);
  151. for(size_t elementIdx = 0; elementIdx < atlasElements.size(); elementIdx++)
  152. {
  153. // Copy character bitmap
  154. if(atlasElements[elementIdx].output.page != pageIdx)
  155. continue;
  156. TexAtlasElementDesc curElement = atlasElements[elementIdx];
  157. bool isMissingGlypth = elementIdx == (atlasElements.size() - 1); // It's always the last element
  158. UINT32 charIdx = 0;
  159. if(!isMissingGlypth)
  160. {
  161. charIdx = seqIdxToCharIdx[(UINT32)elementIdx];
  162. error = FT_Load_Char(face, charIdx, loadFlags);
  163. }
  164. else
  165. {
  166. error = FT_Load_Glyph(face, 0, loadFlags);
  167. }
  168. if(error)
  169. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  170. FT_Render_Glyph(face->glyph, renderMode);
  171. if (error)
  172. BS_EXCEPT(InternalErrorException, "Failed to render a character");
  173. FT_GlyphSlot slot = face->glyph;
  174. if(slot->bitmap.buffer == nullptr && slot->bitmap.rows > 0 && slot->bitmap.width > 0)
  175. BS_EXCEPT(InternalErrorException, "Failed to render glyph bitmap");
  176. UINT8* sourceBuffer = slot->bitmap.buffer;
  177. UINT8* dstBuffer = pixelBuffer + (curElement.output.y * pageIter->width * 2) + curElement.output.x * 2;
  178. if(slot->bitmap.pixel_mode == ft_pixel_mode_grays)
  179. {
  180. for(INT32 bitmapRow = 0; bitmapRow < slot->bitmap.rows; bitmapRow++)
  181. {
  182. for(INT32 bitmapColumn = 0; bitmapColumn < slot->bitmap.width; bitmapColumn++)
  183. {
  184. dstBuffer[bitmapColumn * 2 + 0] = sourceBuffer[bitmapColumn];
  185. dstBuffer[bitmapColumn * 2 + 1] = sourceBuffer[bitmapColumn];
  186. }
  187. dstBuffer += pageIter->width * 2;
  188. sourceBuffer += slot->bitmap.pitch;
  189. }
  190. }
  191. else if(slot->bitmap.pixel_mode == ft_pixel_mode_mono)
  192. {
  193. // 8 pixels are packed into a byte, so do some unpacking
  194. for(INT32 bitmapRow = 0; bitmapRow < slot->bitmap.rows; bitmapRow++)
  195. {
  196. for(INT32 bitmapColumn = 0; bitmapColumn < slot->bitmap.width; bitmapColumn++)
  197. {
  198. UINT8 srcValue = sourceBuffer[bitmapColumn >> 3];
  199. UINT8 dstValue = (srcValue & (128 >> (bitmapColumn & 7))) != 0 ? 255 : 0;
  200. dstBuffer[bitmapColumn * 2 + 0] = dstValue;
  201. dstBuffer[bitmapColumn * 2 + 1] = dstValue;
  202. }
  203. dstBuffer += pageIter->width * 2;
  204. sourceBuffer += slot->bitmap.pitch;
  205. }
  206. }
  207. else
  208. BS_EXCEPT(InternalErrorException, "Unsupported pixel mode for a FreeType bitmap.");
  209. // Store character information
  210. CHAR_DESC charDesc;
  211. float invTexWidth = 1.0f / pageIter->width;
  212. float invTexHeight = 1.0f / pageIter->height;
  213. charDesc.charId = charIdx;
  214. charDesc.width = curElement.input.width;
  215. charDesc.height = curElement.input.height;
  216. charDesc.page = curElement.output.page;
  217. charDesc.uvWidth = invTexWidth * curElement.input.width;
  218. charDesc.uvHeight = invTexHeight * curElement.input.height;
  219. charDesc.uvX = invTexWidth * curElement.output.x;
  220. charDesc.uvY = invTexHeight * curElement.output.y;
  221. charDesc.xOffset = slot->bitmap_left;
  222. charDesc.yOffset = slot->bitmap_top;
  223. charDesc.xAdvance = slot->advance.x >> 6;
  224. charDesc.yAdvance = slot->advance.y >> 6;
  225. baselineOffset = std::max(baselineOffset, (INT32)(slot->metrics.horiBearingY >> 6));
  226. lineHeight = std::max(lineHeight, charDesc.height);
  227. // Load kerning and store char
  228. if(!isMissingGlypth)
  229. {
  230. FT_Vector resultKerning;
  231. for(auto kerningIter = charIndexRanges.begin(); kerningIter != charIndexRanges.end(); ++kerningIter)
  232. {
  233. for(UINT32 kerningCharIdx = kerningIter->first; kerningCharIdx <= kerningIter->second; kerningCharIdx++)
  234. {
  235. if(kerningCharIdx == charIdx)
  236. continue;
  237. error = FT_Get_Kerning(face, charIdx, kerningCharIdx, FT_KERNING_DEFAULT, &resultKerning);
  238. if(error)
  239. BS_EXCEPT(InternalErrorException, "Failed to get kerning information for character: " + toString(charIdx));
  240. INT32 kerningX = (INT32)(resultKerning.x >> 6); // Y kerning is ignored because it is so rare
  241. if(kerningX == 0) // We don't store 0 kerning, this is assumed default
  242. continue;
  243. KerningPair pair;
  244. pair.amount = kerningX;
  245. pair.otherCharId = kerningCharIdx;
  246. charDesc.kerningPairs.push_back(pair);
  247. }
  248. }
  249. fontData->fontDesc.characters[charIdx] = charDesc;
  250. }
  251. else
  252. {
  253. fontData->fontDesc.missingGlyph = charDesc;
  254. }
  255. }
  256. HTexture newTex = Texture::create(TEX_TYPE_2D, pageIter->width, pageIter->height, 0, PF_R8G8);
  257. UINT32 subresourceIdx = newTex->getProperties().mapToSubresourceIdx(0, 0);
  258. // It's possible the formats no longer match
  259. if (newTex->getProperties().getFormat() != pixelData->getFormat())
  260. {
  261. PixelDataPtr temp = newTex->getProperties().allocateSubresourceBuffer(subresourceIdx);
  262. PixelUtil::bulkPixelConversion(*pixelData, *temp);
  263. newTex->writeSubresource(gCoreAccessor(), subresourceIdx, temp, false);
  264. }
  265. else
  266. {
  267. newTex->writeSubresource(gCoreAccessor(), subresourceIdx, pixelData, false);
  268. }
  269. newTex->setName(L"FontPage" + toWString((UINT32)fontData->texturePages.size()));
  270. fontData->texturePages.push_back(newTex);
  271. pageIdx++;
  272. }
  273. fontData->size = fontSizes[i];
  274. fontData->fontDesc.baselineOffset = baselineOffset;
  275. fontData->fontDesc.lineHeight = lineHeight;
  276. // Get space size
  277. error = FT_Load_Char(face, 32, loadFlags);
  278. if(error)
  279. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  280. fontData->fontDesc.spaceWidth = face->glyph->advance.x >> 6;
  281. dataPerSize.push_back(fontData);
  282. }
  283. FontPtr newFont = Font::_createPtr(dataPerSize);
  284. FT_Done_FreeType(library);
  285. WString fileName = filePath.getWFilename(false);
  286. newFont->setName(fileName);
  287. return newFont;
  288. }
  289. }