wrap_Graphics.cpp 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146
  1. /**
  2. * Copyright (c) 2006-2024 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. #include "common/config.h"
  21. #include "wrap_Graphics.h"
  22. #include "Texture.h"
  23. #include "image/ImageData.h"
  24. #include "image/Image.h"
  25. #include "font/Rasterizer.h"
  26. #include "filesystem/Filesystem.h"
  27. #include "filesystem/wrap_Filesystem.h"
  28. #include "video/VideoStream.h"
  29. #include "image/wrap_Image.h"
  30. #include "common/Reference.h"
  31. #include "math/wrap_Transform.h"
  32. #include "thread/wrap_Channel.h"
  33. #include "opengl/Graphics.h"
  34. #include <cassert>
  35. #include <cstring>
  36. #include <cstdlib>
  37. #include <sstream>
  38. #include <algorithm>
  39. // Shove the wrap_Graphics.lua code directly into a raw string literal.
  40. static const char graphics_lua[] =
  41. #include "wrap_Graphics.lua"
  42. ;
  43. namespace love
  44. {
  45. namespace graphics
  46. {
  47. #define instance() (Module::getInstance<Graphics>(Module::M_GRAPHICS))
  48. static int luax_checkgraphicscreated(lua_State *L)
  49. {
  50. if (!instance()->isCreated())
  51. return luaL_error(L, "love.graphics cannot function without a window!");
  52. return 0;
  53. }
  54. int w_reset(lua_State *)
  55. {
  56. instance()->reset();
  57. return 0;
  58. }
  59. int w_clear(lua_State *L)
  60. {
  61. OptionalColorD color(ColorD(0.0, 0.0, 0.0, 0.0));
  62. std::vector<OptionalColorD> colors;
  63. OptionalInt stencil(0);
  64. OptionalDouble depth(1.0);
  65. int argtype = lua_type(L, 1);
  66. int startidx = -1;
  67. if (argtype == LUA_TTABLE)
  68. {
  69. int maxn = lua_gettop(L);
  70. colors.reserve(maxn);
  71. for (int i = 0; i < maxn; i++)
  72. {
  73. argtype = lua_type(L, i + 1);
  74. if (argtype == LUA_TNUMBER || argtype == LUA_TBOOLEAN)
  75. {
  76. startidx = i + 1;
  77. break;
  78. }
  79. else if (argtype == LUA_TNIL || argtype == LUA_TNONE || luax_objlen(L, i + 1) == 0)
  80. {
  81. colors.push_back(OptionalColorD());
  82. continue;
  83. }
  84. for (int j = 1; j <= 4; j++)
  85. lua_rawgeti(L, i + 1, j);
  86. OptionalColorD c;
  87. c.hasValue = true;
  88. c.value.r = luaL_checknumber(L, -4);
  89. c.value.g = luaL_checknumber(L, -3);
  90. c.value.b = luaL_checknumber(L, -2);
  91. c.value.a = luaL_optnumber(L, -1, 1.0);
  92. colors.push_back(c);
  93. lua_pop(L, 4);
  94. }
  95. }
  96. else if (argtype == LUA_TBOOLEAN)
  97. {
  98. color.hasValue = luax_toboolean(L, 1);
  99. startidx = 2;
  100. }
  101. else if (argtype != LUA_TNONE && argtype != LUA_TNIL)
  102. {
  103. color.hasValue = true;
  104. color.value.r = (float) luaL_checknumber(L, 1);
  105. color.value.g = (float) luaL_checknumber(L, 2);
  106. color.value.b = (float) luaL_checknumber(L, 3);
  107. color.value.a = (float) luaL_optnumber(L, 4, 1.0);
  108. startidx = 5;
  109. }
  110. if (startidx >= 0)
  111. {
  112. argtype = lua_type(L, startidx);
  113. if (argtype == LUA_TBOOLEAN)
  114. stencil.hasValue = luax_toboolean(L, startidx);
  115. else if (argtype == LUA_TNUMBER)
  116. stencil.value = (int) luaL_checkinteger(L, startidx);
  117. argtype = lua_type(L, startidx + 1);
  118. if (argtype == LUA_TBOOLEAN)
  119. depth.hasValue = luax_toboolean(L, startidx + 1);
  120. else if (argtype == LUA_TNUMBER)
  121. depth.value = luaL_checknumber(L, startidx + 1);
  122. }
  123. if (colors.empty())
  124. luax_catchexcept(L, [&]() { instance()->clear(color, stencil, depth); });
  125. else
  126. luax_catchexcept(L, [&]() { instance()->clear(colors, stencil, depth); });
  127. return 0;
  128. }
  129. int w_discard(lua_State *L)
  130. {
  131. std::vector<bool> colorbuffers;
  132. if (lua_istable(L, 1))
  133. {
  134. for (size_t i = 1; i <= luax_objlen(L, 1); i++)
  135. {
  136. lua_rawgeti(L, 1, i);
  137. colorbuffers.push_back(luax_optboolean(L, -1, true));
  138. lua_pop(L, 1);
  139. }
  140. }
  141. else
  142. {
  143. bool discardcolor = luax_optboolean(L, 1, true);
  144. size_t numbuffers = std::max((size_t) 1, instance()->getRenderTargets().colors.size());
  145. colorbuffers = std::vector<bool>(numbuffers, discardcolor);
  146. }
  147. bool depthstencil = luax_optboolean(L, 2, true);
  148. instance()->discard(colorbuffers, depthstencil);
  149. return 0;
  150. }
  151. int w_present(lua_State *L)
  152. {
  153. luax_catchexcept(L, [&]() { instance()->present(L); });
  154. return 0;
  155. }
  156. int w_isCreated(lua_State *L)
  157. {
  158. luax_pushboolean(L, instance()->isCreated());
  159. return 1;
  160. }
  161. int w_isActive(lua_State *L)
  162. {
  163. luax_pushboolean(L, instance()->isActive());
  164. return 1;
  165. }
  166. int w_isGammaCorrect(lua_State *L)
  167. {
  168. luax_pushboolean(L, graphics::isGammaCorrect());
  169. return 1;
  170. }
  171. int w_getWidth(lua_State *L)
  172. {
  173. lua_pushinteger(L, instance()->getWidth());
  174. return 1;
  175. }
  176. int w_getHeight(lua_State *L)
  177. {
  178. lua_pushinteger(L, instance()->getHeight());
  179. return 1;
  180. }
  181. int w_getDimensions(lua_State *L)
  182. {
  183. lua_pushinteger(L, instance()->getWidth());
  184. lua_pushinteger(L, instance()->getHeight());
  185. return 2;
  186. }
  187. int w_getPixelWidth(lua_State *L)
  188. {
  189. lua_pushinteger(L, instance()->getPixelWidth());
  190. return 1;
  191. }
  192. int w_getPixelHeight(lua_State *L)
  193. {
  194. lua_pushinteger(L, instance()->getPixelHeight());
  195. return 1;
  196. }
  197. int w_getPixelDimensions(lua_State *L)
  198. {
  199. lua_pushinteger(L, instance()->getPixelWidth());
  200. lua_pushinteger(L, instance()->getPixelHeight());
  201. return 2;
  202. }
  203. int w_getDPIScale(lua_State *L)
  204. {
  205. lua_pushnumber(L, instance()->getScreenDPIScale());
  206. return 1;
  207. }
  208. int w_getQuadIndexBuffer(lua_State *L)
  209. {
  210. luax_pushtype(L, instance()->getQuadIndexBuffer());
  211. return 1;
  212. }
  213. static Graphics::RenderTarget checkRenderTarget(lua_State *L, int idx)
  214. {
  215. lua_rawgeti(L, idx, 1);
  216. Graphics::RenderTarget target(luax_checktexture(L, -1), 0);
  217. lua_pop(L, 1);
  218. TextureType type = target.texture->getTextureType();
  219. if (type == TEXTURE_2D_ARRAY || type == TEXTURE_VOLUME)
  220. target.slice = luax_checkintflag(L, idx, "layer") - 1;
  221. else if (type == TEXTURE_CUBE)
  222. target.slice = luax_checkintflag(L, idx, "face") - 1;
  223. target.mipmap = luax_intflag(L, idx, "mipmap", 1) - 1;
  224. return target;
  225. }
  226. int w_setCanvas(lua_State *L)
  227. {
  228. // called with none -> reset to default buffer
  229. if (lua_isnoneornil(L, 1))
  230. {
  231. instance()->setRenderTarget();
  232. return 0;
  233. }
  234. bool is_table = lua_istable(L, 1);
  235. Graphics::RenderTargets targets;
  236. if (is_table)
  237. {
  238. lua_rawgeti(L, 1, 1);
  239. bool table_of_tables = lua_istable(L, -1);
  240. lua_pop(L, 1);
  241. for (int i = 1; i <= (int) luax_objlen(L, 1); i++)
  242. {
  243. lua_rawgeti(L, 1, i);
  244. if (table_of_tables)
  245. targets.colors.push_back(checkRenderTarget(L, -1));
  246. else
  247. {
  248. targets.colors.emplace_back(luax_checktexture(L, -1), 0);
  249. if (targets.colors.back().texture->getTextureType() != TEXTURE_2D)
  250. return luaL_error(L, "Non-2D textures must use the table-of-tables variant of setCanvas.");
  251. }
  252. lua_pop(L, 1);
  253. }
  254. uint32 tempdepthflag = Graphics::TEMPORARY_RT_DEPTH;
  255. uint32 tempstencilflag = Graphics::TEMPORARY_RT_STENCIL;
  256. lua_getfield(L, 1, "depthstencil");
  257. int dstype = lua_type(L, -1);
  258. if (dstype == LUA_TTABLE)
  259. targets.depthStencil = checkRenderTarget(L, -1);
  260. else if (dstype == LUA_TBOOLEAN)
  261. targets.temporaryRTFlags |= luax_toboolean(L, -1) ? (tempdepthflag | tempstencilflag) : 0;
  262. else if (dstype != LUA_TNONE && dstype != LUA_TNIL)
  263. targets.depthStencil.texture = luax_checktexture(L, -1);
  264. lua_pop(L, 1);
  265. if (targets.depthStencil.texture == nullptr && (targets.temporaryRTFlags & tempdepthflag) == 0)
  266. targets.temporaryRTFlags |= luax_boolflag(L, 1, "depth", false) ? tempdepthflag : 0;
  267. if (targets.depthStencil.texture == nullptr && (targets.temporaryRTFlags & tempstencilflag) == 0)
  268. targets.temporaryRTFlags |= luax_boolflag(L, 1, "stencil", false) ? tempstencilflag : 0;
  269. }
  270. else
  271. {
  272. for (int i = 1; i <= lua_gettop(L); i++)
  273. {
  274. Graphics::RenderTarget target(luax_checktexture(L, i), 0);
  275. TextureType type = target.texture->getTextureType();
  276. if (i == 1 && type != TEXTURE_2D)
  277. {
  278. target.slice = (int) luaL_checkinteger(L, i + 1) - 1;
  279. target.mipmap = (int) luaL_optinteger(L, i + 2, 1) - 1;
  280. targets.colors.push_back(target);
  281. break;
  282. }
  283. else if (type == TEXTURE_2D && lua_isnumber(L, i + 1))
  284. {
  285. target.mipmap = (int) luaL_optinteger(L, i + 1, 1) - 1;
  286. i++;
  287. }
  288. if (i > 1 && type != TEXTURE_2D)
  289. return luaL_error(L, "This variant of setCanvas only supports 2D texture types.");
  290. targets.colors.push_back(target);
  291. }
  292. }
  293. luax_catchexcept(L, [&]() {
  294. if (targets.getFirstTarget().texture != nullptr)
  295. instance()->setRenderTargets(targets);
  296. else
  297. instance()->setRenderTarget();
  298. });
  299. return 0;
  300. }
  301. static void pushRenderTarget(lua_State *L, const Graphics::RenderTarget &rt)
  302. {
  303. lua_createtable(L, 1, 2);
  304. luax_pushtype(L, rt.texture);
  305. lua_rawseti(L, -2, 1);
  306. TextureType type = rt.texture->getTextureType();
  307. if (type == TEXTURE_2D_ARRAY || type == TEXTURE_VOLUME)
  308. {
  309. lua_pushnumber(L, rt.slice + 1);
  310. lua_setfield(L, -2, "layer");
  311. }
  312. else if (type == TEXTURE_CUBE)
  313. {
  314. lua_pushnumber(L, rt.slice + 1);
  315. lua_setfield(L, -2, "face");
  316. }
  317. lua_pushnumber(L, rt.mipmap + 1);
  318. lua_setfield(L, -2, "mipmap");
  319. }
  320. int w_getCanvas(lua_State *L)
  321. {
  322. Graphics::RenderTargets targets = instance()->getRenderTargets();
  323. int ntargets = (int) targets.colors.size();
  324. if (ntargets == 0)
  325. {
  326. lua_pushnil(L);
  327. return 1;
  328. }
  329. bool shouldUseTablesVariant = targets.depthStencil.texture != nullptr;
  330. if (!shouldUseTablesVariant)
  331. {
  332. for (const auto &rt : targets.colors)
  333. {
  334. if (rt.mipmap != 0 || rt.texture->getTextureType() != TEXTURE_2D)
  335. {
  336. shouldUseTablesVariant = true;
  337. break;
  338. }
  339. }
  340. }
  341. if (shouldUseTablesVariant)
  342. {
  343. lua_createtable(L, ntargets, 0);
  344. for (int i = 0; i < ntargets; i++)
  345. {
  346. pushRenderTarget(L, targets.colors[i]);
  347. lua_rawseti(L, -2, i + 1);
  348. }
  349. if (targets.depthStencil.texture != nullptr)
  350. {
  351. pushRenderTarget(L, targets.depthStencil);
  352. lua_setfield(L, -2, "depthstencil");
  353. }
  354. return 1;
  355. }
  356. else
  357. {
  358. for (const auto &rt : targets.colors)
  359. luax_pushtype(L, rt.texture);
  360. return ntargets;
  361. }
  362. }
  363. static void screenshotFunctionCallback(const Graphics::ScreenshotInfo *info, love::image::ImageData *i, void *gd)
  364. {
  365. if (info == nullptr)
  366. return;
  367. lua_State *L = (lua_State *) gd;
  368. Reference *ref = (Reference *) info->data;
  369. if (i != nullptr && L != nullptr)
  370. {
  371. if (ref == nullptr)
  372. luaL_error(L, "Internal error in screenshot callback.");
  373. ref->push(L);
  374. delete ref;
  375. luax_pushtype(L, i);
  376. lua_call(L, 1, 0);
  377. }
  378. else
  379. delete ref;
  380. }
  381. struct ScreenshotFileInfo
  382. {
  383. std::string filename;
  384. image::FormatHandler::EncodedFormat format;
  385. };
  386. static void screenshotFileCallback(const Graphics::ScreenshotInfo *info, love::image::ImageData *i, void * /*gd*/)
  387. {
  388. if (info == nullptr)
  389. return;
  390. ScreenshotFileInfo *fileinfo = (ScreenshotFileInfo *) info->data;
  391. if (i != nullptr && fileinfo != nullptr)
  392. {
  393. try
  394. {
  395. i->encode(fileinfo->format, fileinfo->filename.c_str(), true);
  396. }
  397. catch (love::Exception &e)
  398. {
  399. printf("Screenshot encoding or saving failed: %s", e.what());
  400. // Do nothing...
  401. }
  402. }
  403. delete fileinfo;
  404. }
  405. static void screenshotChannelCallback(const Graphics::ScreenshotInfo *info, love::image::ImageData *i, void * /*gd*/)
  406. {
  407. if (info == nullptr)
  408. return;
  409. auto *channel = (love::thread::Channel *) info->data;
  410. if (channel != nullptr)
  411. {
  412. if (i != nullptr)
  413. channel->push(Variant(&love::image::ImageData::type, i));
  414. channel->release();
  415. }
  416. }
  417. int w_captureScreenshot(lua_State *L)
  418. {
  419. Graphics::ScreenshotInfo info;
  420. if (lua_isfunction(L, 1))
  421. {
  422. lua_pushvalue(L, 1);
  423. info.data = luax_refif(L, LUA_TFUNCTION);
  424. lua_pop(L, 1);
  425. info.callback = screenshotFunctionCallback;
  426. }
  427. else if (lua_isstring(L, 1))
  428. {
  429. std::string filename = luax_checkstring(L, 1);
  430. std::string ext;
  431. size_t dotpos = filename.rfind('.');
  432. if (dotpos != std::string::npos)
  433. ext = filename.substr(dotpos + 1);
  434. std::transform(ext.begin(), ext.end(), ext.begin(), tolower);
  435. image::FormatHandler::EncodedFormat format;
  436. if (!image::ImageData::getConstant(ext.c_str(), format))
  437. return luax_enumerror(L, "encoded image format", image::ImageData::getConstants(format), ext.c_str());
  438. ScreenshotFileInfo *fileinfo = new ScreenshotFileInfo;
  439. fileinfo->filename = filename;
  440. fileinfo->format = format;
  441. info.data = fileinfo;
  442. info.callback = screenshotFileCallback;
  443. }
  444. else if (luax_istype(L, 1, love::thread::Channel::type))
  445. {
  446. auto *channel = love::thread::luax_checkchannel(L, 1);
  447. channel->retain();
  448. info.data = channel;
  449. info.callback = screenshotChannelCallback;
  450. }
  451. else
  452. return luax_typerror(L, 1, "function, string, or Channel");
  453. luax_catchexcept(L,
  454. [&]() { instance()->captureScreenshot(info); },
  455. [&](bool except) { if (except) info.callback(&info, nullptr, nullptr); }
  456. );
  457. return 0;
  458. }
  459. int w_setScissor(lua_State *L)
  460. {
  461. int nargs = lua_gettop(L);
  462. if (nargs == 0 || (nargs == 4 && lua_isnil(L, 1) && lua_isnil(L, 2)
  463. && lua_isnil(L, 3) && lua_isnil(L, 4)))
  464. {
  465. instance()->setScissor();
  466. return 0;
  467. }
  468. Rect rect;
  469. rect.x = (int) luaL_checkinteger(L, 1);
  470. rect.y = (int) luaL_checkinteger(L, 2);
  471. rect.w = (int) luaL_checkinteger(L, 3);
  472. rect.h = (int) luaL_checkinteger(L, 4);
  473. if (rect.w < 0 || rect.h < 0)
  474. return luaL_error(L, "Can't set scissor with negative width and/or height.");
  475. instance()->setScissor(rect);
  476. return 0;
  477. }
  478. int w_intersectScissor(lua_State *L)
  479. {
  480. Rect rect;
  481. rect.x = (int) luaL_checkinteger(L, 1);
  482. rect.y = (int) luaL_checkinteger(L, 2);
  483. rect.w = (int) luaL_checkinteger(L, 3);
  484. rect.h = (int) luaL_checkinteger(L, 4);
  485. if (rect.w < 0 || rect.h < 0)
  486. return luaL_error(L, "Can't set scissor with negative width and/or height.");
  487. instance()->intersectScissor(rect);
  488. return 0;
  489. }
  490. int w_getScissor(lua_State *L)
  491. {
  492. Rect rect;
  493. if (!instance()->getScissor(rect))
  494. return 0;
  495. lua_pushinteger(L, rect.x);
  496. lua_pushinteger(L, rect.y);
  497. lua_pushinteger(L, rect.w);
  498. lua_pushinteger(L, rect.h);
  499. return 4;
  500. }
  501. int w_setStencilMode(lua_State *L)
  502. {
  503. if (lua_gettop(L) <= 1 && lua_isnoneornil(L, 1))
  504. {
  505. luax_catchexcept(L, [&]() { instance()->setStencilMode(); });
  506. return 0;
  507. }
  508. StencilMode mode = STENCIL_MODE_OFF;
  509. const char *modestr = luaL_checkstring(L, 1);
  510. if (!getConstant(modestr, mode))
  511. return luax_enumerror(L, "stencil mode", getConstants(mode), modestr);
  512. int value = (int) luaL_optinteger(L, 3, 1);
  513. luax_catchexcept(L, [&]() { instance()->setStencilMode(mode, value); });
  514. return 0;
  515. }
  516. int w_getStencilMode(lua_State *L)
  517. {
  518. int value = 0;
  519. StencilMode mode = instance()->getStencilMode(value);
  520. const char *modestr;
  521. if (!getConstant(mode, modestr))
  522. return luaL_error(L, "Unknown stencil mode.");
  523. lua_pushstring(L, modestr);
  524. lua_pushinteger(L, value);
  525. return 2;
  526. }
  527. int w_setStencilState(lua_State *L)
  528. {
  529. if (lua_gettop(L) <= 1 && lua_isnoneornil(L, 1))
  530. {
  531. luax_catchexcept(L, [&](){ instance()->setStencilState(); });
  532. return 0;
  533. }
  534. StencilState s;
  535. const char *actionstr = luaL_checkstring(L, 1);
  536. if (!getConstant(actionstr, s.action))
  537. return luax_enumerror(L, "stencil draw action", getConstants(s.action), actionstr);
  538. const char *comparestr = luaL_checkstring(L, 2);
  539. if (!getConstant(comparestr, s.compare))
  540. return luax_enumerror(L, "compare mode", getConstants(s.compare), comparestr);
  541. s.value = (int) luaL_optinteger(L, 3, 0);
  542. s.readMask = (uint32) luaL_optnumber(L, 4, LOVE_UINT32_MAX);
  543. s.writeMask = (uint32) luaL_optnumber(L, 5, LOVE_UINT32_MAX);
  544. luax_catchexcept(L, [&](){ instance()->setStencilState(s); });
  545. return 0;
  546. }
  547. int w_getStencilState(lua_State *L)
  548. {
  549. const StencilState &s = instance()->getStencilState();
  550. const char *actionstr;
  551. if (!getConstant(s.action, actionstr))
  552. return luaL_error(L, "Unknown stencil draw action.");
  553. const char *comparestr;
  554. if (!getConstant(s.compare, comparestr))
  555. return luaL_error(L, "Unknown compare mode.");
  556. lua_pushstring(L, actionstr);
  557. lua_pushstring(L, comparestr);
  558. lua_pushinteger(L, s.value);
  559. lua_pushnumber(L, s.readMask);
  560. lua_pushnumber(L, s.writeMask);
  561. return 5;
  562. }
  563. static void parseDPIScale(Data *d, float *dpiscale)
  564. {
  565. auto fd = dynamic_cast<love::filesystem::FileData *>(d);
  566. if (fd == nullptr)
  567. return;
  568. // Parse a density scale of 2.0 from "[email protected]".
  569. const std::string &fname = fd->getName();
  570. size_t namelen = fname.length();
  571. size_t atpos = fname.rfind('@');
  572. if (atpos != std::string::npos && atpos + 2 < namelen
  573. && (fname[namelen - 1] == 'x' || fname[namelen - 1] == 'X'))
  574. {
  575. char *end = nullptr;
  576. long density = strtol(fname.c_str() + atpos + 1, &end, 10);
  577. if (end != nullptr && density > 0 && dpiscale != nullptr)
  578. *dpiscale = (float) density;
  579. }
  580. }
  581. static std::pair<StrongRef<image::ImageData>, StrongRef<image::CompressedImageData>>
  582. getImageData(lua_State *L, int idx, bool allowcompressed, float *dpiscale)
  583. {
  584. StrongRef<image::ImageData> idata;
  585. StrongRef<image::CompressedImageData> cdata;
  586. if (luax_istype(L, idx, image::ImageData::type))
  587. idata.set(image::luax_checkimagedata(L, idx));
  588. else if (luax_istype(L, idx, image::CompressedImageData::type))
  589. cdata.set(image::luax_checkcompressedimagedata(L, idx));
  590. else if (filesystem::luax_cangetdata(L, idx))
  591. {
  592. // Convert to ImageData / CompressedImageData.
  593. auto imagemodule = Module::getInstance<image::Image>(Module::M_IMAGE);
  594. if (imagemodule == nullptr)
  595. luaL_error(L, "Cannot load images without the love.image module.");
  596. StrongRef<Data> fdata(filesystem::luax_getdata(L, idx), Acquire::NORETAIN);
  597. if (dpiscale != nullptr)
  598. parseDPIScale(fdata, dpiscale);
  599. if (allowcompressed && imagemodule->isCompressed(fdata))
  600. luax_catchexcept(L, [&]() { cdata.set(imagemodule->newCompressedData(fdata), Acquire::NORETAIN); });
  601. else
  602. luax_catchexcept(L, [&]() { idata.set(imagemodule->newImageData(fdata), Acquire::NORETAIN); });
  603. }
  604. else
  605. idata.set(image::luax_checkimagedata(L, idx));
  606. return std::make_pair(idata, cdata);
  607. }
  608. static int w__pushNewTexture(lua_State *L, Texture::Slices *slices, const Texture::Settings &settings)
  609. {
  610. StrongRef<Texture> i;
  611. luax_catchexcept(L,
  612. [&]() { i.set(instance()->newTexture(settings, slices), Acquire::NORETAIN); },
  613. [&](bool) { if (slices) slices->clear(); }
  614. );
  615. luax_pushtype(L, i);
  616. return 1;
  617. }
  618. static void luax_checktexturesettings(lua_State *L, int idx, bool opt, bool checkType, bool checkDimensions, OptionalBool forceRenderTarget, Texture::Settings &s, bool &setdpiscale)
  619. {
  620. setdpiscale = false;
  621. if (forceRenderTarget.hasValue)
  622. s.renderTarget = forceRenderTarget.value;
  623. if (opt && lua_isnoneornil(L, idx))
  624. return;
  625. luax_checktablefields<Texture::SettingType>(L, idx, "texture setting name", Texture::getConstant);
  626. if (!forceRenderTarget.hasValue)
  627. s.renderTarget = luax_boolflag(L, idx, Texture::getConstant(Texture::SETTING_RENDER_TARGET), s.renderTarget);
  628. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_DEBUGNAME));
  629. if (!lua_isnoneornil(L, -1))
  630. {
  631. s.debugName = luaL_checkstring(L, -1);
  632. }
  633. lua_pop(L, 1);
  634. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_FORMAT));
  635. if (!lua_isnoneornil(L, -1))
  636. {
  637. const char *str = luaL_checkstring(L, -1);
  638. if (!getConstant(str, s.format))
  639. luax_enumerror(L, "pixel format", str);
  640. }
  641. lua_pop(L, 1);
  642. if (checkType)
  643. {
  644. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_TYPE));
  645. if (!lua_isnoneornil(L, -1))
  646. {
  647. const char *str = luaL_checkstring(L, -1);
  648. if (!Texture::getConstant(str, s.type))
  649. luax_enumerror(L, "texture type", Texture::getConstants(s.type), str);
  650. }
  651. lua_pop(L, 1);
  652. }
  653. if (checkDimensions)
  654. {
  655. s.width = luax_checkintflag(L, idx, Texture::getConstant(Texture::SETTING_WIDTH));
  656. s.height = luax_checkintflag(L, idx, Texture::getConstant(Texture::SETTING_HEIGHT));
  657. if (s.type == TEXTURE_2D_ARRAY || s.type == TEXTURE_VOLUME)
  658. s.layers = luax_checkintflag(L, idx, Texture::getConstant(Texture::SETTING_LAYERS));
  659. }
  660. else
  661. {
  662. s.width = luax_intflag(L, idx, Texture::getConstant(Texture::SETTING_WIDTH), s.width);
  663. s.height = luax_intflag(L, idx, Texture::getConstant(Texture::SETTING_HEIGHT), s.height);
  664. if (s.type == TEXTURE_2D_ARRAY || s.type == TEXTURE_VOLUME)
  665. s.layers = luax_intflag(L, idx, Texture::getConstant(Texture::SETTING_LAYERS), s.layers);
  666. }
  667. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_MIPMAPS));
  668. if (!lua_isnoneornil(L, -1))
  669. {
  670. if (lua_type(L, -1) == LUA_TBOOLEAN)
  671. s.mipmaps = luax_toboolean(L, -1) ? Texture::MIPMAPS_MANUAL : Texture::MIPMAPS_NONE;
  672. else
  673. {
  674. const char *str = luaL_checkstring(L, -1);
  675. if (!Texture::getConstant(str, s.mipmaps))
  676. luax_enumerror(L, "Texture mipmap mode", Texture::getConstants(s.mipmaps), str);
  677. }
  678. }
  679. lua_pop(L, 1);
  680. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_MIPMAP_COUNT));
  681. if (!lua_isnoneornil(L, -1))
  682. s.mipmapCount = (int) luaL_checkinteger(L, -1);
  683. lua_pop(L, 1);
  684. s.linear = luax_boolflag(L, idx, Texture::getConstant(Texture::SETTING_LINEAR), s.linear);
  685. s.msaa = luax_intflag(L, idx, Texture::getConstant(Texture::SETTING_MSAA), s.msaa);
  686. s.computeWrite = luax_boolflag(L, idx, Texture::getConstant(Texture::SETTING_COMPUTE_WRITE), s.computeWrite);
  687. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_VIEW_FORMATS));
  688. if (!lua_isnoneornil(L, -1))
  689. {
  690. if (lua_type(L, -1) != LUA_TTABLE)
  691. luaL_argerror(L, idx, "expected field 'viewformats' to be a table type");
  692. for (int i = 1; i <= luax_objlen(L, -1); i++)
  693. {
  694. lua_rawgeti(L, -1, i);
  695. const char *str = luaL_checkstring(L, -1);
  696. PixelFormat viewformat = PIXELFORMAT_UNKNOWN;
  697. if (!getConstant(str, viewformat))
  698. luax_enumerror(L, "pixel format", str);
  699. s.viewFormats.push_back(viewformat);
  700. lua_pop(L, 1);
  701. }
  702. }
  703. lua_pop(L, 1);
  704. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_READABLE));
  705. if (!lua_isnoneornil(L, -1))
  706. s.readable.set(luax_checkboolean(L, -1));
  707. lua_pop(L, 1);
  708. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_DPI_SCALE));
  709. if (lua_isnumber(L, -1))
  710. {
  711. s.dpiScale = (float) lua_tonumber(L, -1);
  712. setdpiscale = true;
  713. }
  714. lua_pop(L, 1);
  715. }
  716. int w_newCanvas(lua_State *L)
  717. {
  718. luax_checkgraphicscreated(L);
  719. Texture::Settings s;
  720. OptionalBool forceRenderTarget(true);
  721. bool setDPIScale = false;
  722. if (lua_istable(L, 1))
  723. {
  724. luax_checktexturesettings(L, 1, false, true, true, forceRenderTarget, s, setDPIScale);
  725. }
  726. else
  727. {
  728. // check if width and height are given. else default to screen dimensions.
  729. s.width = (int) luaL_optinteger(L, 1, instance()->getWidth());
  730. s.height = (int) luaL_optinteger(L, 2, instance()->getHeight());
  731. int startidx = 3;
  732. if (lua_isnumber(L, 3))
  733. {
  734. s.layers = (int) luaL_checkinteger(L, 3);
  735. s.type = TEXTURE_2D_ARRAY;
  736. startidx = 4;
  737. }
  738. luax_checktexturesettings(L, startidx, true, true, false, forceRenderTarget, s, setDPIScale);
  739. }
  740. // Default to the screen's current pixel density scale.
  741. if (!setDPIScale)
  742. s.dpiScale = instance()->getScreenDPIScale();
  743. Texture *texture = nullptr;
  744. luax_catchexcept(L, [&](){ texture = instance()->newTexture(s); });
  745. luax_pushtype(L, texture);
  746. texture->release();
  747. return 1;
  748. }
  749. int w_newTexture(lua_State *L)
  750. {
  751. luax_checkgraphicscreated(L);
  752. Texture::Slices slices(TEXTURE_2D);
  753. Texture::Slices *slicesref = &slices;
  754. Texture::Settings settings;
  755. settings.type = TEXTURE_2D;
  756. bool dpiscaleset = false;
  757. if (lua_type(L, 1) == LUA_TNUMBER)
  758. {
  759. slicesref = nullptr;
  760. settings.width = (int) luaL_checkinteger(L, 1);
  761. settings.height = (int) luaL_checkinteger(L, 2);
  762. int startidx = 3;
  763. if (lua_type(L, 3) == LUA_TNUMBER)
  764. {
  765. settings.layers = (int) luaL_checkinteger(L, 3);
  766. settings.type = TEXTURE_2D_ARRAY;
  767. startidx = 4;
  768. }
  769. luax_checktexturesettings(L, startidx, true, true, false, OptionalBool(), settings, dpiscaleset);
  770. }
  771. else
  772. {
  773. luax_checktexturesettings(L, 2, true, false, false, OptionalBool(), settings, dpiscaleset);
  774. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  775. if (lua_istable(L, 1))
  776. {
  777. int n = std::max(1, (int) luax_objlen(L, 1));
  778. for (int i = 0; i < n; i++)
  779. {
  780. lua_rawgeti(L, 1, i + 1);
  781. auto data = getImageData(L, -1, true, i == 0 ? autodpiscale : nullptr);
  782. if (data.first.get())
  783. slices.set(0, i, data.first);
  784. else
  785. slices.set(0, i, data.second->getSlice(0, 0));
  786. }
  787. lua_pop(L, n);
  788. }
  789. else
  790. {
  791. auto data = getImageData(L, 1, true, autodpiscale);
  792. if (data.first.get())
  793. slices.set(0, 0, data.first);
  794. else
  795. slices.add(data.second, 0, 0, false, settings.mipmaps != Texture::MIPMAPS_NONE);
  796. }
  797. }
  798. return w__pushNewTexture(L, slicesref, settings);
  799. }
  800. int w_newCubeTexture(lua_State *L)
  801. {
  802. luax_checkgraphicscreated(L);
  803. Texture::Slices slices(TEXTURE_CUBE);
  804. Texture::Slices *slicesref = &slices;
  805. Texture::Settings settings;
  806. settings.type = TEXTURE_CUBE;
  807. bool dpiscaleset = false;
  808. if (lua_type(L, 1) == LUA_TNUMBER)
  809. {
  810. slicesref = nullptr;
  811. settings.width = settings.height = (int) luaL_checkinteger(L, 1);
  812. luax_checktexturesettings(L, 2, true, false, false, OptionalBool(), settings, dpiscaleset);
  813. }
  814. else
  815. {
  816. luax_checktexturesettings(L, 2, true, false, false, OptionalBool(), settings, dpiscaleset);
  817. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  818. auto imagemodule = Module::getInstance<love::image::Image>(Module::M_IMAGE);
  819. if (!lua_istable(L, 1))
  820. {
  821. auto data = getImageData(L, 1, true, autodpiscale);
  822. std::vector<StrongRef<love::image::ImageData>> faces;
  823. if (data.first.get())
  824. {
  825. luax_catchexcept(L, [&](){ faces = imagemodule->newCubeFaces(data.first); });
  826. for (int i = 0; i < (int) faces.size(); i++)
  827. slices.set(i, 0, faces[i]);
  828. }
  829. else
  830. slices.add(data.second, 0, 0, true, settings.mipmaps != Texture::MIPMAPS_NONE);
  831. }
  832. else
  833. {
  834. int tlen = (int) luax_objlen(L, 1);
  835. if (luax_isarrayoftables(L, 1))
  836. {
  837. if (tlen != 6)
  838. return luaL_error(L, "Cubemap images must have 6 faces.");
  839. for (int face = 0; face < tlen; face++)
  840. {
  841. lua_rawgeti(L, 1, face + 1);
  842. luaL_checktype(L, -1, LUA_TTABLE);
  843. int miplen = std::max(1, (int) luax_objlen(L, -1));
  844. for (int mip = 0; mip < miplen; mip++)
  845. {
  846. lua_rawgeti(L, -1, mip + 1);
  847. auto data = getImageData(L, -1, true, face == 0 && mip == 0 ? autodpiscale : nullptr);
  848. if (data.first.get())
  849. slices.set(face, mip, data.first);
  850. else
  851. slices.set(face, mip, data.second->getSlice(0, 0));
  852. lua_pop(L, 1);
  853. }
  854. }
  855. }
  856. else
  857. {
  858. bool usemipmaps = false;
  859. for (int i = 0; i < tlen; i++)
  860. {
  861. lua_rawgeti(L, 1, i + 1);
  862. auto data = getImageData(L, -1, true, i == 0 ? autodpiscale : nullptr);
  863. if (data.first.get())
  864. {
  865. if (usemipmaps || data.first->getWidth() != data.first->getHeight())
  866. {
  867. usemipmaps = true;
  868. std::vector<StrongRef<love::image::ImageData>> faces;
  869. luax_catchexcept(L, [&](){ faces = imagemodule->newCubeFaces(data.first); });
  870. for (int face = 0; face < (int) faces.size(); face++)
  871. slices.set(face, i, faces[i]);
  872. }
  873. else
  874. slices.set(i, 0, data.first);
  875. }
  876. else
  877. slices.add(data.second, i, 0, false, settings.mipmaps != Texture::MIPMAPS_NONE);
  878. }
  879. }
  880. lua_pop(L, tlen);
  881. }
  882. }
  883. return w__pushNewTexture(L, slicesref, settings);
  884. }
  885. int w_newArrayTexture(lua_State *L)
  886. {
  887. luax_checkgraphicscreated(L);
  888. Texture::Slices slices(TEXTURE_2D_ARRAY);
  889. Texture::Slices *slicesref = &slices;
  890. Texture::Settings settings;
  891. settings.type = TEXTURE_2D_ARRAY;
  892. bool dpiscaleset = false;
  893. if (lua_type(L, 1) == LUA_TNUMBER)
  894. {
  895. slicesref = nullptr;
  896. settings.width = (int) luaL_checkinteger(L, 1);
  897. settings.height = (int) luaL_checkinteger(L, 2);
  898. settings.layers = (int) luaL_checkinteger(L, 3);
  899. luax_checktexturesettings(L, 4, true, false, false, OptionalBool(), settings, dpiscaleset);
  900. }
  901. else
  902. {
  903. luax_checktexturesettings(L, 2, true, false, false, OptionalBool(), settings, dpiscaleset);
  904. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  905. if (lua_istable(L, 1))
  906. {
  907. int tlen = std::max(1, (int) luax_objlen(L, 1));
  908. if (luax_isarrayoftables(L, 1))
  909. {
  910. for (int slice = 0; slice < tlen; slice++)
  911. {
  912. lua_rawgeti(L, 1, slice + 1);
  913. luaL_checktype(L, -1, LUA_TTABLE);
  914. int miplen = std::max(1, (int) luax_objlen(L, -1));
  915. for (int mip = 0; mip < miplen; mip++)
  916. {
  917. lua_rawgeti(L, -1, mip + 1);
  918. auto data = getImageData(L, -1, true, slice == 0 && mip == 0 ? autodpiscale : nullptr);
  919. if (data.first.get())
  920. slices.set(slice, mip, data.first);
  921. else
  922. slices.set(slice, mip, data.second->getSlice(0, 0));
  923. lua_pop(L, 1);
  924. }
  925. }
  926. }
  927. else
  928. {
  929. for (int slice = 0; slice < tlen; slice++)
  930. {
  931. lua_rawgeti(L, 1, slice + 1);
  932. auto data = getImageData(L, -1, true, slice == 0 ? autodpiscale : nullptr);
  933. if (data.first.get())
  934. slices.set(slice, 0, data.first);
  935. else
  936. slices.add(data.second, slice, 0, false, settings.mipmaps != Texture::MIPMAPS_NONE);
  937. }
  938. }
  939. lua_pop(L, tlen);
  940. }
  941. else
  942. {
  943. auto data = getImageData(L, 1, true, autodpiscale);
  944. if (data.first.get())
  945. slices.set(0, 0, data.first);
  946. else
  947. slices.add(data.second, 0, 0, true, settings.mipmaps != Texture::MIPMAPS_NONE);
  948. }
  949. }
  950. return w__pushNewTexture(L, slicesref, settings);
  951. }
  952. int w_newVolumeTexture(lua_State *L)
  953. {
  954. luax_checkgraphicscreated(L);
  955. auto imagemodule = Module::getInstance<love::image::Image>(Module::M_IMAGE);
  956. Texture::Slices slices(TEXTURE_VOLUME);
  957. Texture::Slices *slicesref = &slices;
  958. Texture::Settings settings;
  959. settings.type = TEXTURE_VOLUME;
  960. bool dpiscaleset = false;
  961. if (lua_type(L, 1) == LUA_TNUMBER)
  962. {
  963. slicesref = nullptr;
  964. settings.width = (int) luaL_checkinteger(L, 1);
  965. settings.height = (int) luaL_checkinteger(L, 2);
  966. settings.layers = (int) luaL_checkinteger(L, 3);
  967. luax_checktexturesettings(L, 4, true, false, false, OptionalBool(), settings, dpiscaleset);
  968. }
  969. else
  970. {
  971. luax_checktexturesettings(L, 2, true, false, false, OptionalBool(), settings, dpiscaleset);
  972. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  973. if (lua_istable(L, 1))
  974. {
  975. int tlen = std::max(1, (int) luax_objlen(L, 1));
  976. if (luax_isarrayoftables(L, 1))
  977. {
  978. for (int mip = 0; mip < tlen; mip++)
  979. {
  980. lua_rawgeti(L, 1, mip + 1);
  981. luaL_checktype(L, -1, LUA_TTABLE);
  982. int slicelen = std::max(1, (int) luax_objlen(L, -1));
  983. for (int slice = 0; slice < slicelen; slice++)
  984. {
  985. lua_rawgeti(L, -1, slice + 1);
  986. auto data = getImageData(L, -1, true, slice == 0 && mip == 0 ? autodpiscale : nullptr);
  987. if (data.first.get())
  988. slices.set(slice, mip, data.first);
  989. else
  990. slices.set(slice, mip, data.second->getSlice(0, 0));
  991. lua_pop(L, 1);
  992. }
  993. }
  994. }
  995. else
  996. {
  997. for (int layer = 0; layer < tlen; layer++)
  998. {
  999. lua_rawgeti(L, 1, layer + 1);
  1000. auto data = getImageData(L, -1, true, layer == 0 ? autodpiscale : nullptr);
  1001. if (data.first.get())
  1002. slices.set(layer, 0, data.first);
  1003. else
  1004. slices.add(data.second, layer, 0, false, settings.mipmaps != Texture::MIPMAPS_NONE);
  1005. }
  1006. }
  1007. lua_pop(L, tlen);
  1008. }
  1009. else
  1010. {
  1011. auto data = getImageData(L, 1, true, autodpiscale);
  1012. if (data.first.get())
  1013. {
  1014. std::vector<StrongRef<love::image::ImageData>> layers;
  1015. luax_catchexcept(L, [&](){ layers = imagemodule->newVolumeLayers(data.first); });
  1016. for (int i = 0; i < (int) layers.size(); i++)
  1017. slices.set(i, 0, layers[i]);
  1018. }
  1019. else
  1020. slices.add(data.second, 0, 0, true, settings.mipmaps != Texture::MIPMAPS_NONE);
  1021. }
  1022. }
  1023. return w__pushNewTexture(L, slicesref, settings);
  1024. }
  1025. int w_newImage(lua_State *L)
  1026. {
  1027. //luax_markdeprecated(L, 1, "love.graphics.newImage", API_FUNCTION, DEPRECATED_RENAMED, "love.graphics.newTexture");
  1028. return w_newTexture(L);
  1029. }
  1030. int w_newCubeImage(lua_State *L)
  1031. {
  1032. //luax_markdeprecated(L, 1, "love.graphics.newCubeImage", API_FUNCTION, DEPRECATED_RENAMED, "love.graphics.newCubeTexture");
  1033. return w_newCubeTexture(L);
  1034. }
  1035. int w_newArrayImage(lua_State *L)
  1036. {
  1037. //luax_markdeprecated(L, 1, "love.graphics.newArrayImage", API_FUNCTION, DEPRECATED_RENAMED, "love.graphics.newArrayTexture");
  1038. return w_newArrayTexture(L);
  1039. }
  1040. int w_newVolumeImage(lua_State *L)
  1041. {
  1042. //luax_markdeprecated(L, 1, "love.graphics.newVolumeImage", API_FUNCTION, DEPRECATED_RENAMED, "love.graphics.newVolumeTexture");
  1043. return w_newVolumeTexture(L);
  1044. }
  1045. int w_newTextureView(lua_State *L)
  1046. {
  1047. Texture *base = luax_checktexture(L, 1);
  1048. luaL_checktype(L, 2, LUA_TTABLE);
  1049. Texture::ViewSettings settings;
  1050. lua_getfield(L, 2, "format");
  1051. if (!lua_isnoneornil(L, -1))
  1052. {
  1053. const char *str = luaL_checkstring(L, -1);
  1054. if (!getConstant(str, settings.format.value))
  1055. luax_enumerror(L, "pixel format", str);
  1056. settings.format.hasValue = true;
  1057. }
  1058. lua_pop(L, 1);
  1059. lua_getfield(L, 2, "type");
  1060. if (!lua_isnoneornil(L, -1))
  1061. {
  1062. const char *str = luaL_checkstring(L, -1);
  1063. if (!Texture::getConstant(str, settings.type.value))
  1064. luax_enumerror(L, "texture type", Texture::getConstants(settings.type.value), str);
  1065. settings.type.hasValue = true;
  1066. }
  1067. lua_pop(L, 1);
  1068. lua_getfield(L, 2, "mipmapstart");
  1069. if (!lua_isnoneornil(L, -1))
  1070. settings.mipmapStart.set(luaL_checkint(L, -1) - 1);
  1071. lua_pop(L, 1);
  1072. lua_getfield(L, 2, "mipmapcount");
  1073. if (!lua_isnoneornil(L, -1))
  1074. settings.mipmapCount.set(luaL_checkint(L, -1));
  1075. lua_pop(L, 1);
  1076. lua_getfield(L, 2, "layerstart");
  1077. if (!lua_isnoneornil(L, -1))
  1078. settings.layerStart.set(luaL_checkint(L, -1) - 1);
  1079. lua_pop(L, 1);
  1080. lua_getfield(L, 2, "layers");
  1081. if (!lua_isnoneornil(L, -1))
  1082. settings.layerCount.set(luaL_checkint(L, -1));
  1083. lua_pop(L, 1);
  1084. lua_getfield(L, 2, "debugname");
  1085. if (!lua_isnoneornil(L, -1))
  1086. settings.debugName = luaL_checkstring(L, -1);
  1087. lua_pop(L, 1);
  1088. Texture *t = nullptr;
  1089. luax_catchexcept(L, [&]() { t = instance()->newTextureView(base, settings); });
  1090. luax_pushtype(L, t);
  1091. t->release();
  1092. return 1;
  1093. }
  1094. int w_newQuad(lua_State *L)
  1095. {
  1096. luax_checkgraphicscreated(L);
  1097. Quad::Viewport v;
  1098. v.x = luaL_checknumber(L, 1);
  1099. v.y = luaL_checknumber(L, 2);
  1100. v.w = luaL_checknumber(L, 3);
  1101. v.h = luaL_checknumber(L, 4);
  1102. double sw = 0.0f;
  1103. double sh = 0.0f;
  1104. int layer = 0;
  1105. if (luax_istype(L, 5, Texture::type))
  1106. {
  1107. Texture *texture = luax_checktexture(L, 5);
  1108. sw = texture->getWidth();
  1109. sh = texture->getHeight();
  1110. }
  1111. else if (luax_istype(L, 6, Texture::type))
  1112. {
  1113. layer = (int) luaL_checkinteger(L, 5) - 1;
  1114. Texture *texture = luax_checktexture(L, 6);
  1115. sw = texture->getWidth();
  1116. sh = texture->getHeight();
  1117. }
  1118. else if (!lua_isnoneornil(L, 7))
  1119. {
  1120. layer = (int) luaL_checkinteger(L, 5) - 1;
  1121. sw = luaL_checknumber(L, 6);
  1122. sh = luaL_checknumber(L, 7);
  1123. }
  1124. else
  1125. {
  1126. sw = luaL_checknumber(L, 5);
  1127. sh = luaL_checknumber(L, 6);
  1128. }
  1129. Quad *quad = instance()->newQuad(v, sw, sh);
  1130. quad->setLayer(layer);
  1131. luax_pushtype(L, quad);
  1132. quad->release();
  1133. return 1;
  1134. }
  1135. int w_newFont(lua_State *L)
  1136. {
  1137. luax_checkgraphicscreated(L);
  1138. graphics::Font *font = nullptr;
  1139. // Convert to Rasterizer, if necessary.
  1140. if (!luax_istype(L, 1, love::font::Rasterizer::type))
  1141. {
  1142. std::vector<int> idxs;
  1143. for (int i = 0; i < lua_gettop(L); i++)
  1144. idxs.push_back(i + 1);
  1145. luax_convobj(L, idxs, "font", "newRasterizer");
  1146. }
  1147. love::font::Rasterizer *rasterizer = luax_checktype<love::font::Rasterizer>(L, 1);
  1148. luax_catchexcept(L, [&]() {
  1149. font = instance()->newFont(rasterizer); }
  1150. );
  1151. // Push the type.
  1152. luax_pushtype(L, font);
  1153. font->release();
  1154. return 1;
  1155. }
  1156. int w_newImageFont(lua_State *L)
  1157. {
  1158. luax_checkgraphicscreated(L);
  1159. // Convert to Rasterizer if necessary.
  1160. if (!luax_istype(L, 1, love::font::Rasterizer::type))
  1161. {
  1162. luaL_checktype(L, 2, LUA_TSTRING);
  1163. std::vector<int> idxs;
  1164. for (int i = 0; i < lua_gettop(L); i++)
  1165. idxs.push_back(i + 1);
  1166. luax_convobj(L, idxs, "font", "newImageRasterizer");
  1167. }
  1168. love::font::Rasterizer *rasterizer = luax_checktype<love::font::Rasterizer>(L, 1);
  1169. // Create the font.
  1170. Font *font = instance()->newFont(rasterizer);
  1171. // Push the type.
  1172. luax_pushtype(L, font);
  1173. font->release();
  1174. return 1;
  1175. }
  1176. int w_newSpriteBatch(lua_State *L)
  1177. {
  1178. luax_checkgraphicscreated(L);
  1179. Texture *texture = luax_checktexture(L, 1);
  1180. int size = (int) luaL_optinteger(L, 2, 1000);
  1181. BufferDataUsage usage = BUFFERDATAUSAGE_DYNAMIC;
  1182. if (lua_gettop(L) > 2)
  1183. {
  1184. const char *usagestr = luaL_checkstring(L, 3);
  1185. if (!getConstant(usagestr, usage))
  1186. return luax_enumerror(L, "usage hint", getConstants(usage), usagestr);
  1187. }
  1188. SpriteBatch *t = nullptr;
  1189. luax_catchexcept(L,
  1190. [&](){ t = instance()->newSpriteBatch(texture, size, usage); }
  1191. );
  1192. luax_pushtype(L, t);
  1193. t->release();
  1194. return 1;
  1195. }
  1196. int w_newParticleSystem(lua_State *L)
  1197. {
  1198. luax_checkgraphicscreated(L);
  1199. Texture *texture = luax_checktexture(L, 1);
  1200. lua_Number size = luaL_optnumber(L, 2, 1000);
  1201. ParticleSystem *t = nullptr;
  1202. if (size < 1.0 || size > ParticleSystem::MAX_PARTICLES)
  1203. return luaL_error(L, "Invalid ParticleSystem size");
  1204. luax_catchexcept(L,
  1205. [&](){ t = instance()->newParticleSystem(texture, int(size)); }
  1206. );
  1207. luax_pushtype(L, t);
  1208. t->release();
  1209. return 1;
  1210. }
  1211. static int w_getShaderSource(lua_State *L, int startidx, std::vector<std::string> &stages, Shader::CompileOptions &options)
  1212. {
  1213. using namespace love::filesystem;
  1214. luax_checkgraphicscreated(L);
  1215. auto fs = Module::getInstance<Filesystem>(Module::M_FILESYSTEM);
  1216. // read any filepath arguments
  1217. for (int i = startidx; i < startidx + 2; i++)
  1218. {
  1219. if (!lua_isstring(L, i))
  1220. {
  1221. if (luax_cangetfiledata(L, i))
  1222. {
  1223. FileData *fd = luax_getfiledata(L, i);
  1224. lua_pushlstring(L, (const char *) fd->getData(), fd->getSize());
  1225. fd->release();
  1226. lua_replace(L, i);
  1227. }
  1228. continue;
  1229. }
  1230. size_t slen = 0;
  1231. const char *str = lua_tolstring(L, i, &slen);
  1232. Filesystem::Info info = {};
  1233. if (fs != nullptr && fs->getInfo(str, info))
  1234. {
  1235. FileData *fd = nullptr;
  1236. luax_catchexcept(L, [&](){ fd = fs->read(str); });
  1237. lua_pushlstring(L, (const char *) fd->getData(), fd->getSize());
  1238. fd->release();
  1239. lua_replace(L, i);
  1240. }
  1241. else
  1242. {
  1243. // Check if the argument looks like a filepath - we want a nicer
  1244. // error for misspelled filepath arguments.
  1245. if (slen > 0 && slen < 64 && !strchr(str, '\n'))
  1246. {
  1247. const char *ext = strchr(str, '.');
  1248. if (ext != nullptr && !strchr(ext, ';') && !strchr(ext, ' '))
  1249. return luaL_error(L, "Could not open file %s. Does not exist.", str);
  1250. }
  1251. }
  1252. }
  1253. bool has_arg1 = lua_isstring(L, startidx + 0) != 0;
  1254. bool has_arg2 = lua_isstring(L, startidx + 1) != 0;
  1255. // require at least one string argument
  1256. if (!(has_arg1 || has_arg2))
  1257. luaL_checkstring(L, startidx);
  1258. if (has_arg1)
  1259. stages.push_back(luax_checkstring(L, startidx + 0));
  1260. if (has_arg2)
  1261. stages.push_back(luax_checkstring(L, startidx + 1));
  1262. int optionsidx = has_arg2 ? startidx + 2 : startidx + 1;
  1263. if (!lua_isnoneornil(L, optionsidx))
  1264. {
  1265. luaL_checktype(L, optionsidx, LUA_TTABLE);
  1266. lua_getfield(L, optionsidx, "defines");
  1267. if (!lua_isnoneornil(L, -1))
  1268. {
  1269. if (!lua_istable(L, -1))
  1270. luaL_argerror(L, optionsidx, "expected 'defines' field to be a table");
  1271. lua_pushnil(L);
  1272. while (lua_next(L, -2))
  1273. {
  1274. std::string defname;
  1275. std::string defval;
  1276. if (lua_type(L, -2) == LUA_TNUMBER && lua_type(L, -1) == LUA_TSTRING)
  1277. defname = luaL_checkstring(L, -1);
  1278. else if (lua_type(L, -2) != LUA_TSTRING)
  1279. luaL_argerror(L, optionsidx, "all fields in the 'defines' table must use string keys.");
  1280. else
  1281. {
  1282. defname = luaL_checkstring(L, -2);
  1283. if (lua_type(L, -1) == LUA_TBOOLEAN)
  1284. defval = luax_toboolean(L, -1) ? "1" : "0";
  1285. else
  1286. {
  1287. const char *val = lua_tostring(L, -1);
  1288. if (val == nullptr)
  1289. luaL_argerror(L, optionsidx, "'defines' table values must be strings, numbers, or booleans.");
  1290. defval = val;
  1291. }
  1292. }
  1293. options.defines[defname] = defval;
  1294. lua_pop(L, 1);
  1295. }
  1296. }
  1297. lua_pop(L, 1);
  1298. lua_getfield(L, optionsidx, "debugname");
  1299. if (!lua_isnoneornil(L, -1))
  1300. options.debugName = luax_checkstring(L, -1);
  1301. lua_pop(L, 1);
  1302. }
  1303. return 0;
  1304. }
  1305. int w_newShader(lua_State *L)
  1306. {
  1307. std::vector<std::string> stages;
  1308. Shader::CompileOptions options;
  1309. w_getShaderSource(L, 1, stages, options);
  1310. bool should_error = false;
  1311. try
  1312. {
  1313. Shader *shader = instance()->newShader(stages, options);
  1314. luax_pushtype(L, shader);
  1315. shader->release();
  1316. }
  1317. catch (love::Exception &e)
  1318. {
  1319. luax_getfunction(L, "graphics", "_transformGLSLErrorMessages");
  1320. lua_pushstring(L, e.what());
  1321. // Function pushes the new error string onto the stack.
  1322. lua_pcall(L, 1, 1, 0);
  1323. should_error = true;
  1324. }
  1325. if (should_error)
  1326. return lua_error(L);
  1327. return 1;
  1328. }
  1329. int w_newComputeShader(lua_State* L)
  1330. {
  1331. std::vector<std::string> stages;
  1332. Shader::CompileOptions options;
  1333. w_getShaderSource(L, 1, stages, options);
  1334. bool should_error = false;
  1335. try
  1336. {
  1337. Shader *shader = instance()->newComputeShader(stages[0], options);
  1338. luax_pushtype(L, shader);
  1339. shader->release();
  1340. }
  1341. catch (love::Exception &e)
  1342. {
  1343. luax_getfunction(L, "graphics", "_transformGLSLErrorMessages");
  1344. lua_pushstring(L, e.what());
  1345. // Function pushes the new error string onto the stack.
  1346. lua_pcall(L, 1, 1, 0);
  1347. should_error = true;
  1348. }
  1349. if (should_error)
  1350. return lua_error(L);
  1351. return 1;
  1352. }
  1353. int w_validateShader(lua_State *L)
  1354. {
  1355. bool gles = luax_checkboolean(L, 1);
  1356. std::vector<std::string> stages;
  1357. Shader::CompileOptions options;
  1358. w_getShaderSource(L, 2, stages, options);
  1359. bool success = true;
  1360. std::string err;
  1361. try
  1362. {
  1363. success = instance()->validateShader(gles, stages, options, err);
  1364. }
  1365. catch (love::Exception &e)
  1366. {
  1367. success = false;
  1368. err = e.what();
  1369. }
  1370. luax_pushboolean(L, success);
  1371. if (!success)
  1372. {
  1373. luax_pushstring(L, err);
  1374. return 2;
  1375. }
  1376. return 1;
  1377. }
  1378. static BufferDataUsage luax_optdatausage(lua_State *L, int idx, BufferDataUsage def)
  1379. {
  1380. const char *usagestr = lua_isnoneornil(L, idx) ? nullptr : luaL_checkstring(L, idx);
  1381. if (usagestr && !getConstant(usagestr, def))
  1382. luax_enumerror(L, "usage hint", getConstants(def), usagestr);
  1383. return def;
  1384. }
  1385. static void luax_optbuffersettings(lua_State *L, int idx, Buffer::Settings &settings)
  1386. {
  1387. if (lua_isnoneornil(L, idx))
  1388. return;
  1389. luaL_checktype(L, idx, LUA_TTABLE);
  1390. lua_getfield(L, idx, "usage");
  1391. settings.dataUsage = luax_optdatausage(L, -1, settings.dataUsage);
  1392. lua_pop(L, 1);
  1393. lua_getfield(L, idx, "debugname");
  1394. if (!lua_isnoneornil(L, -1))
  1395. settings.debugName = luax_checkstring(L, -1);
  1396. lua_pop(L, 1);
  1397. }
  1398. static Buffer::DataDeclaration luax_checkdatadeclaration(lua_State* L, int formattableidx, int arrayindex, int declindex, bool requirename)
  1399. {
  1400. Buffer::DataDeclaration decl("", DATAFORMAT_MAX_ENUM);
  1401. lua_getfield(L, declindex, "name");
  1402. if (requirename && lua_type(L, -1) != LUA_TSTRING)
  1403. {
  1404. std::ostringstream ss;
  1405. ss << "'name' field expected in array element #";
  1406. ss << arrayindex;
  1407. ss << " of format table";
  1408. std::string str = ss.str();
  1409. luaL_argerror(L, formattableidx, str.c_str());
  1410. }
  1411. else if (!lua_isnoneornil(L, -1))
  1412. decl.name = luax_checkstring(L, -1);
  1413. lua_pop(L, 1);
  1414. lua_getfield(L, declindex, "format");
  1415. if (lua_type(L, -1) != LUA_TSTRING)
  1416. {
  1417. std::ostringstream ss;
  1418. ss << "'format' field expected in array element #";
  1419. ss << arrayindex;
  1420. ss << " of format table";
  1421. std::string str = ss.str();
  1422. luaL_argerror(L, formattableidx, str.c_str());
  1423. }
  1424. const char* formatstr = luaL_checkstring(L, -1);
  1425. if (!getConstant(formatstr, decl.format))
  1426. luax_enumerror(L, "data format", getConstants(decl.format), formatstr);
  1427. lua_pop(L, 1);
  1428. decl.arrayLength = luax_intflag(L, declindex, "arraylength", 0);
  1429. return decl;
  1430. }
  1431. static void luax_checkbufferformat(lua_State *L, int idx, std::vector<Buffer::DataDeclaration> &format)
  1432. {
  1433. if (lua_type(L, idx) == LUA_TSTRING)
  1434. {
  1435. Buffer::DataDeclaration decl("", DATAFORMAT_MAX_ENUM);
  1436. const char *formatstr = luaL_checkstring(L, idx);
  1437. if (!getConstant(formatstr, decl.format))
  1438. luax_enumerror(L, "data format", getConstants(decl.format), formatstr);
  1439. format.push_back(decl);
  1440. return;
  1441. }
  1442. luaL_checktype(L, idx, LUA_TTABLE);
  1443. int tablelen = luax_objlen(L, idx);
  1444. for (int i = 1; i <= tablelen; i++)
  1445. {
  1446. lua_rawgeti(L, idx, i);
  1447. luaL_checktype(L, -1, LUA_TTABLE);
  1448. Buffer::DataDeclaration decl = luax_checkdatadeclaration(L, idx, i, -1, false);
  1449. format.push_back(decl);
  1450. lua_pop(L, 1);
  1451. }
  1452. }
  1453. static Buffer *luax_newbuffer(lua_State *L, int idx, Buffer::Settings settings, const std::vector<Buffer::DataDeclaration> &format)
  1454. {
  1455. size_t arraylength = 0;
  1456. size_t bytesize = 0;
  1457. Data *data = nullptr;
  1458. const void *initialdata = nullptr;
  1459. int ncomponents = 0;
  1460. for (const Buffer::DataDeclaration &decl : format)
  1461. ncomponents += getDataFormatInfo(decl.format).components;
  1462. if (luax_istype(L, idx, Data::type))
  1463. {
  1464. data = luax_checktype<Data>(L, idx);
  1465. initialdata = data->getData();
  1466. bytesize = data->getSize();
  1467. }
  1468. bool tableoftables = false;
  1469. if (lua_istable(L, idx))
  1470. {
  1471. arraylength = luax_objlen(L, idx);
  1472. lua_rawgeti(L, idx, 1);
  1473. tableoftables = lua_istable(L, -1);
  1474. lua_pop(L, 1);
  1475. if (!tableoftables)
  1476. {
  1477. if (arraylength % ncomponents != 0)
  1478. luaL_error(L, "Array length in flat array variant of newBuffer must be a multiple of the total number of components (%d)", ncomponents);
  1479. arraylength /= ncomponents;
  1480. }
  1481. }
  1482. else if (data == nullptr)
  1483. {
  1484. lua_Integer len = luaL_checkinteger(L, idx);
  1485. if (len <= 0)
  1486. luaL_argerror(L, idx, "number of elements must be greater than 0");
  1487. arraylength = (size_t) len;
  1488. settings.zeroInitialize = true;
  1489. }
  1490. Buffer *b = nullptr;
  1491. luax_catchexcept(L, [&] { b = instance()->newBuffer(settings, format, initialdata, bytesize, arraylength); });
  1492. if (lua_istable(L, idx))
  1493. {
  1494. Buffer::Mapper mapper(*b);
  1495. char *data = (char *) mapper.data;
  1496. const auto &members = b->getDataMembers();
  1497. size_t stride = b->getArrayStride();
  1498. if (tableoftables)
  1499. {
  1500. for (size_t i = 0; i < arraylength; i++)
  1501. {
  1502. // get arraydata[index]
  1503. lua_rawgeti(L, 2, i + 1);
  1504. luaL_checktype(L, -1, LUA_TTABLE);
  1505. // get arraydata[index][j]
  1506. for (int j = 1; j <= ncomponents; j++)
  1507. lua_rawgeti(L, -j, j);
  1508. int idx = -ncomponents;
  1509. for (const Buffer::DataMember &member : members)
  1510. {
  1511. luax_writebufferdata(L, idx, member.decl.format, data + member.offset);
  1512. idx += member.info.components;
  1513. }
  1514. lua_pop(L, ncomponents + 1);
  1515. data += stride;
  1516. }
  1517. }
  1518. else // Flat array
  1519. {
  1520. for (size_t i = 0; i < arraylength; i++)
  1521. {
  1522. // get arraydata[arrayindex * ncomponents + componentindex]
  1523. for (int componentindex = 1; componentindex <= ncomponents; componentindex++)
  1524. lua_rawgeti(L, 2, i * ncomponents + componentindex);
  1525. int idx = -ncomponents;
  1526. for (const Buffer::DataMember &member : members)
  1527. {
  1528. luax_writebufferdata(L, idx, member.decl.format, data + member.offset);
  1529. idx += member.info.components;
  1530. }
  1531. lua_pop(L, ncomponents);
  1532. data += stride;
  1533. }
  1534. }
  1535. }
  1536. return b;
  1537. }
  1538. int w_newBuffer(lua_State *L)
  1539. {
  1540. Buffer::Settings settings(0, BUFFERDATAUSAGE_DYNAMIC);
  1541. luaL_checktype(L, 3, LUA_TTABLE);
  1542. for (int i = 0; i < BUFFERUSAGE_MAX_ENUM; i++)
  1543. {
  1544. BufferUsage bufferusage = (BufferUsage) i;
  1545. const char *tname = nullptr;
  1546. if (!getConstant(bufferusage, tname))
  1547. continue;
  1548. if (luax_boolflag(L, 3, tname, false))
  1549. settings.usageFlags = (BufferUsageFlags)(settings.usageFlags | (1u << i));
  1550. }
  1551. luax_optbuffersettings(L, 3, settings);
  1552. std::vector<Buffer::DataDeclaration> format;
  1553. luax_checkbufferformat(L, 1, format);
  1554. Buffer *b = luax_newbuffer(L, 2, settings, format);
  1555. luax_pushtype(L, b);
  1556. b->release();
  1557. return 1;
  1558. }
  1559. static PrimitiveType luax_checkmeshdrawmode(lua_State *L, int idx)
  1560. {
  1561. const char *modestr = luaL_checkstring(L, idx);
  1562. PrimitiveType mode = PRIMITIVE_TRIANGLES;
  1563. if (!getConstant(modestr, mode))
  1564. luax_enumerror(L, "mesh draw mode", getConstants(mode), modestr);
  1565. return mode;
  1566. }
  1567. static Mesh *newStandardMesh(lua_State *L)
  1568. {
  1569. Mesh *t = nullptr;
  1570. PrimitiveType drawmode = luax_checkmeshdrawmode(L, 2);
  1571. BufferDataUsage usage = luax_optdatausage(L, 3, BUFFERDATAUSAGE_DYNAMIC);
  1572. std::vector<Buffer::DataDeclaration> format = Mesh::getDefaultVertexFormat();
  1573. // First argument is a table of standard vertices, or the number of
  1574. // standard vertices.
  1575. if (lua_istable(L, 1))
  1576. {
  1577. size_t vertexcount = luax_objlen(L, 1);
  1578. std::vector<Vertex> vertices;
  1579. vertices.reserve(vertexcount);
  1580. // Get the vertices from the table.
  1581. for (size_t i = 1; i <= vertexcount; i++)
  1582. {
  1583. lua_rawgeti(L, 1, (int) i);
  1584. if (lua_type(L, -1) != LUA_TTABLE)
  1585. {
  1586. luax_typerror(L, 1, "table of tables");
  1587. return nullptr;
  1588. }
  1589. for (int j = 1; j <= 8; j++)
  1590. lua_rawgeti(L, -j, j);
  1591. Vertex v;
  1592. v.x = (float) luaL_checknumber(L, -8);
  1593. v.y = (float) luaL_checknumber(L, -7);
  1594. v.s = (float) luaL_optnumber(L, -6, 0.0);
  1595. v.t = (float) luaL_optnumber(L, -5, 0.0);
  1596. v.color.r = (unsigned char) (luax_optnumberclamped01(L, -4, 1.0) * 255.0);
  1597. v.color.g = (unsigned char) (luax_optnumberclamped01(L, -3, 1.0) * 255.0);
  1598. v.color.b = (unsigned char) (luax_optnumberclamped01(L, -2, 1.0) * 255.0);
  1599. v.color.a = (unsigned char) (luax_optnumberclamped01(L, -1, 1.0) * 255.0);
  1600. lua_pop(L, 9);
  1601. vertices.push_back(v);
  1602. }
  1603. luax_catchexcept(L, [&](){ t = instance()->newMesh(format, vertices.data(), vertices.size() * sizeof(Vertex), drawmode, usage); });
  1604. }
  1605. else
  1606. {
  1607. int count = (int) luaL_checkinteger(L, 1);
  1608. luax_catchexcept(L, [&](){ t = instance()->newMesh(format, count, drawmode, usage); });
  1609. }
  1610. return t;
  1611. }
  1612. static Mesh *newCustomMesh(lua_State *L)
  1613. {
  1614. Mesh *t = nullptr;
  1615. // First argument is the vertex format, second is a table of vertices or
  1616. // the number of vertices.
  1617. std::vector<Buffer::DataDeclaration> vertexformat;
  1618. PrimitiveType drawmode = luax_checkmeshdrawmode(L, 3);
  1619. BufferDataUsage usage = luax_optdatausage(L, 4, BUFFERDATAUSAGE_DYNAMIC);
  1620. lua_rawgeti(L, 1, 1);
  1621. if (!lua_istable(L, -1))
  1622. {
  1623. luaL_argerror(L, 1, "table of tables expected");
  1624. return nullptr;
  1625. }
  1626. lua_pop(L, 1);
  1627. // Per-vertex attribute data formats.
  1628. for (int i = 1; i <= (int) luax_objlen(L, 1); i++)
  1629. {
  1630. lua_rawgeti(L, 1, i);
  1631. Buffer::DataDeclaration decl("", DATAFORMAT_MAX_ENUM);
  1632. lua_getfield(L, -1, "format");
  1633. bool hasformatfield = !lua_isnoneornil(L, -1);
  1634. lua_pop(L, 1);
  1635. if (hasformatfield || luax_objlen(L, -1) == 0)
  1636. decl = luax_checkdatadeclaration(L, 1, i, -1, true);
  1637. else
  1638. {
  1639. // Legacy format arguments: {name, datatype, components}
  1640. for (int j = 1; j <= 3; j++)
  1641. lua_rawgeti(L, -j, j);
  1642. decl.name = luaL_checkstring(L, -3);
  1643. const char* tname = luaL_checkstring(L, -2);
  1644. int components = (int)luaL_checkinteger(L, -1);
  1645. // Check deprecated format names.
  1646. if (strcmp(tname, "byte") == 0 || strcmp(tname, "unorm8") == 0)
  1647. {
  1648. if (components == 4)
  1649. decl.format = DATAFORMAT_UNORM8_VEC4;
  1650. else
  1651. luaL_error(L, "Invalid component count (%d) for vertex data type %s", components, tname);
  1652. }
  1653. else if (strcmp(tname, "unorm16") == 0)
  1654. {
  1655. if (components == 2)
  1656. decl.format = DATAFORMAT_UNORM16_VEC2;
  1657. else if (components == 4)
  1658. decl.format = DATAFORMAT_UNORM16_VEC4;
  1659. else
  1660. luaL_error(L, "Invalid component count (%d) for vertex data type %s", components, tname);
  1661. }
  1662. else if (strcmp(tname, "float") == 0)
  1663. {
  1664. if (components == 1)
  1665. decl.format = DATAFORMAT_FLOAT;
  1666. else if (components == 2)
  1667. decl.format = DATAFORMAT_FLOAT_VEC2;
  1668. else if (components == 3)
  1669. decl.format = DATAFORMAT_FLOAT_VEC3;
  1670. else if (components == 4)
  1671. decl.format = DATAFORMAT_FLOAT_VEC4;
  1672. else
  1673. luaL_error(L, "Invalid component count (%d) for vertex data type %s", components, tname);
  1674. }
  1675. if (decl.format == DATAFORMAT_MAX_ENUM)
  1676. luax_enumerror(L, "vertex data type", {"float", "byte", "unorm8", "unorm16"}, tname);
  1677. lua_pop(L, 3);
  1678. luax_markdeprecated(L, 1, "vertex format array values in love.graphics.newMesh", API_CUSTOM, DEPRECATED_REPLACED, "named table fields 'format' and 'name'");
  1679. }
  1680. lua_pop(L, 1);
  1681. vertexformat.push_back(decl);
  1682. }
  1683. if (lua_isnumber(L, 2))
  1684. {
  1685. int vertexcount = (int) luaL_checkinteger(L, 2);
  1686. luax_catchexcept(L, [&](){ t = instance()->newMesh(vertexformat, vertexcount, drawmode, usage); });
  1687. }
  1688. else if (luax_istype(L, 2, Data::type))
  1689. {
  1690. // Vertex data comes directly from a Data object.
  1691. Data *data = luax_checktype<Data>(L, 2);
  1692. luax_catchexcept(L, [&](){ t = instance()->newMesh(vertexformat, data->getData(), data->getSize(), drawmode, usage); });
  1693. }
  1694. else
  1695. {
  1696. // Table of vertices.
  1697. lua_rawgeti(L, 2, 1);
  1698. if (!lua_istable(L, -1))
  1699. {
  1700. luaL_argerror(L, 2, "expected table of tables");
  1701. return nullptr;
  1702. }
  1703. lua_pop(L, 1);
  1704. size_t numvertices = luax_objlen(L, 2);
  1705. luax_catchexcept(L, [&](){ t = instance()->newMesh(vertexformat, numvertices, drawmode, usage); });
  1706. char *data = (char *) t->getVertexData();
  1707. size_t stride = t->getVertexStride();
  1708. const auto &members = t->getVertexFormat();
  1709. for (size_t vertindex = 0; vertindex < numvertices; vertindex++)
  1710. {
  1711. // get vertices[vertindex]
  1712. lua_rawgeti(L, 2, vertindex + 1);
  1713. luaL_checktype(L, -1, LUA_TTABLE);
  1714. int n = 0;
  1715. for (size_t i = 0; i < vertexformat.size(); i++)
  1716. {
  1717. const auto &member = members[i];
  1718. const auto &info = getDataFormatInfo(member.decl.format);
  1719. // get vertices[vertindex][n]
  1720. for (int c = 0; c < info.components; c++)
  1721. {
  1722. n++;
  1723. lua_rawgeti(L, -(c + 1), n);
  1724. }
  1725. size_t offset = vertindex * stride + member.offset;
  1726. // Fetch the values from Lua and store them in data buffer.
  1727. luax_writebufferdata(L, -info.components, member.decl.format, data + offset);
  1728. lua_pop(L, info.components);
  1729. }
  1730. lua_pop(L, 1); // pop vertices[vertindex]
  1731. }
  1732. t->setVertexDataModified(0, stride * numvertices);
  1733. t->flush();
  1734. }
  1735. return t;
  1736. }
  1737. static bool luax_isbufferattributetable(lua_State* L, int idx)
  1738. {
  1739. if (lua_type(L, idx) != LUA_TTABLE)
  1740. return false;
  1741. lua_rawgeti(L, idx, 1);
  1742. if (lua_type(L, -1) != LUA_TTABLE)
  1743. {
  1744. lua_pop(L, 1);
  1745. return false;
  1746. }
  1747. lua_getfield(L, -1, "buffer");
  1748. bool isbuffer = luax_istype(L, -1, Buffer::type);
  1749. lua_pop(L, 2);
  1750. return isbuffer;
  1751. }
  1752. static Mesh::BufferAttribute luax_checkbufferattributetable(lua_State *L, int idx)
  1753. {
  1754. Mesh::BufferAttribute attrib = {};
  1755. attrib.step = STEP_PER_VERTEX;
  1756. attrib.enabled = true;
  1757. lua_getfield(L, idx, "buffer");
  1758. attrib.buffer = luax_checkbuffer(L, -1);
  1759. lua_pop(L, 1);
  1760. lua_getfield(L, idx, "name");
  1761. attrib.name = luax_checkstring(L, -1);
  1762. lua_pop(L, 1);
  1763. lua_getfield(L, idx, "step");
  1764. if (!lua_isnoneornil(L, -1))
  1765. {
  1766. const char *stepstr = luaL_checkstring(L, -1);
  1767. if (!getConstant(stepstr, attrib.step))
  1768. luax_enumerror(L, "vertex attribute step", getConstants(attrib.step), stepstr);
  1769. }
  1770. lua_pop(L, 1);
  1771. lua_getfield(L, idx, "nameinbuffer");
  1772. if (!lua_isnoneornil(L, -1))
  1773. attrib.nameInBuffer = luax_checkstring(L, -1);
  1774. else
  1775. attrib.nameInBuffer = attrib.name;
  1776. lua_pop(L, 1);
  1777. lua_getfield(L, idx, "startindex");
  1778. attrib.startArrayIndex = (int) luaL_optinteger(L, -1, 1) - 1;
  1779. lua_pop(L, 1);
  1780. return attrib;
  1781. }
  1782. static Mesh* newMeshFromBuffers(lua_State *L)
  1783. {
  1784. std::vector<Mesh::BufferAttribute> attributes;
  1785. for (size_t i = 1; i <= luax_objlen(L, 1); i++)
  1786. {
  1787. lua_rawgeti(L, 1, i);
  1788. attributes.push_back(luax_checkbufferattributetable(L, -1));
  1789. lua_pop(L, 1);
  1790. }
  1791. PrimitiveType drawmode = luax_checkmeshdrawmode(L, 2);
  1792. Mesh *t = nullptr;
  1793. luax_catchexcept(L, [&]() { t = instance()->newMesh(attributes, drawmode); });
  1794. return t;
  1795. }
  1796. int w_newMesh(lua_State *L)
  1797. {
  1798. luax_checkgraphicscreated(L);
  1799. // Check first argument: table or number of vertices.
  1800. int arg1type = lua_type(L, 1);
  1801. if (arg1type != LUA_TTABLE && arg1type != LUA_TNUMBER)
  1802. luaL_argerror(L, 1, "table or number expected");
  1803. Mesh *t = nullptr;
  1804. int arg2type = lua_type(L, 2);
  1805. if (luax_isbufferattributetable(L, 1))
  1806. t = newMeshFromBuffers(L);
  1807. else if (arg1type == LUA_TTABLE && (arg2type == LUA_TTABLE || arg2type == LUA_TNUMBER || arg2type == LUA_TUSERDATA))
  1808. t = newCustomMesh(L);
  1809. else
  1810. t = newStandardMesh(L);
  1811. luax_pushtype(L, t);
  1812. t->release();
  1813. return 1;
  1814. }
  1815. int w_newTextBatch(lua_State *L)
  1816. {
  1817. luax_checkgraphicscreated(L);
  1818. graphics::Font *font = luax_checkfont(L, 1);
  1819. TextBatch *t = nullptr;
  1820. if (lua_isnoneornil(L, 2))
  1821. luax_catchexcept(L, [&](){ t = instance()->newTextBatch(font); });
  1822. else
  1823. {
  1824. std::vector<love::font::ColoredString> text;
  1825. luax_checkcoloredstring(L, 2, text);
  1826. luax_catchexcept(L, [&](){ t = instance()->newTextBatch(font, text); });
  1827. }
  1828. luax_pushtype(L, t);
  1829. t->release();
  1830. return 1;
  1831. }
  1832. int w_newText(lua_State *L)
  1833. {
  1834. luax_markdeprecated(L, 1, "love.graphics.newText", API_FUNCTION, DEPRECATED_RENAMED, "love.graphics.newTextBatch");
  1835. return w_newTextBatch(L);
  1836. }
  1837. int w_newVideo(lua_State *L)
  1838. {
  1839. luax_checkgraphicscreated(L);
  1840. if (!luax_istype(L, 1, love::video::VideoStream::type))
  1841. luax_convobj(L, 1, "video", "newVideoStream");
  1842. auto stream = luax_checktype<love::video::VideoStream>(L, 1);
  1843. float dpiscale = (float) luaL_optnumber(L, 2, 1.0);
  1844. Video *video = nullptr;
  1845. luax_catchexcept(L, [&]() { video = instance()->newVideo(stream, dpiscale); });
  1846. luax_pushtype(L, video);
  1847. video->release();
  1848. return 1;
  1849. }
  1850. int w_readbackBuffer(lua_State *L)
  1851. {
  1852. Buffer *b = luax_checkbuffer(L, 1);
  1853. lua_Integer offset = luaL_optinteger(L, 2, 0);
  1854. lua_Integer size = luaL_optinteger(L, 3, b->getSize() - offset);
  1855. data::ByteData *dest = nullptr;
  1856. size_t destoffset = 0;
  1857. if (!lua_isnoneornil(L, 4))
  1858. {
  1859. dest = luax_checktype<data::ByteData>(L, 4);
  1860. destoffset = (size_t) luaL_optinteger(L, 5, 0);
  1861. }
  1862. love::data::ByteData *data = nullptr;
  1863. luax_catchexcept(L, [&]() { data = instance()->readbackBuffer(b, offset, size, dest, destoffset); });
  1864. luax_pushtype(L, data);
  1865. data->release();
  1866. return 1;
  1867. }
  1868. int w_readbackBufferAsync(lua_State *L)
  1869. {
  1870. Buffer *b = luax_checkbuffer(L, 1);
  1871. lua_Integer offset = luaL_optinteger(L, 2, 0);
  1872. lua_Integer size = luaL_optinteger(L, 3, b->getSize() - offset);
  1873. data::ByteData *dest = nullptr;
  1874. size_t destoffset = 0;
  1875. if (!lua_isnoneornil(L, 4))
  1876. {
  1877. dest = luax_checktype<data::ByteData>(L, 4);
  1878. destoffset = (size_t) luaL_optinteger(L, 5, 0);
  1879. }
  1880. GraphicsReadback *r = nullptr;
  1881. luax_catchexcept(L, [&]() { r = instance()->readbackBufferAsync(b, offset, size, dest, destoffset); });
  1882. luax_pushtype(L, r);
  1883. r->release();
  1884. return 1;
  1885. }
  1886. int w_readbackTexture(lua_State *L)
  1887. {
  1888. Texture *t = luax_checktexture(L, 1);
  1889. int slice = 0;
  1890. if (t->getTextureType() != TEXTURE_2D)
  1891. slice = (int) luaL_checkinteger(L, 2) - 1;
  1892. int mipmap = (int) luaL_optinteger(L, 3, 1) - 1;
  1893. Rect rect = {0, 0, t->getPixelWidth(mipmap), t->getPixelHeight(mipmap)};
  1894. if (!lua_isnoneornil(L, 4))
  1895. {
  1896. rect.x = (int) luaL_checkinteger(L, 4);
  1897. rect.y = (int) luaL_checkinteger(L, 5);
  1898. rect.w = (int) luaL_checkinteger(L, 6);
  1899. rect.h = (int) luaL_checkinteger(L, 7);
  1900. }
  1901. image::ImageData *dest = nullptr;
  1902. int destx = 0;
  1903. int desty = 0;
  1904. if (!lua_isnoneornil(L, 8))
  1905. {
  1906. dest = luax_checktype<image::ImageData>(L, 8);
  1907. destx = (int) luaL_optinteger(L, 9, 0);
  1908. desty = (int) luaL_optinteger(L, 10, 0);
  1909. }
  1910. image::ImageData *imagedata = nullptr;
  1911. luax_catchexcept(L, [&]() { imagedata = instance()->readbackTexture(t, slice, mipmap, rect, dest, destx, desty); });
  1912. luax_pushtype(L, imagedata);
  1913. imagedata->release();
  1914. return 1;
  1915. }
  1916. int w_readbackTextureAsync(lua_State *L)
  1917. {
  1918. Texture *t = luax_checktexture(L, 1);
  1919. int slice = 0;
  1920. if (t->getTextureType() != TEXTURE_2D)
  1921. slice = (int) luaL_checkinteger(L, 2) - 1;
  1922. int mipmap = (int) luaL_optinteger(L, 3, 1) - 1;
  1923. Rect rect = {0, 0, t->getPixelWidth(mipmap), t->getPixelHeight(mipmap)};
  1924. if (!lua_isnoneornil(L, 4))
  1925. {
  1926. rect.x = (int) luaL_checkinteger(L, 4);
  1927. rect.y = (int) luaL_checkinteger(L, 5);
  1928. rect.w = (int) luaL_checkinteger(L, 6);
  1929. rect.h = (int) luaL_checkinteger(L, 7);
  1930. }
  1931. image::ImageData *dest = nullptr;
  1932. int destx = 0;
  1933. int desty = 0;
  1934. if (!lua_isnoneornil(L, 8))
  1935. {
  1936. dest = luax_checktype<image::ImageData>(L, 8);
  1937. destx = (int) luaL_optinteger(L, 9, 0);
  1938. desty = (int) luaL_optinteger(L, 10, 0);
  1939. }
  1940. GraphicsReadback *r = nullptr;
  1941. luax_catchexcept(L, [&]() { r = instance()->readbackTextureAsync(t, slice, mipmap, rect, dest, destx, desty); });
  1942. luax_pushtype(L, r);
  1943. r->release();
  1944. return 1;
  1945. }
  1946. int w_setColor(lua_State *L)
  1947. {
  1948. Colorf c;
  1949. if (lua_istable(L, 1))
  1950. {
  1951. for (int i = 1; i <= 4; i++)
  1952. lua_rawgeti(L, 1, i);
  1953. c.r = (float) luaL_checknumber(L, -4);
  1954. c.g = (float) luaL_checknumber(L, -3);
  1955. c.b = (float) luaL_checknumber(L, -2);
  1956. c.a = (float) luaL_optnumber(L, -1, 1.0);
  1957. lua_pop(L, 4);
  1958. }
  1959. else
  1960. {
  1961. c.r = (float) luaL_checknumber(L, 1);
  1962. c.g = (float) luaL_checknumber(L, 2);
  1963. c.b = (float) luaL_checknumber(L, 3);
  1964. c.a = (float) luaL_optnumber(L, 4, 1.0);
  1965. }
  1966. instance()->setColor(c);
  1967. return 0;
  1968. }
  1969. int w_getColor(lua_State *L)
  1970. {
  1971. Colorf c = instance()->getColor();
  1972. lua_pushnumber(L, c.r);
  1973. lua_pushnumber(L, c.g);
  1974. lua_pushnumber(L, c.b);
  1975. lua_pushnumber(L, c.a);
  1976. return 4;
  1977. }
  1978. int w_setBackgroundColor(lua_State *L)
  1979. {
  1980. Colorf c;
  1981. if (lua_istable(L, 1))
  1982. {
  1983. for (int i = 1; i <= 4; i++)
  1984. lua_rawgeti(L, 1, i);
  1985. c.r = (float) luaL_checknumber(L, -4);
  1986. c.g = (float) luaL_checknumber(L, -3);
  1987. c.b = (float) luaL_checknumber(L, -2);
  1988. c.a = (float) luaL_optnumber(L, -1, 1.0);
  1989. lua_pop(L, 4);
  1990. }
  1991. else
  1992. {
  1993. c.r = (float) luaL_checknumber(L, 1);
  1994. c.g = (float) luaL_checknumber(L, 2);
  1995. c.b = (float) luaL_checknumber(L, 3);
  1996. c.a = (float) luaL_optnumber(L, 4, 1.0);
  1997. }
  1998. instance()->setBackgroundColor(c);
  1999. return 0;
  2000. }
  2001. int w_getBackgroundColor(lua_State *L)
  2002. {
  2003. Colorf c = instance()->getBackgroundColor();
  2004. lua_pushnumber(L, c.r);
  2005. lua_pushnumber(L, c.g);
  2006. lua_pushnumber(L, c.b);
  2007. lua_pushnumber(L, c.a);
  2008. return 4;
  2009. }
  2010. int w_setNewFont(lua_State *L)
  2011. {
  2012. luax_markdeprecated(L, 1, "love.graphics.setNewFont", API_FUNCTION, DEPRECATED_NO_REPLACEMENT, nullptr);
  2013. int ret = w_newFont(L);
  2014. Font *font = luax_checktype<Font>(L, -1);
  2015. instance()->setFont(font);
  2016. return ret;
  2017. }
  2018. int w_setFont(lua_State *L)
  2019. {
  2020. Font *font = luax_checktype<Font>(L, 1);
  2021. instance()->setFont(font);
  2022. return 0;
  2023. }
  2024. int w_getFont(lua_State *L)
  2025. {
  2026. Font *f = nullptr;
  2027. luax_catchexcept(L, [&](){ f = instance()->getFont(); });
  2028. luax_pushtype(L, f);
  2029. return 1;
  2030. }
  2031. int w_setColorMask(lua_State *L)
  2032. {
  2033. ColorChannelMask mask;
  2034. if (lua_isnoneornil(L, 1))
  2035. {
  2036. mask.r = mask.g = mask.b = mask.a = true;
  2037. }
  2038. else if (lua_gettop(L) <= 1)
  2039. {
  2040. // Set all color components if a single argument is given.
  2041. mask.r = mask.g = mask.b = mask.a = luax_checkboolean(L, 1);
  2042. }
  2043. else
  2044. {
  2045. mask.r = luax_checkboolean(L, 1);
  2046. mask.g = luax_checkboolean(L, 2);
  2047. mask.b = luax_checkboolean(L, 3);
  2048. mask.a = luax_checkboolean(L, 4);
  2049. }
  2050. instance()->setColorMask(mask);
  2051. return 0;
  2052. }
  2053. int w_getColorMask(lua_State *L)
  2054. {
  2055. ColorChannelMask mask = instance()->getColorMask();
  2056. luax_pushboolean(L, mask.r);
  2057. luax_pushboolean(L, mask.g);
  2058. luax_pushboolean(L, mask.b);
  2059. luax_pushboolean(L, mask.a);
  2060. return 4;
  2061. }
  2062. int w_setBlendMode(lua_State *L)
  2063. {
  2064. BlendMode mode;
  2065. const char *str = luaL_checkstring(L, 1);
  2066. if (!getConstant(str, mode))
  2067. return luax_enumerror(L, "blend mode", getConstants(mode), str);
  2068. BlendAlpha alphamode = BLENDALPHA_MULTIPLY;
  2069. if (!lua_isnoneornil(L, 2))
  2070. {
  2071. const char *alphastr = luaL_checkstring(L, 2);
  2072. if (!getConstant(alphastr, alphamode))
  2073. return luax_enumerror(L, "blend alpha mode", getConstants(alphamode), alphastr);
  2074. }
  2075. luax_catchexcept(L, [&](){ instance()->setBlendMode(mode, alphamode); });
  2076. return 0;
  2077. }
  2078. int w_getBlendMode(lua_State *L)
  2079. {
  2080. const char *str;
  2081. const char *alphastr;
  2082. BlendAlpha alphamode;
  2083. BlendMode mode = instance()->getBlendMode(alphamode);
  2084. if (!getConstant(mode, str))
  2085. return luaL_error(L, "Unknown blend mode");
  2086. if (!getConstant(alphamode, alphastr))
  2087. return luaL_error(L, "Unknown blend alpha mode");
  2088. lua_pushstring(L, str);
  2089. lua_pushstring(L, alphastr);
  2090. return 2;
  2091. }
  2092. static BlendOperation luax_checkblendop(lua_State *L, int idx)
  2093. {
  2094. BlendOperation op = BLENDOP_ADD;
  2095. const char *str = luaL_checkstring(L, idx);
  2096. if (!getConstant(str, op))
  2097. luax_enumerror(L, "blend operation", getConstants(op), str);
  2098. return op;
  2099. }
  2100. static BlendFactor luax_checkblendfactor(lua_State *L, int idx)
  2101. {
  2102. BlendFactor factor = BLENDFACTOR_ZERO;
  2103. const char *str = luaL_checkstring(L, idx);
  2104. if (!getConstant(str, factor))
  2105. luax_enumerror(L, "blend factor", getConstants(factor), str);
  2106. return factor;
  2107. }
  2108. static void luax_pushblendop(lua_State *L, BlendOperation op)
  2109. {
  2110. const char *str;
  2111. if (!getConstant(op, str))
  2112. luaL_error(L, "unknown blend operation");
  2113. lua_pushstring(L, str);
  2114. }
  2115. static void luax_pushblendfactor(lua_State *L, BlendFactor factor)
  2116. {
  2117. const char *str;
  2118. if (!getConstant(factor, str))
  2119. luaL_error(L, "unknown blend factor");
  2120. lua_pushstring(L, str);
  2121. }
  2122. int w_setBlendState(lua_State *L)
  2123. {
  2124. BlendState state;
  2125. if (!lua_isnoneornil(L, 1))
  2126. {
  2127. state.enable = true;
  2128. if (lua_gettop(L) >= 4)
  2129. {
  2130. state.operationRGB = luax_checkblendop(L, 1);
  2131. state.operationA = luax_checkblendop(L, 2);
  2132. state.srcFactorRGB = luax_checkblendfactor(L, 3);
  2133. state.srcFactorA = luax_checkblendfactor(L, 4);
  2134. state.dstFactorRGB = luax_checkblendfactor(L, 5);
  2135. state.dstFactorA = luax_checkblendfactor(L, 6);
  2136. }
  2137. else
  2138. {
  2139. state.operationRGB = state.operationA = luax_checkblendop(L, 1);
  2140. state.srcFactorRGB = state.srcFactorA = luax_checkblendfactor(L, 2);
  2141. state.dstFactorRGB = state.dstFactorA = luax_checkblendfactor(L, 3);
  2142. }
  2143. }
  2144. luax_catchexcept(L, [&](){ instance()->setBlendState(state); });
  2145. return 0;
  2146. }
  2147. int w_getBlendState(lua_State *L)
  2148. {
  2149. const BlendState &state = instance()->getBlendState();
  2150. if (state.enable)
  2151. {
  2152. luax_pushblendop(L, state.operationRGB);
  2153. luax_pushblendop(L, state.operationA);
  2154. luax_pushblendfactor(L, state.srcFactorRGB);
  2155. luax_pushblendfactor(L, state.srcFactorA);
  2156. luax_pushblendfactor(L, state.dstFactorRGB);
  2157. luax_pushblendfactor(L, state.dstFactorA);
  2158. }
  2159. else
  2160. {
  2161. for (int i = 0; i < 6; i++)
  2162. lua_pushnil(L);
  2163. }
  2164. return 6;
  2165. }
  2166. int w_setDefaultFilter(lua_State *L)
  2167. {
  2168. SamplerState s = instance()->getDefaultSamplerState();
  2169. const char *minstr = luaL_checkstring(L, 1);
  2170. const char *magstr = luaL_optstring(L, 2, minstr);
  2171. if (!SamplerState::getConstant(minstr, s.minFilter))
  2172. return luax_enumerror(L, "filter mode", SamplerState::getConstants(s.minFilter), minstr);
  2173. if (!SamplerState::getConstant(magstr, s.magFilter))
  2174. return luax_enumerror(L, "filter mode", SamplerState::getConstants(s.magFilter), magstr);
  2175. s.maxAnisotropy = std::min(std::max(1, (int) luaL_optnumber(L, 3, 1.0)), LOVE_UINT8_MAX);
  2176. instance()->setDefaultSamplerState(s);
  2177. return 0;
  2178. }
  2179. int w_getDefaultFilter(lua_State *L)
  2180. {
  2181. const SamplerState &s = instance()->getDefaultSamplerState();
  2182. const char *minstr;
  2183. const char *magstr;
  2184. if (!SamplerState::getConstant(s.minFilter, minstr))
  2185. return luaL_error(L, "Unknown minification filter mode");
  2186. if (!SamplerState::getConstant(s.magFilter, magstr))
  2187. return luaL_error(L, "Unknown magnification filter mode");
  2188. lua_pushstring(L, minstr);
  2189. lua_pushstring(L, magstr);
  2190. lua_pushnumber(L, s.maxAnisotropy);
  2191. return 3;
  2192. }
  2193. int w_setDefaultMipmapFilter(lua_State *L)
  2194. {
  2195. SamplerState s = instance()->getDefaultSamplerState();
  2196. s.mipmapFilter = SamplerState::MIPMAP_FILTER_NONE;
  2197. if (!lua_isnoneornil(L, 1))
  2198. {
  2199. const char *str = luaL_checkstring(L, 1);
  2200. if (!SamplerState::getConstant(str, s.mipmapFilter))
  2201. return luax_enumerror(L, "filter mode", SamplerState::getConstants(s.mipmapFilter), str);
  2202. }
  2203. s.lodBias = -((float) luaL_optnumber(L, 2, 0.0));
  2204. instance()->setDefaultSamplerState(s);
  2205. return 0;
  2206. }
  2207. int w_getDefaultMipmapFilter(lua_State *L)
  2208. {
  2209. const SamplerState &s = instance()->getDefaultSamplerState();
  2210. const char *str;
  2211. if (SamplerState::getConstant(s.mipmapFilter, str))
  2212. lua_pushstring(L, str);
  2213. else
  2214. lua_pushnil(L);
  2215. lua_pushnumber(L, -s.lodBias);
  2216. return 2;
  2217. }
  2218. int w_setLineWidth(lua_State *L)
  2219. {
  2220. float width = (float)luaL_checknumber(L, 1);
  2221. instance()->setLineWidth(width);
  2222. return 0;
  2223. }
  2224. int w_setLineStyle(lua_State *L)
  2225. {
  2226. Graphics::LineStyle style;
  2227. const char *str = luaL_checkstring(L, 1);
  2228. if (!Graphics::getConstant(str, style))
  2229. return luax_enumerror(L, "line style", Graphics::getConstants(style), str);
  2230. instance()->setLineStyle(style);
  2231. return 0;
  2232. }
  2233. int w_setLineJoin(lua_State *L)
  2234. {
  2235. Graphics::LineJoin join;
  2236. const char *str = luaL_checkstring(L, 1);
  2237. if (!Graphics::getConstant(str, join))
  2238. return luax_enumerror(L, "line join", Graphics::getConstants(join), str);
  2239. instance()->setLineJoin(join);
  2240. return 0;
  2241. }
  2242. int w_getLineWidth(lua_State *L)
  2243. {
  2244. lua_pushnumber(L, instance()->getLineWidth());
  2245. return 1;
  2246. }
  2247. int w_getLineStyle(lua_State *L)
  2248. {
  2249. Graphics::LineStyle style = instance()->getLineStyle();
  2250. const char *str;
  2251. if (!Graphics::getConstant(style, str))
  2252. return luaL_error(L, "Unknown line style");
  2253. lua_pushstring(L, str);
  2254. return 1;
  2255. }
  2256. int w_getLineJoin(lua_State *L)
  2257. {
  2258. Graphics::LineJoin join = instance()->getLineJoin();
  2259. const char *str;
  2260. if (!Graphics::getConstant(join, str))
  2261. return luaL_error(L, "Unknown line join");
  2262. lua_pushstring(L, str);
  2263. return 1;
  2264. }
  2265. int w_setPointSize(lua_State *L)
  2266. {
  2267. float size = (float)luaL_checknumber(L, 1);
  2268. instance()->setPointSize(size);
  2269. return 0;
  2270. }
  2271. int w_getPointSize(lua_State *L)
  2272. {
  2273. lua_pushnumber(L, instance()->getPointSize());
  2274. return 1;
  2275. }
  2276. int w_setDepthMode(lua_State *L)
  2277. {
  2278. if (lua_isnoneornil(L, 1) && lua_isnoneornil(L, 2))
  2279. luax_catchexcept(L, [&]() { instance()->setDepthMode(); });
  2280. else
  2281. {
  2282. CompareMode compare = COMPARE_ALWAYS;
  2283. const char *str = luaL_checkstring(L, 1);
  2284. bool write = luax_checkboolean(L, 2);
  2285. if (!getConstant(str, compare))
  2286. return luax_enumerror(L, "compare mode", getConstants(compare), str);
  2287. luax_catchexcept(L, [&]() { instance()->setDepthMode(compare, write); });
  2288. }
  2289. return 0;
  2290. }
  2291. int w_getDepthMode(lua_State *L)
  2292. {
  2293. CompareMode compare = COMPARE_ALWAYS;
  2294. bool write = false;
  2295. instance()->getDepthMode(compare, write);
  2296. const char *str;
  2297. if (!getConstant(compare, str))
  2298. return luaL_error(L, "Unknown compare mode");
  2299. lua_pushstring(L, str);
  2300. luax_pushboolean(L, write);
  2301. return 2;
  2302. }
  2303. int w_setMeshCullMode(lua_State *L)
  2304. {
  2305. const char *str = luaL_checkstring(L, 1);
  2306. CullMode mode;
  2307. if (!getConstant(str, mode))
  2308. return luax_enumerror(L, "cull mode", getConstants(mode), str);
  2309. luax_catchexcept(L, [&]() { instance()->setMeshCullMode(mode); });
  2310. return 0;
  2311. }
  2312. int w_getMeshCullMode(lua_State *L)
  2313. {
  2314. CullMode mode = instance()->getMeshCullMode();
  2315. const char *str;
  2316. if (!getConstant(mode, str))
  2317. return luaL_error(L, "Unknown cull mode");
  2318. lua_pushstring(L, str);
  2319. return 1;
  2320. }
  2321. int w_setFrontFaceWinding(lua_State *L)
  2322. {
  2323. const char *str = luaL_checkstring(L, 1);
  2324. Winding winding;
  2325. if (!getConstant(str, winding))
  2326. return luax_enumerror(L, "vertex winding", getConstants(winding), str);
  2327. luax_catchexcept(L, [&]() { instance()->setFrontFaceWinding(winding); });
  2328. return 0;
  2329. }
  2330. int w_getFrontFaceWinding(lua_State *L)
  2331. {
  2332. Winding winding = instance()->getFrontFaceWinding();
  2333. const char *str;
  2334. if (!getConstant(winding, str))
  2335. return luaL_error(L, "Unknown vertex winding");
  2336. lua_pushstring(L, str);
  2337. return 1;
  2338. }
  2339. int w_setWireframe(lua_State *L)
  2340. {
  2341. instance()->setWireframe(luax_checkboolean(L, 1));
  2342. return 0;
  2343. }
  2344. int w_isWireframe(lua_State *L)
  2345. {
  2346. luax_pushboolean(L, instance()->isWireframe());
  2347. return 1;
  2348. }
  2349. int w_setShader(lua_State *L)
  2350. {
  2351. if (lua_isnoneornil(L,1))
  2352. {
  2353. instance()->setShader();
  2354. return 0;
  2355. }
  2356. Shader *shader = luax_checkshader(L, 1);
  2357. instance()->setShader(shader);
  2358. return 0;
  2359. }
  2360. int w_getShader(lua_State *L)
  2361. {
  2362. Shader *shader = instance()->getShader();
  2363. if (shader)
  2364. luax_pushtype(L, shader);
  2365. else
  2366. lua_pushnil(L);
  2367. return 1;
  2368. }
  2369. int w_getSupported(lua_State *L)
  2370. {
  2371. const Graphics::Capabilities &caps = instance()->getCapabilities();
  2372. if (lua_istable(L, 1))
  2373. lua_pushvalue(L, 1);
  2374. else
  2375. lua_createtable(L, 0, (int) Graphics::FEATURE_MAX_ENUM);
  2376. for (int i = 0; i < (int) Graphics::FEATURE_MAX_ENUM; i++)
  2377. {
  2378. auto feature = (Graphics::Feature) i;
  2379. const char *name = nullptr;
  2380. if (!Graphics::getConstant(feature, name))
  2381. continue;
  2382. luax_pushboolean(L, caps.features[i]);
  2383. lua_setfield(L, -2, name);
  2384. }
  2385. return 1;
  2386. }
  2387. int w_getTextureFormats(lua_State *L)
  2388. {
  2389. luaL_checktype(L, 1, LUA_TTABLE);
  2390. bool rt = luax_checkboolflag(L, 1, Texture::getConstant(Texture::SETTING_RENDER_TARGET));
  2391. bool computewrite = luax_boolflag(L, 1, Texture::getConstant(Texture::SETTING_COMPUTE_WRITE), false);
  2392. OptionalBool readable;
  2393. lua_getfield(L, 1, Texture::getConstant(Texture::SETTING_READABLE));
  2394. if (!lua_isnoneornil(L, -1))
  2395. readable.set(luax_checkboolean(L, -1));
  2396. lua_pop(L, 1);
  2397. if (lua_istable(L, 2))
  2398. lua_pushvalue(L, 2);
  2399. else
  2400. lua_createtable(L, 0, (int) PIXELFORMAT_MAX_ENUM);
  2401. for (int i = 0; i < (int) PIXELFORMAT_MAX_ENUM; i++)
  2402. {
  2403. PixelFormat format = (PixelFormat) i;
  2404. const char *name = nullptr;
  2405. if (format == PIXELFORMAT_UNKNOWN || !love::getConstant(format, name))
  2406. continue;
  2407. uint32 usage = PIXELFORMATUSAGEFLAGS_NONE;
  2408. if (rt)
  2409. usage |= PIXELFORMATUSAGEFLAGS_RENDERTARGET;
  2410. if (readable.get(!isPixelFormatDepthStencil(format)))
  2411. usage |= PIXELFORMATUSAGEFLAGS_SAMPLE;
  2412. if (computewrite)
  2413. usage |= PIXELFORMATUSAGEFLAGS_COMPUTEWRITE;
  2414. luax_pushboolean(L, instance()->isPixelFormatSupported(format, (PixelFormatUsageFlags) usage));
  2415. lua_setfield(L, -2, name);
  2416. }
  2417. return 1;
  2418. }
  2419. static int w__getFormats(lua_State *L, int idx, bool (*isFormatSupported)(PixelFormat), bool (*ignore)(PixelFormat))
  2420. {
  2421. if (lua_istable(L, idx))
  2422. lua_pushvalue(L, idx);
  2423. else
  2424. lua_createtable(L, 0, (int) PIXELFORMAT_MAX_ENUM);
  2425. for (int i = 0; i < (int) PIXELFORMAT_MAX_ENUM; i++)
  2426. {
  2427. PixelFormat format = (PixelFormat) i;
  2428. const char *name = nullptr;
  2429. if (format == PIXELFORMAT_UNKNOWN || !love::getConstant(format, name) || ignore(format))
  2430. continue;
  2431. luax_pushboolean(L, isFormatSupported(format));
  2432. lua_setfield(L, -2, name);
  2433. }
  2434. return 1;
  2435. }
  2436. int w_getCanvasFormats(lua_State *L)
  2437. {
  2438. luax_markdeprecated(L, 1, "love.graphics.getCanvasFormats", API_FUNCTION, DEPRECATED_REPLACED, "love.graphics.getTextureFormats");
  2439. bool (*supported)(PixelFormat);
  2440. int idx = 1;
  2441. if (lua_type(L, 1) == LUA_TBOOLEAN)
  2442. {
  2443. idx = 2;
  2444. if (luax_checkboolean(L, 1))
  2445. {
  2446. supported = [](PixelFormat format) -> bool
  2447. {
  2448. const uint32 usage = PIXELFORMATUSAGEFLAGS_SAMPLE | PIXELFORMATUSAGEFLAGS_RENDERTARGET;
  2449. return instance()->isPixelFormatSupported(format, (PixelFormatUsageFlags) usage);
  2450. };
  2451. }
  2452. else
  2453. {
  2454. supported = [](PixelFormat format) -> bool
  2455. {
  2456. return instance()->isPixelFormatSupported(format, PIXELFORMATUSAGEFLAGS_RENDERTARGET);
  2457. };
  2458. }
  2459. }
  2460. else
  2461. {
  2462. supported = [](PixelFormat format) -> bool
  2463. {
  2464. bool readable = !isPixelFormatDepthStencil(format);
  2465. uint32 usage = PIXELFORMATUSAGEFLAGS_RENDERTARGET;
  2466. if (readable)
  2467. usage |= PIXELFORMATUSAGEFLAGS_SAMPLE;
  2468. return instance()->isPixelFormatSupported(format, (PixelFormatUsageFlags) usage);
  2469. };
  2470. }
  2471. return w__getFormats(L, idx, supported, isPixelFormatCompressed);
  2472. }
  2473. int w_getImageFormats(lua_State *L)
  2474. {
  2475. luax_markdeprecated(L, 1, "love.graphics.getImageFormats", API_FUNCTION, DEPRECATED_REPLACED, "love.graphics.getTextureFormats");
  2476. const auto supported = [](PixelFormat format) -> bool
  2477. {
  2478. return instance()->isPixelFormatSupported(format, PIXELFORMATUSAGEFLAGS_SAMPLE);
  2479. };
  2480. const auto ignore = [](PixelFormat format) -> bool
  2481. {
  2482. return !(image::ImageData::validPixelFormat(format) || isPixelFormatCompressed(format));
  2483. };
  2484. return w__getFormats(L, 1, supported, ignore);
  2485. }
  2486. int w_getTextureTypes(lua_State *L)
  2487. {
  2488. const Graphics::Capabilities &caps = instance()->getCapabilities();
  2489. if (lua_istable(L, 1))
  2490. lua_pushvalue(L, 1);
  2491. else
  2492. lua_createtable(L, 0, (int) TEXTURE_MAX_ENUM);
  2493. for (int i = 0; i < (int) TEXTURE_MAX_ENUM; i++)
  2494. {
  2495. TextureType textype = (TextureType) i;
  2496. const char *name = nullptr;
  2497. if (!Texture::getConstant(textype, name))
  2498. continue;
  2499. luax_pushboolean(L, caps.textureTypes[i]);
  2500. lua_setfield(L, -2, name);
  2501. }
  2502. return 1;
  2503. }
  2504. int w_getRendererInfo(lua_State *L)
  2505. {
  2506. Graphics::RendererInfo info;
  2507. luax_catchexcept(L, [&](){ info = instance()->getRendererInfo(); });
  2508. luax_pushstring(L, info.name);
  2509. luax_pushstring(L, info.version);
  2510. luax_pushstring(L, info.vendor);
  2511. luax_pushstring(L, info.device);
  2512. return 4;
  2513. }
  2514. int w_getSystemLimits(lua_State *L)
  2515. {
  2516. const Graphics::Capabilities &caps = instance()->getCapabilities();
  2517. if (lua_istable(L, 1))
  2518. lua_pushvalue(L, 1);
  2519. else
  2520. lua_createtable(L, 0, (int) Graphics::LIMIT_MAX_ENUM);
  2521. for (int i = 0; i < (int) Graphics::LIMIT_MAX_ENUM; i++)
  2522. {
  2523. Graphics::SystemLimit limittype = (Graphics::SystemLimit) i;
  2524. const char *name = nullptr;
  2525. if (!Graphics::getConstant(limittype, name))
  2526. continue;
  2527. lua_pushnumber(L, caps.limits[i]);
  2528. lua_setfield(L, -2, name);
  2529. }
  2530. return 1;
  2531. }
  2532. int w_getStats(lua_State *L)
  2533. {
  2534. Graphics::Stats stats = instance()->getStats();
  2535. if (lua_istable(L, 1))
  2536. lua_pushvalue(L, 1);
  2537. else
  2538. lua_createtable(L, 0, 7);
  2539. lua_pushinteger(L, stats.drawCalls);
  2540. lua_setfield(L, -2, "drawcalls");
  2541. lua_pushinteger(L, stats.drawCallsBatched);
  2542. lua_setfield(L, -2, "drawcallsbatched");
  2543. lua_pushinteger(L, stats.renderTargetSwitches);
  2544. lua_setfield(L, -2, "canvasswitches");
  2545. lua_pushinteger(L, stats.shaderSwitches);
  2546. lua_setfield(L, -2, "shaderswitches");
  2547. lua_pushinteger(L, stats.textures);
  2548. lua_setfield(L, -2, "textures");
  2549. lua_pushinteger(L, stats.fonts);
  2550. lua_setfield(L, -2, "fonts");
  2551. lua_pushinteger(L, stats.buffers);
  2552. lua_setfield(L, -2, "buffers");
  2553. lua_pushnumber(L, (lua_Number) stats.textureMemory);
  2554. lua_setfield(L, -2, "texturememory");
  2555. lua_pushnumber(L, (lua_Number) stats.bufferMemory);
  2556. lua_setfield(L, -2, "buffermemory");
  2557. return 1;
  2558. }
  2559. int w_draw(lua_State *L)
  2560. {
  2561. Drawable *drawable = nullptr;
  2562. Texture *texture = nullptr;
  2563. Quad *quad = luax_totype<Quad>(L, 2);
  2564. int startidx = 2;
  2565. if (quad != nullptr)
  2566. {
  2567. texture = luax_checktexture(L, 1);
  2568. startidx = 3;
  2569. }
  2570. else if (lua_isnil(L, 2) && !lua_isnoneornil(L, 3))
  2571. {
  2572. return luax_typerror(L, 2, "Quad");
  2573. }
  2574. else
  2575. {
  2576. drawable = luax_checktype<Drawable>(L, 1);
  2577. startidx = 2;
  2578. }
  2579. luax_checkstandardtransform(L, startidx, [&](const Matrix4 &m)
  2580. {
  2581. luax_catchexcept(L, [&]()
  2582. {
  2583. if (texture && quad)
  2584. instance()->draw(texture, quad, m);
  2585. else
  2586. instance()->draw(drawable, m);
  2587. });
  2588. });
  2589. return 0;
  2590. }
  2591. int w_drawLayer(lua_State *L)
  2592. {
  2593. Texture *texture = luax_checktexture(L, 1);
  2594. int layer = (int) luaL_checkinteger(L, 2) - 1;
  2595. int startidx = 3;
  2596. Quad *quad = luax_totype<Quad>(L, startidx);
  2597. if (quad != nullptr)
  2598. {
  2599. texture = luax_checktexture(L, 1);
  2600. startidx++;
  2601. }
  2602. else if (lua_isnil(L, startidx) && !lua_isnoneornil(L, startidx + 1))
  2603. {
  2604. return luax_typerror(L, startidx, "Quad");
  2605. }
  2606. luax_checkstandardtransform(L, startidx, [&](const Matrix4 &m)
  2607. {
  2608. luax_catchexcept(L, [&]()
  2609. {
  2610. if (quad)
  2611. instance()->drawLayer(texture, layer, quad, m);
  2612. else
  2613. instance()->drawLayer(texture, layer, m);
  2614. });
  2615. });
  2616. return 0;
  2617. }
  2618. int w_drawInstanced(lua_State *L)
  2619. {
  2620. Mesh *t = luax_checkmesh(L, 1);
  2621. int instancecount = (int) luaL_checkinteger(L, 2);
  2622. luax_checkstandardtransform(L, 3, [&](const Matrix4 &m)
  2623. {
  2624. luax_catchexcept(L, [&]() { instance()->drawInstanced(t, m, instancecount); });
  2625. });
  2626. return 0;
  2627. }
  2628. int w_drawIndirect(lua_State *L)
  2629. {
  2630. Mesh *t = luax_checkmesh(L, 1);
  2631. Buffer *argsbuffer = luax_checkbuffer(L, 2);
  2632. int argsindex = (int) luaL_checkinteger(L, 3) - 1;
  2633. luax_checkstandardtransform(L, 4, [&](const Matrix4 &m)
  2634. {
  2635. luax_catchexcept(L, [&]() { instance()->drawIndirect(t, m, argsbuffer, argsindex); });
  2636. });
  2637. return 0;
  2638. }
  2639. int w_drawFromShader(lua_State *L)
  2640. {
  2641. if (luax_istype(L, 1, Buffer::type))
  2642. {
  2643. // Indexed drawing.
  2644. Buffer *t = luax_checkbuffer(L, 1);
  2645. int indexcount = (int) luaL_checkinteger(L, 2);
  2646. int instancecount = (int) luaL_optinteger(L, 3, 1);
  2647. int indexstart = (int) luaL_optinteger(L, 4, 1) - 1;
  2648. Texture *tex = nullptr;
  2649. if (!lua_isnoneornil(L, 5))
  2650. tex = luax_checktexture(L, 5);
  2651. luax_catchexcept(L, [&]() { instance()->drawFromShader(t, indexcount, instancecount, indexstart, tex); });
  2652. }
  2653. else
  2654. {
  2655. const char *primstr = luaL_checkstring(L, 1);
  2656. PrimitiveType primtype = PRIMITIVE_TRIANGLES;
  2657. if (!getConstant(primstr, primtype))
  2658. return luax_enumerror(L, "primitive type", getConstants(primtype), primstr);
  2659. int vertexcount = (int) luaL_checkinteger(L, 2);
  2660. int instancecount = (int) luaL_optinteger(L, 3, 1);
  2661. Texture *tex = nullptr;
  2662. if (!lua_isnoneornil(L, 4))
  2663. tex = luax_checktexture(L, 4);
  2664. luax_catchexcept(L, [&]() { instance()->drawFromShader(primtype, vertexcount, instancecount, tex); });
  2665. }
  2666. return 0;
  2667. }
  2668. int w_drawFromShaderIndirect(lua_State *L)
  2669. {
  2670. if (luax_istype(L, 1, Buffer::type))
  2671. {
  2672. // Indexed drawing.
  2673. Buffer *t = luax_checkbuffer(L, 1);
  2674. Buffer *argsbuffer = luax_checkbuffer(L, 2);
  2675. int argsindex = (int) luaL_optinteger(L, 3, 1) - 1;
  2676. Texture *tex = nullptr;
  2677. if (!lua_isnoneornil(L, 4))
  2678. tex = luax_checktexture(L, 4);
  2679. luax_catchexcept(L, [&]() { instance()->drawFromShaderIndirect(t, argsbuffer, argsindex, tex); });
  2680. }
  2681. else
  2682. {
  2683. const char *primstr = luaL_checkstring(L, 1);
  2684. PrimitiveType primtype = PRIMITIVE_TRIANGLES;
  2685. if (!getConstant(primstr, primtype))
  2686. return luax_enumerror(L, "primitive type", getConstants(primtype), primstr);
  2687. Buffer *argsbuffer = luax_checkbuffer(L, 2);
  2688. int argsindex = (int) luaL_optinteger(L, 3, 1) - 1;
  2689. Texture *tex = nullptr;
  2690. if (!lua_isnoneornil(L, 4))
  2691. tex = luax_checktexture(L, 4);
  2692. luax_catchexcept(L, [&]() { instance()->drawFromShaderIndirect(primtype, argsbuffer, argsindex, tex); });
  2693. }
  2694. return 0;
  2695. }
  2696. int w_print(lua_State *L)
  2697. {
  2698. std::vector<love::font::ColoredString> str;
  2699. luax_checkcoloredstring(L, 1, str);
  2700. if (luax_istype(L, 2, Font::type))
  2701. {
  2702. Font *font = luax_checkfont(L, 2);
  2703. luax_checkstandardtransform(L, 3, [&](const Matrix4 &m)
  2704. {
  2705. luax_catchexcept(L, [&](){ instance()->print(str, font, m); });
  2706. });
  2707. }
  2708. else
  2709. {
  2710. luax_checkstandardtransform(L, 2, [&](const Matrix4 &m)
  2711. {
  2712. luax_catchexcept(L, [&](){ instance()->print(str, m); });
  2713. });
  2714. }
  2715. return 0;
  2716. }
  2717. int w_printf(lua_State *L)
  2718. {
  2719. std::vector<love::font::ColoredString> str;
  2720. luax_checkcoloredstring(L, 1, str);
  2721. Font *font = nullptr;
  2722. int startidx = 2;
  2723. if (luax_istype(L, startidx, Font::type))
  2724. {
  2725. font = luax_checkfont(L, startidx);
  2726. startidx++;
  2727. }
  2728. Font::AlignMode align = Font::ALIGN_LEFT;
  2729. Matrix4 m;
  2730. int formatidx = startidx + 2;
  2731. if (luax_istype(L, startidx, math::Transform::type))
  2732. {
  2733. math::Transform *tf = luax_totype<math::Transform>(L, startidx);
  2734. m = tf->getMatrix();
  2735. formatidx = startidx + 1;
  2736. }
  2737. else
  2738. {
  2739. float x = (float)luaL_checknumber(L, startidx + 0);
  2740. float y = (float)luaL_checknumber(L, startidx + 1);
  2741. float angle = (float) luaL_optnumber(L, startidx + 4, 0.0f);
  2742. float sx = (float) luaL_optnumber(L, startidx + 5, 1.0f);
  2743. float sy = (float) luaL_optnumber(L, startidx + 6, sx);
  2744. float ox = (float) luaL_optnumber(L, startidx + 7, 0.0f);
  2745. float oy = (float) luaL_optnumber(L, startidx + 8, 0.0f);
  2746. float kx = (float) luaL_optnumber(L, startidx + 9, 0.0f);
  2747. float ky = (float) luaL_optnumber(L, startidx + 10, 0.0f);
  2748. m = Matrix4(x, y, angle, sx, sy, ox, oy, kx, ky);
  2749. }
  2750. float wrap = (float)luaL_checknumber(L, formatidx);
  2751. const char *astr = lua_isnoneornil(L, formatidx + 1) ? nullptr : luaL_checkstring(L, formatidx + 1);
  2752. if (astr != nullptr && !Font::getConstant(astr, align))
  2753. return luax_enumerror(L, "alignment", Font::getConstants(align), astr);
  2754. if (font != nullptr)
  2755. luax_catchexcept(L, [&](){ instance()->printf(str, font, wrap, align, m); });
  2756. else
  2757. luax_catchexcept(L, [&](){ instance()->printf(str, wrap, align, m); });
  2758. return 0;
  2759. }
  2760. int w_points(lua_State *L)
  2761. {
  2762. // love.graphics.points has 3 variants:
  2763. // - points(x1, y1, x2, y2, ...)
  2764. // - points({x1, y1, x2, y2, ...})
  2765. // - points({{x1, y1 [, r, g, b, a]}, {x2, y2 [, r, g, b, a]}, ...})
  2766. int args = lua_gettop(L);
  2767. bool is_table = false;
  2768. bool is_table_of_tables = false;
  2769. if (args == 1 && lua_istable(L, 1))
  2770. {
  2771. is_table = true;
  2772. args = (int) luax_objlen(L, 1);
  2773. lua_rawgeti(L, 1, 1);
  2774. is_table_of_tables = lua_istable(L, -1);
  2775. lua_pop(L, 1);
  2776. }
  2777. if (args % 2 != 0 && !is_table_of_tables)
  2778. return luaL_error(L, "Number of vertex components must be a multiple of two");
  2779. int numpositions = args / 2;
  2780. if (is_table_of_tables)
  2781. numpositions = args;
  2782. Vector2 *positions = nullptr;
  2783. Colorf *colors = nullptr;
  2784. if (is_table_of_tables)
  2785. {
  2786. size_t datasize = (sizeof(Vector2) + sizeof(Colorf)) * numpositions;
  2787. uint8 *data = instance()->getScratchBuffer<uint8>(datasize);
  2788. positions = (Vector2 *) data;
  2789. colors = (Colorf *) (data + sizeof(Vector2) * numpositions);
  2790. }
  2791. else
  2792. positions = instance()->getScratchBuffer<Vector2>(numpositions);
  2793. if (is_table)
  2794. {
  2795. if (is_table_of_tables)
  2796. {
  2797. // points({{x1, y1 [, r, g, b, a]}, {x2, y2 [, r, g, b, a]}, ...})
  2798. for (int i = 0; i < args; i++)
  2799. {
  2800. lua_rawgeti(L, 1, i + 1);
  2801. for (int j = 1; j <= 6; j++)
  2802. lua_rawgeti(L, -j, j);
  2803. positions[i].x = luax_checkfloat(L, -6);
  2804. positions[i].y = luax_checkfloat(L, -5);
  2805. colors[i].r = (float) luax_optnumberclamped01(L, -4, 1.0);
  2806. colors[i].g = (float) luax_optnumberclamped01(L, -3, 1.0);
  2807. colors[i].b = (float) luax_optnumberclamped01(L, -2, 1.0);
  2808. colors[i].a = (float) luax_optnumberclamped01(L, -1, 1.0);
  2809. lua_pop(L, 7);
  2810. }
  2811. }
  2812. else
  2813. {
  2814. // points({x1, y1, x2, y2, ...})
  2815. for (int i = 0; i < numpositions; i++)
  2816. {
  2817. lua_rawgeti(L, 1, i * 2 + 1);
  2818. lua_rawgeti(L, 1, i * 2 + 2);
  2819. positions[i].x = luax_checkfloat(L, -2);
  2820. positions[i].y = luax_checkfloat(L, -1);
  2821. lua_pop(L, 2);
  2822. }
  2823. }
  2824. }
  2825. else
  2826. {
  2827. for (int i = 0; i < numpositions; i++)
  2828. {
  2829. positions[i].x = luax_checkfloat(L, i * 2 + 1);
  2830. positions[i].y = luax_checkfloat(L, i * 2 + 2);
  2831. }
  2832. }
  2833. luax_catchexcept(L, [&](){ instance()->points(positions, colors, numpositions); });
  2834. return 0;
  2835. }
  2836. int w_line(lua_State *L)
  2837. {
  2838. int args = lua_gettop(L);
  2839. int arg1type = lua_type(L, 1);
  2840. bool is_table = false;
  2841. if (args == 1 && arg1type == LUA_TTABLE)
  2842. {
  2843. args = (int) luax_objlen(L, 1);
  2844. is_table = true;
  2845. }
  2846. if (arg1type != LUA_TTABLE && arg1type != LUA_TNUMBER)
  2847. return luax_typerror(L, 1, "table or number");
  2848. else if (args % 2 != 0)
  2849. return luaL_error(L, "Number of vertex components must be a multiple of two.");
  2850. else if (args < 4)
  2851. return luaL_error(L, "Need at least two vertices to draw a line.");
  2852. int numvertices = args / 2;
  2853. Vector2 *coords = instance()->getScratchBuffer<Vector2>(numvertices);
  2854. if (is_table)
  2855. {
  2856. for (int i = 0; i < numvertices; ++i)
  2857. {
  2858. lua_rawgeti(L, 1, (i * 2) + 1);
  2859. lua_rawgeti(L, 1, (i * 2) + 2);
  2860. coords[i].x = luax_checkfloat(L, -2);
  2861. coords[i].y = luax_checkfloat(L, -1);
  2862. lua_pop(L, 2);
  2863. }
  2864. }
  2865. else
  2866. {
  2867. for (int i = 0; i < numvertices; ++i)
  2868. {
  2869. coords[i].x = luax_checkfloat(L, (i * 2) + 1);
  2870. coords[i].y = luax_checkfloat(L, (i * 2) + 2);
  2871. }
  2872. }
  2873. luax_catchexcept(L,
  2874. [&](){ instance()->polyline(coords, numvertices); }
  2875. );
  2876. return 0;
  2877. }
  2878. int w_rectangle(lua_State *L)
  2879. {
  2880. Graphics::DrawMode mode;
  2881. const char *str = luaL_checkstring(L, 1);
  2882. if (!Graphics::getConstant(str, mode))
  2883. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2884. float x = (float)luaL_checknumber(L, 2);
  2885. float y = (float)luaL_checknumber(L, 3);
  2886. float w = (float)luaL_checknumber(L, 4);
  2887. float h = (float)luaL_checknumber(L, 5);
  2888. if (lua_isnoneornil(L, 6))
  2889. {
  2890. luax_catchexcept(L, [&](){ instance()->rectangle(mode, x, y, w, h); });
  2891. return 0;
  2892. }
  2893. float rx = (float)luaL_optnumber(L, 6, 0.0);
  2894. float ry = (float)luaL_optnumber(L, 7, rx);
  2895. if (lua_isnoneornil(L, 8))
  2896. luax_catchexcept(L, [&](){ instance()->rectangle(mode, x, y, w, h, rx, ry); });
  2897. else
  2898. {
  2899. int points = (int) luaL_checkinteger(L, 8);
  2900. luax_catchexcept(L, [&](){ instance()->rectangle(mode, x, y, w, h, rx, ry, points); });
  2901. }
  2902. return 0;
  2903. }
  2904. int w_circle(lua_State *L)
  2905. {
  2906. Graphics::DrawMode mode;
  2907. const char *str = luaL_checkstring(L, 1);
  2908. if (!Graphics::getConstant(str, mode))
  2909. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2910. float x = (float)luaL_checknumber(L, 2);
  2911. float y = (float)luaL_checknumber(L, 3);
  2912. float radius = (float)luaL_checknumber(L, 4);
  2913. if (lua_isnoneornil(L, 5))
  2914. luax_catchexcept(L, [&](){ instance()->circle(mode, x, y, radius); });
  2915. else
  2916. {
  2917. int points = (int) luaL_checkinteger(L, 5);
  2918. luax_catchexcept(L, [&](){ instance()->circle(mode, x, y, radius, points); });
  2919. }
  2920. return 0;
  2921. }
  2922. int w_ellipse(lua_State *L)
  2923. {
  2924. Graphics::DrawMode mode;
  2925. const char *str = luaL_checkstring(L, 1);
  2926. if (!Graphics::getConstant(str, mode))
  2927. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2928. float x = (float)luaL_checknumber(L, 2);
  2929. float y = (float)luaL_checknumber(L, 3);
  2930. float a = (float)luaL_checknumber(L, 4);
  2931. float b = (float)luaL_optnumber(L, 5, a);
  2932. if (lua_isnoneornil(L, 6))
  2933. luax_catchexcept(L, [&](){ instance()->ellipse(mode, x, y, a, b); });
  2934. else
  2935. {
  2936. int points = (int) luaL_checkinteger(L, 6);
  2937. luax_catchexcept(L, [&](){ instance()->ellipse(mode, x, y, a, b, points); });
  2938. }
  2939. return 0;
  2940. }
  2941. int w_arc(lua_State *L)
  2942. {
  2943. Graphics::DrawMode drawmode;
  2944. const char *drawstr = luaL_checkstring(L, 1);
  2945. if (!Graphics::getConstant(drawstr, drawmode))
  2946. return luax_enumerror(L, "draw mode", Graphics::getConstants(drawmode), drawstr);
  2947. int startidx = 2;
  2948. Graphics::ArcMode arcmode = Graphics::ARC_PIE;
  2949. if (lua_type(L, 2) == LUA_TSTRING)
  2950. {
  2951. const char *arcstr = luaL_checkstring(L, 2);
  2952. if (!Graphics::getConstant(arcstr, arcmode))
  2953. return luax_enumerror(L, "arc mode", Graphics::getConstants(arcmode), arcstr);
  2954. startidx = 3;
  2955. }
  2956. float x = (float) luaL_checknumber(L, startidx + 0);
  2957. float y = (float) luaL_checknumber(L, startidx + 1);
  2958. float radius = (float) luaL_checknumber(L, startidx + 2);
  2959. float angle1 = (float) luaL_checknumber(L, startidx + 3);
  2960. float angle2 = (float) luaL_checknumber(L, startidx + 4);
  2961. if (lua_isnoneornil(L, startidx + 5))
  2962. luax_catchexcept(L, [&](){ instance()->arc(drawmode, arcmode, x, y, radius, angle1, angle2); });
  2963. else
  2964. {
  2965. int points = (int) luaL_checkinteger(L, startidx + 5);
  2966. luax_catchexcept(L, [&](){ instance()->arc(drawmode, arcmode, x, y, radius, angle1, angle2, points); });
  2967. }
  2968. return 0;
  2969. }
  2970. int w_polygon(lua_State *L)
  2971. {
  2972. int args = lua_gettop(L) - 1;
  2973. Graphics::DrawMode mode;
  2974. const char *str = luaL_checkstring(L, 1);
  2975. if (!Graphics::getConstant(str, mode))
  2976. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2977. bool is_table = false;
  2978. if (args == 1 && lua_istable(L, 2))
  2979. {
  2980. args = (int) luax_objlen(L, 2);
  2981. is_table = true;
  2982. }
  2983. if (args % 2 != 0)
  2984. return luaL_error(L, "Number of vertex components must be a multiple of two");
  2985. else if (args < 6)
  2986. return luaL_error(L, "Need at least three vertices to draw a polygon");
  2987. int numvertices = args / 2;
  2988. // fetch coords
  2989. Vector2 *coords = instance()->getScratchBuffer<Vector2>(numvertices + 1);
  2990. if (is_table)
  2991. {
  2992. for (int i = 0; i < numvertices; ++i)
  2993. {
  2994. lua_rawgeti(L, 2, (i * 2) + 1);
  2995. lua_rawgeti(L, 2, (i * 2) + 2);
  2996. coords[i].x = luax_checkfloat(L, -2);
  2997. coords[i].y = luax_checkfloat(L, -1);
  2998. lua_pop(L, 2);
  2999. }
  3000. }
  3001. else
  3002. {
  3003. for (int i = 0; i < numvertices; ++i)
  3004. {
  3005. coords[i].x = luax_checkfloat(L, (i * 2) + 2);
  3006. coords[i].y = luax_checkfloat(L, (i * 2) + 3);
  3007. }
  3008. }
  3009. // make a closed loop
  3010. coords[numvertices] = coords[0];
  3011. luax_catchexcept(L, [&](){ instance()->polygon(mode, coords, numvertices+1); });
  3012. return 0;
  3013. }
  3014. int w_dispatchThreadgroups(lua_State* L)
  3015. {
  3016. Shader *shader = luax_checkshader(L, 1);
  3017. int x = (int) luaL_checkinteger(L, 2);
  3018. int y = (int) luaL_optinteger(L, 3, 1);
  3019. int z = (int) luaL_optinteger(L, 4, 1);
  3020. luax_catchexcept(L, [&](){ instance()->dispatchThreadgroups(shader, x, y, z); });
  3021. return 0;
  3022. }
  3023. int w_dispatchIndirect(lua_State *L)
  3024. {
  3025. Shader *shader = luax_checkshader(L, 1);
  3026. Buffer *argsbuffer = luax_checkbuffer(L, 2);
  3027. int argsindex = (int) luaL_optinteger(L, 3, 1) - 1;
  3028. luax_catchexcept(L, [&]() { instance()->dispatchIndirect(shader, argsbuffer, argsindex); });
  3029. return 0;
  3030. }
  3031. int w_copyBuffer(lua_State *L)
  3032. {
  3033. Buffer *source = luax_checkbuffer(L, 1);
  3034. Buffer *dest = luax_checkbuffer(L, 2);
  3035. ptrdiff_t sourceoffset = luaL_optinteger(L, 3, 0);
  3036. ptrdiff_t destoffset = luaL_optinteger(L, 4, 0);
  3037. ptrdiff_t size = std::min(source->getSize() - sourceoffset, dest->getSize() - destoffset);
  3038. if (!lua_isnoneornil(L, 5))
  3039. size = luaL_checkinteger(L, 5);
  3040. if (sourceoffset < 0 || destoffset < 0)
  3041. return luaL_error(L, "copyBuffer offsets cannot be negative.");
  3042. if (size <= 0)
  3043. return luaL_error(L, "copyBuffer size must be greater than 0.");
  3044. luax_catchexcept(L, [&](){ instance()->copyBuffer(source, dest, sourceoffset, destoffset, size); });
  3045. return 0;
  3046. }
  3047. int w_copyBufferToTexture(lua_State *L)
  3048. {
  3049. Buffer *source = luax_checkbuffer(L, 1);
  3050. Texture *dest = luax_checktexture(L, 2);
  3051. ptrdiff_t sourceoffset = luaL_optinteger(L, 3, 0);
  3052. if (sourceoffset < 0)
  3053. return luaL_error(L, "copyBufferToTexture source offset cannot be negative.");
  3054. int sourcewidth = (int) luaL_optinteger(L, 4, 0);
  3055. int slice = 0;
  3056. int mipmap = 0;
  3057. if (dest->getTextureType() != TEXTURE_2D)
  3058. slice = (int) luaL_checkinteger(L, 5) - 1;
  3059. mipmap = (int) luaL_optinteger(L, 6, 1) - 1;
  3060. Rect rect = {0, 0, dest->getPixelWidth(mipmap), dest->getPixelHeight(mipmap)};
  3061. if (!lua_isnoneornil(L, 7))
  3062. {
  3063. rect.x = (int) luaL_checkinteger(L, 7);
  3064. rect.y = (int) luaL_checkinteger(L, 8);
  3065. rect.w = (int) luaL_checkinteger(L, 9);
  3066. rect.h = (int) luaL_checkinteger(L, 10);
  3067. }
  3068. luax_catchexcept(L, [&](){ instance()->copyBufferToTexture(source, dest, sourceoffset, sourcewidth, slice, mipmap, rect); });
  3069. return 0;
  3070. }
  3071. int w_copyTextureToBuffer(lua_State *L)
  3072. {
  3073. Texture *source = luax_checktexture(L, 1);
  3074. Buffer *dest = luax_checkbuffer(L, 2);
  3075. int slice = 0;
  3076. int mipmap = 0;
  3077. if (source->getTextureType() != TEXTURE_2D)
  3078. slice = (int) luaL_checkinteger(L, 3) - 1;
  3079. mipmap = (int) luaL_optinteger(L, 4, 1) - 1;
  3080. Rect rect = {0, 0, source->getPixelWidth(mipmap), source->getPixelHeight(mipmap)};
  3081. if (!lua_isnoneornil(L, 5))
  3082. {
  3083. rect.x = (int) luaL_checkinteger(L, 5);
  3084. rect.y = (int) luaL_checkinteger(L, 6);
  3085. rect.w = (int) luaL_checkinteger(L, 7);
  3086. rect.h = (int) luaL_checkinteger(L, 8);
  3087. }
  3088. ptrdiff_t destoffset = luaL_optinteger(L, 9, 0);
  3089. if (destoffset < 0)
  3090. return luaL_error(L, "copyTextureToBuffer dest offset cannot be negative.");
  3091. int destwidth = (int) luaL_optinteger(L, 10, 0);
  3092. luax_catchexcept(L, [&](){ instance()->copyTextureToBuffer(source, dest, slice, mipmap, rect, destoffset, destwidth); });
  3093. return 0;
  3094. }
  3095. int w_flushBatch(lua_State *)
  3096. {
  3097. instance()->flushBatchedDraws();
  3098. return 0;
  3099. }
  3100. int w_getStackDepth(lua_State *L)
  3101. {
  3102. lua_pushnumber(L, instance()->getStackDepth());
  3103. return 1;
  3104. }
  3105. int w_push(lua_State *L)
  3106. {
  3107. Graphics::StackType stype = Graphics::STACK_TRANSFORM;
  3108. const char *sname = lua_isnoneornil(L, 1) ? nullptr : luaL_checkstring(L, 1);
  3109. if (sname && !Graphics::getConstant(sname, stype))
  3110. return luax_enumerror(L, "graphics stack type", Graphics::getConstants(stype), sname);
  3111. luax_catchexcept(L, [&](){ instance()->push(stype); });
  3112. if (luax_istype(L, 2, math::Transform::type))
  3113. {
  3114. math::Transform *t = luax_totype<math::Transform>(L, 2);
  3115. luax_catchexcept(L, [&]() { instance()->applyTransform(t->getMatrix()); });
  3116. }
  3117. return 0;
  3118. }
  3119. int w_pop(lua_State *L)
  3120. {
  3121. luax_catchexcept(L, [&](){ instance()->pop(); });
  3122. return 0;
  3123. }
  3124. int w_rotate(lua_State *L)
  3125. {
  3126. float angle = (float)luaL_checknumber(L, 1);
  3127. instance()->rotate(angle);
  3128. return 0;
  3129. }
  3130. int w_scale(lua_State *L)
  3131. {
  3132. float sx = (float)luaL_optnumber(L, 1, 1.0f);
  3133. float sy = (float)luaL_optnumber(L, 2, sx);
  3134. instance()->scale(sx, sy);
  3135. return 0;
  3136. }
  3137. int w_translate(lua_State *L)
  3138. {
  3139. float x = (float)luaL_checknumber(L, 1);
  3140. float y = (float)luaL_checknumber(L, 2);
  3141. instance()->translate(x, y);
  3142. return 0;
  3143. }
  3144. int w_shear(lua_State *L)
  3145. {
  3146. float kx = (float)luaL_checknumber(L, 1);
  3147. float ky = (float)luaL_checknumber(L, 2);
  3148. instance()->shear(kx, ky);
  3149. return 0;
  3150. }
  3151. int w_origin(lua_State * /*L*/)
  3152. {
  3153. instance()->origin();
  3154. return 0;
  3155. }
  3156. int w_applyTransform(lua_State *L)
  3157. {
  3158. luax_checkstandardtransform(L, 1, [&](const Matrix4 &m)
  3159. {
  3160. luax_catchexcept(L, [&]() { instance()->applyTransform(m); });
  3161. });
  3162. return 0;
  3163. }
  3164. int w_replaceTransform(lua_State *L)
  3165. {
  3166. luax_checkstandardtransform(L, 1, [&](const Matrix4 &m)
  3167. {
  3168. luax_catchexcept(L, [&]() { instance()->replaceTransform(m); });
  3169. });
  3170. return 0;
  3171. }
  3172. int w_transformPoint(lua_State *L)
  3173. {
  3174. Vector2 p;
  3175. p.x = (float) luaL_checknumber(L, 1);
  3176. p.y = (float) luaL_checknumber(L, 2);
  3177. p = instance()->transformPoint(p);
  3178. lua_pushnumber(L, p.x);
  3179. lua_pushnumber(L, p.y);
  3180. return 2;
  3181. }
  3182. int w_inverseTransformPoint(lua_State *L)
  3183. {
  3184. Vector2 p;
  3185. p.x = (float) luaL_checknumber(L, 1);
  3186. p.y = (float) luaL_checknumber(L, 2);
  3187. p = instance()->inverseTransformPoint(p);
  3188. lua_pushnumber(L, p.x);
  3189. lua_pushnumber(L, p.y);
  3190. return 2;
  3191. }
  3192. int w_setProjection(lua_State *L)
  3193. {
  3194. math::Transform *transform = luax_totype<math::Transform>(L, 1);
  3195. if (transform != nullptr)
  3196. {
  3197. instance()->setProjection(transform->getMatrix());
  3198. return 0;
  3199. }
  3200. math::Transform::MatrixLayout layout = math::Transform::MATRIX_ROW_MAJOR;
  3201. int idx = 1;
  3202. if (lua_type(L, idx) == LUA_TSTRING)
  3203. {
  3204. const char* layoutstr = lua_tostring(L, idx);
  3205. if (!math::Transform::getConstant(layoutstr, layout))
  3206. return luax_enumerror(L, "matrix layout", math::Transform::getConstants(layout), layoutstr);
  3207. idx++;
  3208. }
  3209. float elements[16];
  3210. love::math::luax_checkmatrix(L, idx, layout, elements);
  3211. instance()->setProjection(Matrix4(elements));
  3212. return 0;
  3213. }
  3214. int w_resetProjection(lua_State */*L*/)
  3215. {
  3216. instance()->resetProjection();
  3217. return 0;
  3218. }
  3219. // List of functions to wrap.
  3220. static const luaL_Reg functions[] =
  3221. {
  3222. { "reset", w_reset },
  3223. { "clear", w_clear },
  3224. { "discard", w_discard },
  3225. { "present", w_present },
  3226. { "newCanvas", w_newCanvas },
  3227. { "newTexture", w_newTexture },
  3228. { "newCubeTexture", w_newCubeTexture },
  3229. { "newArrayTexture", w_newArrayTexture },
  3230. { "newVolumeTexture", w_newVolumeTexture },
  3231. { "newTextureView", w_newTextureView },
  3232. { "newQuad", w_newQuad },
  3233. { "newFont", w_newFont },
  3234. { "newImageFont", w_newImageFont },
  3235. { "newSpriteBatch", w_newSpriteBatch },
  3236. { "newParticleSystem", w_newParticleSystem },
  3237. { "newShader", w_newShader },
  3238. { "newComputeShader", w_newComputeShader },
  3239. { "newBuffer", w_newBuffer },
  3240. { "newMesh", w_newMesh },
  3241. { "newTextBatch", w_newTextBatch },
  3242. { "_newVideo", w_newVideo },
  3243. { "readbackBuffer", w_readbackBuffer },
  3244. { "readbackBufferAsync", w_readbackBufferAsync },
  3245. { "readbackTexture", w_readbackTexture },
  3246. { "readbackTextureAsync", w_readbackTextureAsync },
  3247. { "validateShader", w_validateShader },
  3248. { "setCanvas", w_setCanvas },
  3249. { "getCanvas", w_getCanvas },
  3250. { "setColor", w_setColor },
  3251. { "getColor", w_getColor },
  3252. { "setBackgroundColor", w_setBackgroundColor },
  3253. { "getBackgroundColor", w_getBackgroundColor },
  3254. { "setNewFont", w_setNewFont },
  3255. { "setFont", w_setFont },
  3256. { "getFont", w_getFont },
  3257. { "setColorMask", w_setColorMask },
  3258. { "getColorMask", w_getColorMask },
  3259. { "setBlendMode", w_setBlendMode },
  3260. { "getBlendMode", w_getBlendMode },
  3261. { "setBlendState", w_setBlendState },
  3262. { "getBlendState", w_getBlendState },
  3263. { "setDefaultFilter", w_setDefaultFilter },
  3264. { "getDefaultFilter", w_getDefaultFilter },
  3265. { "setDefaultMipmapFilter", w_setDefaultMipmapFilter },
  3266. { "getDefaultMipmapFilter", w_getDefaultMipmapFilter },
  3267. { "setLineWidth", w_setLineWidth },
  3268. { "setLineStyle", w_setLineStyle },
  3269. { "setLineJoin", w_setLineJoin },
  3270. { "getLineWidth", w_getLineWidth },
  3271. { "getLineStyle", w_getLineStyle },
  3272. { "getLineJoin", w_getLineJoin },
  3273. { "setPointSize", w_setPointSize },
  3274. { "getPointSize", w_getPointSize },
  3275. { "setDepthMode", w_setDepthMode },
  3276. { "getDepthMode", w_getDepthMode },
  3277. { "setMeshCullMode", w_setMeshCullMode },
  3278. { "getMeshCullMode", w_getMeshCullMode },
  3279. { "setFrontFaceWinding", w_setFrontFaceWinding },
  3280. { "getFrontFaceWinding", w_getFrontFaceWinding },
  3281. { "setWireframe", w_setWireframe },
  3282. { "isWireframe", w_isWireframe },
  3283. { "setShader", w_setShader },
  3284. { "getShader", w_getShader },
  3285. { "getSupported", w_getSupported },
  3286. { "getTextureFormats", w_getTextureFormats },
  3287. { "getRendererInfo", w_getRendererInfo },
  3288. { "getSystemLimits", w_getSystemLimits },
  3289. { "getTextureTypes", w_getTextureTypes },
  3290. { "getStats", w_getStats },
  3291. { "captureScreenshot", w_captureScreenshot },
  3292. { "draw", w_draw },
  3293. { "drawLayer", w_drawLayer },
  3294. { "drawInstanced", w_drawInstanced },
  3295. { "drawIndirect", w_drawIndirect },
  3296. { "drawFromShader", w_drawFromShader },
  3297. { "drawFromShaderIndirect", w_drawFromShaderIndirect },
  3298. { "print", w_print },
  3299. { "printf", w_printf },
  3300. { "dispatchThreadgroups", w_dispatchThreadgroups },
  3301. { "dispatchIndirect", w_dispatchIndirect },
  3302. { "copyBuffer", w_copyBuffer },
  3303. { "copyBufferToTexture", w_copyBufferToTexture },
  3304. { "copyTextureToBuffer", w_copyTextureToBuffer },
  3305. { "isCreated", w_isCreated },
  3306. { "isActive", w_isActive },
  3307. { "isGammaCorrect", w_isGammaCorrect },
  3308. { "getWidth", w_getWidth },
  3309. { "getHeight", w_getHeight },
  3310. { "getDimensions", w_getDimensions },
  3311. { "getPixelWidth", w_getPixelWidth },
  3312. { "getPixelHeight", w_getPixelHeight },
  3313. { "getPixelDimensions", w_getPixelDimensions },
  3314. { "getDPIScale", w_getDPIScale },
  3315. { "getQuadIndexBuffer", w_getQuadIndexBuffer },
  3316. { "setScissor", w_setScissor },
  3317. { "intersectScissor", w_intersectScissor },
  3318. { "getScissor", w_getScissor },
  3319. { "setStencilMode", w_setStencilMode },
  3320. { "getStencilMode", w_getStencilMode },
  3321. { "setStencilState", w_setStencilState },
  3322. { "getStencilState", w_getStencilState },
  3323. { "points", w_points },
  3324. { "line", w_line },
  3325. { "rectangle", w_rectangle },
  3326. { "circle", w_circle },
  3327. { "ellipse", w_ellipse },
  3328. { "arc", w_arc },
  3329. { "polygon", w_polygon },
  3330. { "flushBatch", w_flushBatch },
  3331. { "getStackDepth", w_getStackDepth },
  3332. { "push", w_push },
  3333. { "pop", w_pop },
  3334. { "rotate", w_rotate },
  3335. { "scale", w_scale },
  3336. { "translate", w_translate },
  3337. { "shear", w_shear },
  3338. { "origin", w_origin },
  3339. { "applyTransform", w_applyTransform },
  3340. { "replaceTransform", w_replaceTransform },
  3341. { "transformPoint", w_transformPoint },
  3342. { "inverseTransformPoint", w_inverseTransformPoint },
  3343. { "setProjection", w_setProjection },
  3344. { "resetProjection", w_resetProjection },
  3345. // Deprecated
  3346. { "newImage", w_newImage },
  3347. { "newArrayImage", w_newArrayImage },
  3348. { "newVolumeImage", w_newVolumeImage },
  3349. { "newCubeImage", w_newCubeImage },
  3350. { "newText", w_newText },
  3351. { "getCanvasFormats", w_getCanvasFormats },
  3352. { "getImageFormats", w_getImageFormats },
  3353. { 0, 0 }
  3354. };
  3355. static int luaopen_drawable(lua_State *L)
  3356. {
  3357. return luax_register_type(L, &Drawable::type, nullptr);
  3358. }
  3359. // Types for this module.
  3360. static const lua_CFunction types[] =
  3361. {
  3362. luaopen_drawable,
  3363. luaopen_texture,
  3364. luaopen_font,
  3365. luaopen_quad,
  3366. luaopen_graphicsbuffer,
  3367. luaopen_graphicsreadback,
  3368. luaopen_spritebatch,
  3369. luaopen_particlesystem,
  3370. luaopen_shader,
  3371. luaopen_mesh,
  3372. luaopen_textbatch,
  3373. luaopen_video,
  3374. 0
  3375. };
  3376. extern "C" int luaopen_love_graphics(lua_State *L)
  3377. {
  3378. Graphics *instance = Graphics::createInstance();
  3379. if (instance == nullptr)
  3380. {
  3381. printf("Cannot create graphics: no supported renderer on this system.\n");
  3382. return luaL_error(L, "Cannot create graphics: no supported renderer on this system.");
  3383. }
  3384. WrappedModule w;
  3385. w.module = instance;
  3386. w.name = "graphics";
  3387. w.type = &Graphics::type;
  3388. w.functions = functions;
  3389. w.types = types;
  3390. int n = luax_register_module(L, w);
  3391. if (luaL_loadbuffer(L, (const char *)graphics_lua, sizeof(graphics_lua), "=[love \"wrap_Graphics.lua\"]") == 0)
  3392. lua_call(L, 0, 0);
  3393. else
  3394. lua_error(L);
  3395. return n;
  3396. }
  3397. } // graphics
  3398. } // love