Graphics.cpp 28 KB

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