Graphics.cpp 28 KB

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