Canvas.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. /**
  2. * Copyright (c) 2006-2017 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 <algorithm> // For min/max
  23. namespace love
  24. {
  25. namespace graphics
  26. {
  27. namespace opengl
  28. {
  29. static GLenum createFBO(GLuint &framebuffer, TextureType texType, PixelFormat format, GLuint texture, int layers, int mips)
  30. {
  31. // get currently bound fbo to reset to it later
  32. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  33. glGenFramebuffers(1, &framebuffer);
  34. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, framebuffer);
  35. if (texture != 0)
  36. {
  37. bool unusedSRGB = false;
  38. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(format, false, unusedSRGB);
  39. int faces = texType == TEXTURE_CUBE ? 6 : 1;
  40. // Make sure all faces and layers of the texture are initialized to
  41. // transparent black. This is unfortunately probably pretty slow for
  42. // 2D-array and 3D textures with a lot of layers...
  43. for (int mip = mips - 1; mip >= 0; mip--)
  44. {
  45. int nlayers = layers;
  46. if (texType == TEXTURE_VOLUME)
  47. nlayers = std::max(layers >> mip, 1);
  48. for (int layer = nlayers - 1; layer >= 0; layer--)
  49. {
  50. for (int face = faces - 1; face >= 0; face--)
  51. {
  52. for (GLenum attachment : fmt.framebufferAttachments)
  53. {
  54. if (attachment == GL_NONE)
  55. continue;
  56. gl.framebufferTexture(attachment, texType, texture, mip, layer, face);
  57. }
  58. if (isPixelFormatDepthStencil(format))
  59. {
  60. gl.clearDepth(1.0);
  61. glClearStencil(0);
  62. glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  63. }
  64. else
  65. {
  66. glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  67. glClear(GL_COLOR_BUFFER_BIT);
  68. }
  69. }
  70. }
  71. }
  72. }
  73. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  74. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  75. return status;
  76. }
  77. static bool createRenderbuffer(int width, int height, int &samples, PixelFormat pixelformat, GLuint &buffer)
  78. {
  79. int reqsamples = samples;
  80. bool unusedSRGB = false;
  81. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(pixelformat, true, unusedSRGB);
  82. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  83. // Temporary FBO used to clear the renderbuffer.
  84. GLuint fbo = 0;
  85. glGenFramebuffers(1, &fbo);
  86. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  87. glGenRenderbuffers(1, &buffer);
  88. glBindRenderbuffer(GL_RENDERBUFFER, buffer);
  89. if (samples > 1)
  90. glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, fmt.internalformat, width, height);
  91. else
  92. glRenderbufferStorage(GL_RENDERBUFFER, fmt.internalformat, width, height);
  93. for (GLenum attachment : fmt.framebufferAttachments)
  94. {
  95. if (attachment != GL_NONE)
  96. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, buffer);
  97. }
  98. if (samples > 1)
  99. glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
  100. else
  101. samples = 0;
  102. glBindRenderbuffer(GL_RENDERBUFFER, 0);
  103. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  104. if (status == GL_FRAMEBUFFER_COMPLETE && (reqsamples <= 1 || samples > 1))
  105. {
  106. if (isPixelFormatDepthStencil(pixelformat))
  107. {
  108. gl.clearDepth(1.0);
  109. glClearStencil(0);
  110. glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  111. }
  112. else
  113. {
  114. // Initialize the buffer to transparent black.
  115. glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  116. glClear(GL_COLOR_BUFFER_BIT);
  117. }
  118. }
  119. else
  120. {
  121. glDeleteRenderbuffers(1, &buffer);
  122. buffer = 0;
  123. samples = 0;
  124. }
  125. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  126. gl.deleteFramebuffer(fbo);
  127. return status == GL_FRAMEBUFFER_COMPLETE;
  128. }
  129. Canvas::Canvas(const Settings &settings)
  130. : love::graphics::Canvas(settings)
  131. , fbo(0)
  132. , texture(0)
  133. , renderbuffer(0)
  134. , actualSamples(0)
  135. {
  136. format = getSizedFormat(format);
  137. initQuad();
  138. loadVolatile();
  139. if (status != GL_FRAMEBUFFER_COMPLETE)
  140. throw love::Exception("Cannot create Canvas: %s", OpenGL::framebufferStatusString(status));
  141. }
  142. Canvas::~Canvas()
  143. {
  144. unloadVolatile();
  145. }
  146. bool Canvas::loadVolatile()
  147. {
  148. if (texture != 0)
  149. return true;
  150. OpenGL::TempDebugGroup debuggroup("Canvas load");
  151. fbo = texture = 0;
  152. renderbuffer = 0;
  153. status = GL_FRAMEBUFFER_COMPLETE;
  154. // getMaxRenderbufferSamples will be 0 on systems that don't support
  155. // multisampled renderbuffers / don't export FBO multisample extensions.
  156. actualSamples = getRequestedMSAA();
  157. actualSamples = std::min(actualSamples, gl.getMaxRenderbufferSamples());
  158. actualSamples = std::max(actualSamples, 0);
  159. actualSamples = actualSamples == 1 ? 0 : actualSamples;
  160. if (isReadable())
  161. {
  162. glGenTextures(1, &texture);
  163. gl.bindTextureToUnit(this, 0, false);
  164. GLenum gltype = OpenGL::getGLTextureType(texType);
  165. if (GLAD_ANGLE_texture_usage)
  166. glTexParameteri(gltype, GL_TEXTURE_USAGE_ANGLE, GL_FRAMEBUFFER_ATTACHMENT_ANGLE);
  167. setFilter(filter);
  168. setWrap(wrap);
  169. setMipmapSharpness(mipmapSharpness);
  170. setDepthSampleMode(depthCompareMode);
  171. while (glGetError() != GL_NO_ERROR)
  172. /* Clear the error buffer. */;
  173. bool isSRGB = format == PIXELFORMAT_sRGBA8;
  174. if (!gl.rawTexStorage(texType, mipmapCount, format, isSRGB, pixelWidth, pixelHeight, texType == TEXTURE_VOLUME ? depth : layers))
  175. {
  176. status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
  177. return false;
  178. }
  179. if (glGetError() != GL_NO_ERROR)
  180. {
  181. gl.deleteTexture(texture);
  182. texture = 0;
  183. status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
  184. return false;
  185. }
  186. // Create a canvas-local FBO used for glReadPixels as well as MSAA blitting.
  187. status = createFBO(fbo, texType, format, texture, texType == TEXTURE_VOLUME ? depth : layers, mipmapCount);
  188. if (status != GL_FRAMEBUFFER_COMPLETE)
  189. {
  190. if (fbo != 0)
  191. {
  192. gl.deleteFramebuffer(fbo);
  193. fbo = 0;
  194. }
  195. return false;
  196. }
  197. }
  198. if (!isReadable() || actualSamples > 0)
  199. createRenderbuffer(pixelWidth, pixelHeight, actualSamples, format, renderbuffer);
  200. int64 memsize = getPixelFormatSize(format) * pixelWidth * pixelHeight;
  201. if (getMipmapCount() > 1)
  202. memsize *= 1.33334;
  203. if (actualSamples > 1 && isReadable())
  204. memsize += getPixelFormatSize(format) * pixelWidth * pixelHeight * actualSamples;
  205. else if (actualSamples > 1)
  206. memsize *= actualSamples;
  207. setGraphicsMemorySize(memsize);
  208. return true;
  209. }
  210. void Canvas::unloadVolatile()
  211. {
  212. if (fbo != 0)
  213. gl.deleteFramebuffer(fbo);
  214. if (renderbuffer != 0)
  215. glDeleteRenderbuffers(1, &renderbuffer);
  216. if (texture != 0)
  217. gl.deleteTexture(texture);
  218. fbo = 0;
  219. renderbuffer = 0;
  220. texture = 0;
  221. setGraphicsMemorySize(0);
  222. }
  223. void Canvas::setFilter(const Texture::Filter &f)
  224. {
  225. Texture::setFilter(f);
  226. if (!OpenGL::hasTextureFilteringSupport(getPixelFormat()))
  227. {
  228. filter.mag = filter.min = FILTER_NEAREST;
  229. if (filter.mipmap == FILTER_LINEAR)
  230. filter.mipmap = FILTER_NEAREST;
  231. }
  232. gl.bindTextureToUnit(this, 0, false);
  233. gl.setTextureFilter(texType, filter);
  234. }
  235. bool Canvas::setWrap(const Texture::Wrap &w)
  236. {
  237. Graphics::flushStreamDrawsGlobal();
  238. bool success = true;
  239. bool forceclamp = texType == TEXTURE_CUBE;
  240. wrap = w;
  241. // If we only have limited NPOT support then the wrap mode must be CLAMP.
  242. if ((GLAD_ES_VERSION_2_0 && !(GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot))
  243. && (pixelWidth != nextP2(pixelWidth) || pixelHeight != nextP2(pixelHeight) || depth != nextP2(depth)))
  244. {
  245. forceclamp = true;
  246. }
  247. if (forceclamp)
  248. {
  249. if (wrap.s != WRAP_CLAMP || wrap.t != WRAP_CLAMP || wrap.r != WRAP_CLAMP)
  250. success = false;
  251. wrap.s = wrap.t = wrap.r = WRAP_CLAMP;
  252. }
  253. if (!gl.isClampZeroTextureWrapSupported())
  254. {
  255. if (wrap.s == WRAP_CLAMP_ZERO) wrap.s = WRAP_CLAMP;
  256. if (wrap.t == WRAP_CLAMP_ZERO) wrap.t = WRAP_CLAMP;
  257. if (wrap.r == WRAP_CLAMP_ZERO) wrap.r = WRAP_CLAMP;
  258. }
  259. gl.bindTextureToUnit(this, 0, false);
  260. gl.setTextureWrap(texType, wrap);
  261. return success;
  262. }
  263. bool Canvas::setMipmapSharpness(float sharpness)
  264. {
  265. if (!gl.isSamplerLODBiasSupported())
  266. return false;
  267. Graphics::flushStreamDrawsGlobal();
  268. float maxbias = gl.getMaxLODBias();
  269. if (maxbias > 0.01f)
  270. maxbias -= 0.0f;
  271. mipmapSharpness = std::min(std::max(sharpness, -maxbias), maxbias);
  272. gl.bindTextureToUnit(this, 0, false);
  273. // negative bias is sharper
  274. glTexParameterf(gl.getGLTextureType(texType), GL_TEXTURE_LOD_BIAS, -mipmapSharpness);
  275. return true;
  276. }
  277. void Canvas::setDepthSampleMode(Optional<CompareMode> mode)
  278. {
  279. Texture::setDepthSampleMode(mode);
  280. bool supported = gl.isDepthCompareSampleSupported();
  281. if (mode.hasValue)
  282. {
  283. if (!supported)
  284. throw love::Exception("Depth comparison sampling in shaders is not supported on this system.");
  285. Graphics::flushStreamDrawsGlobal();
  286. gl.bindTextureToUnit(texType, texture, 0, false);
  287. GLenum gltextype = OpenGL::getGLTextureType(texType);
  288. // See the comment in depthstencil.h
  289. GLenum glmode = OpenGL::getGLCompareMode(getReversedCompareMode(mode.value));
  290. glTexParameteri(gltextype, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  291. glTexParameteri(gltextype, GL_TEXTURE_COMPARE_FUNC, glmode);
  292. }
  293. else if (isPixelFormatDepth(format) && supported)
  294. {
  295. Graphics::flushStreamDrawsGlobal();
  296. gl.bindTextureToUnit(texType, texture, 0, false);
  297. GLenum gltextype = OpenGL::getGLTextureType(texType);
  298. glTexParameteri(gltextype, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  299. }
  300. depthCompareMode = mode;
  301. }
  302. ptrdiff_t Canvas::getHandle() const
  303. {
  304. return texture;
  305. }
  306. love::image::ImageData *Canvas::newImageData(love::image::Image *module, int slice, int mipmap, const Rect &r)
  307. {
  308. love::image::ImageData *data = love::graphics::Canvas::newImageData(module, slice, mipmap, r);
  309. bool isSRGB = false;
  310. OpenGL::TextureFormat fmt = gl.convertPixelFormat(data->getFormat(), false, isSRGB);
  311. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  312. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getFBO());
  313. if (slice > 0 || mipmap > 0)
  314. {
  315. int layer = texType == TEXTURE_CUBE ? 0 : slice;
  316. int face = texType == TEXTURE_CUBE ? slice : 0;
  317. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, mipmap, layer, face);
  318. }
  319. glReadPixels(r.x, r.y, r.w, r.h, fmt.externalformat, fmt.type, data->getData());
  320. if (slice > 0 || mipmap > 0)
  321. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, 0, 0, 0);
  322. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  323. return data;
  324. }
  325. void Canvas::generateMipmaps()
  326. {
  327. if (getMipmapCount() == 1 || getMipmapMode() == MIPMAPS_NONE)
  328. throw love::Exception("generateMipmaps can only be called on a Canvas which was created with mipmaps enabled.");
  329. gl.bindTextureToUnit(this, 0, false);
  330. GLenum gltextype = OpenGL::getGLTextureType(texType);
  331. if (gl.bugs.generateMipmapsRequiresTexture2DEnable)
  332. glEnable(gltextype);
  333. glGenerateMipmap(gltextype);
  334. }
  335. PixelFormat Canvas::getSizedFormat(PixelFormat format)
  336. {
  337. switch (format)
  338. {
  339. case PIXELFORMAT_NORMAL:
  340. if (isGammaCorrect())
  341. return PIXELFORMAT_sRGBA8;
  342. else if (!OpenGL::isPixelFormatSupported(PIXELFORMAT_RGBA8, true, true, false))
  343. // 32-bit render targets don't have guaranteed support on GLES2.
  344. return PIXELFORMAT_RGBA4;
  345. else
  346. return PIXELFORMAT_RGBA8;
  347. case PIXELFORMAT_HDR:
  348. return PIXELFORMAT_RGBA16F;
  349. default:
  350. return format;
  351. }
  352. }
  353. bool Canvas::isSupported()
  354. {
  355. return GLAD_ES_VERSION_2_0 || GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_object || GLAD_EXT_framebuffer_object;
  356. }
  357. bool Canvas::isMultiFormatMultiCanvasSupported()
  358. {
  359. return gl.getMaxRenderTargets() > 1 && (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_object);
  360. }
  361. Canvas::SupportedFormat Canvas::supportedFormats[] = {};
  362. Canvas::SupportedFormat Canvas::checkedFormats[] = {};
  363. bool Canvas::isFormatSupported(PixelFormat format)
  364. {
  365. return isFormatSupported(format, !isPixelFormatDepthStencil(format));
  366. }
  367. bool Canvas::isFormatSupported(PixelFormat format, bool readable)
  368. {
  369. if (!isSupported())
  370. return false;
  371. const char *fstr = "?";
  372. love::getConstant(format, fstr);
  373. bool supported = true;
  374. format = getSizedFormat(format);
  375. if (!OpenGL::isPixelFormatSupported(format, true, readable, false))
  376. return false;
  377. if (checkedFormats[format].get(readable))
  378. return supportedFormats[format].get(readable);
  379. // Even though we might have the necessary OpenGL version or extension,
  380. // drivers are still allowed to throw FRAMEBUFFER_UNSUPPORTED when attaching
  381. // a texture to a FBO whose format the driver doesn't like. So we should
  382. // test with an actual FBO.
  383. GLuint texture = 0;
  384. GLuint renderbuffer = 0;
  385. bool unusedSRGB = false;
  386. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(format, readable, unusedSRGB);
  387. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  388. GLuint fbo = 0;
  389. glGenFramebuffers(1, &fbo);
  390. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  391. // Make sure at least something is bound to a color attachment. I believe
  392. // this is required on ES2 but I'm not positive.
  393. if (isPixelFormatDepthStencil(format))
  394. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, TEXTURE_2D, gl.getDefaultTexture(TEXTURE_2D), 0, 0, 0);
  395. if (readable)
  396. {
  397. glGenTextures(1, &texture);
  398. gl.bindTextureToUnit(TEXTURE_2D, texture, 0, false);
  399. Texture::Filter f;
  400. f.min = f.mag = Texture::FILTER_NEAREST;
  401. gl.setTextureFilter(TEXTURE_2D, f);
  402. Texture::Wrap w;
  403. gl.setTextureWrap(TEXTURE_2D, w);
  404. unusedSRGB = false;
  405. gl.rawTexStorage(TEXTURE_2D, 1, format, unusedSRGB, 1, 1);
  406. }
  407. else
  408. {
  409. glGenRenderbuffers(1, &renderbuffer);
  410. glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
  411. glRenderbufferStorage(GL_RENDERBUFFER, fmt.internalformat, 1, 1);
  412. }
  413. for (GLenum attachment : fmt.framebufferAttachments)
  414. {
  415. if (attachment == GL_NONE)
  416. continue;
  417. if (readable)
  418. gl.framebufferTexture(attachment, TEXTURE_2D, texture, 0, 0, 0);
  419. else
  420. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, renderbuffer);
  421. }
  422. supported = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
  423. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  424. gl.deleteFramebuffer(fbo);
  425. if (texture != 0)
  426. gl.deleteTexture(texture);
  427. if (renderbuffer != 0)
  428. glDeleteRenderbuffers(1, &renderbuffer);
  429. // Cache the result so we don't do this for every isFormatSupported call.
  430. checkedFormats[format].set(readable, true);
  431. supportedFormats[format].set(readable, supported);
  432. return supported;
  433. }
  434. } // opengl
  435. } // graphics
  436. } // love