Graphics.cpp 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  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. namespace love
  30. {
  31. namespace graphics
  32. {
  33. namespace opengl
  34. {
  35. Graphics::Graphics()
  36. : currentFont(0)
  37. , lineStyle(LINE_SMOOTH)
  38. , lineWidth(1)
  39. , matrixLimit(0)
  40. , userMatrices(0)
  41. {
  42. currentWindow = love::window::sdl::Window::getSingleton();
  43. }
  44. Graphics::~Graphics()
  45. {
  46. if (currentFont != 0)
  47. currentFont->release();
  48. currentWindow->release();
  49. }
  50. const char *Graphics::getName() const
  51. {
  52. return "love.graphics.opengl";
  53. }
  54. bool Graphics::checkMode(int width, int height, bool fullscreen) const
  55. {
  56. return currentWindow->checkWindowSize(width, height, fullscreen);
  57. }
  58. DisplayState Graphics::saveState()
  59. {
  60. DisplayState s;
  61. s.color = getColor();
  62. s.backgroundColor = getBackgroundColor();
  63. s.blendMode = getBlendMode();
  64. s.colorMode = getColorMode();
  65. //get line style
  66. s.lineStyle = lineStyle;
  67. //get the point size
  68. glGetFloatv(GL_POINT_SIZE, &s.pointSize);
  69. //get point style
  70. s.pointStyle = (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE) ? Graphics::POINT_SMOOTH : Graphics::POINT_ROUGH;
  71. //get scissor status
  72. s.scissor = (glIsEnabled(GL_SCISSOR_TEST) == GL_TRUE);
  73. //do we have scissor, if so, store the box
  74. if (s.scissor)
  75. glGetIntegerv(GL_SCISSOR_BOX, s.scissorBox);
  76. return s;
  77. }
  78. void Graphics::restoreState(const DisplayState &s)
  79. {
  80. setColor(s.color);
  81. setBackgroundColor(s.backgroundColor);
  82. setBlendMode(s.blendMode);
  83. setColorMode(s.colorMode);
  84. setLine(lineWidth, s.lineStyle);
  85. setPoint(s.pointSize, s.pointStyle);
  86. if (s.scissor)
  87. setScissor(s.scissorBox[0], s.scissorBox[1], s.scissorBox[2], s.scissorBox[3]);
  88. else
  89. setScissor();
  90. }
  91. bool Graphics::setMode(int width, int height, bool fullscreen, bool vsync, int fsaa)
  92. {
  93. // This operation destroys the OpenGL context, so
  94. // we must save the state.
  95. DisplayState tempState;
  96. if (isCreated())
  97. tempState = saveState();
  98. // Unload all volatile objects. These must be reloaded after
  99. // the display mode change.
  100. Volatile::unloadAll();
  101. uninitializeContext();
  102. bool success = currentWindow->setWindow(width, height, fullscreen, vsync, fsaa);
  103. // Regardless of failure, we'll have to set up OpenGL once again.
  104. width = currentWindow->getWidth();
  105. height = currentWindow->getHeight();
  106. // Okay, setup OpenGL.
  107. initializeContext();
  108. // Make sure antialiasing works when set elsewhere
  109. glEnable(GL_MULTISAMPLE);
  110. // Enable blending
  111. glEnable(GL_BLEND);
  112. // "Normal" blending
  113. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  114. // Enable line/point smoothing.
  115. setLineStyle(LINE_SMOOTH);
  116. glEnable(GL_POINT_SMOOTH);
  117. glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
  118. // Auto-generated mipmaps should be the best quality possible
  119. if (GLEE_VERSION_1_4 || GLEE_SGIS_generate_mipmap)
  120. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  121. // Enable textures
  122. glEnable(GL_TEXTURE_2D);
  123. setActiveTextureUnit(0);
  124. // Set the viewport to top-left corner
  125. glViewport(0, 0, width, height);
  126. // Reset the projection matrix
  127. glMatrixMode(GL_PROJECTION);
  128. glLoadIdentity();
  129. // Set up orthographic view (no depth)
  130. glOrtho(0.0, width, height, 0.0, -1.0, 1.0);
  131. // Reset modelview matrix
  132. glMatrixMode(GL_MODELVIEW);
  133. glLoadIdentity();
  134. // Set pixel row alignment
  135. glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
  136. // Reload all volatile objects.
  137. if (!Volatile::loadAll())
  138. std::cerr << "Could not reload all volatile objects." << std::endl;
  139. // Restore the display state.
  140. restoreState(tempState);
  141. // Get the maximum number of matrices
  142. // subtract a few to give the engine some room.
  143. glGetIntegerv(GL_MAX_MODELVIEW_STACK_DEPTH, &matrixLimit);
  144. matrixLimit -= 5;
  145. return success;
  146. }
  147. void Graphics::getMode(int &width, int &height, bool &fullscreen, bool &vsync, int &fsaa) const
  148. {
  149. currentWindow->getWindow(width, height, fullscreen, vsync, fsaa);
  150. }
  151. bool Graphics::toggleFullscreen()
  152. {
  153. int width, height, fsaa;
  154. bool fullscreen, vsync;
  155. currentWindow->getWindow(width, height, fullscreen, vsync, fsaa);
  156. return setMode(width, height, !fullscreen, vsync, fsaa);
  157. }
  158. void Graphics::reset()
  159. {
  160. DisplayState s;
  161. discardStencil();
  162. Canvas::bindDefaultCanvas();
  163. Shader::detach();
  164. restoreState(s);
  165. }
  166. void Graphics::clear()
  167. {
  168. glClear(GL_COLOR_BUFFER_BIT);
  169. glLoadIdentity();
  170. }
  171. void Graphics::present()
  172. {
  173. currentWindow->swapBuffers();
  174. }
  175. void Graphics::setIcon(Image *image)
  176. {
  177. currentWindow->setIcon(image->getData());
  178. }
  179. void Graphics::setCaption(const char *caption)
  180. {
  181. std::string title(caption);
  182. currentWindow->setWindowTitle(title);
  183. }
  184. int Graphics::getCaption(lua_State *L) const
  185. {
  186. std::string title = currentWindow->getWindowTitle();
  187. lua_pushstring(L, title.c_str());
  188. return 1;
  189. }
  190. int Graphics::getWidth() const
  191. {
  192. return currentWindow->getWidth();
  193. }
  194. int Graphics::getHeight() const
  195. {
  196. return currentWindow->getHeight();
  197. }
  198. int Graphics::getRenderHeight() const
  199. {
  200. if (Canvas::current)
  201. return Canvas::current->getHeight();
  202. return getHeight();
  203. }
  204. bool Graphics::isCreated() const
  205. {
  206. return currentWindow->isCreated();
  207. }
  208. int Graphics::getModes(lua_State *L) const
  209. {
  210. int n;
  211. love::window::Window::WindowSize **modes = currentWindow->getFullscreenSizes(n);
  212. if (modes == 0)
  213. return 0;
  214. lua_newtable(L);
  215. for (int i = 0; i < n ; i++)
  216. {
  217. lua_pushinteger(L, i+1);
  218. lua_newtable(L);
  219. // Inner table attribs.
  220. lua_pushstring(L, "width");
  221. lua_pushinteger(L, modes[i]->width);
  222. lua_settable(L, -3);
  223. lua_pushstring(L, "height");
  224. lua_pushinteger(L, modes[i]->height);
  225. lua_settable(L, -3);
  226. // Inner table attribs end.
  227. lua_settable(L, -3);
  228. delete modes[i];
  229. }
  230. delete[] modes;
  231. return 1;
  232. }
  233. void Graphics::setScissor(int x, int y, int width, int height)
  234. {
  235. glEnable(GL_SCISSOR_TEST);
  236. glScissor(x, getRenderHeight() - (y + height), width, height); // Compensates for the fact that our y-coordinate is reverse of OpenGLs.
  237. }
  238. void Graphics::setScissor()
  239. {
  240. glDisable(GL_SCISSOR_TEST);
  241. }
  242. int Graphics::getScissor(lua_State *L) const
  243. {
  244. if (glIsEnabled(GL_SCISSOR_TEST) == GL_FALSE)
  245. return 0;
  246. GLint scissor[4];
  247. glGetIntegerv(GL_SCISSOR_BOX, scissor);
  248. lua_pushnumber(L, scissor[0]);
  249. lua_pushnumber(L, getRenderHeight() - (scissor[1] + scissor[3])); // Compensates for the fact that our y-coordinate is reverse of OpenGLs.
  250. lua_pushnumber(L, scissor[2]);
  251. lua_pushnumber(L, scissor[3]);
  252. return 4;
  253. }
  254. void Graphics::defineStencil()
  255. {
  256. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  257. glEnable(GL_STENCIL_TEST);
  258. glClear(GL_STENCIL_BUFFER_BIT);
  259. glStencilFunc(GL_ALWAYS, 1, 1);
  260. glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  261. }
  262. void Graphics::useStencil(bool invert)
  263. {
  264. glStencilFunc(GL_EQUAL, (int)(!invert), 1); // invert ? 0 : 1
  265. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  266. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  267. }
  268. void Graphics::discardStencil()
  269. {
  270. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  271. glDisable(GL_STENCIL_TEST);
  272. }
  273. Image *Graphics::newImage(love::image::ImageData *data)
  274. {
  275. // Create the image.
  276. Image *image = new Image(data);
  277. bool success;
  278. try
  279. {
  280. success = image->load();
  281. }
  282. catch(love::Exception &)
  283. {
  284. image->release();
  285. throw;
  286. }
  287. if (!success)
  288. {
  289. image->release();
  290. return 0;
  291. }
  292. return image;
  293. }
  294. Quad *Graphics::newQuad(float x, float y, float w, float h, float sw, float sh)
  295. {
  296. Quad::Viewport v;
  297. v.x = x;
  298. v.y = y;
  299. v.w = w;
  300. v.h = h;
  301. return new Quad(v, sw, sh);
  302. }
  303. Font *Graphics::newFont(love::font::Rasterizer *r, const Image::Filter &filter)
  304. {
  305. return new Font(r, filter);
  306. }
  307. SpriteBatch *Graphics::newSpriteBatch(Image *image, int size, int usage)
  308. {
  309. return new SpriteBatch(image, size, usage);
  310. }
  311. ParticleSystem *Graphics::newParticleSystem(Image *image, int size)
  312. {
  313. return new ParticleSystem(image, size);
  314. }
  315. Canvas *Graphics::newCanvas(int width, int height, Canvas::TextureType texture_type)
  316. {
  317. if (texture_type == Canvas::TYPE_HDR && !Canvas::isHdrSupported())
  318. throw Exception("HDR Canvases are not supported by your OpenGL implementation");
  319. while (GL_NO_ERROR != glGetError())
  320. /* clear opengl error flag */;
  321. Canvas *canvas = new Canvas(width, height, texture_type);
  322. GLenum err = canvas->getStatus();
  323. // everything ok, return canvas (early out)
  324. if (err == GL_FRAMEBUFFER_COMPLETE)
  325. return canvas;
  326. // create error message
  327. std::stringstream error_string;
  328. error_string << "Cannot create canvas: ";
  329. switch (err)
  330. {
  331. case GL_FRAMEBUFFER_UNSUPPORTED:
  332. error_string << "Not supported by your OpenGL implementation.";
  333. break;
  334. // remaining error codes are highly unlikely:
  335. case GL_FRAMEBUFFER_UNDEFINED:
  336. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  337. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  338. case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
  339. case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
  340. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  341. error_string << "Error in implementation. Possible fix: Make canvas width and height powers of two.";
  342. break;
  343. default:
  344. // my intel hda card wrongly returns 0 to glCheckFramebufferStatus() but sets
  345. // no error flag. I think it meant to return GL_FRAMEBUFFER_UNSUPPORTED, but who
  346. // knows.
  347. if (glGetError() == GL_NO_ERROR)
  348. error_string << "May not be supported by your OpenGL implementation.";
  349. // the remaining error is an indication of a serious fuckup since it should
  350. // only be returned if glCheckFramebufferStatus() was called with the wrong
  351. // arguments.
  352. else
  353. error_string << "Cannot create canvas: Aliens did it (OpenGL error code: " << glGetError() << ")";
  354. }
  355. canvas->release();
  356. throw Exception(error_string.str().c_str());
  357. return NULL; // never reached
  358. }
  359. Shader *Graphics::newShader(const Shader::ShaderSources &sources)
  360. {
  361. return new Shader(sources);
  362. }
  363. void Graphics::setColor(const Color &c)
  364. {
  365. glColor4ubv(&c.r);
  366. }
  367. Color Graphics::getColor() const
  368. {
  369. float c[4];
  370. glGetFloatv(GL_CURRENT_COLOR, c);
  371. Color t;
  372. t.r = (unsigned char)(255.0f*c[0]);
  373. t.g = (unsigned char)(255.0f*c[1]);
  374. t.b = (unsigned char)(255.0f*c[2]);
  375. t.a = (unsigned char)(255.0f*c[3]);
  376. return t;
  377. }
  378. void Graphics::setBackgroundColor(const Color &c)
  379. {
  380. glClearColor((float)c.r/255.0f, (float)c.g/255.0f, (float)c.b/255.0f, (float)c.a/255.0f);
  381. }
  382. Color Graphics::getBackgroundColor() const
  383. {
  384. float c[4];
  385. glGetFloatv(GL_COLOR_CLEAR_VALUE, c);
  386. Color t;
  387. t.r = (unsigned char)(255.0f*c[0]);
  388. t.g = (unsigned char)(255.0f*c[1]);
  389. t.b = (unsigned char)(255.0f*c[2]);
  390. t.a = (unsigned char)(255.0f*c[3]);
  391. return t;
  392. }
  393. void Graphics::setFont(Font *font)
  394. {
  395. if (currentFont != 0)
  396. currentFont->release();
  397. currentFont = font;
  398. if (font != 0)
  399. currentFont->retain();
  400. }
  401. Font *Graphics::getFont() const
  402. {
  403. return currentFont;
  404. }
  405. void Graphics::setBlendMode(Graphics::BlendMode mode)
  406. {
  407. if (GLEE_VERSION_1_4 || GLEE_ARB_imaging)
  408. {
  409. if (mode == BLEND_SUBTRACTIVE)
  410. glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
  411. else
  412. glBlendEquation(GL_FUNC_ADD);
  413. }
  414. else if (GLEE_EXT_blend_minmax && GLEE_EXT_blend_subtract)
  415. {
  416. if (mode == BLEND_SUBTRACTIVE)
  417. glBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
  418. else
  419. glBlendEquationEXT(GL_FUNC_ADD_EXT);
  420. }
  421. else
  422. {
  423. if (mode == BLEND_SUBTRACTIVE)
  424. throw Exception("This graphics card does not support the subtract blend mode!");
  425. // GL_FUNC_ADD is the default even without access to glBlendEquation, so that'll still work.
  426. }
  427. if (mode == BLEND_ALPHA)
  428. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  429. else if (mode == BLEND_MULTIPLICATIVE)
  430. glBlendFunc(GL_DST_COLOR, GL_ZERO);
  431. else if (mode == BLEND_PREMULTIPLIED)
  432. glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  433. else if (mode == BLEND_NONE)
  434. glBlendFunc(GL_ONE, GL_ZERO);
  435. else // mode == BLEND_ADDITIVE || mode == BLEND_SUBTRACTIVE
  436. glBlendFunc(GL_SRC_ALPHA, GL_ONE);
  437. }
  438. void Graphics::setColorMode(Graphics::ColorMode mode)
  439. {
  440. if (mode == COLOR_MODULATE)
  441. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  442. else if (mode == COLOR_COMBINE)
  443. {
  444. glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_ADD_SIGNED);
  445. glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
  446. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
  447. }
  448. else // mode = COLOR_REPLACE
  449. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  450. }
  451. Graphics::BlendMode Graphics::getBlendMode() const
  452. {
  453. GLint dst, src, equation;
  454. glGetIntegerv(GL_BLEND_DST, &dst);
  455. glGetIntegerv(GL_BLEND_SRC, &src);
  456. glGetIntegerv(GL_BLEND_EQUATION, &equation);
  457. if (equation == GL_FUNC_REVERSE_SUBTRACT) // && src == GL_SRC_ALPHA && dst == GL_ONE
  458. return BLEND_SUBTRACTIVE;
  459. else if (src == GL_SRC_ALPHA && dst == GL_ONE) // && equation == GL_FUNC_ADD
  460. return BLEND_ADDITIVE;
  461. else if (src == GL_SRC_ALPHA && dst == GL_ONE_MINUS_SRC_ALPHA) // && equation == GL_FUNC_ADD
  462. return BLEND_ALPHA;
  463. else if (src == GL_DST_COLOR && dst == GL_ZERO) // && equation == GL_FUNC_ADD
  464. return BLEND_MULTIPLICATIVE;
  465. else if (src == GL_ONE && dst == GL_ONE_MINUS_SRC_ALPHA) // && equation == GL_FUNC_ADD
  466. return BLEND_PREMULTIPLIED;
  467. else if (src == GL_ONE && dst == GL_ZERO)
  468. return BLEND_NONE;
  469. return BLEND_MAX_ENUM; // Should never be reached.
  470. }
  471. Graphics::ColorMode Graphics::getColorMode() const
  472. {
  473. GLint mode;
  474. glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &mode);
  475. if (mode == GL_MODULATE)
  476. return COLOR_MODULATE;
  477. else if (mode == GL_COMBINE)
  478. return COLOR_COMBINE;
  479. else // mode == GL_REPLACE
  480. return COLOR_REPLACE;
  481. }
  482. void Graphics::setDefaultImageFilter(const Image::Filter &f)
  483. {
  484. Image::setDefaultFilter(f);
  485. }
  486. const Image::Filter &Graphics::getDefaultImageFilter() const
  487. {
  488. return Image::getDefaultFilter();
  489. }
  490. void Graphics::setLineWidth(float width)
  491. {
  492. lineWidth = width;
  493. }
  494. void Graphics::setLineStyle(Graphics::LineStyle style)
  495. {
  496. lineStyle = style;
  497. }
  498. void Graphics::setLine(float width, Graphics::LineStyle style)
  499. {
  500. setLineWidth(width);
  501. if (style == 0)
  502. return;
  503. setLineStyle(style);
  504. }
  505. float Graphics::getLineWidth() const
  506. {
  507. return lineWidth;
  508. }
  509. Graphics::LineStyle Graphics::getLineStyle() const
  510. {
  511. return lineStyle;
  512. }
  513. void Graphics::setPointSize(float size)
  514. {
  515. glPointSize((GLfloat)size);
  516. }
  517. void Graphics::setPointStyle(Graphics::PointStyle style)
  518. {
  519. if (style == POINT_SMOOTH)
  520. glEnable(GL_POINT_SMOOTH);
  521. else // love::POINT_ROUGH
  522. glDisable(GL_POINT_SMOOTH);
  523. }
  524. void Graphics::setPoint(float size, Graphics::PointStyle style)
  525. {
  526. if (style == POINT_SMOOTH)
  527. glEnable(GL_POINT_SMOOTH);
  528. else // POINT_ROUGH
  529. glDisable(GL_POINT_SMOOTH);
  530. glPointSize((GLfloat)size);
  531. }
  532. float Graphics::getPointSize() const
  533. {
  534. GLfloat size;
  535. glGetFloatv(GL_POINT_SIZE, &size);
  536. return (float)size;
  537. }
  538. Graphics::PointStyle Graphics::getPointStyle() const
  539. {
  540. if (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE)
  541. return POINT_SMOOTH;
  542. else
  543. return POINT_ROUGH;
  544. }
  545. int Graphics::getMaxPointSize() const
  546. {
  547. GLint max;
  548. glGetIntegerv(GL_POINT_SIZE_MAX, &max);
  549. return (int)max;
  550. }
  551. void Graphics::print(const char *str, float x, float y , float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  552. {
  553. if (currentFont != 0)
  554. {
  555. std::string text(str);
  556. currentFont->print(text, x, y, 0.0, angle, sx, sy, ox, oy, kx, ky);
  557. }
  558. }
  559. void Graphics::printf(const char *str, float x, float y, float wrap, AlignMode align)
  560. {
  561. if (currentFont == 0)
  562. return;
  563. using namespace std;
  564. string text(str);
  565. vector<string> lines_to_draw = currentFont->getWrap(text, wrap);
  566. // now for the actual printing
  567. vector<string>::const_iterator line_iter, line_end = lines_to_draw.end();
  568. float letter_spacing = 0.0f;
  569. for (line_iter = lines_to_draw.begin(); line_iter != line_end; ++line_iter)
  570. {
  571. float width = static_cast<float>(currentFont->getWidth(*line_iter));
  572. switch (align)
  573. {
  574. case ALIGN_RIGHT:
  575. currentFont->print(*line_iter, ceil(x + wrap - width), ceil(y));
  576. break;
  577. case ALIGN_CENTER:
  578. currentFont->print(*line_iter, ceil(x + (wrap - width) / 2), ceil(y));
  579. break;
  580. case ALIGN_JUSTIFY:
  581. if (line_iter->length() > 1 && (line_iter+1) != line_end)
  582. letter_spacing = (wrap - width) / float(line_iter->length() - 1);
  583. else
  584. letter_spacing = 0.0f;
  585. currentFont->print(*line_iter, ceil(x), ceil(y), letter_spacing);
  586. break;
  587. case ALIGN_LEFT:
  588. default:
  589. currentFont->print(*line_iter, ceil(x), ceil(y));
  590. break;
  591. }
  592. y += currentFont->getHeight() * currentFont->getLineHeight();
  593. }
  594. }
  595. /**
  596. * Primitives
  597. **/
  598. void Graphics::point(float x, float y)
  599. {
  600. bindTexture(0);
  601. glBegin(GL_POINTS);
  602. glVertex2f(x, y);
  603. glEnd();
  604. }
  605. // Calculate line boundary points u1 and u2. Sketch:
  606. // u1
  607. // -------------+---...___
  608. // | ```'''-- ---
  609. // p- - - - - - q- - . _ _ | w/2
  610. // | ` ' ' r +
  611. // -------------+---...___ | w/2
  612. // u2 ```'''-- ---
  613. //
  614. // u1 and u2 depend on four things:
  615. // - the half line width w/2
  616. // - the previous line vertex p
  617. // - the current line vertex q
  618. // - the next line vertex r
  619. //
  620. // u1/u2 are the intersection points of the parallel lines to p-q and q-r,
  621. // i.e. the point where
  622. //
  623. // (p + w/2 * n1) + mu * (q - p) = (q + w/2 * n2) + lambda * (r - q) (u1)
  624. // (p - w/2 * n1) + mu * (q - p) = (q - w/2 * n2) + lambda * (r - q) (u2)
  625. //
  626. // with n1,n2 being the normals on the segments p-q and q-r:
  627. //
  628. // n1 = perp(q - p) / |q - p|
  629. // n2 = perp(r - q) / |r - q|
  630. //
  631. // The intersection points can be calculated using cramers rule.
  632. static void pushIntersectionPoints(Vector *vertices, Vector *overdraw,
  633. int pos, int count, float hw, float overdraw_factor,
  634. const Vector &p, const Vector &q, const Vector &r)
  635. {
  636. // calculate line directions
  637. Vector s = (q - p);
  638. Vector t = (r - q);
  639. // calculate vertex displacement vectors
  640. Vector n1 = s.getNormal();
  641. Vector n2 = t.getNormal();
  642. n1.normalize();
  643. n2.normalize();
  644. float det_norm = n1 ^ n2; // will be close to zero if the angle between the normals is sharp
  645. n1 *= hw;
  646. n2 *= hw;
  647. // lines parallel -> assume intersection at displacement points
  648. if (fabs(det_norm) <= .03)
  649. {
  650. vertices[pos] = q - n2;
  651. vertices[pos+1] = q + n2;
  652. }
  653. // real intersection -> calculate boundary intersection points with cramers rule
  654. else
  655. {
  656. float det = s ^ t;
  657. Vector d = n1 - n2;
  658. Vector b = s - d; // s = q - p
  659. Vector c = s + d;
  660. float lambda = (b ^ t) / det;
  661. float mu = (c ^ t) / det;
  662. // ordering for GL_TRIANGLE_STRIP
  663. vertices[pos] = p + s*mu - n1; // u1
  664. vertices[pos+1] = p + s*lambda + n1; // u2
  665. }
  666. if (overdraw)
  667. {
  668. // displacement of the overdraw vertices
  669. Vector x = (vertices[pos] - q) * overdraw_factor;
  670. overdraw[pos] = vertices[pos];
  671. overdraw[pos+1] = vertices[pos] + x;
  672. overdraw[2*count-pos-2] = vertices[pos+1];
  673. overdraw[2*count-pos-1] = vertices[pos+1] - x;
  674. }
  675. }
  676. // precondition:
  677. // glEnableClientState(GL_VERTEX_ARRAY);
  678. static void draw_overdraw(Vector *overdraw, size_t count, float pixel_size, bool looping)
  679. {
  680. // if not looping, the outer overdraw vertices need to be displaced
  681. // to cover the line endings, i.e.:
  682. // +- - - - //- - + +- - - - - //- - - +
  683. // +-------//-----+ : +-------//-----+ :
  684. // | core // line | --> : | core // line | :
  685. // +-----//-------+ : +-----//-------+ :
  686. // +- - //- - - - + +- - - //- - - - - +
  687. if (!looping)
  688. {
  689. Vector s = overdraw[1] - overdraw[3];
  690. s.normalize();
  691. s *= pixel_size;
  692. overdraw[1] += s;
  693. overdraw[2*count-1] += s;
  694. Vector t = overdraw[count-1] - overdraw[count-3];
  695. t.normalize();
  696. t *= pixel_size;
  697. overdraw[count-1] += t;
  698. overdraw[count+1] += t;
  699. // we need to draw two more triangles to close the
  700. // overdraw at the line start.
  701. overdraw[2*count] = overdraw[0];
  702. overdraw[2*count+1] = overdraw[1];
  703. }
  704. // prepare colors:
  705. // even indices in overdraw* point to inner vertices => alpha = current-alpha,
  706. // odd indices point to outer vertices => alpha = 0.
  707. GLfloat c[4];
  708. glGetFloatv(GL_CURRENT_COLOR, c);
  709. Color *colors = new Color[2*count+2];
  710. for (size_t i = 0; i < 2*count+2; ++i)
  711. {
  712. colors[i] = Color(GLubyte(c[0] * 255.f),
  713. GLubyte(c[1] * 255.f),
  714. GLubyte(c[2] * 255.f),
  715. // avoids branching. equiv to if (i%2 == 1) colors[i].a = 0;
  716. GLubyte(c[3] * 255.f) * GLubyte(i%2 == 0));
  717. }
  718. // draw faded out line halos
  719. glEnableClientState(GL_COLOR_ARRAY);
  720. glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
  721. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)overdraw);
  722. glDrawArrays(GL_TRIANGLE_STRIP, 0, 2*count + 2 * int(!looping));
  723. glDisableClientState(GL_COLOR_ARRAY);
  724. // "if GL_COLOR_ARRAY is enabled, the value of the current color is
  725. // undefined after glDrawArrays executes"
  726. glColor4fv(c);
  727. delete[] colors;
  728. }
  729. void Graphics::polyline(const float *coords, size_t count)
  730. {
  731. Vector *vertices = new Vector[count]; // two vertices for every line end-point
  732. Vector *overdraw = NULL;
  733. Vector p,q,r;
  734. bool looping = (coords[0] == coords[count-2]) && (coords[1] == coords[count-1]);
  735. float halfwidth = lineWidth/2.f;
  736. float pixel_size = 1.f;
  737. float overdraw_factor = .0f;
  738. if (lineStyle == LINE_SMOOTH)
  739. {
  740. overdraw = new Vector[2*count+2];
  741. // TODO: is there a better way to get the pixel size at the current scale?
  742. GLfloat m[16];
  743. glGetFloatv(GL_MODELVIEW_MATRIX, m);
  744. float det = m[0]*m[5]*m[10] + m[4]*m[9]*m[2] + m[8]*m[1]*m[6];
  745. det -= m[2]*m[5]*m[8] + m[6]*m[9]*m[0] + m[10]*m[1]*m[4];
  746. pixel_size = 1.f / sqrt(det);
  747. overdraw_factor = pixel_size / halfwidth;
  748. halfwidth = std::max(.0f, halfwidth - .25f*pixel_size);
  749. }
  750. // get line vertex boundaries
  751. // if not looping, extend the line at the beginning, else use last point as `p'
  752. r = Vector(coords[0], coords[1]);
  753. if (!looping)
  754. q = r * 2 - Vector(coords[2], coords[3]);
  755. else
  756. q = Vector(coords[count-4], coords[count-3]);
  757. for (size_t i = 0; i+3 < count; i += 2)
  758. {
  759. p = q;
  760. q = r;
  761. r = Vector(coords[i+2], coords[i+3]);
  762. pushIntersectionPoints(vertices, overdraw, i, count, halfwidth, overdraw_factor, p,q,r);
  763. }
  764. // if not looping, extend the line at the end, else use first point as `r'
  765. p = q;
  766. q = r;
  767. if (!looping)
  768. r += q - p;
  769. else
  770. r = Vector(coords[2], coords[3]);
  771. pushIntersectionPoints(vertices, overdraw, count-2, count, halfwidth, overdraw_factor, p,q,r);
  772. // end get line vertex boundaries
  773. // draw the core line
  774. bindTexture(0);
  775. glEnableClientState(GL_VERTEX_ARRAY);
  776. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)vertices);
  777. glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
  778. // draw the line halo (antialiasing)
  779. if (lineStyle == LINE_SMOOTH)
  780. draw_overdraw(overdraw, count, pixel_size, looping);
  781. glDisableClientState(GL_VERTEX_ARRAY);
  782. // cleanup
  783. delete[] vertices;
  784. if (lineStyle == LINE_SMOOTH)
  785. delete[] overdraw;
  786. }
  787. void Graphics::triangle(DrawMode mode, float x1, float y1, float x2, float y2, float x3, float y3)
  788. {
  789. float coords[] = { x1,y1, x2,y2, x3,y3, x1,y1 };
  790. polygon(mode, coords, 4 * 2);
  791. }
  792. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  793. {
  794. quad(mode, x,y, x,y+h, x+w,y+h, x+w,y);
  795. }
  796. void Graphics::quad(DrawMode mode, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4)
  797. {
  798. float coords[] = { x1,y1, x2,y2, x3,y3, x4,y4, x1,y1 };
  799. polygon(mode, coords, 5 * 2);
  800. }
  801. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  802. {
  803. float two_pi = static_cast<float>(LOVE_M_PI * 2);
  804. if (points <= 0) points = 1;
  805. float angle_shift = (two_pi / points);
  806. float phi = .0f;
  807. float *coords = new float[2 * (points + 1)];
  808. for (int i = 0; i < points; ++i, phi += angle_shift)
  809. {
  810. coords[2*i] = x + radius * cos(phi);
  811. coords[2*i+1] = y + radius * sin(phi);
  812. }
  813. coords[2*points] = coords[0];
  814. coords[2*points+1] = coords[1];
  815. polygon(mode, coords, (points + 1) * 2);
  816. delete[] coords;
  817. }
  818. void Graphics::arc(DrawMode mode, float x, float y, float radius, float angle1, float angle2, int points)
  819. {
  820. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  821. if (points <= 0 || angle1 == angle2)
  822. return;
  823. // Oh, you want to draw a circle?
  824. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  825. {
  826. circle(mode, x, y, radius, points);
  827. return;
  828. }
  829. float angle_shift = (angle2 - angle1) / points;
  830. // Bail on precision issues.
  831. if (angle_shift == 0.0)
  832. return;
  833. float phi = angle1;
  834. int num_coords = (points + 3) * 2;
  835. float *coords = new float[num_coords];
  836. coords[0] = coords[num_coords - 2] = x;
  837. coords[1] = coords[num_coords - 1] = y;
  838. for (int i = 0; i <= points; ++i, phi += angle_shift)
  839. {
  840. coords[2 * (i+1)] = x + radius * cos(phi);
  841. coords[2 * (i+1) + 1] = y + radius * sin(phi);
  842. }
  843. // GL_POLYGON can only fill-draw convex polygons, so we need to do stuff manually here
  844. if (mode == DRAW_LINE)
  845. {
  846. polyline(coords, num_coords); // Artifacts at sharp angles if set to looping.
  847. }
  848. else
  849. {
  850. bindTexture(0);
  851. glEnableClientState(GL_VERTEX_ARRAY);
  852. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *) coords);
  853. glDrawArrays(GL_TRIANGLE_FAN, 0, points + 2);
  854. glDisableClientState(GL_VERTEX_ARRAY);
  855. }
  856. delete[] coords;
  857. }
  858. /// @param mode the draw mode
  859. /// @param coords the coordinate array
  860. /// @param count the number of coordinates/size of the array
  861. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  862. {
  863. // coords is an array of a closed loop of vertices, i.e.
  864. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  865. if (mode == DRAW_LINE)
  866. {
  867. polyline(coords, count);
  868. }
  869. else
  870. {
  871. bindTexture(0);
  872. glEnableClientState(GL_VERTEX_ARRAY);
  873. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)coords);
  874. glDrawArrays(GL_POLYGON, 0, count/2-1); // opengl will close the polygon for us
  875. glDisableClientState(GL_VERTEX_ARRAY);
  876. }
  877. }
  878. love::image::ImageData *Graphics::newScreenshot(love::image::Image *image)
  879. {
  880. int w = getWidth();
  881. int h = getHeight();
  882. int row = 4*w;
  883. int size = row*h;
  884. GLubyte *pixels = new GLubyte[size];
  885. GLubyte *screenshot = new GLubyte[size];
  886. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  887. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  888. GLubyte *src = pixels - row, *dst = screenshot + size;
  889. for (int i = 0; i < h; ++i)
  890. {
  891. memcpy(dst-=row, src+=row, row);
  892. }
  893. love::image::ImageData *img = image->newImageData(w, h, (void *)screenshot);
  894. delete [] pixels;
  895. delete [] screenshot;
  896. return img;
  897. }
  898. void Graphics::push()
  899. {
  900. if (userMatrices == matrixLimit)
  901. throw Exception("Maximum stack depth reached. (More pushes than pops?)");
  902. glPushMatrix();
  903. ++userMatrices;
  904. }
  905. void Graphics::pop()
  906. {
  907. if (userMatrices < 1)
  908. throw Exception("Minimum stack depth reached. (More pops than pushes?)");
  909. glPopMatrix();
  910. --userMatrices;
  911. }
  912. void Graphics::rotate(float r)
  913. {
  914. glRotatef(LOVE_TODEG(r), 0, 0, 1);
  915. }
  916. void Graphics::scale(float x, float y)
  917. {
  918. glScalef(x, y, 1);
  919. }
  920. void Graphics::translate(float x, float y)
  921. {
  922. glTranslatef(x, y, 0);
  923. }
  924. void Graphics::shear(float kx, float ky)
  925. {
  926. Matrix t;
  927. t.setShear(kx, ky);
  928. glMultMatrixf((const GLfloat *)t.getElements());
  929. }
  930. bool Graphics::hasFocus() const
  931. {
  932. return currentWindow->hasFocus();
  933. }
  934. } // opengl
  935. } // graphics
  936. } // love