Graphics.cpp 38 KB

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