Graphics.cpp 29 KB

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