BsFontImporter.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 "BsPath.h"
  8. #include "BsTexAtlasGenerator.h"
  9. #include "BsCoreApplication.h"
  10. #include "BsCoreThread.h"
  11. #include "BsCoreThreadAccessor.h"
  12. #include <ft2build.h>
  13. #include <freetype/freetype.h>
  14. #include FT_FREETYPE_H
  15. using namespace std::placeholders;
  16. namespace BansheeEngine
  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. ImportOptionsPtr FontImporter::createImportOptions() const
  39. {
  40. return bs_shared_ptr<FontImportOptions, ScratchAlloc>();
  41. }
  42. ResourcePtr FontImporter::import(const Path& filePath, ConstImportOptionsPtr 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 = FT_LOAD_RENDER;
  63. if(!fontImportOptions->getAntialiasing())
  64. loadFlags |= FT_LOAD_TARGET_MONO | FT_LOAD_NO_AUTOHINT;
  65. Vector<FontData> dataPerSize;
  66. for(size_t i = 0; i < fontSizes.size(); i++)
  67. {
  68. FT_F26Dot6 ftSize = (FT_F26Dot6)(fontSizes[i] * (1 << 6));
  69. if(FT_Set_Char_Size( face, ftSize, 0, dpi, dpi))
  70. BS_EXCEPT(InternalErrorException, "Could not set character size." );
  71. FontData fontData;
  72. // Get all char sizes so we can generate texture layout
  73. Vector<TexAtlasElementDesc> atlasElements;
  74. Map<UINT32, UINT32> seqIdxToCharIdx;
  75. for(auto iter = charIndexRanges.begin(); iter != charIndexRanges.end(); ++iter)
  76. {
  77. for(UINT32 charIdx = iter->first; charIdx <= iter->second; charIdx++)
  78. {
  79. error = FT_Load_Char(face, (FT_ULong)charIdx, loadFlags);
  80. if(error)
  81. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  82. FT_GlyphSlot slot = face->glyph;
  83. TexAtlasElementDesc atlasElement;
  84. atlasElement.input.width = slot->bitmap.width;
  85. atlasElement.input.height = slot->bitmap.rows;
  86. atlasElements.push_back(atlasElement);
  87. seqIdxToCharIdx[(UINT32)atlasElements.size() - 1] = charIdx;
  88. }
  89. }
  90. // Add missing glyph
  91. {
  92. error = FT_Load_Glyph(face, (FT_ULong)0, loadFlags);
  93. if(error)
  94. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  95. FT_GlyphSlot slot = face->glyph;
  96. TexAtlasElementDesc atlasElement;
  97. atlasElement.input.width = slot->bitmap.width;
  98. atlasElement.input.height = slot->bitmap.rows;
  99. atlasElements.push_back(atlasElement);
  100. }
  101. // Create an optimal layout for character bitmaps
  102. TexAtlasGenerator texAtlasGen(false, MAXIMUM_TEXTURE_SIZE, MAXIMUM_TEXTURE_SIZE);
  103. Vector<TexAtlasPageDesc> pages = texAtlasGen.createAtlasLayout(atlasElements);
  104. INT32 baselineOffset = 0;
  105. UINT32 lineHeight = 0;
  106. // Create char bitmap atlas textures and load character information
  107. UINT32 pageIdx = 0;
  108. for(auto pageIter = pages.begin(); pageIter != pages.end(); ++pageIter)
  109. {
  110. UINT32 bufferSize = pageIter->width * pageIter->height * 2;
  111. // TODO - I don't actually need a 2 channel texture
  112. PixelDataPtr pixelData = bs_shared_ptr<PixelData>(pageIter->width, pageIter->height, 1, PF_R8G8);
  113. pixelData->allocateInternalBuffer();
  114. UINT8* pixelBuffer = pixelData->getData();
  115. memset(pixelBuffer, 0, bufferSize);
  116. for(size_t elementIdx = 0; elementIdx < atlasElements.size(); elementIdx++)
  117. {
  118. // Copy character bitmap
  119. if(atlasElements[elementIdx].output.page != pageIdx)
  120. continue;
  121. TexAtlasElementDesc curElement = atlasElements[elementIdx];
  122. bool isMissingGlypth = elementIdx == (atlasElements.size() - 1); // It's always the last element
  123. UINT32 charIdx = 0;
  124. if(!isMissingGlypth)
  125. {
  126. charIdx = seqIdxToCharIdx[(UINT32)elementIdx];
  127. error = FT_Load_Char(face, charIdx, loadFlags);
  128. }
  129. else
  130. {
  131. error = FT_Load_Glyph(face, 0, loadFlags);
  132. }
  133. if(error)
  134. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  135. FT_GlyphSlot slot = face->glyph;
  136. if(slot->bitmap.buffer == nullptr && slot->bitmap.rows > 0 && slot->bitmap.width > 0)
  137. BS_EXCEPT(InternalErrorException, "Failed to render glyph bitmap");
  138. UINT8* sourceBuffer = slot->bitmap.buffer;
  139. UINT8* dstBuffer = pixelBuffer + (curElement.output.y * pageIter->width * 2) + curElement.output.x * 2;
  140. if(slot->bitmap.pixel_mode == ft_pixel_mode_grays)
  141. {
  142. for(INT32 bitmapRow = 0; bitmapRow < slot->bitmap.rows; bitmapRow++)
  143. {
  144. for(INT32 bitmapColumn = 0; bitmapColumn < slot->bitmap.width; bitmapColumn++)
  145. {
  146. dstBuffer[bitmapColumn * 2 + 0] = sourceBuffer[bitmapColumn];
  147. dstBuffer[bitmapColumn * 2 + 1] = sourceBuffer[bitmapColumn];
  148. }
  149. dstBuffer += pageIter->width * 2;
  150. sourceBuffer += slot->bitmap.pitch;
  151. }
  152. }
  153. else if(slot->bitmap.pixel_mode == ft_pixel_mode_mono)
  154. {
  155. // 8 pixels are packed into a byte, so do some unpacking
  156. for(INT32 bitmapRow = 0; bitmapRow < slot->bitmap.rows; bitmapRow++)
  157. {
  158. for(INT32 bitmapColumn = 0; bitmapColumn < slot->bitmap.width; bitmapColumn++)
  159. {
  160. UINT8 srcValue = sourceBuffer[bitmapColumn >> 3];
  161. UINT8 dstValue = (srcValue & (128 >> (bitmapColumn & 7))) != 0 ? 255 : 0;
  162. dstBuffer[bitmapColumn * 2 + 0] = dstValue;
  163. dstBuffer[bitmapColumn * 2 + 1] = dstValue;
  164. }
  165. dstBuffer += pageIter->width * 2;
  166. sourceBuffer += slot->bitmap.pitch;
  167. }
  168. }
  169. else
  170. BS_EXCEPT(InternalErrorException, "Unsupported pixel mode for a FreeType bitmap.");
  171. // Store character information
  172. CHAR_DESC charDesc;
  173. float invTexWidth = 1.0f / pageIter->width;
  174. float invTexHeight = 1.0f / pageIter->height;
  175. charDesc.charId = charIdx;
  176. charDesc.width = curElement.input.width;
  177. charDesc.height = curElement.input.height;
  178. charDesc.page = curElement.output.page;
  179. charDesc.uvWidth = invTexWidth * curElement.input.width;
  180. charDesc.uvHeight = invTexHeight * curElement.input.height;
  181. charDesc.uvX = invTexWidth * curElement.output.x;
  182. charDesc.uvY = invTexHeight * curElement.output.y;
  183. charDesc.xOffset = slot->bitmap_left;
  184. charDesc.yOffset = slot->bitmap_top;
  185. charDesc.xAdvance = slot->advance.x >> 6;
  186. charDesc.yAdvance = slot->advance.y >> 6;
  187. baselineOffset = std::max(baselineOffset, (INT32)(slot->metrics.horiBearingY >> 6));
  188. lineHeight = std::max(lineHeight, charDesc.height);
  189. // Load kerning and store char
  190. if(!isMissingGlypth)
  191. {
  192. FT_Vector resultKerning;
  193. for(auto kerningIter = charIndexRanges.begin(); kerningIter != charIndexRanges.end(); ++kerningIter)
  194. {
  195. for(UINT32 kerningCharIdx = kerningIter->first; kerningCharIdx <= kerningIter->second; kerningCharIdx++)
  196. {
  197. if(kerningCharIdx == charIdx)
  198. continue;
  199. error = FT_Get_Kerning(face, charIdx, kerningCharIdx, FT_KERNING_DEFAULT, &resultKerning);
  200. if(error)
  201. BS_EXCEPT(InternalErrorException, "Failed to get kerning information for character: " + toString(charIdx));
  202. INT32 kerningX = (INT32)(resultKerning.x >> 6); // Y kerning is ignored because it is so rare
  203. if(kerningX == 0) // We don't store 0 kerning, this is assumed default
  204. continue;
  205. KerningPair pair;
  206. pair.amount = kerningX;
  207. pair.otherCharId = kerningCharIdx;
  208. charDesc.kerningPairs.push_back(pair);
  209. }
  210. }
  211. fontData.fontDesc.characters[charIdx] = charDesc;
  212. }
  213. else
  214. {
  215. fontData.fontDesc.missingGlyph = charDesc;
  216. }
  217. }
  218. HTexture newTex = Texture::create(TEX_TYPE_2D, pageIter->width, pageIter->height, 0, PF_R8G8);
  219. newTex.synchronize(); // TODO - Required due to a bug in allocateSubresourceBuffer
  220. UINT32 subresourceIdx = newTex->mapToSubresourceIdx(0, 0);
  221. // It's possible the formats no longer match
  222. if(newTex->getFormat() != pixelData->getFormat())
  223. {
  224. PixelDataPtr temp = newTex->allocateSubresourceBuffer(subresourceIdx);
  225. PixelUtil::bulkPixelConversion(*pixelData, *temp);
  226. temp->_lock();
  227. gCoreThread().queueReturnCommand(std::bind(&RenderSystem::writeSubresource,
  228. RenderSystem::instancePtr(), newTex.getInternalPtr(), subresourceIdx, temp, false, _1));
  229. }
  230. else
  231. {
  232. pixelData->_lock();
  233. gCoreThread().queueReturnCommand(std::bind(&RenderSystem::writeSubresource,
  234. RenderSystem::instancePtr(), newTex.getInternalPtr(), subresourceIdx, pixelData, false, _1));
  235. }
  236. newTex->setName("FontPage" + toString((UINT32)fontData.texturePages.size()));
  237. fontData.texturePages.push_back(newTex);
  238. pageIdx++;
  239. }
  240. fontData.size = fontSizes[i];
  241. fontData.fontDesc.baselineOffset = baselineOffset;
  242. fontData.fontDesc.lineHeight = lineHeight;
  243. // Get space size
  244. error = FT_Load_Char(face, 32, loadFlags);
  245. if(error)
  246. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  247. fontData.fontDesc.spaceWidth = face->glyph->advance.x >> 6;
  248. dataPerSize.push_back(fontData);
  249. }
  250. FontPtr newFont = Font::_createPtr(dataPerSize);
  251. FT_Done_FreeType(library);
  252. WString fileName = filePath.getWFilename(false);
  253. newFont->setName(toString(fileName));
  254. return newFont;
  255. }
  256. }