Graphics.cpp 37 KB

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