Graphics.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059
  1. /**
  2. * Copyright (c) 2006-2016 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 "Polyline.h"
  27. #include "math/MathModule.h"
  28. #include "window/Window.h"
  29. #include "libraries/xxHash/xxhash.h"
  30. // C++
  31. #include <vector>
  32. #include <sstream>
  33. #include <algorithm>
  34. #include <iterator>
  35. // C
  36. #include <cmath>
  37. #include <cstdio>
  38. #ifdef LOVE_IOS
  39. #include <SDL_syswm.h>
  40. #endif
  41. namespace love
  42. {
  43. namespace graphics
  44. {
  45. namespace opengl
  46. {
  47. Graphics::Graphics()
  48. : quadIndices(nullptr)
  49. , width(0)
  50. , height(0)
  51. , created(false)
  52. , active(true)
  53. , writingToStencil(false)
  54. , canvasSwitchCount(0)
  55. {
  56. gl = OpenGL();
  57. states.reserve(10);
  58. states.push_back(DisplayState());
  59. auto window = getInstance<love::window::Window>(M_WINDOW);
  60. if (window != nullptr)
  61. {
  62. window->setGraphics(this);
  63. if (window->isOpen())
  64. {
  65. int w = 0, h = 0;
  66. window->getPixelDimensions(w, h);
  67. setMode(w, h);
  68. }
  69. }
  70. }
  71. Graphics::~Graphics()
  72. {
  73. // We do this manually so the graphics objects are released before the window.
  74. states.clear();
  75. defaultFont.set(nullptr);
  76. if (Shader::defaultShader)
  77. {
  78. Shader::defaultShader->release();
  79. Shader::defaultShader = nullptr;
  80. }
  81. if (Shader::defaultVideoShader)
  82. {
  83. Shader::defaultVideoShader->release();
  84. Shader::defaultVideoShader = nullptr;
  85. }
  86. if (quadIndices)
  87. delete quadIndices;
  88. }
  89. const char *Graphics::getName() const
  90. {
  91. return "love.graphics.opengl";
  92. }
  93. void Graphics::restoreState(const DisplayState &s)
  94. {
  95. setColor(s.color);
  96. setBackgroundColor(s.backgroundColor);
  97. setBlendMode(s.blendMode, s.blendAlphaMode);
  98. setLineWidth(s.lineWidth);
  99. setLineStyle(s.lineStyle);
  100. setLineJoin(s.lineJoin);
  101. setPointSize(s.pointSize);
  102. if (s.scissor)
  103. setScissor(s.scissorRect);
  104. else
  105. setScissor();
  106. setStencilTest(s.stencilCompare, s.stencilTestValue);
  107. setFont(s.font.get());
  108. setShader(s.shader.get());
  109. setCanvas(s.canvases);
  110. setColorMask(s.colorMask);
  111. setWireframe(s.wireframe);
  112. setDefaultFilter(s.defaultFilter);
  113. setDefaultMipmapFilter(s.defaultMipmapFilter, s.defaultMipmapSharpness);
  114. }
  115. void Graphics::restoreStateChecked(const DisplayState &s)
  116. {
  117. const DisplayState &cur = states.back();
  118. if (s.color != cur.color)
  119. setColor(s.color);
  120. setBackgroundColor(s.backgroundColor);
  121. if (s.blendMode != cur.blendMode || s.blendAlphaMode != cur.blendAlphaMode)
  122. setBlendMode(s.blendMode, s.blendAlphaMode);
  123. // These are just simple assignments.
  124. setLineWidth(s.lineWidth);
  125. setLineStyle(s.lineStyle);
  126. setLineJoin(s.lineJoin);
  127. if (s.pointSize != cur.pointSize)
  128. setPointSize(s.pointSize);
  129. if (s.scissor != cur.scissor || (s.scissor && !(s.scissorRect == cur.scissorRect)))
  130. {
  131. if (s.scissor)
  132. setScissor(s.scissorRect);
  133. else
  134. setScissor();
  135. }
  136. if (s.stencilCompare != cur.stencilCompare || s.stencilTestValue != cur.stencilTestValue)
  137. setStencilTest(s.stencilCompare, s.stencilTestValue);
  138. setFont(s.font.get());
  139. setShader(s.shader.get());
  140. bool canvaseschanged = s.canvases.size() != cur.canvases.size();
  141. if (!canvaseschanged)
  142. {
  143. for (size_t i = 0; i < s.canvases.size() && i < cur.canvases.size(); i++)
  144. {
  145. if (s.canvases[i].get() != cur.canvases[i].get())
  146. {
  147. canvaseschanged = true;
  148. break;
  149. }
  150. }
  151. }
  152. if (canvaseschanged)
  153. setCanvas(s.canvases);
  154. if (s.colorMask != cur.colorMask)
  155. setColorMask(s.colorMask);
  156. if (s.wireframe != cur.wireframe)
  157. setWireframe(s.wireframe);
  158. setDefaultFilter(s.defaultFilter);
  159. setDefaultMipmapFilter(s.defaultMipmapFilter, s.defaultMipmapSharpness);
  160. }
  161. void Graphics::checkSetDefaultFont()
  162. {
  163. // We don't create or set the default Font if an existing font is in use.
  164. if (states.back().font.get() != nullptr)
  165. return;
  166. // Create a new default font if we don't have one yet.
  167. if (!defaultFont.get())
  168. {
  169. auto fontmodule = Module::getInstance<font::Font>(M_FONT);
  170. if (!fontmodule)
  171. throw love::Exception("Font module has not been loaded.");
  172. auto hinting = font::TrueTypeRasterizer::HINTING_NORMAL;
  173. StrongRef<font::Rasterizer> r(fontmodule->newTrueTypeRasterizer(12, hinting), Acquire::NORETAIN);
  174. defaultFont.set(newFont(r.get()), Acquire::NORETAIN);
  175. }
  176. states.back().font.set(defaultFont.get());
  177. }
  178. void Graphics::setViewportSize(int width, int height)
  179. {
  180. this->width = width;
  181. this->height = height;
  182. if (states.back().canvases.empty())
  183. {
  184. // Set the viewport to top-left corner.
  185. gl.setViewport({0, 0, width, height}, false);
  186. // Set up the projection matrix
  187. gl.matrices.projection = Matrix4::ortho(0.0, (float) width, (float) height, 0.0);
  188. }
  189. }
  190. bool Graphics::setMode(int width, int height)
  191. {
  192. this->width = width;
  193. this->height = height;
  194. // Okay, setup OpenGL.
  195. gl.initContext();
  196. gl.setupContext();
  197. created = true;
  198. // Enable blending
  199. glEnable(GL_BLEND);
  200. // Auto-generated mipmaps should be the best quality possible
  201. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  202. if (!GLAD_ES_VERSION_2_0)
  203. {
  204. // Make sure antialiasing works when set elsewhere
  205. glEnable(GL_MULTISAMPLE);
  206. // Enable texturing
  207. glEnable(GL_TEXTURE_2D);
  208. }
  209. gl.setTextureUnit(0);
  210. // Set pixel row alignment
  211. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  212. // Set whether drawing converts input from linear -> sRGB colorspace.
  213. if (GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_sRGB || GLAD_EXT_framebuffer_sRGB
  214. || GLAD_ES_VERSION_3_0 || GLAD_EXT_sRGB)
  215. {
  216. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  217. gl.setFramebufferSRGB(isGammaCorrect());
  218. }
  219. else
  220. setGammaCorrect(false);
  221. bool enabledebug = false;
  222. if (GLAD_VERSION_3_0)
  223. {
  224. // Enable OpenGL's debug output if a debug context has been created.
  225. GLint flags = 0;
  226. glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
  227. enabledebug = (flags & GL_CONTEXT_FLAG_DEBUG_BIT) != 0;
  228. }
  229. setDebug(enabledebug);
  230. // Reload all volatile objects.
  231. if (!Volatile::loadAll())
  232. ::printf("Could not reload all volatile objects.\n");
  233. // Create a quad indices object owned by love.graphics, so at least one
  234. // QuadIndices object is alive at all times while love.graphics is alive.
  235. // This makes sure there aren't too many expensive destruction/creations of
  236. // index buffer objects, since the shared index buffer used by QuadIndices
  237. // objects is destroyed when the last object is destroyed.
  238. if (quadIndices == nullptr)
  239. quadIndices = new QuadIndices(20);
  240. setViewportSize(width, height);
  241. // Restore the graphics state.
  242. restoreState(states.back());
  243. pixelScaleStack.clear();
  244. pixelScaleStack.reserve(5);
  245. pixelScaleStack.push_back(1);
  246. int gammacorrect = isGammaCorrect() ? 1 : 0;
  247. // We always need a default shader.
  248. if (!Shader::defaultShader)
  249. {
  250. Renderer renderer = GLAD_ES_VERSION_2_0 ? RENDERER_OPENGLES : RENDERER_OPENGL;
  251. Shader::defaultShader = newShader(Shader::defaultCode[renderer][gammacorrect]);
  252. }
  253. // and a default video shader.
  254. if (!Shader::defaultVideoShader)
  255. {
  256. Renderer renderer = GLAD_ES_VERSION_2_0 ? RENDERER_OPENGLES : RENDERER_OPENGL;
  257. Shader::defaultVideoShader = newShader(Shader::defaultVideoCode[renderer][gammacorrect]);
  258. }
  259. // A shader should always be active, but the default shader shouldn't be
  260. // returned by getShader(), so we don't do setShader(defaultShader).
  261. if (!Shader::current)
  262. Shader::defaultShader->attach();
  263. return true;
  264. }
  265. void Graphics::unSetMode()
  266. {
  267. if (!isCreated())
  268. return;
  269. // Unload all volatile objects. These must be reloaded after the display
  270. // mode change.
  271. Volatile::unloadAll();
  272. for (const auto &pair : framebufferObjects)
  273. gl.deleteFramebuffer(pair.second);
  274. for (const CachedRenderbuffer &rb : stencilBuffers)
  275. glDeleteRenderbuffers(1, &rb.renderbuffer);
  276. framebufferObjects.clear();
  277. stencilBuffers.clear();
  278. gl.deInitContext();
  279. created = false;
  280. }
  281. void Graphics::setActive(bool enable)
  282. {
  283. // Make sure all pending OpenGL commands have fully executed before
  284. // returning, when going from active to inactive. This is required on iOS.
  285. if (isCreated() && this->active && !enable)
  286. glFinish();
  287. active = enable;
  288. }
  289. bool Graphics::isActive() const
  290. {
  291. // The graphics module is only completely 'active' if there's a window, a
  292. // context, and the active variable is set.
  293. auto window = getInstance<love::window::Window>(M_WINDOW);
  294. return active && isCreated() && window != nullptr && window->isOpen();
  295. }
  296. static void APIENTRY debugCB(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei /*len*/, const GLchar *msg, const GLvoid* /*usr*/)
  297. {
  298. // Human-readable strings for the debug info.
  299. const char *sourceStr = OpenGL::debugSourceString(source);
  300. const char *typeStr = OpenGL::debugTypeString(type);
  301. const char *severityStr = OpenGL::debugSeverityString(severity);
  302. const char *fmt = "OpenGL: %s [source=%s, type=%s, severity=%s, id=%d]\n";
  303. printf(fmt, msg, sourceStr, typeStr, severityStr, id);
  304. }
  305. void Graphics::setDebug(bool enable)
  306. {
  307. // Make sure debug output is supported. The AMD ext. is a bit different
  308. // so we don't make use of it, since AMD drivers now support KHR_debug.
  309. if (!(GLAD_VERSION_4_3 || GLAD_KHR_debug || GLAD_ARB_debug_output))
  310. return;
  311. // TODO: We don't support GL_KHR_debug in GLES yet.
  312. if (GLAD_ES_VERSION_2_0)
  313. return;
  314. // Ugly hack to reduce code duplication.
  315. if (GLAD_ARB_debug_output && !(GLAD_VERSION_4_3 || GLAD_KHR_debug))
  316. {
  317. fp_glDebugMessageCallback = (pfn_glDebugMessageCallback) fp_glDebugMessageCallbackARB;
  318. fp_glDebugMessageControl = (pfn_glDebugMessageControl) fp_glDebugMessageControlARB;
  319. }
  320. if (!enable)
  321. {
  322. // Disable the debug callback function.
  323. glDebugMessageCallback(nullptr, nullptr);
  324. // We can disable debug output entirely with KHR_debug.
  325. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  326. glDisable(GL_DEBUG_OUTPUT);
  327. return;
  328. }
  329. // We don't want asynchronous debug output.
  330. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  331. glDebugMessageCallback(debugCB, nullptr);
  332. // Initially, enable everything.
  333. glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
  334. // Disable messages about deprecated OpenGL functionality.
  335. glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  336. glDebugMessageControl(GL_DEBUG_SOURCE_SHADER_COMPILER, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  337. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  338. glEnable(GL_DEBUG_OUTPUT);
  339. ::printf("OpenGL debug output enabled (LOVE_GRAPHICS_DEBUG=1)\n");
  340. }
  341. void Graphics::reset()
  342. {
  343. DisplayState s;
  344. stopDrawToStencilBuffer();
  345. restoreState(s);
  346. origin();
  347. }
  348. void Graphics::setCanvas(Canvas *canvas)
  349. {
  350. if (canvas == nullptr)
  351. return setCanvas();
  352. std::vector<Canvas *> canvases = {canvas};
  353. setCanvas(canvases);
  354. }
  355. void Graphics::setCanvas(const std::vector<Canvas *> &canvases)
  356. {
  357. DisplayState &state = states.back();
  358. int ncanvases = (int) canvases.size();
  359. if (ncanvases == 0)
  360. return setCanvas();
  361. if (ncanvases == (int) state.canvases.size())
  362. {
  363. bool modified = false;
  364. for (int i = 0; i < ncanvases; i++)
  365. {
  366. if (canvases[i] != state.canvases[i].get())
  367. {
  368. modified = true;
  369. break;
  370. }
  371. }
  372. if (!modified)
  373. return;
  374. }
  375. if (ncanvases > gl.getMaxRenderTargets())
  376. throw love::Exception("This system can't simultaneously render to %d canvases.", ncanvases);
  377. Canvas *firstcanvas = canvases[0];
  378. bool multiformatsupported = Canvas::isMultiFormatMultiCanvasSupported();
  379. PixelFormat firstformat = firstcanvas->getPixelFormat();
  380. bool hasSRGBcanvas = firstformat == PIXELFORMAT_sRGBA8;
  381. for (int i = 1; i < ncanvases; i++)
  382. {
  383. Canvas *c = canvases[i];
  384. if (c->getWidth() != firstcanvas->getWidth() || c->getHeight() != firstcanvas->getHeight())
  385. throw love::Exception("All canvases in must have the same dimensions.");
  386. if (!multiformatsupported && c->getPixelFormat() != firstformat)
  387. throw love::Exception("This system doesn't support multi-canvas rendering with different canvas formats.");
  388. if (c->getRequestedMSAA() != firstcanvas->getRequestedMSAA())
  389. throw love::Exception("All Canvases in must have the same requested MSAA value.");
  390. if (c->getPixelFormat() == PIXELFORMAT_sRGBA8)
  391. hasSRGBcanvas = true;
  392. }
  393. OpenGL::TempDebugGroup debuggroup("setCanvas(...)");
  394. endPass();
  395. bindCachedFBO(canvases);
  396. int w = firstcanvas->getWidth();
  397. int h = firstcanvas->getHeight();
  398. gl.setViewport({0, 0, w, h}, true);
  399. gl.matrices.projection = Matrix4::ortho(0.0, (float) w, 0.0, (float) h);
  400. // Make sure the correct sRGB setting is used when drawing to the canvases.
  401. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  402. {
  403. if (hasSRGBcanvas && !gl.hasFramebufferSRGB())
  404. gl.setFramebufferSRGB(true);
  405. else if (!hasSRGBcanvas && gl.hasFramebufferSRGB())
  406. gl.setFramebufferSRGB(false);
  407. }
  408. std::vector<StrongRef<Canvas>> canvasrefs;
  409. canvasrefs.reserve(canvases.size());
  410. for (Canvas *c : canvases)
  411. canvasrefs.push_back(c);
  412. std::swap(state.canvases, canvasrefs);
  413. canvasSwitchCount++;
  414. }
  415. void Graphics::setCanvas(const std::vector<StrongRef<Canvas>> &canvases)
  416. {
  417. std::vector<Canvas *> canvaslist;
  418. canvaslist.reserve(canvases.size());
  419. for (const StrongRef<Canvas> &c : canvases)
  420. canvaslist.push_back(c.get());
  421. return setCanvas(canvaslist);
  422. }
  423. void Graphics::setCanvas()
  424. {
  425. DisplayState &state = states.back();
  426. if (state.canvases.empty())
  427. return;
  428. OpenGL::TempDebugGroup debuggroup("setCanvas()");
  429. endPass();
  430. state.canvases.clear();
  431. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, gl.getDefaultFBO());
  432. gl.setViewport({0, 0, width, height}, false);
  433. // The projection matrix is flipped compared to rendering to a canvas, due
  434. // to OpenGL considering (0,0) bottom-left instead of top-left.
  435. gl.matrices.projection = Matrix4::ortho(0.0, (float) width, (float) height, 0.0);
  436. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  437. {
  438. if (isGammaCorrect() && !gl.hasFramebufferSRGB())
  439. gl.setFramebufferSRGB(true);
  440. else if (!isGammaCorrect() && gl.hasFramebufferSRGB())
  441. gl.setFramebufferSRGB(false);
  442. }
  443. canvasSwitchCount++;
  444. }
  445. std::vector<Canvas *> Graphics::getCanvas() const
  446. {
  447. std::vector<Canvas *> canvases;
  448. canvases.reserve(states.back().canvases.size());
  449. for (const StrongRef<Canvas> &c : states.back().canvases)
  450. canvases.push_back(c.get());
  451. return canvases;
  452. }
  453. void Graphics::endPass()
  454. {
  455. // Discard the stencil buffer.
  456. discard({}, true);
  457. auto &canvases = states.back().canvases;
  458. // Resolve MSAA buffers.
  459. if (canvases.size() > 0 && canvases[0]->getMSAA() > 1)
  460. {
  461. int w = canvases[0]->getWidth();
  462. int h = canvases[0]->getHeight();
  463. for (int i = 0; i < (int) canvases.size(); i++)
  464. {
  465. glReadBuffer(GL_COLOR_ATTACHMENT0 + i);
  466. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, canvases[i]->getFBO());
  467. if (GLAD_APPLE_framebuffer_multisample)
  468. glResolveMultisampleFramebufferAPPLE();
  469. else
  470. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  471. }
  472. }
  473. }
  474. void Graphics::clear(Colorf c)
  475. {
  476. gammaCorrectColor(c);
  477. glClearColor(c.r, c.g, c.b, c.a);
  478. glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  479. if (gl.bugs.clearRequiresDriverTextureStateUpdate && Shader::current)
  480. {
  481. // This seems to be enough to fix the bug for me. Other methods I've
  482. // tried (e.g. dummy draws) don't work in all cases.
  483. gl.useProgram(0);
  484. gl.useProgram(Shader::current->getProgram());
  485. }
  486. }
  487. void Graphics::clear(const std::vector<OptionalColorf> &colors)
  488. {
  489. if (colors.size() == 0)
  490. return;
  491. int ncanvases = (int) states.back().canvases.size();
  492. int ncolors = std::min((int) colors.size(), ncanvases);
  493. if (ncolors <= 1 && ncanvases <= 1)
  494. {
  495. if (colors[0].enabled)
  496. clear(colors[0].c);
  497. return;
  498. }
  499. bool drawbuffersmodified = false;
  500. for (int i = 0; i < ncolors; i++)
  501. {
  502. if (!colors[i].enabled)
  503. continue;
  504. Colorf c = colors[i].c;
  505. gammaCorrectColor(c);
  506. if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0)
  507. {
  508. const GLfloat carray[] = {c.r, c.g, c.b, c.a};
  509. glClearBufferfv(GL_COLOR, i, carray);
  510. }
  511. else
  512. {
  513. glDrawBuffer(GL_COLOR_ATTACHMENT0 + i);
  514. glClearColor(c.r, c.g, c.b, c.a);
  515. glClear(GL_COLOR_BUFFER_BIT);
  516. drawbuffersmodified = true;
  517. }
  518. }
  519. // Revert to the expected draw buffers once we're done, if glClearBuffer
  520. // wasn't supported.
  521. if (drawbuffersmodified)
  522. {
  523. GLenum bufs[MAX_COLOR_RENDER_TARGETS];
  524. for (int i = 0; i < ncanvases; i++)
  525. bufs[i] = GL_COLOR_ATTACHMENT0 + i;
  526. glDrawBuffers(ncanvases, bufs);
  527. }
  528. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  529. if (gl.bugs.clearRequiresDriverTextureStateUpdate && Shader::current)
  530. {
  531. // This seems to be enough to fix the bug for me. Other methods I've
  532. // tried (e.g. dummy draws) don't work in all cases.
  533. gl.useProgram(0);
  534. gl.useProgram(Shader::current->getProgram());
  535. }
  536. }
  537. bool Graphics::isCanvasActive() const
  538. {
  539. return !states.back().canvases.empty();
  540. }
  541. bool Graphics::isCanvasActive(Canvas *canvas) const
  542. {
  543. for (const auto &c : states.back().canvases)
  544. {
  545. if (c.get() == canvas)
  546. return true;
  547. }
  548. return false;
  549. }
  550. void Graphics::discard(const std::vector<bool> &colorbuffers, bool depthstencil)
  551. {
  552. discard(OpenGL::FRAMEBUFFER_ALL, colorbuffers, depthstencil);
  553. }
  554. void Graphics::discard(OpenGL::FramebufferTarget target, const std::vector<bool> &colorbuffers, bool depthstencil)
  555. {
  556. if (!(GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0 || GLAD_EXT_discard_framebuffer))
  557. return;
  558. GLenum gltarget = GL_FRAMEBUFFER;
  559. if (target == OpenGL::FRAMEBUFFER_READ)
  560. gltarget = GL_READ_FRAMEBUFFER;
  561. else if (target == OpenGL::FRAMEBUFFER_DRAW)
  562. gltarget = GL_DRAW_FRAMEBUFFER;
  563. std::vector<GLenum> attachments;
  564. attachments.reserve(colorbuffers.size());
  565. // glDiscardFramebuffer uses different attachment enums for the default FBO.
  566. if (states.back().canvases.empty() && gl.getDefaultFBO() == 0)
  567. {
  568. if (colorbuffers.size() > 0 && colorbuffers[0])
  569. attachments.push_back(GL_COLOR);
  570. if (depthstencil)
  571. {
  572. attachments.push_back(GL_STENCIL);
  573. attachments.push_back(GL_DEPTH);
  574. }
  575. }
  576. else
  577. {
  578. int rendertargetcount = std::max((int) states.back().canvases.size(), 1);
  579. for (int i = 0; i < (int) colorbuffers.size(); i++)
  580. {
  581. if (colorbuffers[i] && i < rendertargetcount)
  582. attachments.push_back(GL_COLOR_ATTACHMENT0 + i);
  583. }
  584. if (depthstencil)
  585. {
  586. attachments.push_back(GL_STENCIL_ATTACHMENT);
  587. attachments.push_back(GL_DEPTH_ATTACHMENT);
  588. }
  589. }
  590. // Hint for the driver that it doesn't need to save these buffers.
  591. if (GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0)
  592. glInvalidateFramebuffer(gltarget, (GLint) attachments.size(), &attachments[0]);
  593. else if (GLAD_EXT_discard_framebuffer)
  594. glDiscardFramebufferEXT(gltarget, (GLint) attachments.size(), &attachments[0]);
  595. }
  596. void Graphics::bindCachedFBO(const std::vector<Canvas *> &canvases)
  597. {
  598. int ncanvases = (int) canvases.size();
  599. uint32 hash = XXH32(&canvases[0], sizeof(Canvas *) * ncanvases, 0);
  600. GLuint fbo = framebufferObjects[hash];
  601. if (fbo != 0)
  602. {
  603. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  604. }
  605. else
  606. {
  607. int w = canvases[0]->getWidth();
  608. int h = canvases[0]->getHeight();
  609. int msaa = std::max(canvases[0]->getMSAA(), 1);
  610. glGenFramebuffers(1, &fbo);
  611. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  612. GLenum drawbuffers[MAX_COLOR_RENDER_TARGETS];
  613. for (int i = 0; i < ncanvases; i++)
  614. {
  615. drawbuffers[i] = GL_COLOR_ATTACHMENT0 + i;
  616. if (msaa > 1)
  617. {
  618. GLuint rbo = (GLuint) canvases[i]->getMSAAHandle();
  619. glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffers[i], GL_RENDERBUFFER, rbo);
  620. }
  621. else
  622. {
  623. GLuint tex = *(GLuint *) canvases[i]->getHandle();
  624. glFramebufferTexture2D(GL_FRAMEBUFFER, drawbuffers[i], GL_TEXTURE_2D, tex, 0);
  625. }
  626. }
  627. if (ncanvases > 1)
  628. glDrawBuffers(ncanvases, drawbuffers);
  629. GLuint stencil = attachCachedStencilBuffer(w, h, canvases[0]->getRequestedMSAA());
  630. if (stencil == 0)
  631. {
  632. gl.deleteFramebuffer(fbo);
  633. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, gl.getDefaultFBO());
  634. throw love::Exception("Could not create stencil buffer!");
  635. }
  636. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  637. if (status != GL_FRAMEBUFFER_COMPLETE)
  638. {
  639. gl.deleteFramebuffer(fbo);
  640. const char *sstr = OpenGL::framebufferStatusString(status);
  641. throw love::Exception("Could not create Framebuffer Object! %s", sstr);
  642. }
  643. framebufferObjects[hash] = fbo;
  644. }
  645. }
  646. GLuint Graphics::attachCachedStencilBuffer(int w, int h, int samples)
  647. {
  648. samples = samples == 1 ? 0 : samples;
  649. for (const CachedRenderbuffer &rb : stencilBuffers)
  650. {
  651. if (rb.w == w && rb.h == h && rb.samples == samples)
  652. {
  653. // Attach the buffer to the framebuffer object.
  654. for (GLenum attachment : rb.attachments)
  655. {
  656. if (attachment != GL_NONE)
  657. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, rb.renderbuffer);
  658. }
  659. return rb.renderbuffer;
  660. }
  661. }
  662. OpenGL::TempDebugGroup debuggroup("Create cached stencil buffer");
  663. CachedRenderbuffer rb;
  664. rb.w = w;
  665. rb.h = h;
  666. rb.samples = samples;
  667. rb.attachments[0] = GL_STENCIL_ATTACHMENT;
  668. rb.attachments[1] = GL_NONE;
  669. GLenum format = GL_STENCIL_INDEX8;
  670. // Prefer a combined depth/stencil buffer.
  671. if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_object)
  672. {
  673. format = GL_DEPTH24_STENCIL8;
  674. rb.attachments[0] = GL_DEPTH_STENCIL_ATTACHMENT;
  675. }
  676. else if (GLAD_EXT_packed_depth_stencil || GLAD_OES_packed_depth_stencil)
  677. {
  678. format = GL_DEPTH24_STENCIL8;
  679. rb.attachments[0] = GL_DEPTH_ATTACHMENT;
  680. rb.attachments[1] = GL_STENCIL_ATTACHMENT;
  681. }
  682. glGenRenderbuffers(1, &rb.renderbuffer);
  683. glBindRenderbuffer(GL_RENDERBUFFER, rb.renderbuffer);
  684. if (rb.samples > 1)
  685. glRenderbufferStorageMultisample(GL_RENDERBUFFER, rb.samples, format, rb.w, rb.h);
  686. else
  687. glRenderbufferStorage(GL_RENDERBUFFER, format, rb.w, rb.h);
  688. // Attach the buffer to the framebuffer object.
  689. for (GLenum attachment : rb.attachments)
  690. {
  691. if (attachment != GL_NONE)
  692. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, rb.renderbuffer);
  693. }
  694. glBindRenderbuffer(GL_RENDERBUFFER, 0);
  695. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  696. {
  697. glDeleteRenderbuffers(1, &rb.renderbuffer);
  698. rb.renderbuffer = 0;
  699. }
  700. if (rb.renderbuffer != 0)
  701. {
  702. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  703. stencilBuffers.push_back(rb);
  704. }
  705. return rb.renderbuffer;
  706. }
  707. void Graphics::captureScreenshot(const ScreenshotInfo &info)
  708. {
  709. pendingScreenshotCallbacks.push_back(info);
  710. }
  711. void Graphics::present(void *screenshotCallbackData)
  712. {
  713. if (!isActive())
  714. return;
  715. if (!states.back().canvases.empty())
  716. throw love::Exception("present cannot be called while a Canvas is active.");
  717. endPass();
  718. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, gl.getDefaultFBO());
  719. if (!pendingScreenshotCallbacks.empty())
  720. {
  721. int w = getWidth();
  722. int h = getHeight();
  723. size_t row = 4 * w;
  724. size_t size = row * h;
  725. GLubyte *pixels = nullptr;
  726. GLubyte *screenshot = nullptr;
  727. try
  728. {
  729. pixels = new GLubyte[size];
  730. screenshot = new GLubyte[size];
  731. }
  732. catch (std::exception &)
  733. {
  734. delete[] pixels;
  735. delete[] screenshot;
  736. throw love::Exception("Out of memory.");
  737. }
  738. #ifdef LOVE_IOS
  739. SDL_SysWMinfo info = {};
  740. SDL_VERSION(&info.version);
  741. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  742. if (info.info.uikit.resolveFramebuffer != 0)
  743. {
  744. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, info.info.uikit.resolveFramebuffer);
  745. // We need to do an explicit MSAA resolve on iOS, because it uses GLES
  746. // FBOs rather than a system framebuffer.
  747. if (GLAD_ES_VERSION_3_0)
  748. glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  749. else if (GLAD_APPLE_framebuffer_multisample)
  750. glResolveMultisampleFramebufferAPPLE();
  751. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_READ, info.info.uikit.resolveFramebuffer);
  752. }
  753. #endif
  754. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  755. // Replace alpha values with full opacity.
  756. for (size_t i = 3; i < size; i += 4)
  757. pixels[i] = 255;
  758. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  759. GLubyte *src = pixels - row;
  760. GLubyte *dst = screenshot + size;
  761. for (int i = 0; i < h; ++i)
  762. memcpy(dst-=row, src+=row, row);
  763. delete[] pixels;
  764. auto imagemodule = Module::getInstance<love::image::Image>(M_IMAGE);
  765. for (int i = 0; i < (int) pendingScreenshotCallbacks.size(); i++)
  766. {
  767. const auto &info = pendingScreenshotCallbacks[i];
  768. image::ImageData *img = nullptr;
  769. try
  770. {
  771. img = imagemodule->newImageData(w, h, PIXELFORMAT_RGBA8, screenshot);
  772. }
  773. catch (love::Exception &)
  774. {
  775. delete[] screenshot;
  776. info.callback(nullptr, info.ref, nullptr);
  777. for (int j = i + 1; j < (int) pendingScreenshotCallbacks.size(); j++)
  778. {
  779. const auto &ninfo = pendingScreenshotCallbacks[j];
  780. ninfo.callback(nullptr, ninfo.ref, nullptr);
  781. }
  782. pendingScreenshotCallbacks.clear();
  783. throw;
  784. }
  785. info.callback(img, info.ref, screenshotCallbackData);
  786. img->release();
  787. }
  788. delete[] screenshot;
  789. pendingScreenshotCallbacks.clear();
  790. }
  791. #ifdef LOVE_IOS
  792. // Hack: SDL's color renderbuffer must be bound when swapBuffers is called.
  793. SDL_SysWMinfo info = {};
  794. SDL_VERSION(&info.version);
  795. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  796. glBindRenderbuffer(GL_RENDERBUFFER, info.info.uikit.colorbuffer);
  797. #endif
  798. auto window = getInstance<love::window::Window>(M_WINDOW);
  799. if (window != nullptr)
  800. window->swapBuffers();
  801. // Reset the per-frame stat counts.
  802. gl.stats.drawCalls = 0;
  803. gl.stats.shaderSwitches = 0;
  804. canvasSwitchCount = 0;
  805. }
  806. int Graphics::getWidth() const
  807. {
  808. return width;
  809. }
  810. int Graphics::getHeight() const
  811. {
  812. return height;
  813. }
  814. bool Graphics::isCreated() const
  815. {
  816. return created;
  817. }
  818. void Graphics::setScissor(const Rect &rect)
  819. {
  820. DisplayState &state = states.back();
  821. glEnable(GL_SCISSOR_TEST);
  822. // OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
  823. gl.setScissor(rect, !state.canvases.empty());
  824. state.scissor = true;
  825. state.scissorRect = rect;
  826. }
  827. void Graphics::intersectScissor(const Rect &rect)
  828. {
  829. Rect currect = states.back().scissorRect;
  830. if (!states.back().scissor)
  831. {
  832. currect.x = 0;
  833. currect.y = 0;
  834. currect.w = std::numeric_limits<int>::max();
  835. currect.h = std::numeric_limits<int>::max();
  836. }
  837. int x1 = std::max(currect.x, rect.x);
  838. int y1 = std::max(currect.y, rect.y);
  839. int x2 = std::min(currect.x + currect.w, rect.x + rect.w);
  840. int y2 = std::min(currect.y + currect.h, rect.y + rect.h);
  841. Rect newrect = {x1, y1, std::max(0, x2 - x1), std::max(0, y2 - y1)};
  842. setScissor(newrect);
  843. }
  844. void Graphics::setScissor()
  845. {
  846. states.back().scissor = false;
  847. glDisable(GL_SCISSOR_TEST);
  848. }
  849. bool Graphics::getScissor(Rect &rect) const
  850. {
  851. const DisplayState &state = states.back();
  852. rect = state.scissorRect;
  853. return state.scissor;
  854. }
  855. void Graphics::drawToStencilBuffer(StencilAction action, int value)
  856. {
  857. writingToStencil = true;
  858. // Disable color writes but don't save the state for it.
  859. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  860. GLenum glaction = GL_REPLACE;
  861. switch (action)
  862. {
  863. case STENCIL_REPLACE:
  864. default:
  865. glaction = GL_REPLACE;
  866. break;
  867. case STENCIL_INCREMENT:
  868. glaction = GL_INCR;
  869. break;
  870. case STENCIL_DECREMENT:
  871. glaction = GL_DECR;
  872. break;
  873. case STENCIL_INCREMENT_WRAP:
  874. glaction = GL_INCR_WRAP;
  875. break;
  876. case STENCIL_DECREMENT_WRAP:
  877. glaction = GL_DECR_WRAP;
  878. break;
  879. case STENCIL_INVERT:
  880. glaction = GL_INVERT;
  881. break;
  882. }
  883. // The stencil test must be enabled in order to write to the stencil buffer.
  884. glEnable(GL_STENCIL_TEST);
  885. glStencilFunc(GL_ALWAYS, value, 0xFFFFFFFF);
  886. glStencilOp(GL_KEEP, GL_KEEP, glaction);
  887. }
  888. void Graphics::stopDrawToStencilBuffer()
  889. {
  890. if (!writingToStencil)
  891. return;
  892. writingToStencil = false;
  893. const DisplayState &state = states.back();
  894. // Revert the color write mask.
  895. setColorMask(state.colorMask);
  896. // Use the user-set stencil test state when writes are disabled.
  897. setStencilTest(state.stencilCompare, state.stencilTestValue);
  898. }
  899. void Graphics::setStencilTest(CompareMode compare, int value)
  900. {
  901. DisplayState &state = states.back();
  902. state.stencilCompare = compare;
  903. state.stencilTestValue = value;
  904. if (writingToStencil)
  905. return;
  906. if (compare == COMPARE_ALWAYS)
  907. {
  908. glDisable(GL_STENCIL_TEST);
  909. return;
  910. }
  911. GLenum glcompare = GL_EQUAL;
  912. /**
  913. * Q: Why are some of the compare modes inverted (e.g. COMPARE_LESS becomes
  914. * GL_GREATER)?
  915. *
  916. * A: OpenGL / GPUs do the comparison in the opposite way that makes sense
  917. * for this API. For example, if the compare function is GL_GREATER then the
  918. * stencil test will pass if the reference value is greater than the value
  919. * in the stencil buffer. With our API it's more intuitive to assume that
  920. * setStencilTest(COMPARE_GREATER, 4) will make it pass if the stencil
  921. * buffer has a value greater than 4.
  922. **/
  923. switch (compare)
  924. {
  925. case COMPARE_LESS:
  926. glcompare = GL_GREATER;
  927. break;
  928. case COMPARE_LEQUAL:
  929. glcompare = GL_GEQUAL;
  930. break;
  931. case COMPARE_EQUAL:
  932. default:
  933. glcompare = GL_EQUAL;
  934. break;
  935. case COMPARE_GEQUAL:
  936. glcompare = GL_LEQUAL;
  937. break;
  938. case COMPARE_GREATER:
  939. glcompare = GL_LESS;
  940. break;
  941. case COMPARE_NOTEQUAL:
  942. glcompare = GL_NOTEQUAL;
  943. break;
  944. case COMPARE_ALWAYS:
  945. glcompare = GL_ALWAYS;
  946. break;
  947. }
  948. glEnable(GL_STENCIL_TEST);
  949. glStencilFunc(glcompare, value, 0xFFFFFFFF);
  950. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  951. }
  952. void Graphics::setStencilTest()
  953. {
  954. setStencilTest(COMPARE_ALWAYS, 0);
  955. }
  956. void Graphics::getStencilTest(CompareMode &compare, int &value)
  957. {
  958. const DisplayState &state = states.back();
  959. compare = state.stencilCompare;
  960. value = state.stencilTestValue;
  961. }
  962. void Graphics::clearStencil()
  963. {
  964. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  965. }
  966. Image *Graphics::newImage(const std::vector<love::image::ImageData *> &data, const Image::Flags &flags)
  967. {
  968. return new Image(data, flags);
  969. }
  970. Image *Graphics::newImage(const std::vector<love::image::CompressedImageData *> &cdata, const Image::Flags &flags)
  971. {
  972. return new Image(cdata, flags);
  973. }
  974. Quad *Graphics::newQuad(Quad::Viewport v, double sw, double sh)
  975. {
  976. return new Quad(v, sw, sh);
  977. }
  978. Font *Graphics::newFont(love::font::Rasterizer *r, const Texture::Filter &filter)
  979. {
  980. return new Font(r, filter);
  981. }
  982. SpriteBatch *Graphics::newSpriteBatch(Texture *texture, int size, Mesh::Usage usage)
  983. {
  984. return new SpriteBatch(texture, size, usage);
  985. }
  986. ParticleSystem *Graphics::newParticleSystem(Texture *texture, int size)
  987. {
  988. return new ParticleSystem(texture, size);
  989. }
  990. Canvas *Graphics::newCanvas(int width, int height, PixelFormat format, int msaa)
  991. {
  992. if (!Canvas::isSupported())
  993. throw love::Exception("Canvases are not supported by your OpenGL drivers!");
  994. if (!Canvas::isFormatSupported(format))
  995. {
  996. const char *fstr = "rgba8";
  997. love::getConstant(Canvas::getSizedFormat(format), fstr);
  998. throw love::Exception("The %s canvas format is not supported by your OpenGL drivers.", fstr);
  999. }
  1000. if (width > gl.getMaxTextureSize())
  1001. throw Exception("Cannot create canvas: width of %d pixels is too large for this system.", width);
  1002. else if (height > gl.getMaxTextureSize())
  1003. throw Exception("Cannot create canvas: height of %d pixels is too large for this system.", height);
  1004. Canvas *canvas = new Canvas(width, height, format, msaa);
  1005. GLenum err = canvas->getStatus();
  1006. // everything ok, return canvas (early out)
  1007. if (err == GL_FRAMEBUFFER_COMPLETE)
  1008. return canvas;
  1009. canvas->release();
  1010. throw love::Exception("Cannot create Canvas: %s", OpenGL::framebufferStatusString(err));
  1011. return nullptr; // never reached
  1012. }
  1013. Shader *Graphics::newShader(const Shader::ShaderSource &source)
  1014. {
  1015. return new Shader(source);
  1016. }
  1017. Mesh *Graphics::newMesh(const std::vector<Vertex> &vertices, Mesh::DrawMode drawmode, Mesh::Usage usage)
  1018. {
  1019. return new Mesh(vertices, drawmode, usage);
  1020. }
  1021. Mesh *Graphics::newMesh(int vertexcount, Mesh::DrawMode drawmode, Mesh::Usage usage)
  1022. {
  1023. return new Mesh(vertexcount, drawmode, usage);
  1024. }
  1025. Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, int vertexcount, Mesh::DrawMode drawmode, Mesh::Usage usage)
  1026. {
  1027. return new Mesh(vertexformat, vertexcount, drawmode, usage);
  1028. }
  1029. Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, const void *data, size_t datasize, Mesh::DrawMode drawmode, Mesh::Usage usage)
  1030. {
  1031. return new Mesh(vertexformat, data, datasize, drawmode, usage);
  1032. }
  1033. Text *Graphics::newText(Font *font, const std::vector<Font::ColoredString> &text)
  1034. {
  1035. return new Text(font, text);
  1036. }
  1037. Video *Graphics::newVideo(love::video::VideoStream *stream)
  1038. {
  1039. return new Video(stream);
  1040. }
  1041. bool Graphics::isGammaCorrect() const
  1042. {
  1043. return love::graphics::isGammaCorrect();
  1044. }
  1045. void Graphics::setColor(Colorf c)
  1046. {
  1047. Colorf nc = c;
  1048. gammaCorrectColor(nc);
  1049. glVertexAttrib4f(ATTRIB_CONSTANTCOLOR, nc.r, nc.g, nc.b, nc.a);
  1050. states.back().color = c;
  1051. }
  1052. Colorf Graphics::getColor() const
  1053. {
  1054. return states.back().color;
  1055. }
  1056. void Graphics::setBackgroundColor(Colorf c)
  1057. {
  1058. states.back().backgroundColor = c;
  1059. }
  1060. Colorf Graphics::getBackgroundColor() const
  1061. {
  1062. return states.back().backgroundColor;
  1063. }
  1064. void Graphics::setFont(Font *font)
  1065. {
  1066. // We don't need to set a default font here if null is passed in, since we
  1067. // only care about the default font in getFont and print.
  1068. DisplayState &state = states.back();
  1069. state.font.set(font);
  1070. }
  1071. Font *Graphics::getFont()
  1072. {
  1073. checkSetDefaultFont();
  1074. return states.back().font.get();
  1075. }
  1076. void Graphics::setShader(Shader *shader)
  1077. {
  1078. if (shader == nullptr)
  1079. return setShader();
  1080. DisplayState &state = states.back();
  1081. shader->attach();
  1082. state.shader.set(shader);
  1083. }
  1084. void Graphics::setShader()
  1085. {
  1086. DisplayState &state = states.back();
  1087. // This will activate the default shader.
  1088. Shader::detach();
  1089. state.shader.set(nullptr);
  1090. }
  1091. Shader *Graphics::getShader() const
  1092. {
  1093. return states.back().shader.get();
  1094. }
  1095. void Graphics::setColorMask(ColorMask mask)
  1096. {
  1097. glColorMask(mask.r, mask.g, mask.b, mask.a);
  1098. states.back().colorMask = mask;
  1099. }
  1100. Graphics::ColorMask Graphics::getColorMask() const
  1101. {
  1102. return states.back().colorMask;
  1103. }
  1104. void Graphics::setBlendMode(BlendMode mode, BlendAlpha alphamode)
  1105. {
  1106. GLenum func = GL_FUNC_ADD;
  1107. GLenum srcRGB = GL_ONE;
  1108. GLenum srcA = GL_ONE;
  1109. GLenum dstRGB = GL_ZERO;
  1110. GLenum dstA = GL_ZERO;
  1111. if (mode == BLEND_LIGHTEN || mode == BLEND_DARKEN)
  1112. {
  1113. if (!isSupported(FEATURE_LIGHTEN))
  1114. throw love::Exception("The 'lighten' and 'darken' blend modes are not supported on this system.");
  1115. }
  1116. if (alphamode != BLENDALPHA_PREMULTIPLIED)
  1117. {
  1118. const char *modestr = "unknown";
  1119. switch (mode)
  1120. {
  1121. case BLEND_LIGHTEN:
  1122. case BLEND_DARKEN:
  1123. case BLEND_MULTIPLY:
  1124. getConstant(mode, modestr);
  1125. throw love::Exception("The '%s' blend mode must be used with premultiplied alpha.", modestr);
  1126. break;
  1127. default:
  1128. break;
  1129. }
  1130. }
  1131. switch (mode)
  1132. {
  1133. case BLEND_ALPHA:
  1134. srcRGB = srcA = GL_ONE;
  1135. dstRGB = dstA = GL_ONE_MINUS_SRC_ALPHA;
  1136. break;
  1137. case BLEND_MULTIPLY:
  1138. srcRGB = srcA = GL_DST_COLOR;
  1139. dstRGB = dstA = GL_ZERO;
  1140. break;
  1141. case BLEND_SUBTRACT:
  1142. func = GL_FUNC_REVERSE_SUBTRACT;
  1143. case BLEND_ADD:
  1144. srcRGB = GL_ONE;
  1145. srcA = GL_ZERO;
  1146. dstRGB = dstA = GL_ONE;
  1147. break;
  1148. case BLEND_LIGHTEN:
  1149. func = GL_MAX;
  1150. break;
  1151. case BLEND_DARKEN:
  1152. func = GL_MIN;
  1153. break;
  1154. case BLEND_SCREEN:
  1155. srcRGB = srcA = GL_ONE;
  1156. dstRGB = dstA = GL_ONE_MINUS_SRC_COLOR;
  1157. break;
  1158. case BLEND_REPLACE:
  1159. default:
  1160. srcRGB = srcA = GL_ONE;
  1161. dstRGB = dstA = GL_ZERO;
  1162. break;
  1163. }
  1164. // We can only do alpha-multiplication when srcRGB would have been unmodified.
  1165. if (srcRGB == GL_ONE && alphamode == BLENDALPHA_MULTIPLY)
  1166. srcRGB = GL_SRC_ALPHA;
  1167. glBlendEquation(func);
  1168. glBlendFuncSeparate(srcRGB, dstRGB, srcA, dstA);
  1169. states.back().blendMode = mode;
  1170. states.back().blendAlphaMode = alphamode;
  1171. }
  1172. Graphics::BlendMode Graphics::getBlendMode(BlendAlpha &alphamode) const
  1173. {
  1174. alphamode = states.back().blendAlphaMode;
  1175. return states.back().blendMode;
  1176. }
  1177. void Graphics::setDefaultFilter(const Texture::Filter &f)
  1178. {
  1179. Texture::setDefaultFilter(f);
  1180. states.back().defaultFilter = f;
  1181. }
  1182. const Texture::Filter &Graphics::getDefaultFilter() const
  1183. {
  1184. return Texture::getDefaultFilter();
  1185. }
  1186. void Graphics::setDefaultMipmapFilter(Texture::FilterMode filter, float sharpness)
  1187. {
  1188. Image::setDefaultMipmapFilter(filter);
  1189. Image::setDefaultMipmapSharpness(sharpness);
  1190. states.back().defaultMipmapFilter = filter;
  1191. states.back().defaultMipmapSharpness = sharpness;
  1192. }
  1193. void Graphics::getDefaultMipmapFilter(Texture::FilterMode *filter, float *sharpness) const
  1194. {
  1195. *filter = Image::getDefaultMipmapFilter();
  1196. *sharpness = Image::getDefaultMipmapSharpness();
  1197. }
  1198. void Graphics::setLineWidth(float width)
  1199. {
  1200. states.back().lineWidth = width;
  1201. }
  1202. void Graphics::setLineStyle(Graphics::LineStyle style)
  1203. {
  1204. states.back().lineStyle = style;
  1205. }
  1206. void Graphics::setLineJoin(Graphics::LineJoin join)
  1207. {
  1208. states.back().lineJoin = join;
  1209. }
  1210. float Graphics::getLineWidth() const
  1211. {
  1212. return states.back().lineWidth;
  1213. }
  1214. Graphics::LineStyle Graphics::getLineStyle() const
  1215. {
  1216. return states.back().lineStyle;
  1217. }
  1218. Graphics::LineJoin Graphics::getLineJoin() const
  1219. {
  1220. return states.back().lineJoin;
  1221. }
  1222. void Graphics::setPointSize(float size)
  1223. {
  1224. gl.setPointSize(size);
  1225. states.back().pointSize = size;
  1226. }
  1227. float Graphics::getPointSize() const
  1228. {
  1229. return states.back().pointSize;
  1230. }
  1231. void Graphics::setWireframe(bool enable)
  1232. {
  1233. // Not supported in OpenGL ES.
  1234. if (GLAD_ES_VERSION_2_0)
  1235. return;
  1236. glPolygonMode(GL_FRONT_AND_BACK, enable ? GL_LINE : GL_FILL);
  1237. states.back().wireframe = enable;
  1238. }
  1239. bool Graphics::isWireframe() const
  1240. {
  1241. return states.back().wireframe;
  1242. }
  1243. void Graphics::draw(Drawable *drawable, const Matrix4 &m)
  1244. {
  1245. drawable->draw(m);
  1246. }
  1247. void Graphics::drawq(Texture *texture, Quad *quad, const Matrix4 &m)
  1248. {
  1249. texture->drawq(quad, m);
  1250. }
  1251. void Graphics::print(const std::vector<Font::ColoredString> &str, const Matrix4 &m)
  1252. {
  1253. checkSetDefaultFont();
  1254. DisplayState &state = states.back();
  1255. if (state.font.get() != nullptr)
  1256. state.font->print(str, m);
  1257. }
  1258. void Graphics::printf(const std::vector<Font::ColoredString> &str, float wrap, Font::AlignMode align, const Matrix4 &m)
  1259. {
  1260. checkSetDefaultFont();
  1261. DisplayState &state = states.back();
  1262. if (state.font.get() != nullptr)
  1263. state.font->printf(str, wrap, align, m);
  1264. }
  1265. /**
  1266. * Primitives
  1267. **/
  1268. void Graphics::points(const float *coords, const uint8 *colors, size_t numpoints)
  1269. {
  1270. OpenGL::TempDebugGroup debuggroup("Graphics points draw");
  1271. gl.prepareDraw();
  1272. gl.bindTextureToUnit(gl.getDefaultTexture(), 0, false);
  1273. gl.bindBuffer(BUFFER_VERTEX, 0);
  1274. uint32 attribflags = ATTRIBFLAG_POS;
  1275. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, 0, coords);
  1276. if (colors)
  1277. {
  1278. attribflags |= ATTRIBFLAG_COLOR;
  1279. glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colors);
  1280. }
  1281. gl.useVertexAttribArrays(attribflags);
  1282. gl.drawArrays(GL_POINTS, 0, (GLsizei) numpoints);
  1283. }
  1284. void Graphics::polyline(const float *coords, size_t count)
  1285. {
  1286. const DisplayState &state = states.back();
  1287. float pixelsize = 1.0f / std::max((float) pixelScaleStack.back(), 0.000001f);
  1288. if (state.lineJoin == LINE_JOIN_NONE)
  1289. {
  1290. NoneJoinPolyline line;
  1291. line.render(coords, count, state.lineWidth * .5f, pixelsize, state.lineStyle == LINE_SMOOTH);
  1292. line.draw();
  1293. }
  1294. else if (state.lineJoin == LINE_JOIN_BEVEL)
  1295. {
  1296. BevelJoinPolyline line;
  1297. line.render(coords, count, state.lineWidth * .5f, pixelsize, state.lineStyle == LINE_SMOOTH);
  1298. line.draw();
  1299. }
  1300. else // LINE_JOIN_MITER
  1301. {
  1302. MiterJoinPolyline line;
  1303. line.render(coords, count, state.lineWidth * .5f, pixelsize, state.lineStyle == LINE_SMOOTH);
  1304. line.draw();
  1305. }
  1306. }
  1307. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  1308. {
  1309. float coords[] = {x,y, x,y+h, x+w,y+h, x+w,y, x,y};
  1310. polygon(mode, coords, 5 * 2);
  1311. }
  1312. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry, int points)
  1313. {
  1314. if (rx == 0 || ry == 0)
  1315. {
  1316. rectangle(mode, x, y, w, h);
  1317. return;
  1318. }
  1319. // Radius values that are more than half the rectangle's size aren't handled
  1320. // correctly (for now)...
  1321. if (w >= 0.02f)
  1322. rx = std::min(rx, w / 2.0f - 0.01f);
  1323. if (h >= 0.02f)
  1324. ry = std::min(ry, h / 2.0f - 0.01f);
  1325. points = std::max(points / 4, 1);
  1326. const float half_pi = static_cast<float>(LOVE_M_PI / 2);
  1327. float angle_shift = half_pi / ((float) points + 1.0f);
  1328. int num_coords = (points + 2) * 8;
  1329. float *coords = new float[num_coords + 2];
  1330. float phi = .0f;
  1331. for (int i = 0; i <= points + 2; ++i, phi += angle_shift)
  1332. {
  1333. coords[2 * i + 0] = x + rx * (1 - cosf(phi));
  1334. coords[2 * i + 1] = y + ry * (1 - sinf(phi));
  1335. }
  1336. phi = half_pi;
  1337. for (int i = points + 2; i <= 2 * (points + 2); ++i, phi += angle_shift)
  1338. {
  1339. coords[2 * i + 0] = x + w - rx * (1 + cosf(phi));
  1340. coords[2 * i + 1] = y + ry * (1 - sinf(phi));
  1341. }
  1342. phi = 2 * half_pi;
  1343. for (int i = 2 * (points + 2); i <= 3 * (points + 2); ++i, phi += angle_shift)
  1344. {
  1345. coords[2 * i + 0] = x + w - rx * (1 + cosf(phi));
  1346. coords[2 * i + 1] = y + h - ry * (1 + sinf(phi));
  1347. }
  1348. phi = 3 * half_pi;
  1349. for (int i = 3 * (points + 2); i <= 4 * (points + 2); ++i, phi += angle_shift)
  1350. {
  1351. coords[2 * i + 0] = x + rx * (1 - cosf(phi));
  1352. coords[2 * i + 1] = y + h - ry * (1 + sinf(phi));
  1353. }
  1354. coords[num_coords + 0] = coords[0];
  1355. coords[num_coords + 1] = coords[1];
  1356. polygon(mode, coords, num_coords + 2);
  1357. delete[] coords;
  1358. }
  1359. int Graphics::calculateEllipsePoints(float rx, float ry) const
  1360. {
  1361. int points = (int) sqrtf(((rx + ry) / 2.0f) * 20.0f * (float) pixelScaleStack.back());
  1362. return std::max(points, 8);
  1363. }
  1364. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry)
  1365. {
  1366. rectangle(mode, x, y, w, h, rx, ry, calculateEllipsePoints(rx, ry));
  1367. }
  1368. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  1369. {
  1370. ellipse(mode, x, y, radius, radius, points);
  1371. }
  1372. void Graphics::circle(DrawMode mode, float x, float y, float radius)
  1373. {
  1374. ellipse(mode, x, y, radius, radius);
  1375. }
  1376. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b, int points)
  1377. {
  1378. float two_pi = static_cast<float>(LOVE_M_PI * 2);
  1379. if (points <= 0) points = 1;
  1380. float angle_shift = (two_pi / points);
  1381. float phi = .0f;
  1382. float *coords = new float[2 * (points + 1)];
  1383. for (int i = 0; i < points; ++i, phi += angle_shift)
  1384. {
  1385. coords[2*i+0] = x + a * cosf(phi);
  1386. coords[2*i+1] = y + b * sinf(phi);
  1387. }
  1388. coords[2*points+0] = coords[0];
  1389. coords[2*points+1] = coords[1];
  1390. polygon(mode, coords, (points + 1) * 2);
  1391. delete[] coords;
  1392. }
  1393. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b)
  1394. {
  1395. ellipse(mode, x, y, a, b, calculateEllipsePoints(a, b));
  1396. }
  1397. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2, int points)
  1398. {
  1399. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  1400. if (points <= 0 || angle1 == angle2)
  1401. return;
  1402. // Oh, you want to draw a circle?
  1403. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  1404. {
  1405. circle(drawmode, x, y, radius, points);
  1406. return;
  1407. }
  1408. float angle_shift = (angle2 - angle1) / points;
  1409. // Bail on precision issues.
  1410. if (angle_shift == 0.0)
  1411. return;
  1412. // Prevent the connecting line from being drawn if a closed line arc has a
  1413. // small angle. Avoids some visual issues when connected lines are at sharp
  1414. // angles, due to the miter line join drawing code.
  1415. if (drawmode == DRAW_LINE && arcmode == ARC_CLOSED && fabsf(angle1 - angle2) < LOVE_TORAD(4))
  1416. arcmode = ARC_OPEN;
  1417. // Quick fix for the last part of a filled open arc not being drawn (because
  1418. // polygon(DRAW_FILL, ...) doesn't work without a closed loop of vertices.)
  1419. if (drawmode == DRAW_FILL && arcmode == ARC_OPEN)
  1420. arcmode = ARC_CLOSED;
  1421. float phi = angle1;
  1422. float *coords = nullptr;
  1423. int num_coords = 0;
  1424. const auto createPoints = [&](float *coordinates)
  1425. {
  1426. for (int i = 0; i <= points; ++i, phi += angle_shift)
  1427. {
  1428. coordinates[2 * i + 0] = x + radius * cosf(phi);
  1429. coordinates[2 * i + 1] = y + radius * sinf(phi);
  1430. }
  1431. };
  1432. if (arcmode == ARC_PIE)
  1433. {
  1434. num_coords = (points + 3) * 2;
  1435. coords = new float[num_coords];
  1436. coords[0] = coords[num_coords - 2] = x;
  1437. coords[1] = coords[num_coords - 1] = y;
  1438. createPoints(coords + 2);
  1439. }
  1440. else if (arcmode == ARC_OPEN)
  1441. {
  1442. num_coords = (points + 1) * 2;
  1443. coords = new float[num_coords];
  1444. createPoints(coords);
  1445. }
  1446. else // ARC_CLOSED
  1447. {
  1448. num_coords = (points + 2) * 2;
  1449. coords = new float[num_coords];
  1450. createPoints(coords);
  1451. // Connect the ends of the arc.
  1452. coords[num_coords - 2] = coords[0];
  1453. coords[num_coords - 1] = coords[1];
  1454. }
  1455. // NOTE: We rely on polygon() using GL_TRIANGLE_FAN, when fill mode is used.
  1456. polygon(drawmode, coords, num_coords);
  1457. delete[] coords;
  1458. }
  1459. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2)
  1460. {
  1461. float points = (float) calculateEllipsePoints(radius, radius);
  1462. // The amount of points is based on the fraction of the circle created by the arc.
  1463. float angle = fabsf(angle1 - angle2);
  1464. if (angle < 2.0f * (float) LOVE_M_PI)
  1465. points *= angle / (2.0f * (float) LOVE_M_PI);
  1466. arc(drawmode, arcmode, x, y, radius, angle1, angle2, (int) (points + 0.5f));
  1467. }
  1468. /// @param mode the draw mode
  1469. /// @param coords the coordinate array
  1470. /// @param count the number of coordinates/size of the array
  1471. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  1472. {
  1473. // coords is an array of a closed loop of vertices, i.e.
  1474. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  1475. if (mode == DRAW_LINE)
  1476. {
  1477. polyline(coords, count);
  1478. }
  1479. else
  1480. {
  1481. OpenGL::TempDebugGroup debuggroup("Filled polygon draw");
  1482. gl.prepareDraw();
  1483. gl.bindTextureToUnit(gl.getDefaultTexture(), 0, false);
  1484. gl.bindBuffer(BUFFER_VERTEX, 0);
  1485. gl.useVertexAttribArrays(ATTRIBFLAG_POS);
  1486. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, 0, coords);
  1487. gl.drawArrays(GL_TRIANGLE_FAN, 0, (int)count/2-1); // opengl will close the polygon for us
  1488. }
  1489. }
  1490. Graphics::RendererInfo Graphics::getRendererInfo() const
  1491. {
  1492. RendererInfo info;
  1493. if (GLAD_ES_VERSION_2_0)
  1494. info.name = "OpenGL ES";
  1495. else
  1496. info.name = "OpenGL";
  1497. const char *str = (const char *) glGetString(GL_VERSION);
  1498. if (str)
  1499. info.version = str;
  1500. else
  1501. throw love::Exception("Cannot retrieve renderer version information.");
  1502. str = (const char *) glGetString(GL_VENDOR);
  1503. if (str)
  1504. info.vendor = str;
  1505. else
  1506. throw love::Exception("Cannot retrieve renderer vendor information.");
  1507. str = (const char *) glGetString(GL_RENDERER);
  1508. if (str)
  1509. info.device = str;
  1510. else
  1511. throw love::Exception("Cannot retrieve renderer device information.");
  1512. return info;
  1513. }
  1514. Graphics::Stats Graphics::getStats() const
  1515. {
  1516. Stats stats;
  1517. stats.drawCalls = gl.stats.drawCalls;
  1518. stats.canvasSwitches = canvasSwitchCount;
  1519. stats.shaderSwitches = gl.stats.shaderSwitches;
  1520. stats.canvases = Canvas::canvasCount;
  1521. stats.images = Image::imageCount;
  1522. stats.fonts = Font::fontCount;
  1523. stats.textureMemory = gl.stats.textureMemory;
  1524. return stats;
  1525. }
  1526. double Graphics::getSystemLimit(SystemLimit limittype) const
  1527. {
  1528. switch (limittype)
  1529. {
  1530. case Graphics::LIMIT_POINT_SIZE:
  1531. return (double) gl.getMaxPointSize();
  1532. case Graphics::LIMIT_TEXTURE_SIZE:
  1533. return (double) gl.getMaxTextureSize();
  1534. case Graphics::LIMIT_MULTI_CANVAS:
  1535. return (double) gl.getMaxRenderTargets();
  1536. case Graphics::LIMIT_CANVAS_MSAA:
  1537. return (double) gl.getMaxRenderbufferSamples();
  1538. case Graphics::LIMIT_ANISOTROPY:
  1539. return (double) gl.getMaxAnisotropy();
  1540. default:
  1541. return 0.0;
  1542. }
  1543. }
  1544. bool Graphics::isSupported(Feature feature) const
  1545. {
  1546. switch (feature)
  1547. {
  1548. case FEATURE_MULTI_CANVAS_FORMATS:
  1549. return Canvas::isMultiFormatMultiCanvasSupported();
  1550. case FEATURE_CLAMP_ZERO:
  1551. return gl.isClampZeroTextureWrapSupported();
  1552. case FEATURE_LIGHTEN:
  1553. return GLAD_VERSION_1_4 || GLAD_ES_VERSION_3_0 || GLAD_EXT_blend_minmax;
  1554. case FEATURE_FULL_NPOT:
  1555. return GLAD_VERSION_2_0 || GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot;
  1556. case FEATURE_PIXEL_SHADER_HIGHP:
  1557. return gl.isPixelShaderHighpSupported();
  1558. default:
  1559. return false;
  1560. }
  1561. }
  1562. void Graphics::push(StackType type)
  1563. {
  1564. if (stackTypes.size() == MAX_USER_STACK_DEPTH)
  1565. throw Exception("Maximum stack depth reached (more pushes than pops?)");
  1566. gl.pushTransform();
  1567. pixelScaleStack.push_back(pixelScaleStack.back());
  1568. if (type == STACK_ALL)
  1569. states.push_back(states.back());
  1570. stackTypes.push_back(type);
  1571. }
  1572. void Graphics::pop()
  1573. {
  1574. if (stackTypes.size() < 1)
  1575. throw Exception("Minimum stack depth reached (more pops than pushes?)");
  1576. gl.popTransform();
  1577. pixelScaleStack.pop_back();
  1578. if (stackTypes.back() == STACK_ALL)
  1579. {
  1580. DisplayState &newstate = states[states.size() - 2];
  1581. restoreStateChecked(newstate);
  1582. // The last two states in the stack should be equal now.
  1583. states.pop_back();
  1584. }
  1585. stackTypes.pop_back();
  1586. }
  1587. void Graphics::rotate(float r)
  1588. {
  1589. gl.getTransform().rotate(r);
  1590. }
  1591. void Graphics::scale(float x, float y)
  1592. {
  1593. gl.getTransform().scale(x, y);
  1594. pixelScaleStack.back() *= (fabs(x) + fabs(y)) / 2.0;
  1595. }
  1596. void Graphics::translate(float x, float y)
  1597. {
  1598. gl.getTransform().translate(x, y);
  1599. }
  1600. void Graphics::shear(float kx, float ky)
  1601. {
  1602. gl.getTransform().shear(kx, ky);
  1603. }
  1604. void Graphics::origin()
  1605. {
  1606. gl.getTransform().setIdentity();
  1607. pixelScaleStack.back() = 1;
  1608. }
  1609. void Graphics::applyTransform(love::math::Transform *transform)
  1610. {
  1611. Matrix4 &m = gl.getTransform();
  1612. m *= transform->getMatrix();
  1613. float sx, sy;
  1614. m.getApproximateScale(sx, sy);
  1615. pixelScaleStack.back() = (sx + sy) / 2.0;
  1616. }
  1617. void Graphics::replaceTransform(love::math::Transform *transform)
  1618. {
  1619. const Matrix4 &m = transform->getMatrix();
  1620. gl.getTransform() = m;
  1621. float sx, sy;
  1622. m.getApproximateScale(sx, sy);
  1623. pixelScaleStack.back() = (sx + sy) / 2.0;
  1624. }
  1625. Vector Graphics::transformPoint(Vector point)
  1626. {
  1627. Vector p;
  1628. gl.getTransform().transform(&p, &point, 1);
  1629. return p;
  1630. }
  1631. Vector Graphics::inverseTransformPoint(Vector point)
  1632. {
  1633. Vector p;
  1634. // TODO: We should probably cache the inverse transform so we don't have to
  1635. // re-calculate it every time this is called.
  1636. gl.getTransform().inverse().transform(&p, &point, 1);
  1637. return p;
  1638. }
  1639. } // opengl
  1640. } // graphics
  1641. } // love