2
0

CBitmapFont.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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/Rect.h"
  18. #include "../../lib/filesystem/Filesystem.h"
  19. #include "../../lib/modding/CModHandler.h"
  20. #include "../../lib/texts/Languages.h"
  21. #include "../../lib/texts/TextOperations.h"
  22. #include "../../lib/vcmi_endian.h"
  23. #include "../../lib/VCMI_Lib.h"
  24. #include <SDL_surface.h>
  25. #include <SDL_image.h>
  26. struct AtlasLayout
  27. {
  28. Point dimensions;
  29. std::map<int, Rect> images;
  30. };
  31. /// Attempts to pack provided list of images into 2d box of specified size
  32. /// Returns resulting layout on success and empty optional on failure
  33. static std::optional<AtlasLayout> tryAtlasPacking(Point dimensions, const std::map<int, Point> & images)
  34. {
  35. // Simple atlas packing algorithm. Can be extended if needed, however optimal solution is NP-complete problem, so 'perfect' solution is too costly
  36. AtlasLayout result;
  37. result.dimensions = dimensions;
  38. // a little interval to prevent potential 'bleeding' into adjacent symbols
  39. // should be unnecessary for base game, but may be needed for upscaled filters
  40. constexpr int interval = 1;
  41. int currentHeight = 0;
  42. int nextHeight = 0;
  43. int currentWidth = 0;
  44. for (auto const & image : images)
  45. {
  46. int nextWidth = currentWidth + image.second.x + interval;
  47. if (nextWidth > dimensions.x)
  48. {
  49. currentHeight = nextHeight;
  50. currentWidth = 0;
  51. nextWidth = currentWidth + image.second.x + interval;
  52. }
  53. nextHeight = std::max(nextHeight, currentHeight + image.second.y + interval);
  54. if (nextHeight > dimensions.y)
  55. return std::nullopt; // failure - ran out of space
  56. result.images[image.first] = Rect(Point(currentWidth, currentHeight), image.second);
  57. currentWidth = nextWidth;
  58. }
  59. return result;
  60. }
  61. /// Arranges images to fit into texture atlas with automatic selection of image size
  62. /// Returns images arranged into 2d box
  63. static AtlasLayout doAtlasPacking(const std::map<int, Point> & images)
  64. {
  65. // initial size of an atlas. Smaller size won't even fit tiniest H3 font
  66. Point dimensions(128, 128);
  67. for (;;)
  68. {
  69. auto result = tryAtlasPacking(dimensions, images);
  70. if (result)
  71. return *result;
  72. // else - packing failed. Increase atlas size and try again
  73. // increase width and height in alternating form: (64,64) -> (128,64) -> (128,128) ...
  74. if (dimensions.x > dimensions.y)
  75. dimensions.y *= 2;
  76. else
  77. dimensions.x *= 2;
  78. }
  79. }
  80. void CBitmapFont::loadModFont(const std::string & modName, const ResourcePath & resource, std::unordered_map<CodePoint, EntryFNT> & loadedChars)
  81. {
  82. if (!CResourceHandler::get(modName)->existsResource(resource))
  83. {
  84. logGlobal->error("Failed to load font %s from mod %s", resource.getName(), modName);
  85. return;
  86. }
  87. auto data = CResourceHandler::get(modName)->load(resource)->readAll();
  88. std::string modLanguage = CGI->modh->getModLanguage(modName);
  89. std::string modEncoding = Languages::getLanguageOptions(modLanguage).encoding;
  90. uint32_t dataHeight = data.first[5];
  91. maxHeight = std::max(maxHeight, dataHeight);
  92. constexpr size_t symbolsInFile = 0x100;
  93. constexpr size_t baseIndex = 32;
  94. constexpr size_t offsetIndex = baseIndex + symbolsInFile*12;
  95. constexpr size_t dataIndex = offsetIndex + symbolsInFile*4;
  96. for (uint32_t charIndex = 0; charIndex < symbolsInFile; ++charIndex)
  97. {
  98. CodePoint codepoint = TextOperations::getUnicodeCodepoint(static_cast<char>(charIndex), modEncoding);
  99. EntryFNT symbol;
  100. symbol.leftOffset = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 0);
  101. symbol.width = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 4);
  102. symbol.rightOffset = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 8);
  103. symbol.height = dataHeight;
  104. uint32_t pixelDataOffset = read_le_u32(data.first.get() + offsetIndex + charIndex * 4);
  105. uint32_t pixelsCount = dataHeight * symbol.width;
  106. symbol.pixels.resize(pixelsCount);
  107. uint8_t * pixelData = data.first.get() + dataIndex + pixelDataOffset;
  108. std::copy_n(pixelData, pixelsCount, symbol.pixels.data() );
  109. loadedChars[codepoint] = symbol;
  110. }
  111. }
  112. CBitmapFont::CBitmapFont(const std::string & filename):
  113. maxHeight(0)
  114. {
  115. ResourcePath resource("data/" + filename, EResType::BMP_FONT);
  116. std::unordered_map<CodePoint, EntryFNT> loadedChars;
  117. loadModFont("core", resource, loadedChars);
  118. for(const auto & modName : VLC->modh->getActiveMods())
  119. {
  120. if (CResourceHandler::get(modName)->existsResource(resource))
  121. loadModFont(modName, resource, loadedChars);
  122. }
  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 (GH.screenHandler().getScalingFactor() != 1)
  155. {
  156. // scale using nearest neighbour - looks way better with H3 fonts than more high-quality xBRZ
  157. // TODO: make configurable?
  158. auto scaledSurface = CSDL_Ext::scaleSurfaceIntegerFactor(atlasImage, GH.screenHandler().getScalingFactor(), EScalingAlgorithm::NEAREST);
  159. SDL_FreeSurface(atlasImage);
  160. atlasImage = scaledSurface;
  161. }
  162. IMG_SavePNG(atlasImage, ("/home/ivan/font_" + filename).c_str());
  163. }
  164. CBitmapFont::~CBitmapFont()
  165. {
  166. SDL_FreeSurface(atlasImage);
  167. }
  168. size_t CBitmapFont::getLineHeight() const
  169. {
  170. return maxHeight;
  171. }
  172. size_t CBitmapFont::getGlyphWidth(const char * data) const
  173. {
  174. CodePoint localChar = TextOperations::getUnicodeCodepoint(data, 4);
  175. auto iter = chars.find(localChar);
  176. if (iter == chars.end())
  177. return 0;
  178. return iter->second.leftOffset + iter->second.positionInAtlas.w + iter->second.rightOffset;
  179. }
  180. bool CBitmapFont::canRepresentCharacter(const char *data) const
  181. {
  182. CodePoint localChar = TextOperations::getUnicodeCodepoint(data, 4);
  183. auto iter = chars.find(localChar);
  184. return iter != chars.end();
  185. }
  186. bool CBitmapFont::canRepresentString(const std::string & data) const
  187. {
  188. for(size_t i=0; i<data.size(); i += TextOperations::getUnicodeCharacterSize(data[i]))
  189. if (!canRepresentCharacter(data.data() + i))
  190. return false;
  191. return true;
  192. }
  193. void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & character, const ColorRGBA & color, int &posX, int &posY) const
  194. {
  195. int scalingFactor = GH.screenHandler().getScalingFactor();
  196. posX += character.leftOffset * scalingFactor;
  197. auto sdlColor = CSDL_Ext::toSDL(color);
  198. if (atlasImage->format->palette)
  199. SDL_SetPaletteColors(atlasImage->format->palette, &sdlColor, 255, 1);
  200. else
  201. SDL_SetSurfaceColorMod(atlasImage, color.r, color.g, color.b);
  202. CSDL_Ext::blitSurface(atlasImage, character.positionInAtlas * scalingFactor, surface, Point(posX, posY));
  203. posX += character.positionInAtlas.w * scalingFactor;
  204. posX += character.rightOffset * scalingFactor;
  205. }
  206. void CBitmapFont::renderText(SDL_Surface * surface, const std::string & data, const ColorRGBA & color, const Point & pos) const
  207. {
  208. if (data.empty())
  209. return;
  210. assert(surface);
  211. int posX = pos.x;
  212. int posY = pos.y;
  213. for(size_t i=0; i<data.size(); i += TextOperations::getUnicodeCharacterSize(data[i]))
  214. {
  215. CodePoint codepoint = TextOperations::getUnicodeCodepoint(data.data() + i, data.size() - i);
  216. auto iter = chars.find(codepoint);
  217. if (iter != chars.end())
  218. renderCharacter(surface, iter->second, color, posX, posY);
  219. }
  220. }