Graphics.cpp 45 KB

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