Graphics.cpp 37 KB

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