2
0

CBitmapFont.cpp 9.2 KB

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