Graphics.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917
  1. /**
  2. * Copyright (c) 2006-2020 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 "Buffer.h"
  23. #include "math/MathModule.h"
  24. #include "data/DataModule.h"
  25. #include "Polyline.h"
  26. #include "font/Font.h"
  27. #include "window/Window.h"
  28. #include "SpriteBatch.h"
  29. #include "ParticleSystem.h"
  30. #include "Font.h"
  31. #include "Video.h"
  32. #include "Text.h"
  33. #include "common/deprecation.h"
  34. // C++
  35. #include <algorithm>
  36. #include <stdlib.h>
  37. namespace love
  38. {
  39. namespace graphics
  40. {
  41. static bool gammaCorrect = false;
  42. static bool debugMode = false;
  43. static bool debugModeQueried = false;
  44. void setGammaCorrect(bool gammacorrect)
  45. {
  46. gammaCorrect = gammacorrect;
  47. }
  48. bool isGammaCorrect()
  49. {
  50. return gammaCorrect;
  51. }
  52. void gammaCorrectColor(Colorf &c)
  53. {
  54. if (isGammaCorrect())
  55. {
  56. c.r = math::gammaToLinear(c.r);
  57. c.g = math::gammaToLinear(c.g);
  58. c.b = math::gammaToLinear(c.b);
  59. }
  60. }
  61. Colorf gammaCorrectColor(const Colorf &c)
  62. {
  63. Colorf r = c;
  64. gammaCorrectColor(r);
  65. return r;
  66. }
  67. void unGammaCorrectColor(Colorf &c)
  68. {
  69. if (isGammaCorrect())
  70. {
  71. c.r = math::linearToGamma(c.r);
  72. c.g = math::linearToGamma(c.g);
  73. c.b = math::linearToGamma(c.b);
  74. }
  75. }
  76. Colorf unGammaCorrectColor(const Colorf &c)
  77. {
  78. Colorf r = c;
  79. unGammaCorrectColor(r);
  80. return r;
  81. }
  82. bool isDebugEnabled()
  83. {
  84. if (!debugModeQueried)
  85. {
  86. const char *debugenv = getenv("LOVE_GRAPHICS_DEBUG");
  87. debugMode = debugenv != nullptr && debugenv[0] != '0';
  88. debugModeQueried = true;
  89. }
  90. return debugMode;
  91. }
  92. love::Type Graphics::type("graphics", &Module::type);
  93. Graphics::DefaultShaderCode Graphics::defaultShaderCode[Shader::STANDARD_MAX_ENUM][Shader::LANGUAGE_MAX_ENUM][2];
  94. Graphics::Graphics()
  95. : width(0)
  96. , height(0)
  97. , pixelWidth(0)
  98. , pixelHeight(0)
  99. , created(false)
  100. , active(true)
  101. , writingToStencil(false)
  102. , streamBufferState()
  103. , projectionMatrix()
  104. , canvasSwitchCount(0)
  105. , drawCalls(0)
  106. , drawCallsBatched(0)
  107. , quadIndexBuffer(nullptr)
  108. , capabilities()
  109. , cachedShaderStages()
  110. {
  111. transformStack.reserve(16);
  112. transformStack.push_back(Matrix4());
  113. pixelScaleStack.reserve(16);
  114. pixelScaleStack.push_back(1);
  115. states.reserve(10);
  116. states.push_back(DisplayState());
  117. if (!Shader::initialize())
  118. throw love::Exception("Shader support failed to initialize!");
  119. }
  120. Graphics::~Graphics()
  121. {
  122. delete quadIndexBuffer;
  123. // Clean up standard shaders before the active shader. If we do it after,
  124. // the active shader may try to activate a standard shader when deactivating
  125. // itself, which will cause problems since it calls Graphics methods in the
  126. // Graphics destructor.
  127. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++)
  128. {
  129. if (Shader::standardShaders[i])
  130. {
  131. Shader::standardShaders[i]->release();
  132. Shader::standardShaders[i] = nullptr;
  133. }
  134. }
  135. states.clear();
  136. defaultFont.set(nullptr);
  137. delete streamBufferState.vb[0];
  138. delete streamBufferState.vb[1];
  139. delete streamBufferState.indexBuffer;
  140. for (int i = 0; i < (int) ShaderStage::STAGE_MAX_ENUM; i++)
  141. cachedShaderStages[i].clear();
  142. Shader::deinitialize();
  143. }
  144. void Graphics::createQuadIndexBuffer()
  145. {
  146. if (quadIndexBuffer != nullptr)
  147. return;
  148. size_t size = sizeof(uint16) * (LOVE_UINT16_MAX / 4) * 6;
  149. quadIndexBuffer = newBuffer(size, nullptr, BUFFER_INDEX, vertex::USAGE_STATIC, 0);
  150. Buffer::Mapper map(*quadIndexBuffer);
  151. vertex::fillIndices(vertex::TriangleIndexMode::QUADS, 0, LOVE_UINT16_MAX, (uint16 *) map.get());
  152. }
  153. Quad *Graphics::newQuad(Quad::Viewport v, double sw, double sh)
  154. {
  155. return new Quad(v, sw, sh);
  156. }
  157. Font *Graphics::newFont(love::font::Rasterizer *data)
  158. {
  159. return new Font(data, states.back().defaultSamplerState);
  160. }
  161. Font *Graphics::newDefaultFont(int size, font::TrueTypeRasterizer::Hinting hinting)
  162. {
  163. auto fontmodule = Module::getInstance<font::Font>(M_FONT);
  164. if (!fontmodule)
  165. throw love::Exception("Font module has not been loaded.");
  166. StrongRef<font::Rasterizer> r(fontmodule->newTrueTypeRasterizer(size, hinting), Acquire::NORETAIN);
  167. return newFont(r.get());
  168. }
  169. Video *Graphics::newVideo(love::video::VideoStream *stream, float dpiscale)
  170. {
  171. return new Video(this, stream, dpiscale);
  172. }
  173. love::graphics::SpriteBatch *Graphics::newSpriteBatch(Texture *texture, int size, vertex::Usage usage)
  174. {
  175. return new SpriteBatch(this, texture, size, usage);
  176. }
  177. love::graphics::ParticleSystem *Graphics::newParticleSystem(Texture *texture, int size)
  178. {
  179. return new ParticleSystem(texture, size);
  180. }
  181. ShaderStage *Graphics::newShaderStage(ShaderStage::StageType stage, const std::string &optsource)
  182. {
  183. if (stage == ShaderStage::STAGE_MAX_ENUM)
  184. throw love::Exception("Invalid shader stage.");
  185. const std::string &source = optsource.empty() ? getCurrentDefaultShaderCode().source[stage] : optsource;
  186. ShaderStage *s = nullptr;
  187. std::string cachekey;
  188. if (!source.empty())
  189. {
  190. data::HashFunction::Value hashvalue;
  191. data::hash(data::HashFunction::FUNCTION_SHA1, source.c_str(), source.size(), hashvalue);
  192. cachekey = std::string(hashvalue.data, hashvalue.size);
  193. auto it = cachedShaderStages[stage].find(cachekey);
  194. if (it != cachedShaderStages[stage].end())
  195. {
  196. s = it->second;
  197. s->retain();
  198. }
  199. }
  200. if (s == nullptr)
  201. {
  202. s = newShaderStageInternal(stage, cachekey, source, getRenderer() == RENDERER_OPENGLES);
  203. if (!cachekey.empty())
  204. cachedShaderStages[stage][cachekey] = s;
  205. }
  206. return s;
  207. }
  208. Shader *Graphics::newShader(const std::string &vertex, const std::string &pixel)
  209. {
  210. if (vertex.empty() && pixel.empty())
  211. throw love::Exception("Error creating shader: no source code!");
  212. StrongRef<ShaderStage> vertexstage(newShaderStage(ShaderStage::STAGE_VERTEX, vertex), Acquire::NORETAIN);
  213. StrongRef<ShaderStage> pixelstage(newShaderStage(ShaderStage::STAGE_PIXEL, pixel), Acquire::NORETAIN);
  214. return newShaderInternal(vertexstage.get(), pixelstage.get());
  215. }
  216. Mesh *Graphics::newMesh(const std::vector<Vertex> &vertices, PrimitiveType drawmode, vertex::Usage usage)
  217. {
  218. return newMesh(Mesh::getDefaultVertexFormat(), &vertices[0], vertices.size() * sizeof(Vertex), drawmode, usage);
  219. }
  220. Mesh *Graphics::newMesh(int vertexcount, PrimitiveType drawmode, vertex::Usage usage)
  221. {
  222. return newMesh(Mesh::getDefaultVertexFormat(), vertexcount, drawmode, usage);
  223. }
  224. love::graphics::Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, int vertexcount, PrimitiveType drawmode, vertex::Usage usage)
  225. {
  226. return new Mesh(this, vertexformat, vertexcount, drawmode, usage);
  227. }
  228. love::graphics::Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, const void *data, size_t datasize, PrimitiveType drawmode, vertex::Usage usage)
  229. {
  230. return new Mesh(this, vertexformat, data, datasize, drawmode, usage);
  231. }
  232. love::graphics::Text *Graphics::newText(graphics::Font *font, const std::vector<Font::ColoredString> &text)
  233. {
  234. return new Text(font, text);
  235. }
  236. void Graphics::cleanupCachedShaderStage(ShaderStage::StageType type, const std::string &hashkey)
  237. {
  238. cachedShaderStages[type].erase(hashkey);
  239. }
  240. bool Graphics::validateShader(bool gles, const std::string &vertex, const std::string &pixel, std::string &err)
  241. {
  242. if (vertex.empty() && pixel.empty())
  243. {
  244. err = "Error validating shader: no source code!";
  245. return false;
  246. }
  247. StrongRef<ShaderStage> vertexstage;
  248. StrongRef<ShaderStage> pixelstage;
  249. // Don't use cached shader stages, since the gles flag may not match the
  250. // current renderer.
  251. if (!vertex.empty())
  252. vertexstage.set(new ShaderStageForValidation(this, ShaderStage::STAGE_VERTEX, vertex, gles), Acquire::NORETAIN);
  253. if (!pixel.empty())
  254. pixelstage.set(new ShaderStageForValidation(this, ShaderStage::STAGE_PIXEL, pixel, gles), Acquire::NORETAIN);
  255. return Shader::validate(vertexstage.get(), pixelstage.get(), err);
  256. }
  257. int Graphics::getWidth() const
  258. {
  259. return width;
  260. }
  261. int Graphics::getHeight() const
  262. {
  263. return height;
  264. }
  265. int Graphics::getPixelWidth() const
  266. {
  267. return pixelWidth;
  268. }
  269. int Graphics::getPixelHeight() const
  270. {
  271. return pixelHeight;
  272. }
  273. double Graphics::getCurrentDPIScale() const
  274. {
  275. const auto &rt = states.back().renderTargets.getFirstTarget();
  276. if (rt.canvas.get())
  277. return rt.canvas->getDPIScale();
  278. return getScreenDPIScale();
  279. }
  280. double Graphics::getScreenDPIScale() const
  281. {
  282. return (double) getPixelHeight() / (double) getHeight();
  283. }
  284. bool Graphics::isCreated() const
  285. {
  286. return created;
  287. }
  288. bool Graphics::isActive() const
  289. {
  290. // The graphics module is only completely 'active' if there's a window, a
  291. // context, and the active variable is set.
  292. auto window = getInstance<love::window::Window>(M_WINDOW);
  293. return active && isCreated() && window != nullptr && window->isOpen();
  294. }
  295. void Graphics::reset()
  296. {
  297. DisplayState s;
  298. stopDrawToStencilBuffer();
  299. restoreState(s);
  300. origin();
  301. }
  302. /**
  303. * State functions.
  304. **/
  305. void Graphics::restoreState(const DisplayState &s)
  306. {
  307. setColor(s.color);
  308. setBackgroundColor(s.backgroundColor);
  309. setBlendState(s.blend);
  310. setLineWidth(s.lineWidth);
  311. setLineStyle(s.lineStyle);
  312. setLineJoin(s.lineJoin);
  313. setPointSize(s.pointSize);
  314. if (s.scissor)
  315. setScissor(s.scissorRect);
  316. else
  317. setScissor();
  318. setStencilTest(s.stencilCompare, s.stencilTestValue);
  319. setDepthMode(s.depthTest, s.depthWrite);
  320. setMeshCullMode(s.meshCullMode);
  321. setFrontFaceWinding(s.winding);
  322. setFont(s.font.get());
  323. setShader(s.shader.get());
  324. setCanvas(s.renderTargets);
  325. setColorMask(s.colorMask);
  326. setWireframe(s.wireframe);
  327. setDefaultSamplerState(s.defaultSamplerState);
  328. }
  329. void Graphics::restoreStateChecked(const DisplayState &s)
  330. {
  331. const DisplayState &cur = states.back();
  332. if (s.color != cur.color)
  333. setColor(s.color);
  334. setBackgroundColor(s.backgroundColor);
  335. if (!(s.blend == cur.blend))
  336. setBlendState(s.blend);
  337. // These are just simple assignments.
  338. setLineWidth(s.lineWidth);
  339. setLineStyle(s.lineStyle);
  340. setLineJoin(s.lineJoin);
  341. if (s.pointSize != cur.pointSize)
  342. setPointSize(s.pointSize);
  343. if (s.scissor != cur.scissor || (s.scissor && !(s.scissorRect == cur.scissorRect)))
  344. {
  345. if (s.scissor)
  346. setScissor(s.scissorRect);
  347. else
  348. setScissor();
  349. }
  350. if (s.stencilCompare != cur.stencilCompare || s.stencilTestValue != cur.stencilTestValue)
  351. setStencilTest(s.stencilCompare, s.stencilTestValue);
  352. if (s.depthTest != cur.depthTest || s.depthWrite != cur.depthWrite)
  353. setDepthMode(s.depthTest, s.depthWrite);
  354. setMeshCullMode(s.meshCullMode);
  355. if (s.winding != cur.winding)
  356. setFrontFaceWinding(s.winding);
  357. setFont(s.font.get());
  358. setShader(s.shader.get());
  359. const auto &sRTs = s.renderTargets;
  360. const auto &curRTs = cur.renderTargets;
  361. bool canvaseschanged = sRTs.colors.size() != curRTs.colors.size();
  362. if (!canvaseschanged)
  363. {
  364. for (size_t i = 0; i < sRTs.colors.size() && i < curRTs.colors.size(); i++)
  365. {
  366. if (sRTs.colors[i] != curRTs.colors[i])
  367. {
  368. canvaseschanged = true;
  369. break;
  370. }
  371. }
  372. if (!canvaseschanged && sRTs.depthStencil != curRTs.depthStencil)
  373. canvaseschanged = true;
  374. if (sRTs.temporaryRTFlags != curRTs.temporaryRTFlags)
  375. canvaseschanged = true;
  376. }
  377. if (canvaseschanged)
  378. setCanvas(s.renderTargets);
  379. if (s.colorMask != cur.colorMask)
  380. setColorMask(s.colorMask);
  381. if (s.wireframe != cur.wireframe)
  382. setWireframe(s.wireframe);
  383. setDefaultSamplerState(s.defaultSamplerState);
  384. }
  385. Colorf Graphics::getColor() const
  386. {
  387. return states.back().color;
  388. }
  389. void Graphics::setBackgroundColor(Colorf c)
  390. {
  391. states.back().backgroundColor = c;
  392. }
  393. Colorf Graphics::getBackgroundColor() const
  394. {
  395. return states.back().backgroundColor;
  396. }
  397. void Graphics::checkSetDefaultFont()
  398. {
  399. // We don't create or set the default Font if an existing font is in use.
  400. if (states.back().font.get() != nullptr)
  401. return;
  402. // Create a new default font if we don't have one yet.
  403. if (!defaultFont.get())
  404. defaultFont.set(newDefaultFont(12, font::TrueTypeRasterizer::HINTING_NORMAL), Acquire::NORETAIN);
  405. states.back().font.set(defaultFont.get());
  406. }
  407. void Graphics::setFont(love::graphics::Font *font)
  408. {
  409. // We don't need to set a default font here if null is passed in, since we
  410. // only care about the default font in getFont and print.
  411. DisplayState &state = states.back();
  412. state.font.set(font);
  413. }
  414. love::graphics::Font *Graphics::getFont()
  415. {
  416. checkSetDefaultFont();
  417. return states.back().font.get();
  418. }
  419. void Graphics::setShader(love::graphics::Shader *shader)
  420. {
  421. if (shader == nullptr)
  422. return setShader();
  423. shader->attach();
  424. states.back().shader.set(shader);
  425. }
  426. void Graphics::setShader()
  427. {
  428. Shader::attachDefault(Shader::STANDARD_DEFAULT);
  429. states.back().shader.set(nullptr);
  430. }
  431. love::graphics::Shader *Graphics::getShader() const
  432. {
  433. return states.back().shader.get();
  434. }
  435. void Graphics::setCanvas(RenderTarget rt, uint32 temporaryRTFlags)
  436. {
  437. if (rt.canvas == nullptr)
  438. return setCanvas();
  439. RenderTargets rts;
  440. rts.colors.push_back(rt);
  441. rts.temporaryRTFlags = temporaryRTFlags;
  442. setCanvas(rts);
  443. }
  444. void Graphics::setCanvas(const RenderTargetsStrongRef &rts)
  445. {
  446. RenderTargets targets;
  447. targets.colors.reserve(rts.colors.size());
  448. for (const auto &rt : rts.colors)
  449. targets.colors.emplace_back(rt.canvas.get(), rt.slice, rt.mipmap);
  450. targets.depthStencil = RenderTarget(rts.depthStencil.canvas, rts.depthStencil.slice, rts.depthStencil.mipmap);
  451. targets.temporaryRTFlags = rts.temporaryRTFlags;
  452. return setCanvas(targets);
  453. }
  454. void Graphics::setCanvas(const RenderTargets &rts)
  455. {
  456. DisplayState &state = states.back();
  457. int ncanvases = (int) rts.colors.size();
  458. RenderTarget firsttarget = rts.getFirstTarget();
  459. love::graphics::Canvas *firstcanvas = firsttarget.canvas;
  460. if (firstcanvas == nullptr)
  461. return setCanvas();
  462. const auto &prevRTs = state.renderTargets;
  463. if (ncanvases == (int) prevRTs.colors.size())
  464. {
  465. bool modified = false;
  466. for (int i = 0; i < ncanvases; i++)
  467. {
  468. if (rts.colors[i] != prevRTs.colors[i])
  469. {
  470. modified = true;
  471. break;
  472. }
  473. }
  474. if (!modified && rts.depthStencil != prevRTs.depthStencil)
  475. modified = true;
  476. if (rts.temporaryRTFlags != prevRTs.temporaryRTFlags)
  477. modified = true;
  478. if (!modified)
  479. return;
  480. }
  481. if (ncanvases > capabilities.limits[LIMIT_MULTI_CANVAS])
  482. throw love::Exception("This system can't simultaneously render to %d canvases.", ncanvases);
  483. bool multiformatsupported = capabilities.features[FEATURE_MULTI_CANVAS_FORMATS];
  484. PixelFormat firstcolorformat = PIXELFORMAT_UNKNOWN;
  485. if (!rts.colors.empty())
  486. firstcolorformat = rts.colors[0].canvas->getPixelFormat();
  487. if (isPixelFormatDepthStencil(firstcolorformat))
  488. throw love::Exception("Depth/stencil format Canvases must be used with the 'depthstencil' field of the table passed into setCanvas.");
  489. if (firsttarget.mipmap < 0 || firsttarget.mipmap >= firstcanvas->getMipmapCount())
  490. throw love::Exception("Invalid mipmap level %d.", firsttarget.mipmap + 1);
  491. if (!firstcanvas->isValidSlice(firsttarget.slice))
  492. throw love::Exception("Invalid slice index: %d.", firsttarget.slice + 1);
  493. bool hasSRGBcanvas = firstcolorformat == PIXELFORMAT_sRGBA8_UNORM;
  494. int pixelw = firstcanvas->getPixelWidth(firsttarget.mipmap);
  495. int pixelh = firstcanvas->getPixelHeight(firsttarget.mipmap);
  496. int reqmsaa = firstcanvas->getRequestedMSAA();
  497. for (int i = 1; i < ncanvases; i++)
  498. {
  499. love::graphics::Canvas *c = rts.colors[i].canvas;
  500. PixelFormat format = c->getPixelFormat();
  501. int mip = rts.colors[i].mipmap;
  502. int slice = rts.colors[i].slice;
  503. if (mip < 0 || mip >= c->getMipmapCount())
  504. throw love::Exception("Invalid mipmap level %d.", mip + 1);
  505. if (!c->isValidSlice(slice))
  506. throw love::Exception("Invalid slice index: %d.", slice + 1);
  507. if (c->getPixelWidth(mip) != pixelw || c->getPixelHeight(mip) != pixelh)
  508. throw love::Exception("All canvases must have the same pixel dimensions.");
  509. if (!multiformatsupported && format != firstcolorformat)
  510. throw love::Exception("This system doesn't support multi-canvas rendering with different canvas formats.");
  511. if (c->getRequestedMSAA() != reqmsaa)
  512. throw love::Exception("All Canvases must have the same MSAA value.");
  513. if (isPixelFormatDepthStencil(format))
  514. throw love::Exception("Depth/stencil format Canvases must be used with the 'depthstencil' field of the table passed into setCanvas.");
  515. if (format == PIXELFORMAT_sRGBA8_UNORM)
  516. hasSRGBcanvas = true;
  517. }
  518. if (rts.depthStencil.canvas != nullptr)
  519. {
  520. love::graphics::Canvas *c = rts.depthStencil.canvas;
  521. int mip = rts.depthStencil.mipmap;
  522. int slice = rts.depthStencil.slice;
  523. if (!isPixelFormatDepthStencil(c->getPixelFormat()))
  524. throw love::Exception("Only depth/stencil format Canvases can be used with the 'depthstencil' field of the table passed into setCanvas.");
  525. if (c->getPixelWidth(mip) != pixelw || c->getPixelHeight(mip) != pixelh)
  526. throw love::Exception("All canvases must have the same pixel dimensions.");
  527. if (c->getRequestedMSAA() != firstcanvas->getRequestedMSAA())
  528. throw love::Exception("All Canvases must have the same MSAA value.");
  529. if (mip < 0 || mip >= c->getMipmapCount())
  530. throw love::Exception("Invalid mipmap level %d.", mip + 1);
  531. if (!c->isValidSlice(slice))
  532. throw love::Exception("Invalid slice index: %d.", slice + 1);
  533. }
  534. int w = firstcanvas->getWidth(firsttarget.mipmap);
  535. int h = firstcanvas->getHeight(firsttarget.mipmap);
  536. flushStreamDraws();
  537. if (rts.depthStencil.canvas == nullptr && rts.temporaryRTFlags != 0)
  538. {
  539. bool wantsdepth = (rts.temporaryRTFlags & TEMPORARY_RT_DEPTH) != 0;
  540. bool wantsstencil = (rts.temporaryRTFlags & TEMPORARY_RT_STENCIL) != 0;
  541. PixelFormat dsformat = PIXELFORMAT_STENCIL8;
  542. if (wantsdepth && wantsstencil)
  543. dsformat = PIXELFORMAT_DEPTH24_UNORM_STENCIL8;
  544. else if (wantsdepth && isPixelFormatSupported(PIXELFORMAT_DEPTH24_UNORM, true, false, false))
  545. dsformat = PIXELFORMAT_DEPTH24_UNORM;
  546. else if (wantsdepth)
  547. dsformat = PIXELFORMAT_DEPTH16_UNORM;
  548. else if (wantsstencil)
  549. dsformat = PIXELFORMAT_STENCIL8;
  550. // We want setCanvasInternal to have a pointer to the temporary RT, but
  551. // we don't want to directly store it in the main graphics state.
  552. RenderTargets realRTs = rts;
  553. realRTs.depthStencil.canvas = getTemporaryCanvas(dsformat, pixelw, pixelh, reqmsaa);
  554. realRTs.depthStencil.slice = 0;
  555. setCanvasInternal(realRTs, w, h, pixelw, pixelh, hasSRGBcanvas);
  556. }
  557. else
  558. setCanvasInternal(rts, w, h, pixelw, pixelh, hasSRGBcanvas);
  559. RenderTargetsStrongRef refs;
  560. refs.colors.reserve(rts.colors.size());
  561. for (auto c : rts.colors)
  562. refs.colors.emplace_back(c.canvas, c.slice, c.mipmap);
  563. refs.depthStencil = RenderTargetStrongRef(rts.depthStencil.canvas, rts.depthStencil.slice);
  564. refs.temporaryRTFlags = rts.temporaryRTFlags;
  565. std::swap(state.renderTargets, refs);
  566. canvasSwitchCount++;
  567. }
  568. void Graphics::setCanvas()
  569. {
  570. DisplayState &state = states.back();
  571. if (state.renderTargets.colors.empty() && state.renderTargets.depthStencil.canvas == nullptr)
  572. return;
  573. flushStreamDraws();
  574. setCanvasInternal(RenderTargets(), width, height, pixelWidth, pixelHeight, isGammaCorrect());
  575. state.renderTargets = RenderTargetsStrongRef();
  576. canvasSwitchCount++;
  577. }
  578. Graphics::RenderTargets Graphics::getCanvas() const
  579. {
  580. const auto &curRTs = states.back().renderTargets;
  581. RenderTargets rts;
  582. rts.colors.reserve(curRTs.colors.size());
  583. for (const auto &rt : curRTs.colors)
  584. rts.colors.emplace_back(rt.canvas.get(), rt.slice, rt.mipmap);
  585. rts.depthStencil = RenderTarget(curRTs.depthStencil.canvas, curRTs.depthStencil.slice, curRTs.depthStencil.mipmap);
  586. rts.temporaryRTFlags = curRTs.temporaryRTFlags;
  587. return rts;
  588. }
  589. bool Graphics::isCanvasActive() const
  590. {
  591. const auto &rts = states.back().renderTargets;
  592. return !rts.colors.empty() || rts.depthStencil.canvas != nullptr;
  593. }
  594. bool Graphics::isCanvasActive(love::graphics::Canvas *canvas) const
  595. {
  596. const auto &rts = states.back().renderTargets;
  597. for (const auto &rt : rts.colors)
  598. {
  599. if (rt.canvas.get() == canvas)
  600. return true;
  601. }
  602. if (rts.depthStencil.canvas.get() == canvas)
  603. return true;
  604. return false;
  605. }
  606. bool Graphics::isCanvasActive(Canvas *canvas, int slice) const
  607. {
  608. const auto &rts = states.back().renderTargets;
  609. for (const auto &rt : rts.colors)
  610. {
  611. if (rt.canvas.get() == canvas && rt.slice == slice)
  612. return true;
  613. }
  614. if (rts.depthStencil.canvas.get() == canvas && rts.depthStencil.slice == slice)
  615. return true;
  616. return false;
  617. }
  618. Canvas *Graphics::getTemporaryCanvas(PixelFormat format, int w, int h, int samples)
  619. {
  620. love::graphics::Canvas *canvas = nullptr;
  621. for (TemporaryCanvas &temp : temporaryCanvases)
  622. {
  623. Canvas *c = temp.canvas;
  624. if (c->getPixelFormat() == format && c->getPixelWidth() == w
  625. && c->getPixelHeight() == h && c->getRequestedMSAA() == samples)
  626. {
  627. canvas = c;
  628. temp.framesSinceUse = 0;
  629. break;
  630. }
  631. }
  632. if (canvas == nullptr)
  633. {
  634. Canvas::Settings settings;
  635. settings.format = format;
  636. settings.width = w;
  637. settings.height = h;
  638. settings.msaa = samples;
  639. canvas = newCanvas(settings);
  640. temporaryCanvases.emplace_back(canvas);
  641. }
  642. return canvas;
  643. }
  644. void Graphics::intersectScissor(const Rect &rect)
  645. {
  646. Rect currect = states.back().scissorRect;
  647. if (!states.back().scissor)
  648. {
  649. currect.x = 0;
  650. currect.y = 0;
  651. currect.w = std::numeric_limits<int>::max();
  652. currect.h = std::numeric_limits<int>::max();
  653. }
  654. int x1 = std::max(currect.x, rect.x);
  655. int y1 = std::max(currect.y, rect.y);
  656. int x2 = std::min(currect.x + currect.w, rect.x + rect.w);
  657. int y2 = std::min(currect.y + currect.h, rect.y + rect.h);
  658. Rect newrect = {x1, y1, std::max(0, x2 - x1), std::max(0, y2 - y1)};
  659. setScissor(newrect);
  660. }
  661. bool Graphics::getScissor(Rect &rect) const
  662. {
  663. const DisplayState &state = states.back();
  664. rect = state.scissorRect;
  665. return state.scissor;
  666. }
  667. void Graphics::setStencilTest()
  668. {
  669. setStencilTest(COMPARE_ALWAYS, 0);
  670. }
  671. void Graphics::getStencilTest(CompareMode &compare, int &value) const
  672. {
  673. const DisplayState &state = states.back();
  674. compare = state.stencilCompare;
  675. value = state.stencilTestValue;
  676. }
  677. void Graphics::setDepthMode()
  678. {
  679. setDepthMode(COMPARE_ALWAYS, false);
  680. }
  681. void Graphics::getDepthMode(CompareMode &compare, bool &write) const
  682. {
  683. const DisplayState &state = states.back();
  684. compare = state.depthTest;
  685. write = state.depthWrite;
  686. }
  687. void Graphics::setMeshCullMode(CullMode cull)
  688. {
  689. // Handled inside the draw() graphics API implementations.
  690. states.back().meshCullMode = cull;
  691. }
  692. CullMode Graphics::getMeshCullMode() const
  693. {
  694. return states.back().meshCullMode;
  695. }
  696. vertex::Winding Graphics::getFrontFaceWinding() const
  697. {
  698. return states.back().winding;
  699. }
  700. ColorChannelMask Graphics::getColorMask() const
  701. {
  702. return states.back().colorMask;
  703. }
  704. void Graphics::setBlendMode(BlendMode mode, BlendAlpha alphamode)
  705. {
  706. if (alphamode == BLENDALPHA_MULTIPLY && !isAlphaMultiplyBlendSupported(mode))
  707. {
  708. const char *modestr = "unknown";
  709. love::graphics::getConstant(mode, modestr);
  710. throw love::Exception("The '%s' blend mode must be used with premultiplied alpha.", modestr);
  711. }
  712. setBlendState(computeBlendState(mode, alphamode));
  713. }
  714. BlendMode Graphics::getBlendMode(BlendAlpha &alphamode) const
  715. {
  716. return computeBlendMode(states.back().blend, alphamode);
  717. }
  718. const BlendState &Graphics::getBlendState() const
  719. {
  720. return states.back().blend;
  721. }
  722. void Graphics::setDefaultSamplerState(const SamplerState &s)
  723. {
  724. states.back().defaultSamplerState = s;
  725. }
  726. const SamplerState &Graphics::getDefaultSamplerState() const
  727. {
  728. return states.back().defaultSamplerState;
  729. }
  730. void Graphics::setLineWidth(float width)
  731. {
  732. states.back().lineWidth = width;
  733. }
  734. void Graphics::setLineStyle(Graphics::LineStyle style)
  735. {
  736. states.back().lineStyle = style;
  737. }
  738. void Graphics::setLineJoin(Graphics::LineJoin join)
  739. {
  740. states.back().lineJoin = join;
  741. }
  742. float Graphics::getLineWidth() const
  743. {
  744. return states.back().lineWidth;
  745. }
  746. Graphics::LineStyle Graphics::getLineStyle() const
  747. {
  748. return states.back().lineStyle;
  749. }
  750. Graphics::LineJoin Graphics::getLineJoin() const
  751. {
  752. return states.back().lineJoin;
  753. }
  754. float Graphics::getPointSize() const
  755. {
  756. return states.back().pointSize;
  757. }
  758. bool Graphics::isWireframe() const
  759. {
  760. return states.back().wireframe;
  761. }
  762. void Graphics::captureScreenshot(const ScreenshotInfo &info)
  763. {
  764. pendingScreenshotCallbacks.push_back(info);
  765. }
  766. Graphics::StreamVertexData Graphics::requestStreamDraw(const StreamDrawCommand &cmd)
  767. {
  768. using namespace vertex;
  769. StreamBufferState &state = streamBufferState;
  770. bool shouldflush = false;
  771. bool shouldresize = false;
  772. if (cmd.primitiveMode != state.primitiveMode
  773. || cmd.formats[0] != state.formats[0] || cmd.formats[1] != state.formats[1]
  774. || ((cmd.indexMode != TriangleIndexMode::NONE) != (state.indexCount > 0))
  775. || cmd.texture != state.texture
  776. || cmd.standardShaderType != state.standardShaderType)
  777. {
  778. shouldflush = true;
  779. }
  780. int totalvertices = state.vertexCount + cmd.vertexCount;
  781. // We only support uint16 index buffers for now.
  782. if (totalvertices > LOVE_UINT16_MAX && cmd.indexMode != TriangleIndexMode::NONE)
  783. shouldflush = true;
  784. int reqIndexCount = getIndexCount(cmd.indexMode, cmd.vertexCount);
  785. size_t reqIndexSize = reqIndexCount * sizeof(uint16);
  786. size_t newdatasizes[2] = {0, 0};
  787. size_t buffersizes[3] = {0, 0, 0};
  788. for (int i = 0; i < 2; i++)
  789. {
  790. if (cmd.formats[i] == CommonFormat::NONE)
  791. continue;
  792. size_t stride = getFormatStride(cmd.formats[i]);
  793. size_t datasize = stride * totalvertices;
  794. if (state.vbMap[i].data != nullptr && datasize > state.vbMap[i].size)
  795. shouldflush = true;
  796. if (datasize > state.vb[i]->getUsableSize())
  797. {
  798. buffersizes[i] = std::max(datasize, state.vb[i]->getSize() * 2);
  799. shouldresize = true;
  800. }
  801. newdatasizes[i] = stride * cmd.vertexCount;
  802. }
  803. if (cmd.indexMode != TriangleIndexMode::NONE)
  804. {
  805. size_t datasize = (state.indexCount + reqIndexCount) * sizeof(uint16);
  806. if (state.indexBufferMap.data != nullptr && datasize > state.indexBufferMap.size)
  807. shouldflush = true;
  808. if (datasize > state.indexBuffer->getUsableSize())
  809. {
  810. buffersizes[2] = std::max(datasize, state.indexBuffer->getSize() * 2);
  811. shouldresize = true;
  812. }
  813. }
  814. if (shouldflush || shouldresize)
  815. {
  816. flushStreamDraws();
  817. state.primitiveMode = cmd.primitiveMode;
  818. state.formats[0] = cmd.formats[0];
  819. state.formats[1] = cmd.formats[1];
  820. state.texture = cmd.texture;
  821. state.standardShaderType = cmd.standardShaderType;
  822. }
  823. if (state.vertexCount == 0 && Shader::isDefaultActive())
  824. Shader::attachDefault(state.standardShaderType);
  825. if (state.vertexCount == 0 && Shader::current != nullptr && cmd.texture != nullptr)
  826. Shader::current->checkMainTexture(cmd.texture);
  827. if (shouldresize)
  828. {
  829. for (int i = 0; i < 2; i++)
  830. {
  831. if (state.vb[i]->getSize() < buffersizes[i])
  832. {
  833. delete state.vb[i];
  834. state.vb[i] = newStreamBuffer(BUFFER_VERTEX, buffersizes[i]);
  835. }
  836. }
  837. if (state.indexBuffer->getSize() < buffersizes[2])
  838. {
  839. delete state.indexBuffer;
  840. state.indexBuffer = newStreamBuffer(BUFFER_INDEX, buffersizes[2]);
  841. }
  842. }
  843. if (cmd.indexMode != TriangleIndexMode::NONE)
  844. {
  845. if (state.indexBufferMap.data == nullptr)
  846. state.indexBufferMap = state.indexBuffer->map(reqIndexSize);
  847. uint16 *indices = (uint16 *) state.indexBufferMap.data;
  848. fillIndices(cmd.indexMode, state.vertexCount, cmd.vertexCount, indices);
  849. state.indexBufferMap.data += reqIndexSize;
  850. }
  851. StreamVertexData d;
  852. for (int i = 0; i < 2; i++)
  853. {
  854. if (newdatasizes[i] > 0)
  855. {
  856. if (state.vbMap[i].data == nullptr)
  857. state.vbMap[i] = state.vb[i]->map(newdatasizes[i]);
  858. d.stream[i] = state.vbMap[i].data;
  859. state.vbMap[i].data += newdatasizes[i];
  860. }
  861. }
  862. if (state.vertexCount > 0)
  863. drawCallsBatched++;
  864. state.vertexCount += cmd.vertexCount;
  865. state.indexCount += reqIndexCount;
  866. return d;
  867. }
  868. void Graphics::flushStreamDraws()
  869. {
  870. using namespace vertex;
  871. auto &sbstate = streamBufferState;
  872. if (sbstate.vertexCount == 0 && sbstate.indexCount == 0)
  873. return;
  874. Attributes attributes;
  875. BufferBindings buffers;
  876. size_t usedsizes[3] = {0, 0, 0};
  877. for (int i = 0; i < 2; i++)
  878. {
  879. if (sbstate.formats[i] == CommonFormat::NONE)
  880. continue;
  881. attributes.setCommonFormat(sbstate.formats[i], (uint8) i);
  882. usedsizes[i] = getFormatStride(sbstate.formats[i]) * sbstate.vertexCount;
  883. size_t offset = sbstate.vb[i]->unmap(usedsizes[i]);
  884. buffers.set(i, sbstate.vb[i], offset);
  885. sbstate.vbMap[i] = StreamBuffer::MapInfo();
  886. }
  887. if (attributes.enableBits == 0)
  888. return;
  889. Colorf nc = getColor();
  890. if (attributes.isEnabled(ATTRIB_COLOR))
  891. setColor(Colorf(1.0f, 1.0f, 1.0f, 1.0f));
  892. pushIdentityTransform();
  893. if (sbstate.indexCount > 0)
  894. {
  895. usedsizes[2] = sizeof(uint16) * sbstate.indexCount;
  896. DrawIndexedCommand cmd(&attributes, &buffers, sbstate.indexBuffer);
  897. cmd.primitiveType = sbstate.primitiveMode;
  898. cmd.indexCount = sbstate.indexCount;
  899. cmd.indexType = INDEX_UINT16;
  900. cmd.indexBufferOffset = sbstate.indexBuffer->unmap(usedsizes[2]);
  901. cmd.texture = sbstate.texture;
  902. draw(cmd);
  903. sbstate.indexBufferMap = StreamBuffer::MapInfo();
  904. }
  905. else
  906. {
  907. DrawCommand cmd(&attributes, &buffers);
  908. cmd.primitiveType = sbstate.primitiveMode;
  909. cmd.vertexStart = 0;
  910. cmd.vertexCount = sbstate.vertexCount;
  911. cmd.texture = sbstate.texture;
  912. draw(cmd);
  913. }
  914. for (int i = 0; i < 2; i++)
  915. {
  916. if (usedsizes[i] > 0)
  917. sbstate.vb[i]->markUsed(usedsizes[i]);
  918. }
  919. if (usedsizes[2] > 0)
  920. sbstate.indexBuffer->markUsed(usedsizes[2]);
  921. popTransform();
  922. if (attributes.isEnabled(ATTRIB_COLOR))
  923. setColor(nc);
  924. streamBufferState.vertexCount = 0;
  925. streamBufferState.indexCount = 0;
  926. }
  927. void Graphics::flushStreamDrawsGlobal()
  928. {
  929. Graphics *instance = getInstance<Graphics>(M_GRAPHICS);
  930. if (instance != nullptr)
  931. instance->flushStreamDraws();
  932. }
  933. /**
  934. * Drawing
  935. **/
  936. void Graphics::draw(Drawable *drawable, const Matrix4 &m)
  937. {
  938. drawable->draw(this, m);
  939. }
  940. void Graphics::draw(Texture *texture, Quad *quad, const Matrix4 &m)
  941. {
  942. texture->draw(this, quad, m);
  943. }
  944. void Graphics::drawLayer(Texture *texture, int layer, const Matrix4 &m)
  945. {
  946. texture->drawLayer(this, layer, m);
  947. }
  948. void Graphics::drawLayer(Texture *texture, int layer, Quad *quad, const Matrix4 &m)
  949. {
  950. texture->drawLayer(this, layer, quad, m);
  951. }
  952. void Graphics::drawInstanced(Mesh *mesh, const Matrix4 &m, int instancecount)
  953. {
  954. mesh->drawInstanced(this, m, instancecount);
  955. }
  956. void Graphics::print(const std::vector<Font::ColoredString> &str, const Matrix4 &m)
  957. {
  958. checkSetDefaultFont();
  959. if (states.back().font.get() != nullptr)
  960. print(str, states.back().font.get(), m);
  961. }
  962. void Graphics::print(const std::vector<Font::ColoredString> &str, Font *font, const Matrix4 &m)
  963. {
  964. font->print(this, str, m, states.back().color);
  965. }
  966. void Graphics::printf(const std::vector<Font::ColoredString> &str, float wrap, Font::AlignMode align, const Matrix4 &m)
  967. {
  968. checkSetDefaultFont();
  969. if (states.back().font.get() != nullptr)
  970. printf(str, states.back().font.get(), wrap, align, m);
  971. }
  972. void Graphics::printf(const std::vector<Font::ColoredString> &str, Font *font, float wrap, Font::AlignMode align, const Matrix4 &m)
  973. {
  974. font->printf(this, str, wrap, align, m, states.back().color);
  975. }
  976. /**
  977. * Primitives (points, shapes, lines).
  978. **/
  979. void Graphics::points(const Vector2 *positions, const Colorf *colors, size_t numpoints)
  980. {
  981. const Matrix4 &t = getTransform();
  982. bool is2D = t.isAffine2DTransform();
  983. StreamDrawCommand cmd;
  984. cmd.primitiveMode = PRIMITIVE_POINTS;
  985. cmd.formats[0] = vertex::getSinglePositionFormat(is2D);
  986. cmd.formats[1] = vertex::CommonFormat::RGBAub;
  987. cmd.vertexCount = (int) numpoints;
  988. StreamVertexData data = requestStreamDraw(cmd);
  989. if (is2D)
  990. t.transformXY((Vector2 *) data.stream[0], positions, cmd.vertexCount);
  991. else
  992. t.transformXY0((Vector3 *) data.stream[0], positions, cmd.vertexCount);
  993. Color32 *colordata = (Color32 *) data.stream[1];
  994. if (colors)
  995. {
  996. Colorf nc = getColor();
  997. gammaCorrectColor(nc);
  998. if (isGammaCorrect())
  999. {
  1000. for (int i = 0; i < cmd.vertexCount; i++)
  1001. {
  1002. Colorf ci = colors[i];
  1003. gammaCorrectColor(ci);
  1004. ci *= nc;
  1005. unGammaCorrectColor(ci);
  1006. colordata[i] = toColor32(ci);
  1007. }
  1008. }
  1009. else
  1010. {
  1011. for (int i = 0; i < cmd.vertexCount; i++)
  1012. colordata[i] = toColor32(nc * colors[i]);
  1013. }
  1014. }
  1015. else
  1016. {
  1017. Color32 c = toColor32(getColor());
  1018. for (int i = 0; i < cmd.vertexCount; i++)
  1019. colordata[i] = c;
  1020. }
  1021. }
  1022. int Graphics::calculateEllipsePoints(float rx, float ry) const
  1023. {
  1024. int points = (int) sqrtf(((rx + ry) / 2.0f) * 20.0f * (float) pixelScaleStack.back());
  1025. return std::max(points, 8);
  1026. }
  1027. void Graphics::polyline(const Vector2 *vertices, size_t count)
  1028. {
  1029. float halfwidth = getLineWidth() * 0.5f;
  1030. LineJoin linejoin = getLineJoin();
  1031. LineStyle linestyle = getLineStyle();
  1032. float pixelsize = 1.0f / std::max((float) pixelScaleStack.back(), 0.000001f);
  1033. if (linejoin == LINE_JOIN_NONE)
  1034. {
  1035. NoneJoinPolyline line;
  1036. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1037. line.draw(this);
  1038. }
  1039. else if (linejoin == LINE_JOIN_BEVEL)
  1040. {
  1041. BevelJoinPolyline line;
  1042. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1043. line.draw(this);
  1044. }
  1045. else if (linejoin == LINE_JOIN_MITER)
  1046. {
  1047. MiterJoinPolyline line;
  1048. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1049. line.draw(this);
  1050. }
  1051. }
  1052. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  1053. {
  1054. Vector2 coords[] = {Vector2(x,y), Vector2(x,y+h), Vector2(x+w,y+h), Vector2(x+w,y), Vector2(x,y)};
  1055. polygon(mode, coords, 5);
  1056. }
  1057. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry, int points)
  1058. {
  1059. if (rx == 0 || ry == 0)
  1060. {
  1061. rectangle(mode, x, y, w, h);
  1062. return;
  1063. }
  1064. // Radius values that are more than half the rectangle's size aren't handled
  1065. // correctly (for now)...
  1066. if (w >= 0.02f)
  1067. rx = std::min(rx, w / 2.0f - 0.01f);
  1068. if (h >= 0.02f)
  1069. ry = std::min(ry, h / 2.0f - 0.01f);
  1070. points = std::max(points / 4, 1);
  1071. const float half_pi = static_cast<float>(LOVE_M_PI / 2);
  1072. float angle_shift = half_pi / ((float) points + 1.0f);
  1073. int num_coords = (points + 2) * 4;
  1074. Vector2 *coords = getScratchBuffer<Vector2>(num_coords + 1);
  1075. float phi = .0f;
  1076. for (int i = 0; i <= points + 2; ++i, phi += angle_shift)
  1077. {
  1078. coords[i].x = x + rx * (1 - cosf(phi));
  1079. coords[i].y = y + ry * (1 - sinf(phi));
  1080. }
  1081. phi = half_pi;
  1082. for (int i = points + 2; i <= 2 * (points + 2); ++i, phi += angle_shift)
  1083. {
  1084. coords[i].x = x + w - rx * (1 + cosf(phi));
  1085. coords[i].y = y + ry * (1 - sinf(phi));
  1086. }
  1087. phi = 2 * half_pi;
  1088. for (int i = 2 * (points + 2); i <= 3 * (points + 2); ++i, phi += angle_shift)
  1089. {
  1090. coords[i].x = x + w - rx * (1 + cosf(phi));
  1091. coords[i].y = y + h - ry * (1 + sinf(phi));
  1092. }
  1093. phi = 3 * half_pi;
  1094. for (int i = 3 * (points + 2); i <= 4 * (points + 2); ++i, phi += angle_shift)
  1095. {
  1096. coords[i].x = x + rx * (1 - cosf(phi));
  1097. coords[i].y = y + h - ry * (1 + sinf(phi));
  1098. }
  1099. coords[num_coords] = coords[0];
  1100. polygon(mode, coords, num_coords + 1);
  1101. }
  1102. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry)
  1103. {
  1104. rectangle(mode, x, y, w, h, rx, ry, calculateEllipsePoints(rx, ry));
  1105. }
  1106. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  1107. {
  1108. ellipse(mode, x, y, radius, radius, points);
  1109. }
  1110. void Graphics::circle(DrawMode mode, float x, float y, float radius)
  1111. {
  1112. ellipse(mode, x, y, radius, radius);
  1113. }
  1114. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b, int points)
  1115. {
  1116. float two_pi = (float) (LOVE_M_PI * 2);
  1117. if (points <= 0) points = 1;
  1118. float angle_shift = (two_pi / points);
  1119. float phi = .0f;
  1120. // 1 extra point at the end for a closed loop, and 1 extra point at the
  1121. // start in filled mode for the vertex in the center of the ellipse.
  1122. int extrapoints = 1 + (mode == DRAW_FILL ? 1 : 0);
  1123. Vector2 *polygoncoords = getScratchBuffer<Vector2>(points + extrapoints);
  1124. Vector2 *coords = polygoncoords;
  1125. if (mode == DRAW_FILL)
  1126. {
  1127. coords[0].x = x;
  1128. coords[0].y = y;
  1129. coords++;
  1130. }
  1131. for (int i = 0; i < points; ++i, phi += angle_shift)
  1132. {
  1133. coords[i].x = x + a * cosf(phi);
  1134. coords[i].y = y + b * sinf(phi);
  1135. }
  1136. coords[points] = coords[0];
  1137. // Last argument to polygon(): don't skip the last vertex in fill mode.
  1138. polygon(mode, polygoncoords, points + extrapoints, false);
  1139. }
  1140. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b)
  1141. {
  1142. ellipse(mode, x, y, a, b, calculateEllipsePoints(a, b));
  1143. }
  1144. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2, int points)
  1145. {
  1146. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  1147. if (points <= 0 || angle1 == angle2)
  1148. return;
  1149. // Oh, you want to draw a circle?
  1150. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  1151. {
  1152. circle(drawmode, x, y, radius, points);
  1153. return;
  1154. }
  1155. float angle_shift = (angle2 - angle1) / points;
  1156. // Bail on precision issues.
  1157. if (angle_shift == 0.0)
  1158. return;
  1159. // Prevent the connecting line from being drawn if a closed line arc has a
  1160. // small angle. Avoids some visual issues when connected lines are at sharp
  1161. // angles, due to the miter line join drawing code.
  1162. if (drawmode == DRAW_LINE && arcmode == ARC_CLOSED && fabsf(angle1 - angle2) < LOVE_TORAD(4))
  1163. arcmode = ARC_OPEN;
  1164. // Quick fix for the last part of a filled open arc not being drawn (because
  1165. // polygon(DRAW_FILL, ...) doesn't work without a closed loop of vertices.)
  1166. if (drawmode == DRAW_FILL && arcmode == ARC_OPEN)
  1167. arcmode = ARC_CLOSED;
  1168. float phi = angle1;
  1169. Vector2 *coords = nullptr;
  1170. int num_coords = 0;
  1171. const auto createPoints = [&](Vector2 *coordinates)
  1172. {
  1173. for (int i = 0; i <= points; ++i, phi += angle_shift)
  1174. {
  1175. coordinates[i].x = x + radius * cosf(phi);
  1176. coordinates[i].y = y + radius * sinf(phi);
  1177. }
  1178. };
  1179. if (arcmode == ARC_PIE)
  1180. {
  1181. num_coords = points + 3;
  1182. coords = getScratchBuffer<Vector2>(num_coords);
  1183. coords[0] = coords[num_coords - 1] = Vector2(x, y);
  1184. createPoints(coords + 1);
  1185. }
  1186. else if (arcmode == ARC_OPEN)
  1187. {
  1188. num_coords = points + 1;
  1189. coords = getScratchBuffer<Vector2>(num_coords);
  1190. createPoints(coords);
  1191. }
  1192. else // ARC_CLOSED
  1193. {
  1194. num_coords = points + 2;
  1195. coords = getScratchBuffer<Vector2>(num_coords);
  1196. createPoints(coords);
  1197. // Connect the ends of the arc.
  1198. coords[num_coords - 1] = coords[0];
  1199. }
  1200. polygon(drawmode, coords, num_coords);
  1201. }
  1202. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2)
  1203. {
  1204. float points = (float) calculateEllipsePoints(radius, radius);
  1205. // The amount of points is based on the fraction of the circle created by the arc.
  1206. float angle = fabsf(angle1 - angle2);
  1207. if (angle < 2.0f * (float) LOVE_M_PI)
  1208. points *= angle / (2.0f * (float) LOVE_M_PI);
  1209. arc(drawmode, arcmode, x, y, radius, angle1, angle2, (int) (points + 0.5f));
  1210. }
  1211. void Graphics::polygon(DrawMode mode, const Vector2 *coords, size_t count, bool skipLastFilledVertex)
  1212. {
  1213. // coords is an array of a closed loop of vertices, i.e.
  1214. // coords[count-1] == coords[0]
  1215. if (mode == DRAW_LINE)
  1216. {
  1217. polyline(coords, count);
  1218. }
  1219. else
  1220. {
  1221. const Matrix4 &t = getTransform();
  1222. bool is2D = t.isAffine2DTransform();
  1223. StreamDrawCommand cmd;
  1224. cmd.formats[0] = vertex::getSinglePositionFormat(is2D);
  1225. cmd.formats[1] = vertex::CommonFormat::RGBAub;
  1226. cmd.indexMode = vertex::TriangleIndexMode::FAN;
  1227. cmd.vertexCount = (int)count - (skipLastFilledVertex ? 1 : 0);
  1228. StreamVertexData data = requestStreamDraw(cmd);
  1229. if (is2D)
  1230. t.transformXY((Vector2 *) data.stream[0], coords, cmd.vertexCount);
  1231. else
  1232. t.transformXY0((Vector3 *) data.stream[0], coords, cmd.vertexCount);
  1233. Color32 c = toColor32(getColor());
  1234. Color32 *colordata = (Color32 *) data.stream[1];
  1235. for (int i = 0; i < cmd.vertexCount; i++)
  1236. colordata[i] = c;
  1237. }
  1238. }
  1239. const Graphics::Capabilities &Graphics::getCapabilities() const
  1240. {
  1241. return capabilities;
  1242. }
  1243. Graphics::Stats Graphics::getStats() const
  1244. {
  1245. Stats stats;
  1246. getAPIStats(stats.shaderSwitches);
  1247. stats.drawCalls = drawCalls;
  1248. if (streamBufferState.vertexCount > 0)
  1249. stats.drawCalls++;
  1250. stats.canvasSwitches = canvasSwitchCount;
  1251. stats.drawCallsBatched = drawCallsBatched;
  1252. stats.canvases = Canvas::canvasCount;
  1253. stats.images = Image::imageCount;
  1254. stats.fonts = Font::fontCount;
  1255. stats.textureMemory = Texture::totalGraphicsMemory;
  1256. return stats;
  1257. }
  1258. size_t Graphics::getStackDepth() const
  1259. {
  1260. return stackTypeStack.size();
  1261. }
  1262. void Graphics::push(StackType type)
  1263. {
  1264. if (stackTypeStack.size() == MAX_USER_STACK_DEPTH)
  1265. throw Exception("Maximum stack depth reached (more pushes than pops?)");
  1266. pushTransform();
  1267. pixelScaleStack.push_back(pixelScaleStack.back());
  1268. if (type == STACK_ALL)
  1269. states.push_back(states.back());
  1270. stackTypeStack.push_back(type);
  1271. }
  1272. void Graphics::pop()
  1273. {
  1274. if (stackTypeStack.size() < 1)
  1275. throw Exception("Minimum stack depth reached (more pops than pushes?)");
  1276. popTransform();
  1277. pixelScaleStack.pop_back();
  1278. if (stackTypeStack.back() == STACK_ALL)
  1279. {
  1280. DisplayState &newstate = states[states.size() - 2];
  1281. restoreStateChecked(newstate);
  1282. // The last two states in the stack should be equal now.
  1283. states.pop_back();
  1284. }
  1285. stackTypeStack.pop_back();
  1286. }
  1287. /**
  1288. * Transform and stack functions.
  1289. **/
  1290. const Matrix4 &Graphics::getTransform() const
  1291. {
  1292. return transformStack.back();
  1293. }
  1294. const Matrix4 &Graphics::getProjection() const
  1295. {
  1296. return projectionMatrix;
  1297. }
  1298. void Graphics::pushTransform()
  1299. {
  1300. transformStack.push_back(transformStack.back());
  1301. }
  1302. void Graphics::pushIdentityTransform()
  1303. {
  1304. transformStack.push_back(Matrix4());
  1305. }
  1306. void Graphics::popTransform()
  1307. {
  1308. transformStack.pop_back();
  1309. }
  1310. void Graphics::rotate(float r)
  1311. {
  1312. transformStack.back().rotate(r);
  1313. }
  1314. void Graphics::scale(float x, float y)
  1315. {
  1316. transformStack.back().scale(x, y);
  1317. pixelScaleStack.back() *= (fabs(x) + fabs(y)) / 2.0;
  1318. }
  1319. void Graphics::translate(float x, float y)
  1320. {
  1321. transformStack.back().translate(x, y);
  1322. }
  1323. void Graphics::shear(float kx, float ky)
  1324. {
  1325. transformStack.back().shear(kx, ky);
  1326. }
  1327. void Graphics::origin()
  1328. {
  1329. transformStack.back().setIdentity();
  1330. pixelScaleStack.back() = 1;
  1331. }
  1332. void Graphics::applyTransform(love::math::Transform *transform)
  1333. {
  1334. Matrix4 &m = transformStack.back();
  1335. m *= transform->getMatrix();
  1336. float sx, sy;
  1337. m.getApproximateScale(sx, sy);
  1338. pixelScaleStack.back() = (sx + sy) / 2.0;
  1339. }
  1340. void Graphics::replaceTransform(love::math::Transform *transform)
  1341. {
  1342. const Matrix4 &m = transform->getMatrix();
  1343. transformStack.back() = m;
  1344. float sx, sy;
  1345. m.getApproximateScale(sx, sy);
  1346. pixelScaleStack.back() = (sx + sy) / 2.0;
  1347. }
  1348. Vector2 Graphics::transformPoint(Vector2 point)
  1349. {
  1350. Vector2 p;
  1351. transformStack.back().transformXY(&p, &point, 1);
  1352. return p;
  1353. }
  1354. Vector2 Graphics::inverseTransformPoint(Vector2 point)
  1355. {
  1356. Vector2 p;
  1357. // TODO: We should probably cache the inverse transform so we don't have to
  1358. // re-calculate it every time this is called.
  1359. transformStack.back().inverse().transformXY(&p, &point, 1);
  1360. return p;
  1361. }
  1362. const Graphics::DefaultShaderCode &Graphics::getCurrentDefaultShaderCode() const
  1363. {
  1364. int languageindex = (int) getShaderLanguageTarget();
  1365. int gammaindex = isGammaCorrect() ? 1 : 0;
  1366. return defaultShaderCode[Shader::STANDARD_DEFAULT][languageindex][gammaindex];
  1367. }
  1368. /**
  1369. * Constants.
  1370. **/
  1371. bool Graphics::getConstant(const char *in, DrawMode &out)
  1372. {
  1373. return drawModes.find(in, out);
  1374. }
  1375. bool Graphics::getConstant(DrawMode in, const char *&out)
  1376. {
  1377. return drawModes.find(in, out);
  1378. }
  1379. std::vector<std::string> Graphics::getConstants(DrawMode)
  1380. {
  1381. return drawModes.getNames();
  1382. }
  1383. bool Graphics::getConstant(const char *in, ArcMode &out)
  1384. {
  1385. return arcModes.find(in, out);
  1386. }
  1387. bool Graphics::getConstant(ArcMode in, const char *&out)
  1388. {
  1389. return arcModes.find(in, out);
  1390. }
  1391. std::vector<std::string> Graphics::getConstants(ArcMode)
  1392. {
  1393. return arcModes.getNames();
  1394. }
  1395. bool Graphics::getConstant(const char *in, LineStyle &out)
  1396. {
  1397. return lineStyles.find(in, out);
  1398. }
  1399. bool Graphics::getConstant(LineStyle in, const char *&out)
  1400. {
  1401. return lineStyles.find(in, out);
  1402. }
  1403. std::vector<std::string> Graphics::getConstants(LineStyle)
  1404. {
  1405. return lineStyles.getNames();
  1406. }
  1407. bool Graphics::getConstant(const char *in, LineJoin &out)
  1408. {
  1409. return lineJoins.find(in, out);
  1410. }
  1411. bool Graphics::getConstant(LineJoin in, const char *&out)
  1412. {
  1413. return lineJoins.find(in, out);
  1414. }
  1415. std::vector<std::string> Graphics::getConstants(LineJoin)
  1416. {
  1417. return lineJoins.getNames();
  1418. }
  1419. bool Graphics::getConstant(const char *in, Feature &out)
  1420. {
  1421. return features.find(in, out);
  1422. }
  1423. bool Graphics::getConstant(Feature in, const char *&out)
  1424. {
  1425. return features.find(in, out);
  1426. }
  1427. bool Graphics::getConstant(const char *in, SystemLimit &out)
  1428. {
  1429. return systemLimits.find(in, out);
  1430. }
  1431. bool Graphics::getConstant(SystemLimit in, const char *&out)
  1432. {
  1433. return systemLimits.find(in, out);
  1434. }
  1435. bool Graphics::getConstant(const char *in, StackType &out)
  1436. {
  1437. return stackTypes.find(in, out);
  1438. }
  1439. bool Graphics::getConstant(StackType in, const char *&out)
  1440. {
  1441. return stackTypes.find(in, out);
  1442. }
  1443. std::vector<std::string> Graphics::getConstants(StackType)
  1444. {
  1445. return stackTypes.getNames();
  1446. }
  1447. StringMap<Graphics::DrawMode, Graphics::DRAW_MAX_ENUM>::Entry Graphics::drawModeEntries[] =
  1448. {
  1449. { "line", DRAW_LINE },
  1450. { "fill", DRAW_FILL },
  1451. };
  1452. StringMap<Graphics::DrawMode, Graphics::DRAW_MAX_ENUM> Graphics::drawModes(Graphics::drawModeEntries, sizeof(Graphics::drawModeEntries));
  1453. StringMap<Graphics::ArcMode, Graphics::ARC_MAX_ENUM>::Entry Graphics::arcModeEntries[] =
  1454. {
  1455. { "open", ARC_OPEN },
  1456. { "closed", ARC_CLOSED },
  1457. { "pie", ARC_PIE },
  1458. };
  1459. StringMap<Graphics::ArcMode, Graphics::ARC_MAX_ENUM> Graphics::arcModes(Graphics::arcModeEntries, sizeof(Graphics::arcModeEntries));
  1460. StringMap<Graphics::LineStyle, Graphics::LINE_MAX_ENUM>::Entry Graphics::lineStyleEntries[] =
  1461. {
  1462. { "smooth", LINE_SMOOTH },
  1463. { "rough", LINE_ROUGH }
  1464. };
  1465. StringMap<Graphics::LineStyle, Graphics::LINE_MAX_ENUM> Graphics::lineStyles(Graphics::lineStyleEntries, sizeof(Graphics::lineStyleEntries));
  1466. StringMap<Graphics::LineJoin, Graphics::LINE_JOIN_MAX_ENUM>::Entry Graphics::lineJoinEntries[] =
  1467. {
  1468. { "none", LINE_JOIN_NONE },
  1469. { "miter", LINE_JOIN_MITER },
  1470. { "bevel", LINE_JOIN_BEVEL }
  1471. };
  1472. StringMap<Graphics::LineJoin, Graphics::LINE_JOIN_MAX_ENUM> Graphics::lineJoins(Graphics::lineJoinEntries, sizeof(Graphics::lineJoinEntries));
  1473. StringMap<Graphics::Feature, Graphics::FEATURE_MAX_ENUM>::Entry Graphics::featureEntries[] =
  1474. {
  1475. { "multicanvasformats", FEATURE_MULTI_CANVAS_FORMATS },
  1476. { "clampzero", FEATURE_CLAMP_ZERO },
  1477. { "blendminmax", FEATURE_BLENDMINMAX },
  1478. { "lighten", FEATURE_LIGHTEN },
  1479. { "fullnpot", FEATURE_FULL_NPOT },
  1480. { "pixelshaderhighp", FEATURE_PIXEL_SHADER_HIGHP },
  1481. { "shaderderivatives", FEATURE_SHADER_DERIVATIVES },
  1482. { "glsl3", FEATURE_GLSL3 },
  1483. { "glsl4", FEATURE_GLSL4 },
  1484. { "instancing", FEATURE_INSTANCING },
  1485. };
  1486. StringMap<Graphics::Feature, Graphics::FEATURE_MAX_ENUM> Graphics::features(Graphics::featureEntries, sizeof(Graphics::featureEntries));
  1487. StringMap<Graphics::SystemLimit, Graphics::LIMIT_MAX_ENUM>::Entry Graphics::systemLimitEntries[] =
  1488. {
  1489. { "pointsize", LIMIT_POINT_SIZE },
  1490. { "texturesize", LIMIT_TEXTURE_SIZE },
  1491. { "texturelayers", LIMIT_TEXTURE_LAYERS },
  1492. { "volumetexturesize", LIMIT_VOLUME_TEXTURE_SIZE },
  1493. { "cubetexturesize", LIMIT_CUBE_TEXTURE_SIZE },
  1494. { "multicanvas", LIMIT_MULTI_CANVAS },
  1495. { "canvasmsaa", LIMIT_CANVAS_MSAA },
  1496. { "anisotropy", LIMIT_ANISOTROPY },
  1497. };
  1498. StringMap<Graphics::SystemLimit, Graphics::LIMIT_MAX_ENUM> Graphics::systemLimits(Graphics::systemLimitEntries, sizeof(Graphics::systemLimitEntries));
  1499. StringMap<Graphics::StackType, Graphics::STACK_MAX_ENUM>::Entry Graphics::stackTypeEntries[] =
  1500. {
  1501. { "all", STACK_ALL },
  1502. { "transform", STACK_TRANSFORM },
  1503. };
  1504. StringMap<Graphics::StackType, Graphics::STACK_MAX_ENUM> Graphics::stackTypes(Graphics::stackTypeEntries, sizeof(Graphics::stackTypeEntries));
  1505. } // graphics
  1506. } // love