Graphics.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. /**
  2. * Copyright (c) 2006-2013 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "common/config.h"
  21. #include "common/math.h"
  22. #include "common/Vector.h"
  23. #include "Graphics.h"
  24. #include "window/sdl/Window.h"
  25. #include <vector>
  26. #include <sstream>
  27. #include <algorithm>
  28. #include <iterator>
  29. using love::window::WindowFlags;
  30. namespace love
  31. {
  32. namespace graphics
  33. {
  34. namespace opengl
  35. {
  36. Graphics::Graphics()
  37. : currentFont(0)
  38. , lineStyle(LINE_SMOOTH)
  39. , lineWidth(1)
  40. , matrixLimit(0)
  41. , userMatrices(0)
  42. , colorMask()
  43. , width(0)
  44. , height(0)
  45. , created(false)
  46. , savedState()
  47. {
  48. currentWindow = love::window::sdl::Window::getSingleton();
  49. if (currentWindow->isCreated())
  50. setMode(currentWindow->getWidth(), currentWindow->getHeight());
  51. }
  52. Graphics::~Graphics()
  53. {
  54. if (currentFont != 0)
  55. currentFont->release();
  56. currentWindow->release();
  57. }
  58. const char *Graphics::getName() const
  59. {
  60. return "love.graphics.opengl";
  61. }
  62. DisplayState Graphics::saveState()
  63. {
  64. DisplayState s;
  65. s.color = getColor();
  66. s.backgroundColor = getBackgroundColor();
  67. s.blendMode = getBlendMode();
  68. //get line style
  69. s.lineStyle = lineStyle;
  70. //get the point size
  71. glGetFloatv(GL_POINT_SIZE, &s.pointSize);
  72. //get point style
  73. s.pointStyle = (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE) ? Graphics::POINT_SMOOTH : Graphics::POINT_ROUGH;
  74. // get alpha test status
  75. s.alphaTest = isAlphaTestEnabled();
  76. if (s.alphaTest)
  77. {
  78. // if alpha testing is enabled, store mode and reference alpha
  79. s.alphaTestMode = getAlphaTestMode();
  80. s.alphaTestRef = getAlphaTestRef();
  81. }
  82. //get scissor status
  83. s.scissor = (glIsEnabled(GL_SCISSOR_TEST) == GL_TRUE);
  84. //do we have scissor, if so, store the box
  85. if (s.scissor)
  86. glGetIntegerv(GL_SCISSOR_BOX, s.scissorBox);
  87. for (int i = 0; i < 4; i++)
  88. s.colorMask[i] = colorMask[i];
  89. return s;
  90. }
  91. void Graphics::restoreState(const DisplayState &s)
  92. {
  93. setColor(s.color);
  94. setBackgroundColor(s.backgroundColor);
  95. setBlendMode(s.blendMode);
  96. setLine(lineWidth, s.lineStyle);
  97. setPoint(s.pointSize, s.pointStyle);
  98. if (s.alphaTest)
  99. setAlphaTest(s.alphaTestMode, s.alphaTestRef);
  100. else
  101. setAlphaTest();
  102. if (s.scissor)
  103. setScissor(s.scissorBox[0], s.scissorBox[1], s.scissorBox[2], s.scissorBox[3]);
  104. else
  105. setScissor();
  106. setColorMask(s.colorMask[0], s.colorMask[1], s.colorMask[2], s.colorMask[3]);
  107. }
  108. bool Graphics::setMode(int width, int height)
  109. {
  110. this->width = width;
  111. this->height = height;
  112. // Okay, setup OpenGL.
  113. gl.initContext();
  114. // Make sure antialiasing works when set elsewhere
  115. if (GLEE_VERSION_1_3 || GLEE_ARB_multisample)
  116. glEnable(GL_MULTISAMPLE);
  117. // Enable blending
  118. glEnable(GL_BLEND);
  119. // "Normal" blending
  120. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  121. // Enable all color component writes.
  122. setColorMask(true, true, true, true);
  123. // Enable line/point smoothing.
  124. setLineStyle(LINE_SMOOTH);
  125. glEnable(GL_POINT_SMOOTH);
  126. glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
  127. // Auto-generated mipmaps should be the best quality possible
  128. if (GLEE_VERSION_1_4 || GLEE_SGIS_generate_mipmap)
  129. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  130. // Set default alpha test mode and value
  131. glAlphaFunc(GL_GREATER, 0.0f);
  132. setAlphaTest();
  133. // Enable textures
  134. glEnable(GL_TEXTURE_2D);
  135. gl.setActiveTextureUnit(0);
  136. // Set the viewport to top-left corner
  137. glViewport(0, 0, width, height);
  138. // Reset the projection matrix
  139. glMatrixMode(GL_PROJECTION);
  140. glLoadIdentity();
  141. // Set up orthographic view (no depth)
  142. glOrtho(0.0, width, height, 0.0, -1.0, 1.0);
  143. // Reset modelview matrix
  144. glMatrixMode(GL_MODELVIEW);
  145. glLoadIdentity();
  146. // Set pixel row alignment
  147. glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
  148. // Reload all volatile objects.
  149. if (!Volatile::loadAll())
  150. std::cerr << "Could not reload all volatile objects." << std::endl;
  151. // Restore the display state.
  152. restoreState(savedState);
  153. pixel_size_stack.clear();
  154. pixel_size_stack.reserve(5);
  155. pixel_size_stack.push_back(1);
  156. // Get the maximum number of matrices
  157. // subtract a few to give the engine some room.
  158. glGetIntegerv(GL_MAX_MODELVIEW_STACK_DEPTH, &matrixLimit);
  159. matrixLimit -= 5;
  160. created = true;
  161. return true;
  162. }
  163. void Graphics::unSetMode()
  164. {
  165. // Window re-creation may destroy the GL context, so we must save the state.
  166. if (isCreated())
  167. savedState = saveState();
  168. // Unload all volatile objects. These must be reloaded after the display
  169. // mode change.
  170. Volatile::unloadAll();
  171. gl.deInitContext();
  172. }
  173. void Graphics::reset()
  174. {
  175. DisplayState s;
  176. discardStencil();
  177. Canvas::bindDefaultCanvas();
  178. Shader::detach();
  179. restoreState(s);
  180. pixel_size_stack.clear();
  181. pixel_size_stack.reserve(5);
  182. pixel_size_stack.push_back(1);
  183. }
  184. void Graphics::clear()
  185. {
  186. glClear(GL_COLOR_BUFFER_BIT);
  187. }
  188. void Graphics::present()
  189. {
  190. currentWindow->swapBuffers();
  191. }
  192. int Graphics::getWidth() const
  193. {
  194. return width;
  195. }
  196. int Graphics::getHeight() const
  197. {
  198. return height;
  199. }
  200. int Graphics::getRenderWidth() const
  201. {
  202. if (Canvas::current)
  203. return Canvas::current->getWidth();
  204. return getWidth();
  205. }
  206. int Graphics::getRenderHeight() const
  207. {
  208. if (Canvas::current)
  209. return Canvas::current->getHeight();
  210. return getHeight();
  211. }
  212. bool Graphics::isCreated() const
  213. {
  214. return created;
  215. }
  216. void Graphics::setScissor(int x, int y, int width, int height)
  217. {
  218. glEnable(GL_SCISSOR_TEST);
  219. // Compensates for the fact that our y-coordinate is reverse of OpenGL's.
  220. glScissor(x, getRenderHeight() - (y + height), width, height);
  221. }
  222. void Graphics::setScissor()
  223. {
  224. glDisable(GL_SCISSOR_TEST);
  225. }
  226. int Graphics::getScissor(lua_State *L) const
  227. {
  228. if (glIsEnabled(GL_SCISSOR_TEST) == GL_FALSE)
  229. return 0;
  230. GLint scissor[4];
  231. glGetIntegerv(GL_SCISSOR_BOX, scissor);
  232. lua_pushnumber(L, scissor[0]);
  233. lua_pushnumber(L, getRenderHeight() - (scissor[1] + scissor[3])); // Compensates for the fact that our y-coordinate is reverse of OpenGLs.
  234. lua_pushnumber(L, scissor[2]);
  235. lua_pushnumber(L, scissor[3]);
  236. return 4;
  237. }
  238. void Graphics::defineStencil()
  239. {
  240. // Make sure the active canvas has a stencil buffer.
  241. if (Canvas::current)
  242. Canvas::current->checkCreateStencil();
  243. // Disable color writes but don't save the mask values.
  244. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  245. glClear(GL_STENCIL_BUFFER_BIT);
  246. glEnable(GL_STENCIL_TEST);
  247. glStencilFunc(GL_ALWAYS, 1, 1);
  248. glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  249. }
  250. void Graphics::useStencil(bool invert)
  251. {
  252. glStencilFunc(GL_EQUAL, (GLint)(!invert), 1); // invert ? 0 : 1
  253. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  254. setColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
  255. }
  256. void Graphics::discardStencil()
  257. {
  258. setColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
  259. glDisable(GL_STENCIL_TEST);
  260. }
  261. void Graphics::setAlphaTest(Graphics::AlphaTestMode mode, unsigned char refalpha)
  262. {
  263. GLclampf ref = refalpha / 255.0f;
  264. glEnable(GL_ALPHA_TEST);
  265. switch (mode)
  266. {
  267. case ALPHATEST_LESS:
  268. glAlphaFunc(GL_LESS, ref);
  269. break;
  270. case ALPHATEST_LEQUAL:
  271. glAlphaFunc(GL_LEQUAL, ref);
  272. break;
  273. case ALPHATEST_EQUAL:
  274. glAlphaFunc(GL_EQUAL, ref);
  275. break;
  276. case ALPHATEST_NOTEQUAL:
  277. glAlphaFunc(GL_NOTEQUAL, ref);
  278. break;
  279. case ALPHATEST_GEQUAL:
  280. glAlphaFunc(GL_GEQUAL, ref);
  281. break;
  282. case ALPHATEST_GREATER:
  283. glAlphaFunc(GL_GREATER, ref);
  284. break;
  285. default:
  286. glDisable(GL_ALPHA_TEST);
  287. break;
  288. }
  289. }
  290. void Graphics::setAlphaTest()
  291. {
  292. glDisable(GL_ALPHA_TEST);
  293. }
  294. bool Graphics::isAlphaTestEnabled()
  295. {
  296. return glIsEnabled(GL_ALPHA_TEST) == GL_TRUE;
  297. }
  298. Graphics::AlphaTestMode Graphics::getAlphaTestMode()
  299. {
  300. GLint func;
  301. glGetIntegerv(GL_ALPHA_TEST_FUNC, &func);
  302. switch (func)
  303. {
  304. case GL_LESS:
  305. return ALPHATEST_LESS;
  306. case GL_LEQUAL:
  307. return ALPHATEST_LEQUAL;
  308. case GL_EQUAL:
  309. return ALPHATEST_EQUAL;
  310. case GL_NOTEQUAL:
  311. return ALPHATEST_NOTEQUAL;
  312. case GL_GEQUAL:
  313. return ALPHATEST_GEQUAL;
  314. case GL_GREATER:
  315. return ALPHATEST_GREATER;
  316. default:
  317. return ALPHATEST_MAX_ENUM;
  318. }
  319. }
  320. unsigned char Graphics::getAlphaTestRef()
  321. {
  322. GLfloat ref;
  323. glGetFloatv(GL_ALPHA_TEST_REF, &ref);
  324. return ref * 255;
  325. }
  326. Image *Graphics::newImage(love::image::ImageData *data)
  327. {
  328. // Create the image.
  329. Image *image = new Image(data);
  330. bool success;
  331. try
  332. {
  333. success = image->load();
  334. }
  335. catch(love::Exception &)
  336. {
  337. image->release();
  338. throw;
  339. }
  340. if (!success)
  341. {
  342. image->release();
  343. return 0;
  344. }
  345. return image;
  346. }
  347. Image *Graphics::newImage(love::image::CompressedData *cdata)
  348. {
  349. // Create the image.
  350. Image *image = new Image(cdata);
  351. bool success;
  352. try
  353. {
  354. success = image->load();
  355. }
  356. catch(love::Exception &)
  357. {
  358. image->release();
  359. throw;
  360. }
  361. if (!success)
  362. {
  363. image->release();
  364. return 0;
  365. }
  366. return image;
  367. }
  368. Geometry *Graphics::newGeometry(const std::vector<vertex> &vertices)
  369. {
  370. return new Geometry(vertices);
  371. }
  372. Geometry *Graphics::newQuad(float x, float y, float w, float h, float sw, float sh)
  373. {
  374. return new Geometry(x, y, w, h, sw, sh);
  375. }
  376. Font *Graphics::newFont(love::font::Rasterizer *r, const Image::Filter &filter)
  377. {
  378. return new Font(r, filter);
  379. }
  380. SpriteBatch *Graphics::newSpriteBatch(Image *image, int size, int usage)
  381. {
  382. return new SpriteBatch(image, size, usage);
  383. }
  384. ParticleSystem *Graphics::newParticleSystem(Image *image, int size)
  385. {
  386. return new ParticleSystem(image, size);
  387. }
  388. Canvas *Graphics::newCanvas(int width, int height, Canvas::TextureType texture_type)
  389. {
  390. if (texture_type == Canvas::TYPE_HDR && !Canvas::isHDRSupported())
  391. throw Exception("HDR Canvases are not supported by your OpenGL implementation");
  392. while (GL_NO_ERROR != glGetError())
  393. /* clear opengl error flag */;
  394. Canvas *canvas = new Canvas(width, height, texture_type);
  395. GLenum err = canvas->getStatus();
  396. // everything ok, return canvas (early out)
  397. if (err == GL_FRAMEBUFFER_COMPLETE)
  398. return canvas;
  399. // create error message
  400. std::stringstream error_string;
  401. error_string << "Cannot create canvas: ";
  402. switch (err)
  403. {
  404. case GL_FRAMEBUFFER_UNSUPPORTED:
  405. error_string << "Not supported by your OpenGL implementation.";
  406. break;
  407. // remaining error codes are highly unlikely:
  408. case GL_FRAMEBUFFER_UNDEFINED:
  409. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  410. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  411. case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
  412. case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
  413. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  414. error_string << "Error in implementation. Possible fix: Make canvas width and height powers of two.";
  415. break;
  416. default:
  417. // my intel hda card wrongly returns 0 to glCheckFramebufferStatus() but sets
  418. // no error flag. I think it meant to return GL_FRAMEBUFFER_UNSUPPORTED, but who
  419. // knows.
  420. if (glGetError() == GL_NO_ERROR)
  421. error_string << "May not be supported by your OpenGL implementation.";
  422. // the remaining error is an indication of a serious fuckup since it should
  423. // only be returned if glCheckFramebufferStatus() was called with the wrong
  424. // arguments.
  425. else
  426. error_string << "Cannot create canvas: Aliens did it (OpenGL error code: " << glGetError() << ")";
  427. }
  428. canvas->release();
  429. throw Exception(error_string.str().c_str());
  430. return NULL; // never reached
  431. }
  432. Shader *Graphics::newShader(const Shader::ShaderSources &sources)
  433. {
  434. return new Shader(sources);
  435. }
  436. void Graphics::setColor(const Color &c)
  437. {
  438. gl.setColor(c);
  439. }
  440. Color Graphics::getColor() const
  441. {
  442. return gl.getColor();
  443. }
  444. void Graphics::setBackgroundColor(const Color &c)
  445. {
  446. glClearColor((float)c.r/255.0f, (float)c.g/255.0f, (float)c.b/255.0f, (float)c.a/255.0f);
  447. }
  448. Color Graphics::getBackgroundColor() const
  449. {
  450. float c[4];
  451. glGetFloatv(GL_COLOR_CLEAR_VALUE, c);
  452. Color t;
  453. t.r = (unsigned char)(255.0f*c[0]);
  454. t.g = (unsigned char)(255.0f*c[1]);
  455. t.b = (unsigned char)(255.0f*c[2]);
  456. t.a = (unsigned char)(255.0f*c[3]);
  457. return t;
  458. }
  459. void Graphics::setFont(Font *font)
  460. {
  461. if (currentFont != 0)
  462. currentFont->release();
  463. currentFont = font;
  464. if (font != 0)
  465. currentFont->retain();
  466. }
  467. Font *Graphics::getFont() const
  468. {
  469. return currentFont;
  470. }
  471. void Graphics::setColorMask(bool r, bool g, bool b, bool a)
  472. {
  473. colorMask[0] = r;
  474. colorMask[1] = g;
  475. colorMask[2] = b;
  476. colorMask[3] = a;
  477. glColorMask((GLboolean) r, (GLboolean) g, (GLboolean) b, (GLboolean) a);
  478. }
  479. const bool *Graphics::getColorMask() const
  480. {
  481. return colorMask;
  482. }
  483. void Graphics::setBlendMode(Graphics::BlendMode mode)
  484. {
  485. const int gl_1_4 = GLEE_VERSION_1_4;
  486. GLenum func = GL_FUNC_ADD;
  487. GLenum src_rgb = GL_ONE;
  488. GLenum src_a = GL_ONE;
  489. GLenum dst_rgb = GL_ZERO;
  490. GLenum dst_a = GL_ZERO;
  491. switch (mode)
  492. {
  493. case BLEND_ALPHA:
  494. if (gl_1_4 || GLEE_EXT_blend_func_separate)
  495. {
  496. src_rgb = GL_SRC_ALPHA;
  497. src_a = GL_ONE;
  498. dst_rgb = dst_a = GL_ONE_MINUS_SRC_ALPHA;
  499. }
  500. else
  501. {
  502. // Fallback for OpenGL implementations without support for separate blend functions.
  503. // This will most likely only be used for the Microsoft software renderer and
  504. // since it's still stuck with OpenGL 1.1, the only expected difference is a
  505. // different alpha value when reading back the default framebuffer (newScreenshot).
  506. src_rgb = src_a = GL_SRC_ALPHA;
  507. dst_rgb = dst_a = GL_ONE_MINUS_SRC_ALPHA;
  508. }
  509. break;
  510. case BLEND_MULTIPLICATIVE:
  511. src_rgb = src_a = GL_DST_COLOR;
  512. dst_rgb = dst_a = GL_ZERO;
  513. break;
  514. case BLEND_PREMULTIPLIED:
  515. src_rgb = src_a = GL_ONE;
  516. dst_rgb = dst_a = GL_ONE_MINUS_SRC_ALPHA;
  517. break;
  518. case BLEND_SUBTRACTIVE:
  519. func = GL_FUNC_REVERSE_SUBTRACT;
  520. case BLEND_ADDITIVE:
  521. src_rgb = src_a = GL_SRC_ALPHA;
  522. dst_rgb = dst_a = GL_ONE;
  523. break;
  524. case BLEND_REPLACE:
  525. default:
  526. src_rgb = src_a = GL_ONE;
  527. dst_rgb = dst_a = GL_ZERO;
  528. break;
  529. }
  530. if (gl_1_4 || GLEE_ARB_imaging)
  531. glBlendEquation(func);
  532. else if (GLEE_EXT_blend_minmax && GLEE_EXT_blend_subtract)
  533. glBlendEquationEXT(func);
  534. else
  535. {
  536. if (func == GL_FUNC_REVERSE_SUBTRACT)
  537. throw Exception("This graphics card does not support the subtractive blend mode!");
  538. // GL_FUNC_ADD is the default even without access to glBlendEquation, so that'll still work.
  539. }
  540. if (src_rgb == src_a && dst_rgb == dst_a)
  541. glBlendFunc(src_rgb, dst_rgb);
  542. else
  543. {
  544. if (gl_1_4)
  545. glBlendFuncSeparate(src_rgb, dst_rgb, src_a, dst_a);
  546. else if (GLEE_EXT_blend_func_separate)
  547. glBlendFuncSeparateEXT(src_rgb, dst_rgb, src_a, dst_a);
  548. else
  549. throw Exception("This graphics card does not support separated rgb and alpha blend functions!");
  550. }
  551. }
  552. Graphics::BlendMode Graphics::getBlendMode() const
  553. {
  554. const int gl_1_4 = GLEE_VERSION_1_4;
  555. GLint src_rgb, src_a, dst_rgb, dst_a;
  556. GLint equation = GL_FUNC_ADD;
  557. if (gl_1_4 || GLEE_EXT_blend_func_separate)
  558. {
  559. glGetIntegerv(GL_BLEND_SRC_RGB, &src_rgb);
  560. glGetIntegerv(GL_BLEND_SRC_ALPHA, &src_a);
  561. glGetIntegerv(GL_BLEND_DST_RGB, &dst_rgb);
  562. glGetIntegerv(GL_BLEND_DST_ALPHA, &dst_a);
  563. }
  564. else
  565. {
  566. glGetIntegerv(GL_BLEND_SRC, &src_rgb);
  567. glGetIntegerv(GL_BLEND_DST, &dst_rgb);
  568. src_a = src_rgb;
  569. dst_a = dst_rgb;
  570. }
  571. if (gl_1_4 || GLEE_ARB_imaging || (GLEE_EXT_blend_minmax && GLEE_EXT_blend_subtract))
  572. glGetIntegerv(GL_BLEND_EQUATION, &equation);
  573. if (equation == GL_FUNC_REVERSE_SUBTRACT) // && src == GL_SRC_ALPHA && dst == GL_ONE
  574. return BLEND_SUBTRACTIVE;
  575. // Everything else has equation == GL_FUNC_ADD.
  576. else if (src_rgb == src_a && dst_rgb == dst_a)
  577. {
  578. if (src_rgb == GL_SRC_ALPHA && dst_rgb == GL_ONE)
  579. return BLEND_ADDITIVE;
  580. else if (src_rgb == GL_SRC_ALPHA && dst_rgb == GL_ONE_MINUS_SRC_ALPHA)
  581. return BLEND_ALPHA; // alpha blend mode fallback for very old OpenGL versions.
  582. else if (src_rgb == GL_DST_COLOR && dst_rgb == GL_ZERO)
  583. return BLEND_MULTIPLICATIVE;
  584. else if (src_rgb == GL_ONE && dst_rgb == GL_ONE_MINUS_SRC_ALPHA)
  585. return BLEND_PREMULTIPLIED;
  586. else if (src_rgb == GL_ONE && dst_rgb == GL_ZERO)
  587. return BLEND_REPLACE;
  588. }
  589. else if (src_rgb == GL_SRC_ALPHA && src_a == GL_ONE &&
  590. dst_rgb == GL_ONE_MINUS_SRC_ALPHA && dst_a == GL_ONE_MINUS_SRC_ALPHA)
  591. return BLEND_ALPHA;
  592. throw Exception("Unknown blend mode");
  593. }
  594. void Graphics::setDefaultFilter(const Image::Filter &f)
  595. {
  596. Image::setDefaultFilter(f);
  597. }
  598. const Image::Filter &Graphics::getDefaultFilter() const
  599. {
  600. return Image::getDefaultFilter();
  601. }
  602. void Graphics::setDefaultMipmapFilter(Image::FilterMode filter, float sharpness)
  603. {
  604. Image::setDefaultMipmapFilter(filter);
  605. Image::setDefaultMipmapSharpness(sharpness);
  606. }
  607. void Graphics::getDefaultMipmapFilter(Image::FilterMode *filter, float *sharpness) const
  608. {
  609. *filter = Image::getDefaultMipmapFilter();
  610. *sharpness = Image::getDefaultMipmapSharpness();
  611. }
  612. void Graphics::setLineWidth(float width)
  613. {
  614. lineWidth = width;
  615. }
  616. void Graphics::setLineStyle(Graphics::LineStyle style)
  617. {
  618. lineStyle = style;
  619. }
  620. void Graphics::setLine(float width, Graphics::LineStyle style)
  621. {
  622. setLineWidth(width);
  623. if (style == 0)
  624. return;
  625. setLineStyle(style);
  626. }
  627. float Graphics::getLineWidth() const
  628. {
  629. return lineWidth;
  630. }
  631. Graphics::LineStyle Graphics::getLineStyle() const
  632. {
  633. return lineStyle;
  634. }
  635. void Graphics::setPointSize(float size)
  636. {
  637. glPointSize((GLfloat)size);
  638. }
  639. void Graphics::setPointStyle(Graphics::PointStyle style)
  640. {
  641. if (style == POINT_SMOOTH)
  642. glEnable(GL_POINT_SMOOTH);
  643. else // love::POINT_ROUGH
  644. glDisable(GL_POINT_SMOOTH);
  645. }
  646. void Graphics::setPoint(float size, Graphics::PointStyle style)
  647. {
  648. if (style == POINT_SMOOTH)
  649. glEnable(GL_POINT_SMOOTH);
  650. else // POINT_ROUGH
  651. glDisable(GL_POINT_SMOOTH);
  652. glPointSize((GLfloat)size);
  653. }
  654. float Graphics::getPointSize() const
  655. {
  656. GLfloat size;
  657. glGetFloatv(GL_POINT_SIZE, &size);
  658. return (float)size;
  659. }
  660. Graphics::PointStyle Graphics::getPointStyle() const
  661. {
  662. if (glIsEnabled(GL_POINT_SMOOTH) == GL_TRUE)
  663. return POINT_SMOOTH;
  664. else
  665. return POINT_ROUGH;
  666. }
  667. int Graphics::getMaxPointSize() const
  668. {
  669. GLint max;
  670. glGetIntegerv(GL_POINT_SIZE_MAX, &max);
  671. return (int)max;
  672. }
  673. void Graphics::print(const char *str, float x, float y , float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  674. {
  675. if (currentFont != 0)
  676. {
  677. std::string text(str);
  678. currentFont->print(text, x, y, 0.0, angle, sx, sy, ox, oy, kx, ky);
  679. }
  680. }
  681. void Graphics::printf(const char *str, float x, float y, float wrap, AlignMode align, float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  682. {
  683. if (currentFont == 0)
  684. return;
  685. using std::string;
  686. using std::vector;
  687. string text(str);
  688. vector<string> lines_to_draw = currentFont->getWrap(text, wrap);
  689. glPushMatrix();
  690. static Matrix t;
  691. t.setTransformation(ceil(x), ceil(y), angle, sx, sy, ox, oy, kx, ky);
  692. glMultMatrixf((const GLfloat *)t.getElements());
  693. x = y = 0.0f;
  694. try
  695. {
  696. // now for the actual printing
  697. vector<string>::const_iterator line_iter, line_end = lines_to_draw.end();
  698. float letter_spacing = 0.0f;
  699. for (line_iter = lines_to_draw.begin(); line_iter != line_end; ++line_iter)
  700. {
  701. float width = static_cast<float>(currentFont->getWidth(*line_iter));
  702. switch (align)
  703. {
  704. case ALIGN_RIGHT:
  705. currentFont->print(*line_iter, ceil(x + (wrap - width)), ceil(y), 0.0f);
  706. break;
  707. case ALIGN_CENTER:
  708. currentFont->print(*line_iter, ceil(x + (wrap - width) / 2), ceil(y), 0.0f);
  709. break;
  710. case ALIGN_JUSTIFY:
  711. if (line_iter->length() > 1 && (line_iter+1) != line_end)
  712. letter_spacing = (wrap - width) / float(line_iter->length() - 1);
  713. else
  714. letter_spacing = 0.0f;
  715. currentFont->print(*line_iter, ceil(x), ceil(y), letter_spacing);
  716. break;
  717. case ALIGN_LEFT:
  718. default:
  719. currentFont->print(*line_iter, ceil(x), ceil(y), 0.0f);
  720. break;
  721. }
  722. y += currentFont->getHeight() * currentFont->getLineHeight();
  723. }
  724. }
  725. catch (love::Exception &)
  726. {
  727. glPopMatrix();
  728. throw;
  729. }
  730. glPopMatrix();
  731. }
  732. /**
  733. * Primitives
  734. **/
  735. void Graphics::point(float x, float y)
  736. {
  737. gl.bindTexture(0);
  738. glBegin(GL_POINTS);
  739. glVertex2f(x, y);
  740. glEnd();
  741. }
  742. // Calculate line boundary points u1 and u2. Sketch:
  743. // u1
  744. // -------------+---...___
  745. // | ```'''-- ---
  746. // p- - - - - - q- - . _ _ | w/2
  747. // | ` ' ' r +
  748. // -------------+---...___ | w/2
  749. // u2 ```'''-- ---
  750. //
  751. // u1 and u2 depend on four things:
  752. // - the half line width w/2
  753. // - the previous line vertex p
  754. // - the current line vertex q
  755. // - the next line vertex r
  756. //
  757. // u1/u2 are the intersection points of the parallel lines to p-q and q-r,
  758. // i.e. the point where
  759. //
  760. // (p + w/2 * n1) + mu * (q - p) = (q + w/2 * n2) + lambda * (r - q) (u1)
  761. // (p - w/2 * n1) + mu * (q - p) = (q - w/2 * n2) + lambda * (r - q) (u2)
  762. //
  763. // with n1,n2 being the normals on the segments p-q and q-r:
  764. //
  765. // n1 = perp(q - p) / |q - p|
  766. // n2 = perp(r - q) / |r - q|
  767. //
  768. // The intersection points can be calculated using cramers rule.
  769. static void pushIntersectionPoints(Vector *vertices, Vector *overdraw,
  770. int pos, int count, float hw, float overdraw_factor,
  771. const Vector &p, const Vector &q, const Vector &r)
  772. {
  773. // calculate line directions
  774. Vector s = (q - p);
  775. Vector t = (r - q);
  776. // calculate vertex displacement vectors
  777. Vector n1 = s.getNormal();
  778. Vector n2 = t.getNormal();
  779. n1.normalize();
  780. n2.normalize();
  781. float det_norm = n1 ^ n2; // will be close to zero if the angle between the normals is sharp
  782. n1 *= hw;
  783. n2 *= hw;
  784. // lines parallel -> assume intersection at displacement points
  785. if (fabs(det_norm) <= .03)
  786. {
  787. vertices[pos] = q - n2;
  788. vertices[pos+1] = q + n2;
  789. }
  790. // real intersection -> calculate boundary intersection points with cramers rule
  791. else
  792. {
  793. float det = s ^ t;
  794. Vector d = n1 - n2;
  795. Vector b = s - d; // s = q - p
  796. Vector c = s + d;
  797. float lambda = (b ^ t) / det;
  798. float mu = (c ^ t) / det;
  799. // ordering for GL_TRIANGLE_STRIP
  800. vertices[pos] = p + s*mu - n1; // u1
  801. vertices[pos+1] = p + s*lambda + n1; // u2
  802. }
  803. if (overdraw)
  804. {
  805. // displacement of the overdraw vertices
  806. Vector x = (vertices[pos] - q) * overdraw_factor;
  807. overdraw[pos] = vertices[pos];
  808. overdraw[pos+1] = vertices[pos] + x;
  809. overdraw[2*count-pos-2] = vertices[pos+1];
  810. overdraw[2*count-pos-1] = vertices[pos+1] - x;
  811. }
  812. }
  813. // precondition:
  814. // glEnableClientState(GL_VERTEX_ARRAY);
  815. static void draw_overdraw(Vector *overdraw, size_t count, float pixel_size, bool looping)
  816. {
  817. // if not looping, the outer overdraw vertices need to be displaced
  818. // to cover the line endings, i.e.:
  819. // +- - - - //- - + +- - - - - //- - - +
  820. // +-------//-----+ : +-------//-----+ :
  821. // | core // line | --> : | core // line | :
  822. // +-----//-------+ : +-----//-------+ :
  823. // +- - //- - - - + +- - - //- - - - - +
  824. if (!looping)
  825. {
  826. Vector s = overdraw[1] - overdraw[3];
  827. s.normalize();
  828. s *= pixel_size;
  829. overdraw[1] += s;
  830. overdraw[2*count-1] += s;
  831. Vector t = overdraw[count-1] - overdraw[count-3];
  832. t.normalize();
  833. t *= pixel_size;
  834. overdraw[count-1] += t;
  835. overdraw[count+1] += t;
  836. // we need to draw two more triangles to close the
  837. // overdraw at the line start.
  838. overdraw[2*count] = overdraw[0];
  839. overdraw[2*count+1] = overdraw[1];
  840. }
  841. // prepare colors:
  842. // even indices in overdraw* point to inner vertices => alpha = current-alpha,
  843. // odd indices point to outer vertices => alpha = 0.
  844. Color c = gl.getColor();
  845. Color *colors = new Color[2*count+2];
  846. for (size_t i = 0; i < 2*count+2; ++i)
  847. {
  848. colors[i] = c;
  849. // avoids branching. equiv to if (i%2 == 1) colors[i].a = 0;
  850. colors[i].a *= GLubyte(i % 2 == 0);
  851. }
  852. // draw faded out line halos
  853. glEnableClientState(GL_COLOR_ARRAY);
  854. glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
  855. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)overdraw);
  856. glDrawArrays(GL_TRIANGLE_STRIP, 0, 2*count + 2 * int(!looping));
  857. glDisableClientState(GL_COLOR_ARRAY);
  858. // "if GL_COLOR_ARRAY is enabled, the value of the current color is
  859. // undefined after glDrawArrays executes"
  860. gl.setColor(c);
  861. delete[] colors;
  862. }
  863. void Graphics::polyline(const float *coords, size_t count)
  864. {
  865. Vector *vertices = new Vector[count]; // two vertices for every line end-point
  866. Vector *overdraw = NULL;
  867. Vector p,q,r;
  868. bool looping = (coords[0] == coords[count-2]) && (coords[1] == coords[count-1]);
  869. float halfwidth = lineWidth/2.f;
  870. float pixel_size = pixel_size_stack.back();
  871. float overdraw_factor = .0f;
  872. if (lineStyle == LINE_SMOOTH)
  873. {
  874. overdraw = new Vector[2*count+2];
  875. overdraw_factor = pixel_size / halfwidth;
  876. halfwidth = std::max(.0f, halfwidth - .25f*pixel_size);
  877. }
  878. // get line vertex boundaries
  879. // if not looping, extend the line at the beginning, else use last point as `p'
  880. r = Vector(coords[0], coords[1]);
  881. if (!looping)
  882. q = r * 2 - Vector(coords[2], coords[3]);
  883. else
  884. q = Vector(coords[count-4], coords[count-3]);
  885. for (size_t i = 0; i+3 < count; i += 2)
  886. {
  887. p = q;
  888. q = r;
  889. r = Vector(coords[i+2], coords[i+3]);
  890. pushIntersectionPoints(vertices, overdraw, i, count, halfwidth, overdraw_factor, p,q,r);
  891. }
  892. // if not looping, extend the line at the end, else use first point as `r'
  893. p = q;
  894. q = r;
  895. if (!looping)
  896. r += q - p;
  897. else
  898. r = Vector(coords[2], coords[3]);
  899. pushIntersectionPoints(vertices, overdraw, count-2, count, halfwidth, overdraw_factor, p,q,r);
  900. // end get line vertex boundaries
  901. // draw the core line
  902. gl.bindTexture(0);
  903. glEnableClientState(GL_VERTEX_ARRAY);
  904. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)vertices);
  905. glDrawArrays(GL_TRIANGLE_STRIP, 0, count);
  906. // draw the line halo (antialiasing)
  907. if (lineStyle == LINE_SMOOTH)
  908. draw_overdraw(overdraw, count, pixel_size, looping);
  909. glDisableClientState(GL_VERTEX_ARRAY);
  910. // cleanup
  911. delete[] vertices;
  912. if (lineStyle == LINE_SMOOTH)
  913. delete[] overdraw;
  914. }
  915. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  916. {
  917. float coords[] = {x,y, x,y+h, x+w,y+h, x+w,y, x,y};
  918. polygon(mode, coords, 5 * 2);
  919. }
  920. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  921. {
  922. float two_pi = static_cast<float>(LOVE_M_PI * 2);
  923. if (points <= 0) points = 1;
  924. float angle_shift = (two_pi / points);
  925. float phi = .0f;
  926. float *coords = new float[2 * (points + 1)];
  927. for (int i = 0; i < points; ++i, phi += angle_shift)
  928. {
  929. coords[2*i] = x + radius * cosf(phi);
  930. coords[2*i+1] = y + radius * sinf(phi);
  931. }
  932. coords[2*points] = coords[0];
  933. coords[2*points+1] = coords[1];
  934. polygon(mode, coords, (points + 1) * 2);
  935. delete[] coords;
  936. }
  937. void Graphics::arc(DrawMode mode, float x, float y, float radius, float angle1, float angle2, int points)
  938. {
  939. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  940. if (points <= 0 || angle1 == angle2)
  941. return;
  942. // Oh, you want to draw a circle?
  943. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  944. {
  945. circle(mode, x, y, radius, points);
  946. return;
  947. }
  948. float angle_shift = (angle2 - angle1) / points;
  949. // Bail on precision issues.
  950. if (angle_shift == 0.0)
  951. return;
  952. float phi = angle1;
  953. int num_coords = (points + 3) * 2;
  954. float *coords = new float[num_coords];
  955. coords[0] = coords[num_coords - 2] = x;
  956. coords[1] = coords[num_coords - 1] = y;
  957. for (int i = 0; i <= points; ++i, phi += angle_shift)
  958. {
  959. coords[2 * (i+1)] = x + radius * cosf(phi);
  960. coords[2 * (i+1) + 1] = y + radius * sinf(phi);
  961. }
  962. // GL_POLYGON can only fill-draw convex polygons, so we need to do stuff manually here
  963. if (mode == DRAW_LINE)
  964. {
  965. polyline(coords, num_coords); // Artifacts at sharp angles if set to looping.
  966. }
  967. else
  968. {
  969. gl.bindTexture(0);
  970. glEnableClientState(GL_VERTEX_ARRAY);
  971. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *) coords);
  972. glDrawArrays(GL_TRIANGLE_FAN, 0, points + 2);
  973. glDisableClientState(GL_VERTEX_ARRAY);
  974. }
  975. delete[] coords;
  976. }
  977. /// @param mode the draw mode
  978. /// @param coords the coordinate array
  979. /// @param count the number of coordinates/size of the array
  980. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  981. {
  982. // coords is an array of a closed loop of vertices, i.e.
  983. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  984. if (mode == DRAW_LINE)
  985. {
  986. polyline(coords, count);
  987. }
  988. else
  989. {
  990. gl.bindTexture(0);
  991. glEnableClientState(GL_VERTEX_ARRAY);
  992. glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)coords);
  993. glDrawArrays(GL_POLYGON, 0, count/2-1); // opengl will close the polygon for us
  994. glDisableClientState(GL_VERTEX_ARRAY);
  995. }
  996. }
  997. love::image::ImageData *Graphics::newScreenshot(love::image::Image *image, bool copyAlpha)
  998. {
  999. // Temporarily unbind the currently active canvas (glReadPixels reads the
  1000. // active framebuffer, not the main one.)
  1001. Canvas *curcanvas = Canvas::current;
  1002. if (curcanvas)
  1003. Canvas::bindDefaultCanvas();
  1004. int w = getWidth();
  1005. int h = getHeight();
  1006. int row = 4*w;
  1007. int size = row*h;
  1008. GLubyte *pixels = 0;
  1009. GLubyte *screenshot = 0;
  1010. try
  1011. {
  1012. pixels = new GLubyte[size];
  1013. screenshot = new GLubyte[size];
  1014. }
  1015. catch (std::exception &)
  1016. {
  1017. delete[] pixels;
  1018. delete[] screenshot;
  1019. if (curcanvas)
  1020. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  1021. throw love::Exception("Out of memory.");
  1022. }
  1023. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  1024. if (!copyAlpha)
  1025. {
  1026. // Replace alpha values with full opacity.
  1027. for (int i = 3; i < size; i += 4)
  1028. pixels[i] = 255;
  1029. }
  1030. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  1031. GLubyte *src = pixels - row, *dst = screenshot + size;
  1032. for (int i = 0; i < h; ++i)
  1033. memcpy(dst-=row, src+=row, row);
  1034. delete[] pixels;
  1035. love::image::ImageData *img = 0;
  1036. try
  1037. {
  1038. img = image->newImageData(w, h, (void *) screenshot);
  1039. }
  1040. catch (love::Exception &)
  1041. {
  1042. delete[] screenshot;
  1043. if (curcanvas)
  1044. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  1045. throw;
  1046. }
  1047. delete[] screenshot;
  1048. // Re-bind the active canvas, if necessary.
  1049. if (curcanvas)
  1050. curcanvas->startGrab(curcanvas->getAttachedCanvases());
  1051. return img;
  1052. }
  1053. std::string Graphics::getRendererInfo(Graphics::RendererInfo infotype) const
  1054. {
  1055. const char *infostr = 0;
  1056. switch (infotype)
  1057. {
  1058. case Graphics::RENDERER_INFO_NAME:
  1059. default:
  1060. infostr = "OpenGL";
  1061. break;
  1062. case Graphics::RENDERER_INFO_VERSION:
  1063. infostr = (const char *) glGetString(GL_VERSION);
  1064. break;
  1065. case Graphics::RENDERER_INFO_VENDOR:
  1066. infostr = (const char *) glGetString(GL_VENDOR);
  1067. break;
  1068. case Graphics::RENDERER_INFO_DEVICE:
  1069. infostr = (const char *) glGetString(GL_RENDERER);
  1070. break;
  1071. }
  1072. if (!infostr)
  1073. throw love::Exception("Cannot retrieve renderer information.");
  1074. return std::string(infostr);
  1075. }
  1076. void Graphics::push()
  1077. {
  1078. if (userMatrices == matrixLimit)
  1079. throw Exception("Maximum stack depth reached. (More pushes than pops?)");
  1080. glPushMatrix();
  1081. ++userMatrices;
  1082. pixel_size_stack.push_back(pixel_size_stack.back());
  1083. }
  1084. void Graphics::pop()
  1085. {
  1086. if (userMatrices < 1)
  1087. throw Exception("Minimum stack depth reached. (More pops than pushes?)");
  1088. glPopMatrix();
  1089. --userMatrices;
  1090. pixel_size_stack.pop_back();
  1091. }
  1092. void Graphics::rotate(float r)
  1093. {
  1094. glRotatef(LOVE_TODEG(r), 0, 0, 1);
  1095. }
  1096. void Graphics::scale(float x, float y)
  1097. {
  1098. glScalef(x, y, 1);
  1099. pixel_size_stack.back() *= 2. / double(x + y);
  1100. }
  1101. void Graphics::translate(float x, float y)
  1102. {
  1103. glTranslatef(x, y, 0);
  1104. }
  1105. void Graphics::shear(float kx, float ky)
  1106. {
  1107. Matrix t;
  1108. t.setShear(kx, ky);
  1109. glMultMatrixf((const GLfloat *)t.getElements());
  1110. }
  1111. void Graphics::origin()
  1112. {
  1113. glLoadIdentity();
  1114. pixel_size_stack.back() = 1;
  1115. }
  1116. } // opengl
  1117. } // graphics
  1118. } // love