Fonts.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /*
  2. * Fonts.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 "Fonts.h"
  12. #include <SDL_ttf.h>
  13. #include "SDL_Pixels.h"
  14. #include "../../lib/JsonNode.h"
  15. #include "../../lib/vcmi_endian.h"
  16. #include "../../lib/filesystem/Filesystem.h"
  17. #include "../../lib/CGeneralTextHandler.h"
  18. size_t IFont::getStringWidth(const std::string & data) const
  19. {
  20. size_t width = 0;
  21. for(size_t i=0; i<data.size(); i += Unicode::getCharacterSize(data[i]))
  22. {
  23. width += getGlyphWidth(data.data() + i);
  24. }
  25. return width;
  26. }
  27. void IFont::renderTextLeft(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  28. {
  29. renderText(surface, data, color, pos);
  30. }
  31. void IFont::renderTextRight(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  32. {
  33. Point size((int)getStringWidth(data), (int)getLineHeight());
  34. renderText(surface, data, color, pos - size);
  35. }
  36. void IFont::renderTextCenter(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  37. {
  38. Point size((int)getStringWidth(data), (int)getLineHeight());
  39. renderText(surface, data, color, pos - size / 2);
  40. }
  41. void IFont::renderTextLinesLeft(SDL_Surface * surface, const std::vector<std::string> & data, const SDL_Color & color, const Point & pos) const
  42. {
  43. Point currPos = pos;
  44. for(const std::string & line : data)
  45. {
  46. renderTextLeft(surface, line, color, currPos);
  47. currPos.y += (int)getLineHeight();
  48. }
  49. }
  50. void IFont::renderTextLinesRight(SDL_Surface * surface, const std::vector<std::string> & data, const SDL_Color & color, const Point & pos) const
  51. {
  52. Point currPos = pos;
  53. currPos.y -= (int)data.size() * (int)getLineHeight();
  54. for(const std::string & line : data)
  55. {
  56. renderTextRight(surface, line, color, currPos);
  57. currPos.y += (int)getLineHeight();
  58. }
  59. }
  60. void IFont::renderTextLinesCenter(SDL_Surface * surface, const std::vector<std::string> & data, const SDL_Color & color, const Point & pos) const
  61. {
  62. Point currPos = pos;
  63. currPos.y -= (int)data.size() * (int)getLineHeight() / 2;
  64. for(const std::string & line : data)
  65. {
  66. renderTextCenter(surface, line, color, currPos);
  67. currPos.y += (int)getLineHeight();
  68. }
  69. }
  70. std::array<CBitmapFont::BitmapChar, CBitmapFont::totalChars> CBitmapFont::loadChars() const
  71. {
  72. std::array<BitmapChar, totalChars> ret;
  73. size_t offset = 32;
  74. for (auto & elem : ret)
  75. {
  76. elem.leftOffset = read_le_u32(data.first.get() + offset); offset+=4;
  77. elem.width = read_le_u32(data.first.get() + offset); offset+=4;
  78. elem.rightOffset = read_le_u32(data.first.get() + offset); offset+=4;
  79. }
  80. for (auto & elem : ret)
  81. {
  82. int pixelOffset = read_le_u32(data.first.get() + offset); offset+=4;
  83. elem.pixels = data.first.get() + 4128 + pixelOffset;
  84. assert(pixelOffset + 4128 < data.second);
  85. }
  86. return ret;
  87. }
  88. CBitmapFont::CBitmapFont(const std::string & filename):
  89. data(CResourceHandler::get()->load(ResourceID("data/" + filename, EResType::BMP_FONT))->readAll()),
  90. chars(loadChars()),
  91. height(data.first.get()[5])
  92. {}
  93. size_t CBitmapFont::getLineHeight() const
  94. {
  95. return height;
  96. }
  97. size_t CBitmapFont::getGlyphWidth(const char * data) const
  98. {
  99. std::string localChar = Unicode::fromUnicode(std::string(data, Unicode::getCharacterSize(data[0])));
  100. if (localChar.size() == 1)
  101. {
  102. const BitmapChar & ch = chars[ui8(localChar[0])];
  103. return ch.leftOffset + ch.width + ch.rightOffset;
  104. }
  105. return 0;
  106. }
  107. void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & character, const SDL_Color & color, int &posX, int &posY) const
  108. {
  109. Rect clipRect;
  110. CSDL_Ext::getClipRect(surface, clipRect);
  111. posX += character.leftOffset;
  112. CSDL_Ext::TColorPutter colorPutter = CSDL_Ext::getPutterFor(surface, 0);
  113. Uint8 bpp = surface->format->BytesPerPixel;
  114. // start of line, may differ from 0 due to end of surface or clipped surface
  115. int lineBegin = std::max<int>(0, clipRect.y - posY);
  116. int lineEnd = std::min<int>(height, clipRect.y + clipRect.h - posY - 1);
  117. // start end end of each row, may differ from 0
  118. int rowBegin = std::max<int>(0, clipRect.x - posX);
  119. int rowEnd = std::min<int>(character.width, clipRect.x + clipRect.w - posX - 1);
  120. //for each line in symbol
  121. for(int dy = lineBegin; dy <lineEnd; dy++)
  122. {
  123. Uint8 *dstLine = (Uint8*)surface->pixels;
  124. Uint8 *srcLine = character.pixels;
  125. // shift source\destination pixels to current position
  126. dstLine += (posY+dy) * surface->pitch + posX * bpp;
  127. srcLine += dy * character.width;
  128. //for each column in line
  129. for(int dx = rowBegin; dx < rowEnd; dx++)
  130. {
  131. Uint8* dstPixel = dstLine + dx*bpp;
  132. switch(srcLine[dx])
  133. {
  134. case 1: //black "shadow"
  135. colorPutter(dstPixel, 0, 0, 0);
  136. break;
  137. case 255: //text colour
  138. colorPutter(dstPixel, color.r, color.g, color.b);
  139. break;
  140. default :
  141. break; //transparency
  142. }
  143. }
  144. }
  145. posX += character.width;
  146. posX += character.rightOffset;
  147. }
  148. void CBitmapFont::renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  149. {
  150. if (data.empty())
  151. return;
  152. assert(surface);
  153. int posX = pos.x;
  154. int posY = pos.y;
  155. // Should be used to detect incorrect text parsing. Disabled right now due to some old UI code (mostly pregame and battles)
  156. //assert(data[0] != '{');
  157. //assert(data[data.size()-1] != '}');
  158. SDL_LockSurface(surface);
  159. for(size_t i=0; i<data.size(); i += Unicode::getCharacterSize(data[i]))
  160. {
  161. std::string localChar = Unicode::fromUnicode(data.substr(i, Unicode::getCharacterSize(data[i])));
  162. if (localChar.size() == 1)
  163. renderCharacter(surface, chars[ui8(localChar[0])], color, posX, posY);
  164. }
  165. SDL_UnlockSurface(surface);
  166. }
  167. std::pair<std::unique_ptr<ui8[]>, ui64> CTrueTypeFont::loadData(const JsonNode & config)
  168. {
  169. std::string filename = "Data/" + config["file"].String();
  170. return CResourceHandler::get()->load(ResourceID(filename, EResType::TTF_FONT))->readAll();
  171. }
  172. TTF_Font * CTrueTypeFont::loadFont(const JsonNode &config)
  173. {
  174. int pointSize = static_cast<int>(config["size"].Float());
  175. if(!TTF_WasInit() && TTF_Init()==-1)
  176. throw std::runtime_error(std::string("Failed to initialize true type support: ") + TTF_GetError() + "\n");
  177. return TTF_OpenFontRW(SDL_RWFromConstMem(data.first.get(), (int)data.second), 1, pointSize);
  178. }
  179. int CTrueTypeFont::getFontStyle(const JsonNode &config)
  180. {
  181. const JsonVector & names = config["style"].Vector();
  182. int ret = 0;
  183. for(const JsonNode & node : names)
  184. {
  185. if (node.String() == "bold")
  186. ret |= TTF_STYLE_BOLD;
  187. else if (node.String() == "italic")
  188. ret |= TTF_STYLE_ITALIC;
  189. }
  190. return ret;
  191. }
  192. CTrueTypeFont::CTrueTypeFont(const JsonNode & fontConfig):
  193. data(loadData(fontConfig)),
  194. font(loadFont(fontConfig), TTF_CloseFont),
  195. blended(fontConfig["blend"].Bool())
  196. {
  197. assert(font);
  198. TTF_SetFontStyle(font.get(), getFontStyle(fontConfig));
  199. }
  200. size_t CTrueTypeFont::getLineHeight() const
  201. {
  202. return TTF_FontHeight(font.get());
  203. }
  204. size_t CTrueTypeFont::getGlyphWidth(const char *data) const
  205. {
  206. return getStringWidth(std::string(data, Unicode::getCharacterSize(*data)));
  207. /*
  208. int advance;
  209. TTF_GlyphMetrics(font.get(), *data, nullptr, nullptr, nullptr, nullptr, &advance);
  210. return advance;
  211. */
  212. }
  213. size_t CTrueTypeFont::getStringWidth(const std::string & data) const
  214. {
  215. int width;
  216. TTF_SizeUTF8(font.get(), data.c_str(), &width, nullptr);
  217. return width;
  218. }
  219. void CTrueTypeFont::renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  220. {
  221. if (color.r != 0 && color.g != 0 && color.b != 0) // not black - add shadow
  222. {
  223. SDL_Color black = { 0, 0, 0, SDL_ALPHA_OPAQUE};
  224. renderText(surface, data, black, pos + Point(1,1));
  225. }
  226. if (!data.empty())
  227. {
  228. SDL_Surface * rendered;
  229. if (blended)
  230. rendered = TTF_RenderUTF8_Blended(font.get(), data.c_str(), color);
  231. else
  232. rendered = TTF_RenderUTF8_Solid(font.get(), data.c_str(), color);
  233. assert(rendered);
  234. CSDL_Ext::blitSurface(rendered, surface, pos);
  235. SDL_FreeSurface(rendered);
  236. }
  237. }
  238. size_t CBitmapHanFont::getCharacterDataOffset(size_t index) const
  239. {
  240. size_t rowSize = (size + 7) / 8; // 1 bit per pixel, rounded up
  241. size_t charSize = rowSize * size; // glyph contains "size" rows
  242. return index * charSize;
  243. }
  244. size_t CBitmapHanFont::getCharacterIndex(ui8 first, ui8 second) const
  245. {
  246. if (second > 0x7f )
  247. second--;
  248. return (first - 0x81) * (12*16 - 2) + (second - 0x40);
  249. }
  250. void CBitmapHanFont::renderCharacter(SDL_Surface * surface, int characterIndex, const SDL_Color & color, int &posX, int &posY) const
  251. {
  252. //TODO: somewhat duplicated with CBitmapFont::renderCharacter();
  253. Rect clipRect;
  254. CSDL_Ext::getClipRect(surface, clipRect);
  255. CSDL_Ext::TColorPutter colorPutter = CSDL_Ext::getPutterFor(surface, 0);
  256. Uint8 bpp = surface->format->BytesPerPixel;
  257. // start of line, may differ from 0 due to end of surface or clipped surface
  258. int lineBegin = std::max<int>(0, clipRect.y - posY);
  259. int lineEnd = std::min((int)size, clipRect.y + clipRect.h - posY);
  260. // start end end of each row, may differ from 0
  261. int rowBegin = std::max<int>(0, clipRect.x - posX);
  262. int rowEnd = std::min<int>((int)size, clipRect.x + clipRect.w - posX);
  263. //for each line in symbol
  264. for(int dy = lineBegin; dy <lineEnd; dy++)
  265. {
  266. Uint8 *dstLine = (Uint8*)surface->pixels;
  267. Uint8 *source = data.first.get() + getCharacterDataOffset(characterIndex);
  268. // shift source\destination pixels to current position
  269. dstLine += (posY+dy) * surface->pitch + posX * bpp;
  270. source += ((size + 7) / 8) * dy;
  271. //for each column in line
  272. for(int dx = rowBegin; dx < rowEnd; dx++)
  273. {
  274. // select current bit in bitmap
  275. int bit = (source[dx / 8] << (dx % 8)) & 0x80;
  276. Uint8* dstPixel = dstLine + dx*bpp;
  277. if (bit != 0)
  278. colorPutter(dstPixel, color.r, color.g, color.b);
  279. }
  280. }
  281. posX += (int)size + 1;
  282. }
  283. void CBitmapHanFont::renderText(SDL_Surface * surface, const std::string & data, const SDL_Color & color, const Point & pos) const
  284. {
  285. int posX = pos.x;
  286. int posY = pos.y;
  287. SDL_LockSurface(surface);
  288. for(size_t i=0; i<data.size(); i += Unicode::getCharacterSize(data[i]))
  289. {
  290. std::string localChar = Unicode::fromUnicode(data.substr(i, Unicode::getCharacterSize(data[i])));
  291. if (localChar.size() == 1)
  292. fallback->renderCharacter(surface, fallback->chars[ui8(localChar[0])], color, posX, posY);
  293. if (localChar.size() == 2)
  294. renderCharacter(surface, (int)getCharacterIndex(localChar[0], localChar[1]), color, posX, posY);
  295. }
  296. SDL_UnlockSurface(surface);
  297. }
  298. CBitmapHanFont::CBitmapHanFont(const JsonNode &config):
  299. fallback(new CBitmapFont(config["fallback"].String())),
  300. data(CResourceHandler::get()->load(ResourceID("data/" + config["name"].String(), EResType::OTHER))->readAll()),
  301. size((size_t)config["size"].Float())
  302. {
  303. // basic tests to make sure that fonts are OK
  304. // 1) fonts must contain 190 "sections", 126 symbols each.
  305. assert(getCharacterIndex(0xfe, 0xff) == 190*126);
  306. // 2) ensure that font size is correct - enough to fit all possible symbols
  307. assert(getCharacterDataOffset(getCharacterIndex(0xfe, 0xff)) == data.second);
  308. }
  309. size_t CBitmapHanFont::getLineHeight() const
  310. {
  311. return std::max(size + 1, fallback->getLineHeight());
  312. }
  313. size_t CBitmapHanFont::getGlyphWidth(const char * data) const
  314. {
  315. std::string localChar = Unicode::fromUnicode(std::string(data, Unicode::getCharacterSize(data[0])));
  316. if (localChar.size() == 1)
  317. return fallback->getGlyphWidth(data);
  318. if (localChar.size() == 2)
  319. return size + 1;
  320. return 0;
  321. }