Graphics.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  1. /**
  2. * Copyright (c) 2006-2015 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::clear(Colorf c)
  344. {
  345. Colorf nc = Colorf(c.r/255.0f, c.g/255.0f, c.b/255.0f, c.a/255.0f);
  346. gammaCorrectColor(nc);
  347. glClearColor(nc.r, nc.g, nc.b, nc.a);
  348. glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  349. }
  350. void Graphics::clear(const std::vector<Colorf> &colors)
  351. {
  352. if (colors.size() == 0)
  353. return;
  354. if (states.back().canvases.size() == 0)
  355. return clear(colors[0]);
  356. if (colors.size() != states.back().canvases.size())
  357. throw love::Exception("Number of clear colors must match the number of active canvases (%ld)", states.back().canvases.size());
  358. std::vector<GLenum> bufs;
  359. for (int i = 0; i < (int) colors.size(); i++)
  360. {
  361. GLfloat c[] = {colors[i].r/255.f, colors[i].g/255.f, colors[i].b/255.f, colors[i].a/255.f};
  362. // TODO: Investigate a potential bug on AMD drivers in Windows/Linux
  363. // which apparently causes the clear color to be incorrect when mixed
  364. // sRGB and linear render targets are active.
  365. if (isGammaCorrect())
  366. {
  367. for (int i = 0; i < 3; i++)
  368. c[i] = math::Math::instance.gammaToLinear(c[i]);
  369. }
  370. if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0)
  371. glClearBufferfv(GL_COLOR, i, c);
  372. else
  373. {
  374. bufs.push_back(GL_COLOR_ATTACHMENT0 + i);
  375. glDrawBuffer(GL_COLOR_ATTACHMENT0 + i);
  376. glClearColor(c[0], c[1], c[2], c[3]);
  377. glClear(GL_COLOR_BUFFER_BIT);
  378. }
  379. }
  380. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  381. // Revert to the expected draw buffers once we're done, if glClearBuffer
  382. // wasn't supported.
  383. if (!(GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0))
  384. {
  385. if (bufs.size() > 1)
  386. glDrawBuffers((int) bufs.size(), &bufs[0]);
  387. else
  388. glDrawBuffer(GL_COLOR_ATTACHMENT0);
  389. }
  390. }
  391. void Graphics::discard(const std::vector<bool> &colorbuffers, bool stencil)
  392. {
  393. if (!(GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0 || GLAD_EXT_discard_framebuffer))
  394. return;
  395. std::vector<GLenum> attachments;
  396. attachments.reserve(colorbuffers.size());
  397. // glDiscardFramebuffer uses different attachment enums for the default FBO.
  398. if (!Canvas::current && gl.getDefaultFBO() == 0)
  399. {
  400. if (colorbuffers.size() > 0 && colorbuffers[0])
  401. attachments.push_back(GL_COLOR);
  402. if (stencil)
  403. {
  404. attachments.push_back(GL_STENCIL);
  405. attachments.push_back(GL_DEPTH);
  406. }
  407. }
  408. else
  409. {
  410. int rendertargetcount = 1;
  411. if (Canvas::current)
  412. rendertargetcount = (int) states.back().canvases.size();
  413. for (int i = 0; i < (int) colorbuffers.size(); i++)
  414. {
  415. if (colorbuffers[i] && i < rendertargetcount)
  416. attachments.push_back(GL_COLOR_ATTACHMENT0 + i);
  417. }
  418. if (stencil)
  419. {
  420. attachments.push_back(GL_STENCIL_ATTACHMENT);
  421. attachments.push_back(GL_DEPTH_ATTACHMENT);
  422. }
  423. }
  424. // Hint for the driver that it doesn't need to save these buffers.
  425. if (GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0)
  426. glInvalidateFramebuffer(GL_FRAMEBUFFER, (GLint) attachments.size(), &attachments[0]);
  427. else if (GLAD_EXT_discard_framebuffer)
  428. glDiscardFramebufferEXT(GL_FRAMEBUFFER, (GLint) attachments.size(), &attachments[0]);
  429. }
  430. void Graphics::present()
  431. {
  432. if (!isActive())
  433. return;
  434. // Make sure we don't have a canvas active.
  435. std::vector<StrongRef<Canvas>> canvases = states.back().canvases;
  436. setCanvas();
  437. // Discard the stencil buffer before swapping.
  438. discard({}, true);
  439. #ifdef LOVE_IOS
  440. // Hack: SDL's color renderbuffer must be bound when swapBuffers is called.
  441. SDL_SysWMinfo info = {};
  442. SDL_VERSION(&info.version);
  443. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  444. glBindRenderbuffer(GL_RENDERBUFFER, info.info.uikit.colorbuffer);
  445. #endif
  446. if (currentWindow.get())
  447. currentWindow->swapBuffers();
  448. // Restore the currently active canvas, if there is one.
  449. setCanvas(canvases);
  450. // Reset the per-frame stat counts.
  451. gl.stats.drawCalls = 0;
  452. gl.stats.framebufferBinds = 0;
  453. }
  454. int Graphics::getWidth() const
  455. {
  456. return width;
  457. }
  458. int Graphics::getHeight() const
  459. {
  460. return height;
  461. }
  462. bool Graphics::isCreated() const
  463. {
  464. return created;
  465. }
  466. void Graphics::setScissor(int x, int y, int width, int height)
  467. {
  468. ScissorRect rect = {x, y, width, height};
  469. glEnable(GL_SCISSOR_TEST);
  470. // OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
  471. gl.setScissor({rect.x, rect.y, rect.w, rect.h});
  472. states.back().scissor = true;
  473. states.back().scissorRect = rect;
  474. }
  475. void Graphics::intersectScissor(int x, int y, int width, int height)
  476. {
  477. ScissorRect rect = states.back().scissorRect;
  478. if (!states.back().scissor)
  479. {
  480. rect.x = 0;
  481. rect.y = 0;
  482. rect.w = std::numeric_limits<int>::max();
  483. rect.h = std::numeric_limits<int>::max();
  484. }
  485. int x1 = std::max(rect.x, x);
  486. int y1 = std::max(rect.y, y);
  487. int x2 = std::min(rect.x + rect.w, x + width);
  488. int y2 = std::min(rect.y + rect.h, y + height);
  489. setScissor(x1, y1, std::max(0, x2 - x1), std::max(0, y2 - y1));
  490. }
  491. void Graphics::setScissor()
  492. {
  493. states.back().scissor = false;
  494. glDisable(GL_SCISSOR_TEST);
  495. }
  496. bool Graphics::getScissor(int &x, int &y, int &width, int &height) const
  497. {
  498. const DisplayState &state = states.back();
  499. x = state.scissorRect.x;
  500. y = state.scissorRect.y;
  501. width = state.scissorRect.w;
  502. height = state.scissorRect.h;
  503. return state.scissor;
  504. }
  505. void Graphics::drawToStencilBuffer(StencilAction action, int value)
  506. {
  507. writingToStencil = true;
  508. // Make sure the active canvas has a stencil buffer.
  509. if (Canvas::current)
  510. Canvas::current->checkCreateStencil();
  511. // Disable color writes but don't save the state for it.
  512. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  513. GLenum glaction = GL_REPLACE;
  514. switch (action)
  515. {
  516. case STENCIL_REPLACE:
  517. default:
  518. glaction = GL_REPLACE;
  519. break;
  520. case STENCIL_INCREMENT:
  521. glaction = GL_INCR;
  522. break;
  523. case STENCIL_DECREMENT:
  524. glaction = GL_DECR;
  525. break;
  526. case STENCIL_INCREMENT_WRAP:
  527. glaction = GL_INCR_WRAP;
  528. break;
  529. case STENCIL_DECREMENT_WRAP:
  530. glaction = GL_DECR_WRAP;
  531. break;
  532. case STENCIL_INVERT:
  533. glaction = GL_INVERT;
  534. break;
  535. }
  536. // The stencil test must be enabled in order to write to the stencil buffer.
  537. glEnable(GL_STENCIL_TEST);
  538. glStencilFunc(GL_ALWAYS, value, 0xFFFFFFFF);
  539. glStencilOp(GL_KEEP, GL_KEEP, glaction);
  540. }
  541. void Graphics::stopDrawToStencilBuffer()
  542. {
  543. if (!writingToStencil)
  544. return;
  545. writingToStencil = false;
  546. const DisplayState &state = states.back();
  547. // Revert the color write mask.
  548. setColorMask(state.colorMask);
  549. // Use the user-set stencil test state when writes are disabled.
  550. setStencilTest(state.stencilCompare, state.stencilTestValue);
  551. }
  552. void Graphics::setStencilTest(CompareMode compare, int value)
  553. {
  554. DisplayState &state = states.back();
  555. state.stencilCompare = compare;
  556. state.stencilTestValue = value;
  557. if (writingToStencil)
  558. return;
  559. if (compare == COMPARE_ALWAYS)
  560. {
  561. glDisable(GL_STENCIL_TEST);
  562. return;
  563. }
  564. // Make sure the active canvas has a stencil buffer.
  565. if (Canvas::current)
  566. Canvas::current->checkCreateStencil();
  567. GLenum glcompare = GL_EQUAL;
  568. /**
  569. * Q: Why are some of the compare modes inverted (e.g. COMPARE_LESS becomes
  570. * GL_GREATER)?
  571. *
  572. * A: OpenGL / GPUs do the comparison in the opposite way that makes sense
  573. * for this API. For example, if the compare function is GL_GREATER then the
  574. * stencil test will pass if the reference value is greater than the value
  575. * in the stencil buffer. With our API it's more intuitive to assume that
  576. * setStencilTest(COMPARE_GREATER, 4) will make it pass if the stencil
  577. * buffer has a value greater than 4.
  578. **/
  579. switch (compare)
  580. {
  581. case COMPARE_LESS:
  582. glcompare = GL_GREATER;
  583. break;
  584. case COMPARE_LEQUAL:
  585. glcompare = GL_GEQUAL;
  586. break;
  587. case COMPARE_EQUAL:
  588. default:
  589. glcompare = GL_EQUAL;
  590. break;
  591. case COMPARE_GEQUAL:
  592. glcompare = GL_LEQUAL;
  593. break;
  594. case COMPARE_GREATER:
  595. glcompare = GL_LESS;
  596. break;
  597. case COMPARE_NOTEQUAL:
  598. glcompare = GL_NOTEQUAL;
  599. break;
  600. case COMPARE_ALWAYS:
  601. glcompare = GL_ALWAYS;
  602. break;
  603. }
  604. glEnable(GL_STENCIL_TEST);
  605. glStencilFunc(glcompare, value, 0xFFFFFFFF);
  606. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  607. }
  608. void Graphics::setStencilTest()
  609. {
  610. setStencilTest(COMPARE_ALWAYS, 0);
  611. }
  612. void Graphics::getStencilTest(CompareMode &compare, int &value)
  613. {
  614. const DisplayState &state = states.back();
  615. compare = state.stencilCompare;
  616. value = state.stencilTestValue;
  617. }
  618. void Graphics::clearStencil()
  619. {
  620. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  621. }
  622. Image *Graphics::newImage(const std::vector<love::image::ImageData *> &data, const Image::Flags &flags)
  623. {
  624. return new Image(data, flags);
  625. }
  626. Image *Graphics::newImage(const std::vector<love::image::CompressedImageData *> &cdata, const Image::Flags &flags)
  627. {
  628. return new Image(cdata, flags);
  629. }
  630. Quad *Graphics::newQuad(Quad::Viewport v, double sw, double sh)
  631. {
  632. return new Quad(v, sw, sh);
  633. }
  634. Font *Graphics::newFont(love::font::Rasterizer *r, const Texture::Filter &filter)
  635. {
  636. return new Font(r, filter);
  637. }
  638. SpriteBatch *Graphics::newSpriteBatch(Texture *texture, int size, Mesh::Usage usage)
  639. {
  640. return new SpriteBatch(texture, size, usage);
  641. }
  642. ParticleSystem *Graphics::newParticleSystem(Texture *texture, int size)
  643. {
  644. return new ParticleSystem(texture, size);
  645. }
  646. Canvas *Graphics::newCanvas(int width, int height, Canvas::Format format, int msaa)
  647. {
  648. if (!Canvas::isFormatSupported(format))
  649. {
  650. const char *fstr = "rgba8";
  651. Canvas::getConstant(format, fstr);
  652. throw love::Exception("The %s canvas format is not supported by your OpenGL implementation.", fstr);
  653. }
  654. if (width > gl.getMaxTextureSize())
  655. throw Exception("Cannot create canvas: width of %d pixels is too large for this system.", width);
  656. else if (height > gl.getMaxTextureSize())
  657. throw Exception("Cannot create canvas: height of %d pixels is too large for this system.", height);
  658. while (GL_NO_ERROR != glGetError())
  659. /* clear opengl error flag */;
  660. Canvas *canvas = new Canvas(width, height, format, msaa);
  661. GLenum err = canvas->getStatus();
  662. // everything ok, return canvas (early out)
  663. if (err == GL_FRAMEBUFFER_COMPLETE)
  664. return canvas;
  665. // create error message
  666. std::stringstream error_string;
  667. error_string << "Cannot create canvas: ";
  668. switch (err)
  669. {
  670. case GL_FRAMEBUFFER_UNSUPPORTED:
  671. error_string << "Not supported by your OpenGL implementation.";
  672. break;
  673. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  674. error_string << "Texture format cannot be rendered to on this system.";
  675. break;
  676. // remaining error codes are highly unlikely:
  677. case GL_FRAMEBUFFER_UNDEFINED:
  678. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  679. case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
  680. case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
  681. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  682. error_string << "Error in implementation.";
  683. break;
  684. default:
  685. // my intel hda card wrongly returns 0 to glCheckFramebufferStatus() but sets
  686. // no error flag. I think it meant to return GL_FRAMEBUFFER_UNSUPPORTED, but who
  687. // knows.
  688. if (glGetError() == GL_NO_ERROR)
  689. error_string << "May not be supported by your OpenGL implementation.";
  690. // the remaining error is an indication of a serious fuckup since it should
  691. // only be returned if glCheckFramebufferStatus() was called with the wrong
  692. // arguments.
  693. else
  694. error_string << "Cannot create canvas: Aliens did it (OpenGL error code: " << glGetError() << ")";
  695. }
  696. canvas->release();
  697. throw Exception("%s", error_string.str().c_str());
  698. return nullptr; // never reached
  699. }
  700. Shader *Graphics::newShader(const Shader::ShaderSource &source)
  701. {
  702. return new Shader(source);
  703. }
  704. Mesh *Graphics::newMesh(const std::vector<Vertex> &vertices, Mesh::DrawMode drawmode, Mesh::Usage usage)
  705. {
  706. return new Mesh(vertices, drawmode, usage);
  707. }
  708. Mesh *Graphics::newMesh(int vertexcount, Mesh::DrawMode drawmode, Mesh::Usage usage)
  709. {
  710. return new Mesh(vertexcount, drawmode, usage);
  711. }
  712. Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, int vertexcount, Mesh::DrawMode drawmode, Mesh::Usage usage)
  713. {
  714. return new Mesh(vertexformat, vertexcount, drawmode, usage);
  715. }
  716. Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, const void *data, size_t datasize, Mesh::DrawMode drawmode, Mesh::Usage usage)
  717. {
  718. return new Mesh(vertexformat, data, datasize, drawmode, usage);
  719. }
  720. Text *Graphics::newText(Font *font, const std::vector<Font::ColoredString> &text)
  721. {
  722. return new Text(font, text);
  723. }
  724. Video *Graphics::newVideo(love::video::VideoStream *stream)
  725. {
  726. return new Video(stream);
  727. }
  728. bool Graphics::isGammaCorrect() const
  729. {
  730. return love::graphics::isGammaCorrect();
  731. }
  732. void Graphics::setColor(Colorf c)
  733. {
  734. Colorf nc = Colorf(c.r/255.0f, c.g/255.0f, c.b/255.0f, c.a/255.0f);
  735. gammaCorrectColor(nc);
  736. glVertexAttrib4f(ATTRIB_CONSTANTCOLOR, nc.r, nc.g, nc.b, nc.a);
  737. states.back().color = c;
  738. }
  739. Colorf Graphics::getColor() const
  740. {
  741. return states.back().color;
  742. }
  743. void Graphics::setBackgroundColor(Colorf c)
  744. {
  745. states.back().backgroundColor = c;
  746. }
  747. Colorf Graphics::getBackgroundColor() const
  748. {
  749. return states.back().backgroundColor;
  750. }
  751. void Graphics::setFont(Font *font)
  752. {
  753. // We don't need to set a default font here if null is passed in, since we
  754. // only care about the default font in getFont and print.
  755. DisplayState &state = states.back();
  756. state.font.set(font);
  757. }
  758. Font *Graphics::getFont()
  759. {
  760. checkSetDefaultFont();
  761. return states.back().font.get();
  762. }
  763. void Graphics::setShader(Shader *shader)
  764. {
  765. if (shader == nullptr)
  766. return setShader();
  767. DisplayState &state = states.back();
  768. shader->attach();
  769. state.shader.set(shader);
  770. }
  771. void Graphics::setShader()
  772. {
  773. DisplayState &state = states.back();
  774. // This will activate the default shader.
  775. Shader::detach();
  776. state.shader.set(nullptr);
  777. }
  778. Shader *Graphics::getShader() const
  779. {
  780. return states.back().shader.get();
  781. }
  782. void Graphics::setCanvas(Canvas *canvas)
  783. {
  784. if (canvas == nullptr)
  785. return setCanvas();
  786. DisplayState &state = states.back();
  787. canvas->startGrab();
  788. std::vector<StrongRef<Canvas>> canvasref;
  789. canvasref.push_back(canvas);
  790. std::swap(state.canvases, canvasref);
  791. }
  792. void Graphics::setCanvas(const std::vector<Canvas *> &canvases)
  793. {
  794. if (canvases.size() == 0)
  795. return setCanvas();
  796. else if (canvases.size() == 1)
  797. return setCanvas(canvases[0]);
  798. DisplayState &state = states.back();
  799. auto attachments = std::vector<Canvas *>(canvases.begin() + 1, canvases.end());
  800. canvases[0]->startGrab(attachments);
  801. std::vector<StrongRef<Canvas>> canvasrefs;
  802. canvasrefs.reserve(canvases.size());
  803. for (Canvas *c : canvases)
  804. canvasrefs.push_back(c);
  805. std::swap(state.canvases, canvasrefs);
  806. }
  807. void Graphics::setCanvas(const std::vector<StrongRef<Canvas>> &canvases)
  808. {
  809. std::vector<Canvas *> canvaslist;
  810. canvaslist.reserve(canvases.size());
  811. for (const StrongRef<Canvas> &c : canvases)
  812. canvaslist.push_back(c.get());
  813. return setCanvas(canvaslist);
  814. }
  815. void Graphics::setCanvas()
  816. {
  817. DisplayState &state = states.back();
  818. if (Canvas::current != nullptr)
  819. Canvas::current->stopGrab();
  820. state.canvases.clear();
  821. }
  822. std::vector<Canvas *> Graphics::getCanvas() const
  823. {
  824. std::vector<Canvas *> canvases;
  825. canvases.reserve(states.back().canvases.size());
  826. for (const StrongRef<Canvas> &c : states.back().canvases)
  827. canvases.push_back(c.get());
  828. return canvases;
  829. }
  830. void Graphics::setColorMask(ColorMask mask)
  831. {
  832. glColorMask(mask.r, mask.g, mask.b, mask.a);
  833. states.back().colorMask = mask;
  834. }
  835. Graphics::ColorMask Graphics::getColorMask() const
  836. {
  837. return states.back().colorMask;
  838. }
  839. void Graphics::setBlendMode(BlendMode mode, BlendAlpha alphamode)
  840. {
  841. GLenum func = GL_FUNC_ADD;
  842. GLenum srcRGB = GL_ONE;
  843. GLenum srcA = GL_ONE;
  844. GLenum dstRGB = GL_ZERO;
  845. GLenum dstA = GL_ZERO;
  846. switch (mode)
  847. {
  848. case BLEND_ALPHA:
  849. srcRGB = srcA = GL_ONE;
  850. dstRGB = dstA = GL_ONE_MINUS_SRC_ALPHA;
  851. break;
  852. case BLEND_MULTIPLY:
  853. srcRGB = srcA = GL_DST_COLOR;
  854. dstRGB = dstA = GL_ZERO;
  855. break;
  856. case BLEND_SUBTRACT:
  857. func = GL_FUNC_REVERSE_SUBTRACT;
  858. case BLEND_ADD:
  859. srcRGB = GL_ONE;
  860. srcA = GL_ZERO;
  861. dstRGB = dstA = GL_ONE;
  862. break;
  863. case BLEND_SCREEN:
  864. srcRGB = srcA = GL_ONE;
  865. dstRGB = dstA = GL_ONE_MINUS_SRC_COLOR;
  866. break;
  867. case BLEND_REPLACE:
  868. default:
  869. srcRGB = srcA = GL_ONE;
  870. dstRGB = dstA = GL_ZERO;
  871. break;
  872. }
  873. // We can only do alpha-multiplication when srcRGB would have been unmodified.
  874. if (srcRGB == GL_ONE && alphamode == BLENDALPHA_MULTIPLY)
  875. srcRGB = GL_SRC_ALPHA;
  876. glBlendEquation(func);
  877. glBlendFuncSeparate(srcRGB, dstRGB, srcA, dstA);
  878. states.back().blendMode = mode;
  879. states.back().blendAlphaMode = alphamode;
  880. }
  881. Graphics::BlendMode Graphics::getBlendMode(BlendAlpha &alphamode) const
  882. {
  883. alphamode = states.back().blendAlphaMode;
  884. return states.back().blendMode;
  885. }
  886. void Graphics::setDefaultFilter(const Texture::Filter &f)
  887. {
  888. Texture::setDefaultFilter(f);
  889. states.back().defaultFilter = f;
  890. }
  891. const Texture::Filter &Graphics::getDefaultFilter() const
  892. {
  893. return Texture::getDefaultFilter();
  894. }
  895. void Graphics::setDefaultMipmapFilter(Texture::FilterMode filter, float sharpness)
  896. {
  897. Image::setDefaultMipmapFilter(filter);
  898. Image::setDefaultMipmapSharpness(sharpness);
  899. states.back().defaultMipmapFilter = filter;
  900. states.back().defaultMipmapSharpness = sharpness;
  901. }
  902. void Graphics::getDefaultMipmapFilter(Texture::FilterMode *filter, float *sharpness) const
  903. {
  904. *filter = Image::getDefaultMipmapFilter();
  905. *sharpness = Image::getDefaultMipmapSharpness();
  906. }
  907. void Graphics::setLineWidth(float width)
  908. {
  909. states.back().lineWidth = width;
  910. }
  911. void Graphics::setLineStyle(Graphics::LineStyle style)
  912. {
  913. states.back().lineStyle = style;
  914. }
  915. void Graphics::setLineJoin(Graphics::LineJoin join)
  916. {
  917. states.back().lineJoin = join;
  918. }
  919. float Graphics::getLineWidth() const
  920. {
  921. return states.back().lineWidth;
  922. }
  923. Graphics::LineStyle Graphics::getLineStyle() const
  924. {
  925. return states.back().lineStyle;
  926. }
  927. Graphics::LineJoin Graphics::getLineJoin() const
  928. {
  929. return states.back().lineJoin;
  930. }
  931. void Graphics::setPointSize(float size)
  932. {
  933. gl.setPointSize(size);
  934. states.back().pointSize = size;
  935. }
  936. float Graphics::getPointSize() const
  937. {
  938. return states.back().pointSize;
  939. }
  940. void Graphics::setWireframe(bool enable)
  941. {
  942. // Not supported in OpenGL ES.
  943. if (GLAD_ES_VERSION_2_0)
  944. return;
  945. glPolygonMode(GL_FRONT_AND_BACK, enable ? GL_LINE : GL_FILL);
  946. states.back().wireframe = enable;
  947. }
  948. bool Graphics::isWireframe() const
  949. {
  950. return states.back().wireframe;
  951. }
  952. 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)
  953. {
  954. checkSetDefaultFont();
  955. DisplayState &state = states.back();
  956. if (state.font.get() != nullptr)
  957. state.font->print(str, x, y, angle, sx, sy, ox, oy, kx, ky);
  958. }
  959. 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)
  960. {
  961. checkSetDefaultFont();
  962. DisplayState &state = states.back();
  963. if (state.font.get() != nullptr)
  964. state.font->printf(str, x, y, wrap, align, angle, sx, sy, ox, oy, kx, ky);
  965. }
  966. /**
  967. * Primitives
  968. **/
  969. void Graphics::points(const float *coords, const uint8 *colors, size_t numpoints)
  970. {
  971. OpenGL::TempDebugGroup debuggroup("Graphics points draw");
  972. gl.prepareDraw();
  973. gl.bindTexture(gl.getDefaultTexture());
  974. uint32 attribflags = ATTRIBFLAG_POS;
  975. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, 0, coords);
  976. if (colors)
  977. {
  978. attribflags |= ATTRIBFLAG_COLOR;
  979. glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colors);
  980. }
  981. gl.useVertexAttribArrays(attribflags);
  982. gl.drawArrays(GL_POINTS, 0, numpoints);
  983. }
  984. void Graphics::polyline(const float *coords, size_t count)
  985. {
  986. const DisplayState &state = states.back();
  987. if (state.lineJoin == LINE_JOIN_NONE)
  988. {
  989. NoneJoinPolyline line;
  990. line.render(coords, count, state.lineWidth * .5f, float(pixelSizeStack.back()), state.lineStyle == LINE_SMOOTH);
  991. line.draw();
  992. }
  993. else if (state.lineJoin == LINE_JOIN_BEVEL)
  994. {
  995. BevelJoinPolyline line;
  996. line.render(coords, count, state.lineWidth * .5f, float(pixelSizeStack.back()), state.lineStyle == LINE_SMOOTH);
  997. line.draw();
  998. }
  999. else // LINE_JOIN_MITER
  1000. {
  1001. MiterJoinPolyline line;
  1002. line.render(coords, count, state.lineWidth * .5f, float(pixelSizeStack.back()), state.lineStyle == LINE_SMOOTH);
  1003. line.draw();
  1004. }
  1005. }
  1006. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  1007. {
  1008. float coords[] = {x,y, x,y+h, x+w,y+h, x+w,y, x,y};
  1009. polygon(mode, coords, 5 * 2);
  1010. }
  1011. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry, int points)
  1012. {
  1013. if (rx == 0 || ry == 0)
  1014. {
  1015. rectangle(mode, x, y, w, h);
  1016. return;
  1017. }
  1018. // Radius values that are more than half the rectangle's size aren't handled
  1019. // correctly (for now)...
  1020. if (w >= 0.02f)
  1021. rx = std::min(rx, w / 2.0f - 0.01f);
  1022. if (h >= 0.02f)
  1023. ry = std::min(ry, h / 2.0f - 0.01f);
  1024. points = std::max(points, 1);
  1025. const float half_pi = static_cast<float>(LOVE_M_PI / 2);
  1026. float angle_shift = half_pi / ((float) points + 1.0f);
  1027. int num_coords = (points + 2) * 8;
  1028. float *coords = new float[num_coords + 2];
  1029. float phi = .0f;
  1030. for (int i = 0; i <= points + 2; ++i, phi += angle_shift)
  1031. {
  1032. coords[2 * i + 0] = x + rx * (1 - cosf(phi));
  1033. coords[2 * i + 1] = y + ry * (1 - sinf(phi));
  1034. }
  1035. phi = half_pi;
  1036. for (int i = points + 2; i <= 2 * (points + 2); ++i, phi += angle_shift)
  1037. {
  1038. coords[2 * i + 0] = x + w - rx * (1 + cosf(phi));
  1039. coords[2 * i + 1] = y + ry * (1 - sinf(phi));
  1040. }
  1041. phi = 2 * half_pi;
  1042. for (int i = 2 * (points + 2); i <= 3 * (points + 2); ++i, phi += angle_shift)
  1043. {
  1044. coords[2 * i + 0] = x + w - rx * (1 + cosf(phi));
  1045. coords[2 * i + 1] = y + h - ry * (1 + sinf(phi));
  1046. }
  1047. phi = 3 * half_pi;
  1048. for (int i = 3 * (points + 2); i <= 4 * (points + 2); ++i, phi += angle_shift)
  1049. {
  1050. coords[2 * i + 0] = x + rx * (1 - cosf(phi));
  1051. coords[2 * i + 1] = y + h - ry * (1 + sinf(phi));
  1052. }
  1053. coords[num_coords + 0] = coords[0];
  1054. coords[num_coords + 1] = coords[1];
  1055. polygon(mode, coords, num_coords + 2);
  1056. delete[] coords;
  1057. }
  1058. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  1059. {
  1060. ellipse(mode, x, y, radius, radius, points);
  1061. }
  1062. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b, int points)
  1063. {
  1064. float two_pi = static_cast<float>(LOVE_M_PI * 2);
  1065. if (points <= 0) points = 1;
  1066. float angle_shift = (two_pi / points);
  1067. float phi = .0f;
  1068. float *coords = new float[2 * (points + 1)];
  1069. for (int i = 0; i < points; ++i, phi += angle_shift)
  1070. {
  1071. coords[2*i+0] = x + a * cosf(phi);
  1072. coords[2*i+1] = y + b * sinf(phi);
  1073. }
  1074. coords[2*points+0] = coords[0];
  1075. coords[2*points+1] = coords[1];
  1076. polygon(mode, coords, (points + 1) * 2);
  1077. delete[] coords;
  1078. }
  1079. void Graphics::arc(DrawMode mode, float x, float y, float radius, float angle1, float angle2, int points)
  1080. {
  1081. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  1082. if (points <= 0 || angle1 == angle2)
  1083. return;
  1084. // Oh, you want to draw a circle?
  1085. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  1086. {
  1087. circle(mode, x, y, radius, points);
  1088. return;
  1089. }
  1090. float angle_shift = (angle2 - angle1) / points;
  1091. // Bail on precision issues.
  1092. if (angle_shift == 0.0)
  1093. return;
  1094. float phi = angle1;
  1095. int num_coords = (points + 3) * 2;
  1096. float *coords = new float[num_coords];
  1097. coords[0] = coords[num_coords - 2] = x;
  1098. coords[1] = coords[num_coords - 1] = y;
  1099. for (int i = 0; i <= points; ++i, phi += angle_shift)
  1100. {
  1101. coords[2 * (i+1)] = x + radius * cosf(phi);
  1102. coords[2 * (i+1) + 1] = y + radius * sinf(phi);
  1103. }
  1104. // NOTE: We rely on polygon() using GL_TRIANGLE_FAN, when fill mode is used.
  1105. polygon(mode, coords, num_coords);
  1106. delete[] coords;
  1107. }
  1108. /// @param mode the draw mode
  1109. /// @param coords the coordinate array
  1110. /// @param count the number of coordinates/size of the array
  1111. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  1112. {
  1113. // coords is an array of a closed loop of vertices, i.e.
  1114. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  1115. if (mode == DRAW_LINE)
  1116. {
  1117. polyline(coords, count);
  1118. }
  1119. else
  1120. {
  1121. OpenGL::TempDebugGroup debuggroup("Filled polygon draw");
  1122. gl.prepareDraw();
  1123. gl.bindTexture(gl.getDefaultTexture());
  1124. gl.useVertexAttribArrays(ATTRIBFLAG_POS);
  1125. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, 0, coords);
  1126. gl.drawArrays(GL_TRIANGLE_FAN, 0, (int)count/2-1); // opengl will close the polygon for us
  1127. }
  1128. }
  1129. love::image::ImageData *Graphics::newScreenshot(love::image::Image *image, bool copyAlpha)
  1130. {
  1131. // Temporarily unbind the currently active canvas (glReadPixels reads the
  1132. // active framebuffer, not the main one.)
  1133. std::vector<StrongRef<Canvas>> canvases = states.back().canvases;
  1134. setCanvas();
  1135. int w = getWidth();
  1136. int h = getHeight();
  1137. int row = 4 * w;
  1138. int size = row * h;
  1139. GLubyte *pixels = nullptr;
  1140. GLubyte *screenshot = nullptr;
  1141. try
  1142. {
  1143. pixels = new GLubyte[size];
  1144. screenshot = new GLubyte[size];
  1145. }
  1146. catch (std::exception &)
  1147. {
  1148. delete[] pixels;
  1149. delete[] screenshot;
  1150. setCanvas(canvases);
  1151. throw love::Exception("Out of memory.");
  1152. }
  1153. #ifdef LOVE_IOS
  1154. SDL_SysWMinfo info = {};
  1155. SDL_VERSION(&info.version);
  1156. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  1157. if (info.info.uikit.resolveFramebuffer != 0)
  1158. {
  1159. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, info.info.uikit.resolveFramebuffer);
  1160. // We need to do an explicit MSAA resolve on iOS, because it uses GLES
  1161. // FBOs rather than a system framebuffer.
  1162. if (GLAD_ES_VERSION_3_0)
  1163. glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  1164. else if (GLAD_APPLE_framebuffer_multisample)
  1165. glResolveMultisampleFramebufferAPPLE();
  1166. glBindFramebuffer(GL_READ_FRAMEBUFFER, info.info.uikit.resolveFramebuffer);
  1167. }
  1168. #endif
  1169. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  1170. #ifdef LOVE_IOS
  1171. // Restore the previous binding for the main framebuffer.
  1172. if (info.info.uikit.resolveFramebuffer != 0)
  1173. glBindFramebuffer(GL_FRAMEBUFFER, gl.getDefaultFBO());
  1174. #endif
  1175. if (!copyAlpha)
  1176. {
  1177. // Replace alpha values with full opacity.
  1178. for (int i = 3; i < size; i += 4)
  1179. pixels[i] = 255;
  1180. }
  1181. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  1182. GLubyte *src = pixels - row;
  1183. GLubyte *dst = screenshot + size;
  1184. for (int i = 0; i < h; ++i)
  1185. memcpy(dst-=row, src+=row, row);
  1186. delete[] pixels;
  1187. love::image::ImageData *img = nullptr;
  1188. try
  1189. {
  1190. // Tell the new ImageData that it owns the screenshot data, so we don't
  1191. // need to delete it here.
  1192. img = image->newImageData(w, h, (void *) screenshot, true);
  1193. }
  1194. catch (love::Exception &)
  1195. {
  1196. delete[] screenshot;
  1197. setCanvas(canvases);
  1198. throw;
  1199. }
  1200. // Re-bind the active canvas, if necessary.
  1201. setCanvas(canvases);
  1202. return img;
  1203. }
  1204. Graphics::RendererInfo Graphics::getRendererInfo() const
  1205. {
  1206. RendererInfo info;
  1207. if (GLAD_ES_VERSION_2_0)
  1208. info.name = "OpenGL ES";
  1209. else
  1210. info.name = "OpenGL";
  1211. const char *str = (const char *) glGetString(GL_VERSION);
  1212. if (str)
  1213. info.version = str;
  1214. else
  1215. throw love::Exception("Cannot retrieve renderer version information.");
  1216. str = (const char *) glGetString(GL_VENDOR);
  1217. if (str)
  1218. info.vendor = str;
  1219. else
  1220. throw love::Exception("Cannot retrieve renderer vendor information.");
  1221. str = (const char *) glGetString(GL_RENDERER);
  1222. if (str)
  1223. info.device = str;
  1224. else
  1225. throw love::Exception("Cannot retrieve renderer device information.");
  1226. return info;
  1227. }
  1228. Graphics::Stats Graphics::getStats() const
  1229. {
  1230. Stats stats;
  1231. stats.drawCalls = gl.stats.drawCalls;
  1232. stats.canvasSwitches = gl.stats.framebufferBinds;
  1233. stats.canvases = Canvas::canvasCount;
  1234. stats.images = Image::imageCount;
  1235. stats.fonts = Font::fontCount;
  1236. stats.textureMemory = gl.stats.textureMemory;
  1237. return stats;
  1238. }
  1239. double Graphics::getSystemLimit(SystemLimit limittype) const
  1240. {
  1241. switch (limittype)
  1242. {
  1243. case Graphics::LIMIT_POINT_SIZE:
  1244. {
  1245. GLfloat limits[2];
  1246. glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, limits);
  1247. return (double) limits[1];
  1248. }
  1249. case Graphics::LIMIT_TEXTURE_SIZE:
  1250. return (double) gl.getMaxTextureSize();
  1251. case Graphics::LIMIT_MULTI_CANVAS:
  1252. return (double) gl.getMaxRenderTargets();
  1253. case Graphics::LIMIT_CANVAS_MSAA:
  1254. return (double) gl.getMaxRenderbufferSamples();
  1255. default:
  1256. return 0.0;
  1257. }
  1258. }
  1259. bool Graphics::isSupported(Support feature) const
  1260. {
  1261. switch (feature)
  1262. {
  1263. case SUPPORT_MULTI_CANVAS_FORMATS:
  1264. return Canvas::isMultiFormatMultiCanvasSupported();
  1265. case SUPPORT_CLAMP_ZERO:
  1266. return gl.isClampZeroTextureWrapSupported();
  1267. default:
  1268. return false;
  1269. }
  1270. }
  1271. void Graphics::push(StackType type)
  1272. {
  1273. if (stackTypes.size() == MAX_USER_STACK_DEPTH)
  1274. throw Exception("Maximum stack depth reached (more pushes than pops?)");
  1275. gl.pushTransform();
  1276. pixelSizeStack.push_back(pixelSizeStack.back());
  1277. if (type == STACK_ALL)
  1278. states.push_back(states.back());
  1279. stackTypes.push_back(type);
  1280. }
  1281. void Graphics::pop()
  1282. {
  1283. if (stackTypes.size() < 1)
  1284. throw Exception("Minimum stack depth reached (more pops than pushes?)");
  1285. gl.popTransform();
  1286. pixelSizeStack.pop_back();
  1287. if (stackTypes.back() == STACK_ALL)
  1288. {
  1289. DisplayState &newstate = states[states.size() - 2];
  1290. restoreStateChecked(newstate);
  1291. // The last two states in the stack should be equal now.
  1292. states.pop_back();
  1293. }
  1294. stackTypes.pop_back();
  1295. }
  1296. void Graphics::rotate(float r)
  1297. {
  1298. gl.getTransform().rotate(r);
  1299. }
  1300. void Graphics::scale(float x, float y)
  1301. {
  1302. gl.getTransform().scale(x, y);
  1303. pixelSizeStack.back() *= 2. / (fabs(x) + fabs(y));
  1304. }
  1305. void Graphics::translate(float x, float y)
  1306. {
  1307. gl.getTransform().translate(x, y);
  1308. }
  1309. void Graphics::shear(float kx, float ky)
  1310. {
  1311. gl.getTransform().shear(kx, ky);
  1312. }
  1313. void Graphics::origin()
  1314. {
  1315. gl.getTransform().setIdentity();
  1316. pixelSizeStack.back() = 1;
  1317. }
  1318. } // opengl
  1319. } // graphics
  1320. } // love