Graphics.cpp 43 KB

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