Graphics.cpp 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725
  1. /**
  2. * Copyright (c) 2006-2023 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 "TextBatch.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. namespace opengl { extern love::graphics::Graphics *createInstance(); }
  95. #ifdef LOVE_GRAPHICS_METAL
  96. namespace metal { extern love::graphics::Graphics *createInstance(); }
  97. #endif
  98. #ifdef LOVE_GRAPHICS_VULKAN
  99. namespace vulkan { extern love::graphics::Graphics* createInstance(); }
  100. #endif
  101. static const Renderer rendererOrder[] = {
  102. RENDERER_METAL,
  103. RENDERER_OPENGL,
  104. RENDERER_VULKAN,
  105. };
  106. static std::vector<Renderer> defaultRenderers =
  107. {
  108. RENDERER_METAL,
  109. RENDERER_OPENGL,
  110. RENDERER_VULKAN,
  111. };
  112. static std::vector<Renderer> _renderers = defaultRenderers;
  113. const std::vector<Renderer> &getDefaultRenderers()
  114. {
  115. return defaultRenderers;
  116. }
  117. const std::vector<Renderer> &getRenderers()
  118. {
  119. return _renderers;
  120. }
  121. void setRenderers(const std::vector<Renderer> &renderers)
  122. {
  123. _renderers = renderers;
  124. }
  125. Graphics *Graphics::createInstance()
  126. {
  127. Graphics *instance = Module::getInstance<Graphics>(M_GRAPHICS);
  128. if (instance != nullptr)
  129. instance->retain();
  130. else
  131. {
  132. for (auto r : rendererOrder)
  133. {
  134. if (std::find(_renderers.begin(), _renderers.end(), r) == _renderers.end())
  135. continue;
  136. #ifdef LOVE_GRAPHICS_VULKAN
  137. if (r == RENDERER_VULKAN)
  138. instance = vulkan::createInstance();
  139. #endif
  140. if (r == RENDERER_OPENGL)
  141. instance = opengl::createInstance();
  142. #ifdef LOVE_GRAPHICS_METAL
  143. if (r == RENDERER_METAL)
  144. instance = metal::createInstance();
  145. #endif
  146. if (instance != nullptr)
  147. break;
  148. }
  149. }
  150. return instance;
  151. }
  152. Graphics::DisplayState::DisplayState()
  153. {
  154. defaultSamplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_LINEAR;
  155. }
  156. Graphics::Graphics()
  157. : width(0)
  158. , height(0)
  159. , pixelWidth(0)
  160. , pixelHeight(0)
  161. , created(false)
  162. , active(true)
  163. , batchedDrawState()
  164. , deviceProjectionMatrix()
  165. , renderTargetSwitchCount(0)
  166. , drawCalls(0)
  167. , drawCallsBatched(0)
  168. , quadIndexBuffer(nullptr)
  169. , fanIndexBuffer(nullptr)
  170. , capabilities()
  171. , cachedShaderStages()
  172. {
  173. transformStack.reserve(16);
  174. transformStack.push_back(Matrix4());
  175. pixelScaleStack.reserve(16);
  176. pixelScaleStack.push_back(1);
  177. states.reserve(10);
  178. states.push_back(DisplayState());
  179. if (!Shader::initialize())
  180. throw love::Exception("Shader support failed to initialize!");
  181. }
  182. Graphics::~Graphics()
  183. {
  184. if (quadIndexBuffer != nullptr)
  185. quadIndexBuffer->release();
  186. if (fanIndexBuffer != nullptr)
  187. fanIndexBuffer->release();
  188. // Clean up standard shaders before the active shader. If we do it after,
  189. // the active shader may try to activate a standard shader when deactivating
  190. // itself, which will cause problems since it calls Graphics methods in the
  191. // Graphics destructor.
  192. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++)
  193. {
  194. if (Shader::standardShaders[i])
  195. {
  196. Shader::standardShaders[i]->release();
  197. Shader::standardShaders[i] = nullptr;
  198. }
  199. }
  200. states.clear();
  201. defaultFont.set(nullptr);
  202. if (batchedDrawState.vb[0])
  203. batchedDrawState.vb[0]->release();
  204. if (batchedDrawState.vb[1])
  205. batchedDrawState.vb[1]->release();
  206. if (batchedDrawState.indexBuffer)
  207. batchedDrawState.indexBuffer->release();
  208. for (int i = 0; i < (int) SHADERSTAGE_MAX_ENUM; i++)
  209. cachedShaderStages[i].clear();
  210. pendingReadbacks.clear();
  211. clearTemporaryResources();
  212. Shader::deinitialize();
  213. }
  214. void Graphics::createQuadIndexBuffer()
  215. {
  216. if (quadIndexBuffer != nullptr)
  217. return;
  218. size_t size = sizeof(uint16) * getIndexCount(TRIANGLEINDEX_QUADS, LOVE_UINT16_MAX);
  219. Buffer::Settings settings(BUFFERUSAGEFLAG_INDEX, BUFFERDATAUSAGE_STATIC);
  220. quadIndexBuffer = newBuffer(settings, DATAFORMAT_UINT16, nullptr, size, 0);
  221. {
  222. Buffer::Mapper map(*quadIndexBuffer);
  223. fillIndices(TRIANGLEINDEX_QUADS, 0, LOVE_UINT16_MAX, (uint16 *) map.data);
  224. }
  225. quadIndexBuffer->setImmutable(true);
  226. }
  227. void Graphics::createFanIndexBuffer()
  228. {
  229. if (fanIndexBuffer != nullptr)
  230. return;
  231. size_t size = sizeof(uint16) * getIndexCount(TRIANGLEINDEX_FAN, LOVE_UINT16_MAX);
  232. Buffer::Settings settings(BUFFERUSAGEFLAG_INDEX, BUFFERDATAUSAGE_STATIC);
  233. fanIndexBuffer = newBuffer(settings, DATAFORMAT_UINT16, nullptr, size, 0);
  234. Buffer::Mapper map(*fanIndexBuffer);
  235. fillIndices(TRIANGLEINDEX_FAN, 0, LOVE_UINT16_MAX, (uint16 *) map.data);
  236. fanIndexBuffer->setImmutable(true);
  237. }
  238. Quad *Graphics::newQuad(Quad::Viewport v, double sw, double sh)
  239. {
  240. return new Quad(v, sw, sh);
  241. }
  242. Font *Graphics::newFont(love::font::Rasterizer *data)
  243. {
  244. return new Font(data, states.back().defaultSamplerState);
  245. }
  246. Font *Graphics::newDefaultFont(int size, const font::TrueTypeRasterizer::Settings &settings)
  247. {
  248. auto fontmodule = Module::getInstance<font::Font>(M_FONT);
  249. if (!fontmodule)
  250. throw love::Exception("Font module has not been loaded.");
  251. StrongRef<font::Rasterizer> r(fontmodule->newTrueTypeRasterizer(size, settings), Acquire::NORETAIN);
  252. return newFont(r.get());
  253. }
  254. Video *Graphics::newVideo(love::video::VideoStream *stream, float dpiscale)
  255. {
  256. return new Video(this, stream, dpiscale);
  257. }
  258. love::graphics::SpriteBatch *Graphics::newSpriteBatch(Texture *texture, int size, BufferDataUsage usage)
  259. {
  260. return new SpriteBatch(this, texture, size, usage);
  261. }
  262. love::graphics::ParticleSystem *Graphics::newParticleSystem(Texture *texture, int size)
  263. {
  264. return new ParticleSystem(texture, size);
  265. }
  266. ShaderStage *Graphics::newShaderStage(ShaderStageType stage, const std::string &source, const Shader::CompileOptions &options, const Shader::SourceInfo &info, bool cache)
  267. {
  268. ShaderStage *s = nullptr;
  269. std::string cachekey;
  270. // Never cache if there are custom defines set... because hashing would get
  271. // more complicated/expensive, and there shouldn't be a lot of duplicate
  272. // shader stages with custom defines anyway.
  273. if (!options.defines.empty())
  274. cache = false;
  275. if (cache && !source.empty())
  276. {
  277. data::HashFunction::Value hashvalue;
  278. data::hash(data::HashFunction::FUNCTION_SHA1, source.c_str(), source.size(), hashvalue);
  279. cachekey = std::string(hashvalue.data, hashvalue.size);
  280. auto it = cachedShaderStages[stage].find(cachekey);
  281. if (it != cachedShaderStages[stage].end())
  282. {
  283. s = it->second;
  284. s->retain();
  285. }
  286. }
  287. if (s == nullptr)
  288. {
  289. bool glsles = usesGLSLES();
  290. std::string glsl = Shader::createShaderStageCode(this, stage, source, options, info, glsles, true);
  291. s = newShaderStageInternal(stage, cachekey, glsl, glsles);
  292. if (cache && !cachekey.empty())
  293. cachedShaderStages[stage][cachekey] = s;
  294. }
  295. return s;
  296. }
  297. Shader *Graphics::newShader(const std::vector<std::string> &stagessource, const Shader::CompileOptions &options)
  298. {
  299. StrongRef<ShaderStage> stages[SHADERSTAGE_MAX_ENUM] = {};
  300. bool validstages[SHADERSTAGE_MAX_ENUM] = {};
  301. validstages[SHADERSTAGE_VERTEX] = true;
  302. validstages[SHADERSTAGE_PIXEL] = true;
  303. for (const std::string &source : stagessource)
  304. {
  305. Shader::SourceInfo info = Shader::getSourceInfo(source);
  306. bool isanystage = false;
  307. for (int i = 0; i < SHADERSTAGE_MAX_ENUM; i++)
  308. {
  309. if (!validstages[i])
  310. continue;
  311. if (info.stages[i] != Shader::ENTRYPOINT_NONE)
  312. {
  313. isanystage = true;
  314. stages[i].set(newShaderStage((ShaderStageType) i, source, options, info, true), Acquire::NORETAIN);
  315. }
  316. }
  317. if (!isanystage)
  318. throw love::Exception("Could not parse shader code (missing shader entry point function such as 'position' or 'effect')");
  319. }
  320. for (int i = 0; i < SHADERSTAGE_MAX_ENUM; i++)
  321. {
  322. auto stype = (ShaderStageType) i;
  323. if (validstages[i] && stages[i].get() == nullptr)
  324. {
  325. const std::string &source = Shader::getDefaultCode(Shader::STANDARD_DEFAULT, stype);
  326. Shader::SourceInfo info = Shader::getSourceInfo(source);
  327. Shader::CompileOptions opts;
  328. stages[i].set(newShaderStage(stype, source, opts, info, true), Acquire::NORETAIN);
  329. }
  330. }
  331. return newShaderInternal(stages);
  332. }
  333. Shader *Graphics::newComputeShader(const std::string &source, const Shader::CompileOptions &options)
  334. {
  335. Shader::SourceInfo info = Shader::getSourceInfo(source);
  336. if (info.stages[SHADERSTAGE_COMPUTE] == Shader::ENTRYPOINT_NONE)
  337. throw love::Exception("Could not parse compute shader code (missing 'computemain' function?)");
  338. StrongRef<ShaderStage> stages[SHADERSTAGE_MAX_ENUM];
  339. // Don't bother caching compute shader intermediate source, since there
  340. // shouldn't be much reuse.
  341. stages[SHADERSTAGE_COMPUTE].set(newShaderStage(SHADERSTAGE_COMPUTE, source, options, info, false));
  342. return newShaderInternal(stages);
  343. }
  344. Buffer *Graphics::newBuffer(const Buffer::Settings &settings, DataFormat format, const void *data, size_t size, size_t arraylength)
  345. {
  346. std::vector<Buffer::DataDeclaration> dataformat = {{"", format, 0}};
  347. return newBuffer(settings, dataformat, data, size, arraylength);
  348. }
  349. Mesh *Graphics::newMesh(const std::vector<Buffer::DataDeclaration> &vertexformat, int vertexcount, PrimitiveType drawmode, BufferDataUsage usage)
  350. {
  351. return new Mesh(this, vertexformat, vertexcount, drawmode, usage);
  352. }
  353. Mesh *Graphics::newMesh(const std::vector<Buffer::DataDeclaration> &vertexformat, const void *data, size_t datasize, PrimitiveType drawmode, BufferDataUsage usage)
  354. {
  355. return new Mesh(this, vertexformat, data, datasize, drawmode, usage);
  356. }
  357. Mesh *Graphics::newMesh(const std::vector<Mesh::BufferAttribute> &attributes, PrimitiveType drawmode)
  358. {
  359. return new Mesh(attributes, drawmode);
  360. }
  361. love::graphics::TextBatch *Graphics::newTextBatch(graphics::Font *font, const std::vector<love::font::ColoredString> &text)
  362. {
  363. return new TextBatch(font, text);
  364. }
  365. love::data::ByteData *Graphics::readbackBuffer(Buffer *buffer, size_t offset, size_t size, data::ByteData *dest, size_t destoffset)
  366. {
  367. StrongRef<GraphicsReadback> readback;
  368. readback.set(newReadbackInternal(READBACK_IMMEDIATE, buffer, offset, size, dest, destoffset), Acquire::NORETAIN);
  369. auto data = readback->getBufferData();
  370. if (data == nullptr)
  371. throw love::Exception("love.graphics.readbackBuffer failed.");
  372. data->retain();
  373. return data;
  374. }
  375. GraphicsReadback *Graphics::readbackBufferAsync(Buffer *buffer, size_t offset, size_t size, data::ByteData *dest, size_t destoffset)
  376. {
  377. auto readback = newReadbackInternal(READBACK_ASYNC, buffer, offset, size, dest, destoffset);
  378. pendingReadbacks.push_back(readback);
  379. return readback;
  380. }
  381. image::ImageData *Graphics::readbackTexture(Texture *texture, int slice, int mipmap, const Rect &rect, image::ImageData *dest, int destx, int desty)
  382. {
  383. StrongRef<GraphicsReadback> readback;
  384. readback.set(newReadbackInternal(READBACK_IMMEDIATE, texture, slice, mipmap, rect, dest, destx, desty), Acquire::NORETAIN);
  385. auto imagedata = readback->getImageData();
  386. if (imagedata == nullptr)
  387. throw love::Exception("love.graphics.readbackTexture failed.");
  388. imagedata->retain();
  389. return imagedata;
  390. }
  391. GraphicsReadback *Graphics::readbackTextureAsync(Texture *texture, int slice, int mipmap, const Rect &rect, image::ImageData *dest, int destx, int desty)
  392. {
  393. auto readback = newReadbackInternal(READBACK_ASYNC, texture, slice, mipmap, rect, dest, destx, desty);
  394. pendingReadbacks.push_back(readback);
  395. return readback;
  396. }
  397. void Graphics::cleanupCachedShaderStage(ShaderStageType type, const std::string &hashkey)
  398. {
  399. cachedShaderStages[type].erase(hashkey);
  400. }
  401. bool Graphics::validateShader(bool gles, const std::vector<std::string> &stagessource, const Shader::CompileOptions &options, std::string &err)
  402. {
  403. StrongRef<ShaderStage> stages[SHADERSTAGE_MAX_ENUM] = {};
  404. bool validstages[SHADERSTAGE_MAX_ENUM] = {};
  405. validstages[SHADERSTAGE_VERTEX] = true;
  406. validstages[SHADERSTAGE_PIXEL] = true;
  407. validstages[SHADERSTAGE_COMPUTE] = true;
  408. // Don't use cached shader stages, since the gles flag may not match the
  409. // current renderer.
  410. for (const std::string &source : stagessource)
  411. {
  412. Shader::SourceInfo info = Shader::getSourceInfo(source);
  413. bool isanystage = false;
  414. for (int i = 0; i < SHADERSTAGE_MAX_ENUM; i++)
  415. {
  416. auto stype = (ShaderStageType) i;
  417. if (!validstages[i])
  418. continue;
  419. if (info.stages[i] != Shader::ENTRYPOINT_NONE)
  420. {
  421. isanystage = true;
  422. std::string glsl = Shader::createShaderStageCode(this, stype, source, options, info, gles, false);
  423. stages[i].set(new ShaderStageForValidation(this, stype, glsl, gles), Acquire::NORETAIN);
  424. }
  425. }
  426. if (!isanystage)
  427. {
  428. err = "Could not parse shader code (missing 'position' or 'effect' function?)";
  429. return false;
  430. }
  431. }
  432. return Shader::validate(stages, err);
  433. }
  434. int Graphics::getWidth() const
  435. {
  436. return width;
  437. }
  438. int Graphics::getHeight() const
  439. {
  440. return height;
  441. }
  442. int Graphics::getPixelWidth() const
  443. {
  444. return pixelWidth;
  445. }
  446. int Graphics::getPixelHeight() const
  447. {
  448. return pixelHeight;
  449. }
  450. double Graphics::getCurrentDPIScale() const
  451. {
  452. const auto &rt = states.back().renderTargets.getFirstTarget();
  453. if (rt.texture.get())
  454. return rt.texture->getDPIScale();
  455. return getScreenDPIScale();
  456. }
  457. double Graphics::getScreenDPIScale() const
  458. {
  459. return (double) getPixelHeight() / (double) getHeight();
  460. }
  461. bool Graphics::isCreated() const
  462. {
  463. return created;
  464. }
  465. bool Graphics::isActive() const
  466. {
  467. // The graphics module is only completely 'active' if there's a window, a
  468. // context, and the active variable is set.
  469. auto window = getInstance<love::window::Window>(M_WINDOW);
  470. return active && isCreated() && window != nullptr && window->isOpen();
  471. }
  472. void Graphics::reset()
  473. {
  474. DisplayState s;
  475. restoreState(s);
  476. origin();
  477. }
  478. /**
  479. * State functions.
  480. **/
  481. void Graphics::restoreState(const DisplayState &s)
  482. {
  483. setColor(s.color);
  484. setBackgroundColor(s.backgroundColor);
  485. setBlendState(s.blend);
  486. setLineWidth(s.lineWidth);
  487. setLineStyle(s.lineStyle);
  488. setLineJoin(s.lineJoin);
  489. setPointSize(s.pointSize);
  490. if (s.scissor)
  491. setScissor(s.scissorRect);
  492. else
  493. setScissor();
  494. setMeshCullMode(s.meshCullMode);
  495. setFrontFaceWinding(s.winding);
  496. setFont(s.font.get());
  497. setShader(s.shader.get());
  498. setRenderTargets(s.renderTargets);
  499. setStencilMode(s.stencil.action, s.stencil.compare, s.stencil.value, s.stencil.readMask, s.stencil.writeMask);
  500. setDepthMode(s.depthTest, s.depthWrite);
  501. setColorMask(s.colorMask);
  502. setWireframe(s.wireframe);
  503. setDefaultSamplerState(s.defaultSamplerState);
  504. if (s.useCustomProjection)
  505. updateDeviceProjection(s.customProjection);
  506. else
  507. resetProjection();
  508. }
  509. void Graphics::restoreStateChecked(const DisplayState &s)
  510. {
  511. const DisplayState &cur = states.back();
  512. if (s.color != cur.color)
  513. setColor(s.color);
  514. setBackgroundColor(s.backgroundColor);
  515. if (!(s.blend == cur.blend))
  516. setBlendState(s.blend);
  517. // These are just simple assignments.
  518. setLineWidth(s.lineWidth);
  519. setLineStyle(s.lineStyle);
  520. setLineJoin(s.lineJoin);
  521. if (s.pointSize != cur.pointSize)
  522. setPointSize(s.pointSize);
  523. if (s.scissor != cur.scissor || (s.scissor && !(s.scissorRect == cur.scissorRect)))
  524. {
  525. if (s.scissor)
  526. setScissor(s.scissorRect);
  527. else
  528. setScissor();
  529. }
  530. setMeshCullMode(s.meshCullMode);
  531. if (s.winding != cur.winding)
  532. setFrontFaceWinding(s.winding);
  533. setFont(s.font.get());
  534. setShader(s.shader.get());
  535. const auto &sRTs = s.renderTargets;
  536. const auto &curRTs = cur.renderTargets;
  537. bool rtschanged = sRTs.colors.size() != curRTs.colors.size();
  538. if (!rtschanged)
  539. {
  540. for (size_t i = 0; i < sRTs.colors.size() && i < curRTs.colors.size(); i++)
  541. {
  542. if (sRTs.colors[i] != curRTs.colors[i])
  543. {
  544. rtschanged = true;
  545. break;
  546. }
  547. }
  548. if (!rtschanged && sRTs.depthStencil != curRTs.depthStencil)
  549. rtschanged = true;
  550. if (sRTs.temporaryRTFlags != curRTs.temporaryRTFlags)
  551. rtschanged = true;
  552. }
  553. if (rtschanged)
  554. setRenderTargets(s.renderTargets);
  555. if (!(s.stencil == cur.stencil))
  556. setStencilMode(s.stencil.action, s.stencil.compare, s.stencil.value, s.stencil.readMask, s.stencil.writeMask);
  557. if (s.depthTest != cur.depthTest || s.depthWrite != cur.depthWrite)
  558. setDepthMode(s.depthTest, s.depthWrite);
  559. if (s.colorMask != cur.colorMask)
  560. setColorMask(s.colorMask);
  561. if (s.wireframe != cur.wireframe)
  562. setWireframe(s.wireframe);
  563. setDefaultSamplerState(s.defaultSamplerState);
  564. if (s.useCustomProjection)
  565. setCustomProjection(s.customProjection);
  566. else if (cur.useCustomProjection)
  567. resetProjection();
  568. }
  569. Colorf Graphics::getColor() const
  570. {
  571. return states.back().color;
  572. }
  573. void Graphics::setBackgroundColor(Colorf c)
  574. {
  575. states.back().backgroundColor = c;
  576. }
  577. Colorf Graphics::getBackgroundColor() const
  578. {
  579. return states.back().backgroundColor;
  580. }
  581. void Graphics::checkSetDefaultFont()
  582. {
  583. // We don't create or set the default Font if an existing font is in use.
  584. if (states.back().font.get() != nullptr)
  585. return;
  586. // Create a new default font if we don't have one yet.
  587. if (!defaultFont.get())
  588. {
  589. font::TrueTypeRasterizer::Settings settings;
  590. defaultFont.set(newDefaultFont(13, settings), Acquire::NORETAIN);
  591. }
  592. states.back().font.set(defaultFont.get());
  593. }
  594. void Graphics::setFont(love::graphics::Font *font)
  595. {
  596. // We don't need to set a default font here if null is passed in, since we
  597. // only care about the default font in getFont and print.
  598. DisplayState &state = states.back();
  599. state.font.set(font);
  600. }
  601. love::graphics::Font *Graphics::getFont()
  602. {
  603. checkSetDefaultFont();
  604. return states.back().font.get();
  605. }
  606. void Graphics::setShader(love::graphics::Shader *shader)
  607. {
  608. if (shader == nullptr)
  609. return setShader();
  610. shader->attach();
  611. states.back().shader.set(shader);
  612. }
  613. void Graphics::setShader()
  614. {
  615. Shader::attachDefault(Shader::STANDARD_DEFAULT);
  616. states.back().shader.set(nullptr);
  617. }
  618. love::graphics::Shader *Graphics::getShader() const
  619. {
  620. return states.back().shader.get();
  621. }
  622. void Graphics::setRenderTarget(RenderTarget rt, uint32 temporaryRTFlags)
  623. {
  624. if (rt.texture == nullptr)
  625. return setRenderTarget();
  626. RenderTargets rts;
  627. rts.colors.push_back(rt);
  628. rts.temporaryRTFlags = temporaryRTFlags;
  629. setRenderTargets(rts);
  630. }
  631. void Graphics::setRenderTargets(const RenderTargetsStrongRef &rts)
  632. {
  633. RenderTargets targets;
  634. targets.colors.reserve(rts.colors.size());
  635. for (const auto &rt : rts.colors)
  636. targets.colors.emplace_back(rt.texture.get(), rt.slice, rt.mipmap);
  637. targets.depthStencil = RenderTarget(rts.depthStencil.texture, rts.depthStencil.slice, rts.depthStencil.mipmap);
  638. targets.temporaryRTFlags = rts.temporaryRTFlags;
  639. return setRenderTargets(targets);
  640. }
  641. void Graphics::setRenderTargets(const RenderTargets &rts)
  642. {
  643. DisplayState &state = states.back();
  644. int rtcount = (int) rts.colors.size();
  645. RenderTarget firsttarget = rts.getFirstTarget();
  646. Texture *firsttex = firsttarget.texture;
  647. if (firsttex == nullptr)
  648. return setRenderTarget();
  649. const auto &prevRTs = state.renderTargets;
  650. if (rtcount == (int) prevRTs.colors.size())
  651. {
  652. bool modified = false;
  653. for (int i = 0; i < rtcount; i++)
  654. {
  655. if (rts.colors[i] != prevRTs.colors[i])
  656. {
  657. modified = true;
  658. break;
  659. }
  660. }
  661. if (!modified && rts.depthStencil != prevRTs.depthStencil)
  662. modified = true;
  663. if (rts.temporaryRTFlags != prevRTs.temporaryRTFlags)
  664. modified = true;
  665. if (!modified)
  666. return;
  667. }
  668. if (rtcount > capabilities.limits[LIMIT_RENDER_TARGETS])
  669. throw love::Exception("This system can't simultaneously render to %d textures.", rtcount);
  670. bool multiformatsupported = capabilities.features[FEATURE_MULTI_RENDER_TARGET_FORMATS];
  671. PixelFormat firstcolorformat = PIXELFORMAT_UNKNOWN;
  672. if (!rts.colors.empty())
  673. firstcolorformat = rts.colors[0].texture->getPixelFormat();
  674. if (!firsttex->isRenderTarget())
  675. throw love::Exception("Texture must be created as a render target to be used in setRenderTargets.");
  676. if (isPixelFormatDepthStencil(firstcolorformat))
  677. throw love::Exception("Depth/stencil format textures must be used with the 'depthstencil' field of the table passed into setRenderTargets.");
  678. if (firsttarget.mipmap < 0 || firsttarget.mipmap >= firsttex->getMipmapCount())
  679. throw love::Exception("Invalid mipmap level %d.", firsttarget.mipmap + 1);
  680. if (!firsttex->isValidSlice(firsttarget.slice, firsttarget.mipmap))
  681. throw love::Exception("Invalid slice index: %d.", firsttarget.slice + 1);
  682. bool hasSRGBtexture = isPixelFormatSRGB(firstcolorformat);
  683. int pixelw = firsttex->getPixelWidth(firsttarget.mipmap);
  684. int pixelh = firsttex->getPixelHeight(firsttarget.mipmap);
  685. int reqmsaa = firsttex->getRequestedMSAA();
  686. for (int i = 1; i < rtcount; i++)
  687. {
  688. Texture *c = rts.colors[i].texture;
  689. PixelFormat format = c->getPixelFormat();
  690. int mip = rts.colors[i].mipmap;
  691. int slice = rts.colors[i].slice;
  692. if (!c->isRenderTarget())
  693. throw love::Exception("Texture must be created as a render target to be used in setRenderTargets.");
  694. if (mip < 0 || mip >= c->getMipmapCount())
  695. throw love::Exception("Invalid mipmap level %d.", mip + 1);
  696. if (!c->isValidSlice(slice, mip))
  697. throw love::Exception("Invalid slice index: %d.", slice + 1);
  698. if (c->getPixelWidth(mip) != pixelw || c->getPixelHeight(mip) != pixelh)
  699. throw love::Exception("All textures must have the same pixel dimensions.");
  700. if (!multiformatsupported && format != firstcolorformat)
  701. throw love::Exception("This system doesn't support multi-render-target rendering with different texture formats.");
  702. if (c->getRequestedMSAA() != reqmsaa)
  703. throw love::Exception("All textures must have the same MSAA value.");
  704. if (isPixelFormatDepthStencil(format))
  705. throw love::Exception("Depth/stencil format textures must be used with the 'depthstencil' field of the table passed into setRenderTargets.");
  706. if (isPixelFormatSRGB(format))
  707. hasSRGBtexture = true;
  708. }
  709. if (rts.depthStencil.texture != nullptr)
  710. {
  711. Texture *c = rts.depthStencil.texture;
  712. int mip = rts.depthStencil.mipmap;
  713. int slice = rts.depthStencil.slice;
  714. if (!c->isRenderTarget())
  715. throw love::Exception("Texture must be created as a render target to be used in setRenderTargets.");
  716. if (!isPixelFormatDepthStencil(c->getPixelFormat()))
  717. throw love::Exception("Only depth/stencil format textures can be used with the 'depthstencil' field of the table passed into setRenderTargets.");
  718. if (c->getPixelWidth(mip) != pixelw || c->getPixelHeight(mip) != pixelh)
  719. throw love::Exception("All Textures must have the same pixel dimensions.");
  720. if (c->getRequestedMSAA() != firsttex->getRequestedMSAA())
  721. throw love::Exception("All Textures must have the same MSAA value.");
  722. if (mip < 0 || mip >= c->getMipmapCount())
  723. throw love::Exception("Invalid mipmap level %d.", mip + 1);
  724. if (!c->isValidSlice(slice, mip))
  725. throw love::Exception("Invalid slice index: %d.", slice + 1);
  726. }
  727. flushBatchedDraws();
  728. if (rts.depthStencil.texture == nullptr && rts.temporaryRTFlags != 0)
  729. {
  730. bool wantsdepth = (rts.temporaryRTFlags & TEMPORARY_RT_DEPTH) != 0;
  731. bool wantsstencil = (rts.temporaryRTFlags & TEMPORARY_RT_STENCIL) != 0;
  732. PixelFormat dsformat = PIXELFORMAT_STENCIL8;
  733. if (wantsdepth && wantsstencil)
  734. dsformat = PIXELFORMAT_DEPTH24_UNORM_STENCIL8;
  735. else if (wantsdepth && isPixelFormatSupported(PIXELFORMAT_DEPTH24_UNORM, PIXELFORMATUSAGEFLAGS_RENDERTARGET))
  736. dsformat = PIXELFORMAT_DEPTH24_UNORM;
  737. else if (wantsdepth)
  738. dsformat = PIXELFORMAT_DEPTH16_UNORM;
  739. else if (wantsstencil)
  740. dsformat = PIXELFORMAT_STENCIL8;
  741. // We want setRenderTargetsInternal to have a pointer to the temporary RT,
  742. // but we don't want to directly store it in the main graphics state.
  743. RenderTargets realRTs = rts;
  744. realRTs.depthStencil.texture = getTemporaryTexture(dsformat, pixelw, pixelh, reqmsaa);
  745. realRTs.depthStencil.slice = 0;
  746. // TODO: fix this to call release at the right time.
  747. // This only works here because nothing else calls getTemporaryTexture.
  748. releaseTemporaryTexture(realRTs.depthStencil.texture);
  749. setRenderTargetsInternal(realRTs, pixelw, pixelh, hasSRGBtexture);
  750. }
  751. else
  752. setRenderTargetsInternal(rts, pixelw, pixelh, hasSRGBtexture);
  753. RenderTargetsStrongRef refs;
  754. refs.colors.reserve(rts.colors.size());
  755. for (auto c : rts.colors)
  756. refs.colors.emplace_back(c.texture, c.slice, c.mipmap);
  757. refs.depthStencil = RenderTargetStrongRef(rts.depthStencil.texture, rts.depthStencil.slice);
  758. refs.temporaryRTFlags = rts.temporaryRTFlags;
  759. std::swap(state.renderTargets, refs);
  760. renderTargetSwitchCount++;
  761. resetProjection();
  762. // Clear/reset the temporary depth/stencil buffers.
  763. // TODO: make this deferred somehow to avoid double clearing if the user
  764. // also calls love.graphics.clear after setCanvas.
  765. if (rts.depthStencil.texture == nullptr && rts.temporaryRTFlags != 0)
  766. {
  767. OptionalColorD clearcolor;
  768. OptionalInt clearstencil(0);
  769. OptionalDouble cleardepth(1.0);
  770. clear(clearcolor, clearstencil, cleardepth);
  771. }
  772. }
  773. void Graphics::setRenderTarget()
  774. {
  775. DisplayState &state = states.back();
  776. if (state.renderTargets.colors.empty() && state.renderTargets.depthStencil.texture == nullptr)
  777. return;
  778. flushBatchedDraws();
  779. setRenderTargetsInternal(RenderTargets(), pixelWidth, pixelHeight, isGammaCorrect());
  780. state.renderTargets = RenderTargetsStrongRef();
  781. renderTargetSwitchCount++;
  782. resetProjection();
  783. }
  784. Graphics::RenderTargets Graphics::getRenderTargets() const
  785. {
  786. const auto &curRTs = states.back().renderTargets;
  787. RenderTargets rts;
  788. rts.colors.reserve(curRTs.colors.size());
  789. for (const auto &rt : curRTs.colors)
  790. rts.colors.emplace_back(rt.texture.get(), rt.slice, rt.mipmap);
  791. rts.depthStencil = RenderTarget(curRTs.depthStencil.texture, curRTs.depthStencil.slice, curRTs.depthStencil.mipmap);
  792. rts.temporaryRTFlags = curRTs.temporaryRTFlags;
  793. return rts;
  794. }
  795. bool Graphics::isRenderTargetActive() const
  796. {
  797. const auto &rts = states.back().renderTargets;
  798. return !rts.colors.empty() || rts.depthStencil.texture != nullptr;
  799. }
  800. bool Graphics::isRenderTargetActive(Texture *texture) const
  801. {
  802. const auto &rts = states.back().renderTargets;
  803. for (const auto &rt : rts.colors)
  804. {
  805. if (rt.texture.get() == texture)
  806. return true;
  807. }
  808. if (rts.depthStencil.texture.get() == texture)
  809. return true;
  810. return false;
  811. }
  812. bool Graphics::isRenderTargetActive(Texture *texture, int slice) const
  813. {
  814. const auto &rts = states.back().renderTargets;
  815. for (const auto &rt : rts.colors)
  816. {
  817. if (rt.texture.get() == texture && rt.slice == slice)
  818. return true;
  819. }
  820. if (rts.depthStencil.texture.get() == texture && rts.depthStencil.slice == slice)
  821. return true;
  822. return false;
  823. }
  824. Texture *Graphics::getTemporaryTexture(PixelFormat format, int w, int h, int samples)
  825. {
  826. Texture *texture = nullptr;
  827. for (TemporaryTexture &temp : temporaryTextures)
  828. {
  829. if (temp.framesSinceUse < 0)
  830. continue;
  831. Texture *c = temp.texture;
  832. if (c->getPixelFormat() == format && c->getPixelWidth() == w
  833. && c->getPixelHeight() == h && c->getRequestedMSAA() == samples)
  834. {
  835. texture = c;
  836. temp.framesSinceUse = -1;
  837. break;
  838. }
  839. }
  840. if (texture == nullptr)
  841. {
  842. Texture::Settings settings;
  843. settings.renderTarget = true;
  844. settings.format = format;
  845. settings.width = w;
  846. settings.height = h;
  847. settings.msaa = samples;
  848. texture = newTexture(settings);
  849. temporaryTextures.emplace_back(texture);
  850. }
  851. return texture;
  852. }
  853. void Graphics::releaseTemporaryTexture(Texture *texture)
  854. {
  855. for (TemporaryTexture &temp : temporaryTextures)
  856. {
  857. if (temp.texture == texture)
  858. {
  859. temp.framesSinceUse = 0;
  860. break;
  861. }
  862. }
  863. }
  864. Buffer *Graphics::getTemporaryBuffer(size_t size, DataFormat format, uint32 usageflags, BufferDataUsage datausage)
  865. {
  866. Buffer *buffer = nullptr;
  867. for (TemporaryBuffer &temp : temporaryBuffers)
  868. {
  869. if (temp.framesSinceUse < 0)
  870. continue;
  871. Buffer *b = temp.buffer;
  872. if (temp.size == size && b->getDataMember(0).decl.format == format
  873. && b->getUsageFlags() == usageflags && b->getDataUsage() == datausage)
  874. {
  875. buffer = b;
  876. temp.framesSinceUse = -1;
  877. break;
  878. }
  879. }
  880. if (buffer == nullptr)
  881. {
  882. Buffer::Settings settings(usageflags, datausage);
  883. buffer = newBuffer(settings, format, nullptr, size, 0);
  884. temporaryBuffers.emplace_back(buffer, size);
  885. }
  886. return buffer;
  887. }
  888. void Graphics::releaseTemporaryBuffer(Buffer *buffer)
  889. {
  890. for (TemporaryBuffer &temp : temporaryBuffers)
  891. {
  892. if (temp.buffer == buffer)
  893. {
  894. temp.framesSinceUse = 0;
  895. break;
  896. }
  897. }
  898. }
  899. void Graphics::updateTemporaryResources()
  900. {
  901. for (int i = (int) temporaryTextures.size() - 1; i >= 0; i--)
  902. {
  903. auto &t = temporaryTextures[i];
  904. if (t.framesSinceUse >= MAX_TEMPORARY_RESOURCE_UNUSED_FRAMES)
  905. {
  906. t.texture->release();
  907. t = temporaryTextures.back();
  908. temporaryTextures.pop_back();
  909. }
  910. else if (t.framesSinceUse >= 0)
  911. t.framesSinceUse++;
  912. }
  913. for (int i = (int) temporaryBuffers.size() - 1; i >= 0; i--)
  914. {
  915. auto &t = temporaryBuffers[i];
  916. if (t.framesSinceUse >= MAX_TEMPORARY_RESOURCE_UNUSED_FRAMES)
  917. {
  918. t.buffer->release();
  919. t = temporaryBuffers.back();
  920. temporaryBuffers.pop_back();
  921. }
  922. else if (t.framesSinceUse >= 0)
  923. t.framesSinceUse++;
  924. }
  925. }
  926. void Graphics::clearTemporaryResources()
  927. {
  928. for (auto temp :temporaryBuffers)
  929. temp.buffer->release();
  930. for (auto temp : temporaryTextures)
  931. temp.texture->release();
  932. temporaryBuffers.clear();
  933. temporaryTextures.clear();
  934. }
  935. void Graphics::updatePendingReadbacks()
  936. {
  937. for (int i = (int)pendingReadbacks.size() - 1; i >= 0; i--)
  938. {
  939. pendingReadbacks[i]->update();
  940. if (pendingReadbacks[i]->isComplete())
  941. {
  942. pendingReadbacks[i] = pendingReadbacks.back();
  943. pendingReadbacks.pop_back();
  944. }
  945. }
  946. }
  947. void Graphics::intersectScissor(const Rect &rect)
  948. {
  949. Rect currect = states.back().scissorRect;
  950. if (!states.back().scissor)
  951. {
  952. currect.x = 0;
  953. currect.y = 0;
  954. currect.w = std::numeric_limits<int>::max();
  955. currect.h = std::numeric_limits<int>::max();
  956. }
  957. int x1 = std::max(currect.x, rect.x);
  958. int y1 = std::max(currect.y, rect.y);
  959. int x2 = std::min(currect.x + currect.w, rect.x + rect.w);
  960. int y2 = std::min(currect.y + currect.h, rect.y + rect.h);
  961. Rect newrect = {x1, y1, std::max(0, x2 - x1), std::max(0, y2 - y1)};
  962. setScissor(newrect);
  963. }
  964. bool Graphics::getScissor(Rect &rect) const
  965. {
  966. const DisplayState &state = states.back();
  967. rect = state.scissorRect;
  968. return state.scissor;
  969. }
  970. void Graphics::setStencilMode()
  971. {
  972. setStencilMode(STENCIL_KEEP, COMPARE_ALWAYS, 0, LOVE_UINT32_MAX, LOVE_UINT32_MAX);
  973. }
  974. void Graphics::getStencilMode(StencilAction &action, CompareMode &compare, int &value, uint32 &readmask, uint32 &writemask) const
  975. {
  976. const DisplayState &state = states.back();
  977. action = state.stencil.action;
  978. compare = state.stencil.compare;
  979. value = state.stencil.value;
  980. readmask = state.stencil.readMask;
  981. writemask = state.stencil.writeMask;
  982. }
  983. void Graphics::setDepthMode()
  984. {
  985. setDepthMode(COMPARE_ALWAYS, false);
  986. }
  987. void Graphics::getDepthMode(CompareMode &compare, bool &write) const
  988. {
  989. const DisplayState &state = states.back();
  990. compare = state.depthTest;
  991. write = state.depthWrite;
  992. }
  993. void Graphics::setMeshCullMode(CullMode cull)
  994. {
  995. // Handled inside the draw() graphics API implementations.
  996. states.back().meshCullMode = cull;
  997. }
  998. CullMode Graphics::getMeshCullMode() const
  999. {
  1000. return states.back().meshCullMode;
  1001. }
  1002. Winding Graphics::getFrontFaceWinding() const
  1003. {
  1004. return states.back().winding;
  1005. }
  1006. ColorChannelMask Graphics::getColorMask() const
  1007. {
  1008. return states.back().colorMask;
  1009. }
  1010. void Graphics::setBlendMode(BlendMode mode, BlendAlpha alphamode)
  1011. {
  1012. if (alphamode == BLENDALPHA_MULTIPLY && !isAlphaMultiplyBlendSupported(mode))
  1013. {
  1014. const char *modestr = "unknown";
  1015. love::graphics::getConstant(mode, modestr);
  1016. throw love::Exception("The '%s' blend mode must be used with premultiplied alpha.", modestr);
  1017. }
  1018. setBlendState(computeBlendState(mode, alphamode));
  1019. }
  1020. BlendMode Graphics::getBlendMode(BlendAlpha &alphamode) const
  1021. {
  1022. return computeBlendMode(states.back().blend, alphamode);
  1023. }
  1024. const BlendState &Graphics::getBlendState() const
  1025. {
  1026. return states.back().blend;
  1027. }
  1028. void Graphics::setDefaultSamplerState(const SamplerState &s)
  1029. {
  1030. states.back().defaultSamplerState = s;
  1031. }
  1032. const SamplerState &Graphics::getDefaultSamplerState() const
  1033. {
  1034. return states.back().defaultSamplerState;
  1035. }
  1036. void Graphics::setLineWidth(float width)
  1037. {
  1038. states.back().lineWidth = width;
  1039. }
  1040. void Graphics::setLineStyle(Graphics::LineStyle style)
  1041. {
  1042. states.back().lineStyle = style;
  1043. }
  1044. void Graphics::setLineJoin(Graphics::LineJoin join)
  1045. {
  1046. states.back().lineJoin = join;
  1047. }
  1048. float Graphics::getLineWidth() const
  1049. {
  1050. return states.back().lineWidth;
  1051. }
  1052. Graphics::LineStyle Graphics::getLineStyle() const
  1053. {
  1054. return states.back().lineStyle;
  1055. }
  1056. Graphics::LineJoin Graphics::getLineJoin() const
  1057. {
  1058. return states.back().lineJoin;
  1059. }
  1060. float Graphics::getPointSize() const
  1061. {
  1062. return states.back().pointSize;
  1063. }
  1064. bool Graphics::isWireframe() const
  1065. {
  1066. return states.back().wireframe;
  1067. }
  1068. void Graphics::captureScreenshot(const ScreenshotInfo &info)
  1069. {
  1070. pendingScreenshotCallbacks.push_back(info);
  1071. }
  1072. void Graphics::copyBuffer(Buffer *source, Buffer *dest, size_t sourceoffset, size_t destoffset, size_t size)
  1073. {
  1074. if (!capabilities.features[FEATURE_COPY_BUFFER])
  1075. throw love::Exception("Buffer copying is not supported on this system.");
  1076. Range sourcerange(sourceoffset, size);
  1077. Range destrange(destoffset, size);
  1078. if (dest->getDataUsage() == BUFFERDATAUSAGE_STREAM)
  1079. throw love::Exception("Buffers created with 'stream' data usage cannot be used as a copy destination.");
  1080. if (source->getDataUsage() == BUFFERDATAUSAGE_READBACK)
  1081. throw love::Exception("Buffers created with 'readback' data usage cannot be used as a copy source.");
  1082. if (sourcerange.getMax() >= source->getSize())
  1083. throw love::Exception("Buffer copy source offset and size doesn't fit within the source Buffer's size.");
  1084. if (destrange.getMax() >= dest->getSize())
  1085. throw love::Exception("Buffer copy destination offset and size doesn't fit within the destination buffer's size.");
  1086. if (source == dest && sourcerange.intersects(destrange))
  1087. throw love::Exception("Copying a portion of a buffer to the same buffer requires non-overlapping source and destination offsets.");
  1088. if (dest->isImmutable())
  1089. throw love::Exception("Cannot copy to an immutable buffer.");
  1090. if (sourceoffset % 4 != 0 || destoffset % 4 != 0 || size % 4 != 0)
  1091. throw love::Exception("Buffer copy source offset, destination offset, and size parameters must be multiples of 4 bytes.");
  1092. source->copyTo(dest, sourceoffset, destoffset, size);
  1093. }
  1094. void Graphics::copyTextureToBuffer(Texture *source, Buffer *dest, int slice, int mipmap, const Rect &rect, size_t destoffset, int destwidth)
  1095. {
  1096. if (!capabilities.features[FEATURE_COPY_TEXTURE_TO_BUFFER])
  1097. {
  1098. if (!source->isRenderTarget())
  1099. throw love::Exception("Copying a non-render target Texture to a Buffer is not supported on this system.");
  1100. if (!capabilities.features[FEATURE_COPY_RENDER_TARGET_TO_BUFFER])
  1101. throw love::Exception("Copying a render target Texture to a Buffer is not supported on this system.");
  1102. }
  1103. PixelFormat format = source->getPixelFormat();
  1104. if (isPixelFormatDepthStencil(format))
  1105. throw love::Exception("Copying a depth/stencil Texture to a Buffer is not supported.");
  1106. if (!source->isReadable())
  1107. throw love::Exception("copyTextureToBuffer can only be called on readable Textures.");
  1108. if (dest->getDataUsage() == BUFFERDATAUSAGE_STREAM)
  1109. throw love::Exception("Buffers created with 'stream' data usage cannot be used as a copy destination.");
  1110. if (dest->isImmutable())
  1111. throw love::Exception("Cannot copy to an immutable buffer.");
  1112. if (isRenderTargetActive(source))
  1113. throw love::Exception("copyTextureToBuffer cannot be called while the Texture is an active render target.");
  1114. if (mipmap < 0 || mipmap >= source->getMipmapCount())
  1115. throw love::Exception("Invalid texture mipmap index %d.", mipmap + 1);
  1116. TextureType textype = source->getTextureType();
  1117. if (slice < 0 || (textype == TEXTURE_CUBE && slice >= 6)
  1118. || (textype == TEXTURE_VOLUME && slice >= source->getDepth(mipmap))
  1119. || (textype == TEXTURE_2D_ARRAY && slice >= source->getLayerCount()))
  1120. {
  1121. throw love::Exception("Invalid texture slice index %d.", slice + 1);
  1122. }
  1123. int mipw = source->getPixelWidth(mipmap);
  1124. int miph = source->getPixelHeight(mipmap);
  1125. if (rect.x < 0 || rect.y < 0 || rect.w <= 0 || rect.h <= 0
  1126. || (rect.x + rect.w) > mipw || (rect.y + rect.h) > miph)
  1127. {
  1128. throw love::Exception("Invalid rectangle dimensions (x=%d, y=%d, w=%d, h=%d) for %dx%d texture.", rect.x, rect.y, rect.w, rect.h, mipw, miph);
  1129. }
  1130. if (destwidth <= 0)
  1131. destwidth = rect.w;
  1132. size_t size = 0;
  1133. if (isPixelFormatCompressed(format))
  1134. {
  1135. if (destwidth != rect.w) // OpenGL limitation...
  1136. throw love::Exception("Copying a compressed texture to a buffer cannot use a custom destination width.");
  1137. const PixelFormatInfo &info = getPixelFormatInfo(format);
  1138. int bw = (int) info.blockWidth;
  1139. int bh = (int) info.blockHeight;
  1140. if (rect.x % bw != 0 || rect.y % bh != 0 ||
  1141. ((rect.w % bw != 0 || rect.h % bh != 0) && rect.x + rect.w != source->getPixelWidth(mipmap)))
  1142. {
  1143. const char *name = nullptr;
  1144. love::getConstant(format, name);
  1145. throw love::Exception("Compressed texture format %s only supports copying a sub-rectangle with offset and dimensions that are a multiple of %d x %d.", name, bw, bh);
  1146. }
  1147. // Note: this will need to change if destwidth == rect.w restriction
  1148. // is removed.
  1149. size = getPixelFormatSliceSize(format, destwidth, rect.h);
  1150. }
  1151. else
  1152. {
  1153. // Not the cleanest, but should work since uncompressed formats always
  1154. // have 1x1 blocks.
  1155. int pixels = (rect.h - 1) * destwidth + rect.w;
  1156. size = getPixelFormatUncompressedRowSize(format, pixels);
  1157. }
  1158. Range destrange(destoffset, size);
  1159. if (destoffset % 4 != 0 || size % 4 != 0)
  1160. throw love::Exception("Buffer copy destination offset and computed byte size must be multiples of 4 bytes.");
  1161. if (destrange.getMax() >= dest->getSize())
  1162. throw love::Exception("Buffer copy destination offset and width/height doesn't fit within the destination Buffer.");
  1163. source->copyToBuffer(dest, slice, mipmap, rect, destoffset, destwidth, size);
  1164. }
  1165. void Graphics::copyBufferToTexture(Buffer *source, Texture *dest, size_t sourceoffset, int sourcewidth, int slice, int mipmap, const Rect &rect)
  1166. {
  1167. if (!capabilities.features[FEATURE_COPY_BUFFER_TO_TEXTURE])
  1168. throw love::Exception("Copying a Buffer to a Texture is not supported on this system.");
  1169. if (source->getDataUsage() == BUFFERDATAUSAGE_READBACK)
  1170. throw love::Exception("Buffers created with 'readback' data usage cannot be used as a copy source.");
  1171. PixelFormat format = dest->getPixelFormat();
  1172. if (isPixelFormatDepthStencil(format))
  1173. throw love::Exception("Copying a Buffer to a depth/stencil Texture is not supported.");
  1174. if (!dest->isReadable())
  1175. throw love::Exception("copyBufferToTexture can only be called on readable Textures.");
  1176. if (isRenderTargetActive(dest))
  1177. throw love::Exception("copyBufferToTexture cannot be called while the Texture is an active render target.");
  1178. if (mipmap < 0 || mipmap >= dest->getMipmapCount())
  1179. throw love::Exception("Invalid texture mipmap index %d.", mipmap + 1);
  1180. TextureType textype = dest->getTextureType();
  1181. if (slice < 0 || (textype == TEXTURE_CUBE && slice >= 6)
  1182. || (textype == TEXTURE_VOLUME && slice >= dest->getDepth(mipmap))
  1183. || (textype == TEXTURE_2D_ARRAY && slice >= dest->getLayerCount()))
  1184. {
  1185. throw love::Exception("Invalid texture slice index %d.", slice + 1);
  1186. }
  1187. int mipw = dest->getPixelWidth(mipmap);
  1188. int miph = dest->getPixelHeight(mipmap);
  1189. if (rect.x < 0 || rect.y < 0 || rect.w <= 0 || rect.h <= 0
  1190. || (rect.x + rect.w) > mipw || (rect.y + rect.h) > miph)
  1191. {
  1192. throw love::Exception("Invalid rectangle dimensions (x=%d, y=%d, w=%d, h=%d) for %dx%d texture.", rect.x, rect.y, rect.w, rect.h, mipw, miph);
  1193. }
  1194. if (sourcewidth <= 0)
  1195. sourcewidth = rect.w;
  1196. size_t size = 0;
  1197. if (isPixelFormatCompressed(format))
  1198. {
  1199. if (sourcewidth != rect.w) // OpenGL limitation...
  1200. throw love::Exception("Copying a buffer to a compressed texture cannot use a custom source width.");
  1201. const PixelFormatInfo &info = getPixelFormatInfo(format);
  1202. int bw = (int) info.blockWidth;
  1203. int bh = (int) info.blockHeight;
  1204. if (rect.x % bw != 0 || rect.y % bh != 0 ||
  1205. ((rect.w % bw != 0 || rect.h % bh != 0) && rect.x + rect.w != dest->getPixelWidth(mipmap)))
  1206. {
  1207. const char *name = nullptr;
  1208. love::getConstant(format, name);
  1209. throw love::Exception("Compressed texture format %s only supports copying a sub-rectangle with offset and dimensions that are a multiple of %d x %d.", name, bw, bh);
  1210. }
  1211. // Note: this will need to change if sourcewidth == rect.w restriction
  1212. // is removed.
  1213. size = getPixelFormatSliceSize(format, sourcewidth, rect.h);
  1214. }
  1215. else
  1216. {
  1217. // Not the cleanest, but should work since uncompressed formats always
  1218. // have 1x1 blocks.
  1219. int pixels = (rect.h - 1) * sourcewidth + rect.w;
  1220. size = getPixelFormatUncompressedRowSize(format, pixels);
  1221. }
  1222. Range sourcerange(sourceoffset, size);
  1223. if (sourceoffset % 4 != 0 || size % 4 != 0)
  1224. throw love::Exception("Buffer copy source offset and computed byte size must be multiples of 4 bytes.");
  1225. if (sourcerange.getMax() >= source->getSize())
  1226. throw love::Exception("Buffer copy source offset and width/height doesn't fit within the source Buffer.");
  1227. dest->copyFromBuffer(source, sourceoffset, sourcewidth, size, slice, mipmap, rect);
  1228. }
  1229. static const char *getIndirectArgsTypeName(Graphics::IndirectArgsType argstype)
  1230. {
  1231. switch (argstype)
  1232. {
  1233. case Graphics::INDIRECT_ARGS_DISPATCH: return "Compute shader threadgroup argument data";
  1234. case Graphics::INDIRECT_ARGS_DRAW_VERTICES: return "Draw vertices argument data";
  1235. case Graphics::INDIRECT_ARGS_DRAW_INDICES: return "Draw indices argument data";
  1236. }
  1237. return "(Unknown argument data)";
  1238. }
  1239. void Graphics::validateIndirectArgsBuffer(IndirectArgsType argstype, Buffer *indirectargs, int argsindex)
  1240. {
  1241. if (!capabilities.features[FEATURE_INDIRECT_DRAW])
  1242. throw love::Exception("Indirect draws and compute dispatches are not supported on this system.");
  1243. if ((indirectargs->getUsageFlags() & BUFFERUSAGEFLAG_INDIRECT_ARGUMENTS) == 0)
  1244. throw love::Exception("The given Buffer must be created with the indirectarguments usage flag set, to be used for indirect arguments.");
  1245. if (argsindex < 0)
  1246. throw love::Exception("The given indirect argument index cannot be negative.");
  1247. size_t argelements = 0;
  1248. if (argstype == INDIRECT_ARGS_DISPATCH)
  1249. argelements = 3;
  1250. else if (argstype == INDIRECT_ARGS_DRAW_VERTICES)
  1251. argelements = 4;
  1252. else if (argstype == INDIRECT_ARGS_DRAW_INDICES)
  1253. argelements = 5;
  1254. size_t totalmembers = indirectargs->getArrayLength() * indirectargs->getDataMembers().size();
  1255. if (totalmembers % argelements != 0)
  1256. throw love::Exception("%s requires the given indirect argument Buffer to have a multiple of %ld int or uint values.", getIndirectArgsTypeName(argstype), argelements);
  1257. size_t argsoffset = argsindex * indirectargs->getArrayStride();
  1258. if (indirectargs->getSize() < argsoffset + sizeof(uint32) * argelements)
  1259. throw love::Exception("The given index into the indirect argument Buffer does not fit within the Buffer's size.");
  1260. }
  1261. void Graphics::dispatchThreadgroups(Shader *shader, int x, int y, int z)
  1262. {
  1263. if (!shader->hasStage(SHADERSTAGE_COMPUTE))
  1264. throw love::Exception("Only compute shaders can have threads dispatched.");
  1265. if (x <= 0 || y <= 0 || z <= 0)
  1266. throw love::Exception("Threadgroup dispatch size must be positive.");
  1267. if (x > capabilities.limits[LIMIT_THREADGROUPS_X]
  1268. || y > capabilities.limits[LIMIT_THREADGROUPS_Y]
  1269. || z > capabilities.limits[LIMIT_THREADGROUPS_Z])
  1270. {
  1271. throw love::Exception("Too many threadgroups dispatched.");
  1272. }
  1273. flushBatchedDraws();
  1274. auto prevshader = Shader::current;
  1275. shader->attach();
  1276. bool success = dispatch(shader, x, y, z);
  1277. if (prevshader != nullptr)
  1278. prevshader->attach();
  1279. if (!success)
  1280. throw love::Exception("Compute shader must have resources bound to all writable texture and buffer variables.");
  1281. }
  1282. void Graphics::dispatchIndirect(Shader *shader, Buffer *indirectargs, int argsindex)
  1283. {
  1284. if (!shader->hasStage(SHADERSTAGE_COMPUTE))
  1285. throw love::Exception("Only compute shaders can have threads dispatched.");
  1286. validateIndirectArgsBuffer(INDIRECT_ARGS_DISPATCH, indirectargs, argsindex);
  1287. flushBatchedDraws();
  1288. auto prevshader = Shader::current;
  1289. shader->attach();
  1290. bool success = dispatch(shader, indirectargs, argsindex * indirectargs->getArrayStride());
  1291. if (prevshader != nullptr)
  1292. prevshader->attach();
  1293. if (!success)
  1294. throw love::Exception("Compute shader must have resources bound to all writable texture and buffer variables.");
  1295. }
  1296. Graphics::BatchedVertexData Graphics::requestBatchedDraw(const BatchedDrawCommand &cmd)
  1297. {
  1298. BatchedDrawState &state = batchedDrawState;
  1299. bool shouldflush = false;
  1300. bool shouldresize = false;
  1301. if (cmd.primitiveMode != state.primitiveMode
  1302. || cmd.formats[0] != state.formats[0] || cmd.formats[1] != state.formats[1]
  1303. || ((cmd.indexMode != TRIANGLEINDEX_NONE) != (state.indexCount > 0))
  1304. || cmd.texture != state.texture
  1305. || cmd.standardShaderType != state.standardShaderType)
  1306. {
  1307. shouldflush = true;
  1308. }
  1309. int totalvertices = state.vertexCount + cmd.vertexCount;
  1310. // We only support uint16 index buffers for now.
  1311. if (totalvertices > LOVE_UINT16_MAX && cmd.indexMode != TRIANGLEINDEX_NONE)
  1312. shouldflush = true;
  1313. int reqIndexCount = getIndexCount(cmd.indexMode, cmd.vertexCount);
  1314. size_t reqIndexSize = reqIndexCount * sizeof(uint16);
  1315. size_t newdatasizes[2] = {0, 0};
  1316. size_t buffersizes[3] = {0, 0, 0};
  1317. for (int i = 0; i < 2; i++)
  1318. {
  1319. if (cmd.formats[i] == CommonFormat::NONE)
  1320. continue;
  1321. size_t stride = getFormatStride(cmd.formats[i]);
  1322. size_t datasize = stride * totalvertices;
  1323. if (state.vbMap[i].data != nullptr && datasize > state.vbMap[i].size)
  1324. shouldflush = true;
  1325. if (datasize > state.vb[i]->getUsableSize())
  1326. {
  1327. buffersizes[i] = std::max(datasize, state.vb[i]->getSize() * 2);
  1328. shouldresize = true;
  1329. }
  1330. newdatasizes[i] = stride * cmd.vertexCount;
  1331. }
  1332. if (cmd.indexMode != TRIANGLEINDEX_NONE)
  1333. {
  1334. size_t datasize = (state.indexCount + reqIndexCount) * sizeof(uint16);
  1335. if (state.indexBufferMap.data != nullptr && datasize > state.indexBufferMap.size)
  1336. shouldflush = true;
  1337. if (datasize > state.indexBuffer->getUsableSize())
  1338. {
  1339. buffersizes[2] = std::max(datasize, state.indexBuffer->getSize() * 2);
  1340. shouldresize = true;
  1341. }
  1342. }
  1343. if (shouldflush || shouldresize)
  1344. {
  1345. flushBatchedDraws();
  1346. state.primitiveMode = cmd.primitiveMode;
  1347. state.formats[0] = cmd.formats[0];
  1348. state.formats[1] = cmd.formats[1];
  1349. state.texture = cmd.texture;
  1350. state.standardShaderType = cmd.standardShaderType;
  1351. }
  1352. if (state.vertexCount == 0)
  1353. {
  1354. if (Shader::isDefaultActive())
  1355. Shader::attachDefault(state.standardShaderType);
  1356. if (Shader::current != nullptr)
  1357. Shader::current->validateDrawState(cmd.primitiveMode, cmd.texture);
  1358. }
  1359. if (shouldresize)
  1360. {
  1361. for (int i = 0; i < 2; i++)
  1362. {
  1363. if (state.vb[i]->getSize() < buffersizes[i])
  1364. {
  1365. state.vb[i]->release();
  1366. state.vb[i] = newStreamBuffer(BUFFERUSAGE_VERTEX, buffersizes[i]);
  1367. }
  1368. }
  1369. if (state.indexBuffer->getSize() < buffersizes[2])
  1370. {
  1371. state.indexBuffer->release();
  1372. state.indexBuffer = newStreamBuffer(BUFFERUSAGE_INDEX, buffersizes[2]);
  1373. }
  1374. }
  1375. if (cmd.indexMode != TRIANGLEINDEX_NONE)
  1376. {
  1377. if (state.indexBufferMap.data == nullptr)
  1378. state.indexBufferMap = state.indexBuffer->map(reqIndexSize);
  1379. uint16 *indices = (uint16 *) state.indexBufferMap.data;
  1380. fillIndices(cmd.indexMode, state.vertexCount, cmd.vertexCount, indices);
  1381. state.indexBufferMap.data += reqIndexSize;
  1382. }
  1383. BatchedVertexData d;
  1384. for (int i = 0; i < 2; i++)
  1385. {
  1386. if (newdatasizes[i] > 0)
  1387. {
  1388. if (state.vbMap[i].data == nullptr)
  1389. state.vbMap[i] = state.vb[i]->map(newdatasizes[i]);
  1390. d.stream[i] = state.vbMap[i].data;
  1391. state.vbMap[i].data += newdatasizes[i];
  1392. }
  1393. }
  1394. if (state.vertexCount > 0)
  1395. drawCallsBatched++;
  1396. state.vertexCount += cmd.vertexCount;
  1397. state.indexCount += reqIndexCount;
  1398. return d;
  1399. }
  1400. void Graphics::flushBatchedDraws()
  1401. {
  1402. auto &sbstate = batchedDrawState;
  1403. if (sbstate.vertexCount == 0 && sbstate.indexCount == 0)
  1404. return;
  1405. VertexAttributes attributes;
  1406. BufferBindings buffers;
  1407. size_t usedsizes[3] = {0, 0, 0};
  1408. for (int i = 0; i < 2; i++)
  1409. {
  1410. if (sbstate.formats[i] == CommonFormat::NONE)
  1411. continue;
  1412. attributes.setCommonFormat(sbstate.formats[i], (uint8) i);
  1413. usedsizes[i] = getFormatStride(sbstate.formats[i]) * sbstate.vertexCount;
  1414. size_t offset = sbstate.vb[i]->unmap(usedsizes[i]);
  1415. buffers.set(i, sbstate.vb[i], offset);
  1416. sbstate.vbMap[i] = StreamBuffer::MapInfo();
  1417. }
  1418. if (attributes.enableBits == 0)
  1419. return;
  1420. Colorf nc = getColor();
  1421. if (attributes.isEnabled(ATTRIB_COLOR))
  1422. setColor(Colorf(1.0f, 1.0f, 1.0f, 1.0f));
  1423. pushIdentityTransform();
  1424. if (sbstate.indexCount > 0)
  1425. {
  1426. usedsizes[2] = sizeof(uint16) * sbstate.indexCount;
  1427. DrawIndexedCommand cmd(&attributes, &buffers, sbstate.indexBuffer);
  1428. cmd.primitiveType = sbstate.primitiveMode;
  1429. cmd.indexCount = sbstate.indexCount;
  1430. cmd.indexType = INDEX_UINT16;
  1431. cmd.indexBufferOffset = sbstate.indexBuffer->unmap(usedsizes[2]);
  1432. cmd.texture = sbstate.texture;
  1433. draw(cmd);
  1434. sbstate.indexBufferMap = StreamBuffer::MapInfo();
  1435. }
  1436. else
  1437. {
  1438. DrawCommand cmd(&attributes, &buffers);
  1439. cmd.primitiveType = sbstate.primitiveMode;
  1440. cmd.vertexStart = 0;
  1441. cmd.vertexCount = sbstate.vertexCount;
  1442. cmd.texture = sbstate.texture;
  1443. draw(cmd);
  1444. }
  1445. for (int i = 0; i < 2; i++)
  1446. {
  1447. if (usedsizes[i] > 0)
  1448. sbstate.vb[i]->markUsed(usedsizes[i]);
  1449. }
  1450. if (usedsizes[2] > 0)
  1451. sbstate.indexBuffer->markUsed(usedsizes[2]);
  1452. popTransform();
  1453. if (attributes.isEnabled(ATTRIB_COLOR))
  1454. setColor(nc);
  1455. batchedDrawState.vertexCount = 0;
  1456. batchedDrawState.indexCount = 0;
  1457. }
  1458. void Graphics::flushBatchedDrawsGlobal()
  1459. {
  1460. Graphics *instance = getInstance<Graphics>(M_GRAPHICS);
  1461. if (instance != nullptr)
  1462. instance->flushBatchedDraws();
  1463. }
  1464. /**
  1465. * Drawing
  1466. **/
  1467. void Graphics::draw(Drawable *drawable, const Matrix4 &m)
  1468. {
  1469. drawable->draw(this, m);
  1470. }
  1471. void Graphics::draw(Texture *texture, Quad *quad, const Matrix4 &m)
  1472. {
  1473. texture->draw(this, quad, m);
  1474. }
  1475. void Graphics::drawLayer(Texture *texture, int layer, const Matrix4 &m)
  1476. {
  1477. texture->drawLayer(this, layer, m);
  1478. }
  1479. void Graphics::drawLayer(Texture *texture, int layer, Quad *quad, const Matrix4 &m)
  1480. {
  1481. texture->drawLayer(this, layer, quad, m);
  1482. }
  1483. void Graphics::drawInstanced(Mesh *mesh, const Matrix4 &m, int instancecount)
  1484. {
  1485. mesh->drawInstanced(this, m, instancecount);
  1486. }
  1487. void Graphics::drawIndirect(Mesh *mesh, const Matrix4 &m, Buffer *indirectargs, int argsindex)
  1488. {
  1489. mesh->drawIndirect(this, m, indirectargs, argsindex);
  1490. }
  1491. void Graphics::drawFromShader(PrimitiveType primtype, int vertexcount, int instancecount, Texture *maintexture)
  1492. {
  1493. if (primtype == PRIMITIVE_TRIANGLE_FAN && vertexcount > LOVE_UINT16_MAX)
  1494. throw love::Exception("drawFromShader cannot draw more than %d vertices when the 'fan' draw mode is used.", LOVE_UINT16_MAX);
  1495. // Emulated triangle fan via an index buffer.
  1496. if (primtype == PRIMITIVE_TRIANGLE_FAN && getFanIndexBuffer())
  1497. {
  1498. int indexcount = getIndexCount(TRIANGLEINDEX_FAN, vertexcount);
  1499. drawFromShader(getFanIndexBuffer(), indexcount, instancecount, 0, maintexture);
  1500. return;
  1501. }
  1502. flushBatchedDraws();
  1503. if (!capabilities.features[FEATURE_GLSL3])
  1504. throw love::Exception("drawFromShader is not supported on this system (GLSL3 support is required.)");
  1505. if (Shader::isDefaultActive() || !Shader::current)
  1506. throw love::Exception("drawFromShader can only be used with a custom shader.");
  1507. if (vertexcount < 0 || instancecount < 0)
  1508. throw love::Exception("drawFromShader vertex and instance count parameters must not be negative.");
  1509. Shader::current->validateDrawState(primtype, maintexture);
  1510. VertexAttributes attributes;
  1511. BufferBindings buffers;
  1512. DrawCommand cmd(&attributes, &buffers);
  1513. cmd.primitiveType = primtype;
  1514. cmd.vertexCount = vertexcount;
  1515. cmd.instanceCount = std::max(1, instancecount);
  1516. cmd.texture = maintexture;
  1517. draw(cmd);
  1518. }
  1519. void Graphics::drawFromShader(Buffer *indexbuffer, int indexcount, int instancecount, int startindex, Texture *maintexture)
  1520. {
  1521. flushBatchedDraws();
  1522. if (!capabilities.features[FEATURE_GLSL3])
  1523. throw love::Exception("drawFromShader is not supported on this system (GLSL3 support is required.)");
  1524. if (!(indexbuffer->getUsageFlags() & BUFFERUSAGEFLAG_INDEX))
  1525. throw love::Exception("The buffer passed to drawFromShader must be an index buffer.");
  1526. if (startindex < 0)
  1527. throw love::Exception("drawFromShader startindex parameter must not be negative.");
  1528. if (indexcount < 0 || instancecount < 0)
  1529. throw love::Exception("drawFromShader index and instance count parameters must not be negative.");
  1530. if ((size_t)(startindex + indexcount) > indexbuffer->getArrayLength() * indexbuffer->getDataMembers().size())
  1531. throw love::Exception("drawFromShader startindex and index count parameters do not fit in the given index buffer.");
  1532. if (Shader::isDefaultActive() || !Shader::current)
  1533. throw love::Exception("drawFromShader can only be used with a custom shader.");
  1534. Shader::current->validateDrawState(PRIMITIVE_TRIANGLES, maintexture);
  1535. VertexAttributes attributes;
  1536. BufferBindings buffers;
  1537. DrawIndexedCommand cmd(&attributes, &buffers, indexbuffer);
  1538. cmd.primitiveType = PRIMITIVE_TRIANGLES;
  1539. cmd.indexCount = indexcount;
  1540. cmd.instanceCount = std::max(1, instancecount);
  1541. cmd.indexType = getIndexDataType(indexbuffer->getDataMember(0).decl.format);
  1542. cmd.indexBufferOffset = startindex * getIndexDataSize(cmd.indexType);
  1543. cmd.texture = maintexture;
  1544. draw(cmd);
  1545. }
  1546. void Graphics::drawFromShaderIndirect(PrimitiveType primtype, Buffer *indirectargs, int argsindex, Texture *maintexture)
  1547. {
  1548. flushBatchedDraws();
  1549. if (primtype == PRIMITIVE_TRIANGLE_FAN)
  1550. throw love::Exception("The fan draw mode is not supported in indirect draws.");
  1551. if (Shader::isDefaultActive() || !Shader::current)
  1552. throw love::Exception("drawFromShaderIndirect can only be used with a custom shader.");
  1553. validateIndirectArgsBuffer(INDIRECT_ARGS_DRAW_VERTICES, indirectargs, argsindex);
  1554. Shader::current->validateDrawState(primtype, maintexture);
  1555. VertexAttributes attributes;
  1556. BufferBindings buffers;
  1557. DrawCommand cmd(&attributes, &buffers);
  1558. cmd.primitiveType = primtype;
  1559. cmd.indirectBuffer = indirectargs;
  1560. cmd.indirectBufferOffset = argsindex * indirectargs->getArrayStride();
  1561. cmd.texture = maintexture;
  1562. draw(cmd);
  1563. }
  1564. void Graphics::drawFromShaderIndirect(Buffer *indexbuffer, Buffer *indirectargs, int argsindex, Texture *maintexture)
  1565. {
  1566. flushBatchedDraws();
  1567. if (!(indexbuffer->getUsageFlags() & BUFFERUSAGEFLAG_INDEX))
  1568. throw love::Exception("The buffer passed to the indexed variant of drawFromShaderIndirect must be an index buffer.");
  1569. if (Shader::isDefaultActive() || !Shader::current)
  1570. throw love::Exception("drawFromShaderIndirect can only be used with a custom shader.");
  1571. validateIndirectArgsBuffer(INDIRECT_ARGS_DRAW_INDICES, indirectargs, argsindex);
  1572. Shader::current->validateDrawState(PRIMITIVE_TRIANGLES, maintexture);
  1573. VertexAttributes attributes;
  1574. BufferBindings buffers;
  1575. DrawIndexedCommand cmd(&attributes, &buffers, indexbuffer);
  1576. cmd.primitiveType = PRIMITIVE_TRIANGLES;
  1577. cmd.indexType = getIndexDataType(indexbuffer->getDataMember(0).decl.format);
  1578. cmd.indirectBuffer = indirectargs;
  1579. cmd.indexBufferOffset = argsindex * indirectargs->getArrayStride();
  1580. cmd.texture = maintexture;
  1581. draw(cmd);
  1582. }
  1583. void Graphics::print(const std::vector<love::font::ColoredString> &str, const Matrix4 &m)
  1584. {
  1585. checkSetDefaultFont();
  1586. if (states.back().font.get() != nullptr)
  1587. print(str, states.back().font.get(), m);
  1588. }
  1589. void Graphics::print(const std::vector<love::font::ColoredString> &str, Font *font, const Matrix4 &m)
  1590. {
  1591. font->print(this, str, m, states.back().color);
  1592. }
  1593. void Graphics::printf(const std::vector<love::font::ColoredString> &str, float wrap, Font::AlignMode align, const Matrix4 &m)
  1594. {
  1595. checkSetDefaultFont();
  1596. if (states.back().font.get() != nullptr)
  1597. printf(str, states.back().font.get(), wrap, align, m);
  1598. }
  1599. void Graphics::printf(const std::vector<love::font::ColoredString> &str, Font *font, float wrap, Font::AlignMode align, const Matrix4 &m)
  1600. {
  1601. font->printf(this, str, wrap, align, m, states.back().color);
  1602. }
  1603. /**
  1604. * Primitives (points, shapes, lines).
  1605. **/
  1606. void Graphics::points(const Vector2 *positions, const Colorf *colors, size_t numpoints)
  1607. {
  1608. const Matrix4 &t = getTransform();
  1609. bool is2D = t.isAffine2DTransform();
  1610. BatchedDrawCommand cmd;
  1611. cmd.primitiveMode = PRIMITIVE_POINTS;
  1612. cmd.formats[0] = getSinglePositionFormat(is2D);
  1613. cmd.formats[1] = CommonFormat::RGBAub;
  1614. cmd.vertexCount = (int) numpoints;
  1615. cmd.standardShaderType = Shader::STANDARD_POINTS;
  1616. BatchedVertexData data = requestBatchedDraw(cmd);
  1617. if (is2D)
  1618. t.transformXY((Vector2 *) data.stream[0], positions, cmd.vertexCount);
  1619. else
  1620. t.transformXY0((Vector3 *) data.stream[0], positions, cmd.vertexCount);
  1621. Color32 *colordata = (Color32 *) data.stream[1];
  1622. if (colors)
  1623. {
  1624. Colorf nc = getColor();
  1625. gammaCorrectColor(nc);
  1626. if (isGammaCorrect())
  1627. {
  1628. for (int i = 0; i < cmd.vertexCount; i++)
  1629. {
  1630. Colorf ci = colors[i];
  1631. gammaCorrectColor(ci);
  1632. ci *= nc;
  1633. unGammaCorrectColor(ci);
  1634. colordata[i] = toColor32(ci);
  1635. }
  1636. }
  1637. else
  1638. {
  1639. for (int i = 0; i < cmd.vertexCount; i++)
  1640. colordata[i] = toColor32(nc * colors[i]);
  1641. }
  1642. }
  1643. else
  1644. {
  1645. Color32 c = toColor32(getColor());
  1646. for (int i = 0; i < cmd.vertexCount; i++)
  1647. colordata[i] = c;
  1648. }
  1649. }
  1650. int Graphics::calculateEllipsePoints(float rx, float ry) const
  1651. {
  1652. int points = (int) sqrtf(((rx + ry) / 2.0f) * 20.0f * (float) pixelScaleStack.back());
  1653. return std::max(points, 8);
  1654. }
  1655. void Graphics::polyline(const Vector2 *vertices, size_t count)
  1656. {
  1657. float halfwidth = getLineWidth() * 0.5f;
  1658. LineJoin linejoin = getLineJoin();
  1659. LineStyle linestyle = getLineStyle();
  1660. float pixelsize = 1.0f / std::max((float) pixelScaleStack.back(), 0.000001f);
  1661. if (linejoin == LINE_JOIN_NONE)
  1662. {
  1663. NoneJoinPolyline line;
  1664. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1665. line.draw(this);
  1666. }
  1667. else if (linejoin == LINE_JOIN_BEVEL)
  1668. {
  1669. BevelJoinPolyline line;
  1670. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1671. line.draw(this);
  1672. }
  1673. else if (linejoin == LINE_JOIN_MITER)
  1674. {
  1675. MiterJoinPolyline line;
  1676. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1677. line.draw(this);
  1678. }
  1679. }
  1680. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  1681. {
  1682. Vector2 coords[] = {Vector2(x,y), Vector2(x,y+h), Vector2(x+w,y+h), Vector2(x+w,y), Vector2(x,y)};
  1683. polygon(mode, coords, 5);
  1684. }
  1685. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry, int points)
  1686. {
  1687. if (rx <= 0 || ry <= 0)
  1688. {
  1689. rectangle(mode, x, y, w, h);
  1690. return;
  1691. }
  1692. // Radius values that are more than half the rectangle's size aren't handled
  1693. // correctly (for now)...
  1694. if (w >= 0.02f)
  1695. rx = std::min(rx, w / 2.0f - 0.01f);
  1696. if (h >= 0.02f)
  1697. ry = std::min(ry, h / 2.0f - 0.01f);
  1698. points = std::max(points / 4, 1);
  1699. const float half_pi = static_cast<float>(LOVE_M_PI / 2);
  1700. float angle_shift = half_pi / ((float) points + 1.0f);
  1701. int num_coords = (points + 2) * 4;
  1702. Vector2 *coords = getScratchBuffer<Vector2>(num_coords + 1);
  1703. float phi = .0f;
  1704. for (int i = 0; i <= points + 2; ++i, phi += angle_shift)
  1705. {
  1706. coords[i].x = x + rx * (1 - cosf(phi));
  1707. coords[i].y = y + ry * (1 - sinf(phi));
  1708. }
  1709. phi = half_pi;
  1710. for (int i = points + 2; i <= 2 * (points + 2); ++i, phi += angle_shift)
  1711. {
  1712. coords[i].x = x + w - rx * (1 + cosf(phi));
  1713. coords[i].y = y + ry * (1 - sinf(phi));
  1714. }
  1715. phi = 2 * half_pi;
  1716. for (int i = 2 * (points + 2); i <= 3 * (points + 2); ++i, phi += angle_shift)
  1717. {
  1718. coords[i].x = x + w - rx * (1 + cosf(phi));
  1719. coords[i].y = y + h - ry * (1 + sinf(phi));
  1720. }
  1721. phi = 3 * half_pi;
  1722. for (int i = 3 * (points + 2); i <= 4 * (points + 2); ++i, phi += angle_shift)
  1723. {
  1724. coords[i].x = x + rx * (1 - cosf(phi));
  1725. coords[i].y = y + h - ry * (1 + sinf(phi));
  1726. }
  1727. coords[num_coords] = coords[0];
  1728. polygon(mode, coords, num_coords + 1);
  1729. }
  1730. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry)
  1731. {
  1732. int points = calculateEllipsePoints(std::min(rx, std::abs(w/2)), std::min(ry, std::abs(h/2)));
  1733. rectangle(mode, x, y, w, h, rx, ry, points);
  1734. }
  1735. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  1736. {
  1737. ellipse(mode, x, y, radius, radius, points);
  1738. }
  1739. void Graphics::circle(DrawMode mode, float x, float y, float radius)
  1740. {
  1741. ellipse(mode, x, y, radius, radius);
  1742. }
  1743. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b, int points)
  1744. {
  1745. float two_pi = (float) (LOVE_M_PI * 2);
  1746. if (points <= 0) points = 1;
  1747. float angle_shift = (two_pi / points);
  1748. float phi = .0f;
  1749. // 1 extra point at the end for a closed loop, and 1 extra point at the
  1750. // start in filled mode for the vertex in the center of the ellipse.
  1751. int extrapoints = 1 + (mode == DRAW_FILL ? 1 : 0);
  1752. Vector2 *polygoncoords = getScratchBuffer<Vector2>(points + extrapoints);
  1753. Vector2 *coords = polygoncoords;
  1754. if (mode == DRAW_FILL)
  1755. {
  1756. coords[0].x = x;
  1757. coords[0].y = y;
  1758. coords++;
  1759. }
  1760. for (int i = 0; i < points; ++i, phi += angle_shift)
  1761. {
  1762. coords[i].x = x + a * cosf(phi);
  1763. coords[i].y = y + b * sinf(phi);
  1764. }
  1765. coords[points] = coords[0];
  1766. // Last argument to polygon(): don't skip the last vertex in fill mode.
  1767. polygon(mode, polygoncoords, points + extrapoints, false);
  1768. }
  1769. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b)
  1770. {
  1771. ellipse(mode, x, y, a, b, calculateEllipsePoints(a, b));
  1772. }
  1773. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2, int points)
  1774. {
  1775. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  1776. if (points <= 0 || angle1 == angle2)
  1777. return;
  1778. // Oh, you want to draw a circle?
  1779. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  1780. {
  1781. circle(drawmode, x, y, radius, points);
  1782. return;
  1783. }
  1784. float angle_shift = (angle2 - angle1) / points;
  1785. // Bail on precision issues.
  1786. if (angle_shift == 0.0)
  1787. return;
  1788. // Prevent the connecting line from being drawn if a closed line arc has a
  1789. // small angle. Avoids some visual issues when connected lines are at sharp
  1790. // angles, due to the miter line join drawing code.
  1791. if (drawmode == DRAW_LINE && arcmode == ARC_CLOSED && fabsf(angle1 - angle2) < LOVE_TORAD(4))
  1792. arcmode = ARC_OPEN;
  1793. // Quick fix for the last part of a filled open arc not being drawn (because
  1794. // polygon(DRAW_FILL, ...) doesn't work without a closed loop of vertices.)
  1795. if (drawmode == DRAW_FILL && arcmode == ARC_OPEN)
  1796. arcmode = ARC_CLOSED;
  1797. float phi = angle1;
  1798. Vector2 *coords = nullptr;
  1799. int num_coords = 0;
  1800. const auto createPoints = [&](Vector2 *coordinates)
  1801. {
  1802. for (int i = 0; i <= points; ++i, phi += angle_shift)
  1803. {
  1804. coordinates[i].x = x + radius * cosf(phi);
  1805. coordinates[i].y = y + radius * sinf(phi);
  1806. }
  1807. };
  1808. if (arcmode == ARC_PIE)
  1809. {
  1810. num_coords = points + 3;
  1811. coords = getScratchBuffer<Vector2>(num_coords);
  1812. coords[0] = coords[num_coords - 1] = Vector2(x, y);
  1813. createPoints(coords + 1);
  1814. }
  1815. else if (arcmode == ARC_OPEN)
  1816. {
  1817. num_coords = points + 1;
  1818. coords = getScratchBuffer<Vector2>(num_coords);
  1819. createPoints(coords);
  1820. }
  1821. else // ARC_CLOSED
  1822. {
  1823. num_coords = points + 2;
  1824. coords = getScratchBuffer<Vector2>(num_coords);
  1825. createPoints(coords);
  1826. // Connect the ends of the arc.
  1827. coords[num_coords - 1] = coords[0];
  1828. }
  1829. polygon(drawmode, coords, num_coords);
  1830. }
  1831. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2)
  1832. {
  1833. float points = (float) calculateEllipsePoints(radius, radius);
  1834. // The amount of points is based on the fraction of the circle created by the arc.
  1835. float angle = fabsf(angle1 - angle2);
  1836. if (angle < 2.0f * (float) LOVE_M_PI)
  1837. points *= angle / (2.0f * (float) LOVE_M_PI);
  1838. arc(drawmode, arcmode, x, y, radius, angle1, angle2, (int) (points + 0.5f));
  1839. }
  1840. void Graphics::polygon(DrawMode mode, const Vector2 *coords, size_t count, bool skipLastFilledVertex)
  1841. {
  1842. // coords is an array of a closed loop of vertices, i.e.
  1843. // coords[count-1] == coords[0]
  1844. if (mode == DRAW_LINE)
  1845. {
  1846. polyline(coords, count);
  1847. }
  1848. else
  1849. {
  1850. const Matrix4 &t = getTransform();
  1851. bool is2D = t.isAffine2DTransform();
  1852. BatchedDrawCommand cmd;
  1853. cmd.formats[0] = getSinglePositionFormat(is2D);
  1854. cmd.formats[1] = CommonFormat::RGBAub;
  1855. cmd.indexMode = TRIANGLEINDEX_FAN;
  1856. cmd.vertexCount = (int)count - (skipLastFilledVertex ? 1 : 0);
  1857. BatchedVertexData data = requestBatchedDraw(cmd);
  1858. if (is2D)
  1859. t.transformXY((Vector2 *) data.stream[0], coords, cmd.vertexCount);
  1860. else
  1861. t.transformXY0((Vector3 *) data.stream[0], coords, cmd.vertexCount);
  1862. Color32 c = toColor32(getColor());
  1863. Color32 *colordata = (Color32 *) data.stream[1];
  1864. for (int i = 0; i < cmd.vertexCount; i++)
  1865. colordata[i] = c;
  1866. }
  1867. }
  1868. const Graphics::Capabilities &Graphics::getCapabilities() const
  1869. {
  1870. return capabilities;
  1871. }
  1872. PixelFormat Graphics::getSizedFormat(PixelFormat format) const
  1873. {
  1874. switch (format)
  1875. {
  1876. case PIXELFORMAT_NORMAL:
  1877. if (isGammaCorrect())
  1878. return PIXELFORMAT_RGBA8_sRGB;
  1879. else
  1880. return PIXELFORMAT_RGBA8_UNORM;
  1881. case PIXELFORMAT_HDR:
  1882. return PIXELFORMAT_RGBA16_FLOAT;
  1883. default:
  1884. return format;
  1885. }
  1886. }
  1887. Graphics::Stats Graphics::getStats() const
  1888. {
  1889. Stats stats;
  1890. getAPIStats(stats.shaderSwitches);
  1891. stats.drawCalls = drawCalls;
  1892. if (batchedDrawState.vertexCount > 0)
  1893. stats.drawCalls++;
  1894. stats.renderTargetSwitches = renderTargetSwitchCount;
  1895. stats.drawCallsBatched = drawCallsBatched;
  1896. stats.textures = Texture::textureCount;
  1897. stats.fonts = Font::fontCount;
  1898. stats.textureMemory = Texture::totalGraphicsMemory;
  1899. return stats;
  1900. }
  1901. size_t Graphics::getStackDepth() const
  1902. {
  1903. return stackTypeStack.size();
  1904. }
  1905. void Graphics::push(StackType type)
  1906. {
  1907. if (stackTypeStack.size() == MAX_USER_STACK_DEPTH)
  1908. throw Exception("Maximum stack depth reached (more pushes than pops?)");
  1909. pushTransform();
  1910. pixelScaleStack.push_back(pixelScaleStack.back());
  1911. if (type == STACK_ALL)
  1912. states.push_back(states.back());
  1913. stackTypeStack.push_back(type);
  1914. }
  1915. void Graphics::pop()
  1916. {
  1917. if (stackTypeStack.size() < 1)
  1918. throw Exception("Minimum stack depth reached (more pops than pushes?)");
  1919. popTransform();
  1920. pixelScaleStack.pop_back();
  1921. if (stackTypeStack.back() == STACK_ALL)
  1922. {
  1923. DisplayState &newstate = states[states.size() - 2];
  1924. restoreStateChecked(newstate);
  1925. // The last two states in the stack should be equal now.
  1926. states.pop_back();
  1927. }
  1928. stackTypeStack.pop_back();
  1929. }
  1930. /**
  1931. * Transform and stack functions.
  1932. **/
  1933. const Matrix4 &Graphics::getTransform() const
  1934. {
  1935. return transformStack.back();
  1936. }
  1937. const Matrix4 &Graphics::getDeviceProjection() const
  1938. {
  1939. return deviceProjectionMatrix;
  1940. }
  1941. void Graphics::pushTransform()
  1942. {
  1943. transformStack.push_back(transformStack.back());
  1944. }
  1945. void Graphics::pushIdentityTransform()
  1946. {
  1947. transformStack.push_back(Matrix4());
  1948. }
  1949. void Graphics::popTransform()
  1950. {
  1951. transformStack.pop_back();
  1952. }
  1953. void Graphics::rotate(float r)
  1954. {
  1955. transformStack.back().rotate(r);
  1956. }
  1957. void Graphics::scale(float x, float y)
  1958. {
  1959. transformStack.back().scale(x, y);
  1960. pixelScaleStack.back() *= (fabs(x) + fabs(y)) / 2.0;
  1961. }
  1962. void Graphics::translate(float x, float y)
  1963. {
  1964. transformStack.back().translate(x, y);
  1965. }
  1966. void Graphics::shear(float kx, float ky)
  1967. {
  1968. transformStack.back().shear(kx, ky);
  1969. }
  1970. void Graphics::origin()
  1971. {
  1972. transformStack.back().setIdentity();
  1973. pixelScaleStack.back() = 1;
  1974. }
  1975. void Graphics::applyTransform(const Matrix4 &m)
  1976. {
  1977. Matrix4 &current = transformStack.back();
  1978. current *= m;
  1979. float sx, sy;
  1980. current.getApproximateScale(sx, sy);
  1981. pixelScaleStack.back() = (sx + sy) / 2.0;
  1982. }
  1983. void Graphics::replaceTransform(const Matrix4 &m)
  1984. {
  1985. transformStack.back() = m;
  1986. float sx, sy;
  1987. m.getApproximateScale(sx, sy);
  1988. pixelScaleStack.back() = (sx + sy) / 2.0;
  1989. }
  1990. Vector2 Graphics::transformPoint(Vector2 point)
  1991. {
  1992. Vector2 p;
  1993. transformStack.back().transformXY(&p, &point, 1);
  1994. return p;
  1995. }
  1996. Vector2 Graphics::inverseTransformPoint(Vector2 point)
  1997. {
  1998. Vector2 p;
  1999. // TODO: We should probably cache the inverse transform so we don't have to
  2000. // re-calculate it every time this is called.
  2001. transformStack.back().inverse().transformXY(&p, &point, 1);
  2002. return p;
  2003. }
  2004. void Graphics::setOrthoProjection(float w, float h, float near, float far)
  2005. {
  2006. if (near >= far)
  2007. throw love::Exception("Orthographic projection Z far value must be greater than the Z near value.");
  2008. Matrix4 m = Matrix4::ortho(0.0f, w, 0.0f, h, near, far);
  2009. setCustomProjection(m);
  2010. }
  2011. void Graphics::setPerspectiveProjection(float verticalfov, float aspect, float near, float far)
  2012. {
  2013. if (near <= 0.0f)
  2014. throw love::Exception("Perspective projection Z near value must be greater than 0.");
  2015. if (near >= far)
  2016. throw love::Exception("Perspective projection Z far value must be greater than the Z near value.");
  2017. Matrix4 m = Matrix4::perspective(verticalfov, aspect, near, far);
  2018. setCustomProjection(m);
  2019. }
  2020. void Graphics::setCustomProjection(const Matrix4 &m)
  2021. {
  2022. flushBatchedDraws();
  2023. auto &state = states.back();
  2024. state.useCustomProjection = true;
  2025. state.customProjection = m;
  2026. updateDeviceProjection(m);
  2027. }
  2028. void Graphics::resetProjection()
  2029. {
  2030. flushBatchedDraws();
  2031. auto &state = states.back();
  2032. int w = getWidth();
  2033. int h = getHeight();
  2034. const auto &rt = state.renderTargets.getFirstTarget();
  2035. if (rt.texture.get())
  2036. {
  2037. w = rt.texture->getWidth(rt.mipmap);
  2038. h = rt.texture->getHeight(rt.mipmap);
  2039. }
  2040. state.useCustomProjection = false;
  2041. updateDeviceProjection(Matrix4::ortho(0.0f, w, 0.0f, h, -10.0f, 10.0f));
  2042. }
  2043. void Graphics::updateDeviceProjection(const Matrix4 &projection)
  2044. {
  2045. // Note: graphics implementations define computeDeviceProjection.
  2046. deviceProjectionMatrix = computeDeviceProjection(projection, isRenderTargetActive());
  2047. }
  2048. Matrix4 Graphics::calculateDeviceProjection(const Matrix4 &projection, uint32 flags) const
  2049. {
  2050. Matrix4 m = projection;
  2051. bool reverseZ = (flags & DEVICE_PROJECTION_REVERSE_Z) != 0;
  2052. if (flags & DEVICE_PROJECTION_FLIP_Y)
  2053. m.setRow(1, -m.getRow(1));
  2054. if (flags & DEVICE_PROJECTION_Z_01) // Go from Z [-1, 1] to Z [0, 1].
  2055. m.setRow(2, m.getRow(2) * (reverseZ ? -0.5f : 0.5f) + m.getRow(3));
  2056. else if (reverseZ)
  2057. m.setRow(2, -m.getRow(2));
  2058. return m;
  2059. }
  2060. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::DrawMode, Graphics::DRAW_MAX_ENUM, drawMode)
  2061. {
  2062. { "line", Graphics::DRAW_LINE },
  2063. { "fill", Graphics::DRAW_FILL },
  2064. }
  2065. STRINGMAP_CLASS_END(Graphics, Graphics::DrawMode, Graphics::DRAW_MAX_ENUM, drawMode)
  2066. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::ArcMode, Graphics::ARC_MAX_ENUM, arcMode)
  2067. {
  2068. { "open", Graphics::ARC_OPEN },
  2069. { "closed", Graphics::ARC_CLOSED },
  2070. { "pie", Graphics::ARC_PIE },
  2071. }
  2072. STRINGMAP_CLASS_END(Graphics, Graphics::ArcMode, Graphics::ARC_MAX_ENUM, arcMode)
  2073. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::LineStyle, Graphics::LINE_MAX_ENUM, lineStyle)
  2074. {
  2075. { "smooth", Graphics::LINE_SMOOTH },
  2076. { "rough", Graphics::LINE_ROUGH }
  2077. }
  2078. STRINGMAP_CLASS_END(Graphics, Graphics::LineStyle, Graphics::LINE_MAX_ENUM, lineStyle)
  2079. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::LineJoin, Graphics::LINE_JOIN_MAX_ENUM, lineJoin)
  2080. {
  2081. { "none", Graphics::LINE_JOIN_NONE },
  2082. { "miter", Graphics::LINE_JOIN_MITER },
  2083. { "bevel", Graphics::LINE_JOIN_BEVEL }
  2084. }
  2085. STRINGMAP_CLASS_END(Graphics, Graphics::LineJoin, Graphics::LINE_JOIN_MAX_ENUM, lineJoin)
  2086. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::Feature, Graphics::FEATURE_MAX_ENUM, feature)
  2087. {
  2088. { "multirendertargetformats", Graphics::FEATURE_MULTI_RENDER_TARGET_FORMATS },
  2089. { "clampzero", Graphics::FEATURE_CLAMP_ZERO },
  2090. { "clampone", Graphics::FEATURE_CLAMP_ONE },
  2091. { "blendminmax", Graphics::FEATURE_BLEND_MINMAX },
  2092. { "lighten", Graphics::FEATURE_LIGHTEN },
  2093. { "fullnpot", Graphics::FEATURE_FULL_NPOT },
  2094. { "pixelshaderhighp", Graphics::FEATURE_PIXEL_SHADER_HIGHP },
  2095. { "shaderderivatives", Graphics::FEATURE_SHADER_DERIVATIVES },
  2096. { "glsl3", Graphics::FEATURE_GLSL3 },
  2097. { "glsl4", Graphics::FEATURE_GLSL4 },
  2098. { "instancing", Graphics::FEATURE_INSTANCING },
  2099. { "texelbuffer", Graphics::FEATURE_TEXEL_BUFFER },
  2100. { "indexbuffer32bit", Graphics::FEATURE_INDEX_BUFFER_32BIT },
  2101. { "copybuffer", Graphics::FEATURE_COPY_BUFFER },
  2102. { "copybuffertotexture", Graphics::FEATURE_COPY_BUFFER_TO_TEXTURE },
  2103. { "copytexturetobuffer", Graphics::FEATURE_COPY_TEXTURE_TO_BUFFER },
  2104. { "copyrendertargettobuffer", Graphics::FEATURE_COPY_RENDER_TARGET_TO_BUFFER },
  2105. { "mipmaprange", Graphics::FEATURE_MIPMAP_RANGE },
  2106. { "indirectdraw", Graphics::FEATURE_INDIRECT_DRAW },
  2107. }
  2108. STRINGMAP_CLASS_END(Graphics, Graphics::Feature, Graphics::FEATURE_MAX_ENUM, feature)
  2109. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::SystemLimit, Graphics::LIMIT_MAX_ENUM, systemLimit)
  2110. {
  2111. { "pointsize", Graphics::LIMIT_POINT_SIZE },
  2112. { "texturesize", Graphics::LIMIT_TEXTURE_SIZE },
  2113. { "texturelayers", Graphics::LIMIT_TEXTURE_LAYERS },
  2114. { "volumetexturesize", Graphics::LIMIT_VOLUME_TEXTURE_SIZE },
  2115. { "cubetexturesize", Graphics::LIMIT_CUBE_TEXTURE_SIZE },
  2116. { "texelbuffersize", Graphics::LIMIT_TEXEL_BUFFER_SIZE },
  2117. { "shaderstoragebuffersize", Graphics::LIMIT_SHADER_STORAGE_BUFFER_SIZE },
  2118. { "threadgroupsx", Graphics::LIMIT_THREADGROUPS_X },
  2119. { "threadgroupsy", Graphics::LIMIT_THREADGROUPS_Y },
  2120. { "threadgroupsz", Graphics::LIMIT_THREADGROUPS_Z },
  2121. { "rendertargets", Graphics::LIMIT_RENDER_TARGETS },
  2122. { "texturemsaa", Graphics::LIMIT_TEXTURE_MSAA },
  2123. { "anisotropy", Graphics::LIMIT_ANISOTROPY },
  2124. }
  2125. STRINGMAP_CLASS_END(Graphics, Graphics::SystemLimit, Graphics::LIMIT_MAX_ENUM, systemLimit)
  2126. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::StackType, Graphics::STACK_MAX_ENUM, stackType)
  2127. {
  2128. { "all", Graphics::STACK_ALL },
  2129. { "transform", Graphics::STACK_TRANSFORM },
  2130. }
  2131. STRINGMAP_CLASS_END(Graphics, Graphics::StackType, Graphics::STACK_MAX_ENUM, stackType)
  2132. STRINGMAP_BEGIN(Renderer, RENDERER_MAX_ENUM, renderer)
  2133. {
  2134. { "opengl", RENDERER_OPENGL },
  2135. { "vulkan", RENDERER_VULKAN },
  2136. { "metal", RENDERER_METAL },
  2137. }
  2138. STRINGMAP_END(Renderer, RENDERER_MAX_ENUM, renderer)
  2139. } // graphics
  2140. } // love