Graphics.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. /**
  2. * Copyright (c) 2006-2013 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. #include "common/config.h"
  21. #include "common/math.h"
  22. #include "common/Vector.h"
  23. #include "Graphics.h"
  24. #include "window/sdl/Window.h"
  25. #include <vector>
  26. #include <sstream>
  27. #include <algorithm>
  28. #include <iterator>
  29. using love::window::WindowFlags;
  30. namespace love
  31. {
  32. namespace graphics
  33. {
  34. namespace opengl
  35. {
  36. Graphics::Graphics()
  37. : currentFont(0)
  38. , lineStyle(LINE_SMOOTH)
  39. , lineWidth(1)
  40. , matrixLimit(0)
  41. , userMatrices(0)
  42. , colorMask()
  43. , width(0)
  44. , height(0)
  45. , created(false)
  46. , savedState()
  47. {
  48. currentWindow = love::window::sdl::Window::getSingleton();
  49. if (currentWindow->isCreated())
  50. setMode(currentWindow->getWidth(), currentWindow->getHeight());
  51. }
  52. Graphics::~Graphics()
  53. {
  54. if (currentFont != 0)
  55. currentFont->release();
  56. currentWindow->release();
  57. }
  58. const char *Graphics::getName() const
  59. {
  60. return "love.graphics.opengl";
  61. }
  62. DisplayState Graphics::saveState()
  63. {
  64. DisplayState s;
  65. s.color = getColor();
  66. s.backgroundColor = getBackgroundColor();
  67. s.blendMode = getBlendMode();
  68. //get line style
  69. s.lineStyle = lineStyle;
  70. //get the point size
  71. glGetFloatv(GL_POINT_SIZE, &s.pointSize);
  72. //get point style
  73. s.pointStyle = (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE) ? Graphics::POINT_SMOOTH : Graphics::POINT_ROUGH;
  74. // get alpha test status
  75. s.alphaTest = isAlphaTestEnabled();
  76. if (s.alphaTest)
  77. {
  78. // if alpha testing is enabled, store mode and reference alpha
  79. s.alphaTestMode = getAlphaTestMode();
  80. s.alphaTestRef = getAlphaTestRef();
  81. }
  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. return s;
  90. }
  91. void Graphics::restoreState(const DisplayState &s)
  92. {
  93. setColor(s.color);
  94. setBackgroundColor(s.backgroundColor);
  95. setBlendMode(s.blendMode);
  96. setLineWidth(lineWidth);
  97. setLineStyle(s.lineStyle);
  98. setPointSize(s.pointSize);
  99. setPointStyle(s.pointStyle);
  100. if (s.alphaTest)
  101. setAlphaTest(s.alphaTestMode, s.alphaTestRef);
  102. else
  103. setAlphaTest();
  104. if (s.scissor)
  105. setScissor(s.scissorBox.x, s.scissorBox.y, s.scissorBox.w, s.scissorBox.h);
  106. else
  107. setScissor();
  108. setColorMask(s.colorMask[0], s.colorMask[1], s.colorMask[2], s.colorMask[3]);
  109. }
  110. bool Graphics::setMode(int width, int height)
  111. {
  112. this->width = width;
  113. this->height = height;
  114. // Okay, setup OpenGL.
  115. gl.initContext();
  116. // Make sure antialiasing works when set elsewhere
  117. if (GLEE_VERSION_1_3 || GLEE_ARB_multisample)
  118. glEnable(GL_MULTISAMPLE);
  119. // Enable blending
  120. glEnable(GL_BLEND);
  121. // "Normal" blending
  122. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  123. // Enable all color component writes.
  124. setColorMask(true, true, true, true);
  125. // Enable line/point smoothing.
  126. setLineStyle(LINE_SMOOTH);
  127. glEnable(GL_POINT_SMOOTH);
  128. glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
  129. // Auto-generated mipmaps should be the best quality possible
  130. if (GLEE_VERSION_1_4 || GLEE_SGIS_generate_mipmap)
  131. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  132. // Set default alpha test mode and value
  133. glAlphaFunc(GL_GREATER, 0.0f);
  134. setAlphaTest();
  135. // Enable textures
  136. glEnable(GL_TEXTURE_2D);
  137. gl.setActiveTextureUnit(0);
  138. // Set the viewport to top-left corner
  139. gl.setViewport(OpenGL::Viewport(0, 0, width, height));
  140. // Reset the projection matrix
  141. glMatrixMode(GL_PROJECTION);
  142. glLoadIdentity();
  143. // Set up orthographic view (no depth)
  144. glOrtho(0.0, width, height, 0.0, -1.0, 1.0);
  145. // Reset modelview matrix
  146. glMatrixMode(GL_MODELVIEW);
  147. glLoadIdentity();
  148. // Set pixel row alignment
  149. glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
  150. // Reload all volatile objects.
  151. if (!Volatile::loadAll())
  152. std::cerr << "Could not reload all volatile objects." << std::endl;
  153. // Restore the display state.
  154. restoreState(savedState);
  155. pixel_size_stack.clear();
  156. pixel_size_stack.reserve(5);
  157. pixel_size_stack.push_back(1);
  158. // Get the maximum number of matrices
  159. // subtract a few to give the engine some room.
  160. glGetIntegerv(GL_MAX_MODELVIEW_STACK_DEPTH, &matrixLimit);
  161. matrixLimit -= 5;
  162. created = true;
  163. return true;
  164. }
  165. void Graphics::unSetMode()
  166. {
  167. // Window re-creation may destroy the GL context, so we must save the state.
  168. if (isCreated())
  169. savedState = saveState();
  170. // Unload all volatile objects. These must be reloaded after the display
  171. // mode change.
  172. Volatile::unloadAll();
  173. gl.deInitContext();
  174. }
  175. void Graphics::reset()
  176. {
  177. DisplayState s;
  178. discardStencil();
  179. Canvas::bindDefaultCanvas();
  180. Shader::detach();
  181. restoreState(s);
  182. pixel_size_stack.clear();
  183. pixel_size_stack.reserve(5);
  184. pixel_size_stack.push_back(1);
  185. }
  186. void Graphics::clear()
  187. {
  188. glClear(GL_COLOR_BUFFER_BIT);
  189. }
  190. void Graphics::present()
  191. {
  192. currentWindow->swapBuffers();
  193. }
  194. int Graphics::getWidth() const
  195. {
  196. return width;
  197. }
  198. int Graphics::getHeight() const
  199. {
  200. return height;
  201. }
  202. int Graphics::getRenderWidth() const
  203. {
  204. if (Canvas::current)
  205. return Canvas::current->getWidth();
  206. return getWidth();
  207. }
  208. int Graphics::getRenderHeight() const
  209. {
  210. if (Canvas::current)
  211. return Canvas::current->getHeight();
  212. return getHeight();
  213. }
  214. bool Graphics::isCreated() const
  215. {
  216. return created;
  217. }
  218. void Graphics::setScissor(int x, int y, int width, int height)
  219. {
  220. glEnable(GL_SCISSOR_TEST);
  221. // OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
  222. gl.setScissor(OpenGL::Viewport(x, y, width, height));
  223. }
  224. void Graphics::setScissor()
  225. {
  226. glDisable(GL_SCISSOR_TEST);
  227. }
  228. int Graphics::getScissor(lua_State *L) const
  229. {
  230. if (glIsEnabled(GL_SCISSOR_TEST) == GL_FALSE)
  231. return 0;
  232. OpenGL::Viewport scissor = gl.getScissor();
  233. lua_pushinteger(L, scissor.x);
  234. lua_pushinteger(L, scissor.y);
  235. lua_pushinteger(L, scissor.w);
  236. lua_pushinteger(L, scissor.h);
  237. return 4;
  238. }
  239. void Graphics::defineStencil()
  240. {
  241. // Make sure the active canvas has a stencil buffer.
  242. if (Canvas::current)
  243. Canvas::current->checkCreateStencil();
  244. // Disable color writes but don't save the mask values.
  245. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  246. glClear(GL_STENCIL_BUFFER_BIT);
  247. glEnable(GL_STENCIL_TEST);
  248. glStencilFunc(GL_ALWAYS, 1, 1);
  249. glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  250. }
  251. void Graphics::useStencil(bool invert)
  252. {
  253. glStencilFunc(GL_EQUAL, (GLint)(!invert), 1); // invert ? 0 : 1
  254. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  255. setColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
  256. }
  257. void Graphics::discardStencil()
  258. {
  259. setColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
  260. glDisable(GL_STENCIL_TEST);
  261. }
  262. void Graphics::setAlphaTest(Graphics::AlphaTestMode mode, unsigned char refalpha)
  263. {
  264. GLclampf ref = refalpha / 255.0f;
  265. glEnable(GL_ALPHA_TEST);
  266. switch (mode)
  267. {
  268. case ALPHATEST_LESS:
  269. glAlphaFunc(GL_LESS, ref);
  270. break;
  271. case ALPHATEST_LEQUAL:
  272. glAlphaFunc(GL_LEQUAL, ref);
  273. break;
  274. case ALPHATEST_EQUAL:
  275. glAlphaFunc(GL_EQUAL, ref);
  276. break;
  277. case ALPHATEST_NOTEQUAL:
  278. glAlphaFunc(GL_NOTEQUAL, ref);
  279. break;
  280. case ALPHATEST_GEQUAL:
  281. glAlphaFunc(GL_GEQUAL, ref);
  282. break;
  283. case ALPHATEST_GREATER:
  284. glAlphaFunc(GL_GREATER, ref);
  285. break;
  286. default:
  287. glDisable(GL_ALPHA_TEST);
  288. break;
  289. }
  290. }
  291. void Graphics::setAlphaTest()
  292. {
  293. glDisable(GL_ALPHA_TEST);
  294. }
  295. bool Graphics::isAlphaTestEnabled()
  296. {
  297. return glIsEnabled(GL_ALPHA_TEST) == GL_TRUE;
  298. }
  299. Graphics::AlphaTestMode Graphics::getAlphaTestMode()
  300. {
  301. GLint func;
  302. glGetIntegerv(GL_ALPHA_TEST_FUNC, &func);
  303. switch (func)
  304. {
  305. case GL_LESS:
  306. return ALPHATEST_LESS;
  307. case GL_LEQUAL:
  308. return ALPHATEST_LEQUAL;
  309. case GL_EQUAL:
  310. return ALPHATEST_EQUAL;
  311. case GL_NOTEQUAL:
  312. return ALPHATEST_NOTEQUAL;
  313. case GL_GEQUAL:
  314. return ALPHATEST_GEQUAL;
  315. case GL_GREATER:
  316. return ALPHATEST_GREATER;
  317. default:
  318. return ALPHATEST_MAX_ENUM;
  319. }
  320. }
  321. unsigned char Graphics::getAlphaTestRef()
  322. {
  323. GLfloat ref;
  324. glGetFloatv(GL_ALPHA_TEST_REF, &ref);
  325. return ref * 255;
  326. }
  327. int Graphics::getMaxImageSize() const
  328. {
  329. return gl.getMaxTextureSize();
  330. }
  331. Image *Graphics::newImage(love::image::ImageData *data)
  332. {
  333. // Create the image.
  334. Image *image = new Image(data);
  335. bool success;
  336. try
  337. {
  338. success = image->load();
  339. }
  340. catch(love::Exception &)
  341. {
  342. image->release();
  343. throw;
  344. }
  345. if (!success)
  346. {
  347. image->release();
  348. return 0;
  349. }
  350. return image;
  351. }
  352. Image *Graphics::newImage(love::image::CompressedData *cdata)
  353. {
  354. // Create the image.
  355. Image *image = new Image(cdata);
  356. bool success;
  357. try
  358. {
  359. success = image->load();
  360. }
  361. catch(love::Exception &)
  362. {
  363. image->release();
  364. throw;
  365. }
  366. if (!success)
  367. {
  368. image->release();
  369. return 0;
  370. }
  371. return image;
  372. }
  373. Geometry *Graphics::newGeometry(const std::vector<vertex> &vertices, const std::vector<uint16> &vertexmap, Geometry::DrawMode mode)
  374. {
  375. return new Geometry(vertices, vertexmap, mode);
  376. }
  377. Geometry *Graphics::newQuad(float x, float y, float w, float h, float sw, float sh)
  378. {
  379. return new Geometry(x, y, w, h, sw, sh);
  380. }
  381. Font *Graphics::newFont(love::font::Rasterizer *r, const Image::Filter &filter)
  382. {
  383. return new Font(r, filter);
  384. }
  385. SpriteBatch *Graphics::newSpriteBatch(Image *image, int size, int usage)
  386. {
  387. return new SpriteBatch(image, size, usage);
  388. }
  389. ParticleSystem *Graphics::newParticleSystem(Image *image, int size)
  390. {
  391. return new ParticleSystem(image, size);
  392. }
  393. Canvas *Graphics::newCanvas(int width, int height, Canvas::TextureType texture_type)
  394. {
  395. if (texture_type == Canvas::TYPE_HDR && !Canvas::isHDRSupported())
  396. throw Exception("HDR Canvases are not supported by your OpenGL implementation");
  397. if (width > gl.getMaxTextureSize())
  398. throw Exception("Cannot create canvas: width of %d pixels is too large for this system.", width);
  399. else if (height > gl.getMaxTextureSize())
  400. throw Exception("Cannot create canvas: height of %d pixels is too large for this system.", height);
  401. while (GL_NO_ERROR != glGetError())
  402. /* clear opengl error flag */;
  403. Canvas *canvas = new Canvas(width, height, texture_type);
  404. GLenum err = canvas->getStatus();
  405. // everything ok, return canvas (early out)
  406. if (err == GL_FRAMEBUFFER_COMPLETE)
  407. return canvas;
  408. // create error message
  409. std::stringstream error_string;
  410. error_string << "Cannot create canvas: ";
  411. switch (err)
  412. {
  413. case GL_FRAMEBUFFER_UNSUPPORTED:
  414. error_string << "Not supported by your OpenGL implementation.";
  415. break;
  416. // remaining error codes are highly unlikely:
  417. case GL_FRAMEBUFFER_UNDEFINED:
  418. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  419. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  420. case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
  421. case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
  422. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  423. error_string << "Error in implementation. Possible fix: Make canvas width and height powers of two.";
  424. break;
  425. default:
  426. // my intel hda card wrongly returns 0 to glCheckFramebufferStatus() but sets
  427. // no error flag. I think it meant to return GL_FRAMEBUFFER_UNSUPPORTED, but who
  428. // knows.
  429. if (glGetError() == GL_NO_ERROR)
  430. error_string << "May not be supported by your OpenGL implementation.";
  431. // the remaining error is an indication of a serious fuckup since it should
  432. // only be returned if glCheckFramebufferStatus() was called with the wrong
  433. // arguments.
  434. else
  435. error_string << "Cannot create canvas: Aliens did it (OpenGL error code: " << glGetError() << ")";
  436. }
  437. canvas->release();
  438. throw Exception(error_string.str().c_str());
  439. return NULL; // never reached
  440. }
  441. Shader *Graphics::newShader(const Shader::ShaderSources &sources)
  442. {
  443. return new Shader(sources);
  444. }
  445. void Graphics::setColor(const Color &c)
  446. {
  447. gl.setColor(c);
  448. }
  449. Color Graphics::getColor() const
  450. {
  451. return gl.getColor();
  452. }
  453. void Graphics::setBackgroundColor(const Color &c)
  454. {
  455. gl.setClearColor(c);
  456. }
  457. Color Graphics::getBackgroundColor() const
  458. {
  459. return gl.getClearColor();
  460. }
  461. void Graphics::setFont(Font *font)
  462. {
  463. Object::AutoRelease fontrelease(currentFont);
  464. currentFont = font;
  465. if (font != 0)
  466. currentFont->retain();
  467. }
  468. Font *Graphics::getFont() const
  469. {
  470. return currentFont;
  471. }
  472. void Graphics::setColorMask(bool r, bool g, bool b, bool a)
  473. {
  474. colorMask[0] = r;
  475. colorMask[1] = g;
  476. colorMask[2] = b;
  477. colorMask[3] = a;
  478. glColorMask((GLboolean) r, (GLboolean) g, (GLboolean) b, (GLboolean) a);
  479. }
  480. const bool *Graphics::getColorMask() const
  481. {
  482. return colorMask;
  483. }
  484. void Graphics::setBlendMode(Graphics::BlendMode mode)
  485. {
  486. const int gl_1_4 = GLEE_VERSION_1_4;
  487. GLenum func = GL_FUNC_ADD;
  488. GLenum src_rgb = GL_ONE;
  489. GLenum src_a = GL_ONE;
  490. GLenum dst_rgb = GL_ZERO;
  491. GLenum dst_a = GL_ZERO;
  492. switch (mode)
  493. {
  494. case BLEND_ALPHA:
  495. if (gl_1_4 || GLEE_EXT_blend_func_separate)
  496. {
  497. src_rgb = GL_SRC_ALPHA;
  498. src_a = GL_ONE;
  499. dst_rgb = dst_a = 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. src_rgb = src_a = GL_SRC_ALPHA;
  508. dst_rgb = dst_a = GL_ONE_MINUS_SRC_ALPHA;
  509. }
  510. break;
  511. case BLEND_MULTIPLICATIVE:
  512. src_rgb = src_a = GL_DST_COLOR;
  513. dst_rgb = dst_a = GL_ZERO;
  514. break;
  515. case BLEND_PREMULTIPLIED:
  516. src_rgb = src_a = GL_ONE;
  517. dst_rgb = dst_a = GL_ONE_MINUS_SRC_ALPHA;
  518. break;
  519. case BLEND_SUBTRACTIVE:
  520. func = GL_FUNC_REVERSE_SUBTRACT;
  521. case BLEND_ADDITIVE:
  522. src_rgb = src_a = GL_SRC_ALPHA;
  523. dst_rgb = dst_a = GL_ONE;
  524. break;
  525. case BLEND_REPLACE:
  526. default:
  527. src_rgb = src_a = GL_ONE;
  528. dst_rgb = dst_a = GL_ZERO;
  529. break;
  530. }
  531. if (gl_1_4 || GLEE_ARB_imaging)
  532. glBlendEquation(func);
  533. else if (GLEE_EXT_blend_minmax && GLEE_EXT_blend_subtract)
  534. glBlendEquationEXT(func);
  535. else
  536. {
  537. if (func == GL_FUNC_REVERSE_SUBTRACT)
  538. throw Exception("This graphics card does not support the subtractive blend mode!");
  539. // GL_FUNC_ADD is the default even without access to glBlendEquation, so that'll still work.
  540. }
  541. if (src_rgb == src_a && dst_rgb == dst_a)
  542. glBlendFunc(src_rgb, dst_rgb);
  543. else
  544. {
  545. if (gl_1_4)
  546. glBlendFuncSeparate(src_rgb, dst_rgb, src_a, dst_a);
  547. else if (GLEE_EXT_blend_func_separate)
  548. glBlendFuncSeparateEXT(src_rgb, dst_rgb, src_a, dst_a);
  549. else
  550. throw Exception("This graphics card does not support separated rgb and alpha blend functions!");
  551. }
  552. }
  553. Graphics::BlendMode Graphics::getBlendMode() const
  554. {
  555. const int gl_1_4 = GLEE_VERSION_1_4;
  556. GLint src_rgb, src_a, dst_rgb, dst_a;
  557. GLint equation = GL_FUNC_ADD;
  558. if (gl_1_4 || GLEE_EXT_blend_func_separate)
  559. {
  560. glGetIntegerv(GL_BLEND_SRC_RGB, &src_rgb);
  561. glGetIntegerv(GL_BLEND_SRC_ALPHA, &src_a);
  562. glGetIntegerv(GL_BLEND_DST_RGB, &dst_rgb);
  563. glGetIntegerv(GL_BLEND_DST_ALPHA, &dst_a);
  564. }
  565. else
  566. {
  567. glGetIntegerv(GL_BLEND_SRC, &src_rgb);
  568. glGetIntegerv(GL_BLEND_DST, &dst_rgb);
  569. src_a = src_rgb;
  570. dst_a = dst_rgb;
  571. }
  572. if (gl_1_4 || GLEE_ARB_imaging || (GLEE_EXT_blend_minmax && GLEE_EXT_blend_subtract))
  573. glGetIntegerv(GL_BLEND_EQUATION, &equation);
  574. if (equation == GL_FUNC_REVERSE_SUBTRACT) // && src == GL_SRC_ALPHA && dst == GL_ONE
  575. return BLEND_SUBTRACTIVE;
  576. // Everything else has equation == GL_FUNC_ADD.
  577. else if (src_rgb == src_a && dst_rgb == dst_a)
  578. {
  579. if (src_rgb == GL_SRC_ALPHA && dst_rgb == GL_ONE)
  580. return BLEND_ADDITIVE;
  581. else if (src_rgb == GL_SRC_ALPHA && dst_rgb == GL_ONE_MINUS_SRC_ALPHA)
  582. return BLEND_ALPHA; // alpha blend mode fallback for very old OpenGL versions.
  583. else if (src_rgb == GL_DST_COLOR && dst_rgb == GL_ZERO)
  584. return BLEND_MULTIPLICATIVE;
  585. else if (src_rgb == GL_ONE && dst_rgb == GL_ONE_MINUS_SRC_ALPHA)
  586. return BLEND_PREMULTIPLIED;
  587. else if (src_rgb == GL_ONE && dst_rgb == GL_ZERO)
  588. return BLEND_REPLACE;
  589. }
  590. else if (src_rgb == GL_SRC_ALPHA && src_a == GL_ONE &&
  591. dst_rgb == GL_ONE_MINUS_SRC_ALPHA && dst_a == GL_ONE_MINUS_SRC_ALPHA)
  592. return BLEND_ALPHA;
  593. throw Exception("Unknown blend mode");
  594. }
  595. void Graphics::setDefaultFilter(const Image::Filter &f)
  596. {
  597. Image::setDefaultFilter(f);
  598. }
  599. const Image::Filter &Graphics::getDefaultFilter() const
  600. {
  601. return Image::getDefaultFilter();
  602. }
  603. void Graphics::setDefaultMipmapFilter(Image::FilterMode filter, float sharpness)
  604. {
  605. Image::setDefaultMipmapFilter(filter);
  606. Image::setDefaultMipmapSharpness(sharpness);
  607. }
  608. void Graphics::getDefaultMipmapFilter(Image::FilterMode *filter, float *sharpness) const
  609. {
  610. *filter = Image::getDefaultMipmapFilter();
  611. *sharpness = Image::getDefaultMipmapSharpness();
  612. }
  613. void Graphics::setLineWidth(float width)
  614. {
  615. lineWidth = width;
  616. }
  617. void Graphics::setLineStyle(Graphics::LineStyle style)
  618. {
  619. lineStyle = style;
  620. }
  621. float Graphics::getLineWidth() const
  622. {
  623. return lineWidth;
  624. }
  625. Graphics::LineStyle Graphics::getLineStyle() const
  626. {
  627. return lineStyle;
  628. }
  629. void Graphics::setPointSize(float size)
  630. {
  631. glPointSize((GLfloat)size);
  632. }
  633. void Graphics::setPointStyle(Graphics::PointStyle style)
  634. {
  635. if (style == POINT_SMOOTH)
  636. glEnable(GL_POINT_SMOOTH);
  637. else // love::POINT_ROUGH
  638. glDisable(GL_POINT_SMOOTH);
  639. }
  640. float Graphics::getPointSize() const
  641. {
  642. GLfloat size;
  643. glGetFloatv(GL_POINT_SIZE, &size);
  644. return (float)size;
  645. }
  646. Graphics::PointStyle Graphics::getPointStyle() const
  647. {
  648. if (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE)
  649. return POINT_SMOOTH;
  650. else
  651. return POINT_ROUGH;
  652. }
  653. int Graphics::getMaxPointSize() const
  654. {
  655. GLint max;
  656. glGetIntegerv(GL_POINT_SIZE_MAX, &max);
  657. return (int)max;
  658. }
  659. 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)
  660. {
  661. if (currentFont != 0)
  662. currentFont->print(str, x, y, 0.0, angle, sx, sy, ox, oy, kx, ky);
  663. }
  664. 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)
  665. {
  666. if (currentFont == 0)
  667. return;
  668. using std::string;
  669. using std::vector;
  670. // wrappedlines indicates which lines were automatically wrapped. It's
  671. // guaranteed to have the same number of elements as lines_to_draw.
  672. vector<bool> wrappedlines;
  673. vector<string> lines_to_draw = currentFont->getWrap(str, wrap, 0, &wrappedlines);
  674. glPushMatrix();
  675. static Matrix t;
  676. t.setTransformation(ceil(x), ceil(y), angle, sx, sy, ox, oy, kx, ky);
  677. glMultMatrixf((const GLfloat *)t.getElements());
  678. x = y = 0.0f;
  679. try
  680. {
  681. // now for the actual printing
  682. vector<string>::const_iterator line_iter, line_end = lines_to_draw.end();
  683. float extra_spacing = 0.0f;
  684. int num_spaces = 0;
  685. int i = 0;
  686. for (line_iter = lines_to_draw.begin(); line_iter != line_end; ++line_iter)
  687. {
  688. float width = static_cast<float>(currentFont->getWidth(*line_iter));
  689. switch (align)
  690. {
  691. case ALIGN_RIGHT:
  692. currentFont->print(*line_iter, ceil(x + (wrap - width)), ceil(y), 0.0f);
  693. break;
  694. case ALIGN_CENTER:
  695. currentFont->print(*line_iter, ceil(x + (wrap - width) / 2), ceil(y), 0.0f);
  696. break;
  697. case ALIGN_JUSTIFY:
  698. num_spaces = std::count(line_iter->begin(), line_iter->end(), ' ');
  699. if (wrappedlines[i] && num_spaces >= 1)
  700. extra_spacing = (wrap - width) / float(num_spaces);
  701. else
  702. extra_spacing = 0.0f;
  703. currentFont->print(*line_iter, ceil(x), ceil(y), extra_spacing);
  704. break;
  705. case ALIGN_LEFT:
  706. default:
  707. currentFont->print(*line_iter, ceil(x), ceil(y), 0.0f);
  708. break;
  709. }
  710. y += currentFont->getHeight() * currentFont->getLineHeight();
  711. i++;
  712. }
  713. }
  714. catch (love::Exception &)
  715. {
  716. glPopMatrix();
  717. throw;
  718. }
  719. glPopMatrix();
  720. }
  721. /**
  722. * Primitives
  723. **/
  724. void Graphics::point(float x, float y)
  725. {
  726. gl.bindTexture(0);
  727. glBegin(GL_POINTS);
  728. glVertex2f(x, y);
  729. glEnd();
  730. }
  731. // Calculate line boundary points u1 and u2. Sketch:
  732. // u1
  733. // -------------+---...___
  734. // | ```'''-- ---
  735. // p- - - - - - q- - . _ _ | w/2
  736. // | ` ' ' r +
  737. // -------------+---...___ | w/2
  738. // u2 ```'''-- ---
  739. //
  740. // u1 and u2 depend on four things:
  741. // - the half line width w/2
  742. // - the previous line vertex p
  743. // - the current line vertex q
  744. // - the next line vertex r
  745. //
  746. // u1/u2 are the intersection points of the parallel lines to p-q and q-r,
  747. // i.e. the point where
  748. //
  749. // (p + w/2 * n1) + mu * (q - p) = (q + w/2 * n2) + lambda * (r - q) (u1)
  750. // (p - w/2 * n1) + mu * (q - p) = (q - w/2 * n2) + lambda * (r - q) (u2)
  751. //
  752. // with n1,n2 being the normals on the segments p-q and q-r:
  753. //
  754. // n1 = perp(q - p) / |q - p|
  755. // n2 = perp(r - q) / |r - q|
  756. //
  757. // The intersection points can be calculated using cramers rule.
  758. static void pushIntersectionPoints(Vector *vertices, Vector *overdraw,
  759. int pos, int count, float hw, float overdraw_factor,
  760. const Vector &p, const Vector &q, const Vector &r)
  761. {
  762. // calculate line directions
  763. Vector s = (q - p);
  764. Vector t = (r - q);
  765. // calculate vertex displacement vectors
  766. Vector n1 = s.getNormal();
  767. Vector n2 = t.getNormal();
  768. n1.normalize();
  769. n2.normalize();
  770. float det_norm = n1 ^ n2; // will be close to zero if the angle between the normals is sharp
  771. n1 *= hw;
  772. n2 *= hw;
  773. // lines parallel -> assume intersection at displacement points
  774. if (fabs(det_norm) <= .03)
  775. {
  776. vertices[pos] = q - n2;
  777. vertices[pos+1] = q + n2;
  778. }
  779. // real intersection -> calculate boundary intersection points with cramers rule
  780. else
  781. {
  782. float det = s ^ t;
  783. Vector d = n1 - n2;
  784. Vector b = s - d; // s = q - p
  785. Vector c = s + d;
  786. float lambda = (b ^ t) / det;
  787. float mu = (c ^ t) / det;
  788. // ordering for GL_TRIANGLE_STRIP
  789. vertices[pos] = p + s*mu - n1; // u1
  790. vertices[pos+1] = p + s*lambda + n1; // u2
  791. }
  792. if (overdraw)
  793. {
  794. // displacement of the overdraw vertices
  795. Vector x = (vertices[pos] - q) * overdraw_factor;
  796. overdraw[pos] = vertices[pos];
  797. overdraw[pos+1] = vertices[pos] + x;
  798. overdraw[2*count-pos-2] = vertices[pos+1];
  799. overdraw[2*count-pos-1] = vertices[pos+1] - x;
  800. }
  801. }
  802. // precondition:
  803. // glEnableClientState(GL_VERTEX_ARRAY);
  804. static void draw_overdraw(Vector *overdraw, size_t count, float pixel_size, bool looping)
  805. {
  806. // if not looping, the outer overdraw vertices need to be displaced
  807. // to cover the line endings, i.e.:
  808. // +- - - - //- - + +- - - - - //- - - +
  809. // +-------//-----+ : +-------//-----+ :
  810. // | core // line | --> : | core // line | :
  811. // +-----//-------+ : +-----//-------+ :
  812. // +- - //- - - - + +- - - //- - - - - +
  813. if (!looping)
  814. {
  815. Vector s = overdraw[1] - overdraw[3];
  816. s.normalize();
  817. s *= pixel_size;
  818. overdraw[1] += s;
  819. overdraw[2*count-1] += s;
  820. Vector t = overdraw[count-1] - overdraw[count-3];
  821. t.normalize();
  822. t *= pixel_size;
  823. overdraw[count-1] += t;
  824. overdraw[count+1] += t;
  825. // we need to draw two more triangles to close the
  826. // overdraw at the line start.
  827. overdraw[2*count] = overdraw[0];
  828. overdraw[2*count+1] = overdraw[1];
  829. }
  830. // prepare colors:
  831. // even indices in overdraw* point to inner vertices => alpha = current-alpha,
  832. // odd indices point to outer vertices => alpha = 0.
  833. Color c = gl.getColor();
  834. Color *colors = new Color[2*count+2];
  835. for (size_t i = 0; i < 2*count+2; ++i)
  836. {
  837. colors[i] = c;
  838. // avoids branching. equiv to if (i%2 == 1) colors[i].a = 0;
  839. colors[i].a *= GLubyte(i % 2 == 0);
  840. }
  841. // draw faded out line halos
  842. glEnableClientState(GL_COLOR_ARRAY);
  843. glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
  844. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)overdraw);
  845. glDrawArrays(GL_TRIANGLE_STRIP, 0, 2*count + 2 * int(!looping));
  846. glDisableClientState(GL_COLOR_ARRAY);
  847. // "if GL_COLOR_ARRAY is enabled, the value of the current color is
  848. // undefined after glDrawArrays executes"
  849. gl.setColor(c);
  850. delete[] colors;
  851. }
  852. void Graphics::polyline(const float *coords, size_t count)
  853. {
  854. Vector *vertices = new Vector[count]; // two vertices for every line end-point
  855. Vector *overdraw = NULL;
  856. Vector p,q,r;
  857. bool looping = (coords[0] == coords[count-2]) && (coords[1] == coords[count-1]);
  858. float halfwidth = lineWidth/2.f;
  859. float pixel_size = pixel_size_stack.back();
  860. float overdraw_factor = .0f;
  861. if (lineStyle == LINE_SMOOTH)
  862. {
  863. overdraw = new Vector[2*count+2];
  864. overdraw_factor = pixel_size / halfwidth;
  865. halfwidth = std::max(.0f, halfwidth - .25f*pixel_size);
  866. }
  867. // get line vertex boundaries
  868. // if not looping, extend the line at the beginning, else use last point as `p'
  869. r = Vector(coords[0], coords[1]);
  870. if (!looping)
  871. q = r * 2 - Vector(coords[2], coords[3]);
  872. else
  873. q = Vector(coords[count-4], coords[count-3]);
  874. for (size_t i = 0; i+3 < count; i += 2)
  875. {
  876. p = q;
  877. q = r;
  878. r = Vector(coords[i+2], coords[i+3]);
  879. pushIntersectionPoints(vertices, overdraw, i, count, halfwidth, overdraw_factor, p,q,r);
  880. }
  881. // if not looping, extend the line at the end, else use first point as `r'
  882. p = q;
  883. q = r;
  884. if (!looping)
  885. r += q - p;
  886. else
  887. r = Vector(coords[2], coords[3]);
  888. pushIntersectionPoints(vertices, overdraw, count-2, count, halfwidth, overdraw_factor, p,q,r);
  889. // end get line vertex boundaries
  890. // draw the core line
  891. gl.bindTexture(0);
  892. glEnableClientState(GL_VERTEX_ARRAY);
  893. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)vertices);
  894. glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
  895. // draw the line halo (antialiasing)
  896. if (lineStyle == LINE_SMOOTH)
  897. draw_overdraw(overdraw, count, pixel_size, looping);
  898. glDisableClientState(GL_VERTEX_ARRAY);
  899. // cleanup
  900. delete[] vertices;
  901. if (lineStyle == LINE_SMOOTH)
  902. delete[] overdraw;
  903. }
  904. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  905. {
  906. float coords[] = {x,y, x,y+h, x+w,y+h, x+w,y, x,y};
  907. polygon(mode, coords, 5 * 2);
  908. }
  909. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  910. {
  911. float two_pi = static_cast<float>(LOVE_M_PI * 2);
  912. if (points <= 0) points = 1;
  913. float angle_shift = (two_pi / points);
  914. float phi = .0f;
  915. float *coords = new float[2 * (points + 1)];
  916. for (int i = 0; i < points; ++i, phi += angle_shift)
  917. {
  918. coords[2*i] = x + radius * cosf(phi);
  919. coords[2*i+1] = y + radius * sinf(phi);
  920. }
  921. coords[2*points] = coords[0];
  922. coords[2*points+1] = coords[1];
  923. polygon(mode, coords, (points + 1) * 2);
  924. delete[] coords;
  925. }
  926. void Graphics::arc(DrawMode mode, float x, float y, float radius, float angle1, float angle2, int points)
  927. {
  928. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  929. if (points <= 0 || angle1 == angle2)
  930. return;
  931. // Oh, you want to draw a circle?
  932. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  933. {
  934. circle(mode, x, y, radius, points);
  935. return;
  936. }
  937. float angle_shift = (angle2 - angle1) / points;
  938. // Bail on precision issues.
  939. if (angle_shift == 0.0)
  940. return;
  941. float phi = angle1;
  942. int num_coords = (points + 3) * 2;
  943. float *coords = new float[num_coords];
  944. coords[0] = coords[num_coords - 2] = x;
  945. coords[1] = coords[num_coords - 1] = y;
  946. for (int i = 0; i <= points; ++i, phi += angle_shift)
  947. {
  948. coords[2 * (i+1)] = x + radius * cosf(phi);
  949. coords[2 * (i+1) + 1] = y + radius * sinf(phi);
  950. }
  951. // GL_POLYGON can only fill-draw convex polygons, so we need to do stuff manually here
  952. if (mode == DRAW_LINE)
  953. {
  954. polyline(coords, num_coords); // Artifacts at sharp angles if set to looping.
  955. }
  956. else
  957. {
  958. gl.bindTexture(0);
  959. glEnableClientState(GL_VERTEX_ARRAY);
  960. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *) coords);
  961. glDrawArrays(GL_TRIANGLE_FAN, 0, points + 2);
  962. glDisableClientState(GL_VERTEX_ARRAY);
  963. }
  964. delete[] coords;
  965. }
  966. /// @param mode the draw mode
  967. /// @param coords the coordinate array
  968. /// @param count the number of coordinates/size of the array
  969. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  970. {
  971. // coords is an array of a closed loop of vertices, i.e.
  972. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  973. if (mode == DRAW_LINE)
  974. {
  975. polyline(coords, count);
  976. }
  977. else
  978. {
  979. gl.bindTexture(0);
  980. glEnableClientState(GL_VERTEX_ARRAY);
  981. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)coords);
  982. glDrawArrays(GL_POLYGON, 0, count/2-1); // opengl will close the polygon for us
  983. glDisableClientState(GL_VERTEX_ARRAY);
  984. }
  985. }
  986. love::image::ImageData *Graphics::newScreenshot(love::image::Image *image, bool copyAlpha)
  987. {
  988. // Temporarily unbind the currently active canvas (glReadPixels reads the
  989. // active framebuffer, not the main one.)
  990. Canvas *curcanvas = Canvas::current;
  991. if (curcanvas)
  992. Canvas::bindDefaultCanvas();
  993. int w = getWidth();
  994. int h = getHeight();
  995. int row = 4*w;
  996. int size = row*h;
  997. GLubyte *pixels = 0;
  998. GLubyte *screenshot = 0;
  999. try
  1000. {
  1001. pixels = new GLubyte[size];
  1002. screenshot = new GLubyte[size];
  1003. }
  1004. catch (std::exception &)
  1005. {
  1006. delete[] pixels;
  1007. delete[] screenshot;
  1008. if (curcanvas)
  1009. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  1010. throw love::Exception("Out of memory.");
  1011. }
  1012. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  1013. if (!copyAlpha)
  1014. {
  1015. // Replace alpha values with full opacity.
  1016. for (int i = 3; i < size; i += 4)
  1017. pixels[i] = 255;
  1018. }
  1019. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  1020. GLubyte *src = pixels - row, *dst = screenshot + size;
  1021. for (int i = 0; i < h; ++i)
  1022. memcpy(dst-=row, src+=row, row);
  1023. delete[] pixels;
  1024. love::image::ImageData *img = 0;
  1025. try
  1026. {
  1027. // Tell the new ImageData that it owns the screenshot data, so we don't
  1028. // need to delete it here.
  1029. img = image->newImageData(w, h, (void *) screenshot, true);
  1030. }
  1031. catch (love::Exception &)
  1032. {
  1033. delete[] screenshot;
  1034. if (curcanvas)
  1035. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  1036. throw;
  1037. }
  1038. // Re-bind the active canvas, if necessary.
  1039. if (curcanvas)
  1040. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  1041. return img;
  1042. }
  1043. std::string Graphics::getRendererInfo(Graphics::RendererInfo infotype) const
  1044. {
  1045. const char *infostr = 0;
  1046. switch (infotype)
  1047. {
  1048. case Graphics::RENDERER_INFO_NAME:
  1049. default:
  1050. infostr = "OpenGL";
  1051. break;
  1052. case Graphics::RENDERER_INFO_VERSION:
  1053. infostr = (const char *) glGetString(GL_VERSION);
  1054. break;
  1055. case Graphics::RENDERER_INFO_VENDOR:
  1056. infostr = (const char *) glGetString(GL_VENDOR);
  1057. break;
  1058. case Graphics::RENDERER_INFO_DEVICE:
  1059. infostr = (const char *) glGetString(GL_RENDERER);
  1060. break;
  1061. }
  1062. if (!infostr)
  1063. throw love::Exception("Cannot retrieve renderer information.");
  1064. return std::string(infostr);
  1065. }
  1066. void Graphics::push()
  1067. {
  1068. if (userMatrices == matrixLimit)
  1069. throw Exception("Maximum stack depth reached. (More pushes than pops?)");
  1070. glPushMatrix();
  1071. ++userMatrices;
  1072. pixel_size_stack.push_back(pixel_size_stack.back());
  1073. }
  1074. void Graphics::pop()
  1075. {
  1076. if (userMatrices < 1)
  1077. throw Exception("Minimum stack depth reached. (More pops than pushes?)");
  1078. glPopMatrix();
  1079. --userMatrices;
  1080. pixel_size_stack.pop_back();
  1081. }
  1082. void Graphics::rotate(float r)
  1083. {
  1084. glRotatef(LOVE_TODEG(r), 0, 0, 1);
  1085. }
  1086. void Graphics::scale(float x, float y)
  1087. {
  1088. glScalef(x, y, 1);
  1089. pixel_size_stack.back() *= 2. / double(x + y);
  1090. }
  1091. void Graphics::translate(float x, float y)
  1092. {
  1093. glTranslatef(x, y, 0);
  1094. }
  1095. void Graphics::shear(float kx, float ky)
  1096. {
  1097. Matrix t;
  1098. t.setShear(kx, ky);
  1099. glMultMatrixf((const GLfloat *)t.getElements());
  1100. }
  1101. void Graphics::origin()
  1102. {
  1103. glLoadIdentity();
  1104. pixel_size_stack.back() = 1;
  1105. }
  1106. } // opengl
  1107. } // graphics
  1108. } // love