Graphics.cpp 51 KB

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