CmFontImporter.cpp 10 KB

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