Graphics.cpp 42 KB

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