SpriteBatch.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 "common/config.h"
  21. #include "SpriteBatch.h"
  22. // LOVE
  23. #include "Texture.h"
  24. #include "Quad.h"
  25. #include "Graphics.h"
  26. #include "Buffer.h"
  27. // C++
  28. #include <algorithm>
  29. // C
  30. #include <stddef.h>
  31. namespace love
  32. {
  33. namespace graphics
  34. {
  35. love::Type SpriteBatch::type("SpriteBatch", &Drawable::type);
  36. SpriteBatch::SpriteBatch(Graphics *gfx, Texture *texture, int size, vertex::Usage usage)
  37. : texture(texture)
  38. , size(size)
  39. , next(0)
  40. , color(255, 255, 255, 255)
  41. , colorf(1.0f, 1.0f, 1.0f, 1.0f)
  42. , array_buf(nullptr)
  43. , range_start(-1)
  44. , range_count(-1)
  45. {
  46. if (size <= 0)
  47. throw love::Exception("Invalid SpriteBatch size.");
  48. if (texture == nullptr)
  49. throw love::Exception("A texture must be used when creating a SpriteBatch.");
  50. if (texture->getTextureType() == TEXTURE_2D_ARRAY)
  51. vertex_format = vertex::CommonFormat::XYf_STPf_RGBAub;
  52. else
  53. vertex_format = vertex::CommonFormat::XYf_STf_RGBAub;
  54. vertex_stride = vertex::getFormatStride(vertex_format);
  55. size_t vertex_size = vertex_stride * 4 * size;
  56. array_buf = gfx->newBuffer(vertex_size, nullptr, BUFFER_VERTEX, usage, Buffer::MAP_EXPLICIT_RANGE_MODIFY);
  57. }
  58. SpriteBatch::~SpriteBatch()
  59. {
  60. delete array_buf;
  61. }
  62. int SpriteBatch::add(const Matrix4 &m, int index /*= -1*/)
  63. {
  64. return add(texture->getQuad(), m, index);
  65. }
  66. int SpriteBatch::add(Quad *quad, const Matrix4 &m, int index /*= -1*/)
  67. {
  68. using namespace vertex;
  69. if (vertex_format == CommonFormat::XYf_STPf_RGBAub)
  70. return addLayer(quad->getLayer(), quad, m, index);
  71. if (index < -1 || index >= size)
  72. throw love::Exception("Invalid sprite index: %d", index + 1);
  73. if (index == -1 && next >= size)
  74. setBufferSize(size * 2);
  75. const Vector2 *quadpositions = quad->getVertexPositions();
  76. const Vector2 *quadtexcoords = quad->getVertexTexCoords();
  77. // Always keep the buffer mapped when adding data (it'll be unmapped on draw.)
  78. size_t offset = (index == -1 ? next : index) * vertex_stride * 4;
  79. auto verts = (XYf_STf_RGBAub *) ((uint8 *) array_buf->map() + offset);
  80. m.transformXY(verts, quadpositions, 4);
  81. for (int i = 0; i < 4; i++)
  82. {
  83. verts[i].s = quadtexcoords[i].x;
  84. verts[i].t = quadtexcoords[i].y;
  85. verts[i].color = color;
  86. }
  87. array_buf->setMappedRangeModified(offset, vertex_stride * 4);
  88. // Increment counter.
  89. if (index == -1)
  90. return next++;
  91. return index;
  92. }
  93. int SpriteBatch::addLayer(int layer, const Matrix4 &m, int index)
  94. {
  95. return addLayer(layer, texture->getQuad(), m, index);
  96. }
  97. int SpriteBatch::addLayer(int layer, Quad *quad, const Matrix4 &m, int index)
  98. {
  99. using namespace vertex;
  100. if (vertex_format != CommonFormat::XYf_STPf_RGBAub)
  101. throw love::Exception("addLayer can only be called on a SpriteBatch that uses an Array Texture!");
  102. if (index < -1 || index >= size)
  103. throw love::Exception("Invalid sprite index: %d", index + 1);
  104. if (layer < 0 || layer >= texture->getLayerCount())
  105. throw love::Exception("Invalid layer: %d (Texture has %d layers)", layer + 1, texture->getLayerCount());
  106. if (index == -1 && next >= size)
  107. setBufferSize(size * 2);
  108. const Vector2 *quadpositions = quad->getVertexPositions();
  109. const Vector2 *quadtexcoords = quad->getVertexTexCoords();
  110. // Always keep the buffer mapped when adding data (it'll be unmapped on draw.)
  111. size_t offset = (index == -1 ? next : index) * vertex_stride * 4;
  112. auto verts = (XYf_STPf_RGBAub *) ((uint8 *) array_buf->map() + offset);
  113. m.transformXY(verts, quadpositions, 4);
  114. for (int i = 0; i < 4; i++)
  115. {
  116. verts[i].s = quadtexcoords[i].x;
  117. verts[i].t = quadtexcoords[i].y;
  118. verts[i].p = (float) layer;
  119. verts[i].color = color;
  120. }
  121. array_buf->setMappedRangeModified(offset, vertex_stride * 4);
  122. // Increment counter.
  123. if (index == -1)
  124. return next++;
  125. return index;
  126. }
  127. void SpriteBatch::clear()
  128. {
  129. // Reset the position of the next index.
  130. next = 0;
  131. }
  132. void SpriteBatch::flush()
  133. {
  134. array_buf->unmap();
  135. }
  136. void SpriteBatch::setTexture(Texture *newtexture)
  137. {
  138. if (texture->getTextureType() != newtexture->getTextureType())
  139. throw love::Exception("Texture must have the same type as the SpriteBatch's previous texture.");
  140. texture.set(newtexture);
  141. }
  142. Texture *SpriteBatch::getTexture() const
  143. {
  144. return texture.get();
  145. }
  146. void SpriteBatch::setColor(const Colorf &c)
  147. {
  148. colorf.r = std::min(std::max(c.r, 0.0f), 1.0f);
  149. colorf.g = std::min(std::max(c.g, 0.0f), 1.0f);
  150. colorf.b = std::min(std::max(c.b, 0.0f), 1.0f);
  151. colorf.a = std::min(std::max(c.a, 0.0f), 1.0f);
  152. color = toColor32(colorf);
  153. }
  154. Colorf SpriteBatch::getColor() const
  155. {
  156. return colorf;
  157. }
  158. int SpriteBatch::getCount() const
  159. {
  160. return next;
  161. }
  162. void SpriteBatch::setBufferSize(int newsize)
  163. {
  164. if (newsize <= 0)
  165. throw love::Exception("Invalid SpriteBatch size.");
  166. if (newsize == size)
  167. return;
  168. size_t vertex_size = vertex_stride * 4 * newsize;
  169. love::graphics::Buffer *new_array_buf = nullptr;
  170. int new_next = std::min(next, newsize);
  171. try
  172. {
  173. auto gfx = Module::getInstance<graphics::Graphics>(Module::M_GRAPHICS);
  174. new_array_buf = gfx->newBuffer(vertex_size, nullptr, array_buf->getType(), array_buf->getUsage(), array_buf->getMapFlags());
  175. // Copy as much of the old data into the new GLBuffer as can fit.
  176. size_t copy_size = vertex_stride * 4 * new_next;
  177. array_buf->copyTo(0, copy_size, new_array_buf, 0);
  178. }
  179. catch (love::Exception &)
  180. {
  181. delete new_array_buf;
  182. throw;
  183. }
  184. // We don't need to unmap the old GLBuffer since we're deleting it.
  185. delete array_buf;
  186. array_buf = new_array_buf;
  187. size = newsize;
  188. next = new_next;
  189. }
  190. int SpriteBatch::getBufferSize() const
  191. {
  192. return size;
  193. }
  194. void SpriteBatch::attachAttribute(const std::string &name, Mesh *mesh)
  195. {
  196. AttachedAttribute oldattrib = {};
  197. AttachedAttribute newattrib = {};
  198. if (mesh->getVertexCount() < (size_t) next * 4)
  199. throw love::Exception("Mesh has too few vertices to be attached to this SpriteBatch (at least %d vertices are required)", next*4);
  200. auto it = attached_attributes.find(name);
  201. if (it != attached_attributes.end())
  202. oldattrib = it->second;
  203. newattrib.index = mesh->getAttributeIndex(name);
  204. if (newattrib.index < 0)
  205. throw love::Exception("The specified mesh does not have a vertex attribute named '%s'", name.c_str());
  206. newattrib.mesh = mesh;
  207. attached_attributes[name] = newattrib;
  208. }
  209. void SpriteBatch::setDrawRange(int start, int count)
  210. {
  211. if (start < 0 || count <= 0)
  212. throw love::Exception("Invalid draw range.");
  213. range_start = start;
  214. range_count = count;
  215. }
  216. void SpriteBatch::setDrawRange()
  217. {
  218. range_start = range_count = -1;
  219. }
  220. bool SpriteBatch::getDrawRange(int &start, int &count) const
  221. {
  222. if (range_start < 0 || range_count <= 0)
  223. return false;
  224. start = range_start;
  225. count = range_count;
  226. return true;
  227. }
  228. void SpriteBatch::draw(Graphics *gfx, const Matrix4 &m)
  229. {
  230. using namespace vertex;
  231. if (next == 0)
  232. return;
  233. gfx->flushStreamDraws();
  234. if (texture.get())
  235. {
  236. if (Shader::isDefaultActive())
  237. {
  238. Shader::StandardShader defaultshader = Shader::STANDARD_DEFAULT;
  239. if (texture->getTextureType() == TEXTURE_2D_ARRAY)
  240. defaultshader = Shader::STANDARD_ARRAY;
  241. Shader::attachDefault(defaultshader);
  242. }
  243. if (Shader::current)
  244. Shader::current->checkMainTexture(texture);
  245. }
  246. // Make sure the buffer isn't mapped when we draw (sends data to GPU if needed.)
  247. array_buf->unmap();
  248. Attributes attributes;
  249. BufferBindings buffers;
  250. {
  251. buffers.set(0, array_buf, 0);
  252. attributes.setCommonFormat(vertex_format, 0);
  253. }
  254. int activebuffers = 1;
  255. for (const auto &it : attached_attributes)
  256. {
  257. Mesh *mesh = it.second.mesh.get();
  258. // We have to do this check here as wll because setBufferSize can be
  259. // called after attachAttribute.
  260. if (mesh->getVertexCount() < (size_t) next * 4)
  261. throw love::Exception("Mesh with attribute '%s' attached to this SpriteBatch has too few vertices", it.first.c_str());
  262. int attributeindex = -1;
  263. // If the attribute is one of the LOVE-defined ones, use the constant
  264. // attribute index for it, otherwise query the index from the shader.
  265. BuiltinVertexAttribute builtinattrib;
  266. if (vertex::getConstant(it.first.c_str(), builtinattrib))
  267. attributeindex = (int) builtinattrib;
  268. else if (Shader::current)
  269. attributeindex = Shader::current->getVertexAttributeIndex(it.first);
  270. if (attributeindex >= 0)
  271. {
  272. // Make sure the buffer isn't mapped (sends data to GPU if needed.)
  273. mesh->vertexBuffer->unmap();
  274. const auto &formats = mesh->getVertexFormat();
  275. const auto &format = formats[it.second.index];
  276. uint16 offset = (uint16) mesh->getAttributeOffset(it.second.index);
  277. uint16 stride = (uint16) mesh->getVertexStride();
  278. attributes.set(attributeindex, format.type, (uint8) format.components, offset, activebuffers);
  279. attributes.setBufferLayout(activebuffers, stride);
  280. // TODO: We should reuse buffer bindings with the same buffer+stride+step.
  281. buffers.set(activebuffers, mesh->vertexBuffer, 0);
  282. activebuffers++;
  283. }
  284. }
  285. Graphics::TempTransform transform(gfx, m);
  286. int start = std::min(std::max(0, range_start), next - 1);
  287. int count = next;
  288. if (range_count > 0)
  289. count = std::min(count, range_count);
  290. count = std::min(count, next - start);
  291. if (count > 0)
  292. gfx->drawQuads(start, count, attributes, buffers, texture);
  293. }
  294. } // graphics
  295. } // love