Graphics.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. /**
  2. * Copyright (c) 2006-2014 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 "Polyline.h"
  27. // C++
  28. #include <vector>
  29. #include <sstream>
  30. #include <algorithm>
  31. #include <iterator>
  32. // C
  33. #include <cmath>
  34. namespace love
  35. {
  36. namespace graphics
  37. {
  38. namespace opengl
  39. {
  40. Graphics::Graphics()
  41. : currentFont(0)
  42. , lineStyle(LINE_SMOOTH)
  43. , lineWidth(1)
  44. , matrixLimit(0)
  45. , userMatrices(0)
  46. , colorMask()
  47. , width(0)
  48. , height(0)
  49. , created(false)
  50. , activeStencil(false)
  51. , savedState()
  52. {
  53. currentWindow = love::window::sdl::Window::createSingleton();
  54. int w, h;
  55. love::window::WindowSettings wsettings;
  56. currentWindow->getWindow(w, h, wsettings);
  57. if (currentWindow->isCreated())
  58. setMode(w, h, wsettings.sRGB);
  59. }
  60. Graphics::~Graphics()
  61. {
  62. if (currentFont != 0)
  63. currentFont->release();
  64. currentWindow->release();
  65. }
  66. const char *Graphics::getName() const
  67. {
  68. return "love.graphics.opengl";
  69. }
  70. DisplayState Graphics::saveState()
  71. {
  72. DisplayState s;
  73. s.color = getColor();
  74. s.backgroundColor = getBackgroundColor();
  75. s.blendMode = getBlendMode();
  76. //get line style
  77. s.lineStyle = lineStyle;
  78. //get the point size
  79. glGetFloatv(GL_POINT_SIZE, &s.pointSize);
  80. //get point style
  81. s.pointStyle = (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE) ? Graphics::POINT_SMOOTH : Graphics::POINT_ROUGH;
  82. //get scissor status
  83. s.scissor = (glIsEnabled(GL_SCISSOR_TEST) == GL_TRUE);
  84. //do we have scissor, if so, store the box
  85. if (s.scissor)
  86. s.scissorBox = gl.getScissor();
  87. for (int i = 0; i < 4; i++)
  88. s.colorMask[i] = colorMask[i];
  89. wireframe = isWireframe();
  90. return s;
  91. }
  92. void Graphics::restoreState(const DisplayState &s)
  93. {
  94. setColor(s.color);
  95. setBackgroundColor(s.backgroundColor);
  96. setBlendMode(s.blendMode);
  97. setLineWidth(lineWidth);
  98. setLineStyle(s.lineStyle);
  99. setPointSize(s.pointSize);
  100. setPointStyle(s.pointStyle);
  101. if (s.scissor)
  102. setScissor(s.scissorBox.x, s.scissorBox.y, s.scissorBox.w, s.scissorBox.h);
  103. else
  104. setScissor();
  105. setColorMask(s.colorMask[0], s.colorMask[1], s.colorMask[2], s.colorMask[3]);
  106. setWireframe(s.wireframe);
  107. }
  108. void Graphics::setViewportSize(int width, int height)
  109. {
  110. this->width = width;
  111. this->height = height;
  112. if (!isCreated())
  113. return;
  114. // We want to affect the main screen, not any Canvas that's currently active
  115. // (not that any *should* be active when this is called.)
  116. Canvas *c = Canvas::current;
  117. Canvas::bindDefaultCanvas();
  118. // Set the viewport to top-left corner.
  119. gl.setViewport(OpenGL::Viewport(0, 0, width, height));
  120. // If a canvas was bound before this function was called, it needs to be
  121. // made aware of the new system viewport size.
  122. Canvas::systemViewport = gl.getViewport();
  123. // Reset the projection matrix
  124. glMatrixMode(GL_PROJECTION);
  125. glLoadIdentity();
  126. // Set up orthographic view (no depth)
  127. glOrtho(0.0, width, height, 0.0, -1.0, 1.0);
  128. glMatrixMode(GL_MODELVIEW);
  129. // Restore the previously active Canvas.
  130. if (c != nullptr)
  131. c->startGrab(c->getAttachedCanvases());
  132. }
  133. bool Graphics::setMode(int width, int height, bool &sRGB)
  134. {
  135. this->width = width;
  136. this->height = height;
  137. // Okay, setup OpenGL.
  138. gl.initContext();
  139. created = true;
  140. setViewportSize(width, height);
  141. // Make sure antialiasing works when set elsewhere
  142. if (GLEE_VERSION_1_3 || GLEE_ARB_multisample)
  143. glEnable(GL_MULTISAMPLE);
  144. // Enable blending
  145. glEnable(GL_BLEND);
  146. // Enable all color component writes.
  147. setColorMask(true, true, true, true);
  148. // Enable line/point smoothing.
  149. setLineStyle(LINE_SMOOTH);
  150. glEnable(GL_POINT_SMOOTH);
  151. glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
  152. // Auto-generated mipmaps should be the best quality possible
  153. if (GLEE_VERSION_1_4 || GLEE_SGIS_generate_mipmap)
  154. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  155. // Enable textures
  156. glEnable(GL_TEXTURE_2D);
  157. gl.setTextureUnit(0);
  158. // Reset modelview matrix
  159. glMatrixMode(GL_MODELVIEW);
  160. glLoadIdentity();
  161. // Set pixel row alignment
  162. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  163. // Reload all volatile objects.
  164. if (!Volatile::loadAll())
  165. std::cerr << "Could not reload all volatile objects." << std::endl;
  166. // Restore the display state.
  167. restoreState(savedState);
  168. pixel_size_stack.clear();
  169. pixel_size_stack.reserve(5);
  170. pixel_size_stack.push_back(1);
  171. // Get the maximum number of matrices
  172. // subtract a few to give the engine some room.
  173. glGetIntegerv(GL_MAX_MODELVIEW_STACK_DEPTH, &matrixLimit);
  174. matrixLimit -= 5;
  175. // Set whether drawing converts input from linear -> sRGB colorspace.
  176. if (GLEE_VERSION_3_0 || GLEE_ARB_framebuffer_sRGB || GLEE_EXT_framebuffer_sRGB)
  177. {
  178. if (sRGB)
  179. glEnable(GL_FRAMEBUFFER_SRGB);
  180. else
  181. glDisable(GL_FRAMEBUFFER_SRGB);
  182. }
  183. else
  184. sRGB = false;
  185. Canvas::screenHasSRGB = sRGB;
  186. bool enabledebug = false;
  187. if (GLEE_VERSION_3_0)
  188. {
  189. // Enable OpenGL's debug output if a debug context has been created.
  190. GLint flags = 0;
  191. glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
  192. enabledebug = (flags & GL_CONTEXT_FLAG_DEBUG_BIT) != 0;
  193. }
  194. setDebug(enabledebug);
  195. return true;
  196. }
  197. void Graphics::unSetMode()
  198. {
  199. if (!isCreated())
  200. return;
  201. // Window re-creation may destroy the GL context, so we must save the state.
  202. savedState = saveState();
  203. // Unload all volatile objects. These must be reloaded after the display
  204. // mode change.
  205. Volatile::unloadAll();
  206. gl.deInitContext();
  207. created = false;
  208. }
  209. static void APIENTRY debugCB(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei /*len*/, const GLchar *msg, GLvoid* /*usr*/)
  210. {
  211. // Human-readable strings for the debug info.
  212. const char *sourceStr = OpenGL::debugSourceString(source);
  213. const char *typeStr = OpenGL::debugTypeString(type);
  214. const char *severityStr = OpenGL::debugSeverityString(severity);
  215. const char *fmt = "OpenGL: %s [source=%s, type=%s, severity=%s, id=%d]\n";
  216. printf(fmt, msg, sourceStr, typeStr, severityStr, id);
  217. }
  218. void Graphics::setDebug(bool enable)
  219. {
  220. // Make sure debug output is supported. The AMD ext. is a bit different
  221. // so we don't make use of it, since AMD drivers now support KHR_debug.
  222. if (!(GLEE_VERSION_4_3 || GLEE_KHR_debug || GLEE_ARB_debug_output))
  223. return;
  224. // Ugly hack to reduce code duplication.
  225. if (GLEE_ARB_debug_output && !(GLEE_VERSION_4_3 || GLEE_KHR_debug))
  226. {
  227. glDebugMessageCallback = (GLEEPFNGLDEBUGMESSAGECALLBACKPROC) glDebugMessageCallbackARB;
  228. glDebugMessageControl = (GLEEPFNGLDEBUGMESSAGECONTROLPROC) glDebugMessageControlARB;
  229. }
  230. if (!enable)
  231. {
  232. // Disable the debug callback function.
  233. glDebugMessageCallback(nullptr, nullptr);
  234. // We can disable debug output entirely with KHR_debug.
  235. if (GLEE_VERSION_4_3 || GLEE_KHR_debug)
  236. glDisable(GL_DEBUG_OUTPUT);
  237. return;
  238. }
  239. // We don't want asynchronous debug output.
  240. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  241. glDebugMessageCallback(debugCB, nullptr);
  242. // Initially, enable everything.
  243. glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
  244. // Disable messages about deprecated OpenGL functionality.
  245. glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  246. glDebugMessageControl(GL_DEBUG_SOURCE_SHADER_COMPILER, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  247. if (GLEE_VERSION_4_3 || GLEE_KHR_debug)
  248. glEnable(GL_DEBUG_OUTPUT);
  249. ::printf("OpenGL debug output enabled (LOVE_GRAPHICS_DEBUG=1)\n");
  250. }
  251. void Graphics::reset()
  252. {
  253. DisplayState s;
  254. discardStencil();
  255. Canvas::bindDefaultCanvas();
  256. Shader::detach();
  257. origin();
  258. restoreState(s);
  259. }
  260. void Graphics::clear()
  261. {
  262. glClear(GL_COLOR_BUFFER_BIT);
  263. }
  264. void Graphics::present()
  265. {
  266. currentWindow->swapBuffers();
  267. }
  268. int Graphics::getWidth() const
  269. {
  270. return width;
  271. }
  272. int Graphics::getHeight() const
  273. {
  274. return height;
  275. }
  276. bool Graphics::isCreated() const
  277. {
  278. return created;
  279. }
  280. void Graphics::setScissor(int x, int y, int width, int height)
  281. {
  282. glEnable(GL_SCISSOR_TEST);
  283. // OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
  284. gl.setScissor(OpenGL::Viewport(x, y, width, height));
  285. }
  286. void Graphics::setScissor()
  287. {
  288. glDisable(GL_SCISSOR_TEST);
  289. }
  290. bool Graphics::getScissor(int &x, int &y, int &width, int &height) const
  291. {
  292. OpenGL::Viewport scissor = gl.getScissor();
  293. x = scissor.x;
  294. y = scissor.y;
  295. width = scissor.w;
  296. height = scissor.h;
  297. return glIsEnabled(GL_SCISSOR_TEST) == GL_TRUE;
  298. }
  299. void Graphics::defineStencil()
  300. {
  301. // Make sure the active canvas has a stencil buffer.
  302. if (Canvas::current)
  303. Canvas::current->checkCreateStencil();
  304. // Disable color writes but don't save the mask values.
  305. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  306. glClear(GL_STENCIL_BUFFER_BIT);
  307. glEnable(GL_STENCIL_TEST);
  308. glStencilFunc(GL_ALWAYS, 1, 1);
  309. glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  310. activeStencil = true;
  311. }
  312. void Graphics::useStencil(bool invert)
  313. {
  314. glStencilFunc(GL_EQUAL, (GLint)(!invert), 1); // invert ? 0 : 1
  315. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  316. setColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
  317. }
  318. void Graphics::discardStencil()
  319. {
  320. if (!activeStencil)
  321. return;
  322. setColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
  323. glDisable(GL_STENCIL_TEST);
  324. activeStencil = false;
  325. }
  326. Image *Graphics::newImage(love::image::ImageData *data, Texture::Format format)
  327. {
  328. // Create the image.
  329. Image *image = new Image(data, format);
  330. if (!isCreated())
  331. return image;
  332. bool success = false;
  333. try
  334. {
  335. success = image->load();
  336. }
  337. catch(love::Exception &)
  338. {
  339. image->release();
  340. throw;
  341. }
  342. if (!success)
  343. {
  344. image->release();
  345. return 0;
  346. }
  347. return image;
  348. }
  349. Image *Graphics::newImage(love::image::CompressedData *cdata, Texture::Format format)
  350. {
  351. // Create the image.
  352. Image *image = new Image(cdata, format);
  353. if (!isCreated())
  354. return image;
  355. bool success = false;
  356. try
  357. {
  358. success = image->load();
  359. }
  360. catch(love::Exception &)
  361. {
  362. image->release();
  363. throw;
  364. }
  365. if (!success)
  366. {
  367. image->release();
  368. return 0;
  369. }
  370. return image;
  371. }
  372. Quad *Graphics::newQuad(Quad::Viewport v, float sw, float sh)
  373. {
  374. return new Quad(v, sw, sh);
  375. }
  376. Font *Graphics::newFont(love::font::Rasterizer *r, const Texture::Filter &filter)
  377. {
  378. return new Font(r, filter);
  379. }
  380. SpriteBatch *Graphics::newSpriteBatch(Texture *texture, int size, int usage)
  381. {
  382. return new SpriteBatch(texture, size, usage);
  383. }
  384. ParticleSystem *Graphics::newParticleSystem(Texture *texture, int size)
  385. {
  386. return new ParticleSystem(texture, size);
  387. }
  388. Canvas *Graphics::newCanvas(int width, int height, Texture::Format format, int fsaa)
  389. {
  390. if (format == Texture::FORMAT_HDR && !Canvas::isHDRSupported())
  391. throw Exception("HDR Canvases are not supported by your OpenGL implementation");
  392. if (format == Texture::FORMAT_SRGB && !Canvas::isSRGBSupported())
  393. throw Exception("sRGB Canvases are not supported by your OpenGL implementation");
  394. if (width > gl.getMaxTextureSize())
  395. throw Exception("Cannot create canvas: width of %d pixels is too large for this system.", width);
  396. else if (height > gl.getMaxTextureSize())
  397. throw Exception("Cannot create canvas: height of %d pixels is too large for this system.", height);
  398. while (GL_NO_ERROR != glGetError())
  399. /* clear opengl error flag */;
  400. Canvas *canvas = new Canvas(width, height, format, fsaa);
  401. GLenum err = canvas->getStatus();
  402. // everything ok, return canvas (early out)
  403. if (err == GL_FRAMEBUFFER_COMPLETE)
  404. return canvas;
  405. // create error message
  406. std::stringstream error_string;
  407. error_string << "Cannot create canvas: ";
  408. switch (err)
  409. {
  410. case GL_FRAMEBUFFER_UNSUPPORTED:
  411. error_string << "Not supported by your OpenGL implementation.";
  412. break;
  413. // remaining error codes are highly unlikely:
  414. case GL_FRAMEBUFFER_UNDEFINED:
  415. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  416. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  417. case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
  418. case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
  419. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  420. error_string << "Error in implementation. Possible fix: Make canvas width and height powers of two.";
  421. break;
  422. default:
  423. // my intel hda card wrongly returns 0 to glCheckFramebufferStatus() but sets
  424. // no error flag. I think it meant to return GL_FRAMEBUFFER_UNSUPPORTED, but who
  425. // knows.
  426. if (glGetError() == GL_NO_ERROR)
  427. error_string << "May not be supported by your OpenGL implementation.";
  428. // the remaining error is an indication of a serious fuckup since it should
  429. // only be returned if glCheckFramebufferStatus() was called with the wrong
  430. // arguments.
  431. else
  432. error_string << "Cannot create canvas: Aliens did it (OpenGL error code: " << glGetError() << ")";
  433. }
  434. canvas->release();
  435. throw Exception(error_string.str().c_str());
  436. return NULL; // never reached
  437. }
  438. Shader *Graphics::newShader(const Shader::ShaderSources &sources)
  439. {
  440. return new Shader(sources);
  441. }
  442. Mesh *Graphics::newMesh(const std::vector<Vertex> &vertices, Mesh::DrawMode mode)
  443. {
  444. return new Mesh(vertices, mode);
  445. }
  446. Mesh *Graphics::newMesh(int vertexcount, Mesh::DrawMode mode)
  447. {
  448. return new Mesh(vertexcount, mode);
  449. }
  450. void Graphics::setColor(const Color &c)
  451. {
  452. gl.setColor(c);
  453. }
  454. Color Graphics::getColor() const
  455. {
  456. return gl.getColor();
  457. }
  458. void Graphics::setBackgroundColor(const Color &c)
  459. {
  460. gl.setClearColor(c);
  461. }
  462. Color Graphics::getBackgroundColor() const
  463. {
  464. return gl.getClearColor();
  465. }
  466. void Graphics::setFont(Font *font)
  467. {
  468. Object::AutoRelease fontrelease(currentFont);
  469. currentFont = font;
  470. if (font != 0)
  471. currentFont->retain();
  472. }
  473. Font *Graphics::getFont() const
  474. {
  475. return currentFont;
  476. }
  477. void Graphics::setColorMask(bool r, bool g, bool b, bool a)
  478. {
  479. colorMask[0] = r;
  480. colorMask[1] = g;
  481. colorMask[2] = b;
  482. colorMask[3] = a;
  483. glColorMask((GLboolean) r, (GLboolean) g, (GLboolean) b, (GLboolean) a);
  484. }
  485. const bool *Graphics::getColorMask() const
  486. {
  487. return colorMask;
  488. }
  489. void Graphics::setBlendMode(Graphics::BlendMode mode)
  490. {
  491. OpenGL::BlendState state = {GL_ONE, GL_ONE, GL_ZERO, GL_ZERO, GL_FUNC_ADD};
  492. switch (mode)
  493. {
  494. case BLEND_ALPHA:
  495. if (GLEE_VERSION_1_4 || GLEE_EXT_blend_func_separate)
  496. {
  497. state.srcRGB = GL_SRC_ALPHA;
  498. state.srcA = GL_ONE;
  499. state.dstRGB = state.dstA = GL_ONE_MINUS_SRC_ALPHA;
  500. }
  501. else
  502. {
  503. // Fallback for OpenGL implementations without support for separate blend functions.
  504. // This will most likely only be used for the Microsoft software renderer and
  505. // since it's still stuck with OpenGL 1.1, the only expected difference is a
  506. // different alpha value when reading back the default framebuffer (newScreenshot).
  507. state.srcRGB = state.srcA = GL_SRC_ALPHA;
  508. state.dstRGB = state.dstA = GL_ONE_MINUS_SRC_ALPHA;
  509. }
  510. break;
  511. case BLEND_MULTIPLICATIVE:
  512. state.srcRGB = state.srcA = GL_DST_COLOR;
  513. state.dstRGB = state.dstA = GL_ZERO;
  514. break;
  515. case BLEND_PREMULTIPLIED:
  516. state.srcRGB = state.srcA = GL_ONE;
  517. state.dstRGB = state.dstA = GL_ONE_MINUS_SRC_ALPHA;
  518. break;
  519. case BLEND_SUBTRACTIVE:
  520. state.func = GL_FUNC_REVERSE_SUBTRACT;
  521. case BLEND_ADDITIVE:
  522. state.srcRGB = state.srcA = GL_SRC_ALPHA;
  523. state.dstRGB = state.dstA = GL_ONE;
  524. break;
  525. case BLEND_SCREEN:
  526. state.srcRGB = state.srcA = GL_ONE;
  527. state.dstRGB = state.dstA = GL_ONE_MINUS_SRC_COLOR;
  528. break;
  529. case BLEND_REPLACE:
  530. default:
  531. state.srcRGB = state.srcA = GL_ONE;
  532. state.dstRGB = state.dstA = GL_ZERO;
  533. break;
  534. }
  535. gl.setBlendState(state);
  536. }
  537. Graphics::BlendMode Graphics::getBlendMode() const
  538. {
  539. OpenGL::BlendState state = gl.getBlendState();
  540. if (state.func == GL_FUNC_REVERSE_SUBTRACT) // && src == GL_SRC_ALPHA && dst == GL_ONE
  541. return BLEND_SUBTRACTIVE;
  542. // Everything else has equation == GL_FUNC_ADD.
  543. else if (state.srcRGB == state.srcA && state.dstRGB == state.dstA)
  544. {
  545. if (state.srcRGB == GL_SRC_ALPHA && state.dstRGB == GL_ONE)
  546. return BLEND_ADDITIVE;
  547. else if (state.srcRGB == GL_SRC_ALPHA && state.dstRGB == GL_ONE_MINUS_SRC_ALPHA)
  548. return BLEND_ALPHA; // alpha blend mode fallback for very old OpenGL versions.
  549. else if (state.srcRGB == GL_DST_COLOR && state.dstRGB == GL_ZERO)
  550. return BLEND_MULTIPLICATIVE;
  551. else if (state.srcRGB == GL_ONE && state.dstRGB == GL_ONE_MINUS_SRC_ALPHA)
  552. return BLEND_PREMULTIPLIED;
  553. else if (state.srcRGB == GL_ONE && state.dstRGB == GL_ONE_MINUS_SRC_COLOR)
  554. return BLEND_SCREEN;
  555. else if (state.srcRGB == GL_ONE && state.dstRGB == GL_ZERO)
  556. return BLEND_REPLACE;
  557. }
  558. else if (state.srcRGB == GL_SRC_ALPHA && state.srcA == GL_ONE &&
  559. state.dstRGB == GL_ONE_MINUS_SRC_ALPHA && state.dstA == GL_ONE_MINUS_SRC_ALPHA)
  560. return BLEND_ALPHA;
  561. throw Exception("Unknown blend mode");
  562. }
  563. void Graphics::setDefaultFilter(const Texture::Filter &f)
  564. {
  565. Texture::setDefaultFilter(f);
  566. }
  567. const Texture::Filter &Graphics::getDefaultFilter() const
  568. {
  569. return Texture::getDefaultFilter();
  570. }
  571. void Graphics::setDefaultMipmapFilter(Texture::FilterMode filter, float sharpness)
  572. {
  573. Image::setDefaultMipmapFilter(filter);
  574. Image::setDefaultMipmapSharpness(sharpness);
  575. }
  576. void Graphics::getDefaultMipmapFilter(Texture::FilterMode *filter, float *sharpness) const
  577. {
  578. *filter = Image::getDefaultMipmapFilter();
  579. *sharpness = Image::getDefaultMipmapSharpness();
  580. }
  581. void Graphics::setLineWidth(float width)
  582. {
  583. lineWidth = width;
  584. }
  585. void Graphics::setLineStyle(Graphics::LineStyle style)
  586. {
  587. lineStyle = style;
  588. }
  589. void Graphics::setLineJoin(Graphics::LineJoin join)
  590. {
  591. lineJoin = join;
  592. }
  593. float Graphics::getLineWidth() const
  594. {
  595. return lineWidth;
  596. }
  597. Graphics::LineStyle Graphics::getLineStyle() const
  598. {
  599. return lineStyle;
  600. }
  601. Graphics::LineJoin Graphics::getLineJoin() const
  602. {
  603. return lineJoin;
  604. }
  605. void Graphics::setPointSize(float size)
  606. {
  607. glPointSize((GLfloat)size);
  608. }
  609. void Graphics::setPointStyle(Graphics::PointStyle style)
  610. {
  611. if (style == POINT_SMOOTH)
  612. glEnable(GL_POINT_SMOOTH);
  613. else // love::POINT_ROUGH
  614. glDisable(GL_POINT_SMOOTH);
  615. }
  616. float Graphics::getPointSize() const
  617. {
  618. GLfloat size;
  619. glGetFloatv(GL_POINT_SIZE, &size);
  620. return (float)size;
  621. }
  622. Graphics::PointStyle Graphics::getPointStyle() const
  623. {
  624. if (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE)
  625. return POINT_SMOOTH;
  626. else
  627. return POINT_ROUGH;
  628. }
  629. void Graphics::setWireframe(bool enable)
  630. {
  631. wireframe = enable;
  632. glPolygonMode(GL_FRONT_AND_BACK, enable ? GL_LINE : GL_FILL);
  633. }
  634. bool Graphics::isWireframe() const
  635. {
  636. return wireframe;
  637. }
  638. 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)
  639. {
  640. if (currentFont != nullptr)
  641. currentFont->print(str, x, y, 0.0, angle, sx, sy, ox, oy, kx, ky);
  642. }
  643. void Graphics::printf(const std::string &str, float x, float y, float wrap, AlignMode align, float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  644. {
  645. if (currentFont == nullptr)
  646. return;
  647. if (wrap < 0.0f)
  648. throw love::Exception("Horizontal wrap limit cannot be negative.");
  649. using std::string;
  650. using std::vector;
  651. // wrappedlines indicates which lines were automatically wrapped. It's
  652. // guaranteed to have the same number of elements as lines_to_draw.
  653. vector<bool> wrappedlines;
  654. vector<string> lines_to_draw = currentFont->getWrap(str, wrap, 0, &wrappedlines);
  655. glPushMatrix();
  656. static Matrix t;
  657. t.setTransformation(ceilf(x), ceilf(y), angle, sx, sy, ox, oy, kx, ky);
  658. glMultMatrixf((const GLfloat *)t.getElements());
  659. x = y = 0.0f;
  660. try
  661. {
  662. // now for the actual printing
  663. vector<string>::const_iterator line_iter, line_end = lines_to_draw.end();
  664. float extra_spacing = 0.0f;
  665. int num_spaces = 0;
  666. int i = 0;
  667. for (line_iter = lines_to_draw.begin(); line_iter != line_end; ++line_iter)
  668. {
  669. float width = static_cast<float>(currentFont->getWidth(*line_iter));
  670. switch (align)
  671. {
  672. case ALIGN_RIGHT:
  673. currentFont->print(*line_iter, ceilf(x + (wrap - width)), ceilf(y), 0.0f);
  674. break;
  675. case ALIGN_CENTER:
  676. currentFont->print(*line_iter, ceilf(x + (wrap - width) / 2), ceilf(y), 0.0f);
  677. break;
  678. case ALIGN_JUSTIFY:
  679. num_spaces = std::count(line_iter->begin(), line_iter->end(), ' ');
  680. if (wrappedlines[i] && num_spaces >= 1)
  681. extra_spacing = (wrap - width) / float(num_spaces);
  682. else
  683. extra_spacing = 0.0f;
  684. currentFont->print(*line_iter, ceilf(x), ceilf(y), extra_spacing);
  685. break;
  686. case ALIGN_LEFT:
  687. default:
  688. currentFont->print(*line_iter, ceilf(x), ceilf(y), 0.0f);
  689. break;
  690. }
  691. y += currentFont->getHeight() * currentFont->getLineHeight();
  692. i++;
  693. }
  694. }
  695. catch (love::Exception &)
  696. {
  697. glPopMatrix();
  698. throw;
  699. }
  700. glPopMatrix();
  701. }
  702. /**
  703. * Primitives
  704. **/
  705. void Graphics::point(float x, float y)
  706. {
  707. gl.prepareDraw();
  708. gl.bindTexture(0);
  709. glBegin(GL_POINTS);
  710. glVertex2f(x, y);
  711. glEnd();
  712. }
  713. void Graphics::polyline(const float *coords, size_t count)
  714. {
  715. if (lineJoin == LINE_JOIN_NONE)
  716. {
  717. NoneJoinPolyline line;
  718. line.render(coords, count, lineWidth * .5f, float(pixel_size_stack.back()), lineStyle == LINE_SMOOTH);
  719. line.draw();
  720. }
  721. else if (lineJoin == LINE_JOIN_BEVEL)
  722. {
  723. BevelJoinPolyline line;
  724. line.render(coords, count, lineWidth * .5f, float(pixel_size_stack.back()), lineStyle == LINE_SMOOTH);
  725. line.draw();
  726. }
  727. else // LINE_JOIN_MITER
  728. {
  729. MiterJoinPolyline line;
  730. line.render(coords, count, lineWidth * .5f, float(pixel_size_stack.back()), lineStyle == LINE_SMOOTH);
  731. line.draw();
  732. }
  733. }
  734. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  735. {
  736. float coords[] = {x,y, x,y+h, x+w,y+h, x+w,y, x,y};
  737. polygon(mode, coords, 5 * 2);
  738. }
  739. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  740. {
  741. float two_pi = static_cast<float>(LOVE_M_PI * 2);
  742. if (points <= 0) points = 1;
  743. float angle_shift = (two_pi / points);
  744. float phi = .0f;
  745. float *coords = new float[2 * (points + 1)];
  746. for (int i = 0; i < points; ++i, phi += angle_shift)
  747. {
  748. coords[2*i] = x + radius * cosf(phi);
  749. coords[2*i+1] = y + radius * sinf(phi);
  750. }
  751. coords[2*points] = coords[0];
  752. coords[2*points+1] = coords[1];
  753. polygon(mode, coords, (points + 1) * 2);
  754. delete[] coords;
  755. }
  756. void Graphics::arc(DrawMode mode, float x, float y, float radius, float angle1, float angle2, int points)
  757. {
  758. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  759. if (points <= 0 || angle1 == angle2)
  760. return;
  761. // Oh, you want to draw a circle?
  762. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  763. {
  764. circle(mode, x, y, radius, points);
  765. return;
  766. }
  767. float angle_shift = (angle2 - angle1) / points;
  768. // Bail on precision issues.
  769. if (angle_shift == 0.0)
  770. return;
  771. float phi = angle1;
  772. int num_coords = (points + 3) * 2;
  773. float *coords = new float[num_coords];
  774. coords[0] = coords[num_coords - 2] = x;
  775. coords[1] = coords[num_coords - 1] = y;
  776. for (int i = 0; i <= points; ++i, phi += angle_shift)
  777. {
  778. coords[2 * (i+1)] = x + radius * cosf(phi);
  779. coords[2 * (i+1) + 1] = y + radius * sinf(phi);
  780. }
  781. // GL_POLYGON can only fill-draw convex polygons, so we need to do stuff manually here
  782. if (mode == DRAW_LINE)
  783. {
  784. polyline(coords, num_coords); // Artifacts at sharp angles if set to looping.
  785. }
  786. else
  787. {
  788. gl.prepareDraw();
  789. gl.bindTexture(0);
  790. glEnableClientState(GL_VERTEX_ARRAY);
  791. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *) coords);
  792. glDrawArrays(GL_TRIANGLE_FAN, 0, points + 2);
  793. glDisableClientState(GL_VERTEX_ARRAY);
  794. }
  795. delete[] coords;
  796. }
  797. /// @param mode the draw mode
  798. /// @param coords the coordinate array
  799. /// @param count the number of coordinates/size of the array
  800. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  801. {
  802. // coords is an array of a closed loop of vertices, i.e.
  803. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  804. if (mode == DRAW_LINE)
  805. {
  806. polyline(coords, count);
  807. }
  808. else
  809. {
  810. gl.prepareDraw();
  811. gl.bindTexture(0);
  812. glEnableClientState(GL_VERTEX_ARRAY);
  813. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)coords);
  814. glDrawArrays(GL_POLYGON, 0, count/2-1); // opengl will close the polygon for us
  815. glDisableClientState(GL_VERTEX_ARRAY);
  816. }
  817. }
  818. love::image::ImageData *Graphics::newScreenshot(love::image::Image *image, bool copyAlpha)
  819. {
  820. // Temporarily unbind the currently active canvas (glReadPixels reads the
  821. // active framebuffer, not the main one.)
  822. Canvas *curcanvas = Canvas::current;
  823. if (curcanvas)
  824. Canvas::bindDefaultCanvas();
  825. int w = getWidth();
  826. int h = getHeight();
  827. int row = 4*w;
  828. int size = row*h;
  829. GLubyte *pixels = 0;
  830. GLubyte *screenshot = 0;
  831. try
  832. {
  833. pixels = new GLubyte[size];
  834. screenshot = new GLubyte[size];
  835. }
  836. catch (std::exception &)
  837. {
  838. delete[] pixels;
  839. delete[] screenshot;
  840. if (curcanvas)
  841. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  842. throw love::Exception("Out of memory.");
  843. }
  844. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  845. if (!copyAlpha)
  846. {
  847. // Replace alpha values with full opacity.
  848. for (int i = 3; i < size; i += 4)
  849. pixels[i] = 255;
  850. }
  851. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  852. GLubyte *src = pixels - row, *dst = screenshot + size;
  853. for (int i = 0; i < h; ++i)
  854. memcpy(dst-=row, src+=row, row);
  855. delete[] pixels;
  856. love::image::ImageData *img = 0;
  857. try
  858. {
  859. // Tell the new ImageData that it owns the screenshot data, so we don't
  860. // need to delete it here.
  861. img = image->newImageData(w, h, (void *) screenshot, true);
  862. }
  863. catch (love::Exception &)
  864. {
  865. delete[] screenshot;
  866. if (curcanvas)
  867. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  868. throw;
  869. }
  870. // Re-bind the active canvas, if necessary.
  871. if (curcanvas)
  872. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  873. return img;
  874. }
  875. std::string Graphics::getRendererInfo(Graphics::RendererInfo infotype) const
  876. {
  877. const char *infostr = 0;
  878. switch (infotype)
  879. {
  880. case Graphics::RENDERER_INFO_NAME:
  881. default:
  882. infostr = "OpenGL";
  883. break;
  884. case Graphics::RENDERER_INFO_VERSION:
  885. infostr = (const char *) glGetString(GL_VERSION);
  886. break;
  887. case Graphics::RENDERER_INFO_VENDOR:
  888. infostr = (const char *) glGetString(GL_VENDOR);
  889. break;
  890. case Graphics::RENDERER_INFO_DEVICE:
  891. infostr = (const char *) glGetString(GL_RENDERER);
  892. break;
  893. }
  894. if (!infostr)
  895. throw love::Exception("Cannot retrieve renderer information.");
  896. return std::string(infostr);
  897. }
  898. double Graphics::getSystemLimit(SystemLimit limittype) const
  899. {
  900. double limit = 0.0;
  901. switch (limittype)
  902. {
  903. case Graphics::LIMIT_POINT_SIZE:
  904. {
  905. GLfloat limits[2];
  906. glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, limits);
  907. limit = limits[1];
  908. }
  909. break;
  910. case Graphics::LIMIT_TEXTURE_SIZE:
  911. limit = (double) gl.getMaxTextureSize();
  912. break;
  913. case Graphics::LIMIT_MULTI_CANVAS:
  914. limit = (double) gl.getMaxRenderTargets();
  915. break;
  916. case Graphics::LIMIT_CANVAS_FSAA:
  917. if (GLEE_VERSION_3_0 || GLEE_ARB_framebuffer_object
  918. || GLEE_EXT_framebuffer_multisample)
  919. {
  920. GLint intlimit = 0;
  921. glGetIntegerv(GL_MAX_SAMPLES, &intlimit);
  922. limit = (double) intlimit;
  923. }
  924. break;
  925. default:
  926. break;
  927. }
  928. return limit;
  929. }
  930. void Graphics::push()
  931. {
  932. if (userMatrices == matrixLimit)
  933. throw Exception("Maximum stack depth reached. (More pushes than pops?)");
  934. glPushMatrix();
  935. ++userMatrices;
  936. pixel_size_stack.push_back(pixel_size_stack.back());
  937. }
  938. void Graphics::pop()
  939. {
  940. if (userMatrices < 1)
  941. throw Exception("Minimum stack depth reached. (More pops than pushes?)");
  942. glPopMatrix();
  943. --userMatrices;
  944. pixel_size_stack.pop_back();
  945. }
  946. void Graphics::rotate(float r)
  947. {
  948. glRotatef(LOVE_TODEG(r), 0, 0, 1);
  949. }
  950. void Graphics::scale(float x, float y)
  951. {
  952. glScalef(x, y, 1);
  953. pixel_size_stack.back() *= 2. / (fabs(x) + fabs(y));
  954. }
  955. void Graphics::translate(float x, float y)
  956. {
  957. glTranslatef(x, y, 0);
  958. }
  959. void Graphics::shear(float kx, float ky)
  960. {
  961. Matrix t;
  962. t.setShear(kx, ky);
  963. glMultMatrixf((const GLfloat *)t.getElements());
  964. }
  965. void Graphics::origin()
  966. {
  967. glLoadIdentity();
  968. pixel_size_stack.back() = 1;
  969. }
  970. } // opengl
  971. } // graphics
  972. } // love