Graphics.cpp 51 KB

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