CmFontImporter.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 <ft2build.h>
  9. #include <freetype/freetype.h>
  10. #include FT_FREETYPE_H
  11. namespace CamelotEngine
  12. {
  13. FontImporter::FontImporter()
  14. :SpecificImporter()
  15. {
  16. mExtensions.push_back("ttf");
  17. mExtensions.push_back("otf");
  18. }
  19. FontImporter::~FontImporter()
  20. {
  21. }
  22. bool FontImporter::isExtensionSupported(const String& ext) const
  23. {
  24. String lowerCaseExt = ext;
  25. StringUtil::toLowerCase(lowerCaseExt);
  26. return find(mExtensions.begin(), mExtensions.end(), lowerCaseExt) != mExtensions.end();
  27. }
  28. bool FontImporter::isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const
  29. {
  30. // TODO
  31. return false;
  32. }
  33. ImportOptionsPtr FontImporter::createImportOptions() const
  34. {
  35. return ImportOptionsPtr(CM_NEW(FontImportOptions, ScratchAlloc) FontImportOptions(),
  36. &MemAllocDeleter<FontImportOptions, ScratchAlloc>::deleter);
  37. }
  38. HResource FontImporter::import(const String& filePath, ConstImportOptionsPtr importOptions)
  39. {
  40. const FontImportOptions* gpuProgImportOptions = static_cast<const FontImportOptions*>(importOptions.get());
  41. FT_Library library;
  42. FT_Error error = FT_Init_FreeType(&library);
  43. if (error)
  44. CM_EXCEPT(InternalErrorException, "Error occurred during FreeType library initialization.");
  45. FT_Face face;
  46. error = FT_New_Face(library, filePath.c_str(), 0, &face);
  47. if (error == FT_Err_Unknown_File_Format)
  48. {
  49. CM_EXCEPT(InternalErrorException, "Failed to load font file: " + filePath + ". Unsupported file format.");
  50. }
  51. else if (error)
  52. {
  53. CM_EXCEPT(InternalErrorException, "Failed to load font file: " + filePath + ". Unknown error.");
  54. }
  55. vector<std::pair<UINT32, UINT32>>::type charIndexRanges = gpuProgImportOptions->getCharIndexRanges();
  56. vector<UINT32>::type fontSizes = gpuProgImportOptions->getFontSizes();
  57. UINT32 dpi = gpuProgImportOptions->getDPI();
  58. vector<FontData>::type dataPerSize;
  59. for(size_t i = 0; i < fontSizes.size(); i++)
  60. {
  61. FT_F26Dot6 ftSize = (FT_F26Dot6)(fontSizes[i] * (1 << 6));
  62. if(FT_Set_Char_Size( face, ftSize, 0, dpi, dpi))
  63. CM_EXCEPT(InternalErrorException, "Could not set character size." );
  64. FontData fontData;
  65. // Get all char sizes so we can generate texture layout
  66. vector<TexAtlasElementDesc>::type atlasElements;
  67. map<UINT32, UINT32>::type seqIdxToCharIdx;
  68. for(auto iter = charIndexRanges.begin(); iter != charIndexRanges.end(); ++iter)
  69. {
  70. for(UINT32 charIdx = iter->first; charIdx <= iter->second; charIdx++)
  71. {
  72. error = FT_Load_Char(face, (FT_ULong)charIdx, FT_LOAD_RENDER);
  73. if(error)
  74. CM_EXCEPT(InternalErrorException, "Failed to load a character");
  75. FT_GlyphSlot slot = face->glyph;
  76. TexAtlasElementDesc atlasElement;
  77. atlasElement.input.width = slot->bitmap.width;
  78. atlasElement.input.height = slot->bitmap.rows;
  79. atlasElements.push_back(atlasElement);
  80. seqIdxToCharIdx[(UINT32)atlasElements.size() - 1] = charIdx;
  81. }
  82. }
  83. // Add missing glyph
  84. {
  85. error = FT_Load_Glyph(face, (FT_ULong)0, FT_LOAD_RENDER);
  86. if(error)
  87. CM_EXCEPT(InternalErrorException, "Failed to load a character");
  88. FT_GlyphSlot slot = face->glyph;
  89. TexAtlasElementDesc atlasElement;
  90. atlasElement.input.width = slot->bitmap.width;
  91. atlasElement.input.height = slot->bitmap.rows;
  92. atlasElements.push_back(atlasElement);
  93. }
  94. // Create an optimal layout for character bitmaps
  95. TexAtlasGenerator texAtlasGen(false, MAXIMUM_TEXTURE_SIZE, MAXIMUM_TEXTURE_SIZE);
  96. vector<TexAtlasPageDesc>::type pages = texAtlasGen.createAtlasLayout(atlasElements);
  97. INT32 baselineOffset = 0;
  98. UINT32 lineHeight = 0;
  99. // Create char bitmap atlas textures and load character information
  100. UINT32 pageIdx = 0;
  101. for(auto pageIter = pages.begin(); pageIter != pages.end(); ++pageIter)
  102. {
  103. UINT32 bufferSize = pageIter->width * pageIter->height * 2;
  104. PixelData pixelData(pageIter->width, pageIter->height, 1, PF_R8G8);
  105. UINT8* pixelBuffer = pixelData.allocData(bufferSize);
  106. memset(pixelBuffer, 0, bufferSize);
  107. for(size_t elementIdx = 0; elementIdx < atlasElements.size(); elementIdx++)
  108. {
  109. // Copy character bitmap
  110. if(atlasElements[elementIdx].output.page != pageIdx)
  111. continue;
  112. TexAtlasElementDesc curElement = atlasElements[elementIdx];
  113. bool isMissingGlypth = elementIdx == (atlasElements.size() - 1); // It's always the last element
  114. UINT32 charIdx = 0;
  115. if(!isMissingGlypth)
  116. {
  117. charIdx = seqIdxToCharIdx[(UINT32)elementIdx];
  118. error = FT_Load_Char(face, charIdx, FT_LOAD_RENDER);
  119. }
  120. else
  121. {
  122. error = FT_Load_Glyph(face, 0, FT_LOAD_RENDER);
  123. }
  124. if(error)
  125. CM_EXCEPT(InternalErrorException, "Failed to load a character");
  126. FT_GlyphSlot slot = face->glyph;
  127. if(slot->bitmap.buffer == nullptr && slot->bitmap.rows > 0 && slot->bitmap.width > 0)
  128. CM_EXCEPT(InternalErrorException, "Failed to render glyph bitmap");
  129. UINT8* sourceBuffer = slot->bitmap.buffer;
  130. UINT8* dstBuffer = pixelBuffer + (curElement.output.y * pageIter->width * 2) + curElement.output.x * 2;
  131. for(INT32 bitmapRow = 0; bitmapRow < slot->bitmap.rows; bitmapRow++)
  132. {
  133. for(INT32 bitmapColumn = 0; bitmapColumn < slot->bitmap.width; bitmapColumn++)
  134. {
  135. dstBuffer[bitmapColumn * 2 + 0] = sourceBuffer[bitmapColumn];
  136. dstBuffer[bitmapColumn * 2 + 1] = sourceBuffer[bitmapColumn];
  137. }
  138. dstBuffer += pageIter->width * 2;
  139. sourceBuffer += slot->bitmap.pitch;
  140. }
  141. // Store character information
  142. CHAR_DESC charDesc;
  143. float invTexWidth = 1.0f / pageIter->width;
  144. float invTexHeight = 1.0f / pageIter->height;
  145. charDesc.charId = charIdx;
  146. charDesc.width = curElement.input.width;
  147. charDesc.height = curElement.input.height;
  148. charDesc.page = curElement.output.page;
  149. charDesc.uvWidth = invTexWidth * curElement.input.width;
  150. charDesc.uvHeight = invTexHeight * curElement.input.height;
  151. charDesc.uvX = invTexWidth * curElement.output.x;
  152. charDesc.uvY = invTexHeight * curElement.output.y;
  153. charDesc.xOffset = slot->bitmap_left;
  154. charDesc.yOffset = slot->bitmap_top;
  155. charDesc.xAdvance = slot->advance.x >> 6;
  156. charDesc.yAdvance = slot->advance.y >> 6;
  157. baselineOffset = std::max(baselineOffset, (INT32)(slot->metrics.horiBearingY >> 6));
  158. lineHeight = std::max(lineHeight, charDesc.height);
  159. // Load kerning and store char
  160. if(!isMissingGlypth)
  161. {
  162. FT_Vector resultKerning;
  163. for(auto kerningIter = charIndexRanges.begin(); kerningIter != charIndexRanges.end(); ++kerningIter)
  164. {
  165. for(UINT32 kerningCharIdx = kerningIter->first; kerningCharIdx <= kerningIter->second; kerningCharIdx++)
  166. {
  167. if(kerningCharIdx == charIdx)
  168. continue;
  169. error = FT_Get_Kerning(face, charIdx, kerningCharIdx, FT_KERNING_DEFAULT, &resultKerning);
  170. if(error)
  171. CM_EXCEPT(InternalErrorException, "Failed to get kerning information for character: " + toString(charIdx));
  172. INT32 kerningX = (INT32)(resultKerning.x >> 6); // Y kerning is ignored because it is so rare
  173. if(kerningX == 0) // We don't store 0 kerning, this is assumed default
  174. continue;
  175. KerningPair pair;
  176. pair.amount = kerningX;
  177. pair.otherCharId = kerningCharIdx;
  178. charDesc.kerningPairs.push_back(pair);
  179. }
  180. }
  181. fontData.fontDesc.characters[charIdx] = charDesc;
  182. }
  183. else
  184. {
  185. fontData.fontDesc.missingGlyph = charDesc;
  186. }
  187. }
  188. HTexture newTex = Texture::create(TEX_TYPE_2D, pageIter->width, pageIter->height, 0, PF_R8G8);
  189. newTex.waitUntilLoaded();
  190. newTex->setRawPixels(pixelData);
  191. fontData.texturePages.push_back(newTex);
  192. pageIdx++;
  193. }
  194. fontData.size = fontSizes[i];
  195. fontData.fontDesc.baselineOffset = baselineOffset;
  196. fontData.fontDesc.lineHeight = lineHeight;
  197. // Get space size
  198. error = FT_Load_Char(face, 32, FT_LOAD_RENDER);
  199. if(error)
  200. CM_EXCEPT(InternalErrorException, "Failed to load a character");
  201. fontData.fontDesc.spaceWidth = face->glyph->advance.x >> 6;
  202. dataPerSize.push_back(fontData);
  203. }
  204. HFont newFont = Font::create(dataPerSize);
  205. FT_Done_FreeType(library);
  206. return newFont;
  207. }
  208. }