Graphics.cpp 36 KB

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