Graphics.cpp 43 KB

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