Graphics.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  1. /**
  2. * Copyright (c) 2006-2017 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. // LOVE
  21. #include "Graphics.h"
  22. #include "math/MathModule.h"
  23. #include "Polyline.h"
  24. #include "font/Font.h"
  25. #include "window/Window.h"
  26. // C++
  27. #include <algorithm>
  28. namespace love
  29. {
  30. namespace graphics
  31. {
  32. static bool gammaCorrect = false;
  33. void setGammaCorrect(bool gammacorrect)
  34. {
  35. gammaCorrect = gammacorrect;
  36. }
  37. bool isGammaCorrect()
  38. {
  39. return gammaCorrect;
  40. }
  41. void gammaCorrectColor(Colorf &c)
  42. {
  43. if (isGammaCorrect())
  44. {
  45. c.r = math::gammaToLinear(c.r);
  46. c.g = math::gammaToLinear(c.g);
  47. c.b = math::gammaToLinear(c.b);
  48. }
  49. }
  50. Colorf gammaCorrectColor(const Colorf &c)
  51. {
  52. Colorf r = c;
  53. gammaCorrectColor(r);
  54. return r;
  55. }
  56. void unGammaCorrectColor(Colorf &c)
  57. {
  58. if (isGammaCorrect())
  59. {
  60. c.r = math::linearToGamma(c.r);
  61. c.g = math::linearToGamma(c.g);
  62. c.b = math::linearToGamma(c.b);
  63. }
  64. }
  65. Colorf unGammaCorrectColor(const Colorf &c)
  66. {
  67. Colorf r = c;
  68. unGammaCorrectColor(r);
  69. return r;
  70. }
  71. love::Type Graphics::type("graphics", &Module::type);
  72. Shader::ShaderSource Graphics::defaultShaderCode[Shader::LANGUAGE_MAX_ENUM][2];
  73. Shader::ShaderSource Graphics::defaultVideoShaderCode[Shader::LANGUAGE_MAX_ENUM][2];
  74. Graphics::Graphics()
  75. : width(0)
  76. , height(0)
  77. , pixelWidth(0)
  78. , pixelHeight(0)
  79. , created(false)
  80. , active(true)
  81. , writingToStencil(false)
  82. , streamBufferState()
  83. , projectionMatrix()
  84. , canvasSwitchCount(0)
  85. {
  86. transformStack.reserve(16);
  87. transformStack.push_back(Matrix4());
  88. pixelScaleStack.reserve(16);
  89. pixelScaleStack.push_back(1);
  90. if (!Shader::initialize())
  91. throw love::Exception("Shader support failed to initialize!");
  92. }
  93. Graphics::~Graphics()
  94. {
  95. states.clear();
  96. defaultFont.set(nullptr);
  97. if (Shader::defaultShader)
  98. {
  99. Shader::defaultShader->release();
  100. Shader::defaultShader = nullptr;
  101. }
  102. if (Shader::defaultVideoShader)
  103. {
  104. Shader::defaultVideoShader->release();
  105. Shader::defaultVideoShader = nullptr;
  106. }
  107. delete streamBufferState.vb[0];
  108. delete streamBufferState.vb[1];
  109. delete streamBufferState.indexBuffer;
  110. Shader::deinitialize();
  111. }
  112. Quad *Graphics::newQuad(Quad::Viewport v, double sw, double sh)
  113. {
  114. return new Quad(v, sw, sh);
  115. }
  116. bool Graphics::validateShader(bool gles, const Shader::ShaderSource &source, std::string &err)
  117. {
  118. return Shader::validate(this, gles, source, true, err);
  119. }
  120. int Graphics::getWidth() const
  121. {
  122. return width;
  123. }
  124. int Graphics::getHeight() const
  125. {
  126. return height;
  127. }
  128. int Graphics::getPixelWidth() const
  129. {
  130. return pixelWidth;
  131. }
  132. int Graphics::getPixelHeight() const
  133. {
  134. return pixelHeight;
  135. }
  136. double Graphics::getCurrentPixelDensity() const
  137. {
  138. if (states.back().canvases.size() > 0)
  139. {
  140. love::graphics::Canvas *c = states.back().canvases[0];
  141. return (double) c->getPixelHeight() / (double) c->getHeight();
  142. }
  143. return getScreenPixelDensity();
  144. }
  145. double Graphics::getScreenPixelDensity() const
  146. {
  147. return (double) getPixelHeight() / (double) getHeight();
  148. }
  149. bool Graphics::isCreated() const
  150. {
  151. return created;
  152. }
  153. bool Graphics::isActive() const
  154. {
  155. // The graphics module is only completely 'active' if there's a window, a
  156. // context, and the active variable is set.
  157. auto window = getInstance<love::window::Window>(M_WINDOW);
  158. return active && isCreated() && window != nullptr && window->isOpen();
  159. }
  160. void Graphics::reset()
  161. {
  162. DisplayState s;
  163. stopDrawToStencilBuffer();
  164. restoreState(s);
  165. origin();
  166. }
  167. /**
  168. * State functions.
  169. **/
  170. void Graphics::restoreState(const DisplayState &s)
  171. {
  172. setColor(s.color);
  173. setBackgroundColor(s.backgroundColor);
  174. setBlendMode(s.blendMode, s.blendAlphaMode);
  175. setLineWidth(s.lineWidth);
  176. setLineStyle(s.lineStyle);
  177. setLineJoin(s.lineJoin);
  178. setPointSize(s.pointSize);
  179. if (s.scissor)
  180. setScissor(s.scissorRect);
  181. else
  182. setScissor();
  183. setStencilTest(s.stencilCompare, s.stencilTestValue);
  184. setFont(s.font.get());
  185. setShader(s.shader.get());
  186. setCanvas(s.canvases);
  187. setColorMask(s.colorMask);
  188. setWireframe(s.wireframe);
  189. setDefaultFilter(s.defaultFilter);
  190. setDefaultMipmapFilter(s.defaultMipmapFilter, s.defaultMipmapSharpness);
  191. }
  192. void Graphics::restoreStateChecked(const DisplayState &s)
  193. {
  194. const DisplayState &cur = states.back();
  195. if (s.color != cur.color)
  196. setColor(s.color);
  197. setBackgroundColor(s.backgroundColor);
  198. if (s.blendMode != cur.blendMode || s.blendAlphaMode != cur.blendAlphaMode)
  199. setBlendMode(s.blendMode, s.blendAlphaMode);
  200. // These are just simple assignments.
  201. setLineWidth(s.lineWidth);
  202. setLineStyle(s.lineStyle);
  203. setLineJoin(s.lineJoin);
  204. if (s.pointSize != cur.pointSize)
  205. setPointSize(s.pointSize);
  206. if (s.scissor != cur.scissor || (s.scissor && !(s.scissorRect == cur.scissorRect)))
  207. {
  208. if (s.scissor)
  209. setScissor(s.scissorRect);
  210. else
  211. setScissor();
  212. }
  213. if (s.stencilCompare != cur.stencilCompare || s.stencilTestValue != cur.stencilTestValue)
  214. setStencilTest(s.stencilCompare, s.stencilTestValue);
  215. setFont(s.font.get());
  216. setShader(s.shader.get());
  217. bool canvaseschanged = s.canvases.size() != cur.canvases.size();
  218. if (!canvaseschanged)
  219. {
  220. for (size_t i = 0; i < s.canvases.size() && i < cur.canvases.size(); i++)
  221. {
  222. if (s.canvases[i].get() != cur.canvases[i].get())
  223. {
  224. canvaseschanged = true;
  225. break;
  226. }
  227. }
  228. }
  229. if (canvaseschanged)
  230. setCanvas(s.canvases);
  231. if (s.colorMask != cur.colorMask)
  232. setColorMask(s.colorMask);
  233. if (s.wireframe != cur.wireframe)
  234. setWireframe(s.wireframe);
  235. setDefaultFilter(s.defaultFilter);
  236. setDefaultMipmapFilter(s.defaultMipmapFilter, s.defaultMipmapSharpness);
  237. }
  238. Colorf Graphics::getColor() const
  239. {
  240. return states.back().color;
  241. }
  242. void Graphics::setBackgroundColor(Colorf c)
  243. {
  244. states.back().backgroundColor = c;
  245. }
  246. Colorf Graphics::getBackgroundColor() const
  247. {
  248. return states.back().backgroundColor;
  249. }
  250. void Graphics::checkSetDefaultFont()
  251. {
  252. // We don't create or set the default Font if an existing font is in use.
  253. if (states.back().font.get() != nullptr)
  254. return;
  255. // Create a new default font if we don't have one yet.
  256. if (!defaultFont.get())
  257. {
  258. auto fontmodule = Module::getInstance<font::Font>(M_FONT);
  259. if (!fontmodule)
  260. throw love::Exception("Font module has not been loaded.");
  261. auto hinting = font::TrueTypeRasterizer::HINTING_NORMAL;
  262. StrongRef<font::Rasterizer> r(fontmodule->newTrueTypeRasterizer(12, hinting), Acquire::NORETAIN);
  263. defaultFont.set(newFont(r.get()), Acquire::NORETAIN);
  264. }
  265. states.back().font.set(defaultFont.get());
  266. }
  267. void Graphics::setFont(love::graphics::Font *font)
  268. {
  269. // We don't need to set a default font here if null is passed in, since we
  270. // only care about the default font in getFont and print.
  271. DisplayState &state = states.back();
  272. state.font.set(font);
  273. }
  274. love::graphics::Font *Graphics::getFont()
  275. {
  276. checkSetDefaultFont();
  277. return states.back().font.get();
  278. }
  279. void Graphics::setShader(love::graphics::Shader *shader)
  280. {
  281. if (shader == nullptr)
  282. return setShader();
  283. flushStreamDraws();
  284. shader->attach();
  285. states.back().shader.set(shader);
  286. }
  287. void Graphics::setShader()
  288. {
  289. flushStreamDraws();
  290. Shader::attachDefault();
  291. states.back().shader.set(nullptr);
  292. }
  293. love::graphics::Shader *Graphics::getShader() const
  294. {
  295. return states.back().shader.get();
  296. }
  297. void Graphics::setCanvas(Canvas *canvas)
  298. {
  299. if (canvas == nullptr)
  300. return setCanvas();
  301. std::vector<Canvas *> canvases = {canvas};
  302. setCanvas(canvases);
  303. }
  304. void Graphics::setCanvas(const std::vector<StrongRef<Canvas>> &canvases)
  305. {
  306. std::vector<Canvas *> canvaslist;
  307. canvaslist.reserve(canvases.size());
  308. for (const StrongRef<Canvas> &c : canvases)
  309. canvaslist.push_back(c.get());
  310. return setCanvas(canvaslist);
  311. }
  312. std::vector<Canvas *> Graphics::getCanvas() const
  313. {
  314. std::vector<Canvas *> canvases;
  315. canvases.reserve(states.back().canvases.size());
  316. for (const StrongRef<Canvas> &c : states.back().canvases)
  317. canvases.push_back(c.get());
  318. return canvases;
  319. }
  320. bool Graphics::isCanvasActive() const
  321. {
  322. return !states.back().canvases.empty();
  323. }
  324. bool Graphics::isCanvasActive(love::graphics::Canvas *canvas) const
  325. {
  326. for (const auto &c : states.back().canvases)
  327. {
  328. if (c.get() == canvas)
  329. return true;
  330. }
  331. return false;
  332. }
  333. void Graphics::intersectScissor(const Rect &rect)
  334. {
  335. Rect currect = states.back().scissorRect;
  336. if (!states.back().scissor)
  337. {
  338. currect.x = 0;
  339. currect.y = 0;
  340. currect.w = std::numeric_limits<int>::max();
  341. currect.h = std::numeric_limits<int>::max();
  342. }
  343. int x1 = std::max(currect.x, rect.x);
  344. int y1 = std::max(currect.y, rect.y);
  345. int x2 = std::min(currect.x + currect.w, rect.x + rect.w);
  346. int y2 = std::min(currect.y + currect.h, rect.y + rect.h);
  347. Rect newrect = {x1, y1, std::max(0, x2 - x1), std::max(0, y2 - y1)};
  348. setScissor(newrect);
  349. }
  350. bool Graphics::getScissor(Rect &rect) const
  351. {
  352. const DisplayState &state = states.back();
  353. rect = state.scissorRect;
  354. return state.scissor;
  355. }
  356. void Graphics::getStencilTest(CompareMode &compare, int &value)
  357. {
  358. const DisplayState &state = states.back();
  359. compare = state.stencilCompare;
  360. value = state.stencilTestValue;
  361. }
  362. Graphics::ColorMask Graphics::getColorMask() const
  363. {
  364. return states.back().colorMask;
  365. }
  366. Graphics::BlendMode Graphics::getBlendMode(BlendAlpha &alphamode) const
  367. {
  368. alphamode = states.back().blendAlphaMode;
  369. return states.back().blendMode;
  370. }
  371. void Graphics::setDefaultFilter(const Texture::Filter &f)
  372. {
  373. Texture::defaultFilter = f;
  374. states.back().defaultFilter = f;
  375. }
  376. const Texture::Filter &Graphics::getDefaultFilter() const
  377. {
  378. return Texture::defaultFilter;
  379. }
  380. void Graphics::setDefaultMipmapFilter(Texture::FilterMode filter, float sharpness)
  381. {
  382. Texture::defaultMipmapFilter = filter;
  383. Texture::defaultMipmapSharpness = sharpness;
  384. states.back().defaultMipmapFilter = filter;
  385. states.back().defaultMipmapSharpness = sharpness;
  386. }
  387. void Graphics::getDefaultMipmapFilter(Texture::FilterMode *filter, float *sharpness) const
  388. {
  389. *filter = Texture::defaultMipmapFilter;
  390. *sharpness = Texture::defaultMipmapSharpness;
  391. }
  392. void Graphics::setLineWidth(float width)
  393. {
  394. states.back().lineWidth = width;
  395. }
  396. void Graphics::setLineStyle(Graphics::LineStyle style)
  397. {
  398. states.back().lineStyle = style;
  399. }
  400. void Graphics::setLineJoin(Graphics::LineJoin join)
  401. {
  402. states.back().lineJoin = join;
  403. }
  404. float Graphics::getLineWidth() const
  405. {
  406. return states.back().lineWidth;
  407. }
  408. Graphics::LineStyle Graphics::getLineStyle() const
  409. {
  410. return states.back().lineStyle;
  411. }
  412. Graphics::LineJoin Graphics::getLineJoin() const
  413. {
  414. return states.back().lineJoin;
  415. }
  416. float Graphics::getPointSize() const
  417. {
  418. return states.back().pointSize;
  419. }
  420. bool Graphics::isWireframe() const
  421. {
  422. return states.back().wireframe;
  423. }
  424. void Graphics::captureScreenshot(const ScreenshotInfo &info)
  425. {
  426. pendingScreenshotCallbacks.push_back(info);
  427. }
  428. Graphics::StreamVertexData Graphics::requestStreamDraw(const StreamDrawRequest &req)
  429. {
  430. using namespace vertex;
  431. StreamBufferState &state = streamBufferState;
  432. bool shouldflush = false;
  433. bool shouldresize = false;
  434. if (req.primitiveMode != state.primitiveMode
  435. || req.formats[0] != state.formats[0] || req.formats[1] != state.formats[1]
  436. || ((req.indexMode != TriangleIndexMode::NONE) != (state.indexCount > 0))
  437. || req.texture != state.texture || req.textureHandle != state.textureHandle)
  438. {
  439. shouldflush = true;
  440. }
  441. int totalvertices = state.vertexCount + req.vertexCount;
  442. // We only support uint16 index buffers for now.
  443. if (totalvertices > LOVE_UINT16_MAX && req.indexMode != TriangleIndexMode::NONE)
  444. shouldflush = true;
  445. int reqIndexCount = getIndexCount(req.indexMode, req.vertexCount);
  446. size_t reqIndexSize = reqIndexCount * sizeof(uint16);
  447. size_t newdatasizes[2] = {0, 0};
  448. size_t buffersizes[3] = {0, 0, 0};
  449. for (int i = 0; i < 2; i++)
  450. {
  451. if (req.formats[i] == CommonFormat::NONE)
  452. continue;
  453. size_t stride = getFormatStride(req.formats[i]);
  454. size_t datasize = stride * totalvertices;
  455. if (state.vbMap[i].data != nullptr && datasize > state.vbMap[i].size)
  456. shouldflush = true;
  457. if (datasize > state.vb[i]->getSize())
  458. {
  459. buffersizes[i] = std::max(datasize, state.vb[i]->getSize() * 2);
  460. shouldresize = true;
  461. }
  462. newdatasizes[i] = stride * req.vertexCount;
  463. }
  464. if (req.indexMode != TriangleIndexMode::NONE)
  465. {
  466. size_t datasize = (state.indexCount + reqIndexCount) * sizeof(uint16);
  467. if (state.indexBufferMap.data != nullptr && datasize > state.indexBufferMap.size)
  468. shouldflush = true;
  469. if (datasize > state.indexBuffer->getSize())
  470. {
  471. buffersizes[2] = std::max(datasize, state.indexBuffer->getSize() * 2);
  472. shouldresize = true;
  473. }
  474. }
  475. if (shouldflush || shouldresize)
  476. {
  477. flushStreamDraws();
  478. state.primitiveMode = req.primitiveMode;
  479. state.formats[0] = req.formats[0];
  480. state.formats[1] = req.formats[1];
  481. state.texture = req.texture;
  482. state.textureHandle = req.textureHandle;
  483. }
  484. if (shouldresize)
  485. {
  486. for (int i = 0; i < 2; i++)
  487. {
  488. if (state.vb[i]->getSize() < buffersizes[i])
  489. {
  490. delete state.vb[i];
  491. state.vb[i] = newStreamBuffer(BUFFER_VERTEX, buffersizes[i]);
  492. }
  493. }
  494. if (state.indexBuffer->getSize() < buffersizes[2])
  495. {
  496. delete state.indexBuffer;
  497. state.indexBuffer = newStreamBuffer(BUFFER_INDEX, buffersizes[2]);
  498. }
  499. }
  500. if (req.indexMode != TriangleIndexMode::NONE)
  501. {
  502. if (state.indexBufferMap.data == nullptr)
  503. state.indexBufferMap = state.indexBuffer->map(reqIndexSize);
  504. uint16 *indices = (uint16 *) state.indexBufferMap.data;
  505. fillIndices(req.indexMode, state.vertexCount, req.vertexCount, indices);
  506. state.indexBufferMap.data += reqIndexSize;
  507. }
  508. StreamVertexData d;
  509. for (int i = 0; i < 2; i++)
  510. {
  511. if (newdatasizes[i] > 0)
  512. {
  513. if (state.vbMap[i].data == nullptr)
  514. state.vbMap[i] = state.vb[i]->map(newdatasizes[i]);
  515. d.stream[i] = state.vbMap[i].data;
  516. state.vbMap[i].data += newdatasizes[i];
  517. }
  518. }
  519. state.vertexCount += req.vertexCount;
  520. state.indexCount += reqIndexCount;
  521. return d;
  522. }
  523. /**
  524. * Drawing
  525. **/
  526. void Graphics::print(const std::vector<Font::ColoredString> &str, const Matrix4 &m)
  527. {
  528. checkSetDefaultFont();
  529. DisplayState &state = states.back();
  530. if (state.font.get() != nullptr)
  531. state.font->print(this, str, m, state.color);
  532. }
  533. void Graphics::printf(const std::vector<Font::ColoredString> &str, float wrap, Font::AlignMode align, const Matrix4 &m)
  534. {
  535. checkSetDefaultFont();
  536. DisplayState &state = states.back();
  537. if (state.font.get() != nullptr)
  538. state.font->printf(this, str, wrap, align, m, state.color);
  539. }
  540. void Graphics::draw(Drawable *drawable, const Matrix4 &m)
  541. {
  542. drawable->draw(this, m);
  543. }
  544. void Graphics::draw(Texture *texture, Quad *quad, const Matrix4 &m)
  545. {
  546. texture->drawq(this, quad, m);
  547. }
  548. /**
  549. * Primitives (points, shapes, lines).
  550. **/
  551. void Graphics::points(const float *coords, const Colorf *colors, size_t numpoints)
  552. {
  553. StreamDrawRequest req;
  554. req.primitiveMode = vertex::PrimitiveMode::POINTS;
  555. req.formats[0] = vertex::CommonFormat::XYf;
  556. if (colors)
  557. req.formats[1] = vertex::CommonFormat::RGBAub;
  558. req.vertexCount = (int) numpoints;
  559. StreamVertexData data = requestStreamDraw(req);
  560. const Matrix4 &t = getTransform();
  561. t.transform((Vector *) data.stream[0], (const Vector *) coords, req.vertexCount);
  562. Color *colordata = (Color *) data.stream[1];
  563. if (colors)
  564. {
  565. Colorf nc = getColor();
  566. gammaCorrectColor(nc);
  567. if (isGammaCorrect())
  568. {
  569. for (int i = 0; i < req.vertexCount; i++)
  570. {
  571. Colorf ci = colors[i];
  572. gammaCorrectColor(ci);
  573. ci *= nc;
  574. unGammaCorrectColor(ci);
  575. colordata[i] = toColor(ci);
  576. }
  577. }
  578. else
  579. {
  580. for (int i = 0; i < req.vertexCount; i++)
  581. colordata[i] = toColor(nc * colors[i]);
  582. }
  583. }
  584. else
  585. {
  586. Color c = toColor(getColor());
  587. for (int i = 0; i < req.vertexCount; i++)
  588. colordata[i] = c;
  589. }
  590. }
  591. int Graphics::calculateEllipsePoints(float rx, float ry) const
  592. {
  593. int points = (int) sqrtf(((rx + ry) / 2.0f) * 20.0f * (float) pixelScaleStack.back());
  594. return std::max(points, 8);
  595. }
  596. void Graphics::polyline(const float *coords, size_t count)
  597. {
  598. float halfwidth = getLineWidth() * 0.5f;
  599. LineJoin linejoin = getLineJoin();
  600. LineStyle linestyle = getLineStyle();
  601. float pixelsize = 1.0f / std::max((float) pixelScaleStack.back(), 0.000001f);
  602. if (linejoin == LINE_JOIN_NONE)
  603. {
  604. NoneJoinPolyline line;
  605. line.render(coords, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  606. line.draw(this);
  607. }
  608. else if (linejoin == LINE_JOIN_BEVEL)
  609. {
  610. BevelJoinPolyline line;
  611. line.render(coords, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  612. line.draw(this);
  613. }
  614. else if (linejoin == LINE_JOIN_MITER)
  615. {
  616. MiterJoinPolyline line;
  617. line.render(coords, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  618. line.draw(this);
  619. }
  620. }
  621. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  622. {
  623. float coords[] = {x,y, x,y+h, x+w,y+h, x+w,y, x,y};
  624. polygon(mode, coords, 5 * 2);
  625. }
  626. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry, int points)
  627. {
  628. if (rx == 0 || ry == 0)
  629. {
  630. rectangle(mode, x, y, w, h);
  631. return;
  632. }
  633. // Radius values that are more than half the rectangle's size aren't handled
  634. // correctly (for now)...
  635. if (w >= 0.02f)
  636. rx = std::min(rx, w / 2.0f - 0.01f);
  637. if (h >= 0.02f)
  638. ry = std::min(ry, h / 2.0f - 0.01f);
  639. points = std::max(points / 4, 1);
  640. const float half_pi = static_cast<float>(LOVE_M_PI / 2);
  641. float angle_shift = half_pi / ((float) points + 1.0f);
  642. int num_coords = (points + 2) * 8;
  643. float *coords = getScratchBuffer<float>(num_coords + 2);
  644. float phi = .0f;
  645. for (int i = 0; i <= points + 2; ++i, phi += angle_shift)
  646. {
  647. coords[2 * i + 0] = x + rx * (1 - cosf(phi));
  648. coords[2 * i + 1] = y + ry * (1 - sinf(phi));
  649. }
  650. phi = half_pi;
  651. for (int i = points + 2; i <= 2 * (points + 2); ++i, phi += angle_shift)
  652. {
  653. coords[2 * i + 0] = x + w - rx * (1 + cosf(phi));
  654. coords[2 * i + 1] = y + ry * (1 - sinf(phi));
  655. }
  656. phi = 2 * half_pi;
  657. for (int i = 2 * (points + 2); i <= 3 * (points + 2); ++i, phi += angle_shift)
  658. {
  659. coords[2 * i + 0] = x + w - rx * (1 + cosf(phi));
  660. coords[2 * i + 1] = y + h - ry * (1 + sinf(phi));
  661. }
  662. phi = 3 * half_pi;
  663. for (int i = 3 * (points + 2); i <= 4 * (points + 2); ++i, phi += angle_shift)
  664. {
  665. coords[2 * i + 0] = x + rx * (1 - cosf(phi));
  666. coords[2 * i + 1] = y + h - ry * (1 + sinf(phi));
  667. }
  668. coords[num_coords + 0] = coords[0];
  669. coords[num_coords + 1] = coords[1];
  670. polygon(mode, coords, num_coords + 2);
  671. }
  672. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry)
  673. {
  674. rectangle(mode, x, y, w, h, rx, ry, calculateEllipsePoints(rx, ry));
  675. }
  676. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  677. {
  678. ellipse(mode, x, y, radius, radius, points);
  679. }
  680. void Graphics::circle(DrawMode mode, float x, float y, float radius)
  681. {
  682. ellipse(mode, x, y, radius, radius);
  683. }
  684. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b, int points)
  685. {
  686. float two_pi = (float) (LOVE_M_PI * 2);
  687. if (points <= 0) points = 1;
  688. float angle_shift = (two_pi / points);
  689. float phi = .0f;
  690. float *coords = getScratchBuffer<float>(2 * (points + 1));
  691. for (int i = 0; i < points; ++i, phi += angle_shift)
  692. {
  693. coords[2*i+0] = x + a * cosf(phi);
  694. coords[2*i+1] = y + b * sinf(phi);
  695. }
  696. coords[2*points+0] = coords[0];
  697. coords[2*points+1] = coords[1];
  698. polygon(mode, coords, (points + 1) * 2);
  699. }
  700. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b)
  701. {
  702. ellipse(mode, x, y, a, b, calculateEllipsePoints(a, b));
  703. }
  704. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2, int points)
  705. {
  706. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  707. if (points <= 0 || angle1 == angle2)
  708. return;
  709. // Oh, you want to draw a circle?
  710. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  711. {
  712. circle(drawmode, x, y, radius, points);
  713. return;
  714. }
  715. float angle_shift = (angle2 - angle1) / points;
  716. // Bail on precision issues.
  717. if (angle_shift == 0.0)
  718. return;
  719. // Prevent the connecting line from being drawn if a closed line arc has a
  720. // small angle. Avoids some visual issues when connected lines are at sharp
  721. // angles, due to the miter line join drawing code.
  722. if (drawmode == DRAW_LINE && arcmode == ARC_CLOSED && fabsf(angle1 - angle2) < LOVE_TORAD(4))
  723. arcmode = ARC_OPEN;
  724. // Quick fix for the last part of a filled open arc not being drawn (because
  725. // polygon(DRAW_FILL, ...) doesn't work without a closed loop of vertices.)
  726. if (drawmode == DRAW_FILL && arcmode == ARC_OPEN)
  727. arcmode = ARC_CLOSED;
  728. float phi = angle1;
  729. float *coords = nullptr;
  730. int num_coords = 0;
  731. const auto createPoints = [&](float *coordinates)
  732. {
  733. for (int i = 0; i <= points; ++i, phi += angle_shift)
  734. {
  735. coordinates[2 * i + 0] = x + radius * cosf(phi);
  736. coordinates[2 * i + 1] = y + radius * sinf(phi);
  737. }
  738. };
  739. if (arcmode == ARC_PIE)
  740. {
  741. num_coords = (points + 3) * 2;
  742. coords = getScratchBuffer<float>(num_coords);
  743. coords[0] = coords[num_coords - 2] = x;
  744. coords[1] = coords[num_coords - 1] = y;
  745. createPoints(coords + 2);
  746. }
  747. else if (arcmode == ARC_OPEN)
  748. {
  749. num_coords = (points + 1) * 2;
  750. coords = getScratchBuffer<float>(num_coords);
  751. createPoints(coords);
  752. }
  753. else // ARC_CLOSED
  754. {
  755. num_coords = (points + 2) * 2;
  756. coords = getScratchBuffer<float>(num_coords);
  757. createPoints(coords);
  758. // Connect the ends of the arc.
  759. coords[num_coords - 2] = coords[0];
  760. coords[num_coords - 1] = coords[1];
  761. }
  762. polygon(drawmode, coords, num_coords);
  763. }
  764. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2)
  765. {
  766. float points = (float) calculateEllipsePoints(radius, radius);
  767. // The amount of points is based on the fraction of the circle created by the arc.
  768. float angle = fabsf(angle1 - angle2);
  769. if (angle < 2.0f * (float) LOVE_M_PI)
  770. points *= angle / (2.0f * (float) LOVE_M_PI);
  771. arc(drawmode, arcmode, x, y, radius, angle1, angle2, (int) (points + 0.5f));
  772. }
  773. /// @param mode the draw mode
  774. /// @param coords the coordinate array
  775. /// @param count the number of coordinates/size of the array
  776. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  777. {
  778. // coords is an array of a closed loop of vertices, i.e.
  779. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  780. if (mode == DRAW_LINE)
  781. {
  782. polyline(coords, count);
  783. }
  784. else
  785. {
  786. StreamDrawRequest req;
  787. req.formats[0] = vertex::CommonFormat::XYf;
  788. req.formats[1] = vertex::CommonFormat::RGBAub;
  789. req.indexMode = vertex::TriangleIndexMode::FAN;
  790. req.vertexCount = (int)count/2 - 1;
  791. StreamVertexData data = requestStreamDraw(req);
  792. const Matrix4 &t = getTransform();
  793. t.transform((Vector *) data.stream[0], (const Vector *) coords, req.vertexCount);
  794. Color c = toColor(getColor());
  795. Color *colordata = (Color *) data.stream[1];
  796. for (int i = 0; i < req.vertexCount; i++)
  797. colordata[i] = c;
  798. }
  799. }
  800. void Graphics::push(StackType type)
  801. {
  802. if (stackTypeStack.size() == MAX_USER_STACK_DEPTH)
  803. throw Exception("Maximum stack depth reached (more pushes than pops?)");
  804. pushTransform();
  805. pixelScaleStack.push_back(pixelScaleStack.back());
  806. if (type == STACK_ALL)
  807. states.push_back(states.back());
  808. stackTypeStack.push_back(type);
  809. }
  810. void Graphics::pop()
  811. {
  812. if (stackTypeStack.size() < 1)
  813. throw Exception("Minimum stack depth reached (more pops than pushes?)");
  814. popTransform();
  815. pixelScaleStack.pop_back();
  816. if (stackTypeStack.back() == STACK_ALL)
  817. {
  818. DisplayState &newstate = states[states.size() - 2];
  819. restoreStateChecked(newstate);
  820. // The last two states in the stack should be equal now.
  821. states.pop_back();
  822. }
  823. stackTypeStack.pop_back();
  824. }
  825. /**
  826. * Transform and stack functions.
  827. **/
  828. const Matrix4 &Graphics::getTransform() const
  829. {
  830. return transformStack.back();
  831. }
  832. const Matrix4 &Graphics::getProjection() const
  833. {
  834. return projectionMatrix;
  835. }
  836. void Graphics::pushTransform()
  837. {
  838. transformStack.push_back(transformStack.back());
  839. }
  840. void Graphics::pushIdentityTransform()
  841. {
  842. transformStack.push_back(Matrix4());
  843. }
  844. void Graphics::popTransform()
  845. {
  846. transformStack.pop_back();
  847. }
  848. void Graphics::rotate(float r)
  849. {
  850. transformStack.back().rotate(r);
  851. }
  852. void Graphics::scale(float x, float y)
  853. {
  854. transformStack.back().scale(x, y);
  855. pixelScaleStack.back() *= (fabs(x) + fabs(y)) / 2.0;
  856. }
  857. void Graphics::translate(float x, float y)
  858. {
  859. transformStack.back().translate(x, y);
  860. }
  861. void Graphics::shear(float kx, float ky)
  862. {
  863. transformStack.back().shear(kx, ky);
  864. }
  865. void Graphics::origin()
  866. {
  867. transformStack.back().setIdentity();
  868. pixelScaleStack.back() = 1;
  869. }
  870. void Graphics::applyTransform(love::math::Transform *transform)
  871. {
  872. Matrix4 &m = transformStack.back();
  873. m *= transform->getMatrix();
  874. float sx, sy;
  875. m.getApproximateScale(sx, sy);
  876. pixelScaleStack.back() = (sx + sy) / 2.0;
  877. }
  878. void Graphics::replaceTransform(love::math::Transform *transform)
  879. {
  880. const Matrix4 &m = transform->getMatrix();
  881. transformStack.back() = m;
  882. float sx, sy;
  883. m.getApproximateScale(sx, sy);
  884. pixelScaleStack.back() = (sx + sy) / 2.0;
  885. }
  886. Vector Graphics::transformPoint(Vector point)
  887. {
  888. Vector p;
  889. transformStack.back().transform(&p, &point, 1);
  890. return p;
  891. }
  892. Vector Graphics::inverseTransformPoint(Vector point)
  893. {
  894. Vector p;
  895. // TODO: We should probably cache the inverse transform so we don't have to
  896. // re-calculate it every time this is called.
  897. transformStack.back().inverse().transform(&p, &point, 1);
  898. return p;
  899. }
  900. const Shader::ShaderSource &Graphics::getCurrentDefaultShaderCode() const
  901. {
  902. return defaultShaderCode[getShaderLanguageTarget()][isGammaCorrect() ? 1 : 0];
  903. }
  904. /**
  905. * Constants.
  906. **/
  907. bool Graphics::getConstant(const char *in, DrawMode &out)
  908. {
  909. return drawModes.find(in, out);
  910. }
  911. bool Graphics::getConstant(DrawMode in, const char *&out)
  912. {
  913. return drawModes.find(in, out);
  914. }
  915. bool Graphics::getConstant(const char *in, ArcMode &out)
  916. {
  917. return arcModes.find(in, out);
  918. }
  919. bool Graphics::getConstant(ArcMode in, const char *&out)
  920. {
  921. return arcModes.find(in, out);
  922. }
  923. bool Graphics::getConstant(const char *in, BlendMode &out)
  924. {
  925. return blendModes.find(in, out);
  926. }
  927. bool Graphics::getConstant(BlendMode in, const char *&out)
  928. {
  929. return blendModes.find(in, out);
  930. }
  931. bool Graphics::getConstant(const char *in, BlendAlpha &out)
  932. {
  933. return blendAlphaModes.find(in, out);
  934. }
  935. bool Graphics::getConstant(BlendAlpha in, const char *&out)
  936. {
  937. return blendAlphaModes.find(in, out);
  938. }
  939. bool Graphics::getConstant(const char *in, LineStyle &out)
  940. {
  941. return lineStyles.find(in, out);
  942. }
  943. bool Graphics::getConstant(LineStyle in, const char *&out)
  944. {
  945. return lineStyles.find(in, out);
  946. }
  947. bool Graphics::getConstant(const char *in, LineJoin &out)
  948. {
  949. return lineJoins.find(in, out);
  950. }
  951. bool Graphics::getConstant(LineJoin in, const char *&out)
  952. {
  953. return lineJoins.find(in, out);
  954. }
  955. bool Graphics::getConstant(const char *in, StencilAction &out)
  956. {
  957. return stencilActions.find(in, out);
  958. }
  959. bool Graphics::getConstant(StencilAction in, const char *&out)
  960. {
  961. return stencilActions.find(in, out);
  962. }
  963. bool Graphics::getConstant(const char *in, CompareMode &out)
  964. {
  965. return compareModes.find(in, out);
  966. }
  967. bool Graphics::getConstant(CompareMode in, const char *&out)
  968. {
  969. return compareModes.find(in, out);
  970. }
  971. bool Graphics::getConstant(const char *in, Feature &out)
  972. {
  973. return features.find(in, out);
  974. }
  975. bool Graphics::getConstant(Feature in, const char *&out)
  976. {
  977. return features.find(in, out);
  978. }
  979. bool Graphics::getConstant(const char *in, SystemLimit &out)
  980. {
  981. return systemLimits.find(in, out);
  982. }
  983. bool Graphics::getConstant(SystemLimit in, const char *&out)
  984. {
  985. return systemLimits.find(in, out);
  986. }
  987. bool Graphics::getConstant(const char *in, StackType &out)
  988. {
  989. return stackTypes.find(in, out);
  990. }
  991. bool Graphics::getConstant(StackType in, const char *&out)
  992. {
  993. return stackTypes.find(in, out);
  994. }
  995. StringMap<Graphics::DrawMode, Graphics::DRAW_MAX_ENUM>::Entry Graphics::drawModeEntries[] =
  996. {
  997. { "line", DRAW_LINE },
  998. { "fill", DRAW_FILL },
  999. };
  1000. StringMap<Graphics::DrawMode, Graphics::DRAW_MAX_ENUM> Graphics::drawModes(Graphics::drawModeEntries, sizeof(Graphics::drawModeEntries));
  1001. StringMap<Graphics::ArcMode, Graphics::ARC_MAX_ENUM>::Entry Graphics::arcModeEntries[] =
  1002. {
  1003. { "open", ARC_OPEN },
  1004. { "closed", ARC_CLOSED },
  1005. { "pie", ARC_PIE },
  1006. };
  1007. StringMap<Graphics::ArcMode, Graphics::ARC_MAX_ENUM> Graphics::arcModes(Graphics::arcModeEntries, sizeof(Graphics::arcModeEntries));
  1008. StringMap<Graphics::BlendMode, Graphics::BLEND_MAX_ENUM>::Entry Graphics::blendModeEntries[] =
  1009. {
  1010. { "alpha", BLEND_ALPHA },
  1011. { "add", BLEND_ADD },
  1012. { "subtract", BLEND_SUBTRACT },
  1013. { "multiply", BLEND_MULTIPLY },
  1014. { "lighten", BLEND_LIGHTEN },
  1015. { "darken", BLEND_DARKEN },
  1016. { "screen", BLEND_SCREEN },
  1017. { "replace", BLEND_REPLACE },
  1018. { "none", BLEND_NONE },
  1019. };
  1020. StringMap<Graphics::BlendMode, Graphics::BLEND_MAX_ENUM> Graphics::blendModes(Graphics::blendModeEntries, sizeof(Graphics::blendModeEntries));
  1021. StringMap<Graphics::BlendAlpha, Graphics::BLENDALPHA_MAX_ENUM>::Entry Graphics::blendAlphaEntries[] =
  1022. {
  1023. { "alphamultiply", BLENDALPHA_MULTIPLY },
  1024. { "premultiplied", BLENDALPHA_PREMULTIPLIED },
  1025. };
  1026. StringMap<Graphics::BlendAlpha, Graphics::BLENDALPHA_MAX_ENUM> Graphics::blendAlphaModes(Graphics::blendAlphaEntries, sizeof(Graphics::blendAlphaEntries));
  1027. StringMap<Graphics::LineStyle, Graphics::LINE_MAX_ENUM>::Entry Graphics::lineStyleEntries[] =
  1028. {
  1029. { "smooth", LINE_SMOOTH },
  1030. { "rough", LINE_ROUGH }
  1031. };
  1032. StringMap<Graphics::LineStyle, Graphics::LINE_MAX_ENUM> Graphics::lineStyles(Graphics::lineStyleEntries, sizeof(Graphics::lineStyleEntries));
  1033. StringMap<Graphics::LineJoin, Graphics::LINE_JOIN_MAX_ENUM>::Entry Graphics::lineJoinEntries[] =
  1034. {
  1035. { "none", LINE_JOIN_NONE },
  1036. { "miter", LINE_JOIN_MITER },
  1037. { "bevel", LINE_JOIN_BEVEL }
  1038. };
  1039. StringMap<Graphics::LineJoin, Graphics::LINE_JOIN_MAX_ENUM> Graphics::lineJoins(Graphics::lineJoinEntries, sizeof(Graphics::lineJoinEntries));
  1040. StringMap<Graphics::StencilAction, Graphics::STENCIL_MAX_ENUM>::Entry Graphics::stencilActionEntries[] =
  1041. {
  1042. { "replace", STENCIL_REPLACE },
  1043. { "increment", STENCIL_INCREMENT },
  1044. { "decrement", STENCIL_DECREMENT },
  1045. { "incrementwrap", STENCIL_INCREMENT_WRAP },
  1046. { "decrementwrap", STENCIL_DECREMENT_WRAP },
  1047. { "invert", STENCIL_INVERT },
  1048. };
  1049. StringMap<Graphics::StencilAction, Graphics::STENCIL_MAX_ENUM> Graphics::stencilActions(Graphics::stencilActionEntries, sizeof(Graphics::stencilActionEntries));
  1050. StringMap<Graphics::CompareMode, Graphics::COMPARE_MAX_ENUM>::Entry Graphics::compareModeEntries[] =
  1051. {
  1052. { "less", COMPARE_LESS },
  1053. { "lequal", COMPARE_LEQUAL },
  1054. { "equal", COMPARE_EQUAL },
  1055. { "gequal", COMPARE_GEQUAL },
  1056. { "greater", COMPARE_GREATER },
  1057. { "notequal", COMPARE_NOTEQUAL },
  1058. { "always", COMPARE_ALWAYS },
  1059. };
  1060. StringMap<Graphics::CompareMode, Graphics::COMPARE_MAX_ENUM> Graphics::compareModes(Graphics::compareModeEntries, sizeof(Graphics::compareModeEntries));
  1061. StringMap<Graphics::Feature, Graphics::FEATURE_MAX_ENUM>::Entry Graphics::featureEntries[] =
  1062. {
  1063. { "multicanvasformats", FEATURE_MULTI_CANVAS_FORMATS },
  1064. { "clampzero", FEATURE_CLAMP_ZERO },
  1065. { "lighten", FEATURE_LIGHTEN },
  1066. { "fullnpot", FEATURE_FULL_NPOT },
  1067. { "pixelshaderhighp", FEATURE_PIXEL_SHADER_HIGHP },
  1068. { "glsl3", FEATURE_GLSL3 },
  1069. { "instancing", FEATURE_INSTANCING },
  1070. };
  1071. StringMap<Graphics::Feature, Graphics::FEATURE_MAX_ENUM> Graphics::features(Graphics::featureEntries, sizeof(Graphics::featureEntries));
  1072. StringMap<Graphics::SystemLimit, Graphics::LIMIT_MAX_ENUM>::Entry Graphics::systemLimitEntries[] =
  1073. {
  1074. { "pointsize", LIMIT_POINT_SIZE },
  1075. { "texturesize", LIMIT_TEXTURE_SIZE },
  1076. { "multicanvas", LIMIT_MULTI_CANVAS },
  1077. { "canvasmsaa", LIMIT_CANVAS_MSAA },
  1078. { "anisotropy", LIMIT_ANISOTROPY },
  1079. };
  1080. StringMap<Graphics::SystemLimit, Graphics::LIMIT_MAX_ENUM> Graphics::systemLimits(Graphics::systemLimitEntries, sizeof(Graphics::systemLimitEntries));
  1081. StringMap<Graphics::StackType, Graphics::STACK_MAX_ENUM>::Entry Graphics::stackTypeEntries[] =
  1082. {
  1083. { "all", STACK_ALL },
  1084. { "transform", STACK_TRANSFORM },
  1085. };
  1086. StringMap<Graphics::StackType, Graphics::STACK_MAX_ENUM> Graphics::stackTypes(Graphics::stackTypeEntries, sizeof(Graphics::stackTypeEntries));
  1087. } // graphics
  1088. } // love