Graphics.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  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. if (currentWindow.get())
  58. {
  59. int w, h;
  60. love::window::WindowSettings wsettings;
  61. currentWindow->getWindow(w, h, wsettings);
  62. if (currentWindow->isOpen())
  63. setMode(w, h);
  64. }
  65. }
  66. Graphics::~Graphics()
  67. {
  68. // We do this manually so the graphics objects are released before the window.
  69. states.clear();
  70. defaultFont.set(nullptr);
  71. if (Shader::defaultShader)
  72. {
  73. Shader::defaultShader->release();
  74. Shader::defaultShader = nullptr;
  75. }
  76. if (Shader::defaultVideoShader)
  77. {
  78. Shader::defaultVideoShader->release();
  79. Shader::defaultVideoShader = nullptr;
  80. }
  81. if (quadIndices)
  82. delete quadIndices;
  83. }
  84. const char *Graphics::getName() const
  85. {
  86. return "love.graphics.opengl";
  87. }
  88. void Graphics::restoreState(const DisplayState &s)
  89. {
  90. setColor(s.color);
  91. setBackgroundColor(s.backgroundColor);
  92. setBlendMode(s.blendMode, s.blendAlphaMode);
  93. setLineWidth(s.lineWidth);
  94. setLineStyle(s.lineStyle);
  95. setLineJoin(s.lineJoin);
  96. setPointSize(s.pointSize);
  97. if (s.scissor)
  98. setScissor(s.scissorRect.x, s.scissorRect.y, s.scissorRect.w, s.scissorRect.h);
  99. else
  100. setScissor();
  101. setStencilTest(s.stencilCompare, s.stencilTestValue);
  102. setFont(s.font.get());
  103. setShader(s.shader.get());
  104. setCanvas(s.canvases);
  105. setColorMask(s.colorMask);
  106. setWireframe(s.wireframe);
  107. setDefaultFilter(s.defaultFilter);
  108. setDefaultMipmapFilter(s.defaultMipmapFilter, s.defaultMipmapSharpness);
  109. }
  110. void Graphics::restoreStateChecked(const DisplayState &s)
  111. {
  112. const DisplayState &cur = states.back();
  113. if (s.color != cur.color)
  114. setColor(s.color);
  115. setBackgroundColor(s.backgroundColor);
  116. if (s.blendMode != cur.blendMode || s.blendAlphaMode != cur.blendAlphaMode)
  117. setBlendMode(s.blendMode, s.blendAlphaMode);
  118. // These are just simple assignments.
  119. setLineWidth(s.lineWidth);
  120. setLineStyle(s.lineStyle);
  121. setLineJoin(s.lineJoin);
  122. if (s.pointSize != cur.pointSize)
  123. setPointSize(s.pointSize);
  124. if (s.scissor != cur.scissor || (s.scissor && !(s.scissorRect == cur.scissorRect)))
  125. {
  126. if (s.scissor)
  127. setScissor(s.scissorRect.x, s.scissorRect.y, s.scissorRect.w, s.scissorRect.h);
  128. else
  129. setScissor();
  130. }
  131. if (s.stencilCompare != cur.stencilCompare || s.stencilTestValue != cur.stencilTestValue)
  132. setStencilTest(s.stencilCompare, s.stencilTestValue);
  133. setFont(s.font.get());
  134. setShader(s.shader.get());
  135. bool canvaseschanged = s.canvases.size() != cur.canvases.size();
  136. for (size_t i = 0; i < s.canvases.size() && i < cur.canvases.size(); i++)
  137. {
  138. if (s.canvases[i].get() != cur.canvases[i].get())
  139. {
  140. canvaseschanged = true;
  141. break;
  142. }
  143. }
  144. if (canvaseschanged)
  145. setCanvas(s.canvases);
  146. if (s.colorMask != cur.colorMask)
  147. setColorMask(s.colorMask);
  148. if (s.wireframe != cur.wireframe)
  149. setWireframe(s.wireframe);
  150. setDefaultFilter(s.defaultFilter);
  151. setDefaultMipmapFilter(s.defaultMipmapFilter, s.defaultMipmapSharpness);
  152. }
  153. void Graphics::checkSetDefaultFont()
  154. {
  155. // We don't create or set the default Font if an existing font is in use.
  156. if (states.back().font.get() != nullptr)
  157. return;
  158. // Create a new default font if we don't have one yet.
  159. if (!defaultFont.get())
  160. {
  161. auto fontmodule = Module::getInstance<font::Font>(M_FONT);
  162. if (!fontmodule)
  163. throw love::Exception("Font module has not been loaded.");
  164. StrongRef<font::Rasterizer> r(fontmodule->newTrueTypeRasterizer(12, font::TrueTypeRasterizer::HINTING_NORMAL));
  165. r->release();
  166. defaultFont.set(newFont(r.get()));
  167. defaultFont->release();
  168. }
  169. states.back().font.set(defaultFont.get());
  170. }
  171. void Graphics::setViewportSize(int width, int height)
  172. {
  173. this->width = width;
  174. this->height = height;
  175. if (!isCreated())
  176. return;
  177. // We want to affect the main screen, not any Canvas that's currently active
  178. // (not that any *should* be active when this is called.)
  179. std::vector<StrongRef<Canvas>> canvases = states.back().canvases;
  180. setCanvas();
  181. // Set the viewport to top-left corner.
  182. gl.setViewport({0, 0, width, height});
  183. // If a canvas was bound before this function was called, it needs to be
  184. // made aware of the new system viewport size.
  185. Canvas::systemViewport = gl.getViewport();
  186. // Set up the projection matrix
  187. gl.matrices.projection.back() = Matrix4::ortho(0.0, (float) width, (float) height, 0.0);
  188. // Restore the previously active Canvas.
  189. setCanvas(canvases);
  190. }
  191. bool Graphics::setMode(int width, int height)
  192. {
  193. currentWindow.set(Module::getInstance<love::window::Window>(Module::M_WINDOW));
  194. this->width = width;
  195. this->height = height;
  196. // Okay, setup OpenGL.
  197. gl.initContext();
  198. gl.setupContext();
  199. created = true;
  200. setViewportSize(width, height);
  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. // Restore the graphics state.
  245. restoreState(states.back());
  246. pixelSizeStack.clear();
  247. pixelSizeStack.reserve(5);
  248. pixelSizeStack.push_back(1);
  249. // We always need a default shader.
  250. if (!Shader::defaultShader)
  251. {
  252. Renderer renderer = GLAD_ES_VERSION_2_0 ? RENDERER_OPENGLES : RENDERER_OPENGL;
  253. Shader::defaultShader = newShader(Shader::defaultCode[renderer]);
  254. }
  255. // and a default video shader.
  256. if (!Shader::defaultVideoShader)
  257. {
  258. Renderer renderer = GLAD_ES_VERSION_2_0 ? RENDERER_OPENGLES : RENDERER_OPENGL;
  259. Shader::defaultVideoShader = newShader(Shader::defaultVideoCode[renderer]);
  260. }
  261. // A shader should always be active, but the default shader shouldn't be
  262. // returned by getShader(), so we don't do setShader(defaultShader).
  263. if (!Shader::current)
  264. Shader::defaultShader->attach();
  265. return true;
  266. }
  267. void Graphics::unSetMode()
  268. {
  269. if (!isCreated())
  270. return;
  271. // Unload all volatile objects. These must be reloaded after the display
  272. // mode change.
  273. Volatile::unloadAll();
  274. gl.deInitContext();
  275. created = false;
  276. }
  277. void Graphics::setActive(bool enable)
  278. {
  279. // Make sure all pending OpenGL commands have fully executed before
  280. // returning, when going from active to inactive. This is required on iOS.
  281. if (isCreated() && this->active && !enable)
  282. glFinish();
  283. active = enable;
  284. }
  285. bool Graphics::isActive() const
  286. {
  287. // The graphics module is only completely 'active' if there's a window, a
  288. // context, and the active variable is set.
  289. return active && isCreated() && currentWindow.get() && currentWindow->isOpen();
  290. }
  291. static void APIENTRY debugCB(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei /*len*/, const GLchar *msg, const GLvoid* /*usr*/)
  292. {
  293. // Human-readable strings for the debug info.
  294. const char *sourceStr = OpenGL::debugSourceString(source);
  295. const char *typeStr = OpenGL::debugTypeString(type);
  296. const char *severityStr = OpenGL::debugSeverityString(severity);
  297. const char *fmt = "OpenGL: %s [source=%s, type=%s, severity=%s, id=%d]\n";
  298. printf(fmt, msg, sourceStr, typeStr, severityStr, id);
  299. }
  300. void Graphics::setDebug(bool enable)
  301. {
  302. // Make sure debug output is supported. The AMD ext. is a bit different
  303. // so we don't make use of it, since AMD drivers now support KHR_debug.
  304. if (!(GLAD_VERSION_4_3 || GLAD_KHR_debug || GLAD_ARB_debug_output))
  305. return;
  306. // TODO: We don't support GL_KHR_debug in GLES yet.
  307. if (GLAD_ES_VERSION_2_0)
  308. return;
  309. // Ugly hack to reduce code duplication.
  310. if (GLAD_ARB_debug_output && !(GLAD_VERSION_4_3 || GLAD_KHR_debug))
  311. {
  312. fp_glDebugMessageCallback = (pfn_glDebugMessageCallback) fp_glDebugMessageCallbackARB;
  313. fp_glDebugMessageControl = (pfn_glDebugMessageControl) fp_glDebugMessageControlARB;
  314. }
  315. if (!enable)
  316. {
  317. // Disable the debug callback function.
  318. glDebugMessageCallback(nullptr, nullptr);
  319. // We can disable debug output entirely with KHR_debug.
  320. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  321. glDisable(GL_DEBUG_OUTPUT);
  322. return;
  323. }
  324. // We don't want asynchronous debug output.
  325. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  326. glDebugMessageCallback(debugCB, nullptr);
  327. // Initially, enable everything.
  328. glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
  329. // Disable messages about deprecated OpenGL functionality.
  330. glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  331. glDebugMessageControl(GL_DEBUG_SOURCE_SHADER_COMPILER, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  332. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  333. glEnable(GL_DEBUG_OUTPUT);
  334. ::printf("OpenGL debug output enabled (LOVE_GRAPHICS_DEBUG=1)\n");
  335. }
  336. void Graphics::reset()
  337. {
  338. DisplayState s;
  339. stopDrawToStencilBuffer();
  340. restoreState(s);
  341. origin();
  342. }
  343. void Graphics::dummyDraw()
  344. {
  345. gl.prepareDraw();
  346. // Draw a triangle using a single vertex position indexed 3 times. The
  347. // triangle will be degenerate and won't be rasterized (so the pixel shader
  348. // won't be run), and an index array with a single vertex is used so the
  349. // vertex shader can't prevent the triangle from being degenerate by using
  350. // gl_VertexID.
  351. // NOTE: This code will have to be changed to use a vertex and index buffer,
  352. // for it to work with a Core Profile GL3 backend. But the bug should be
  353. // re-tested in that case as well.
  354. const GLfloat vertex[] = {0.0f, 0.0f};
  355. const GLushort indices[] = {0, 0, 0};
  356. gl.useVertexAttribArrays(ATTRIBFLAG_POS);
  357. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, 0, vertex);
  358. gl.drawElements(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, indices);
  359. }
  360. void Graphics::clear(Colorf c)
  361. {
  362. Colorf nc = Colorf(c.r/255.0f, c.g/255.0f, c.b/255.0f, c.a/255.0f);
  363. gammaCorrectColor(nc);
  364. glClearColor(nc.r, nc.g, nc.b, nc.a);
  365. glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  366. if (gl.bugs.clearRequiresDummyDraw)
  367. dummyDraw();
  368. }
  369. void Graphics::clear(const std::vector<OptionalColorf> &colors)
  370. {
  371. if (colors.size() == 0)
  372. return;
  373. if (states.back().canvases.size() == 0)
  374. {
  375. if (colors[0].enabled)
  376. clear({colors[0].r, colors[0].g, colors[0].b, colors[0].a});
  377. return;
  378. }
  379. if (colors.size() != states.back().canvases.size())
  380. throw love::Exception("Number of clear colors must match the number of active canvases (%ld)", states.back().canvases.size());
  381. bool drawbuffermodified = false;
  382. for (int i = 0; i < (int) colors.size(); i++)
  383. {
  384. if (!colors[i].enabled)
  385. continue;
  386. GLfloat c[] = {colors[i].r/255.f, colors[i].g/255.f, colors[i].b/255.f, colors[i].a/255.f};
  387. // TODO: Investigate a potential bug on AMD drivers in Windows/Linux
  388. // which apparently causes the clear color to be incorrect when mixed
  389. // sRGB and linear render targets are active.
  390. if (isGammaCorrect())
  391. {
  392. for (int i = 0; i < 3; i++)
  393. c[i] = math::Math::instance.gammaToLinear(c[i]);
  394. }
  395. if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0)
  396. glClearBufferfv(GL_COLOR, i, c);
  397. else
  398. {
  399. glDrawBuffer(GL_COLOR_ATTACHMENT0 + i);
  400. glClearColor(c[0], c[1], c[2], c[3]);
  401. glClear(GL_COLOR_BUFFER_BIT);
  402. drawbuffermodified = true;
  403. }
  404. }
  405. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  406. // Revert to the expected draw buffers once we're done, if glClearBuffer
  407. // wasn't supported.
  408. if (drawbuffermodified)
  409. {
  410. std::vector<GLenum> bufs;
  411. for (int i = 0; i < (int) states.back().canvases.size(); i++)
  412. bufs.push_back(GL_COLOR_ATTACHMENT0 + i);
  413. if (bufs.size() > 1)
  414. glDrawBuffers((int) bufs.size(), &bufs[0]);
  415. else
  416. glDrawBuffer(GL_COLOR_ATTACHMENT0);
  417. }
  418. if (gl.bugs.clearRequiresDummyDraw)
  419. dummyDraw();
  420. }
  421. void Graphics::discard(const std::vector<bool> &colorbuffers, bool stencil)
  422. {
  423. if (!(GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0 || GLAD_EXT_discard_framebuffer))
  424. return;
  425. std::vector<GLenum> attachments;
  426. attachments.reserve(colorbuffers.size());
  427. // glDiscardFramebuffer uses different attachment enums for the default FBO.
  428. if (!Canvas::current && gl.getDefaultFBO() == 0)
  429. {
  430. if (colorbuffers.size() > 0 && colorbuffers[0])
  431. attachments.push_back(GL_COLOR);
  432. if (stencil)
  433. {
  434. attachments.push_back(GL_STENCIL);
  435. attachments.push_back(GL_DEPTH);
  436. }
  437. }
  438. else
  439. {
  440. int rendertargetcount = 1;
  441. if (Canvas::current)
  442. rendertargetcount = (int) states.back().canvases.size();
  443. for (int i = 0; i < (int) colorbuffers.size(); i++)
  444. {
  445. if (colorbuffers[i] && i < rendertargetcount)
  446. attachments.push_back(GL_COLOR_ATTACHMENT0 + i);
  447. }
  448. if (stencil)
  449. {
  450. attachments.push_back(GL_STENCIL_ATTACHMENT);
  451. attachments.push_back(GL_DEPTH_ATTACHMENT);
  452. }
  453. }
  454. // Hint for the driver that it doesn't need to save these buffers.
  455. if (GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0)
  456. glInvalidateFramebuffer(GL_FRAMEBUFFER, (GLint) attachments.size(), &attachments[0]);
  457. else if (GLAD_EXT_discard_framebuffer)
  458. glDiscardFramebufferEXT(GL_FRAMEBUFFER, (GLint) attachments.size(), &attachments[0]);
  459. }
  460. void Graphics::present()
  461. {
  462. if (!isActive())
  463. return;
  464. // Make sure we don't have a canvas active.
  465. std::vector<StrongRef<Canvas>> canvases = states.back().canvases;
  466. setCanvas();
  467. // Discard the stencil buffer before swapping.
  468. discard({}, true);
  469. #ifdef LOVE_IOS
  470. // Hack: SDL's color renderbuffer must be bound when swapBuffers is called.
  471. SDL_SysWMinfo info = {};
  472. SDL_VERSION(&info.version);
  473. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  474. glBindRenderbuffer(GL_RENDERBUFFER, info.info.uikit.colorbuffer);
  475. #endif
  476. if (currentWindow.get())
  477. currentWindow->swapBuffers();
  478. // Restore the currently active canvas, if there is one.
  479. setCanvas(canvases);
  480. // Reset the per-frame stat counts.
  481. gl.stats.drawCalls = 0;
  482. gl.stats.framebufferBinds = 0;
  483. }
  484. int Graphics::getWidth() const
  485. {
  486. return width;
  487. }
  488. int Graphics::getHeight() const
  489. {
  490. return height;
  491. }
  492. bool Graphics::isCreated() const
  493. {
  494. return created;
  495. }
  496. void Graphics::setScissor(int x, int y, int width, int height)
  497. {
  498. ScissorRect rect = {x, y, width, height};
  499. glEnable(GL_SCISSOR_TEST);
  500. // OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
  501. gl.setScissor({rect.x, rect.y, rect.w, rect.h});
  502. states.back().scissor = true;
  503. states.back().scissorRect = rect;
  504. }
  505. void Graphics::intersectScissor(int x, int y, int width, int height)
  506. {
  507. ScissorRect rect = states.back().scissorRect;
  508. if (!states.back().scissor)
  509. {
  510. rect.x = 0;
  511. rect.y = 0;
  512. rect.w = std::numeric_limits<int>::max();
  513. rect.h = std::numeric_limits<int>::max();
  514. }
  515. int x1 = std::max(rect.x, x);
  516. int y1 = std::max(rect.y, y);
  517. int x2 = std::min(rect.x + rect.w, x + width);
  518. int y2 = std::min(rect.y + rect.h, y + height);
  519. setScissor(x1, y1, std::max(0, x2 - x1), std::max(0, y2 - y1));
  520. }
  521. void Graphics::setScissor()
  522. {
  523. states.back().scissor = false;
  524. glDisable(GL_SCISSOR_TEST);
  525. }
  526. bool Graphics::getScissor(int &x, int &y, int &width, int &height) const
  527. {
  528. const DisplayState &state = states.back();
  529. x = state.scissorRect.x;
  530. y = state.scissorRect.y;
  531. width = state.scissorRect.w;
  532. height = state.scissorRect.h;
  533. return state.scissor;
  534. }
  535. void Graphics::drawToStencilBuffer(StencilAction action, int value)
  536. {
  537. writingToStencil = true;
  538. // Make sure the active canvas has a stencil buffer.
  539. if (Canvas::current)
  540. Canvas::current->checkCreateStencil();
  541. // Disable color writes but don't save the state for it.
  542. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  543. GLenum glaction = GL_REPLACE;
  544. switch (action)
  545. {
  546. case STENCIL_REPLACE:
  547. default:
  548. glaction = GL_REPLACE;
  549. break;
  550. case STENCIL_INCREMENT:
  551. glaction = GL_INCR;
  552. break;
  553. case STENCIL_DECREMENT:
  554. glaction = GL_DECR;
  555. break;
  556. case STENCIL_INCREMENT_WRAP:
  557. glaction = GL_INCR_WRAP;
  558. break;
  559. case STENCIL_DECREMENT_WRAP:
  560. glaction = GL_DECR_WRAP;
  561. break;
  562. case STENCIL_INVERT:
  563. glaction = GL_INVERT;
  564. break;
  565. }
  566. // The stencil test must be enabled in order to write to the stencil buffer.
  567. glEnable(GL_STENCIL_TEST);
  568. glStencilFunc(GL_ALWAYS, value, 0xFFFFFFFF);
  569. glStencilOp(GL_KEEP, GL_KEEP, glaction);
  570. }
  571. void Graphics::stopDrawToStencilBuffer()
  572. {
  573. if (!writingToStencil)
  574. return;
  575. writingToStencil = false;
  576. const DisplayState &state = states.back();
  577. // Revert the color write mask.
  578. setColorMask(state.colorMask);
  579. // Use the user-set stencil test state when writes are disabled.
  580. setStencilTest(state.stencilCompare, state.stencilTestValue);
  581. }
  582. void Graphics::setStencilTest(CompareMode compare, int value)
  583. {
  584. DisplayState &state = states.back();
  585. state.stencilCompare = compare;
  586. state.stencilTestValue = value;
  587. if (writingToStencil)
  588. return;
  589. if (compare == COMPARE_ALWAYS)
  590. {
  591. glDisable(GL_STENCIL_TEST);
  592. return;
  593. }
  594. // Make sure the active canvas has a stencil buffer.
  595. if (Canvas::current)
  596. Canvas::current->checkCreateStencil();
  597. GLenum glcompare = GL_EQUAL;
  598. /**
  599. * Q: Why are some of the compare modes inverted (e.g. COMPARE_LESS becomes
  600. * GL_GREATER)?
  601. *
  602. * A: OpenGL / GPUs do the comparison in the opposite way that makes sense
  603. * for this API. For example, if the compare function is GL_GREATER then the
  604. * stencil test will pass if the reference value is greater than the value
  605. * in the stencil buffer. With our API it's more intuitive to assume that
  606. * setStencilTest(COMPARE_GREATER, 4) will make it pass if the stencil
  607. * buffer has a value greater than 4.
  608. **/
  609. switch (compare)
  610. {
  611. case COMPARE_LESS:
  612. glcompare = GL_GREATER;
  613. break;
  614. case COMPARE_LEQUAL:
  615. glcompare = GL_GEQUAL;
  616. break;
  617. case COMPARE_EQUAL:
  618. default:
  619. glcompare = GL_EQUAL;
  620. break;
  621. case COMPARE_GEQUAL:
  622. glcompare = GL_LEQUAL;
  623. break;
  624. case COMPARE_GREATER:
  625. glcompare = GL_LESS;
  626. break;
  627. case COMPARE_NOTEQUAL:
  628. glcompare = GL_NOTEQUAL;
  629. break;
  630. case COMPARE_ALWAYS:
  631. glcompare = GL_ALWAYS;
  632. break;
  633. }
  634. glEnable(GL_STENCIL_TEST);
  635. glStencilFunc(glcompare, value, 0xFFFFFFFF);
  636. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  637. }
  638. void Graphics::setStencilTest()
  639. {
  640. setStencilTest(COMPARE_ALWAYS, 0);
  641. }
  642. void Graphics::getStencilTest(CompareMode &compare, int &value)
  643. {
  644. const DisplayState &state = states.back();
  645. compare = state.stencilCompare;
  646. value = state.stencilTestValue;
  647. }
  648. void Graphics::clearStencil()
  649. {
  650. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  651. }
  652. Image *Graphics::newImage(const std::vector<love::image::ImageData *> &data, const Image::Flags &flags)
  653. {
  654. return new Image(data, flags);
  655. }
  656. Image *Graphics::newImage(const std::vector<love::image::CompressedImageData *> &cdata, const Image::Flags &flags)
  657. {
  658. return new Image(cdata, flags);
  659. }
  660. Quad *Graphics::newQuad(Quad::Viewport v, double sw, double sh)
  661. {
  662. return new Quad(v, sw, sh);
  663. }
  664. Font *Graphics::newFont(love::font::Rasterizer *r, const Texture::Filter &filter)
  665. {
  666. return new Font(r, filter);
  667. }
  668. SpriteBatch *Graphics::newSpriteBatch(Texture *texture, int size, Mesh::Usage usage)
  669. {
  670. return new SpriteBatch(texture, size, usage);
  671. }
  672. ParticleSystem *Graphics::newParticleSystem(Texture *texture, int size)
  673. {
  674. return new ParticleSystem(texture, size);
  675. }
  676. Canvas *Graphics::newCanvas(int width, int height, Canvas::Format format, int msaa)
  677. {
  678. if (!Canvas::isFormatSupported(format))
  679. {
  680. const char *fstr = "rgba8";
  681. Canvas::getConstant(format, fstr);
  682. throw love::Exception("The %s canvas format is not supported by your OpenGL implementation.", 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 implementation.";
  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 implementation.";
  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 implementation.";
  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(SUPPORT_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.canvases = Canvas::canvasCount;
  1323. stats.images = Image::imageCount;
  1324. stats.fonts = Font::fontCount;
  1325. stats.textureMemory = gl.stats.textureMemory;
  1326. return stats;
  1327. }
  1328. double Graphics::getSystemLimit(SystemLimit limittype) const
  1329. {
  1330. GLfloat limits[2];
  1331. switch (limittype)
  1332. {
  1333. case Graphics::LIMIT_POINT_SIZE:
  1334. glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, limits);
  1335. return (double) limits[1];
  1336. case Graphics::LIMIT_TEXTURE_SIZE:
  1337. return (double) gl.getMaxTextureSize();
  1338. case Graphics::LIMIT_MULTI_CANVAS:
  1339. return (double) gl.getMaxRenderTargets();
  1340. case Graphics::LIMIT_CANVAS_MSAA:
  1341. return (double) gl.getMaxRenderbufferSamples();
  1342. default:
  1343. return 0.0;
  1344. }
  1345. }
  1346. bool Graphics::isSupported(Support feature) const
  1347. {
  1348. switch (feature)
  1349. {
  1350. case SUPPORT_MULTI_CANVAS_FORMATS:
  1351. return Canvas::isMultiFormatMultiCanvasSupported();
  1352. case SUPPORT_CLAMP_ZERO:
  1353. return gl.isClampZeroTextureWrapSupported();
  1354. case SUPPORT_LIGHTEN:
  1355. return GLAD_VERSION_1_4 || GLAD_ES_VERSION_3_0 || GLAD_EXT_blend_minmax;
  1356. default:
  1357. return false;
  1358. }
  1359. }
  1360. void Graphics::push(StackType type)
  1361. {
  1362. if (stackTypes.size() == MAX_USER_STACK_DEPTH)
  1363. throw Exception("Maximum stack depth reached (more pushes than pops?)");
  1364. gl.pushTransform();
  1365. pixelSizeStack.push_back(pixelSizeStack.back());
  1366. if (type == STACK_ALL)
  1367. states.push_back(states.back());
  1368. stackTypes.push_back(type);
  1369. }
  1370. void Graphics::pop()
  1371. {
  1372. if (stackTypes.size() < 1)
  1373. throw Exception("Minimum stack depth reached (more pops than pushes?)");
  1374. gl.popTransform();
  1375. pixelSizeStack.pop_back();
  1376. if (stackTypes.back() == STACK_ALL)
  1377. {
  1378. DisplayState &newstate = states[states.size() - 2];
  1379. restoreStateChecked(newstate);
  1380. // The last two states in the stack should be equal now.
  1381. states.pop_back();
  1382. }
  1383. stackTypes.pop_back();
  1384. }
  1385. void Graphics::rotate(float r)
  1386. {
  1387. gl.getTransform().rotate(r);
  1388. }
  1389. void Graphics::scale(float x, float y)
  1390. {
  1391. gl.getTransform().scale(x, y);
  1392. pixelSizeStack.back() *= 2. / (fabs(x) + fabs(y));
  1393. }
  1394. void Graphics::translate(float x, float y)
  1395. {
  1396. gl.getTransform().translate(x, y);
  1397. }
  1398. void Graphics::shear(float kx, float ky)
  1399. {
  1400. gl.getTransform().shear(kx, ky);
  1401. }
  1402. void Graphics::origin()
  1403. {
  1404. gl.getTransform().setIdentity();
  1405. pixelSizeStack.back() = 1;
  1406. }
  1407. } // opengl
  1408. } // graphics
  1409. } // love