CBitmapFont.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. * CBitmapFont.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CBitmapFont.h"
  12. #include "SDL_Extensions.h"
  13. #include "../CGameInfo.h"
  14. #include "../gui/CGuiHandler.h"
  15. #include "../render/Colors.h"
  16. #include "../render/IScreenHandler.h"
  17. #include "../../lib/CConfigHandler.h"
  18. #include "../../lib/Rect.h"
  19. #include "../../lib/VCMI_Lib.h"
  20. #include "../../lib/filesystem/Filesystem.h"
  21. #include "../../lib/modding/CModHandler.h"
  22. #include "../../lib/texts/Languages.h"
  23. #include "../../lib/texts/TextOperations.h"
  24. #include "../../lib/vcmi_endian.h"
  25. #include <SDL_surface.h>
  26. #include <SDL_image.h>
  27. struct AtlasLayout
  28. {
  29. Point dimensions;
  30. std::map<int, Rect> images;
  31. };
  32. /// Attempts to pack provided list of images into 2d box of specified size
  33. /// Returns resulting layout on success and empty optional on failure
  34. static std::optional<AtlasLayout> tryAtlasPacking(Point dimensions, const std::map<int, Point> & images)
  35. {
  36. // Simple atlas packing algorithm. Can be extended if needed, however optimal solution is NP-complete problem, so 'perfect' solution is too costly
  37. AtlasLayout result;
  38. result.dimensions = dimensions;
  39. // a little interval to prevent potential 'bleeding' into adjacent symbols
  40. // should be unnecessary for base game, but may be needed for upscaled filters
  41. constexpr int interval = 1;
  42. int currentHeight = 0;
  43. int nextHeight = 0;
  44. int currentWidth = 0;
  45. for (auto const & image : images)
  46. {
  47. int nextWidth = currentWidth + image.second.x + interval;
  48. if (nextWidth > dimensions.x)
  49. {
  50. currentHeight = nextHeight;
  51. currentWidth = 0;
  52. nextWidth = currentWidth + image.second.x + interval;
  53. }
  54. nextHeight = std::max(nextHeight, currentHeight + image.second.y + interval);
  55. if (nextHeight > dimensions.y)
  56. return std::nullopt; // failure - ran out of space
  57. result.images[image.first] = Rect(Point(currentWidth, currentHeight), image.second);
  58. currentWidth = nextWidth;
  59. }
  60. return result;
  61. }
  62. /// Arranges images to fit into texture atlas with automatic selection of image size
  63. /// Returns images arranged into 2d box
  64. static AtlasLayout doAtlasPacking(const std::map<int, Point> & images)
  65. {
  66. // initial size of an atlas. Smaller size won't even fit tiniest H3 font
  67. Point dimensions(128, 128);
  68. for (;;)
  69. {
  70. auto result = tryAtlasPacking(dimensions, images);
  71. if (result)
  72. return *result;
  73. // else - packing failed. Increase atlas size and try again
  74. // increase width and height in alternating form: (64,64) -> (128,64) -> (128,128) ...
  75. if (dimensions.x > dimensions.y)
  76. dimensions.y *= 2;
  77. else
  78. dimensions.x *= 2;
  79. }
  80. }
  81. void CBitmapFont::loadModFont(const std::string & modName, const ResourcePath & resource, std::unordered_map<CodePoint, EntryFNT> & loadedChars)
  82. {
  83. if (!CResourceHandler::get(modName)->existsResource(resource))
  84. {
  85. logGlobal->error("Failed to load font %s from mod %s", resource.getName(), modName);
  86. return;
  87. }
  88. auto data = CResourceHandler::get(modName)->load(resource)->readAll();
  89. std::string modLanguage = CGI->modh->getModLanguage(modName);
  90. std::string modEncoding = Languages::getLanguageOptions(modLanguage).encoding;
  91. uint32_t dataHeight = data.first[5];
  92. maxHeight = std::max(maxHeight, dataHeight);
  93. constexpr size_t symbolsInFile = 0x100;
  94. constexpr size_t baseIndex = 32;
  95. constexpr size_t offsetIndex = baseIndex + symbolsInFile*12;
  96. constexpr size_t dataIndex = offsetIndex + symbolsInFile*4;
  97. for (uint32_t charIndex = 0; charIndex < symbolsInFile; ++charIndex)
  98. {
  99. CodePoint codepoint = TextOperations::getUnicodeCodepoint(static_cast<char>(charIndex), modEncoding);
  100. EntryFNT symbol;
  101. symbol.leftOffset = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 0);
  102. symbol.width = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 4);
  103. symbol.rightOffset = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 8);
  104. symbol.height = dataHeight;
  105. uint32_t pixelDataOffset = read_le_u32(data.first.get() + offsetIndex + charIndex * 4);
  106. uint32_t pixelsCount = dataHeight * symbol.width;
  107. symbol.pixels.resize(pixelsCount);
  108. uint8_t * pixelData = data.first.get() + dataIndex + pixelDataOffset;
  109. std::copy_n(pixelData, pixelsCount, symbol.pixels.data() );
  110. loadedChars[codepoint] = symbol;
  111. }
  112. }
  113. CBitmapFont::CBitmapFont(const std::string & filename):
  114. maxHeight(0)
  115. {
  116. ResourcePath resource("data/" + filename, EResType::BMP_FONT);
  117. std::unordered_map<CodePoint, EntryFNT> loadedChars;
  118. loadModFont("core", resource, loadedChars);
  119. for(const auto & modName : VLC->modh->getActiveMods())
  120. {
  121. if (CResourceHandler::get(modName)->existsResource(resource))
  122. loadModFont(modName, resource, loadedChars);
  123. }
  124. std::map<int, Point> atlasSymbol;
  125. for (auto const & symbol : loadedChars)
  126. atlasSymbol[symbol.first] = Point(symbol.second.width, symbol.second.height);
  127. auto atlas = doAtlasPacking(atlasSymbol);
  128. atlasImage = SDL_CreateRGBSurface(0, atlas.dimensions.x, atlas.dimensions.y, 8, 0, 0, 0, 0);
  129. assert(atlasImage->format->palette != nullptr);
  130. assert(atlasImage->format->palette->ncolors == 256);
  131. atlasImage->format->palette->colors[0] = { 0, 255, 255, SDL_ALPHA_OPAQUE }; // transparency
  132. atlasImage->format->palette->colors[1] = { 0, 0, 0, SDL_ALPHA_OPAQUE }; // black shadow
  133. CSDL_Ext::fillSurface(atlasImage, CSDL_Ext::toSDL(Colors::CYAN));
  134. CSDL_Ext::setColorKey(atlasImage, CSDL_Ext::toSDL(Colors::CYAN));
  135. for (size_t i = 2; i < atlasImage->format->palette->ncolors; ++i)
  136. atlasImage->format->palette->colors[i] = { 255, 255, 255, SDL_ALPHA_OPAQUE };
  137. for (auto const & symbol : loadedChars)
  138. {
  139. BitmapChar storedEntry;
  140. storedEntry.leftOffset = symbol.second.leftOffset;
  141. storedEntry.rightOffset = symbol.second.rightOffset;
  142. storedEntry.positionInAtlas = atlas.images.at(symbol.first);
  143. // Copy pixel data to atlas
  144. uint8_t *dstPixels = static_cast<uint8_t*>(atlasImage->pixels);
  145. uint8_t *dstLine = dstPixels + storedEntry.positionInAtlas.y * atlasImage->pitch;
  146. uint8_t *dst = dstLine + storedEntry.positionInAtlas.x;
  147. for (size_t i = 0; i < storedEntry.positionInAtlas.h; ++i)
  148. {
  149. const uint8_t *srcPtr = symbol.second.pixels.data() + i * storedEntry.positionInAtlas.w;
  150. uint8_t * dstPtr = dst + i * atlasImage->pitch;
  151. std::copy_n(srcPtr, storedEntry.positionInAtlas.w, dstPtr);
  152. }
  153. chars[symbol.first] = storedEntry;
  154. }
  155. if (GH.screenHandler().getScalingFactor() != 1)
  156. {
  157. static const std::map<std::string, EScalingAlgorithm> filterNameToEnum = {
  158. { "nearest", EScalingAlgorithm::NEAREST},
  159. { "bilinear", EScalingAlgorithm::BILINEAR},
  160. { "xbrz", EScalingAlgorithm::XBRZ}
  161. };
  162. auto filterName = settings["video"]["fontUpscalingFilter"].String();
  163. EScalingAlgorithm algorithm = filterNameToEnum.at(filterName);
  164. auto scaledSurface = CSDL_Ext::scaleSurfaceIntegerFactor(atlasImage, GH.screenHandler().getScalingFactor(), algorithm);
  165. SDL_FreeSurface(atlasImage);
  166. atlasImage = scaledSurface;
  167. }
  168. IMG_SavePNG(atlasImage, ("/home/ivan/font_" + filename).c_str());
  169. }
  170. CBitmapFont::~CBitmapFont()
  171. {
  172. SDL_FreeSurface(atlasImage);
  173. }
  174. size_t CBitmapFont::getLineHeight() const
  175. {
  176. return maxHeight;
  177. }
  178. size_t CBitmapFont::getGlyphWidth(const char * data) const
  179. {
  180. CodePoint localChar = TextOperations::getUnicodeCodepoint(data, 4);
  181. auto iter = chars.find(localChar);
  182. if (iter == chars.end())
  183. return 0;
  184. return iter->second.leftOffset + iter->second.positionInAtlas.w + iter->second.rightOffset;
  185. }
  186. bool CBitmapFont::canRepresentCharacter(const char *data) const
  187. {
  188. CodePoint localChar = TextOperations::getUnicodeCodepoint(data, 4);
  189. auto iter = chars.find(localChar);
  190. return iter != chars.end();
  191. }
  192. bool CBitmapFont::canRepresentString(const std::string & data) const
  193. {
  194. for(size_t i=0; i<data.size(); i += TextOperations::getUnicodeCharacterSize(data[i]))
  195. if (!canRepresentCharacter(data.data() + i))
  196. return false;
  197. return true;
  198. }
  199. void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & character, const ColorRGBA & color, int &posX, int &posY) const
  200. {
  201. int scalingFactor = GH.screenHandler().getScalingFactor();
  202. posX += character.leftOffset * scalingFactor;
  203. auto sdlColor = CSDL_Ext::toSDL(color);
  204. if (atlasImage->format->palette)
  205. SDL_SetPaletteColors(atlasImage->format->palette, &sdlColor, 255, 1);
  206. else
  207. SDL_SetSurfaceColorMod(atlasImage, color.r, color.g, color.b);
  208. CSDL_Ext::blitSurface(atlasImage, character.positionInAtlas * scalingFactor, surface, Point(posX, posY));
  209. posX += character.positionInAtlas.w * scalingFactor;
  210. posX += character.rightOffset * scalingFactor;
  211. }
  212. void CBitmapFont::renderText(SDL_Surface * surface, const std::string & data, const ColorRGBA & color, const Point & pos) const
  213. {
  214. if (data.empty())
  215. return;
  216. assert(surface);
  217. int posX = pos.x;
  218. int posY = pos.y;
  219. for(size_t i=0; i<data.size(); i += TextOperations::getUnicodeCharacterSize(data[i]))
  220. {
  221. CodePoint codepoint = TextOperations::getUnicodeCodepoint(data.data() + i, data.size() - i);
  222. auto iter = chars.find(codepoint);
  223. if (iter != chars.end())
  224. renderCharacter(surface, iter->second, color, posX, posY);
  225. }
  226. }