Graphics.cpp 37 KB

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