Graphics.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812
  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. auto hinting = font::TrueTypeRasterizer::HINTING_NORMAL;
  165. StrongRef<font::Rasterizer> r(fontmodule->newTrueTypeRasterizer(12, hinting), Acquire::NORETAIN);
  166. defaultFont.set(newFont(r.get()), Acquire::NORETAIN);
  167. }
  168. states.back().font.set(defaultFont.get());
  169. }
  170. void Graphics::setViewportSize(int width, int height)
  171. {
  172. this->width = width;
  173. this->height = height;
  174. if (!isCreated())
  175. return;
  176. // We want to affect the main screen, not any Canvas that's currently active
  177. // (not that any *should* be active when this is called.)
  178. std::vector<StrongRef<Canvas>> canvases = states.back().canvases;
  179. setCanvas();
  180. // Set the viewport to top-left corner.
  181. gl.setViewport({0, 0, width, height});
  182. // If a canvas was bound before this function was called, it needs to be
  183. // made aware of the new system viewport size.
  184. Canvas::systemViewport = gl.getViewport();
  185. // Set up the projection matrix
  186. gl.matrices.projection.back() = Matrix4::ortho(0.0, (float) width, (float) height, 0.0);
  187. // Restore the previously active Canvas.
  188. setCanvas(canvases);
  189. }
  190. bool Graphics::setMode(int width, int height)
  191. {
  192. currentWindow.set(Module::getInstance<love::window::Window>(Module::M_WINDOW));
  193. this->width = width;
  194. this->height = height;
  195. // Okay, setup OpenGL.
  196. gl.initContext();
  197. gl.setupContext();
  198. created = true;
  199. // Enable blending
  200. glEnable(GL_BLEND);
  201. // Auto-generated mipmaps should be the best quality possible
  202. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  203. if (!GLAD_ES_VERSION_2_0)
  204. {
  205. // Make sure antialiasing works when set elsewhere
  206. glEnable(GL_MULTISAMPLE);
  207. // Enable texturing
  208. glEnable(GL_TEXTURE_2D);
  209. }
  210. gl.setTextureUnit(0);
  211. // Set pixel row alignment
  212. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  213. // Set whether drawing converts input from linear -> sRGB colorspace.
  214. if (GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_sRGB || GLAD_EXT_framebuffer_sRGB
  215. || GLAD_ES_VERSION_3_0 || GLAD_EXT_sRGB)
  216. {
  217. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  218. gl.setFramebufferSRGB(isGammaCorrect());
  219. }
  220. else
  221. setGammaCorrect(false);
  222. Canvas::screenHasSRGB = isGammaCorrect();
  223. bool enabledebug = false;
  224. if (GLAD_VERSION_3_0)
  225. {
  226. // Enable OpenGL's debug output if a debug context has been created.
  227. GLint flags = 0;
  228. glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
  229. enabledebug = (flags & GL_CONTEXT_FLAG_DEBUG_BIT) != 0;
  230. }
  231. setDebug(enabledebug);
  232. // Reload all volatile objects.
  233. if (!Volatile::loadAll())
  234. ::printf("Could not reload all volatile objects.\n");
  235. // Create a quad indices object owned by love.graphics, so at least one
  236. // QuadIndices object is alive at all times while love.graphics is alive.
  237. // This makes sure there aren't too many expensive destruction/creations of
  238. // index buffer objects, since the shared index buffer used by QuadIndices
  239. // objects is destroyed when the last object is destroyed.
  240. if (quadIndices == nullptr)
  241. quadIndices = new QuadIndices(20);
  242. setViewportSize(width, height);
  243. // Restore the graphics state.
  244. restoreState(states.back());
  245. pixelSizeStack.clear();
  246. pixelSizeStack.reserve(5);
  247. pixelSizeStack.push_back(1);
  248. int gammacorrect = isGammaCorrect() ? 1 : 0;
  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][gammacorrect]);
  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][gammacorrect]);
  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::clear(Colorf c)
  344. {
  345. gammaCorrectColor(c);
  346. glClearColor(c.r, c.g, c.b, c.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, colors[i].g, colors[i].b, colors[i].a};
  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::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 = c;
  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:
  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, const Matrix4 &m)
  1009. {
  1010. checkSetDefaultFont();
  1011. DisplayState &state = states.back();
  1012. if (state.font.get() != nullptr)
  1013. state.font->print(str, m);
  1014. }
  1015. void Graphics::printf(const std::vector<Font::ColoredString> &str, float wrap, Font::AlignMode align, const Matrix4 &m)
  1016. {
  1017. checkSetDefaultFont();
  1018. DisplayState &state = states.back();
  1019. if (state.font.get() != nullptr)
  1020. state.font->printf(str, wrap, align, m);
  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.bindTextureToUnit(gl.getDefaultTexture(), 0, false);
  1030. gl.bindBuffer(BUFFER_VERTEX, 0);
  1031. uint32 attribflags = ATTRIBFLAG_POS;
  1032. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, 0, coords);
  1033. if (colors)
  1034. {
  1035. attribflags |= ATTRIBFLAG_COLOR;
  1036. glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colors);
  1037. }
  1038. gl.useVertexAttribArrays(attribflags);
  1039. gl.drawArrays(GL_POINTS, 0, (GLsizei) numpoints);
  1040. }
  1041. void Graphics::polyline(const float *coords, size_t count)
  1042. {
  1043. const DisplayState &state = states.back();
  1044. if (state.lineJoin == LINE_JOIN_NONE)
  1045. {
  1046. NoneJoinPolyline line;
  1047. line.render(coords, count, state.lineWidth * .5f, float(pixelSizeStack.back()), state.lineStyle == LINE_SMOOTH);
  1048. line.draw();
  1049. }
  1050. else if (state.lineJoin == LINE_JOIN_BEVEL)
  1051. {
  1052. BevelJoinPolyline line;
  1053. line.render(coords, count, state.lineWidth * .5f, float(pixelSizeStack.back()), state.lineStyle == LINE_SMOOTH);
  1054. line.draw();
  1055. }
  1056. else // LINE_JOIN_MITER
  1057. {
  1058. MiterJoinPolyline line;
  1059. line.render(coords, count, state.lineWidth * .5f, float(pixelSizeStack.back()), state.lineStyle == LINE_SMOOTH);
  1060. line.draw();
  1061. }
  1062. }
  1063. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  1064. {
  1065. float coords[] = {x,y, x,y+h, x+w,y+h, x+w,y, x,y};
  1066. polygon(mode, coords, 5 * 2);
  1067. }
  1068. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry, int points)
  1069. {
  1070. if (rx == 0 || ry == 0)
  1071. {
  1072. rectangle(mode, x, y, w, h);
  1073. return;
  1074. }
  1075. // Radius values that are more than half the rectangle's size aren't handled
  1076. // correctly (for now)...
  1077. if (w >= 0.02f)
  1078. rx = std::min(rx, w / 2.0f - 0.01f);
  1079. if (h >= 0.02f)
  1080. ry = std::min(ry, h / 2.0f - 0.01f);
  1081. points = std::max(points / 4, 1);
  1082. const float half_pi = static_cast<float>(LOVE_M_PI / 2);
  1083. float angle_shift = half_pi / ((float) points + 1.0f);
  1084. int num_coords = (points + 2) * 8;
  1085. float *coords = new float[num_coords + 2];
  1086. float phi = .0f;
  1087. for (int i = 0; i <= points + 2; ++i, phi += angle_shift)
  1088. {
  1089. coords[2 * i + 0] = x + rx * (1 - cosf(phi));
  1090. coords[2 * i + 1] = y + ry * (1 - sinf(phi));
  1091. }
  1092. phi = half_pi;
  1093. for (int i = points + 2; i <= 2 * (points + 2); ++i, phi += angle_shift)
  1094. {
  1095. coords[2 * i + 0] = x + w - rx * (1 + cosf(phi));
  1096. coords[2 * i + 1] = y + ry * (1 - sinf(phi));
  1097. }
  1098. phi = 2 * half_pi;
  1099. for (int i = 2 * (points + 2); i <= 3 * (points + 2); ++i, phi += angle_shift)
  1100. {
  1101. coords[2 * i + 0] = x + w - rx * (1 + cosf(phi));
  1102. coords[2 * i + 1] = y + h - ry * (1 + sinf(phi));
  1103. }
  1104. phi = 3 * half_pi;
  1105. for (int i = 3 * (points + 2); i <= 4 * (points + 2); ++i, phi += angle_shift)
  1106. {
  1107. coords[2 * i + 0] = x + rx * (1 - cosf(phi));
  1108. coords[2 * i + 1] = y + h - ry * (1 + sinf(phi));
  1109. }
  1110. coords[num_coords + 0] = coords[0];
  1111. coords[num_coords + 1] = coords[1];
  1112. polygon(mode, coords, num_coords + 2);
  1113. delete[] coords;
  1114. }
  1115. int Graphics::calculateEllipsePoints(float rx, float ry) const
  1116. {
  1117. float pixelScale = 1.0f / std::max((float) pixelSizeStack.back(), 0.00001f);
  1118. int points = (int) sqrtf(((rx + ry) / 2.0f) * 20.0f * pixelScale);
  1119. return std::max(points, 8);
  1120. }
  1121. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry)
  1122. {
  1123. rectangle(mode, x, y, w, h, rx, ry, calculateEllipsePoints(rx, ry));
  1124. }
  1125. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  1126. {
  1127. ellipse(mode, x, y, radius, radius, points);
  1128. }
  1129. void Graphics::circle(DrawMode mode, float x, float y, float radius)
  1130. {
  1131. ellipse(mode, x, y, radius, radius);
  1132. }
  1133. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b, int points)
  1134. {
  1135. float two_pi = static_cast<float>(LOVE_M_PI * 2);
  1136. if (points <= 0) points = 1;
  1137. float angle_shift = (two_pi / points);
  1138. float phi = .0f;
  1139. float *coords = new float[2 * (points + 1)];
  1140. for (int i = 0; i < points; ++i, phi += angle_shift)
  1141. {
  1142. coords[2*i+0] = x + a * cosf(phi);
  1143. coords[2*i+1] = y + b * sinf(phi);
  1144. }
  1145. coords[2*points+0] = coords[0];
  1146. coords[2*points+1] = coords[1];
  1147. polygon(mode, coords, (points + 1) * 2);
  1148. delete[] coords;
  1149. }
  1150. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b)
  1151. {
  1152. ellipse(mode, x, y, a, b, calculateEllipsePoints(a, b));
  1153. }
  1154. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2, int points)
  1155. {
  1156. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  1157. if (points <= 0 || angle1 == angle2)
  1158. return;
  1159. // Oh, you want to draw a circle?
  1160. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  1161. {
  1162. circle(drawmode, x, y, radius, points);
  1163. return;
  1164. }
  1165. float angle_shift = (angle2 - angle1) / points;
  1166. // Bail on precision issues.
  1167. if (angle_shift == 0.0)
  1168. return;
  1169. // Prevent the connecting line from being drawn if a closed line arc has a
  1170. // small angle. Avoids some visual issues when connected lines are at sharp
  1171. // angles, due to the miter line join drawing code.
  1172. if (drawmode == DRAW_LINE && arcmode == ARC_CLOSED && fabsf(angle1 - angle2) < LOVE_TORAD(4))
  1173. arcmode = ARC_OPEN;
  1174. // Quick fix for the last part of a filled open arc not being drawn (because
  1175. // polygon(DRAW_FILL, ...) doesn't work without a closed loop of vertices.)
  1176. if (drawmode == DRAW_FILL && arcmode == ARC_OPEN)
  1177. arcmode = ARC_CLOSED;
  1178. float phi = angle1;
  1179. float *coords = nullptr;
  1180. int num_coords = 0;
  1181. const auto createPoints = [&](float *coordinates)
  1182. {
  1183. for (int i = 0; i <= points; ++i, phi += angle_shift)
  1184. {
  1185. coordinates[2 * i + 0] = x + radius * cosf(phi);
  1186. coordinates[2 * i + 1] = y + radius * sinf(phi);
  1187. }
  1188. };
  1189. if (arcmode == ARC_PIE)
  1190. {
  1191. num_coords = (points + 3) * 2;
  1192. coords = new float[num_coords];
  1193. coords[0] = coords[num_coords - 2] = x;
  1194. coords[1] = coords[num_coords - 1] = y;
  1195. createPoints(coords + 2);
  1196. }
  1197. else if (arcmode == ARC_OPEN)
  1198. {
  1199. num_coords = (points + 1) * 2;
  1200. coords = new float[num_coords];
  1201. createPoints(coords);
  1202. }
  1203. else // ARC_CLOSED
  1204. {
  1205. num_coords = (points + 2) * 2;
  1206. coords = new float[num_coords];
  1207. createPoints(coords);
  1208. // Connect the ends of the arc.
  1209. coords[num_coords - 2] = coords[0];
  1210. coords[num_coords - 1] = coords[1];
  1211. }
  1212. // NOTE: We rely on polygon() using GL_TRIANGLE_FAN, when fill mode is used.
  1213. polygon(drawmode, coords, num_coords);
  1214. delete[] coords;
  1215. }
  1216. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2)
  1217. {
  1218. float points = (float) calculateEllipsePoints(radius, radius);
  1219. // The amount of points is based on the fraction of the circle created by the arc.
  1220. float angle = fabsf(angle1 - angle2);
  1221. if (angle < 2.0f * (float) LOVE_M_PI)
  1222. points *= angle / (2.0f * (float) LOVE_M_PI);
  1223. arc(drawmode, arcmode, x, y, radius, angle1, angle2, (int) (points + 0.5f));
  1224. }
  1225. /// @param mode the draw mode
  1226. /// @param coords the coordinate array
  1227. /// @param count the number of coordinates/size of the array
  1228. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  1229. {
  1230. // coords is an array of a closed loop of vertices, i.e.
  1231. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  1232. if (mode == DRAW_LINE)
  1233. {
  1234. polyline(coords, count);
  1235. }
  1236. else
  1237. {
  1238. OpenGL::TempDebugGroup debuggroup("Filled polygon draw");
  1239. gl.prepareDraw();
  1240. gl.bindTextureToUnit(gl.getDefaultTexture(), 0, false);
  1241. gl.bindBuffer(BUFFER_VERTEX, 0);
  1242. gl.useVertexAttribArrays(ATTRIBFLAG_POS);
  1243. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, 0, coords);
  1244. gl.drawArrays(GL_TRIANGLE_FAN, 0, (int)count/2-1); // opengl will close the polygon for us
  1245. }
  1246. }
  1247. love::image::ImageData *Graphics::newScreenshot(love::image::Image *image, bool copyAlpha)
  1248. {
  1249. // Temporarily unbind the currently active canvas (glReadPixels reads the
  1250. // active framebuffer, not the main one.)
  1251. std::vector<StrongRef<Canvas>> canvases = states.back().canvases;
  1252. setCanvas();
  1253. int w = getWidth();
  1254. int h = getHeight();
  1255. int row = 4 * w;
  1256. int size = row * h;
  1257. GLubyte *pixels = nullptr;
  1258. GLubyte *screenshot = nullptr;
  1259. try
  1260. {
  1261. pixels = new GLubyte[size];
  1262. screenshot = new GLubyte[size];
  1263. }
  1264. catch (std::exception &)
  1265. {
  1266. delete[] pixels;
  1267. delete[] screenshot;
  1268. setCanvas(canvases);
  1269. throw love::Exception("Out of memory.");
  1270. }
  1271. #ifdef LOVE_IOS
  1272. SDL_SysWMinfo info = {};
  1273. SDL_VERSION(&info.version);
  1274. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  1275. if (info.info.uikit.resolveFramebuffer != 0)
  1276. {
  1277. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, info.info.uikit.resolveFramebuffer);
  1278. // We need to do an explicit MSAA resolve on iOS, because it uses GLES
  1279. // FBOs rather than a system framebuffer.
  1280. if (GLAD_ES_VERSION_3_0)
  1281. glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  1282. else if (GLAD_APPLE_framebuffer_multisample)
  1283. glResolveMultisampleFramebufferAPPLE();
  1284. glBindFramebuffer(GL_READ_FRAMEBUFFER, info.info.uikit.resolveFramebuffer);
  1285. }
  1286. #endif
  1287. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  1288. #ifdef LOVE_IOS
  1289. // Restore the previous binding for the main framebuffer.
  1290. if (info.info.uikit.resolveFramebuffer != 0)
  1291. glBindFramebuffer(GL_FRAMEBUFFER, gl.getDefaultFBO());
  1292. #endif
  1293. if (!copyAlpha)
  1294. {
  1295. // Replace alpha values with full opacity.
  1296. for (int i = 3; i < size; i += 4)
  1297. pixels[i] = 255;
  1298. }
  1299. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  1300. GLubyte *src = pixels - row;
  1301. GLubyte *dst = screenshot + size;
  1302. for (int i = 0; i < h; ++i)
  1303. memcpy(dst-=row, src+=row, row);
  1304. delete[] pixels;
  1305. love::image::ImageData *img = nullptr;
  1306. try
  1307. {
  1308. // Tell the new ImageData that it owns the screenshot data, so we don't
  1309. // need to delete it here.
  1310. img = image->newImageData(w, h, image::ImageData::FORMAT_RGBA8, screenshot, true);
  1311. }
  1312. catch (love::Exception &)
  1313. {
  1314. delete[] screenshot;
  1315. setCanvas(canvases);
  1316. throw;
  1317. }
  1318. // Re-bind the active canvas, if necessary.
  1319. setCanvas(canvases);
  1320. return img;
  1321. }
  1322. Graphics::RendererInfo Graphics::getRendererInfo() const
  1323. {
  1324. RendererInfo info;
  1325. if (GLAD_ES_VERSION_2_0)
  1326. info.name = "OpenGL ES";
  1327. else
  1328. info.name = "OpenGL";
  1329. const char *str = (const char *) glGetString(GL_VERSION);
  1330. if (str)
  1331. info.version = str;
  1332. else
  1333. throw love::Exception("Cannot retrieve renderer version information.");
  1334. str = (const char *) glGetString(GL_VENDOR);
  1335. if (str)
  1336. info.vendor = str;
  1337. else
  1338. throw love::Exception("Cannot retrieve renderer vendor information.");
  1339. str = (const char *) glGetString(GL_RENDERER);
  1340. if (str)
  1341. info.device = str;
  1342. else
  1343. throw love::Exception("Cannot retrieve renderer device information.");
  1344. return info;
  1345. }
  1346. Graphics::Stats Graphics::getStats() const
  1347. {
  1348. Stats stats;
  1349. stats.drawCalls = gl.stats.drawCalls;
  1350. stats.canvasSwitches = gl.stats.framebufferBinds;
  1351. stats.shaderSwitches = gl.stats.shaderSwitches;
  1352. stats.canvases = Canvas::canvasCount;
  1353. stats.images = Image::imageCount;
  1354. stats.fonts = Font::fontCount;
  1355. stats.textureMemory = gl.stats.textureMemory;
  1356. return stats;
  1357. }
  1358. double Graphics::getSystemLimit(SystemLimit limittype) const
  1359. {
  1360. switch (limittype)
  1361. {
  1362. case Graphics::LIMIT_POINT_SIZE:
  1363. return (double) gl.getMaxPointSize();
  1364. case Graphics::LIMIT_TEXTURE_SIZE:
  1365. return (double) gl.getMaxTextureSize();
  1366. case Graphics::LIMIT_MULTI_CANVAS:
  1367. return (double) gl.getMaxRenderTargets();
  1368. case Graphics::LIMIT_CANVAS_MSAA:
  1369. return (double) gl.getMaxRenderbufferSamples();
  1370. default:
  1371. return 0.0;
  1372. }
  1373. }
  1374. bool Graphics::isSupported(Feature feature) const
  1375. {
  1376. switch (feature)
  1377. {
  1378. case FEATURE_MULTI_CANVAS_FORMATS:
  1379. return Canvas::isMultiFormatMultiCanvasSupported();
  1380. case FEATURE_CLAMP_ZERO:
  1381. return gl.isClampZeroTextureWrapSupported();
  1382. case FEATURE_LIGHTEN:
  1383. return GLAD_VERSION_1_4 || GLAD_ES_VERSION_3_0 || GLAD_EXT_blend_minmax;
  1384. default:
  1385. return false;
  1386. }
  1387. }
  1388. void Graphics::push(StackType type)
  1389. {
  1390. if (stackTypes.size() == MAX_USER_STACK_DEPTH)
  1391. throw Exception("Maximum stack depth reached (more pushes than pops?)");
  1392. gl.pushTransform();
  1393. pixelSizeStack.push_back(pixelSizeStack.back());
  1394. if (type == STACK_ALL)
  1395. states.push_back(states.back());
  1396. stackTypes.push_back(type);
  1397. }
  1398. void Graphics::pop()
  1399. {
  1400. if (stackTypes.size() < 1)
  1401. throw Exception("Minimum stack depth reached (more pops than pushes?)");
  1402. gl.popTransform();
  1403. pixelSizeStack.pop_back();
  1404. if (stackTypes.back() == STACK_ALL)
  1405. {
  1406. DisplayState &newstate = states[states.size() - 2];
  1407. restoreStateChecked(newstate);
  1408. // The last two states in the stack should be equal now.
  1409. states.pop_back();
  1410. }
  1411. stackTypes.pop_back();
  1412. }
  1413. void Graphics::rotate(float r)
  1414. {
  1415. gl.getTransform().rotate(r);
  1416. }
  1417. void Graphics::scale(float x, float y)
  1418. {
  1419. gl.getTransform().scale(x, y);
  1420. pixelSizeStack.back() *= 2. / (fabs(x) + fabs(y));
  1421. }
  1422. void Graphics::translate(float x, float y)
  1423. {
  1424. gl.getTransform().translate(x, y);
  1425. }
  1426. void Graphics::shear(float kx, float ky)
  1427. {
  1428. gl.getTransform().shear(kx, ky);
  1429. }
  1430. void Graphics::origin()
  1431. {
  1432. gl.getTransform().setIdentity();
  1433. pixelSizeStack.back() = 1;
  1434. }
  1435. Vector Graphics::transformPoint(Vector point)
  1436. {
  1437. Vector p;
  1438. gl.getTransform().transform(&p, &point, 1);
  1439. return p;
  1440. }
  1441. Vector Graphics::inverseTransformPoint(Vector point)
  1442. {
  1443. Vector p;
  1444. // TODO: We should probably cache the inverse transform so we don't have to
  1445. // re-calculate it every time this is called.
  1446. gl.getTransform().inverse().transform(&p, &point, 1);
  1447. return p;
  1448. }
  1449. } // opengl
  1450. } // graphics
  1451. } // love