Graphics.cpp 39 KB

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