Graphics.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  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 &e)
  276. {
  277. image->release();
  278. throw love::Exception(e.what());
  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)
  326. {
  327. Canvas *canvas = new Canvas(width, height);
  328. GLenum err = canvas->getStatus();
  329. // everything ok, return canvas (early out)
  330. if (err == GL_FRAMEBUFFER_COMPLETE)
  331. return canvas;
  332. // create error message
  333. std::stringstream error_string;
  334. error_string << "Cannot create canvas: ";
  335. switch (err)
  336. {
  337. case GL_FRAMEBUFFER_UNSUPPORTED:
  338. error_string << "Not supported by your OpenGL implementation.";
  339. break;
  340. // remaining error codes are highly unlikely:
  341. case GL_FRAMEBUFFER_UNDEFINED:
  342. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  343. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  344. case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
  345. case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
  346. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  347. error_string << "Error in implementation. Possible fix: Make canvas width and height powers of two.";
  348. break;
  349. default:
  350. // my intel hda card wrongly returns 0 to glCheckFramebufferStatus() but sets
  351. // no error flag. I think it meant to return GL_FRAMEBUFFER_UNSUPPORTED, but who
  352. // knows.
  353. if (glGetError() == GL_NO_ERROR)
  354. error_string << "May not be supported by your OpenGL implementation.";
  355. // the remaining error is an indication of a serious fuckup since it should
  356. // only be returned if glCheckFramebufferStatus() was called with the wrong
  357. // arguments.
  358. else
  359. error_string << "Cannot create canvas: Aliens did it (OpenGL error code: " << glGetError() << ")";
  360. }
  361. canvas->release();
  362. throw Exception(error_string.str().c_str());
  363. return NULL; // never reached
  364. }
  365. PixelEffect *Graphics::newPixelEffect(const std::string &code)
  366. {
  367. PixelEffect *effect = NULL;
  368. try
  369. {
  370. effect = new PixelEffect(code);
  371. }
  372. catch(love::Exception &e)
  373. {
  374. if (effect)
  375. delete effect;
  376. throw(e);
  377. }
  378. return effect;
  379. }
  380. void Graphics::setColor(const Color &c)
  381. {
  382. glColor4ubv(&c.r);
  383. }
  384. Color Graphics::getColor()
  385. {
  386. float c[4];
  387. glGetFloatv(GL_CURRENT_COLOR, c);
  388. Color t;
  389. t.r = (unsigned char)(255.0f*c[0]);
  390. t.g = (unsigned char)(255.0f*c[1]);
  391. t.b = (unsigned char)(255.0f*c[2]);
  392. t.a = (unsigned char)(255.0f*c[3]);
  393. return t;
  394. }
  395. void Graphics::setBackgroundColor(const Color &c)
  396. {
  397. glClearColor((float)c.r/255.0f, (float)c.g/255.0f, (float)c.b/255.0f, (float)c.a/255.0f);
  398. }
  399. Color Graphics::getBackgroundColor()
  400. {
  401. float c[4];
  402. glGetFloatv(GL_COLOR_CLEAR_VALUE, c);
  403. Color t;
  404. t.r = (unsigned char)(255.0f*c[0]);
  405. t.g = (unsigned char)(255.0f*c[1]);
  406. t.b = (unsigned char)(255.0f*c[2]);
  407. t.a = (unsigned char)(255.0f*c[3]);
  408. return t;
  409. }
  410. void Graphics::setFont(Font *font)
  411. {
  412. if (currentFont != 0)
  413. currentFont->release();
  414. currentFont = font;
  415. if (font != 0)
  416. currentFont->retain();
  417. }
  418. Font *Graphics::getFont()
  419. {
  420. return currentFont;
  421. }
  422. void Graphics::setBlendMode(Graphics::BlendMode mode)
  423. {
  424. if (GLEE_VERSION_1_4 || GLEE_ARB_imaging)
  425. {
  426. if (mode == BLEND_SUBTRACTIVE)
  427. glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
  428. else
  429. glBlendEquation(GL_FUNC_ADD);
  430. }
  431. else if (GLEE_EXT_blend_minmax && GLEE_EXT_blend_subtract)
  432. {
  433. if (mode == BLEND_SUBTRACTIVE)
  434. glBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
  435. else
  436. glBlendEquationEXT(GL_FUNC_ADD_EXT);
  437. }
  438. else
  439. {
  440. if (mode == BLEND_SUBTRACTIVE)
  441. throw Exception("This graphics card does not support the subtract blend mode!");
  442. // GL_FUNC_ADD is the default even without access to glBlendEquation, so that'll still work.
  443. }
  444. if (mode == BLEND_ALPHA)
  445. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  446. else if (mode == BLEND_MULTIPLICATIVE)
  447. glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA);
  448. else if (mode == BLEND_PREMULTIPLIED)
  449. glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  450. else // mode == BLEND_ADDITIVE || mode == BLEND_SUBTRACTIVE
  451. glBlendFunc(GL_SRC_ALPHA, GL_ONE);
  452. }
  453. void Graphics::setColorMode(Graphics::ColorMode mode)
  454. {
  455. if (mode == COLOR_MODULATE)
  456. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  457. else if (mode == COLOR_COMBINE)
  458. {
  459. glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_ADD_SIGNED);
  460. glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
  461. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
  462. }
  463. else // mode = COLOR_REPLACE
  464. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  465. }
  466. void Graphics::setDefaultImageFilter(const Image::Filter &f)
  467. {
  468. Image::setDefaultFilter(f);
  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_ONE_MINUS_SRC_ALPHA) // && 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. const Image::Filter &Graphics::getDefaultImageFilter() const
  500. {
  501. return Image::getDefaultFilter();
  502. }
  503. void Graphics::setLineWidth(float width)
  504. {
  505. lineWidth = width;
  506. }
  507. void Graphics::setLineStyle(Graphics::LineStyle style)
  508. {
  509. lineStyle = style;
  510. }
  511. void Graphics::setLine(float width, Graphics::LineStyle style)
  512. {
  513. setLineWidth(width);
  514. if (style == 0)
  515. return;
  516. setLineStyle(style);
  517. }
  518. float Graphics::getLineWidth()
  519. {
  520. return lineWidth;
  521. }
  522. Graphics::LineStyle Graphics::getLineStyle()
  523. {
  524. return lineStyle;
  525. }
  526. void Graphics::setPointSize(float size)
  527. {
  528. glPointSize((GLfloat)size);
  529. }
  530. void Graphics::setPointStyle(Graphics::PointStyle style)
  531. {
  532. if (style == POINT_SMOOTH)
  533. glEnable(GL_POINT_SMOOTH);
  534. else // love::POINT_ROUGH
  535. glDisable(GL_POINT_SMOOTH);
  536. }
  537. void Graphics::setPoint(float size, Graphics::PointStyle style)
  538. {
  539. if (style == POINT_SMOOTH)
  540. glEnable(GL_POINT_SMOOTH);
  541. else // POINT_ROUGH
  542. glDisable(GL_POINT_SMOOTH);
  543. glPointSize((GLfloat)size);
  544. }
  545. float Graphics::getPointSize()
  546. {
  547. GLfloat size;
  548. glGetFloatv(GL_POINT_SIZE, &size);
  549. return (float)size;
  550. }
  551. Graphics::PointStyle Graphics::getPointStyle()
  552. {
  553. if (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE)
  554. return POINT_SMOOTH;
  555. else
  556. return POINT_ROUGH;
  557. }
  558. int Graphics::getMaxPointSize()
  559. {
  560. GLint max;
  561. glGetIntegerv(GL_POINT_SIZE_MAX, &max);
  562. return (int)max;
  563. }
  564. void Graphics::print(const char *str, float x, float y , float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  565. {
  566. if (currentFont != 0)
  567. {
  568. std::string text(str);
  569. currentFont->print(text, x, y, 0.0, angle, sx, sy, ox, oy, kx, ky);
  570. }
  571. }
  572. void Graphics::printf(const char *str, float x, float y, float wrap, AlignMode align)
  573. {
  574. if (currentFont == 0)
  575. return;
  576. using namespace std;
  577. string text(str);
  578. vector<string> lines_to_draw = currentFont->getWrap(text, wrap);
  579. // now for the actual printing
  580. vector<string>::const_iterator line_iter, line_end = lines_to_draw.end();
  581. float letter_spacing = 0.0f;
  582. for (line_iter = lines_to_draw.begin(); line_iter != line_end; ++line_iter)
  583. {
  584. float width = static_cast<float>(currentFont->getWidth(*line_iter));
  585. switch (align)
  586. {
  587. case ALIGN_RIGHT:
  588. currentFont->print(*line_iter, ceil(x + wrap - width), ceil(y));
  589. break;
  590. case ALIGN_CENTER:
  591. currentFont->print(*line_iter, ceil(x + (wrap - width) / 2), ceil(y));
  592. break;
  593. case ALIGN_JUSTIFY:
  594. if (line_iter->length() > 1 && (line_iter+1) != line_end)
  595. letter_spacing = (wrap - width) / float(line_iter->length() - 1);
  596. else
  597. letter_spacing = 0.0f;
  598. currentFont->print(*line_iter, ceil(x), ceil(y), letter_spacing);
  599. break;
  600. case ALIGN_LEFT:
  601. default:
  602. currentFont->print(*line_iter, ceil(x), ceil(y));
  603. break;
  604. }
  605. y += currentFont->getHeight() * currentFont->getLineHeight();
  606. }
  607. }
  608. /**
  609. * Primitives
  610. **/
  611. void Graphics::point(float x, float y)
  612. {
  613. glDisable(GL_TEXTURE_2D);
  614. glBegin(GL_POINTS);
  615. glVertex2f(x, y);
  616. glEnd();
  617. glEnable(GL_TEXTURE_2D);
  618. }
  619. // Calculate line boundary points u1 and u2. Sketch:
  620. // u1
  621. // -------------+---...___
  622. // | ```'''-- ---
  623. // p- - - - - - q- - . _ _ | w/2
  624. // | ` ' ' r +
  625. // -------------+---...___ | w/2
  626. // u2 ```'''-- ---
  627. //
  628. // u1 and u2 depend on four things:
  629. // - the half line width w/2
  630. // - the previous line vertex p
  631. // - the current line vertex q
  632. // - the next line vertex r
  633. //
  634. // u1/u2 are the intersection points of the parallel lines to p-q and q-r,
  635. // i.e. the point where
  636. //
  637. // (p + w/2 * n1) + mu * (q - p) = (q + w/2 * n2) + lambda * (r - q) (u1)
  638. // (p - w/2 * n1) + mu * (q - p) = (q - w/2 * n2) + lambda * (r - q) (u2)
  639. //
  640. // with n1,n2 being the normals on the segments p-q and q-r:
  641. //
  642. // n1 = perp(q - p) / |q - p|
  643. // n2 = perp(r - q) / |r - q|
  644. //
  645. // The intersection points can be calculated using cramers rule.
  646. static void pushIntersectionPoints(Vector *vertices, Vector *overdraw,
  647. int pos, int count, float hw, float overdraw_factor,
  648. const Vector &p, const Vector &q, const Vector &r)
  649. {
  650. // calculate line directions
  651. Vector s = (q - p);
  652. Vector t = (r - q);
  653. // calculate vertex displacement vectors
  654. Vector n1 = s.getNormal();
  655. Vector n2 = t.getNormal();
  656. n1.normalize();
  657. n2.normalize();
  658. float det_norm = n1 ^ n2; // will be close to zero if the angle between the normals is sharp
  659. n1 *= hw;
  660. n2 *= hw;
  661. // lines parallel -> assume intersection at displacement points
  662. if (fabs(det_norm) <= .03)
  663. {
  664. vertices[pos] = q - n2;
  665. vertices[pos+1] = q + n2;
  666. }
  667. // real intersection -> calculate boundary intersection points with cramers rule
  668. else
  669. {
  670. float det = s ^ t;
  671. Vector d = n1 - n2;
  672. Vector b = s - d; // s = q - p
  673. Vector c = s + d;
  674. float lambda = (b ^ t) / det;
  675. float mu = (c ^ t) / det;
  676. // ordering for GL_TRIANGLE_STRIP
  677. vertices[pos] = p + s*mu - n1; // u1
  678. vertices[pos+1] = p + s*lambda + n1; // u2
  679. }
  680. if (overdraw)
  681. {
  682. // displacement of the overdraw vertices
  683. Vector x = (vertices[pos] - q) * overdraw_factor;
  684. overdraw[pos] = vertices[pos];
  685. overdraw[pos+1] = vertices[pos] + x;
  686. overdraw[2*count-pos-2] = vertices[pos+1];
  687. overdraw[2*count-pos-1] = vertices[pos+1] - x;
  688. }
  689. }
  690. // precondition:
  691. // glEnableClientState(GL_VERTEX_ARRAY);
  692. static void draw_overdraw(Vector *overdraw, size_t count, float pixel_size, bool looping)
  693. {
  694. // if not looping, the outer overdraw vertices need to be displaced
  695. // to cover the line endings, i.e.:
  696. // +- - - - //- - + +- - - - - //- - - +
  697. // +-------//-----+ : +-------//-----+ :
  698. // | core // line | --> : | core // line | :
  699. // +-----//-------+ : +-----//-------+ :
  700. // +- - //- - - - + +- - - //- - - - - +
  701. if (!looping)
  702. {
  703. Vector s = overdraw[1] - overdraw[3];
  704. s.normalize();
  705. s *= pixel_size;
  706. overdraw[1] += s;
  707. overdraw[2*count-1] += s;
  708. Vector t = overdraw[count-1] - overdraw[count-3];
  709. t.normalize();
  710. t *= pixel_size;
  711. overdraw[count-1] += t;
  712. overdraw[count+1] += t;
  713. // we need to draw two more triangles to close the
  714. // overdraw at the line start.
  715. overdraw[2*count] = overdraw[0];
  716. overdraw[2*count+1] = overdraw[1];
  717. }
  718. // prepare colors:
  719. // even indices in overdraw* point to inner vertices => alpha = current-alpha,
  720. // odd indices point to outer vertices => alpha = 0.
  721. GLfloat c[4];
  722. glGetFloatv(GL_CURRENT_COLOR, c);
  723. Color *colors = new Color[2*count+2];
  724. for (size_t i = 0; i < 2*count+2; ++i)
  725. {
  726. colors[i] = Color(GLubyte(c[0] * 255.f),
  727. GLubyte(c[1] * 255.f),
  728. GLubyte(c[2] * 255.f),
  729. // avoids branching. equiv to if (i%2 == 1) colors[i].a = 0;
  730. GLubyte(c[3] * 255.f) * GLubyte(i%2 == 0));
  731. }
  732. // draw faded out line halos
  733. glEnableClientState(GL_COLOR_ARRAY);
  734. glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
  735. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)overdraw);
  736. glDrawArrays(GL_TRIANGLE_STRIP, 0, 2*count + 2 * int(!looping));
  737. glDisableClientState(GL_COLOR_ARRAY);
  738. // "if GL_COLOR_ARRAY is enabled, the value of the current color is
  739. // undefined after glDrawArrays executes"
  740. glColor4fv(c);
  741. delete[] colors;
  742. }
  743. void Graphics::polyline(const float *coords, size_t count)
  744. {
  745. Vector *vertices = new Vector[count]; // two vertices for every line end-point
  746. Vector *overdraw = NULL;
  747. Vector p,q,r;
  748. bool looping = (coords[0] == coords[count-2]) && (coords[1] == coords[count-1]);
  749. float halfwidth = lineWidth/2.f;
  750. float pixel_size = 1.f;
  751. float overdraw_factor = .0f;
  752. if (lineStyle == LINE_SMOOTH)
  753. {
  754. overdraw = new Vector[2*count+2];
  755. // TODO: is there a better way to get the pixel size at the current scale?
  756. GLfloat m[16];
  757. glGetFloatv(GL_MODELVIEW_MATRIX, m);
  758. float det = m[0]*m[5]*m[10] + m[4]*m[9]*m[2] + m[8]*m[1]*m[6];
  759. det -= m[2]*m[5]*m[8] + m[6]*m[9]*m[0] + m[10]*m[1]*m[4];
  760. pixel_size = 1.f / sqrt(det);
  761. overdraw_factor = pixel_size / halfwidth;
  762. halfwidth = std::max(.0f, halfwidth - .25f*pixel_size);
  763. }
  764. // get line vertex boundaries
  765. // if not looping, extend the line at the beginning, else use last point as `p'
  766. r = Vector(coords[0], coords[1]);
  767. if (!looping)
  768. q = r * 2 - Vector(coords[2], coords[3]);
  769. else
  770. q = Vector(coords[count-4], coords[count-3]);
  771. for (size_t i = 0; i+3 < count; i += 2)
  772. {
  773. p = q;
  774. q = r;
  775. r = Vector(coords[i+2], coords[i+3]);
  776. pushIntersectionPoints(vertices, overdraw, i, count, halfwidth, overdraw_factor, p,q,r);
  777. }
  778. // if not looping, extend the line at the end, else use first point as `r'
  779. p = q;
  780. q = r;
  781. if (!looping)
  782. r += q - p;
  783. else
  784. r = Vector(coords[2], coords[3]);
  785. pushIntersectionPoints(vertices, overdraw, count-2, count, halfwidth, overdraw_factor, p,q,r);
  786. // end get line vertex boundaries
  787. // draw the core line
  788. glDisable(GL_TEXTURE_2D);
  789. glEnableClientState(GL_VERTEX_ARRAY);
  790. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)vertices);
  791. glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
  792. // draw the line halo (antialiasing)
  793. if (lineStyle == LINE_SMOOTH)
  794. draw_overdraw(overdraw, count, pixel_size, looping);
  795. glDisableClientState(GL_VERTEX_ARRAY);
  796. glEnable(GL_TEXTURE_2D);
  797. // cleanup
  798. delete[] vertices;
  799. if (lineStyle == LINE_SMOOTH)
  800. delete[] overdraw;
  801. }
  802. void Graphics::triangle(DrawMode mode, float x1, float y1, float x2, float y2, float x3, float y3)
  803. {
  804. float coords[] = { x1,y1, x2,y2, x3,y3, x1,y1 };
  805. polygon(mode, coords, 4 * 2);
  806. }
  807. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  808. {
  809. quad(mode, x,y, x,y+h, x+w,y+h, x+w,y);
  810. }
  811. void Graphics::quad(DrawMode mode, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4)
  812. {
  813. float coords[] = { x1,y1, x2,y2, x3,y3, x4,y4, x1,y1 };
  814. polygon(mode, coords, 5 * 2);
  815. }
  816. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  817. {
  818. float two_pi = static_cast<float>(LOVE_M_PI * 2);
  819. if (points <= 0) points = 1;
  820. float angle_shift = (two_pi / points);
  821. float phi = .0f;
  822. float *coords = new float[2 * (points + 1)];
  823. for (int i = 0; i < points; ++i, phi += angle_shift)
  824. {
  825. coords[2*i] = x + radius * cos(phi);
  826. coords[2*i+1] = y + radius * sin(phi);
  827. }
  828. coords[2*points] = coords[0];
  829. coords[2*points+1] = coords[1];
  830. polygon(mode, coords, (points + 1) * 2);
  831. delete[] coords;
  832. }
  833. void Graphics::arc(DrawMode mode, float x, float y, float radius, float angle1, float angle2, int points)
  834. {
  835. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  836. if (points <= 0 || angle1 == angle2)
  837. return;
  838. // Oh, you want to draw a circle?
  839. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  840. {
  841. circle(mode, x, y, radius, points);
  842. return;
  843. }
  844. float angle_shift = (angle2 - angle1) / points;
  845. // Bail on precision issues.
  846. if (angle_shift == 0.0)
  847. return;
  848. float phi = angle1;
  849. int num_coords = (points + 3) * 2;
  850. float *coords = new float[num_coords];
  851. coords[0] = coords[num_coords - 2] = x;
  852. coords[1] = coords[num_coords - 1] = y;
  853. for (int i = 0; i <= points; ++i, phi += angle_shift)
  854. {
  855. coords[2 * (i+1)] = x + radius * cos(phi);
  856. coords[2 * (i+1) + 1] = y + radius * sin(phi);
  857. }
  858. // GL_POLYGON can only fill-draw convex polygons, so we need to do stuff manually here
  859. if (mode == DRAW_LINE)
  860. {
  861. polyline(coords, num_coords); // Artifacts at sharp angles if set to looping.
  862. }
  863. else
  864. {
  865. glDisable(GL_TEXTURE_2D);
  866. glEnableClientState(GL_VERTEX_ARRAY);
  867. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *) coords);
  868. glDrawArrays(GL_TRIANGLE_FAN, 0, points + 2);
  869. glDisableClientState(GL_VERTEX_ARRAY);
  870. glEnable(GL_TEXTURE_2D);
  871. }
  872. delete[] coords;
  873. }
  874. /// @param mode the draw mode
  875. /// @param coords the coordinate array
  876. /// @param count the number of coordinates/size of the array
  877. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  878. {
  879. // coords is an array of a closed loop of vertices, i.e.
  880. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  881. if (mode == DRAW_LINE)
  882. {
  883. polyline(coords, count);
  884. }
  885. else
  886. {
  887. glDisable(GL_TEXTURE_2D);
  888. glEnableClientState(GL_VERTEX_ARRAY);
  889. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)coords);
  890. glDrawArrays(GL_POLYGON, 0, count/2-1); // opengl will close the polygon for us
  891. glDisableClientState(GL_VERTEX_ARRAY);
  892. glEnable(GL_TEXTURE_2D);
  893. }
  894. }
  895. love::image::ImageData *Graphics::newScreenshot(love::image::Image *image)
  896. {
  897. int w = getWidth();
  898. int h = getHeight();
  899. int row = 4*w;
  900. int size = row*h;
  901. GLubyte *pixels = new GLubyte[size];
  902. GLubyte *screenshot = new GLubyte[size];
  903. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  904. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  905. GLubyte *src = pixels - row, *dst = screenshot + size;
  906. for (int i = 0; i < h; ++i)
  907. {
  908. memcpy(dst-=row, src+=row, row);
  909. }
  910. love::image::ImageData *img = image->newImageData(w, h, (void *)screenshot);
  911. delete [] pixels;
  912. delete [] screenshot;
  913. return img;
  914. }
  915. void Graphics::push()
  916. {
  917. if (userMatrices == matrixLimit)
  918. throw Exception("Maximum stack depth reached.");
  919. glPushMatrix();
  920. ++userMatrices;
  921. }
  922. void Graphics::pop()
  923. {
  924. if (userMatrices < 1)
  925. throw Exception("Minimum stack depth reached. (More pops than pushes?)");
  926. glPopMatrix();
  927. --userMatrices;
  928. }
  929. void Graphics::rotate(float r)
  930. {
  931. glRotatef(LOVE_TODEG(r), 0, 0, 1);
  932. }
  933. void Graphics::scale(float x, float y)
  934. {
  935. glScalef(x, y, 1);
  936. }
  937. void Graphics::translate(float x, float y)
  938. {
  939. glTranslatef(x, y, 0);
  940. }
  941. void Graphics::shear(float kx, float ky)
  942. {
  943. Matrix t;
  944. t.setShear(kx, ky);
  945. glMultMatrixf((const GLfloat *)t.getElements());
  946. }
  947. void Graphics::drawTest(Image *image, float x, float y, float a, float sx, float sy, float ox, float oy)
  948. {
  949. image->bind();
  950. // Buffer for transforming the image.
  951. vertex buf[4];
  952. Matrix t;
  953. t.translate(x, y);
  954. t.rotate(a);
  955. t.scale(sx, sy);
  956. t.translate(ox, oy);
  957. t.transform(buf, image->getVertices(), 4);
  958. const vertex *vertices = image->getVertices();
  959. glEnableClientState(GL_VERTEX_ARRAY);
  960. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  961. glVertexPointer(2, GL_FLOAT, sizeof(vertex), (GLvoid *)&buf[0].x);
  962. glTexCoordPointer(2, GL_FLOAT, sizeof(vertex), (GLvoid *)&vertices[0].s);
  963. glDrawArrays(GL_QUADS, 0, 4);
  964. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  965. glDisableClientState(GL_VERTEX_ARRAY);
  966. }
  967. bool Graphics::hasFocus()
  968. {
  969. return currentWindow->hasFocus();
  970. }
  971. } // opengl
  972. } // graphics
  973. } // love