BsFontImporter.cpp 11 KB

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