BsFontImporter.cpp 12 KB

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