wrap_Graphics.cpp 86 KB

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