Font.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. /**
  2. * Copyright (c) 2006-2016 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "common/config.h"
  21. #include "Font.h"
  22. #include "font/GlyphData.h"
  23. #include "libraries/utf8/utf8.h"
  24. #include "common/math.h"
  25. #include "common/Matrix.h"
  26. #include "graphics/Graphics.h"
  27. #include <math.h>
  28. #include <sstream>
  29. #include <algorithm> // for max
  30. #include <limits>
  31. namespace love
  32. {
  33. namespace graphics
  34. {
  35. namespace opengl
  36. {
  37. static inline uint16 normToUint16(double n)
  38. {
  39. return (uint16) (n * LOVE_UINT16_MAX);
  40. }
  41. int Font::fontCount = 0;
  42. Font::Font(love::font::Rasterizer *r, const Texture::Filter &filter)
  43. : rasterizers({r})
  44. , height(r->getHeight())
  45. , lineHeight(1)
  46. , textureWidth(128)
  47. , textureHeight(128)
  48. , filter(filter)
  49. , useSpacesAsTab(false)
  50. , quadIndices(20) // We make this bigger at draw-time, if needed.
  51. , textureCacheID(0)
  52. , textureMemorySize(0)
  53. {
  54. this->filter.mipmap = Texture::FILTER_NONE;
  55. // Try to find the best texture size match for the font size. default to the
  56. // largest texture size if no rough match is found.
  57. while (true)
  58. {
  59. if ((height * 0.8) * height * 30 <= textureWidth * textureHeight)
  60. break;
  61. TextureSize nextsize = getNextTextureSize();
  62. if (nextsize.width <= textureWidth && nextsize.height <= textureHeight)
  63. break;
  64. textureWidth = nextsize.width;
  65. textureHeight = nextsize.height;
  66. }
  67. love::font::GlyphData *gd = r->getGlyphData(32); // Space character.
  68. type = (gd->getFormat() == font::GlyphData::FORMAT_LUMINANCE_ALPHA) ? FONT_TRUETYPE : FONT_IMAGE;
  69. gd->release();
  70. if (!r->hasGlyph(9)) // No tab character in the Rasterizer.
  71. useSpacesAsTab = true;
  72. loadVolatile();
  73. ++fontCount;
  74. }
  75. Font::~Font()
  76. {
  77. unloadVolatile();
  78. --fontCount;
  79. }
  80. Font::TextureSize Font::getNextTextureSize() const
  81. {
  82. TextureSize size = {textureWidth, textureHeight};
  83. int maxsize = std::min(4096, gl.getMaxTextureSize());
  84. if (size.width * 2 <= maxsize || size.height * 2 <= maxsize)
  85. {
  86. // {128, 128} -> {256, 128} -> {256, 256} -> {512, 256} -> etc.
  87. if (size.width == size.height)
  88. size.width *= 2;
  89. else
  90. size.height *= 2;
  91. }
  92. return size;
  93. }
  94. GLenum Font::getTextureFormat(FontType fontType, GLenum *internalformat) const
  95. {
  96. GLenum format = fontType == FONT_TRUETYPE ? GL_LUMINANCE_ALPHA : GL_RGBA;
  97. GLenum iformat = fontType == FONT_TRUETYPE ? GL_LUMINANCE8_ALPHA8 : GL_RGBA8;
  98. if (format == GL_RGBA && isGammaCorrect())
  99. {
  100. // In ES2, the internalformat and format params of TexImage must match.
  101. // ES3 doesn't allow "GL_SRGB_ALPHA" as the internal format. But it also
  102. // requires GL_LUMINANCE_ALPHA rather than GL_LUMINANCE8_ALPHA8 as the
  103. // internal format, for LA.
  104. if (GLAD_ES_VERSION_2_0 && !GLAD_ES_VERSION_3_0)
  105. format = iformat = GL_SRGB_ALPHA;
  106. else
  107. iformat = GL_SRGB8_ALPHA8;
  108. }
  109. else if (GLAD_ES_VERSION_2_0)
  110. iformat = format;
  111. if (internalformat != nullptr)
  112. *internalformat = iformat;
  113. return format;
  114. }
  115. void Font::createTexture()
  116. {
  117. OpenGL::TempDebugGroup debuggroup("Font create texture");
  118. size_t bpp = type == FONT_TRUETYPE ? 2 : 4;
  119. size_t prevmemsize = textureMemorySize;
  120. if (prevmemsize > 0)
  121. {
  122. textureMemorySize -= (textureWidth * textureHeight * bpp);
  123. gl.updateTextureMemorySize(prevmemsize, textureMemorySize);
  124. }
  125. GLuint t = 0;
  126. TextureSize size = {textureWidth, textureHeight};
  127. TextureSize nextsize = getNextTextureSize();
  128. bool recreatetexture = false;
  129. // If we have an existing texture already, we'll try replacing it with a
  130. // larger-sized one rather than creating a second one. Having a single
  131. // texture reduces texture switches and draw calls when rendering.
  132. if ((nextsize.width > size.width || nextsize.height > size.height)
  133. && !textures.empty())
  134. {
  135. recreatetexture = true;
  136. size = nextsize;
  137. t = textures.back();
  138. }
  139. else
  140. glGenTextures(1, &t);
  141. gl.bindTexture(t);
  142. gl.setTextureFilter(filter);
  143. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  144. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  145. GLenum internalformat = GL_RGBA;
  146. GLenum format = getTextureFormat(type, &internalformat);
  147. // Initialize the texture with transparent black.
  148. std::vector<GLubyte> emptydata(size.width * size.height * bpp, 0);
  149. // Clear errors before initializing.
  150. while (glGetError() != GL_NO_ERROR);
  151. glTexImage2D(GL_TEXTURE_2D, 0, internalformat, size.width, size.height, 0,
  152. format, GL_UNSIGNED_BYTE, &emptydata[0]);
  153. if (glGetError() != GL_NO_ERROR)
  154. {
  155. if (!recreatetexture)
  156. gl.deleteTexture(t);
  157. throw love::Exception("Could not create font texture!");
  158. }
  159. textureWidth = size.width;
  160. textureHeight = size.height;
  161. rowHeight = textureX = textureY = TEXTURE_PADDING;
  162. prevmemsize = textureMemorySize;
  163. textureMemorySize += emptydata.size();
  164. gl.updateTextureMemorySize(prevmemsize, textureMemorySize);
  165. // Re-add the old glyphs if we re-created the existing texture object.
  166. if (recreatetexture)
  167. {
  168. textureCacheID++;
  169. std::vector<uint32> glyphstoadd;
  170. for (const auto &glyphpair : glyphs)
  171. glyphstoadd.push_back(glyphpair.first);
  172. glyphs.clear();
  173. for (uint32 g : glyphstoadd)
  174. addGlyph(g);
  175. }
  176. else
  177. textures.push_back(t);
  178. }
  179. love::font::GlyphData *Font::getRasterizerGlyphData(uint32 glyph)
  180. {
  181. // Use spaces for the tab 'glyph'.
  182. if (glyph == 9 && useSpacesAsTab)
  183. {
  184. love::font::GlyphData *spacegd = rasterizers[0]->getGlyphData(32);
  185. love::font::GlyphData::Format fmt = spacegd->getFormat();
  186. love::font::GlyphMetrics gm = {};
  187. gm.advance = spacegd->getAdvance() * SPACES_PER_TAB;
  188. gm.bearingX = spacegd->getBearingX();
  189. gm.bearingY = spacegd->getBearingY();
  190. spacegd->release();
  191. return new love::font::GlyphData(glyph, gm, fmt);
  192. }
  193. for (const StrongRef<love::font::Rasterizer> &r : rasterizers)
  194. {
  195. if (r->hasGlyph(glyph))
  196. return r->getGlyphData(glyph);
  197. }
  198. return rasterizers[0]->getGlyphData(glyph);
  199. }
  200. const Font::Glyph &Font::addGlyph(uint32 glyph)
  201. {
  202. StrongRef<love::font::GlyphData> gd(getRasterizerGlyphData(glyph), Acquire::NORETAIN);
  203. int w = gd->getWidth();
  204. int h = gd->getHeight();
  205. if (textureX + w + TEXTURE_PADDING > textureWidth)
  206. {
  207. // out of space - new row!
  208. textureX = TEXTURE_PADDING;
  209. textureY += rowHeight;
  210. rowHeight = TEXTURE_PADDING;
  211. }
  212. if (textureY + h + TEXTURE_PADDING > textureHeight)
  213. {
  214. // totally out of space - new texture!
  215. createTexture();
  216. // Makes sure the above code for checking if the glyph can fit at
  217. // the current position in the texture is run again for this glyph.
  218. return addGlyph(glyph);
  219. }
  220. Glyph g;
  221. g.texture = 0;
  222. g.spacing = gd->getAdvance();
  223. memset(g.vertices, 0, sizeof(GlyphVertex) * 4);
  224. // don't waste space for empty glyphs. also fixes a divide by zero bug with ATI drivers
  225. if (w > 0 && h > 0)
  226. {
  227. GLenum format = getTextureFormat(type);
  228. g.texture = textures.back();
  229. gl.bindTexture(g.texture);
  230. glTexSubImage2D(GL_TEXTURE_2D, 0, textureX, textureY, w, h,
  231. format, GL_UNSIGNED_BYTE, gd->getData());
  232. double tX = (double) textureX, tY = (double) textureY;
  233. double tWidth = (double) textureWidth, tHeight = (double) textureHeight;
  234. Color c(255, 255, 255, 255);
  235. // 0----2
  236. // | / |
  237. // | / |
  238. // 1----3
  239. const GlyphVertex verts[4] = {
  240. {float(0), float(0), normToUint16((tX+0)/tWidth), normToUint16((tY+0)/tHeight), c},
  241. {float(0), float(h), normToUint16((tX+0)/tWidth), normToUint16((tY+h)/tHeight), c},
  242. {float(w), float(0), normToUint16((tX+w)/tWidth), normToUint16((tY+0)/tHeight), c},
  243. {float(w), float(h), normToUint16((tX+w)/tWidth), normToUint16((tY+h)/tHeight), c}
  244. };
  245. // Copy vertex data to the glyph and set proper bearing.
  246. for (int i = 0; i < 4; i++)
  247. {
  248. g.vertices[i] = verts[i];
  249. g.vertices[i].x += gd->getBearingX();
  250. g.vertices[i].y -= gd->getBearingY();
  251. }
  252. textureX += w + TEXTURE_PADDING;
  253. rowHeight = std::max(rowHeight, h + TEXTURE_PADDING);
  254. }
  255. const auto p = glyphs.insert(std::make_pair(glyph, g));
  256. return p.first->second;
  257. }
  258. const Font::Glyph &Font::findGlyph(uint32 glyph)
  259. {
  260. const auto it = glyphs.find(glyph);
  261. if (it != glyphs.end())
  262. return it->second;
  263. return addGlyph(glyph);
  264. }
  265. float Font::getKerning(uint32 leftglyph, uint32 rightglyph)
  266. {
  267. uint64 packedglyphs = ((uint64) leftglyph << 32) | (uint64) rightglyph;
  268. const auto it = kerning.find(packedglyphs);
  269. if (it != kerning.end())
  270. return it->second;
  271. float k = rasterizers[0]->getKerning(leftglyph, rightglyph);
  272. for (const auto &r : rasterizers)
  273. {
  274. if (r->hasGlyph(leftglyph) && r->hasGlyph(rightglyph))
  275. {
  276. k = r->getKerning(leftglyph, rightglyph);
  277. break;
  278. }
  279. }
  280. kerning[packedglyphs] = k;
  281. return k;
  282. }
  283. void Font::getCodepointsFromString(const std::string &text, Codepoints &codepoints)
  284. {
  285. codepoints.reserve(text.size());
  286. try
  287. {
  288. utf8::iterator<std::string::const_iterator> i(text.begin(), text.begin(), text.end());
  289. utf8::iterator<std::string::const_iterator> end(text.end(), text.begin(), text.end());
  290. while (i != end)
  291. {
  292. uint32 g = *i++;
  293. codepoints.push_back(g);
  294. }
  295. }
  296. catch (utf8::exception &e)
  297. {
  298. throw love::Exception("UTF-8 decoding error: %s", e.what());
  299. }
  300. }
  301. void Font::getCodepointsFromString(const std::vector<ColoredString> &strs, ColoredCodepoints &codepoints)
  302. {
  303. if (strs.empty())
  304. return;
  305. codepoints.cps.reserve(strs[0].str.size());
  306. for (const ColoredString &cstr : strs)
  307. {
  308. // No need to add the color if the string is empty anyway, and the code
  309. // further on assumes no two colors share the same starting position.
  310. if (cstr.str.size() == 0)
  311. continue;
  312. IndexedColor c = {cstr.color, (int) codepoints.cps.size()};
  313. codepoints.colors.push_back(c);
  314. getCodepointsFromString(cstr.str, codepoints.cps);
  315. }
  316. if (codepoints.colors.size() == 1)
  317. {
  318. IndexedColor c = codepoints.colors[0];
  319. if (c.index == 0 && c.color == Colorf(1.0f, 1.0f, 1.0f, 1.0f))
  320. codepoints.colors.pop_back();
  321. }
  322. }
  323. float Font::getHeight() const
  324. {
  325. return (float) height;
  326. }
  327. std::vector<Font::DrawCommand> Font::generateVertices(const ColoredCodepoints &codepoints, std::vector<GlyphVertex> &vertices, float extra_spacing, Vector offset, TextInfo *info)
  328. {
  329. // Spacing counter and newline handling.
  330. float dx = offset.x;
  331. float dy = offset.y;
  332. float lineheight = getBaseline();
  333. int maxwidth = 0;
  334. // Keeps track of when we need to switch textures in our vertex array.
  335. std::vector<DrawCommand> commands;
  336. // Pre-allocate space for the maximum possible number of vertices.
  337. size_t vertstartsize = vertices.size();
  338. vertices.reserve(vertstartsize + codepoints.cps.size() * 4);
  339. uint32 prevglyph = 0;
  340. Color curcolor(255, 255, 255, 255);
  341. int curcolori = -1;
  342. int ncolors = (int) codepoints.colors.size();
  343. for (int i = 0; i < (int) codepoints.cps.size(); i++)
  344. {
  345. uint32 g = codepoints.cps[i];
  346. if (curcolori + 1 < ncolors && codepoints.colors[curcolori + 1].index == i)
  347. {
  348. const Colorf &c = codepoints.colors[++curcolori].color;
  349. curcolor.r = (unsigned char) (c.r * 255.0f);
  350. curcolor.g = (unsigned char) (c.g * 255.0f);
  351. curcolor.b = (unsigned char) (c.b * 255.0f);
  352. curcolor.a = (unsigned char) (c.a * 255.0f);
  353. }
  354. if (g == '\n')
  355. {
  356. if (dx > maxwidth)
  357. maxwidth = (int) dx;
  358. // Wrap newline, but do not print it.
  359. dy += floorf(getHeight() * getLineHeight() + 0.5f);
  360. dx = offset.x;
  361. continue;
  362. }
  363. // Ignore carriage returns
  364. if (g == '\r')
  365. continue;
  366. uint32 cacheid = textureCacheID;
  367. const Glyph &glyph = findGlyph(g);
  368. // If findGlyph invalidates the texture cache, re-start the loop.
  369. if (cacheid != textureCacheID)
  370. {
  371. i = 0;
  372. maxwidth = 0;
  373. dx = offset.x;
  374. dy = offset.y;
  375. commands.clear();
  376. vertices.resize(vertstartsize);
  377. prevglyph = 0;
  378. curcolori = -1;
  379. curcolor = Color(255, 255, 255, 255);
  380. continue;
  381. }
  382. // Add kerning to the current horizontal offset.
  383. dx += getKerning(prevglyph, g);
  384. if (glyph.texture != 0)
  385. {
  386. // Copy the vertices and set their colors and relative positions.
  387. for (int j = 0; j < 4; j++)
  388. {
  389. vertices.push_back(glyph.vertices[j]);
  390. vertices.back().x += dx;
  391. vertices.back().y += dy + lineheight;
  392. vertices.back().color = curcolor;
  393. }
  394. // Check if glyph texture has changed since the last iteration.
  395. if (commands.empty() || commands.back().texture != glyph.texture)
  396. {
  397. // Add a new draw command if the texture has changed.
  398. DrawCommand cmd;
  399. cmd.startvertex = (int) vertices.size() - 4;
  400. cmd.vertexcount = 0;
  401. cmd.texture = glyph.texture;
  402. commands.push_back(cmd);
  403. }
  404. commands.back().vertexcount += 4;
  405. }
  406. // Advance the x position for the next glyph.
  407. dx += glyph.spacing;
  408. // Account for extra spacing given to space characters.
  409. if (g == ' ' && extra_spacing != 0.0f)
  410. dx = floorf(dx + extra_spacing);
  411. prevglyph = g;
  412. }
  413. const auto drawsort = [](const DrawCommand &a, const DrawCommand &b) -> bool
  414. {
  415. // Texture binds are expensive, so we should sort by that first.
  416. if (a.texture != b.texture)
  417. return a.texture < b.texture;
  418. else
  419. return a.startvertex < b.startvertex;
  420. };
  421. std::sort(commands.begin(), commands.end(), drawsort);
  422. if (dx > maxwidth)
  423. maxwidth = (int) dx;
  424. if (info != nullptr)
  425. {
  426. info->width = maxwidth - offset.x;;
  427. info->height = (int) dy + (dx > 0.0f ? floorf(getHeight() * getLineHeight() + 0.5f) : 0) - offset.y;
  428. }
  429. return commands;
  430. }
  431. std::vector<Font::DrawCommand> Font::generateVertices(const std::string &text, std::vector<GlyphVertex> &vertices, float extra_spacing, Vector offset, TextInfo *info)
  432. {
  433. ColoredCodepoints codepoints;
  434. getCodepointsFromString(text, codepoints.cps);
  435. return generateVertices(codepoints, vertices, extra_spacing, offset, info);
  436. }
  437. std::vector<Font::DrawCommand> Font::generateVerticesFormatted(const ColoredCodepoints &text, float wrap, AlignMode align, std::vector<GlyphVertex> &vertices, TextInfo *info)
  438. {
  439. wrap = std::max(wrap, 0.0f);
  440. uint32 cacheid = textureCacheID;
  441. std::vector<DrawCommand> drawcommands;
  442. vertices.reserve(text.cps.size() * 4);
  443. std::vector<int> widths;
  444. std::vector<ColoredCodepoints> lines;
  445. getWrap(text, wrap, lines, &widths);
  446. float y = 0.0f;
  447. float maxwidth = 0.0f;
  448. for (int i = 0; i < (int) lines.size(); i++)
  449. {
  450. const auto &line = lines[i];
  451. float width = (float) widths[i];
  452. love::Vector offset(0.0f, floorf(y));
  453. float extraspacing = 0.0f;
  454. maxwidth = std::max(width, maxwidth);
  455. switch (align)
  456. {
  457. case ALIGN_RIGHT:
  458. offset.x = floorf(wrap - width);
  459. break;
  460. case ALIGN_CENTER:
  461. offset.x = floorf((wrap - width) / 2.0f);
  462. break;
  463. case ALIGN_JUSTIFY:
  464. {
  465. float numspaces = (float) std::count(line.cps.begin(), line.cps.end(), ' ');
  466. if (width < wrap && numspaces >= 1)
  467. extraspacing = (wrap - width) / numspaces;
  468. else
  469. extraspacing = 0.0f;
  470. break;
  471. }
  472. case ALIGN_LEFT:
  473. default:
  474. break;
  475. }
  476. std::vector<DrawCommand> newcommands = generateVertices(line, vertices, extraspacing, offset);
  477. if (!newcommands.empty())
  478. {
  479. auto firstcmd = newcommands.begin();
  480. // If the first draw command in the new list has the same texture
  481. // as the last one in the existing list we're building and its
  482. // vertices are in-order, we can combine them (saving a draw call.)
  483. if (!drawcommands.empty())
  484. {
  485. auto prevcmd = drawcommands.back();
  486. if (prevcmd.texture == firstcmd->texture && (prevcmd.startvertex + prevcmd.vertexcount) == firstcmd->startvertex)
  487. {
  488. drawcommands.back().vertexcount += firstcmd->vertexcount;
  489. ++firstcmd;
  490. }
  491. }
  492. // Append the new draw commands to the list we're building.
  493. drawcommands.insert(drawcommands.end(), firstcmd, newcommands.end());
  494. }
  495. y += getHeight() * getLineHeight();
  496. }
  497. if (info != nullptr)
  498. {
  499. info->width = (int) maxwidth;
  500. info->height = (int) y;
  501. }
  502. if (cacheid != textureCacheID)
  503. {
  504. vertices.clear();
  505. drawcommands = generateVerticesFormatted(text, wrap, align, vertices);
  506. }
  507. return drawcommands;
  508. }
  509. void Font::drawVertices(const std::vector<DrawCommand> &drawcommands, bool bufferedvertices)
  510. {
  511. // Vertex attribute pointers need to be set before calling this function.
  512. // This assumes that the attribute pointers are constant for all vertices.
  513. int totalverts = 0;
  514. for (const DrawCommand &cmd : drawcommands)
  515. totalverts = std::max(cmd.startvertex + cmd.vertexcount, totalverts);
  516. if ((size_t) totalverts / 4 > quadIndices.getSize())
  517. quadIndices = QuadIndices((size_t) totalverts / 4);
  518. gl.prepareDraw();
  519. const GLenum gltype = quadIndices.getType();
  520. const size_t elemsize = quadIndices.getElementSize();
  521. // We only get indices from the index buffer if we're also using vertex
  522. // buffers, because at least one graphics driver (the one for Kepler nvidia
  523. // GPUs in OS X 10.11) fails to render geometry if an index buffer is used
  524. // with client-side vertex arrays.
  525. if (bufferedvertices)
  526. quadIndices.getBuffer()->bind();
  527. // We need a separate draw call for every section of the text which uses a
  528. // different texture than the previous section.
  529. for (const DrawCommand &cmd : drawcommands)
  530. {
  531. GLsizei count = (cmd.vertexcount / 4) * 6;
  532. size_t offset = (cmd.startvertex / 4) * 6 * elemsize;
  533. // TODO: Use glDrawElementsBaseVertex when supported?
  534. gl.bindTexture(cmd.texture);
  535. if (bufferedvertices)
  536. gl.drawElements(GL_TRIANGLES, count, gltype, quadIndices.getPointer(offset));
  537. else
  538. gl.drawElements(GL_TRIANGLES, count, gltype, quadIndices.getIndices(offset));
  539. }
  540. if (bufferedvertices)
  541. quadIndices.getBuffer()->unbind();
  542. }
  543. void Font::printv(const Matrix4 &t, const std::vector<DrawCommand> &drawcommands, const std::vector<GlyphVertex> &vertices)
  544. {
  545. if (vertices.empty() || drawcommands.empty())
  546. return;
  547. OpenGL::TempDebugGroup debuggroup("Font print");
  548. OpenGL::TempTransform transform(gl);
  549. transform.get() *= t;
  550. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, sizeof(GlyphVertex), &vertices[0].x);
  551. glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_UNSIGNED_SHORT, GL_TRUE, sizeof(GlyphVertex), &vertices[0].s);
  552. glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(GlyphVertex), &vertices[0].color.r);
  553. gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_TEXCOORD | ATTRIBFLAG_COLOR);
  554. drawVertices(drawcommands, false);
  555. }
  556. void Font::print(const std::vector<ColoredString> &text, float x, float y, float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  557. {
  558. ColoredCodepoints codepoints;
  559. getCodepointsFromString(text, codepoints);
  560. std::vector<GlyphVertex> vertices;
  561. std::vector<DrawCommand> drawcommands = generateVertices(codepoints, vertices);
  562. Matrix4 t(x, y, angle, sx, sy, ox, oy, kx, ky);
  563. printv(t, drawcommands, vertices);
  564. }
  565. void Font::printf(const std::vector<ColoredString> &text, float x, float y, float wrap, AlignMode align, float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  566. {
  567. ColoredCodepoints codepoints;
  568. getCodepointsFromString(text, codepoints);
  569. std::vector<GlyphVertex> vertices;
  570. std::vector<DrawCommand> drawcommands = generateVerticesFormatted(codepoints, wrap, align, vertices);
  571. Matrix4 t(x, y, angle, sx, sy, ox, oy, kx, ky);
  572. printv(t, drawcommands, vertices);
  573. }
  574. int Font::getWidth(const std::string &str)
  575. {
  576. if (str.size() == 0) return 0;
  577. std::istringstream iss(str);
  578. std::string line;
  579. int max_width = 0;
  580. while (getline(iss, line, '\n'))
  581. {
  582. int width = 0;
  583. uint32 prevglyph = 0;
  584. try
  585. {
  586. utf8::iterator<std::string::const_iterator> i(line.begin(), line.begin(), line.end());
  587. utf8::iterator<std::string::const_iterator> end(line.end(), line.begin(), line.end());
  588. while (i != end)
  589. {
  590. uint32 c = *i++;
  591. // Ignore carriage returns
  592. if (c == '\r')
  593. continue;
  594. const Glyph &g = findGlyph(c);
  595. width += g.spacing + getKerning(prevglyph, c);
  596. prevglyph = c;
  597. }
  598. }
  599. catch (utf8::exception &e)
  600. {
  601. throw love::Exception("UTF-8 decoding error: %s", e.what());
  602. }
  603. max_width = std::max(max_width, width);
  604. }
  605. return max_width;
  606. }
  607. int Font::getWidth(char character)
  608. {
  609. const Glyph &g = findGlyph(character);
  610. return g.spacing;
  611. }
  612. void Font::getWrap(const ColoredCodepoints &codepoints, float wraplimit, std::vector<ColoredCodepoints> &lines, std::vector<int> *linewidths)
  613. {
  614. // Per-line info.
  615. float width = 0.0f;
  616. float widthbeforelastspace = 0.0f;
  617. float widthoftrailingspace = 0.0f;
  618. uint32 prevglyph = 0;
  619. int lastspaceindex = -1;
  620. // Keeping the indexed colors "in sync" is a bit tricky, since we split
  621. // things up and we might skip some glyphs but we don't want to skip any
  622. // color which starts at those indices.
  623. Colorf curcolor(1.0f, 1.0f, 1.0f, 1.0f);
  624. bool addcurcolor = false;
  625. int curcolori = -1;
  626. int endcolori = (int) codepoints.colors.size() - 1;
  627. // A wrapped line of text.
  628. ColoredCodepoints wline;
  629. int i = 0;
  630. while (i < (int) codepoints.cps.size())
  631. {
  632. uint32 c = codepoints.cps[i];
  633. // Determine the current color before doing anything else, to make sure
  634. // it's still applied to future glyphs even if this one is skipped.
  635. if (curcolori < endcolori && codepoints.colors[curcolori + 1].index == i)
  636. {
  637. curcolor = codepoints.colors[curcolori + 1].color;
  638. curcolori++;
  639. addcurcolor = true;
  640. }
  641. // Split text at newlines.
  642. if (c == '\n')
  643. {
  644. lines.push_back(wline);
  645. // Ignore the width of any trailing spaces, for individual lines.
  646. if (linewidths)
  647. linewidths->push_back(width - widthoftrailingspace);
  648. // Make sure the new line keeps any color that was set previously.
  649. addcurcolor = true;
  650. width = widthbeforelastspace = widthoftrailingspace = 0.0f;
  651. prevglyph = 0; // Reset kerning information.
  652. lastspaceindex = -1;
  653. wline.cps.clear();
  654. wline.colors.clear();
  655. i++;
  656. continue;
  657. }
  658. // Ignore carriage returns
  659. if (c == '\r')
  660. {
  661. i++;
  662. continue;
  663. }
  664. const Glyph &g = findGlyph(c);
  665. float charwidth = g.spacing + getKerning(prevglyph, c);
  666. float newwidth = width + charwidth;
  667. // Wrap the line if it exceeds the wrap limit. Don't wrap yet if we're
  668. // processing a newline character, though.
  669. if (c != ' ' && newwidth > wraplimit)
  670. {
  671. // If this is the first character in the line and it exceeds the
  672. // limit, skip it completely.
  673. if (wline.cps.empty())
  674. i++;
  675. else if (lastspaceindex != -1)
  676. {
  677. // 'Rewind' to the last seen space, if the line has one.
  678. // FIXME: This could be more efficient...
  679. while (!wline.cps.empty() && wline.cps.back() != ' ')
  680. wline.cps.pop_back();
  681. while (!wline.colors.empty() && wline.colors.back().index >= (int) wline.cps.size())
  682. wline.colors.pop_back();
  683. // Also 'rewind' to the color that the last character is using.
  684. for (int colori = curcolori; colori >= 0; colori--)
  685. {
  686. if (codepoints.colors[colori].index <= lastspaceindex)
  687. {
  688. curcolor = codepoints.colors[colori].color;
  689. curcolori = colori;
  690. break;
  691. }
  692. }
  693. // Ignore the width of trailing spaces in wrapped lines.
  694. width = widthbeforelastspace;
  695. i = lastspaceindex;
  696. i++; // Start the next line after the space.
  697. }
  698. lines.push_back(wline);
  699. if (linewidths)
  700. linewidths->push_back(width);
  701. addcurcolor = true;
  702. prevglyph = 0;
  703. width = widthbeforelastspace = widthoftrailingspace = 0.0f;
  704. wline.cps.clear();
  705. wline.colors.clear();
  706. lastspaceindex = -1;
  707. continue;
  708. }
  709. if (prevglyph != ' ' && c == ' ')
  710. widthbeforelastspace = width;
  711. width = newwidth;
  712. prevglyph = c;
  713. if (addcurcolor)
  714. {
  715. wline.colors.push_back({curcolor, (int) wline.cps.size()});
  716. addcurcolor = false;
  717. }
  718. wline.cps.push_back(c);
  719. // Keep track of the last seen space, so we can "rewind" to it when
  720. // wrapping.
  721. if (c == ' ')
  722. {
  723. lastspaceindex = i;
  724. widthoftrailingspace += charwidth;
  725. }
  726. else if (c != '\n')
  727. widthoftrailingspace = 0.0f;
  728. i++;
  729. }
  730. // Push the last line.
  731. if (!wline.cps.empty())
  732. {
  733. lines.push_back(wline);
  734. // Ignore the width of any trailing spaces, for individual lines.
  735. if (linewidths)
  736. linewidths->push_back(width - widthoftrailingspace);
  737. }
  738. }
  739. void Font::getWrap(const std::vector<ColoredString> &text, float wraplimit, std::vector<std::string> &lines, std::vector<int> *linewidths)
  740. {
  741. ColoredCodepoints cps;
  742. getCodepointsFromString(text, cps);
  743. std::vector<ColoredCodepoints> codepointlines;
  744. getWrap(cps, wraplimit, codepointlines, linewidths);
  745. std::string line;
  746. for (const ColoredCodepoints &codepoints : codepointlines)
  747. {
  748. line.clear();
  749. line.reserve(codepoints.cps.size());
  750. for (uint32 codepoint : codepoints.cps)
  751. {
  752. char character[5] = {'\0'};
  753. char *end = utf8::unchecked::append(codepoint, character);
  754. line.append(character, end - character);
  755. }
  756. lines.push_back(line);
  757. }
  758. }
  759. void Font::setLineHeight(float height)
  760. {
  761. lineHeight = height;
  762. }
  763. float Font::getLineHeight() const
  764. {
  765. return lineHeight;
  766. }
  767. void Font::setFilter(const Texture::Filter &f)
  768. {
  769. if (!Texture::validateFilter(f, false))
  770. throw love::Exception("Invalid texture filter.");
  771. filter = f;
  772. for (GLuint texture : textures)
  773. {
  774. gl.bindTexture(texture);
  775. gl.setTextureFilter(filter);
  776. }
  777. }
  778. const Texture::Filter &Font::getFilter()
  779. {
  780. return filter;
  781. }
  782. bool Font::loadVolatile()
  783. {
  784. createTexture();
  785. textureCacheID++;
  786. return true;
  787. }
  788. void Font::unloadVolatile()
  789. {
  790. // nuke everything from orbit
  791. glyphs.clear();
  792. for (GLuint texture : textures)
  793. gl.deleteTexture(texture);
  794. textures.clear();
  795. gl.updateTextureMemorySize(textureMemorySize, 0);
  796. textureMemorySize = 0;
  797. }
  798. int Font::getAscent() const
  799. {
  800. return rasterizers[0]->getAscent();
  801. }
  802. int Font::getDescent() const
  803. {
  804. return rasterizers[0]->getDescent();
  805. }
  806. float Font::getBaseline() const
  807. {
  808. // 1.25 is magic line height for true type fonts
  809. return (type == FONT_TRUETYPE) ? floorf(getHeight() / 1.25f + 0.5f) : 0.0f;
  810. }
  811. bool Font::hasGlyph(uint32 glyph) const
  812. {
  813. for (const StrongRef<love::font::Rasterizer> &r : rasterizers)
  814. {
  815. if (r->hasGlyph(glyph))
  816. return true;
  817. }
  818. return false;
  819. }
  820. bool Font::hasGlyphs(const std::string &text) const
  821. {
  822. if (text.size() == 0)
  823. return false;
  824. try
  825. {
  826. utf8::iterator<std::string::const_iterator> i(text.begin(), text.begin(), text.end());
  827. utf8::iterator<std::string::const_iterator> end(text.end(), text.begin(), text.end());
  828. while (i != end)
  829. {
  830. uint32 codepoint = *i++;
  831. if (!hasGlyph(codepoint))
  832. return false;
  833. }
  834. }
  835. catch (utf8::exception &e)
  836. {
  837. throw love::Exception("UTF-8 decoding error: %s", e.what());
  838. }
  839. return true;
  840. }
  841. void Font::setFallbacks(const std::vector<Font *> &fallbacks)
  842. {
  843. for (const Font *f : fallbacks)
  844. {
  845. if (f->type != this->type)
  846. throw love::Exception("Font fallbacks must be of the same font type.");
  847. }
  848. rasterizers.resize(1);
  849. // NOTE: this won't invalidate already-rasterized glyphs.
  850. for (const Font *f : fallbacks)
  851. rasterizers.push_back(f->rasterizers[0]);
  852. }
  853. uint32 Font::getTextureCacheID() const
  854. {
  855. return textureCacheID;
  856. }
  857. bool Font::getConstant(const char *in, AlignMode &out)
  858. {
  859. return alignModes.find(in, out);
  860. }
  861. bool Font::getConstant(AlignMode in, const char *&out)
  862. {
  863. return alignModes.find(in, out);
  864. }
  865. StringMap<Font::AlignMode, Font::ALIGN_MAX_ENUM>::Entry Font::alignModeEntries[] =
  866. {
  867. { "left", ALIGN_LEFT },
  868. { "right", ALIGN_RIGHT },
  869. { "center", ALIGN_CENTER },
  870. { "justify", ALIGN_JUSTIFY },
  871. };
  872. StringMap<Font::AlignMode, Font::ALIGN_MAX_ENUM> Font::alignModes(Font::alignModeEntries, sizeof(Font::alignModeEntries));
  873. } // opengl
  874. } // graphics
  875. } // love