Graphics.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  1. /**
  2. * Copyright (c) 2006-2021 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. // LOVE
  21. #include "common/config.h"
  22. #include "common/math.h"
  23. #include "common/Vector.h"
  24. #include "Graphics.h"
  25. #include "font/Font.h"
  26. #include "StreamBuffer.h"
  27. #include "math/MathModule.h"
  28. #include "window/Window.h"
  29. #include "Buffer.h"
  30. #include "ShaderStage.h"
  31. #include "libraries/xxHash/xxhash.h"
  32. // C++
  33. #include <vector>
  34. #include <sstream>
  35. #include <algorithm>
  36. #include <iterator>
  37. // C
  38. #include <cmath>
  39. #include <cstdio>
  40. #ifdef LOVE_IOS
  41. #include <SDL_syswm.h>
  42. #endif
  43. namespace love
  44. {
  45. namespace graphics
  46. {
  47. namespace opengl
  48. {
  49. static GLenum getGLBlendOperation(BlendOperation op)
  50. {
  51. switch (op)
  52. {
  53. case BLENDOP_ADD: return GL_FUNC_ADD;
  54. case BLENDOP_SUBTRACT: return GL_FUNC_SUBTRACT;
  55. case BLENDOP_REVERSE_SUBTRACT: return GL_FUNC_REVERSE_SUBTRACT;
  56. case BLENDOP_MIN: return GL_MIN;
  57. case BLENDOP_MAX: return GL_MAX;
  58. case BLENDOP_MAX_ENUM: return 0;
  59. }
  60. return 0;
  61. }
  62. static GLenum getGLBlendFactor(BlendFactor factor)
  63. {
  64. switch (factor)
  65. {
  66. case BLENDFACTOR_ZERO: return GL_ZERO;
  67. case BLENDFACTOR_ONE: return GL_ONE;
  68. case BLENDFACTOR_SRC_COLOR: return GL_SRC_COLOR;
  69. case BLENDFACTOR_ONE_MINUS_SRC_COLOR: return GL_ONE_MINUS_SRC_COLOR;
  70. case BLENDFACTOR_SRC_ALPHA: return GL_SRC_ALPHA;
  71. case BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return GL_ONE_MINUS_SRC_ALPHA;
  72. case BLENDFACTOR_DST_COLOR: return GL_DST_COLOR;
  73. case BLENDFACTOR_ONE_MINUS_DST_COLOR: return GL_ONE_MINUS_DST_COLOR;
  74. case BLENDFACTOR_DST_ALPHA: return GL_DST_ALPHA;
  75. case BLENDFACTOR_ONE_MINUS_DST_ALPHA: return GL_ONE_MINUS_DST_ALPHA;
  76. case BLENDFACTOR_SRC_ALPHA_SATURATED: return GL_SRC_ALPHA_SATURATE;
  77. case BLENDFACTOR_MAX_ENUM: return 0;
  78. }
  79. return 0;
  80. }
  81. Graphics::Graphics()
  82. : windowHasStencil(false)
  83. , mainVAO(0)
  84. , internalBackbufferFBO(0)
  85. , requestedBackbufferMSAA(0)
  86. , bufferMapMemory(nullptr)
  87. , bufferMapMemorySize(2 * 1024 * 1024)
  88. , defaultBuffers()
  89. , supportedFormats()
  90. {
  91. gl = OpenGL();
  92. try
  93. {
  94. bufferMapMemory = new char[bufferMapMemorySize];
  95. }
  96. catch (std::exception &)
  97. {
  98. // Handled in getBufferMapMemory.
  99. }
  100. auto window = getInstance<love::window::Window>(M_WINDOW);
  101. if (window != nullptr)
  102. {
  103. window->setGraphics(this);
  104. if (window->isOpen())
  105. {
  106. int w, h;
  107. love::window::WindowSettings s;
  108. window->getWindow(w, h, s);
  109. double dpiW = w;
  110. double dpiH = h;
  111. window->windowToDPICoords(&dpiW, &dpiH);
  112. setMode((int) dpiW, (int) dpiH, window->getPixelWidth(), window->getPixelHeight(), s.stencil, s.msaa);
  113. }
  114. }
  115. }
  116. Graphics::~Graphics()
  117. {
  118. delete[] bufferMapMemory;
  119. }
  120. const char *Graphics::getName() const
  121. {
  122. return "love.graphics.opengl";
  123. }
  124. love::graphics::StreamBuffer *Graphics::newStreamBuffer(BufferUsage type, size_t size)
  125. {
  126. return CreateStreamBuffer(type, size);
  127. }
  128. love::graphics::Texture *Graphics::newTexture(const Texture::Settings &settings, const Texture::Slices *data)
  129. {
  130. return new Texture(settings, data);
  131. }
  132. love::graphics::ShaderStage *Graphics::newShaderStageInternal(ShaderStageType stage, const std::string &cachekey, const std::string &source, bool gles)
  133. {
  134. return new ShaderStage(this, stage, source, gles, cachekey);
  135. }
  136. love::graphics::Shader *Graphics::newShaderInternal(StrongRef<love::graphics::ShaderStage> stages[SHADERSTAGE_MAX_ENUM])
  137. {
  138. return new Shader(stages);
  139. }
  140. love::graphics::Buffer *Graphics::newBuffer(const Buffer::Settings &settings, const std::vector<Buffer::DataDeclaration> &format, const void *data, size_t size, size_t arraylength)
  141. {
  142. return new Buffer(this, settings, format, data, size, arraylength);
  143. }
  144. void Graphics::setViewportSize(int width, int height, int pixelwidth, int pixelheight)
  145. {
  146. this->width = width;
  147. this->height = height;
  148. this->pixelWidth = pixelwidth;
  149. this->pixelHeight = pixelheight;
  150. if (!isRenderTargetActive())
  151. {
  152. // Set the viewport to top-left corner.
  153. gl.setViewport({0, 0, pixelwidth, pixelheight});
  154. // Re-apply the scissor if it was active, since the rectangle passed to
  155. // glScissor is affected by the viewport dimensions.
  156. if (states.back().scissor)
  157. setScissor(states.back().scissorRect);
  158. // Set up the projection matrix
  159. projectionMatrix = Matrix4::ortho(0.0, (float) width, (float) height, 0.0, -10.0f, 10.0f);
  160. }
  161. updateBackbuffer(width, height, pixelwidth, pixelheight, requestedBackbufferMSAA);
  162. }
  163. void Graphics::updateBackbuffer(int width, int height, int /*pixelwidth*/, int pixelheight, int msaa)
  164. {
  165. bool useinternalbackbuffer = false;
  166. if (msaa > 1)
  167. useinternalbackbuffer = true;
  168. // Our internal backbuffer code needs glBlitFramebuffer.
  169. if (!(GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_object || GLAD_ES_VERSION_3_0
  170. || GLAD_EXT_framebuffer_blit || GLAD_ANGLE_framebuffer_blit || GLAD_NV_framebuffer_blit))
  171. {
  172. if (!(msaa > 1 && GLAD_APPLE_framebuffer_multisample))
  173. useinternalbackbuffer = false;
  174. }
  175. GLuint prevFBO = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  176. bool restoreFBO = prevFBO != getInternalBackbufferFBO();
  177. if (useinternalbackbuffer)
  178. {
  179. Texture::Settings settings;
  180. settings.width = width;
  181. settings.height = height;
  182. settings.dpiScale = (float)pixelheight / (float)height;
  183. settings.msaa = msaa;
  184. settings.renderTarget = true;
  185. settings.readable.set(false);
  186. settings.format = isGammaCorrect() ? PIXELFORMAT_sRGBA8_UNORM : PIXELFORMAT_RGBA8_UNORM;
  187. internalBackbuffer.set(newTexture(settings), Acquire::NORETAIN);
  188. settings.format = PIXELFORMAT_DEPTH24_UNORM_STENCIL8;
  189. internalBackbufferDepthStencil.set(newTexture(settings), Acquire::NORETAIN);
  190. RenderTargets rts;
  191. rts.colors.push_back(internalBackbuffer.get());
  192. rts.depthStencil.texture = internalBackbufferDepthStencil;
  193. internalBackbufferFBO = bindCachedFBO(rts);
  194. }
  195. else
  196. {
  197. internalBackbuffer.set(nullptr);
  198. internalBackbufferDepthStencil.set(nullptr);
  199. internalBackbufferFBO = 0;
  200. }
  201. requestedBackbufferMSAA = msaa;
  202. if (restoreFBO)
  203. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, prevFBO);
  204. }
  205. GLuint Graphics::getInternalBackbufferFBO() const
  206. {
  207. if (internalBackbufferFBO != 0)
  208. return internalBackbufferFBO;
  209. else
  210. return getSystemBackbufferFBO();
  211. }
  212. GLuint Graphics::getSystemBackbufferFBO() const
  213. {
  214. #ifdef LOVE_IOS
  215. // Hack: iOS uses a custom FBO.
  216. SDL_SysWMinfo info = {};
  217. SDL_VERSION(&info.version);
  218. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  219. if (info.info.uikit.resolveFramebuffer != 0)
  220. return info.info.uikit.resolveFramebuffer;
  221. else
  222. return info.info.uikit.framebuffer;
  223. #else
  224. return 0;
  225. #endif
  226. }
  227. bool Graphics::setMode(int width, int height, int pixelwidth, int pixelheight, bool windowhasstencil, int msaa)
  228. {
  229. this->width = width;
  230. this->height = height;
  231. this->windowHasStencil = windowhasstencil;
  232. this->requestedBackbufferMSAA = msaa;
  233. // Okay, setup OpenGL.
  234. gl.initContext();
  235. if (gl.isCoreProfile())
  236. {
  237. glGenVertexArrays(1, &mainVAO);
  238. glBindVertexArray(mainVAO);
  239. }
  240. gl.setupContext();
  241. created = true;
  242. initCapabilities();
  243. // Enable blending
  244. gl.setEnableState(OpenGL::ENABLE_BLEND, true);
  245. // Auto-generated mipmaps should be the best quality possible
  246. if (!gl.isCoreProfile())
  247. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  248. if (!GLAD_ES_VERSION_2_0 && !gl.isCoreProfile())
  249. {
  250. // Make sure antialiasing works when set elsewhere
  251. glEnable(GL_MULTISAMPLE);
  252. // Enable texturing
  253. glEnable(GL_TEXTURE_2D);
  254. }
  255. if (!GLAD_ES_VERSION_2_0)
  256. glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
  257. gl.setTextureUnit(0);
  258. // Set pixel row alignment - code that calls glTexSubImage and glReadPixels
  259. // assumes there's no row alignment, but OpenGL defaults to 4 bytes.
  260. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  261. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  262. // Always enable seamless cubemap filtering when possible.
  263. if (GLAD_VERSION_3_2 || GLAD_ARB_seamless_cube_map)
  264. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  265. // Set whether drawing converts input from linear -> sRGB colorspace.
  266. if (!gl.bugs.brokenSRGB && (GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_sRGB
  267. || GLAD_EXT_framebuffer_sRGB || GLAD_ES_VERSION_3_0))
  268. {
  269. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  270. gl.setEnableState(OpenGL::ENABLE_FRAMEBUFFER_SRGB, isGammaCorrect());
  271. }
  272. else
  273. setGammaCorrect(false);
  274. setDebug(isDebugEnabled());
  275. setViewportSize(width, height, pixelwidth, pixelheight);
  276. if (batchedDrawState.vb[0] == nullptr)
  277. {
  278. // Initial sizes that should be good enough for most cases. It will
  279. // resize to fit if needed, later.
  280. batchedDrawState.vb[0] = CreateStreamBuffer(BUFFERUSAGE_VERTEX, 1024 * 1024 * 1);
  281. batchedDrawState.vb[1] = CreateStreamBuffer(BUFFERUSAGE_VERTEX, 256 * 1024 * 1);
  282. batchedDrawState.indexBuffer = CreateStreamBuffer(BUFFERUSAGE_INDEX, sizeof(uint16) * LOVE_UINT16_MAX);
  283. }
  284. // TODO: one buffer each for float, int, uint
  285. if (capabilities.features[FEATURE_TEXEL_BUFFER] && defaultBuffers[BUFFERUSAGE_TEXEL].get() == nullptr)
  286. {
  287. Buffer::Settings settings(BUFFERUSAGEFLAG_TEXEL, BUFFERDATAUSAGE_STATIC);
  288. std::vector<Buffer::DataDeclaration> format = {{"", DATAFORMAT_FLOAT_VEC4, 0}};
  289. const float texel[] = {0.0f, 0.0f, 0.0f, 1.0f};
  290. auto buffer = newBuffer(settings, format, texel, sizeof(texel), 1);
  291. defaultBuffers[BUFFERUSAGE_TEXEL].set(buffer, Acquire::NORETAIN);
  292. }
  293. if (capabilities.features[FEATURE_GLSL4] && defaultBuffers[BUFFERUSAGE_SHADER_STORAGE].get() == nullptr)
  294. {
  295. Buffer::Settings settings(BUFFERUSAGEFLAG_SHADER_STORAGE, BUFFERDATAUSAGE_STATIC);
  296. std::vector<Buffer::DataDeclaration> format = {{"", DATAFORMAT_FLOAT, 0}};
  297. std::vector<float> data;
  298. data.resize(Buffer::SHADER_STORAGE_BUFFER_MAX_STRIDE / 4);
  299. auto buffer = newBuffer(settings, format, data.data(), data.size() * sizeof(float), data.size());
  300. defaultBuffers[BUFFERUSAGE_SHADER_STORAGE].set(buffer, Acquire::NORETAIN);
  301. }
  302. // Load default resources before other Volatile.
  303. for (int i = 0; i < BUFFERUSAGE_MAX_ENUM; i++)
  304. {
  305. if (defaultBuffers[i].get())
  306. ((Buffer *) defaultBuffers[i].get())->loadVolatile();
  307. }
  308. if (defaultBuffers[BUFFERUSAGE_TEXEL].get())
  309. gl.setDefaultTexelBuffer((GLuint) defaultBuffers[BUFFERUSAGE_TEXEL]->getTexelBufferHandle());
  310. if (defaultBuffers[BUFFERUSAGE_SHADER_STORAGE].get())
  311. gl.setDefaultStorageBuffer((GLuint) defaultBuffers[BUFFERUSAGE_SHADER_STORAGE]->getHandle());
  312. // Reload all volatile objects.
  313. if (!Volatile::loadAll())
  314. ::printf("Could not reload all volatile objects.\n");
  315. createQuadIndexBuffer();
  316. // Restore the graphics state.
  317. restoreState(states.back());
  318. // We always need a default shader.
  319. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++)
  320. {
  321. auto stype = (Shader::StandardShader) i;
  322. if (i == Shader::STANDARD_ARRAY && !capabilities.textureTypes[TEXTURE_2D_ARRAY])
  323. continue;
  324. // Apparently some intel GMA drivers on windows fail to compile shaders
  325. // which use array textures despite claiming support for the extension.
  326. try
  327. {
  328. if (!Shader::standardShaders[i])
  329. {
  330. std::vector<std::string> stages;
  331. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_VERTEX));
  332. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_PIXEL));
  333. Shader::standardShaders[i] = newShader(stages);
  334. }
  335. }
  336. catch (love::Exception &)
  337. {
  338. if (i == Shader::STANDARD_ARRAY)
  339. capabilities.textureTypes[TEXTURE_2D_ARRAY] = false;
  340. else
  341. throw;
  342. }
  343. }
  344. // A shader should always be active, but the default shader shouldn't be
  345. // returned by getShader(), so we don't do setShader(defaultShader).
  346. if (!Shader::current)
  347. Shader::standardShaders[Shader::STANDARD_DEFAULT]->attach();
  348. return true;
  349. }
  350. void Graphics::unSetMode()
  351. {
  352. if (!isCreated())
  353. return;
  354. flushBatchedDraws();
  355. internalBackbuffer.set(nullptr);
  356. internalBackbufferDepthStencil.set(nullptr);
  357. // Unload all volatile objects. These must be reloaded after the display
  358. // mode change.
  359. Volatile::unloadAll();
  360. for (const auto &pair : framebufferObjects)
  361. gl.deleteFramebuffer(pair.second);
  362. for (auto temp : temporaryTextures)
  363. temp.texture->release();
  364. framebufferObjects.clear();
  365. temporaryTextures.clear();
  366. if (mainVAO != 0)
  367. {
  368. glDeleteVertexArrays(1, &mainVAO);
  369. mainVAO = 0;
  370. }
  371. gl.deInitContext();
  372. created = false;
  373. }
  374. void Graphics::setActive(bool enable)
  375. {
  376. flushBatchedDraws();
  377. // Make sure all pending OpenGL commands have fully executed before
  378. // returning, when going from active to inactive. This is required on iOS.
  379. if (isCreated() && this->active && !enable)
  380. glFinish();
  381. active = enable;
  382. }
  383. static bool computeDispatchBarriers(Shader *shader, GLbitfield &preDispatchBarriers, GLbitfield &postDispatchBarriers)
  384. {
  385. // TODO: handle indirect argument buffer types, when those are added.
  386. for (auto buffer : shader->getActiveWritableStorageBuffers())
  387. {
  388. if (buffer == nullptr)
  389. return false;
  390. auto usage = buffer->getUsageFlags();
  391. postDispatchBarriers |= GL_BUFFER_UPDATE_BARRIER_BIT;
  392. if (usage & BUFFERUSAGEFLAG_SHADER_STORAGE)
  393. {
  394. preDispatchBarriers |= GL_SHADER_STORAGE_BARRIER_BIT;
  395. postDispatchBarriers |= GL_SHADER_STORAGE_BARRIER_BIT;
  396. }
  397. if (usage & BUFFERUSAGEFLAG_TEXEL)
  398. postDispatchBarriers |= GL_TEXTURE_FETCH_BARRIER_BIT;
  399. if (usage & BUFFERUSAGEFLAG_INDEX)
  400. postDispatchBarriers |= GL_ELEMENT_ARRAY_BARRIER_BIT;
  401. if (usage & BUFFERUSAGEFLAG_VERTEX)
  402. postDispatchBarriers |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT;
  403. postDispatchBarriers |= GL_PIXEL_BUFFER_BARRIER_BIT;
  404. }
  405. for (const auto &binding : shader->getStorageTextureBindings())
  406. {
  407. if (binding.texture == nullptr)
  408. return false;
  409. if (binding.access == GL_READ_ONLY)
  410. continue;
  411. preDispatchBarriers |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
  412. postDispatchBarriers |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT
  413. | GL_TEXTURE_UPDATE_BARRIER_BIT
  414. | GL_TEXTURE_FETCH_BARRIER_BIT;
  415. if (binding.texture->isRenderTarget())
  416. postDispatchBarriers |= GL_FRAMEBUFFER_BARRIER_BIT;
  417. }
  418. return true;
  419. }
  420. bool Graphics::dispatch(int x, int y, int z)
  421. {
  422. // Set by higher level code before calling dispatch(x, y, z).
  423. auto shader = (Shader *) Shader::current;
  424. GLbitfield preDispatchBarriers = 0;
  425. GLbitfield postDispatchBarriers = 0;
  426. if (!computeDispatchBarriers(shader, preDispatchBarriers, postDispatchBarriers))
  427. return false;
  428. // glMemoryBarrier before dispatch to make sure non-compute-read ->
  429. // compute-write is synced.
  430. // TODO: is this needed? spec language around GL_SHADER_IMAGE_ACCESS_BARRIER_BIT
  431. // makes me think so.
  432. // This is overly conservative (dispatch -> dispatch will have redundant
  433. // barriers).
  434. if (preDispatchBarriers != 0)
  435. glMemoryBarrier(preDispatchBarriers);
  436. glDispatchCompute(x, y, z);
  437. // Not as (theoretically) efficient as issuing the barrier right before
  438. // they're used later, but much less complicated.
  439. if (postDispatchBarriers != 0)
  440. glMemoryBarrier(postDispatchBarriers);
  441. return true;
  442. }
  443. void Graphics::draw(const DrawCommand &cmd)
  444. {
  445. gl.prepareDraw(this);
  446. gl.setVertexAttributes(*cmd.attributes, *cmd.buffers);
  447. gl.bindTextureToUnit(cmd.texture, 0, false);
  448. gl.setCullMode(cmd.cullMode);
  449. GLenum glprimitivetype = OpenGL::getGLPrimitiveType(cmd.primitiveType);
  450. if (cmd.instanceCount > 1)
  451. glDrawArraysInstanced(glprimitivetype, cmd.vertexStart, cmd.vertexCount, cmd.instanceCount);
  452. else
  453. glDrawArrays(glprimitivetype, cmd.vertexStart, cmd.vertexCount);
  454. ++drawCalls;
  455. }
  456. void Graphics::draw(const DrawIndexedCommand &cmd)
  457. {
  458. gl.prepareDraw(this);
  459. gl.setVertexAttributes(*cmd.attributes, *cmd.buffers);
  460. gl.bindTextureToUnit(cmd.texture, 0, false);
  461. gl.setCullMode(cmd.cullMode);
  462. const void *gloffset = BUFFER_OFFSET(cmd.indexBufferOffset);
  463. GLenum glprimitivetype = OpenGL::getGLPrimitiveType(cmd.primitiveType);
  464. GLenum gldatatype = OpenGL::getGLIndexDataType(cmd.indexType);
  465. gl.bindBuffer(BUFFERUSAGE_INDEX, cmd.indexBuffer->getHandle());
  466. if (cmd.instanceCount > 1)
  467. glDrawElementsInstanced(glprimitivetype, cmd.indexCount, gldatatype, gloffset, cmd.instanceCount);
  468. else
  469. glDrawElements(glprimitivetype, cmd.indexCount, gldatatype, gloffset);
  470. ++drawCalls;
  471. }
  472. static inline void advanceVertexOffsets(const VertexAttributes &attributes, BufferBindings &buffers, int vertexcount)
  473. {
  474. // TODO: Figure out a better way to avoid touching the same buffer multiple
  475. // times, if multiple attributes share the buffer.
  476. uint32 touchedbuffers = 0;
  477. for (unsigned int i = 0; i < VertexAttributes::MAX; i++)
  478. {
  479. if (!attributes.isEnabled(i))
  480. continue;
  481. auto &attrib = attributes.attribs[i];
  482. uint32 bufferbit = 1u << attrib.bufferIndex;
  483. if ((touchedbuffers & bufferbit) == 0)
  484. {
  485. touchedbuffers |= bufferbit;
  486. const auto &layout = attributes.bufferLayouts[attrib.bufferIndex];
  487. buffers.info[attrib.bufferIndex].offset += layout.stride * vertexcount;
  488. }
  489. }
  490. }
  491. void Graphics::drawQuads(int start, int count, const VertexAttributes &attributes, const BufferBindings &buffers, love::graphics::Texture *texture)
  492. {
  493. const int MAX_VERTICES_PER_DRAW = LOVE_UINT16_MAX;
  494. const int MAX_QUADS_PER_DRAW = MAX_VERTICES_PER_DRAW / 4;
  495. gl.prepareDraw(this);
  496. gl.bindTextureToUnit(texture, 0, false);
  497. gl.setCullMode(CULL_NONE);
  498. gl.bindBuffer(BUFFERUSAGE_INDEX, quadIndexBuffer->getHandle());
  499. if (gl.isBaseVertexSupported())
  500. {
  501. gl.setVertexAttributes(attributes, buffers);
  502. int basevertex = start * 4;
  503. for (int quadindex = 0; quadindex < count; quadindex += MAX_QUADS_PER_DRAW)
  504. {
  505. int quadcount = std::min(MAX_QUADS_PER_DRAW, count - quadindex);
  506. glDrawElementsBaseVertex(GL_TRIANGLES, quadcount * 6, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0), basevertex);
  507. ++drawCalls;
  508. basevertex += quadcount * 4;
  509. }
  510. }
  511. else
  512. {
  513. BufferBindings bufferscopy = buffers;
  514. if (start > 0)
  515. advanceVertexOffsets(attributes, bufferscopy, start * 4);
  516. for (int quadindex = 0; quadindex < count; quadindex += MAX_QUADS_PER_DRAW)
  517. {
  518. gl.setVertexAttributes(attributes, bufferscopy);
  519. int quadcount = std::min(MAX_QUADS_PER_DRAW, count - quadindex);
  520. glDrawElements(GL_TRIANGLES, quadcount * 6, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
  521. ++drawCalls;
  522. if (count > MAX_QUADS_PER_DRAW)
  523. advanceVertexOffsets(attributes, bufferscopy, quadcount * 4);
  524. }
  525. }
  526. }
  527. static void APIENTRY debugCB(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei /*len*/, const GLchar *msg, const GLvoid* /*usr*/)
  528. {
  529. // Human-readable strings for the debug info.
  530. const char *sourceStr = OpenGL::debugSourceString(source);
  531. const char *typeStr = OpenGL::debugTypeString(type);
  532. const char *severityStr = OpenGL::debugSeverityString(severity);
  533. const char *fmt = "OpenGL: %s [source=%s, type=%s, severity=%s, id=%d]\n";
  534. printf(fmt, msg, sourceStr, typeStr, severityStr, id);
  535. }
  536. void Graphics::setDebug(bool enable)
  537. {
  538. // Make sure debug output is supported. The AMD ext. is a bit different
  539. // so we don't make use of it, since AMD drivers now support KHR_debug.
  540. if (!(GLAD_VERSION_4_3 || GLAD_KHR_debug || GLAD_ARB_debug_output))
  541. return;
  542. // TODO: We don't support GL_KHR_debug in GLES yet.
  543. if (GLAD_ES_VERSION_2_0)
  544. return;
  545. // Ugly hack to reduce code duplication.
  546. if (GLAD_ARB_debug_output && !(GLAD_VERSION_4_3 || GLAD_KHR_debug))
  547. {
  548. fp_glDebugMessageCallback = (pfn_glDebugMessageCallback) fp_glDebugMessageCallbackARB;
  549. fp_glDebugMessageControl = (pfn_glDebugMessageControl) fp_glDebugMessageControlARB;
  550. }
  551. if (!enable)
  552. {
  553. // Disable the debug callback function.
  554. glDebugMessageCallback(nullptr, nullptr);
  555. // We can disable debug output entirely with KHR_debug.
  556. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  557. glDisable(GL_DEBUG_OUTPUT);
  558. return;
  559. }
  560. // We don't want asynchronous debug output.
  561. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  562. glDebugMessageCallback(debugCB, nullptr);
  563. // Initially, enable everything.
  564. glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
  565. // Disable messages about deprecated OpenGL functionality.
  566. glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  567. glDebugMessageControl(GL_DEBUG_SOURCE_SHADER_COMPILER, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  568. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  569. glEnable(GL_DEBUG_OUTPUT);
  570. ::printf("OpenGL debug output enabled (LOVE_GRAPHICS_DEBUG=1)\n");
  571. }
  572. void Graphics::setRenderTargetsInternal(const RenderTargets &rts, int w, int h, int pixelw, int pixelh, bool hasSRGBtexture)
  573. {
  574. const DisplayState &state = states.back();
  575. OpenGL::TempDebugGroup debuggroup("setRenderTargets");
  576. flushBatchedDraws();
  577. endPass();
  578. bool iswindow = rts.getFirstTarget().texture == nullptr;
  579. Winding vertexwinding = state.winding;
  580. if (iswindow)
  581. {
  582. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getInternalBackbufferFBO());
  583. // The projection matrix is flipped compared to rendering to a texture,
  584. // due to OpenGL considering (0,0) bottom-left instead of top-left.
  585. projectionMatrix = Matrix4::ortho(0.0, (float) w, (float) h, 0.0, -10.0f, 10.0f);
  586. }
  587. else
  588. {
  589. bindCachedFBO(rts);
  590. projectionMatrix = Matrix4::ortho(0.0, (float) w, 0.0, (float) h, -10.0f, 10.0f);
  591. // Flip front face winding when rendering to a texture, since our
  592. // projection matrix is flipped.
  593. vertexwinding = vertexwinding == WINDING_CW ? WINDING_CCW : WINDING_CW;
  594. }
  595. glFrontFace(vertexwinding == WINDING_CW ? GL_CW : GL_CCW);
  596. gl.setViewport({0, 0, pixelw, pixelh});
  597. // Re-apply the scissor if it was active, since the rectangle passed to
  598. // glScissor is affected by the viewport dimensions.
  599. if (state.scissor)
  600. setScissor(state.scissorRect);
  601. // Make sure the correct sRGB setting is used when drawing to the textures.
  602. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  603. {
  604. if (hasSRGBtexture != gl.isStateEnabled(OpenGL::ENABLE_FRAMEBUFFER_SRGB))
  605. gl.setEnableState(OpenGL::ENABLE_FRAMEBUFFER_SRGB, hasSRGBtexture);
  606. }
  607. }
  608. void Graphics::endPass()
  609. {
  610. auto &rts = states.back().renderTargets;
  611. love::graphics::Texture *depthstencil = rts.depthStencil.texture.get();
  612. // Discard the depth/stencil buffer if we're using an internal cached one.
  613. if (depthstencil == nullptr && (rts.temporaryRTFlags & (TEMPORARY_RT_DEPTH | TEMPORARY_RT_STENCIL)) != 0)
  614. discard({}, true);
  615. else if (!rts.getFirstTarget().texture.get())
  616. discard({}, true); // Backbuffer
  617. // Resolve MSAA buffers. MSAA is only supported for 2D render targets so we
  618. // don't have to worry about resolving to slices.
  619. if (rts.colors.size() > 0 && rts.colors[0].texture->getMSAA() > 1)
  620. {
  621. int mip = rts.colors[0].mipmap;
  622. int w = rts.colors[0].texture->getPixelWidth(mip);
  623. int h = rts.colors[0].texture->getPixelHeight(mip);
  624. for (int i = 0; i < (int) rts.colors.size(); i++)
  625. {
  626. Texture *c = (Texture *) rts.colors[i].texture.get();
  627. if (!c->isReadable())
  628. continue;
  629. glReadBuffer(GL_COLOR_ATTACHMENT0 + i);
  630. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, c->getFBO());
  631. if (GLAD_APPLE_framebuffer_multisample)
  632. glResolveMultisampleFramebufferAPPLE();
  633. else
  634. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  635. }
  636. }
  637. if (depthstencil != nullptr && depthstencil->getMSAA() > 1 && depthstencil->isReadable())
  638. {
  639. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, ((Texture *) depthstencil)->getFBO());
  640. if (GLAD_APPLE_framebuffer_multisample)
  641. glResolveMultisampleFramebufferAPPLE();
  642. else
  643. {
  644. int mip = rts.depthStencil.mipmap;
  645. int w = depthstencil->getPixelWidth(mip);
  646. int h = depthstencil->getPixelHeight(mip);
  647. PixelFormat format = depthstencil->getPixelFormat();
  648. GLbitfield mask = 0;
  649. if (isPixelFormatDepth(format))
  650. mask |= GL_DEPTH_BUFFER_BIT;
  651. if (isPixelFormatStencil(format))
  652. mask |= GL_STENCIL_BUFFER_BIT;
  653. if (mask != 0)
  654. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, mask, GL_NEAREST);
  655. }
  656. }
  657. // generateMipmaps can't be used for depth/stencil textures.
  658. for (const auto &rt : rts.colors)
  659. {
  660. if (rt.texture->getMipmapsMode() == Texture::MIPMAPS_AUTO && rt.mipmap == 0)
  661. rt.texture->generateMipmaps();
  662. }
  663. }
  664. void Graphics::clear(OptionalColorD c, OptionalInt stencil, OptionalDouble depth)
  665. {
  666. if (c.hasValue || stencil.hasValue || depth.hasValue)
  667. flushBatchedDraws();
  668. GLbitfield flags = 0;
  669. if (c.hasValue)
  670. {
  671. Colorf cf((float)c.value.r, (float)c.value.g, (float)c.value.b, (float)c.value.a);
  672. gammaCorrectColor(cf);
  673. glClearColor(cf.r, cf.g, cf.b, cf.a);
  674. flags |= GL_COLOR_BUFFER_BIT;
  675. }
  676. if (stencil.hasValue)
  677. {
  678. glClearStencil(stencil.value);
  679. flags |= GL_STENCIL_BUFFER_BIT;
  680. }
  681. bool hadDepthWrites = gl.hasDepthWrites();
  682. if (depth.hasValue)
  683. {
  684. if (!hadDepthWrites) // glDepthMask also affects glClear.
  685. gl.setDepthWrites(true);
  686. gl.clearDepth(depth.value);
  687. flags |= GL_DEPTH_BUFFER_BIT;
  688. }
  689. if (flags != 0)
  690. glClear(flags);
  691. if (depth.hasValue && !hadDepthWrites)
  692. gl.setDepthWrites(hadDepthWrites);
  693. if (c.hasValue && gl.bugs.clearRequiresDriverTextureStateUpdate && Shader::current)
  694. {
  695. // This seems to be enough to fix the bug for me. Other methods I've
  696. // tried (e.g. dummy draws) don't work in all cases.
  697. gl.useProgram(0);
  698. gl.useProgram((GLuint) Shader::current->getHandle());
  699. }
  700. }
  701. void Graphics::clear(const std::vector<OptionalColorD> &colors, OptionalInt stencil, OptionalDouble depth)
  702. {
  703. if (colors.size() == 0 && !stencil.hasValue && !depth.hasValue)
  704. return;
  705. const auto &rts = states.back().renderTargets.colors;
  706. int ncolorRTs = (int) rts.size();
  707. int ncolors = (int) colors.size();
  708. if (ncolors <= 1 && (ncolorRTs == 0 || (ncolorRTs == 1 && rts[0].texture != nullptr && !isPixelFormatInteger(rts[0].texture->getPixelFormat()))))
  709. {
  710. clear(ncolors > 0 ? colors[0] : OptionalColorD(), stencil, depth);
  711. return;
  712. }
  713. flushBatchedDraws();
  714. bool drawbuffersmodified = false;
  715. ncolors = std::min(ncolors, ncolorRTs);
  716. for (int i = 0; i < ncolors; i++)
  717. {
  718. if (!colors[i].hasValue)
  719. continue;
  720. PixelFormatType datatype = PIXELFORMATTYPE_UNORM;
  721. if (rts[i].texture != nullptr)
  722. datatype = getPixelFormatInfo(rts[i].texture->getPixelFormat()).dataType;
  723. ColorD c = colors[i].value;
  724. if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0)
  725. {
  726. if (datatype == PIXELFORMATTYPE_SINT)
  727. {
  728. const GLint carray[] = {(GLint)c.r, (GLint)c.g, (GLint)c.b, (GLint)c.a};
  729. glClearBufferiv(GL_COLOR, i, carray);
  730. }
  731. else if (datatype == PIXELFORMATTYPE_UINT)
  732. {
  733. const GLuint carray[] = {(GLuint)c.r, (GLuint)c.g, (GLuint)c.b, (GLuint)c.a};
  734. glClearBufferuiv(GL_COLOR, i, carray);
  735. }
  736. else
  737. {
  738. Colorf cf((float)c.r, (float)c.g, (float)c.b, (float)c.a);
  739. gammaCorrectColor(cf);
  740. const GLfloat carray[] = {cf.r, cf.g, cf.b, cf.a};
  741. glClearBufferfv(GL_COLOR, i, carray);
  742. }
  743. }
  744. else
  745. {
  746. Colorf cf((float)c.r, (float)c.g, (float)c.b, (float)c.a);
  747. gammaCorrectColor(cf);
  748. glDrawBuffer(GL_COLOR_ATTACHMENT0 + i);
  749. glClearColor(cf.r, cf.g, cf.b, cf.a);
  750. glClear(GL_COLOR_BUFFER_BIT);
  751. drawbuffersmodified = true;
  752. }
  753. }
  754. // Revert to the expected draw buffers once we're done, if glClearBuffer
  755. // wasn't supported.
  756. if (drawbuffersmodified)
  757. {
  758. GLenum bufs[MAX_COLOR_RENDER_TARGETS];
  759. for (int i = 0; i < ncolorRTs; i++)
  760. bufs[i] = GL_COLOR_ATTACHMENT0 + i;
  761. glDrawBuffers(ncolorRTs, bufs);
  762. }
  763. GLbitfield flags = 0;
  764. if (stencil.hasValue)
  765. {
  766. glClearStencil(stencil.value);
  767. flags |= GL_STENCIL_BUFFER_BIT;
  768. }
  769. bool hadDepthWrites = gl.hasDepthWrites();
  770. if (depth.hasValue)
  771. {
  772. if (!hadDepthWrites) // glDepthMask also affects glClear.
  773. gl.setDepthWrites(true);
  774. gl.clearDepth(depth.value);
  775. flags |= GL_DEPTH_BUFFER_BIT;
  776. }
  777. if (flags != 0)
  778. glClear(flags);
  779. if (depth.hasValue && !hadDepthWrites)
  780. gl.setDepthWrites(hadDepthWrites);
  781. if (gl.bugs.clearRequiresDriverTextureStateUpdate && Shader::current)
  782. {
  783. // This seems to be enough to fix the bug for me. Other methods I've
  784. // tried (e.g. dummy draws) don't work in all cases.
  785. gl.useProgram(0);
  786. gl.useProgram((GLuint) Shader::current->getHandle());
  787. }
  788. }
  789. void Graphics::discard(const std::vector<bool> &colorbuffers, bool depthstencil)
  790. {
  791. flushBatchedDraws();
  792. discard(OpenGL::FRAMEBUFFER_ALL, colorbuffers, depthstencil);
  793. }
  794. void Graphics::discard(OpenGL::FramebufferTarget target, const std::vector<bool> &colorbuffers, bool depthstencil)
  795. {
  796. if (!(GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0 || GLAD_EXT_discard_framebuffer))
  797. return;
  798. GLenum gltarget = GL_FRAMEBUFFER;
  799. if (target == OpenGL::FRAMEBUFFER_READ)
  800. gltarget = GL_READ_FRAMEBUFFER;
  801. else if (target == OpenGL::FRAMEBUFFER_DRAW)
  802. gltarget = GL_DRAW_FRAMEBUFFER;
  803. std::vector<GLenum> attachments;
  804. attachments.reserve(colorbuffers.size());
  805. // glDiscardFramebuffer uses different attachment enums for the default FBO.
  806. if (!isRenderTargetActive() && getInternalBackbufferFBO() == 0)
  807. {
  808. if (colorbuffers.size() > 0 && colorbuffers[0])
  809. attachments.push_back(GL_COLOR);
  810. if (depthstencil)
  811. {
  812. attachments.push_back(GL_STENCIL);
  813. attachments.push_back(GL_DEPTH);
  814. }
  815. }
  816. else
  817. {
  818. int rendertargetcount = std::max((int) states.back().renderTargets.colors.size(), 1);
  819. for (int i = 0; i < (int) colorbuffers.size(); i++)
  820. {
  821. if (colorbuffers[i] && i < rendertargetcount)
  822. attachments.push_back(GL_COLOR_ATTACHMENT0 + i);
  823. }
  824. if (depthstencil)
  825. {
  826. attachments.push_back(GL_STENCIL_ATTACHMENT);
  827. attachments.push_back(GL_DEPTH_ATTACHMENT);
  828. }
  829. }
  830. // Hint for the driver that it doesn't need to save these buffers.
  831. if (GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0)
  832. glInvalidateFramebuffer(gltarget, (GLint) attachments.size(), &attachments[0]);
  833. else if (GLAD_EXT_discard_framebuffer)
  834. glDiscardFramebufferEXT(gltarget, (GLint) attachments.size(), &attachments[0]);
  835. }
  836. void Graphics::cleanupRenderTexture(love::graphics::Texture *texture)
  837. {
  838. if (!texture->isRenderTarget())
  839. return;
  840. for (auto it = framebufferObjects.begin(); it != framebufferObjects.end(); /**/)
  841. {
  842. bool hastexture = false;
  843. const auto &rts = it->first;
  844. for (const RenderTarget &rt : rts.colors)
  845. {
  846. if (rt.texture == texture)
  847. {
  848. hastexture = true;
  849. break;
  850. }
  851. }
  852. hastexture = hastexture || rts.depthStencil.texture == texture;
  853. if (hastexture)
  854. {
  855. if (isCreated())
  856. gl.deleteFramebuffer(it->second);
  857. it = framebufferObjects.erase(it);
  858. }
  859. else
  860. ++it;
  861. }
  862. }
  863. GLuint Graphics::bindCachedFBO(const RenderTargets &targets)
  864. {
  865. GLuint fbo = framebufferObjects[targets];
  866. if (fbo != 0)
  867. {
  868. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  869. }
  870. else
  871. {
  872. int msaa = targets.getFirstTarget().texture->getMSAA();
  873. bool hasDS = targets.depthStencil.texture != nullptr;
  874. glGenFramebuffers(1, &fbo);
  875. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  876. int ncolortargets = 0;
  877. GLenum drawbuffers[MAX_COLOR_RENDER_TARGETS];
  878. auto attachRT = [&](const RenderTarget &rt)
  879. {
  880. bool renderbuffer = msaa > 1 || !rt.texture->isReadable();
  881. bool srgb = false;
  882. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(rt.texture->getPixelFormat(), renderbuffer, srgb);
  883. if (fmt.framebufferAttachments[0] == GL_COLOR_ATTACHMENT0)
  884. {
  885. fmt.framebufferAttachments[0] = GL_COLOR_ATTACHMENT0 + ncolortargets;
  886. drawbuffers[ncolortargets] = fmt.framebufferAttachments[0];
  887. ncolortargets++;
  888. }
  889. GLuint handle = (GLuint) rt.texture->getRenderTargetHandle();
  890. for (GLenum attachment : fmt.framebufferAttachments)
  891. {
  892. if (attachment == GL_NONE)
  893. continue;
  894. else if (renderbuffer)
  895. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, handle);
  896. else
  897. {
  898. TextureType textype = rt.texture->getTextureType();
  899. int layer = textype == TEXTURE_CUBE ? 0 : rt.slice;
  900. int face = textype == TEXTURE_CUBE ? rt.slice : 0;
  901. int level = rt.mipmap;
  902. gl.framebufferTexture(attachment, textype, handle, level, layer, face);
  903. }
  904. }
  905. };
  906. for (const auto &rt : targets.colors)
  907. attachRT(rt);
  908. if (hasDS)
  909. attachRT(targets.depthStencil);
  910. if (ncolortargets > 1)
  911. glDrawBuffers(ncolortargets, drawbuffers);
  912. else if (ncolortargets == 0 && hasDS && (GLAD_ES_VERSION_3_0 || !GLAD_ES_VERSION_2_0))
  913. {
  914. // glDrawBuffers is an ext in GL2. glDrawBuffer doesn't exist in ES3.
  915. GLenum none = GL_NONE;
  916. if (GLAD_ES_VERSION_3_0)
  917. glDrawBuffers(1, &none);
  918. else
  919. glDrawBuffer(GL_NONE);
  920. glReadBuffer(GL_NONE);
  921. }
  922. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  923. if (status != GL_FRAMEBUFFER_COMPLETE)
  924. {
  925. gl.deleteFramebuffer(fbo);
  926. const char *sstr = OpenGL::framebufferStatusString(status);
  927. throw love::Exception("Could not create Framebuffer Object! %s", sstr);
  928. }
  929. framebufferObjects[targets] = fbo;
  930. }
  931. return fbo;
  932. }
  933. void Graphics::present(void *screenshotCallbackData)
  934. {
  935. if (!isActive())
  936. return;
  937. if (isRenderTargetActive())
  938. throw love::Exception("present cannot be called while a render target is active.");
  939. deprecations.draw(this);
  940. flushBatchedDraws();
  941. endPass();
  942. int w = getPixelWidth();
  943. int h = getPixelHeight();
  944. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getInternalBackbufferFBO());
  945. // Copy internal backbuffer to system backbuffer. When MSAA is used this
  946. // is a direct MSAA resolve.
  947. if (internalBackbuffer.get())
  948. {
  949. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, getSystemBackbufferFBO());
  950. // Discard system backbuffer to prevent it from copying its contents
  951. // from VRAM to chip memory.
  952. discard(OpenGL::FRAMEBUFFER_DRAW, {true}, true);
  953. // updateBackbuffer checks for glBlitFramebuffer support.
  954. if (GLAD_APPLE_framebuffer_multisample && internalBackbuffer->getMSAA() > 1)
  955. glResolveMultisampleFramebufferAPPLE();
  956. else
  957. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  958. // Discarding the internal backbuffer directly after resolving it should
  959. // eliminate any copy back to vram it might need to do.
  960. discard(OpenGL::FRAMEBUFFER_READ, {true}, false);
  961. }
  962. if (!pendingScreenshotCallbacks.empty())
  963. {
  964. size_t row = 4 * w;
  965. size_t size = row * h;
  966. GLubyte *pixels = nullptr;
  967. GLubyte *screenshot = nullptr;
  968. try
  969. {
  970. pixels = new GLubyte[size];
  971. screenshot = new GLubyte[size];
  972. }
  973. catch (std::exception &)
  974. {
  975. delete[] pixels;
  976. delete[] screenshot;
  977. throw love::Exception("Out of memory.");
  978. }
  979. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getSystemBackbufferFBO());
  980. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  981. // Replace alpha values with full opacity.
  982. for (size_t i = 3; i < size; i += 4)
  983. pixels[i] = 255;
  984. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  985. GLubyte *src = pixels - row;
  986. GLubyte *dst = screenshot + size;
  987. for (int i = 0; i < h; ++i)
  988. memcpy(dst-=row, src+=row, row);
  989. delete[] pixels;
  990. auto imagemodule = Module::getInstance<love::image::Image>(M_IMAGE);
  991. for (int i = 0; i < (int) pendingScreenshotCallbacks.size(); i++)
  992. {
  993. const auto &info = pendingScreenshotCallbacks[i];
  994. image::ImageData *img = nullptr;
  995. try
  996. {
  997. img = imagemodule->newImageData(w, h, PIXELFORMAT_RGBA8_UNORM, screenshot);
  998. }
  999. catch (love::Exception &)
  1000. {
  1001. delete[] screenshot;
  1002. info.callback(&info, nullptr, nullptr);
  1003. for (int j = i + 1; j < (int) pendingScreenshotCallbacks.size(); j++)
  1004. {
  1005. const auto &ninfo = pendingScreenshotCallbacks[j];
  1006. ninfo.callback(&ninfo, nullptr, nullptr);
  1007. }
  1008. pendingScreenshotCallbacks.clear();
  1009. throw;
  1010. }
  1011. info.callback(&info, img, screenshotCallbackData);
  1012. img->release();
  1013. }
  1014. delete[] screenshot;
  1015. pendingScreenshotCallbacks.clear();
  1016. }
  1017. #ifdef LOVE_IOS
  1018. // Hack: SDL's color renderbuffer must be bound when swapBuffers is called.
  1019. SDL_SysWMinfo info = {};
  1020. SDL_VERSION(&info.version);
  1021. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  1022. glBindRenderbuffer(GL_RENDERBUFFER, info.info.uikit.colorbuffer);
  1023. #endif
  1024. for (StreamBuffer *buffer : batchedDrawState.vb)
  1025. buffer->nextFrame();
  1026. batchedDrawState.indexBuffer->nextFrame();
  1027. auto window = getInstance<love::window::Window>(M_WINDOW);
  1028. if (window != nullptr)
  1029. window->swapBuffers();
  1030. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getInternalBackbufferFBO());
  1031. // Reset the per-frame stat counts.
  1032. drawCalls = 0;
  1033. gl.stats.shaderSwitches = 0;
  1034. renderTargetSwitchCount = 0;
  1035. drawCallsBatched = 0;
  1036. // This assumes temporary textures will only be used within a render pass.
  1037. for (int i = (int) temporaryTextures.size() - 1; i >= 0; i--)
  1038. {
  1039. if (temporaryTextures[i].framesSinceUse >= MAX_TEMPORARY_TEXTURE_UNUSED_FRAMES)
  1040. {
  1041. temporaryTextures[i].texture->release();
  1042. temporaryTextures[i] = temporaryTextures.back();
  1043. temporaryTextures.pop_back();
  1044. }
  1045. else
  1046. temporaryTextures[i].framesSinceUse++;
  1047. }
  1048. }
  1049. int Graphics::getRequestedBackbufferMSAA() const
  1050. {
  1051. return requestedBackbufferMSAA;
  1052. }
  1053. int Graphics::getBackbufferMSAA() const
  1054. {
  1055. return internalBackbuffer.get() ? internalBackbuffer->getMSAA() : 0;
  1056. }
  1057. void Graphics::setScissor(const Rect &rect)
  1058. {
  1059. flushBatchedDraws();
  1060. DisplayState &state = states.back();
  1061. if (!gl.isStateEnabled(OpenGL::ENABLE_SCISSOR_TEST))
  1062. gl.setEnableState(OpenGL::ENABLE_SCISSOR_TEST, true);
  1063. double dpiscale = getCurrentDPIScale();
  1064. Rect glrect;
  1065. glrect.x = (int) (rect.x * dpiscale);
  1066. glrect.y = (int) (rect.y * dpiscale);
  1067. glrect.w = (int) (rect.w * dpiscale);
  1068. glrect.h = (int) (rect.h * dpiscale);
  1069. // OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
  1070. gl.setScissor(glrect, isRenderTargetActive());
  1071. state.scissor = true;
  1072. state.scissorRect = rect;
  1073. }
  1074. void Graphics::setScissor()
  1075. {
  1076. if (states.back().scissor)
  1077. flushBatchedDraws();
  1078. states.back().scissor = false;
  1079. if (gl.isStateEnabled(OpenGL::ENABLE_SCISSOR_TEST))
  1080. gl.setEnableState(OpenGL::ENABLE_SCISSOR_TEST, false);
  1081. }
  1082. void Graphics::drawToStencilBuffer(StencilAction action, int value)
  1083. {
  1084. const auto &rts = states.back().renderTargets;
  1085. love::graphics::Texture *dstexture = rts.depthStencil.texture.get();
  1086. if (!isRenderTargetActive() && !windowHasStencil)
  1087. throw love::Exception("The window must have stenciling enabled to draw to the main screen's stencil buffer.");
  1088. else if (isRenderTargetActive() && (rts.temporaryRTFlags & TEMPORARY_RT_STENCIL) == 0 && (dstexture == nullptr || !isPixelFormatStencil(dstexture->getPixelFormat())))
  1089. throw love::Exception("Drawing to the stencil buffer with a render target active requires either stencil=true or a custom stencil-type texture to be used, in setRenderTarget.");
  1090. flushBatchedDraws();
  1091. writingToStencil = true;
  1092. // Disable color writes but don't save the state for it.
  1093. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1094. GLenum glaction = GL_REPLACE;
  1095. switch (action)
  1096. {
  1097. case STENCIL_REPLACE:
  1098. default:
  1099. glaction = GL_REPLACE;
  1100. break;
  1101. case STENCIL_INCREMENT:
  1102. glaction = GL_INCR;
  1103. break;
  1104. case STENCIL_DECREMENT:
  1105. glaction = GL_DECR;
  1106. break;
  1107. case STENCIL_INCREMENT_WRAP:
  1108. glaction = GL_INCR_WRAP;
  1109. break;
  1110. case STENCIL_DECREMENT_WRAP:
  1111. glaction = GL_DECR_WRAP;
  1112. break;
  1113. case STENCIL_INVERT:
  1114. glaction = GL_INVERT;
  1115. break;
  1116. }
  1117. // The stencil test must be enabled in order to write to the stencil buffer.
  1118. if (!gl.isStateEnabled(OpenGL::ENABLE_STENCIL_TEST))
  1119. gl.setEnableState(OpenGL::ENABLE_STENCIL_TEST, true);
  1120. glStencilFunc(GL_ALWAYS, value, 0xFFFFFFFF);
  1121. glStencilOp(GL_KEEP, GL_KEEP, glaction);
  1122. }
  1123. void Graphics::stopDrawToStencilBuffer()
  1124. {
  1125. if (!writingToStencil)
  1126. return;
  1127. flushBatchedDraws();
  1128. writingToStencil = false;
  1129. const DisplayState &state = states.back();
  1130. // Revert the color write mask.
  1131. setColorMask(state.colorMask);
  1132. // Use the user-set stencil test state when writes are disabled.
  1133. setStencilTest(state.stencilCompare, state.stencilTestValue);
  1134. }
  1135. void Graphics::setStencilTest(CompareMode compare, int value)
  1136. {
  1137. DisplayState &state = states.back();
  1138. if (state.stencilCompare != compare || state.stencilTestValue != value)
  1139. flushBatchedDraws();
  1140. state.stencilCompare = compare;
  1141. state.stencilTestValue = value;
  1142. if (writingToStencil)
  1143. return;
  1144. if (compare == COMPARE_ALWAYS)
  1145. {
  1146. if (gl.isStateEnabled(OpenGL::ENABLE_STENCIL_TEST))
  1147. gl.setEnableState(OpenGL::ENABLE_STENCIL_TEST, false);
  1148. return;
  1149. }
  1150. /**
  1151. * OpenGL / GPUs do the comparison in the opposite way that makes sense
  1152. * for this API. For example, if the compare function is GL_GREATER then the
  1153. * stencil test will pass if the reference value is greater than the value
  1154. * in the stencil buffer. With our API it's more intuitive to assume that
  1155. * setStencilTest(COMPARE_GREATER, 4) will make it pass if the stencil
  1156. * buffer has a value greater than 4.
  1157. **/
  1158. GLenum glcompare = OpenGL::getGLCompareMode(getReversedCompareMode(compare));
  1159. if (!gl.isStateEnabled(OpenGL::ENABLE_STENCIL_TEST))
  1160. gl.setEnableState(OpenGL::ENABLE_STENCIL_TEST, true);
  1161. glStencilFunc(glcompare, value, 0xFFFFFFFF);
  1162. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  1163. }
  1164. void Graphics::setDepthMode(CompareMode compare, bool write)
  1165. {
  1166. DisplayState &state = states.back();
  1167. if (state.depthTest != compare || state.depthWrite != write)
  1168. flushBatchedDraws();
  1169. state.depthTest = compare;
  1170. state.depthWrite = write;
  1171. bool depthenable = compare != COMPARE_ALWAYS || write;
  1172. if (depthenable != gl.isStateEnabled(OpenGL::ENABLE_DEPTH_TEST))
  1173. gl.setEnableState(OpenGL::ENABLE_DEPTH_TEST, depthenable);
  1174. if (depthenable)
  1175. {
  1176. glDepthFunc(OpenGL::getGLCompareMode(compare));
  1177. gl.setDepthWrites(write);
  1178. }
  1179. }
  1180. void Graphics::setFrontFaceWinding(Winding winding)
  1181. {
  1182. DisplayState &state = states.back();
  1183. if (state.winding != winding)
  1184. flushBatchedDraws();
  1185. state.winding = winding;
  1186. if (isRenderTargetActive())
  1187. winding = winding == WINDING_CW ? WINDING_CCW : WINDING_CW;
  1188. glFrontFace(winding == WINDING_CW ? GL_CW : GL_CCW);
  1189. }
  1190. void Graphics::setColor(Colorf c)
  1191. {
  1192. c.r = std::min(std::max(c.r, 0.0f), 1.0f);
  1193. c.g = std::min(std::max(c.g, 0.0f), 1.0f);
  1194. c.b = std::min(std::max(c.b, 0.0f), 1.0f);
  1195. c.a = std::min(std::max(c.a, 0.0f), 1.0f);
  1196. states.back().color = c;
  1197. }
  1198. void Graphics::setColorMask(ColorChannelMask mask)
  1199. {
  1200. flushBatchedDraws();
  1201. glColorMask(mask.r, mask.g, mask.b, mask.a);
  1202. states.back().colorMask = mask;
  1203. }
  1204. void Graphics::setBlendState(const BlendState &blend)
  1205. {
  1206. if (!(blend == states.back().blend))
  1207. flushBatchedDraws();
  1208. if (blend.operationRGB == BLENDOP_MAX || blend.operationA == BLENDOP_MAX
  1209. || blend.operationRGB == BLENDOP_MIN || blend.operationA == BLENDOP_MIN)
  1210. {
  1211. if (!capabilities.features[FEATURE_BLEND_MINMAX])
  1212. throw love::Exception("The 'min' and 'max' blend operations are not supported on this system.");
  1213. }
  1214. if (blend.enable != gl.isStateEnabled(OpenGL::ENABLE_BLEND))
  1215. gl.setEnableState(OpenGL::ENABLE_BLEND, blend.enable);
  1216. if (blend.enable)
  1217. {
  1218. GLenum opRGB = getGLBlendOperation(blend.operationRGB);
  1219. GLenum opA = getGLBlendOperation(blend.operationA);
  1220. GLenum srcRGB = getGLBlendFactor(blend.srcFactorRGB);
  1221. GLenum srcA = getGLBlendFactor(blend.srcFactorA);
  1222. GLenum dstRGB = getGLBlendFactor(blend.dstFactorRGB);
  1223. GLenum dstA = getGLBlendFactor(blend.dstFactorA);
  1224. glBlendEquationSeparate(opRGB, opA);
  1225. glBlendFuncSeparate(srcRGB, dstRGB, srcA, dstA);
  1226. }
  1227. states.back().blend = blend;
  1228. }
  1229. void Graphics::setPointSize(float size)
  1230. {
  1231. if (size != states.back().pointSize)
  1232. flushBatchedDraws();
  1233. states.back().pointSize = size;
  1234. }
  1235. void Graphics::setWireframe(bool enable)
  1236. {
  1237. // Not supported in OpenGL ES.
  1238. if (GLAD_ES_VERSION_2_0)
  1239. return;
  1240. flushBatchedDraws();
  1241. glPolygonMode(GL_FRONT_AND_BACK, enable ? GL_LINE : GL_FILL);
  1242. states.back().wireframe = enable;
  1243. }
  1244. void *Graphics::getBufferMapMemory(size_t size)
  1245. {
  1246. // We don't need anything more complicated because get/release calls are
  1247. // never interleaved (as of when this comment was written.)
  1248. if (bufferMapMemory == nullptr || size > bufferMapMemorySize)
  1249. return malloc(size);
  1250. return bufferMapMemory;
  1251. }
  1252. void Graphics::releaseBufferMapMemory(void *mem)
  1253. {
  1254. if (mem != bufferMapMemory)
  1255. free(mem);
  1256. }
  1257. Graphics::Renderer Graphics::getRenderer() const
  1258. {
  1259. return GLAD_ES_VERSION_2_0 ? RENDERER_OPENGLES : RENDERER_OPENGL;
  1260. }
  1261. Graphics::RendererInfo Graphics::getRendererInfo() const
  1262. {
  1263. RendererInfo info;
  1264. if (GLAD_ES_VERSION_2_0)
  1265. info.name = "OpenGL ES";
  1266. else
  1267. info.name = "OpenGL";
  1268. const char *str = (const char *) glGetString(GL_VERSION);
  1269. if (str)
  1270. info.version = str;
  1271. else
  1272. throw love::Exception("Cannot retrieve renderer version information.");
  1273. str = (const char *) glGetString(GL_VENDOR);
  1274. if (str)
  1275. info.vendor = str;
  1276. else
  1277. throw love::Exception("Cannot retrieve renderer vendor information.");
  1278. str = (const char *) glGetString(GL_RENDERER);
  1279. if (str)
  1280. info.device = str;
  1281. else
  1282. throw love::Exception("Cannot retrieve renderer device information.");
  1283. return info;
  1284. }
  1285. void Graphics::getAPIStats(int &shaderswitches) const
  1286. {
  1287. shaderswitches = gl.stats.shaderSwitches;
  1288. }
  1289. void Graphics::initCapabilities()
  1290. {
  1291. capabilities.features[FEATURE_MULTI_RENDER_TARGET_FORMATS] = gl.isMultiFormatMRTSupported();
  1292. capabilities.features[FEATURE_CLAMP_ZERO] = gl.isClampZeroOneTextureWrapSupported();
  1293. capabilities.features[FEATURE_BLEND_MINMAX] = GLAD_VERSION_1_4 || GLAD_ES_VERSION_3_0 || GLAD_EXT_blend_minmax;
  1294. capabilities.features[FEATURE_LIGHTEN] = capabilities.features[FEATURE_BLEND_MINMAX];
  1295. capabilities.features[FEATURE_FULL_NPOT] = GLAD_VERSION_2_0 || GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot;
  1296. capabilities.features[FEATURE_PIXEL_SHADER_HIGHP] = gl.isPixelShaderHighpSupported();
  1297. capabilities.features[FEATURE_SHADER_DERIVATIVES] = GLAD_VERSION_2_0 || GLAD_ES_VERSION_3_0 || GLAD_OES_standard_derivatives;
  1298. capabilities.features[FEATURE_GLSL3] = GLAD_ES_VERSION_3_0 || gl.isCoreProfile();
  1299. capabilities.features[FEATURE_GLSL4] = GLAD_ES_VERSION_3_1 || (gl.isCoreProfile() && GLAD_VERSION_4_3);
  1300. capabilities.features[FEATURE_INSTANCING] = gl.isInstancingSupported();
  1301. capabilities.features[FEATURE_TEXEL_BUFFER] = gl.isBufferUsageSupported(BUFFERUSAGE_TEXEL);
  1302. capabilities.features[FEATURE_COPY_BUFFER] = gl.isCopyBufferSupported();
  1303. capabilities.features[FEATURE_COPY_BUFFER_TO_TEXTURE] = gl.isCopyBufferToTextureSupported();
  1304. capabilities.features[FEATURE_COPY_TEXTURE_TO_BUFFER] = gl.isCopyTextureToBufferSupported();
  1305. capabilities.features[FEATURE_COPY_RENDER_TARGET_TO_BUFFER] = gl.isCopyRenderTargetToBufferSupported();
  1306. static_assert(FEATURE_MAX_ENUM == 15, "Graphics::initCapabilities must be updated when adding a new graphics feature!");
  1307. capabilities.limits[LIMIT_POINT_SIZE] = gl.getMaxPointSize();
  1308. capabilities.limits[LIMIT_TEXTURE_SIZE] = gl.getMax2DTextureSize();
  1309. capabilities.limits[LIMIT_TEXTURE_LAYERS] = gl.getMaxTextureLayers();
  1310. capabilities.limits[LIMIT_VOLUME_TEXTURE_SIZE] = gl.getMax3DTextureSize();
  1311. capabilities.limits[LIMIT_CUBE_TEXTURE_SIZE] = gl.getMaxCubeTextureSize();
  1312. capabilities.limits[LIMIT_TEXEL_BUFFER_SIZE] = gl.getMaxTexelBufferSize();
  1313. capabilities.limits[LIMIT_SHADER_STORAGE_BUFFER_SIZE] = gl.getMaxShaderStorageBufferSize();
  1314. capabilities.limits[LIMIT_THREADGROUPS_X] = gl.getMaxComputeWorkGroupsX();
  1315. capabilities.limits[LIMIT_THREADGROUPS_Y] = gl.getMaxComputeWorkGroupsY();
  1316. capabilities.limits[LIMIT_THREADGROUPS_Z] = gl.getMaxComputeWorkGroupsZ();
  1317. capabilities.limits[LIMIT_RENDER_TARGETS] = gl.getMaxRenderTargets();
  1318. capabilities.limits[LIMIT_TEXTURE_MSAA] = gl.getMaxSamples();
  1319. capabilities.limits[LIMIT_ANISOTROPY] = gl.getMaxAnisotropy();
  1320. static_assert(LIMIT_MAX_ENUM == 13, "Graphics::initCapabilities must be updated when adding a new system limit!");
  1321. for (int i = 0; i < TEXTURE_MAX_ENUM; i++)
  1322. capabilities.textureTypes[i] = gl.isTextureTypeSupported((TextureType) i);
  1323. }
  1324. PixelFormat Graphics::getSizedFormat(PixelFormat format, bool rendertarget, bool readable) const
  1325. {
  1326. uint32 requiredflags = 0;
  1327. if (rendertarget)
  1328. requiredflags |= PIXELFORMATUSAGEFLAGS_RENDERTARGET;
  1329. if (readable)
  1330. requiredflags |= PIXELFORMATUSAGEFLAGS_SAMPLE;
  1331. switch (format)
  1332. {
  1333. case PIXELFORMAT_NORMAL:
  1334. if (isGammaCorrect())
  1335. return PIXELFORMAT_sRGBA8_UNORM;
  1336. else if ((OpenGL::getPixelFormatUsageFlags(PIXELFORMAT_RGBA8_UNORM) & requiredflags) != requiredflags)
  1337. // 32-bit render targets don't have guaranteed support on GLES2.
  1338. return PIXELFORMAT_RGBA4_UNORM;
  1339. else
  1340. return PIXELFORMAT_RGBA8_UNORM;
  1341. case PIXELFORMAT_HDR:
  1342. return PIXELFORMAT_RGBA16_FLOAT;
  1343. default:
  1344. return format;
  1345. }
  1346. }
  1347. bool Graphics::isPixelFormatSupported(PixelFormat format, PixelFormatUsageFlags usage, bool sRGB)
  1348. {
  1349. if (sRGB && format == PIXELFORMAT_RGBA8_UNORM)
  1350. {
  1351. format = getSRGBPixelFormat(format);
  1352. sRGB = false;
  1353. }
  1354. bool rendertarget = (usage & PIXELFORMATUSAGEFLAGS_RENDERTARGET) != 0;
  1355. bool readable = (usage & PIXELFORMATUSAGEFLAGS_SAMPLE) != 0;
  1356. bool computewrite = (usage & PIXELFORMATUSAGEFLAGS_COMPUTEWRITE) != 0;
  1357. format = getSizedFormat(format, rendertarget, readable);
  1358. OptionalBool &supported = supportedFormats[format][rendertarget ? 1 : 0][readable ? 1 : 0][computewrite ? 1 : 0][sRGB ? 1 : 0];
  1359. if (supported.hasValue)
  1360. return supported.value;
  1361. uint32 supportedflags = OpenGL::getPixelFormatUsageFlags(format);
  1362. if ((usage & supportedflags) != usage)
  1363. {
  1364. supported.set(false);
  1365. return supported.value;
  1366. }
  1367. if (!rendertarget)
  1368. {
  1369. supported.set(true);
  1370. return supported.value;
  1371. }
  1372. // Even though we might have the necessary OpenGL version or extension,
  1373. // drivers are still allowed to throw FRAMEBUFFER_UNSUPPORTED when attaching
  1374. // a texture to a FBO whose format the driver doesn't like. So we should
  1375. // test with an actual FBO.
  1376. GLuint texture = 0;
  1377. GLuint renderbuffer = 0;
  1378. // Avoid the test for depth/stencil formats - not every GL version
  1379. // guarantees support for depth/stencil-only render targets (which we would
  1380. // need for the test below to work), and we already do some finagling in
  1381. // convertPixelFormat to try to use the best-supported internal
  1382. // depth/stencil format for a particular driver.
  1383. if (isPixelFormatDepthStencil(format))
  1384. {
  1385. supported.set(true);
  1386. return true;
  1387. }
  1388. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(format, !readable, sRGB);
  1389. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  1390. GLuint fbo = 0;
  1391. glGenFramebuffers(1, &fbo);
  1392. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  1393. // Make sure at least something is bound to a color attachment. I believe
  1394. // this is required on ES2 but I'm not positive.
  1395. if (isPixelFormatDepthStencil(format))
  1396. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, TEXTURE_2D, gl.getDefaultTexture(TEXTURE_2D, DATA_BASETYPE_FLOAT), 0, 0, 0);
  1397. if (readable)
  1398. {
  1399. glGenTextures(1, &texture);
  1400. gl.bindTextureToUnit(TEXTURE_2D, texture, 0, false);
  1401. SamplerState s;
  1402. s.minFilter = s.magFilter = SamplerState::FILTER_NEAREST;
  1403. gl.setSamplerState(TEXTURE_2D, s);
  1404. gl.rawTexStorage(TEXTURE_2D, 1, format, sRGB, 1, 1);
  1405. }
  1406. else
  1407. {
  1408. glGenRenderbuffers(1, &renderbuffer);
  1409. glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
  1410. glRenderbufferStorage(GL_RENDERBUFFER, fmt.internalformat, 1, 1);
  1411. }
  1412. for (GLenum attachment : fmt.framebufferAttachments)
  1413. {
  1414. if (attachment == GL_NONE)
  1415. continue;
  1416. if (readable)
  1417. gl.framebufferTexture(attachment, TEXTURE_2D, texture, 0, 0, 0);
  1418. else
  1419. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, renderbuffer);
  1420. }
  1421. supported.set(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
  1422. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  1423. gl.deleteFramebuffer(fbo);
  1424. if (texture != 0)
  1425. gl.deleteTexture(texture);
  1426. if (renderbuffer != 0)
  1427. glDeleteRenderbuffers(1, &renderbuffer);
  1428. return supported.value;
  1429. }
  1430. } // opengl
  1431. } // graphics
  1432. } // love