Fonts.cpp 11 KB

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