Canvas.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 "Canvas.h"
  21. #include "graphics/Graphics.h"
  22. #include "Graphics.h"
  23. #include <algorithm> // For min/max
  24. namespace love
  25. {
  26. namespace graphics
  27. {
  28. namespace opengl
  29. {
  30. static GLenum createFBO(GLuint &framebuffer, TextureType texType, PixelFormat format, GLuint texture, int layers)
  31. {
  32. // get currently bound fbo to reset to it later
  33. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  34. glGenFramebuffers(1, &framebuffer);
  35. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, framebuffer);
  36. if (texture != 0)
  37. {
  38. if (isPixelFormatDepthStencil(format) && (GLAD_ES_VERSION_3_0 || !GLAD_ES_VERSION_2_0))
  39. {
  40. // glDrawBuffers is an ext in GL2. glDrawBuffer doesn't exist in ES3.
  41. GLenum none = GL_NONE;
  42. if (GLAD_ES_VERSION_3_0)
  43. glDrawBuffers(1, &none);
  44. else
  45. glDrawBuffer(GL_NONE);
  46. glReadBuffer(GL_NONE);
  47. }
  48. bool unusedSRGB = false;
  49. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(format, false, unusedSRGB);
  50. int faces = texType == TEXTURE_CUBE ? 6 : 1;
  51. // Make sure all faces and layers of the texture are initialized to
  52. // transparent black. This is unfortunately probably pretty slow for
  53. // 2D-array and 3D textures with a lot of layers...
  54. for (int layer = layers - 1; layer >= 0; layer--)
  55. {
  56. for (int face = faces - 1; face >= 0; face--)
  57. {
  58. for (GLenum attachment : fmt.framebufferAttachments)
  59. {
  60. if (attachment == GL_NONE)
  61. continue;
  62. gl.framebufferTexture(attachment, texType, texture, 0, layer, face);
  63. }
  64. if (isPixelFormatDepthStencil(format))
  65. {
  66. bool hadDepthWrites = gl.hasDepthWrites();
  67. if (!hadDepthWrites) // glDepthMask also affects glClear.
  68. gl.setDepthWrites(true);
  69. gl.clearDepth(1.0);
  70. glClearStencil(0);
  71. glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  72. if (!hadDepthWrites)
  73. gl.setDepthWrites(hadDepthWrites);
  74. }
  75. else
  76. {
  77. glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  78. glClear(GL_COLOR_BUFFER_BIT);
  79. }
  80. }
  81. }
  82. }
  83. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  84. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  85. return status;
  86. }
  87. static bool createRenderbuffer(int width, int height, int &samples, PixelFormat pixelformat, GLuint &buffer)
  88. {
  89. int reqsamples = samples;
  90. bool unusedSRGB = false;
  91. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(pixelformat, true, unusedSRGB);
  92. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  93. // Temporary FBO used to clear the renderbuffer.
  94. GLuint fbo = 0;
  95. glGenFramebuffers(1, &fbo);
  96. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  97. if (isPixelFormatDepthStencil(pixelformat) && (GLAD_ES_VERSION_3_0 || !GLAD_ES_VERSION_2_0))
  98. {
  99. // glDrawBuffers is an ext in GL2. glDrawBuffer doesn't exist in ES3.
  100. GLenum none = GL_NONE;
  101. if (GLAD_ES_VERSION_3_0)
  102. glDrawBuffers(1, &none);
  103. else
  104. glDrawBuffer(GL_NONE);
  105. glReadBuffer(GL_NONE);
  106. }
  107. glGenRenderbuffers(1, &buffer);
  108. glBindRenderbuffer(GL_RENDERBUFFER, buffer);
  109. if (samples > 1)
  110. glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, fmt.internalformat, width, height);
  111. else
  112. glRenderbufferStorage(GL_RENDERBUFFER, fmt.internalformat, width, height);
  113. for (GLenum attachment : fmt.framebufferAttachments)
  114. {
  115. if (attachment != GL_NONE)
  116. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, buffer);
  117. }
  118. if (samples > 1)
  119. glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
  120. else
  121. samples = 0;
  122. glBindRenderbuffer(GL_RENDERBUFFER, 0);
  123. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  124. if (status == GL_FRAMEBUFFER_COMPLETE && (reqsamples <= 1 || samples > 1))
  125. {
  126. if (isPixelFormatDepthStencil(pixelformat))
  127. {
  128. bool hadDepthWrites = gl.hasDepthWrites();
  129. if (!hadDepthWrites) // glDepthMask also affects glClear.
  130. gl.setDepthWrites(true);
  131. gl.clearDepth(1.0);
  132. glClearStencil(0);
  133. glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  134. if (!hadDepthWrites)
  135. gl.setDepthWrites(hadDepthWrites);
  136. }
  137. else
  138. {
  139. // Initialize the buffer to transparent black.
  140. glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  141. glClear(GL_COLOR_BUFFER_BIT);
  142. }
  143. }
  144. else
  145. {
  146. glDeleteRenderbuffers(1, &buffer);
  147. buffer = 0;
  148. samples = 0;
  149. }
  150. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  151. gl.deleteFramebuffer(fbo);
  152. return status == GL_FRAMEBUFFER_COMPLETE;
  153. }
  154. Canvas::Canvas(const Settings &settings)
  155. : love::graphics::Canvas(settings)
  156. , fbo(0)
  157. , texture(0)
  158. , renderbuffer(0)
  159. , actualSamples(0)
  160. {
  161. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  162. if (gfx != nullptr)
  163. format = gfx->getSizedFormat(format, renderTarget, readable, sRGB);
  164. initQuad();
  165. loadVolatile();
  166. if (status != GL_FRAMEBUFFER_COMPLETE)
  167. throw love::Exception("Cannot create Canvas: %s", OpenGL::framebufferStatusString(status));
  168. }
  169. Canvas::~Canvas()
  170. {
  171. unloadVolatile();
  172. }
  173. bool Canvas::loadVolatile()
  174. {
  175. if (texture != 0)
  176. return true;
  177. OpenGL::TempDebugGroup debuggroup("Canvas load");
  178. fbo = texture = 0;
  179. renderbuffer = 0;
  180. status = GL_FRAMEBUFFER_COMPLETE;
  181. // getMaxRenderbufferSamples will be 0 on systems that don't support
  182. // multisampled renderbuffers / don't export FBO multisample extensions.
  183. actualSamples = std::min(getRequestedMSAA(), gl.getMaxRenderbufferSamples());
  184. actualSamples = std::max(actualSamples, 0);
  185. actualSamples = actualSamples == 1 ? 0 : actualSamples;
  186. if (isReadable())
  187. {
  188. glGenTextures(1, &texture);
  189. gl.bindTextureToUnit(this, 0, false);
  190. GLenum gltype = OpenGL::getGLTextureType(texType);
  191. if (GLAD_ANGLE_texture_usage)
  192. glTexParameteri(gltype, GL_TEXTURE_USAGE_ANGLE, GL_FRAMEBUFFER_ATTACHMENT_ANGLE);
  193. setSamplerState(samplerState);
  194. while (glGetError() != GL_NO_ERROR)
  195. /* Clear the error buffer. */;
  196. bool isSRGB = format == PIXELFORMAT_sRGBA8_UNORM;
  197. if (!gl.rawTexStorage(texType, mipmapCount, format, isSRGB, pixelWidth, pixelHeight, texType == TEXTURE_VOLUME ? depth : layers))
  198. {
  199. status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
  200. return false;
  201. }
  202. if (glGetError() != GL_NO_ERROR)
  203. {
  204. gl.deleteTexture(texture);
  205. texture = 0;
  206. status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
  207. return false;
  208. }
  209. // Create a local FBO used for glReadPixels as well as MSAA blitting.
  210. status = createFBO(fbo, texType, format, texture, texType == TEXTURE_VOLUME ? depth : layers);
  211. if (status != GL_FRAMEBUFFER_COMPLETE)
  212. {
  213. if (fbo != 0)
  214. {
  215. gl.deleteFramebuffer(fbo);
  216. fbo = 0;
  217. }
  218. return false;
  219. }
  220. }
  221. if (!isReadable() || actualSamples > 0)
  222. createRenderbuffer(pixelWidth, pixelHeight, actualSamples, format, renderbuffer);
  223. int64 memsize = getPixelFormatSize(format) * pixelWidth * pixelHeight;
  224. if (getMipmapCount() > 1)
  225. memsize *= 1.33334;
  226. if (actualSamples > 1 && isReadable())
  227. memsize += getPixelFormatSize(format) * pixelWidth * pixelHeight * actualSamples;
  228. else if (actualSamples > 1)
  229. memsize *= actualSamples;
  230. setGraphicsMemorySize(memsize);
  231. if (getMipmapCount() > 1)
  232. generateMipmaps();
  233. return true;
  234. }
  235. void Canvas::unloadVolatile()
  236. {
  237. if (fbo != 0 || renderbuffer != 0 || texture != 0)
  238. {
  239. // This is a bit ugly, but we need some way to destroy the cached FBO
  240. // when this Canvas' texture is destroyed.
  241. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  242. if (gfx != nullptr)
  243. gfx->cleanupCanvas(this);
  244. }
  245. if (fbo != 0)
  246. gl.deleteFramebuffer(fbo);
  247. if (renderbuffer != 0)
  248. glDeleteRenderbuffers(1, &renderbuffer);
  249. if (texture != 0)
  250. gl.deleteTexture(texture);
  251. fbo = 0;
  252. renderbuffer = 0;
  253. texture = 0;
  254. setGraphicsMemorySize(0);
  255. }
  256. void Canvas::setSamplerState(const SamplerState &s)
  257. {
  258. Texture::setSamplerState(s);
  259. if (samplerState.depthSampleMode.hasValue && !gl.isDepthCompareSampleSupported())
  260. throw love::Exception("Depth comparison sampling in shaders is not supported on this system.");
  261. if (!OpenGL::hasTextureFilteringSupport(getPixelFormat()))
  262. {
  263. samplerState.magFilter = samplerState.minFilter = SamplerState::FILTER_NEAREST;
  264. if (samplerState.mipmapFilter == SamplerState::MIPMAP_FILTER_LINEAR)
  265. samplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_NEAREST;
  266. }
  267. // If we only have limited NPOT support then the wrap mode must be CLAMP.
  268. if ((GLAD_ES_VERSION_2_0 && !(GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot))
  269. && (pixelWidth != nextP2(pixelWidth) || pixelHeight != nextP2(pixelHeight) || depth != nextP2(depth)))
  270. {
  271. samplerState.wrapU = samplerState.wrapV = samplerState.wrapW = SamplerState::WRAP_CLAMP;
  272. }
  273. gl.bindTextureToUnit(this, 0, false);
  274. gl.setSamplerState(texType, samplerState);
  275. }
  276. ptrdiff_t Canvas::getHandle() const
  277. {
  278. return texture;
  279. }
  280. love::image::ImageData *Canvas::newImageData(love::image::Image *module, int slice, int mipmap, const Rect &r)
  281. {
  282. love::image::ImageData *data = love::graphics::Canvas::newImageData(module, slice, mipmap, r);
  283. bool isSRGB = false;
  284. OpenGL::TextureFormat fmt = gl.convertPixelFormat(data->getFormat(), false, isSRGB);
  285. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  286. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getFBO());
  287. if (slice > 0 || mipmap > 0)
  288. {
  289. int layer = texType == TEXTURE_CUBE ? 0 : slice;
  290. int face = texType == TEXTURE_CUBE ? slice : 0;
  291. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, mipmap, layer, face);
  292. }
  293. glReadPixels(r.x, r.y, r.w, r.h, fmt.externalformat, fmt.type, data->getData());
  294. if (slice > 0 || mipmap > 0)
  295. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, 0, 0, 0);
  296. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  297. return data;
  298. }
  299. void Canvas::generateMipmaps()
  300. {
  301. if (getMipmapCount() == 1 || getMipmapsMode() == MIPMAPS_NONE)
  302. throw love::Exception("generateMipmaps can only be called on a Texture which was created with mipmaps enabled.");
  303. if (isPixelFormatCompressed(format))
  304. throw love::Exception("generateMipmaps cannot be called on a compressed Texture.");
  305. gl.bindTextureToUnit(this, 0, false);
  306. GLenum gltextype = OpenGL::getGLTextureType(texType);
  307. if (gl.bugs.generateMipmapsRequiresTexture2DEnable)
  308. glEnable(gltextype);
  309. glGenerateMipmap(gltextype);
  310. }
  311. } // opengl
  312. } // graphics
  313. } // love