BsFontImporter.cpp 11 KB

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