wrap_Graphics.cpp 75 KB

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