Graphics.cpp 28 KB

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