Graphics.cpp 42 KB

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