Graphics.cpp 37 KB

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