Graphics.cpp 49 KB

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