Graphics.cpp 49 KB

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