Text.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /**
  2. * Copyright (c) 2006-2020 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 "Text.h"
  21. #include "Graphics.h"
  22. #include <algorithm>
  23. namespace love
  24. {
  25. namespace graphics
  26. {
  27. love::Type Text::type("Text", &Drawable::type);
  28. Text::Text(Font *font, const std::vector<Font::ColoredString> &text)
  29. : font(font)
  30. , vertexAttributes(Font::vertexFormat, 0)
  31. , vertexData(nullptr)
  32. , modifiedVertices()
  33. , vertOffset(0)
  34. , textureCacheID((uint32) -1)
  35. {
  36. set(text);
  37. }
  38. Text::~Text()
  39. {
  40. if (vertexData != nullptr)
  41. free(vertexData);
  42. }
  43. void Text::uploadVertices(const std::vector<Font::GlyphVertex> &vertices, size_t vertoffset)
  44. {
  45. size_t offset = vertoffset * sizeof(Font::GlyphVertex);
  46. size_t datasize = vertices.size() * sizeof(Font::GlyphVertex);
  47. // If we haven't created a VBO or the vertices are too big, make a new one.
  48. if (datasize > 0 && (!vertexBuffer || (offset + datasize) > vertexBuffer->getSize()))
  49. {
  50. // Make it bigger than necessary to reduce potential future allocations.
  51. size_t newsize = size_t((offset + datasize) * 1.5);
  52. if (vertexBuffer != nullptr)
  53. newsize = std::max(size_t(vertexBuffer->getSize() * 1.5), newsize);
  54. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  55. Buffer::Settings settings(Buffer::TYPEFLAG_VERTEX, BUFFERUSAGE_DYNAMIC);
  56. auto decl = Buffer::getCommonFormatDeclaration(Font::vertexFormat);
  57. Buffer *newbuffer = gfx->newBuffer(settings, decl, nullptr, newsize, 0);
  58. void *newdata = nullptr;
  59. if (vertexData != nullptr)
  60. newdata = realloc(vertexData, newsize);
  61. else
  62. newdata = malloc(newsize);
  63. if (newdata == nullptr)
  64. throw love::Exception("Out of memory.");
  65. else
  66. vertexData = (uint8 *) newdata;
  67. vertexBuffer = newbuffer;
  68. vertexBuffers.set(0, vertexBuffer, 0);
  69. }
  70. if (vertexData != nullptr && datasize > 0)
  71. {
  72. memcpy(vertexData + offset, &vertices[0], datasize);
  73. modifiedVertices.encapsulate(offset, datasize);
  74. }
  75. }
  76. void Text::regenerateVertices()
  77. {
  78. // If the font's texture cache was invalidated then we need to recreate the
  79. // text's vertices, since glyph texcoords might have changed.
  80. if (font->getTextureCacheID() != textureCacheID)
  81. {
  82. std::vector<TextData> textdata = textData;
  83. clear();
  84. for (const TextData &t : textdata)
  85. addTextData(t);
  86. textureCacheID = font->getTextureCacheID();
  87. }
  88. }
  89. void Text::addTextData(const TextData &t)
  90. {
  91. std::vector<Font::GlyphVertex> vertices;
  92. std::vector<Font::DrawCommand> newcommands;
  93. Font::TextInfo textinfo;
  94. Colorf constantcolor = Colorf(1.0f, 1.0f, 1.0f, 1.0f);
  95. // We only have formatted text if the align mode is valid.
  96. if (t.align == Font::ALIGN_MAX_ENUM)
  97. newcommands = font->generateVertices(t.codepoints, constantcolor, vertices, 0.0f, Vector2(0.0f, 0.0f), &textinfo);
  98. else
  99. newcommands = font->generateVerticesFormatted(t.codepoints, constantcolor, t.wrap, t.align, vertices, &textinfo);
  100. size_t voffset = vertOffset;
  101. // Must be before the early exit below.
  102. if (!t.appendVertices)
  103. {
  104. voffset = 0;
  105. vertOffset = 0;
  106. drawCommands.clear();
  107. textData.clear();
  108. }
  109. if (vertices.empty())
  110. return;
  111. if (t.useMatrix)
  112. t.matrix.transformXY(&vertices[0], &vertices[0], (int) vertices.size());
  113. uploadVertices(vertices, voffset);
  114. if (!newcommands.empty())
  115. {
  116. // The start vertex should be adjusted to account for the vertex offset.
  117. for (Font::DrawCommand &cmd : newcommands)
  118. cmd.startvertex += (int) voffset;
  119. auto firstcmd = newcommands.begin();
  120. // If the first draw command in the new list has the same texture as the
  121. // last one in the existing list we're building and its vertices are
  122. // in-order, we can combine them (saving a draw call.)
  123. if (!drawCommands.empty())
  124. {
  125. auto prevcmd = drawCommands.back();
  126. if (prevcmd.texture == firstcmd->texture && (prevcmd.startvertex + prevcmd.vertexcount) == firstcmd->startvertex)
  127. {
  128. drawCommands.back().vertexcount += firstcmd->vertexcount;
  129. ++firstcmd;
  130. }
  131. }
  132. // Append the new draw commands to the list we're building.
  133. drawCommands.insert(drawCommands.end(), firstcmd, newcommands.end());
  134. }
  135. vertOffset = voffset + vertices.size();
  136. textData.push_back(t);
  137. textData.back().textInfo = textinfo;
  138. // Font::generateVertices can invalidate the font's texture cache.
  139. if (font->getTextureCacheID() != textureCacheID)
  140. regenerateVertices();
  141. }
  142. void Text::set(const std::vector<Font::ColoredString> &text)
  143. {
  144. return set(text, -1.0f, Font::ALIGN_MAX_ENUM);
  145. }
  146. void Text::set(const std::vector<Font::ColoredString> &text, float wrap, Font::AlignMode align)
  147. {
  148. if (text.empty() || (text.size() == 1 && text[0].str.empty()))
  149. return clear();
  150. Font::ColoredCodepoints codepoints;
  151. Font::getCodepointsFromString(text, codepoints);
  152. addTextData({codepoints, wrap, align, {}, false, false, Matrix4()});
  153. }
  154. int Text::add(const std::vector<Font::ColoredString> &text, const Matrix4 &m)
  155. {
  156. return addf(text, -1.0f, Font::ALIGN_MAX_ENUM, m);
  157. }
  158. int Text::addf(const std::vector<Font::ColoredString> &text, float wrap, Font::AlignMode align, const Matrix4 &m)
  159. {
  160. Font::ColoredCodepoints codepoints;
  161. Font::getCodepointsFromString(text, codepoints);
  162. addTextData({codepoints, wrap, align, {}, true, true, m});
  163. return (int) textData.size() - 1;
  164. }
  165. void Text::clear()
  166. {
  167. textData.clear();
  168. drawCommands.clear();
  169. textureCacheID = font->getTextureCacheID();
  170. vertOffset = 0;
  171. }
  172. void Text::setFont(Font *f)
  173. {
  174. font.set(f);
  175. // Invalidate the texture cache ID since the font is different. We also have
  176. // to re-upload all the vertices based on the new font's textures.
  177. textureCacheID = (uint32) -1;
  178. regenerateVertices();
  179. }
  180. Font *Text::getFont() const
  181. {
  182. return font.get();
  183. }
  184. int Text::getWidth(int index) const
  185. {
  186. if (index < 0)
  187. index = std::max((int) textData.size() - 1, 0);
  188. if (index >= (int) textData.size())
  189. return 0;
  190. return textData[index].textInfo.width;
  191. }
  192. int Text::getHeight(int index) const
  193. {
  194. if (index < 0)
  195. index = std::max((int) textData.size() - 1, 0);
  196. if (index >= (int) textData.size())
  197. return 0;
  198. return textData[index].textInfo.height;
  199. }
  200. void Text::draw(Graphics *gfx, const Matrix4 &m)
  201. {
  202. if (vertexBuffer == nullptr || vertexData == nullptr || drawCommands.empty())
  203. return;
  204. gfx->flushBatchedDraws();
  205. if (Shader::isDefaultActive())
  206. Shader::attachDefault(Shader::STANDARD_DEFAULT);
  207. if (Shader::current)
  208. Shader::current->checkMainTextureType(TEXTURE_2D, false);
  209. // Re-generate the text if the Font's texture cache was invalidated.
  210. if (font->getTextureCacheID() != textureCacheID)
  211. regenerateVertices();
  212. int totalverts = 0;
  213. for (const Font::DrawCommand &cmd : drawCommands)
  214. totalverts = std::max(cmd.startvertex + cmd.vertexcount, totalverts);
  215. // Make sure all pending data is uploaded to the GPU.
  216. if (modifiedVertices.isValid())
  217. {
  218. size_t offset = modifiedVertices.getOffset();
  219. size_t size = modifiedVertices.getSize();
  220. if (vertexBuffer->getUsage() == BUFFERUSAGE_STREAM)
  221. vertexBuffer->fill(0, vertexBuffer->getSize(), vertexData);
  222. else
  223. vertexBuffer->fill(offset, size, vertexData + offset);
  224. modifiedVertices.invalidate();
  225. }
  226. Graphics::TempTransform transform(gfx, m);
  227. for (const Font::DrawCommand &cmd : drawCommands)
  228. gfx->drawQuads(cmd.startvertex / 4, cmd.vertexcount / 4, vertexAttributes, vertexBuffers, cmd.texture);
  229. }
  230. } // graphics
  231. } // love