Graphics.cpp 51 KB

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