Canvas.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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::Texture(settings, nullptr)
  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. loadVolatile();
  165. if (status != GL_FRAMEBUFFER_COMPLETE)
  166. throw love::Exception("Cannot create Canvas: %s", OpenGL::framebufferStatusString(status));
  167. }
  168. Canvas::~Canvas()
  169. {
  170. unloadVolatile();
  171. }
  172. bool Canvas::loadVolatile()
  173. {
  174. if (texture != 0)
  175. return true;
  176. OpenGL::TempDebugGroup debuggroup("Canvas load");
  177. fbo = texture = 0;
  178. renderbuffer = 0;
  179. status = GL_FRAMEBUFFER_COMPLETE;
  180. // getMaxRenderbufferSamples will be 0 on systems that don't support
  181. // multisampled renderbuffers / don't export FBO multisample extensions.
  182. actualSamples = std::min(getRequestedMSAA(), gl.getMaxRenderbufferSamples());
  183. actualSamples = std::max(actualSamples, 0);
  184. actualSamples = actualSamples == 1 ? 0 : actualSamples;
  185. if (isReadable())
  186. {
  187. glGenTextures(1, &texture);
  188. gl.bindTextureToUnit(this, 0, false);
  189. GLenum gltype = OpenGL::getGLTextureType(texType);
  190. if (GLAD_ANGLE_texture_usage)
  191. glTexParameteri(gltype, GL_TEXTURE_USAGE_ANGLE, GL_FRAMEBUFFER_ATTACHMENT_ANGLE);
  192. setSamplerState(samplerState);
  193. while (glGetError() != GL_NO_ERROR)
  194. /* Clear the error buffer. */;
  195. bool isSRGB = format == PIXELFORMAT_sRGBA8_UNORM;
  196. if (!gl.rawTexStorage(texType, mipmapCount, format, isSRGB, pixelWidth, pixelHeight, texType == TEXTURE_VOLUME ? depth : layers))
  197. {
  198. status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
  199. return false;
  200. }
  201. if (glGetError() != GL_NO_ERROR)
  202. {
  203. gl.deleteTexture(texture);
  204. texture = 0;
  205. status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
  206. return false;
  207. }
  208. // Create a local FBO used for glReadPixels as well as MSAA blitting.
  209. status = createFBO(fbo, texType, format, texture, texType == TEXTURE_VOLUME ? depth : layers);
  210. if (status != GL_FRAMEBUFFER_COMPLETE)
  211. {
  212. if (fbo != 0)
  213. {
  214. gl.deleteFramebuffer(fbo);
  215. fbo = 0;
  216. }
  217. return false;
  218. }
  219. }
  220. if (!isReadable() || actualSamples > 0)
  221. createRenderbuffer(pixelWidth, pixelHeight, actualSamples, format, renderbuffer);
  222. int64 memsize = getPixelFormatSize(format) * pixelWidth * pixelHeight;
  223. if (getMipmapCount() > 1)
  224. memsize *= 1.33334;
  225. if (actualSamples > 1 && isReadable())
  226. memsize += getPixelFormatSize(format) * pixelWidth * pixelHeight * actualSamples;
  227. else if (actualSamples > 1)
  228. memsize *= actualSamples;
  229. setGraphicsMemorySize(memsize);
  230. if (getMipmapCount() > 1)
  231. generateMipmaps();
  232. return true;
  233. }
  234. void Canvas::unloadVolatile()
  235. {
  236. if (isRenderTarget() && (fbo != 0 || renderbuffer != 0 || texture != 0))
  237. {
  238. // This is a bit ugly, but we need some way to destroy the cached FBO
  239. // when this Canvas' texture is destroyed.
  240. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  241. if (gfx != nullptr)
  242. gfx->cleanupRenderTexture(this);
  243. }
  244. if (fbo != 0)
  245. gl.deleteFramebuffer(fbo);
  246. if (renderbuffer != 0)
  247. glDeleteRenderbuffers(1, &renderbuffer);
  248. if (texture != 0)
  249. gl.deleteTexture(texture);
  250. fbo = 0;
  251. renderbuffer = 0;
  252. texture = 0;
  253. setGraphicsMemorySize(0);
  254. }
  255. void Canvas::setSamplerState(const SamplerState &s)
  256. {
  257. Texture::setSamplerState(s);
  258. if (samplerState.depthSampleMode.hasValue && !gl.isDepthCompareSampleSupported())
  259. throw love::Exception("Depth comparison sampling in shaders is not supported on this system.");
  260. if (!OpenGL::hasTextureFilteringSupport(getPixelFormat()))
  261. {
  262. samplerState.magFilter = samplerState.minFilter = SamplerState::FILTER_NEAREST;
  263. if (samplerState.mipmapFilter == SamplerState::MIPMAP_FILTER_LINEAR)
  264. samplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_NEAREST;
  265. }
  266. // If we only have limited NPOT support then the wrap mode must be CLAMP.
  267. if ((GLAD_ES_VERSION_2_0 && !(GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot))
  268. && (pixelWidth != nextP2(pixelWidth) || pixelHeight != nextP2(pixelHeight) || depth != nextP2(depth)))
  269. {
  270. samplerState.wrapU = samplerState.wrapV = samplerState.wrapW = SamplerState::WRAP_CLAMP;
  271. }
  272. gl.bindTextureToUnit(this, 0, false);
  273. gl.setSamplerState(texType, samplerState);
  274. }
  275. ptrdiff_t Canvas::getHandle() const
  276. {
  277. return texture;
  278. }
  279. love::image::ImageData *Canvas::newImageData(love::image::Image *module, int slice, int mipmap, const Rect &r)
  280. {
  281. love::image::ImageData *data = love::graphics::Texture::newImageData(module, slice, mipmap, r);
  282. bool isSRGB = false;
  283. OpenGL::TextureFormat fmt = gl.convertPixelFormat(data->getFormat(), false, isSRGB);
  284. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  285. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getFBO());
  286. if (slice > 0 || mipmap > 0)
  287. {
  288. int layer = texType == TEXTURE_CUBE ? 0 : slice;
  289. int face = texType == TEXTURE_CUBE ? slice : 0;
  290. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, mipmap, layer, face);
  291. }
  292. glReadPixels(r.x, r.y, r.w, r.h, fmt.externalformat, fmt.type, data->getData());
  293. if (slice > 0 || mipmap > 0)
  294. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, 0, 0, 0);
  295. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  296. return data;
  297. }
  298. void Canvas::generateMipmaps()
  299. {
  300. if (getMipmapCount() == 1 || getMipmapsMode() == MIPMAPS_NONE)
  301. throw love::Exception("generateMipmaps can only be called on a Texture which was created with mipmaps enabled.");
  302. if (isPixelFormatCompressed(format))
  303. throw love::Exception("generateMipmaps cannot be called on a compressed Texture.");
  304. gl.bindTextureToUnit(this, 0, false);
  305. GLenum gltextype = OpenGL::getGLTextureType(texType);
  306. if (gl.bugs.generateMipmapsRequiresTexture2DEnable)
  307. glEnable(gltextype);
  308. glGenerateMipmap(gltextype);
  309. }
  310. void Canvas::uploadByteData(PixelFormat pixelformat, const void *data, size_t size, int level, int slice, const Rect &r, love::image::ImageDataBase */*imgd*/)
  311. {
  312. OpenGL::TempDebugGroup debuggroup("Texture data upload");
  313. gl.bindTextureToUnit(this, 0, false);
  314. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(pixelformat, false, sRGB);
  315. GLenum gltarget = OpenGL::getGLTextureType(texType);
  316. if (texType == TEXTURE_CUBE)
  317. gltarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + slice;
  318. if (isPixelFormatCompressed(pixelformat))
  319. {
  320. if (r.x != 0 || r.y != 0)
  321. throw love::Exception("x and y parameters must be 0 for compressed images.");
  322. if (texType == TEXTURE_2D || texType == TEXTURE_CUBE)
  323. glCompressedTexImage2D(gltarget, level, fmt.internalformat, r.w, r.h, 0, size, data);
  324. else if (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME)
  325. glCompressedTexSubImage3D(gltarget, level, 0, 0, slice, r.w, r.h, 1, fmt.internalformat, size, data);
  326. }
  327. else
  328. {
  329. if (texType == TEXTURE_2D || texType == TEXTURE_CUBE)
  330. glTexSubImage2D(gltarget, level, r.x, r.y, r.w, r.h, fmt.externalformat, fmt.type, data);
  331. else if (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME)
  332. glTexSubImage3D(gltarget, level, r.x, r.y, slice, r.w, r.h, 1, fmt.externalformat, fmt.type, data);
  333. }
  334. }
  335. } // opengl
  336. } // graphics
  337. } // love