Graphics.cpp 38 KB

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