CmFontImporter.cpp 8.9 KB

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