Graphics.cpp 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102
  1. /**
  2. * Copyright (c) 2006-2023 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "common/Exception.h"
  21. #include "common/pixelformat.h"
  22. #include "common/version.h"
  23. #include "window/Window.h"
  24. #include "Buffer.h"
  25. #include "Graphics.h"
  26. #include "GraphicsReadback.h"
  27. #include "Shader.h"
  28. #include "Vulkan.h"
  29. #include <SDL_vulkan.h>
  30. #include <algorithm>
  31. #include <vector>
  32. #include <cstring>
  33. #include <set>
  34. #include <sstream>
  35. #include <array>
  36. #define VOLK_IMPLEMENTATION
  37. #include "libraries/volk/volk.h"
  38. #define VMA_IMPLEMENTATION
  39. #include "libraries/vma/vk_mem_alloc.h"
  40. namespace love
  41. {
  42. namespace graphics
  43. {
  44. namespace vulkan
  45. {
  46. static const std::vector<const char*> validationLayers = {
  47. "VK_LAYER_KHRONOS_validation"
  48. };
  49. static const std::vector<const char*> deviceExtensions = {
  50. VK_KHR_SWAPCHAIN_EXTENSION_NAME,
  51. };
  52. constexpr uint32_t USAGES_POLL_INTERVAL = 5000;
  53. const char *Graphics::getName() const
  54. {
  55. return "love.graphics.vulkan";
  56. }
  57. const VkDevice Graphics::getDevice() const
  58. {
  59. return device;
  60. }
  61. const VmaAllocator Graphics::getVmaAllocator() const
  62. {
  63. return vmaAllocator;
  64. }
  65. Graphics::Graphics()
  66. {
  67. if (SDL_Vulkan_LoadLibrary(nullptr))
  68. throw love::Exception("could not find vulkan");
  69. volkInitializeCustom((PFN_vkGetInstanceProcAddr)SDL_Vulkan_GetVkGetInstanceProcAddr());
  70. }
  71. Graphics::~Graphics()
  72. {
  73. defaultConstantColor.set(nullptr);
  74. defaultTexture.set(nullptr);
  75. SDL_Vulkan_UnloadLibrary();
  76. }
  77. // START OVERRIDEN FUNCTIONS
  78. love::graphics::Texture *Graphics::newTexture(const love::graphics::Texture::Settings &settings, const love::graphics::Texture::Slices *data)
  79. {
  80. return new Texture(this, settings, data);
  81. }
  82. love::graphics::Buffer *Graphics::newBuffer(const love::graphics::Buffer::Settings &settings, const std::vector<love::graphics::Buffer::DataDeclaration> &format, const void *data, size_t size, size_t arraylength)
  83. {
  84. return new Buffer(this, settings, format, data, size, arraylength);
  85. }
  86. void Graphics::clear(OptionalColorD color, OptionalInt stencil, OptionalDouble depth)
  87. {
  88. if (!color.hasValue && !stencil.hasValue && !depth.hasValue)
  89. return;
  90. flushBatchedDraws();
  91. if (renderPassState.active)
  92. {
  93. VkClearAttachment attachment{};
  94. if (color.hasValue)
  95. {
  96. Colorf cf((float)color.value.r, (float)color.value.g, (float)color.value.b, (float)color.value.a);
  97. gammaCorrectColor(cf);
  98. attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  99. attachment.clearValue.color.float32[0] = static_cast<float>(cf.r);
  100. attachment.clearValue.color.float32[1] = static_cast<float>(cf.g);
  101. attachment.clearValue.color.float32[2] = static_cast<float>(cf.b);
  102. attachment.clearValue.color.float32[3] = static_cast<float>(cf.a);
  103. }
  104. VkClearAttachment depthStencilAttachment{};
  105. if (stencil.hasValue)
  106. {
  107. depthStencilAttachment.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
  108. depthStencilAttachment.clearValue.depthStencil.stencil = static_cast<uint32_t>(stencil.value);
  109. }
  110. if (depth.hasValue)
  111. {
  112. depthStencilAttachment.aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
  113. depthStencilAttachment.clearValue.depthStencil.depth = static_cast<float>(depth.value);
  114. }
  115. std::array<VkClearAttachment, 2> attachments = {
  116. attachment,
  117. depthStencilAttachment
  118. };
  119. VkClearRect rect{};
  120. rect.layerCount = 1;
  121. rect.rect.extent.width = static_cast<uint32_t>(renderPassState.width);
  122. rect.rect.extent.height = static_cast<uint32_t>(renderPassState.height);
  123. vkCmdClearAttachments(
  124. commandBuffers[currentFrame],
  125. static_cast<uint32_t>(attachments.size()), attachments.data(),
  126. 1, &rect);
  127. }
  128. else
  129. {
  130. if (color.hasValue)
  131. {
  132. renderPassState.renderPassConfiguration.colorAttachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  133. Colorf cf((float)color.value.r, (float)color.value.g, (float)color.value.b, (float)color.value.a);
  134. gammaCorrectColor(cf);
  135. renderPassState.clearColors[0].color.float32[0] = static_cast<float>(cf.r);
  136. renderPassState.clearColors[0].color.float32[1] = static_cast<float>(cf.g);
  137. renderPassState.clearColors[0].color.float32[2] = static_cast<float>(cf.b);
  138. renderPassState.clearColors[0].color.float32[3] = static_cast<float>(cf.a);
  139. }
  140. if (depth.hasValue)
  141. {
  142. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.depthLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  143. renderPassState.clearColors[1].depthStencil.depth = static_cast<float>(depth.value);
  144. }
  145. if (stencil.hasValue)
  146. {
  147. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  148. renderPassState.clearColors[1].depthStencil.stencil = static_cast<uint32_t>(stencil.value);
  149. }
  150. if (renderPassState.isWindow)
  151. {
  152. renderPassState.windowClearRequested = true;
  153. renderPassState.mainWindowClearColorValue = color;
  154. renderPassState.mainWindowClearDepthValue = depth;
  155. renderPassState.mainWindowClearStencilValue = stencil;
  156. }
  157. else
  158. startRenderPass();
  159. }
  160. }
  161. void Graphics::clear(const std::vector<OptionalColorD> &colors, OptionalInt stencil, OptionalDouble depth)
  162. {
  163. if (colors.empty() && !stencil.hasValue && !depth.hasValue)
  164. return;
  165. flushBatchedDraws();
  166. if (renderPassState.active)
  167. {
  168. std::vector<VkClearAttachment> attachments;
  169. for (const auto &color : colors)
  170. {
  171. VkClearAttachment attachment{};
  172. if (color.hasValue)
  173. {
  174. Colorf cf((float)color.value.r, (float)color.value.g, (float)color.value.b, (float)color.value.a);
  175. gammaCorrectColor(cf);
  176. attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  177. attachment.clearValue.color.float32[0] = static_cast<float>(cf.r);
  178. attachment.clearValue.color.float32[1] = static_cast<float>(cf.g);
  179. attachment.clearValue.color.float32[2] = static_cast<float>(cf.b);
  180. attachment.clearValue.color.float32[3] = static_cast<float>(cf.a);
  181. }
  182. attachments.push_back(attachment);
  183. }
  184. VkClearAttachment depthStencilAttachment{};
  185. if (stencil.hasValue)
  186. {
  187. depthStencilAttachment.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  188. depthStencilAttachment.clearValue.depthStencil.stencil = static_cast<uint32_t>(stencil.value);
  189. }
  190. if (depth.hasValue)
  191. {
  192. depthStencilAttachment.aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
  193. depthStencilAttachment.clearValue.depthStencil.depth = static_cast<float>(depth.value);
  194. }
  195. attachments.push_back(depthStencilAttachment);
  196. VkClearRect rect{};
  197. rect.layerCount = 1;
  198. rect.rect.extent.width = static_cast<uint32_t>(renderPassState.width);
  199. rect.rect.extent.height = static_cast<uint32_t>(renderPassState.height);
  200. vkCmdClearAttachments(
  201. commandBuffers[currentFrame],
  202. static_cast<uint32_t>(attachments.size()), attachments.data(),
  203. 1, &rect);
  204. }
  205. else
  206. {
  207. for (size_t i = 0; i < colors.size(); i++)
  208. {
  209. if (colors[i].hasValue)
  210. {
  211. renderPassState.renderPassConfiguration.colorAttachments[i].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  212. auto &color = colors[i];
  213. Colorf cf((float)color.value.r, (float)color.value.g, (float)color.value.b, (float)color.value.a);
  214. gammaCorrectColor(cf);
  215. renderPassState.clearColors[i].color.float32[0] = static_cast<float>(cf.r);
  216. renderPassState.clearColors[i].color.float32[1] = static_cast<float>(cf.g);
  217. renderPassState.clearColors[i].color.float32[2] = static_cast<float>(cf.b);
  218. renderPassState.clearColors[i].color.float32[3] = static_cast<float>(cf.a);
  219. }
  220. }
  221. if (depth.hasValue)
  222. {
  223. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.depthLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  224. renderPassState.clearColors[colors.size()].depthStencil.depth = static_cast<float>(depth.value);
  225. }
  226. if (stencil.hasValue)
  227. {
  228. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  229. renderPassState.clearColors[colors.size()].depthStencil.stencil = static_cast<uint32_t>(stencil.value);
  230. }
  231. startRenderPass();
  232. }
  233. }
  234. void Graphics::discard(const std::vector<bool> &colorbuffers, bool depthstencil)
  235. {
  236. if (renderPassState.active)
  237. endRenderPass();
  238. auto &renderPassConfiguration = renderPassState.renderPassConfiguration;
  239. for (size_t i = 0; i < colorbuffers.size(); i++)
  240. {
  241. if (colorbuffers[i])
  242. renderPassConfiguration.colorAttachments[i].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  243. }
  244. if (depthstencil)
  245. {
  246. renderPassConfiguration.staticData.depthStencilAttachment.depthLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  247. renderPassConfiguration.staticData.depthStencilAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  248. }
  249. startRenderPass();
  250. }
  251. void Graphics::submitGpuCommands(bool present, void *screenshotCallbackData)
  252. {
  253. flushBatchedDraws();
  254. if (renderPassState.active)
  255. endRenderPass();
  256. if (present)
  257. {
  258. if (pendingScreenshotCallbacks.empty())
  259. Vulkan::cmdTransitionImageLayout(
  260. commandBuffers.at(currentFrame),
  261. swapChainImages.at(imageIndex),
  262. VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  263. VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
  264. else
  265. {
  266. Vulkan::cmdTransitionImageLayout(
  267. commandBuffers.at(currentFrame),
  268. swapChainImages.at(imageIndex),
  269. VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  270. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
  271. Vulkan::cmdTransitionImageLayout(
  272. commandBuffers.at(currentFrame),
  273. screenshotReadbackBuffers.at(currentFrame).image,
  274. VK_IMAGE_LAYOUT_UNDEFINED,
  275. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
  276. VkImageBlit blit{};
  277. blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  278. blit.srcSubresource.layerCount = 1;
  279. blit.srcOffsets[1] = {
  280. static_cast<int>(swapChainExtent.width),
  281. static_cast<int>(swapChainExtent.height),
  282. 1
  283. };
  284. blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  285. blit.dstSubresource.layerCount = 1;
  286. blit.dstOffsets[1] = {
  287. static_cast<int>(swapChainExtent.width),
  288. static_cast<int>(swapChainExtent.height),
  289. 1
  290. };
  291. vkCmdBlitImage(
  292. commandBuffers.at(currentFrame),
  293. swapChainImages.at(imageIndex), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  294. screenshotReadbackBuffers.at(currentFrame).image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  295. 1, &blit,
  296. VK_FILTER_NEAREST);
  297. Vulkan::cmdTransitionImageLayout(
  298. commandBuffers.at(currentFrame),
  299. swapChainImages.at(imageIndex),
  300. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  301. VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
  302. Vulkan::cmdTransitionImageLayout(
  303. commandBuffers.at(currentFrame),
  304. screenshotReadbackBuffers.at(currentFrame).image,
  305. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  306. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
  307. VkBufferImageCopy region{};
  308. region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  309. region.imageSubresource.layerCount = 1;
  310. region.imageExtent = {
  311. swapChainExtent.width,
  312. swapChainExtent.height,
  313. 1
  314. };
  315. vkCmdCopyImageToBuffer(
  316. commandBuffers.at(currentFrame),
  317. screenshotReadbackBuffers.at(currentFrame).image,
  318. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  319. screenshotReadbackBuffers.at(currentFrame).buffer,
  320. 1, &region);
  321. addReadbackCallback([
  322. w = swapChainExtent.width,
  323. h = swapChainExtent.height,
  324. pendingScreenshotCallbacks = pendingScreenshotCallbacks,
  325. screenShotReadbackBuffer = screenshotReadbackBuffers.at(currentFrame),
  326. screenshotCallbackData = screenshotCallbackData]() {
  327. auto imageModule = Module::getInstance<love::image::Image>(M_IMAGE);
  328. for (const auto &info : pendingScreenshotCallbacks)
  329. {
  330. image::ImageData *img = imageModule->newImageData(
  331. w,
  332. h,
  333. PIXELFORMAT_RGBA8_UNORM,
  334. screenShotReadbackBuffer.allocationInfo.pMappedData);
  335. info.callback(&info, img, screenshotCallbackData);
  336. img->release();
  337. }
  338. });
  339. pendingScreenshotCallbacks.clear();
  340. }
  341. }
  342. endRecordingGraphicsCommands();
  343. if (imagesInFlight[imageIndex] != VK_NULL_HANDLE)
  344. vkWaitForFences(device, 1, &imagesInFlight.at(imageIndex), VK_TRUE, UINT64_MAX);
  345. imagesInFlight[imageIndex] = inFlightFences[currentFrame];
  346. std::array<VkCommandBuffer, 1> submitCommandbuffers = { commandBuffers.at(currentFrame) };
  347. VkSubmitInfo submitInfo{};
  348. submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  349. VkSemaphore waitSemaphores[] = { imageAvailableSemaphores.at(currentFrame) };
  350. VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT };
  351. if (imageRequested)
  352. {
  353. submitInfo.waitSemaphoreCount = 1;
  354. submitInfo.pWaitSemaphores = waitSemaphores;
  355. submitInfo.pWaitDstStageMask = waitStages;
  356. imageRequested = false;
  357. }
  358. submitInfo.commandBufferCount = static_cast<uint32_t>(submitCommandbuffers.size());
  359. submitInfo.pCommandBuffers = submitCommandbuffers.data();
  360. VkSemaphore signalSemaphores[] = { renderFinishedSemaphores.at(currentFrame) };
  361. VkFence fence = VK_NULL_HANDLE;
  362. if (present)
  363. {
  364. submitInfo.signalSemaphoreCount = 1;
  365. submitInfo.pSignalSemaphores = signalSemaphores;
  366. vkResetFences(device, 1, &inFlightFences[currentFrame]);
  367. fence = inFlightFences[currentFrame];
  368. }
  369. if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, fence) != VK_SUCCESS)
  370. throw love::Exception("failed to submit draw command buffer");
  371. if (!present)
  372. {
  373. vkQueueWaitIdle(graphicsQueue);
  374. for (auto &callbacks : readbackCallbacks)
  375. {
  376. for (const auto &callback : callbacks)
  377. callback();
  378. callbacks.clear();
  379. }
  380. startRecordingGraphicsCommands();
  381. }
  382. }
  383. void Graphics::present(void *screenshotCallbackdata)
  384. {
  385. if (!isActive())
  386. return;
  387. if (isRenderTargetActive())
  388. throw love::Exception("present cannot be called while a render target is active.");
  389. if (!renderPassState.active && renderPassState.windowClearRequested)
  390. startRenderPass();
  391. deprecations.draw(this);
  392. submitGpuCommands(true, screenshotCallbackdata);
  393. VkPresentInfoKHR presentInfo{};
  394. presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
  395. presentInfo.waitSemaphoreCount = 1;
  396. presentInfo.pWaitSemaphores = &renderFinishedSemaphores.at(currentFrame);
  397. presentInfo.swapchainCount = 1;
  398. presentInfo.pSwapchains = &swapChain;
  399. presentInfo.pImageIndices = &imageIndex;
  400. VkResult result = vkQueuePresentKHR(presentQueue, &presentInfo);
  401. if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || swapChainRecreationRequested)
  402. {
  403. swapChainRecreationRequested = false;
  404. recreateSwapChain();
  405. }
  406. else if (result != VK_SUCCESS)
  407. throw love::Exception("failed to present swap chain image");
  408. for (love::graphics::StreamBuffer *buffer : batchedDrawState.vb)
  409. buffer->nextFrame();
  410. batchedDrawState.indexBuffer->nextFrame();
  411. drawCalls = 0;
  412. renderTargetSwitchCount = 0;
  413. drawCallsBatched = 0;
  414. updatePendingReadbacks();
  415. updateTemporaryResources();
  416. frameCounter++;
  417. currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
  418. beginFrame();
  419. }
  420. void Graphics::setViewportSize(int width, int height, int pixelwidth, int pixelheight)
  421. {
  422. if (swapChain != VK_NULL_HANDLE && (pixelwidth != this->pixelWidth || pixelheight != this->pixelHeight || width != this->width || height != this->height))
  423. requestSwapchainRecreation();
  424. this->width = width;
  425. this->height = height;
  426. this->pixelWidth = pixelwidth;
  427. this->pixelHeight = pixelheight;
  428. if (!isRenderTargetActive())
  429. resetProjection();
  430. }
  431. bool Graphics::setMode(void *context, int width, int height, int pixelwidth, int pixelheight, bool windowhasstencil, int msaa)
  432. {
  433. requestedMsaa = msaa;
  434. windowHasStencil = windowhasstencil;
  435. // Must be called before the swapchain is created.
  436. setViewportSize(width, height, pixelwidth, pixelheight);
  437. cleanUpFunctions.clear();
  438. cleanUpFunctions.resize(MAX_FRAMES_IN_FLIGHT);
  439. readbackCallbacks.clear();
  440. readbackCallbacks.resize(MAX_FRAMES_IN_FLIGHT);
  441. createVulkanInstance();
  442. createSurface();
  443. pickPhysicalDevice();
  444. createLogicalDevice();
  445. createPipelineCache();
  446. initVMA();
  447. initCapabilities();
  448. createSwapChain();
  449. createImageViews();
  450. createScreenshotCallbackBuffers();
  451. createSyncObjects();
  452. createColorResources();
  453. createDepthResources();
  454. transitionColorDepthLayouts = true;
  455. createCommandPool();
  456. createCommandBuffers();
  457. beginFrame();
  458. uint8 whiteColor[] = { 255, 255, 255, 255 };
  459. if (batchedDrawState.vb[0] == nullptr)
  460. {
  461. // Initial sizes that should be good enough for most cases. It will
  462. // resize to fit if needed, later.
  463. batchedDrawState.vb[0] = new StreamBuffer(this, BUFFERUSAGE_VERTEX, 1024 * 1024 * 1);
  464. batchedDrawState.vb[1] = new StreamBuffer(this, BUFFERUSAGE_VERTEX, 256 * 1024 * 1);
  465. batchedDrawState.indexBuffer = new StreamBuffer(this, BUFFERUSAGE_INDEX, sizeof(uint16) * LOVE_UINT16_MAX);
  466. }
  467. // sometimes the VertexColor is not set, so we manually adjust it to white color
  468. if (defaultConstantColor == nullptr)
  469. {
  470. Buffer::DataDeclaration format("ConstantColor", DATAFORMAT_UNORM8_VEC4);
  471. Buffer::Settings settings(BUFFERUSAGEFLAG_VERTEX, BUFFERDATAUSAGE_STATIC);
  472. defaultConstantColor = newBuffer(settings, { format }, whiteColor, sizeof(whiteColor), 1);
  473. }
  474. createDefaultTexture();
  475. createDefaultShaders();
  476. Shader::current = Shader::standardShaders[Shader::StandardShader::STANDARD_DEFAULT];
  477. createQuadIndexBuffer();
  478. createFanIndexBuffer();
  479. restoreState(states.back());
  480. Vulkan::resetShaderSwitches();
  481. frameCounter = 0;
  482. currentFrame = 0;
  483. created = true;
  484. drawCalls = 0;
  485. drawCallsBatched = 0;
  486. return true;
  487. }
  488. void Graphics::initCapabilities()
  489. {
  490. capabilities.features[FEATURE_MULTI_RENDER_TARGET_FORMATS] = true;
  491. capabilities.features[FEATURE_CLAMP_ZERO] = true;
  492. capabilities.features[FEATURE_CLAMP_ONE] = true;
  493. capabilities.features[FEATURE_BLEND_MINMAX] = true;
  494. capabilities.features[FEATURE_LIGHTEN] = true;
  495. capabilities.features[FEATURE_FULL_NPOT] = true;
  496. capabilities.features[FEATURE_PIXEL_SHADER_HIGHP] = true;
  497. capabilities.features[FEATURE_SHADER_DERIVATIVES] = true;
  498. capabilities.features[FEATURE_GLSL3] = true;
  499. capabilities.features[FEATURE_GLSL4] = true;
  500. capabilities.features[FEATURE_INSTANCING] = true;
  501. capabilities.features[FEATURE_TEXEL_BUFFER] = true;
  502. capabilities.features[FEATURE_INDEX_BUFFER_32BIT] = true;
  503. capabilities.features[FEATURE_COPY_BUFFER] = true;
  504. capabilities.features[FEATURE_COPY_BUFFER_TO_TEXTURE] = true;
  505. capabilities.features[FEATURE_COPY_TEXTURE_TO_BUFFER] = true;
  506. capabilities.features[FEATURE_COPY_RENDER_TARGET_TO_BUFFER] = true;
  507. capabilities.features[FEATURE_MIPMAP_RANGE] = true;
  508. capabilities.features[FEATURE_INDIRECT_DRAW] = true;
  509. static_assert(FEATURE_MAX_ENUM == 19, "Graphics::initCapabilities must be updated when adding a new graphics feature!");
  510. VkPhysicalDeviceProperties properties;
  511. vkGetPhysicalDeviceProperties(physicalDevice, &properties);
  512. capabilities.limits[LIMIT_POINT_SIZE] = properties.limits.pointSizeRange[1];
  513. capabilities.limits[LIMIT_TEXTURE_SIZE] = properties.limits.maxImageDimension2D;
  514. capabilities.limits[LIMIT_TEXTURE_LAYERS] = properties.limits.maxImageArrayLayers;
  515. capabilities.limits[LIMIT_VOLUME_TEXTURE_SIZE] = properties.limits.maxImageDimension3D;
  516. capabilities.limits[LIMIT_CUBE_TEXTURE_SIZE] = properties.limits.maxImageDimensionCube;
  517. capabilities.limits[LIMIT_TEXEL_BUFFER_SIZE] = properties.limits.maxTexelBufferElements;
  518. capabilities.limits[LIMIT_SHADER_STORAGE_BUFFER_SIZE] = properties.limits.maxStorageBufferRange;
  519. capabilities.limits[LIMIT_THREADGROUPS_X] = properties.limits.maxComputeWorkGroupCount[0];
  520. capabilities.limits[LIMIT_THREADGROUPS_Y] = properties.limits.maxComputeWorkGroupCount[1];
  521. capabilities.limits[LIMIT_THREADGROUPS_Z] = properties.limits.maxComputeWorkGroupCount[2];
  522. capabilities.limits[LIMIT_RENDER_TARGETS] = properties.limits.maxColorAttachments;
  523. capabilities.limits[LIMIT_TEXTURE_MSAA] = static_cast<double>(getMsaaCount(64));
  524. capabilities.limits[LIMIT_ANISOTROPY] = properties.limits.maxSamplerAnisotropy;
  525. static_assert(LIMIT_MAX_ENUM == 13, "Graphics::initCapabilities must be updated when adding a new system limit!");
  526. capabilities.textureTypes[TEXTURE_2D] = true;
  527. capabilities.textureTypes[TEXTURE_2D_ARRAY] = true;
  528. capabilities.textureTypes[TEXTURE_VOLUME] = true;
  529. capabilities.textureTypes[TEXTURE_CUBE] = true;
  530. }
  531. void Graphics::getAPIStats(int &shaderswitches) const
  532. {
  533. shaderswitches = static_cast<int>(Vulkan::getNumShaderSwitches());
  534. }
  535. void Graphics::unSetMode()
  536. {
  537. renderPassUsages.clear();
  538. framebufferUsages.clear();
  539. pipelineUsages.clear();
  540. created = false;
  541. vkDeviceWaitIdle(device);
  542. Volatile::unloadAll();
  543. cleanup();
  544. }
  545. void Graphics::setActive(bool enable)
  546. {
  547. flushBatchedDraws();
  548. active = enable;
  549. }
  550. int Graphics::getRequestedBackbufferMSAA() const
  551. {
  552. return requestedMsaa;
  553. }
  554. int Graphics::getBackbufferMSAA() const
  555. {
  556. return static_cast<int>(msaaSamples);
  557. }
  558. void Graphics::setFrontFaceWinding(Winding winding)
  559. {
  560. const auto& currentState = states.back();
  561. if (currentState.winding == winding)
  562. return;
  563. flushBatchedDraws();
  564. states.back().winding = winding;
  565. if (optionalDeviceExtensions.extendedDynamicState)
  566. vkCmdSetFrontFaceEXT(
  567. commandBuffers.at(currentFrame),
  568. Vulkan::getFrontFace(winding));
  569. }
  570. void Graphics::setColorMask(ColorChannelMask mask)
  571. {
  572. flushBatchedDraws();
  573. states.back().colorMask = mask;
  574. }
  575. void Graphics::setBlendState(const BlendState &blend)
  576. {
  577. flushBatchedDraws();
  578. states.back().blend = blend;
  579. }
  580. void Graphics::setPointSize(float size)
  581. {
  582. if (size != states.back().pointSize)
  583. flushBatchedDraws();
  584. states.back().pointSize = size;
  585. }
  586. bool Graphics::usesGLSLES() const
  587. {
  588. return false;
  589. }
  590. Graphics::RendererInfo Graphics::getRendererInfo() const
  591. {
  592. VkPhysicalDeviceProperties deviceProperties;
  593. vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
  594. Graphics::RendererInfo info;
  595. info.name = "Vulkan";
  596. info.device = deviceProperties.deviceName;
  597. info.vendor = Vulkan::getVendorName(deviceProperties.vendorID);
  598. info.version = Vulkan::getVulkanApiVersion(deviceProperties.apiVersion);
  599. return info;
  600. }
  601. void Graphics::draw(const DrawCommand &cmd)
  602. {
  603. prepareDraw(*cmd.attributes, *cmd.buffers, cmd.texture, cmd.primitiveType, cmd.cullMode);
  604. if (cmd.indirectBuffer != nullptr)
  605. {
  606. vkCmdDrawIndirect(
  607. commandBuffers.at(currentFrame),
  608. (VkBuffer) cmd.indirectBuffer->getHandle(),
  609. cmd.indirectBufferOffset,
  610. 1,
  611. 0);
  612. }
  613. else
  614. {
  615. vkCmdDraw(
  616. commandBuffers.at(currentFrame),
  617. (uint32) cmd.vertexCount,
  618. (uint32) cmd.instanceCount,
  619. (uint32) cmd.vertexStart,
  620. 0);
  621. }
  622. drawCalls++;
  623. }
  624. void Graphics::draw(const DrawIndexedCommand &cmd)
  625. {
  626. prepareDraw(*cmd.attributes, *cmd.buffers, cmd.texture, cmd.primitiveType, cmd.cullMode);
  627. vkCmdBindIndexBuffer(
  628. commandBuffers.at(currentFrame),
  629. (VkBuffer) cmd.indexBuffer->getHandle(),
  630. (VkDeviceSize) cmd.indexBufferOffset,
  631. Vulkan::getVulkanIndexBufferType(cmd.indexType));
  632. if (cmd.indirectBuffer != nullptr)
  633. {
  634. vkCmdDrawIndexedIndirect(
  635. commandBuffers.at(currentFrame),
  636. (VkBuffer) cmd.indirectBuffer->getHandle(),
  637. cmd.indirectBufferOffset,
  638. 1,
  639. 0);
  640. }
  641. else
  642. {
  643. vkCmdDrawIndexed(
  644. commandBuffers.at(currentFrame),
  645. (uint32) cmd.indexCount,
  646. (uint32) cmd.instanceCount,
  647. 0,
  648. 0,
  649. 0);
  650. }
  651. drawCalls++;
  652. }
  653. void Graphics::drawQuads(int start, int count, const VertexAttributes &attributes, const BufferBindings &buffers, graphics::Texture *texture)
  654. {
  655. const int MAX_VERTICES_PER_DRAW = LOVE_UINT16_MAX;
  656. const int MAX_QUADS_PER_DRAW = MAX_VERTICES_PER_DRAW / 4;
  657. prepareDraw(attributes, buffers, texture, PRIMITIVE_TRIANGLES, CULL_BACK);
  658. vkCmdBindIndexBuffer(
  659. commandBuffers.at(currentFrame),
  660. (VkBuffer)quadIndexBuffer->getHandle(),
  661. 0,
  662. Vulkan::getVulkanIndexBufferType(INDEX_UINT16));
  663. int baseVertex = start * 4;
  664. for (int quadindex = 0; quadindex < count; quadindex += MAX_QUADS_PER_DRAW)
  665. {
  666. int quadcount = std::min(MAX_QUADS_PER_DRAW, count - quadindex);
  667. vkCmdDrawIndexed(
  668. commandBuffers.at(currentFrame),
  669. static_cast<uint32_t>(quadcount * 6),
  670. 1,
  671. 0,
  672. baseVertex,
  673. 0);
  674. baseVertex += quadcount * 4;
  675. drawCalls++;
  676. }
  677. }
  678. void Graphics::setColor(Colorf c)
  679. {
  680. c.r = std::min(std::max(c.r, 0.0f), 1.0f);
  681. c.g = std::min(std::max(c.g, 0.0f), 1.0f);
  682. c.b = std::min(std::max(c.b, 0.0f), 1.0f);
  683. c.a = std::min(std::max(c.a, 0.0f), 1.0f);
  684. states.back().color = c;
  685. }
  686. static VkRect2D computeScissor(const Rect &r, double bufferWidth, double bufferHeight, double dpiScale, VkSurfaceTransformFlagBitsKHR preTransform)
  687. {
  688. double x = static_cast<double>(r.x) * dpiScale;
  689. double y = static_cast<double>(r.y) * dpiScale;
  690. double w = static_cast<double>(r.w) * dpiScale;
  691. double h = static_cast<double>(r.h) * dpiScale;
  692. double scissorX, scissorY, scissorW, scissorH;
  693. switch (preTransform)
  694. {
  695. case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
  696. scissorX = bufferWidth - h - y;
  697. scissorY = x;
  698. scissorW = h;
  699. scissorH = w;
  700. break;
  701. case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
  702. scissorX = bufferWidth - w - x;
  703. scissorY = bufferHeight - h - y;
  704. scissorW = w;
  705. scissorH = h;
  706. break;
  707. case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
  708. scissorX = y;
  709. scissorY = bufferHeight - w - x;
  710. scissorW = h;
  711. scissorH = w;
  712. break;
  713. default:
  714. scissorX = x;
  715. scissorY = y;
  716. scissorW = w;
  717. scissorH = h;
  718. break;
  719. }
  720. VkRect2D scissor = {
  721. {static_cast<int32_t>(scissorX), static_cast<int32_t>(scissorY)},
  722. {static_cast<uint32_t>(scissorW), static_cast<uint32_t>(scissorH)}
  723. };
  724. return scissor;
  725. }
  726. void Graphics::setScissor(const Rect &rect)
  727. {
  728. flushBatchedDraws();
  729. VkRect2D scissor = computeScissor(rect, static_cast<double>(swapChainExtent.width), static_cast<double>(swapChainExtent.height), getCurrentDPIScale(), preTransform);
  730. vkCmdSetScissor(commandBuffers.at(currentFrame), 0, 1, &scissor);
  731. states.back().scissor = true;
  732. states.back().scissorRect = rect;
  733. }
  734. void Graphics::setScissor()
  735. {
  736. flushBatchedDraws();
  737. states.back().scissor = false;
  738. VkRect2D scissor{};
  739. scissor.offset = { 0, 0 };
  740. scissor.extent = swapChainExtent;
  741. vkCmdSetScissor(commandBuffers.at(currentFrame), 0, 1, &scissor);
  742. }
  743. void Graphics::setStencilMode(StencilAction action, CompareMode compare, int value, love::uint32 readmask, love::uint32 writemask)
  744. {
  745. if (action != STENCIL_KEEP)
  746. {
  747. const auto& rts = states.back().renderTargets;
  748. auto dsTexture = rts.depthStencil.texture.get();
  749. if (!isRenderTargetActive() && !windowHasStencil)
  750. throw love::Exception("The window must have stenciling enabled to draw to the main screen's stencil buffer");
  751. else if (isRenderTargetActive() && (rts.temporaryRTFlags & TEMPORARY_RT_STENCIL) == 0 && (dsTexture == nullptr || !isPixelFormatStencil(dsTexture->getPixelFormat())))
  752. throw love::Exception("drawing to the stencil buffer with a render target active requires either stencil=true or a custom stencil-type to be used, in setRenderTarget");
  753. }
  754. flushBatchedDraws();
  755. vkCmdSetStencilWriteMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, writemask);
  756. vkCmdSetStencilCompareMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, readmask);
  757. vkCmdSetStencilReference(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, value);
  758. if (optionalDeviceExtensions.extendedDynamicState)
  759. vkCmdSetStencilOpEXT(
  760. commandBuffers.at(currentFrame),
  761. VK_STENCIL_FRONT_AND_BACK,
  762. VK_STENCIL_OP_KEEP, Vulkan::getStencilOp(action),
  763. VK_STENCIL_OP_KEEP, Vulkan::getCompareOp(getReversedCompareMode(compare)));
  764. states.back().stencil.action = action;
  765. states.back().stencil.compare = compare;
  766. states.back().stencil.value = value;
  767. states.back().stencil.readMask = readmask;
  768. states.back().stencil.writeMask = writemask;
  769. }
  770. void Graphics::setDepthMode(CompareMode compare, bool write)
  771. {
  772. flushBatchedDraws();
  773. if (optionalDeviceExtensions.extendedDynamicState)
  774. {
  775. vkCmdSetDepthCompareOpEXT(
  776. commandBuffers.at(currentFrame), Vulkan::getCompareOp(compare));
  777. vkCmdSetDepthWriteEnableEXT(
  778. commandBuffers.at(currentFrame), Vulkan::getBool(write));
  779. }
  780. states.back().depthTest = compare;
  781. states.back().depthWrite = write;
  782. }
  783. void Graphics::setWireframe(bool enable)
  784. {
  785. flushBatchedDraws();
  786. states.back().wireframe = enable;
  787. }
  788. PixelFormat Graphics::getSizedFormat(PixelFormat format, bool rendertarget, bool readable) const
  789. {
  790. switch (format)
  791. {
  792. case PIXELFORMAT_NORMAL:
  793. if (isGammaCorrect())
  794. return PIXELFORMAT_RGBA8_UNORM_sRGB;
  795. else
  796. return PIXELFORMAT_RGBA8_UNORM;
  797. case PIXELFORMAT_HDR:
  798. return PIXELFORMAT_RGBA16_FLOAT;
  799. default:
  800. return format;
  801. }
  802. }
  803. bool Graphics::isPixelFormatSupported(PixelFormat format, uint32 usage, bool sRGB)
  804. {
  805. bool rendertarget = (usage & PIXELFORMATUSAGEFLAGS_RENDERTARGET) != 0;
  806. bool readable = (usage & PIXELFORMATUSAGEFLAGS_SAMPLE) != 0;
  807. format = getSizedFormat(format, rendertarget, readable);
  808. auto vulkanFormat = Vulkan::getTextureFormat(format, sRGB);
  809. VkFormatProperties formatProperties;
  810. vkGetPhysicalDeviceFormatProperties(physicalDevice, vulkanFormat.internalFormat, &formatProperties);
  811. VkFormatFeatureFlags featureFlags = formatProperties.optimalTilingFeatures;
  812. VkImageUsageFlags usageFlags = 0;
  813. if (!featureFlags)
  814. return false;
  815. if (usage & PIXELFORMATUSAGEFLAGS_SAMPLE)
  816. {
  817. usageFlags |= VK_IMAGE_USAGE_SAMPLED_BIT;
  818. if (!(featureFlags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
  819. return false;
  820. }
  821. if (usage & PIXELFORMATUSAGE_LINEAR)
  822. {
  823. if (!(featureFlags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT))
  824. return false;
  825. }
  826. if (usage & PIXELFORMATUSAGEFLAGS_RENDERTARGET)
  827. {
  828. if (isPixelFormatDepth(format) || isPixelFormatDepthStencil(format))
  829. {
  830. usageFlags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  831. if (!(featureFlags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT))
  832. return false;
  833. }
  834. else
  835. {
  836. usageFlags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  837. if (!(featureFlags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT))
  838. return false;
  839. }
  840. }
  841. if (usage & PIXELFORMATUSAGEFLAGS_BLEND)
  842. {
  843. if (!(featureFlags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT))
  844. return false;
  845. }
  846. if (usage & PIXELFORMATUSAGEFLAGS_COMPUTEWRITE)
  847. {
  848. usageFlags |= VK_IMAGE_USAGE_STORAGE_BIT;
  849. if (!(featureFlags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT))
  850. return false;
  851. }
  852. if (usage & PIXELFORMATUSAGEFLAGS_MSAA)
  853. {
  854. VkImageFormatProperties properties;
  855. if (vkGetPhysicalDeviceImageFormatProperties(physicalDevice, vulkanFormat.internalFormat, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usageFlags, 0, &properties) != VK_SUCCESS)
  856. return false;
  857. if (static_cast<uint32_t>(properties.sampleCounts) == 1)
  858. return false;
  859. }
  860. return true;
  861. }
  862. Renderer Graphics::getRenderer() const
  863. {
  864. return RENDERER_VULKAN;
  865. }
  866. graphics::GraphicsReadback *Graphics::newReadbackInternal(ReadbackMethod method, love::graphics::Buffer *buffer, size_t offset, size_t size, data::ByteData *dest, size_t destoffset)
  867. {
  868. return new GraphicsReadback(this, method, buffer, offset, size, dest, destoffset);
  869. }
  870. graphics::GraphicsReadback *Graphics::newReadbackInternal(ReadbackMethod method, love::graphics::Texture *texture, int slice, int mipmap, const Rect &rect, image::ImageData *dest, int destx, int desty)
  871. {
  872. return new GraphicsReadback(this, method, texture, slice, mipmap, rect, dest, destx, desty);
  873. }
  874. graphics::ShaderStage *Graphics::newShaderStageInternal(ShaderStageType stage, const std::string &cachekey, const std::string &source, bool gles)
  875. {
  876. return new ShaderStage(this, stage, source, gles, cachekey);
  877. }
  878. graphics::Shader *Graphics::newShaderInternal(StrongRef<love::graphics::ShaderStage> stages[SHADERSTAGE_MAX_ENUM])
  879. {
  880. return new Shader(stages);
  881. }
  882. graphics::StreamBuffer *Graphics::newStreamBuffer(BufferUsage type, size_t size)
  883. {
  884. return new StreamBuffer(this, type, size);
  885. }
  886. bool Graphics::dispatch(love::graphics::Shader *shader, int x, int y, int z)
  887. {
  888. usedShadersInFrame.insert(computeShader);
  889. if (renderPassState.active)
  890. endRenderPass();
  891. vkCmdBindPipeline(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE, computeShader->getComputePipeline());
  892. computeShader->cmdPushDescriptorSets(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE);
  893. // TODO: does this need any layout transitions?
  894. vkCmdDispatch(commandBuffers.at(currentFrame), (uint32) x, (uint32) y, (uint32) z);
  895. return true;
  896. }
  897. bool Graphics::dispatch(love::graphics::Shader *shader, love::graphics::Buffer *indirectargs, size_t argsoffset)
  898. {
  899. usedShadersInFrame.insert(computeShader);
  900. if (renderPassState.active)
  901. endRenderPass();
  902. vkCmdBindPipeline(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE, computeShader->getComputePipeline());
  903. computeShader->cmdPushDescriptorSets(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE);
  904. // TODO: does this need any layout transitions?
  905. vkCmdDispatchIndirect(commandBuffers.at(currentFrame), (VkBuffer) indirectargs->getHandle(), argsoffset);
  906. return true;
  907. }
  908. Matrix4 Graphics::computeDeviceProjection(const Matrix4 &projection, bool rendertotexture) const
  909. {
  910. uint32 flags = DEVICE_PROJECTION_DEFAULT;
  911. return calculateDeviceProjection(projection, flags);
  912. }
  913. void Graphics::setRenderTargetsInternal(const RenderTargets &rts, int pixelw, int pixelh, bool hasSRGBtexture)
  914. {
  915. if (renderPassState.active)
  916. endRenderPass();
  917. bool isWindow = rts.getFirstTarget().texture == nullptr;
  918. if (isWindow)
  919. setDefaultRenderPass();
  920. else
  921. setRenderPass(rts, pixelw, pixelh, hasSRGBtexture);
  922. }
  923. // END IMPLEMENTATION OVERRIDDEN FUNCTIONS
  924. void Graphics::initDynamicState()
  925. {
  926. if (states.back().scissor)
  927. setScissor(states.back().scissorRect);
  928. else
  929. setScissor();
  930. vkCmdSetStencilWriteMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, states.back().stencil.writeMask);
  931. vkCmdSetStencilCompareMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, states.back().stencil.readMask);
  932. vkCmdSetStencilReference(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, states.back().stencil.value);
  933. if (optionalDeviceExtensions.extendedDynamicState)
  934. {
  935. vkCmdSetStencilOpEXT(
  936. commandBuffers.at(currentFrame),
  937. VK_STENCIL_FRONT_AND_BACK,
  938. VK_STENCIL_OP_KEEP, Vulkan::getStencilOp(states.back().stencil.action),
  939. VK_STENCIL_OP_KEEP, Vulkan::getCompareOp(getReversedCompareMode(states.back().stencil.compare)));
  940. vkCmdSetDepthCompareOpEXT(
  941. commandBuffers.at(currentFrame), Vulkan::getCompareOp(states.back().depthTest));
  942. vkCmdSetDepthWriteEnableEXT(
  943. commandBuffers.at(currentFrame), Vulkan::getBool(states.back().depthWrite));
  944. vkCmdSetFrontFaceEXT(
  945. commandBuffers.at(currentFrame), Vulkan::getFrontFace(states.back().winding));
  946. }
  947. }
  948. void Graphics::beginFrame()
  949. {
  950. vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
  951. if (frameCounter >= USAGES_POLL_INTERVAL)
  952. {
  953. cleanupUnusedObjects();
  954. frameCounter = 0;
  955. }
  956. while (true)
  957. {
  958. VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
  959. if (result == VK_ERROR_OUT_OF_DATE_KHR)
  960. {
  961. recreateSwapChain();
  962. continue;
  963. }
  964. else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR)
  965. throw love::Exception("failed to acquire swap chain image");
  966. break;
  967. }
  968. imageRequested = true;
  969. for (auto &readbackCallback : readbackCallbacks.at(currentFrame))
  970. readbackCallback();
  971. readbackCallbacks.at(currentFrame).clear();
  972. for (auto &cleanUpFn : cleanUpFunctions.at(currentFrame))
  973. cleanUpFn();
  974. cleanUpFunctions.at(currentFrame).clear();
  975. startRecordingGraphicsCommands();
  976. Vulkan::cmdTransitionImageLayout(
  977. commandBuffers.at(currentFrame),
  978. swapChainImages[imageIndex],
  979. VK_IMAGE_LAYOUT_UNDEFINED,
  980. VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  981. if (transitionColorDepthLayouts)
  982. {
  983. Vulkan::cmdTransitionImageLayout(
  984. commandBuffers.at(currentFrame),
  985. depthImage,
  986. VK_IMAGE_LAYOUT_UNDEFINED,
  987. VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  988. if (colorImage)
  989. Vulkan::cmdTransitionImageLayout(
  990. commandBuffers.at(currentFrame),
  991. colorImage,
  992. VK_IMAGE_LAYOUT_UNDEFINED,
  993. VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  994. transitionColorDepthLayouts = false;
  995. }
  996. Vulkan::resetShaderSwitches();
  997. for (const auto shader : usedShadersInFrame)
  998. shader->newFrame();
  999. usedShadersInFrame.clear();
  1000. }
  1001. void Graphics::startRecordingGraphicsCommands()
  1002. {
  1003. VkCommandBufferBeginInfo beginInfo{};
  1004. beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  1005. beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  1006. beginInfo.pInheritanceInfo = nullptr;
  1007. if (vkBeginCommandBuffer(commandBuffers.at(currentFrame), &beginInfo) != VK_SUCCESS)
  1008. throw love::Exception("failed to begin recording command buffer");
  1009. initDynamicState();
  1010. setDefaultRenderPass();
  1011. }
  1012. void Graphics::endRecordingGraphicsCommands() {
  1013. if (renderPassState.active)
  1014. endRenderPass();
  1015. if (vkEndCommandBuffer(commandBuffers.at(currentFrame)) != VK_SUCCESS)
  1016. throw love::Exception("failed to record command buffer");
  1017. }
  1018. const VkDeviceSize Graphics::getMinUniformBufferOffsetAlignment() const
  1019. {
  1020. return minUniformBufferOffsetAlignment;
  1021. }
  1022. VkCommandBuffer Graphics::getCommandBufferForDataTransfer()
  1023. {
  1024. if (renderPassState.active)
  1025. endRenderPass();
  1026. return commandBuffers.at(currentFrame);
  1027. }
  1028. void Graphics::queueCleanUp(std::function<void()> cleanUp)
  1029. {
  1030. cleanUpFunctions.at(currentFrame).push_back(cleanUp);
  1031. }
  1032. void Graphics::addReadbackCallback(std::function<void()> callback)
  1033. {
  1034. readbackCallbacks.at(currentFrame).push_back(callback);
  1035. }
  1036. graphics::Shader::BuiltinUniformData Graphics::getCurrentBuiltinUniformData()
  1037. {
  1038. love::graphics::Shader::BuiltinUniformData data;
  1039. data.transformMatrix = getTransform();
  1040. data.projectionMatrix = displayRotation * getDeviceProjection();
  1041. // The normal matrix is the transpose of the inverse of the rotation portion
  1042. // (top-left 3x3) of the transform matrix.
  1043. {
  1044. Matrix3 normalmatrix = Matrix3(data.transformMatrix).transposedInverse();
  1045. const float *e = normalmatrix.getElements();
  1046. for (int i = 0; i < 3; i++)
  1047. {
  1048. data.normalMatrix[i].x = e[i * 3 + 0];
  1049. data.normalMatrix[i].y = e[i * 3 + 1];
  1050. data.normalMatrix[i].z = e[i * 3 + 2];
  1051. data.normalMatrix[i].w = 0.0f;
  1052. }
  1053. }
  1054. // Store DPI scale in an unused component of another vector.
  1055. data.normalMatrix[0].w = (float)getCurrentDPIScale();
  1056. // Same with point size.
  1057. data.normalMatrix[1].w = getPointSize();
  1058. data.screenSizeParams.x = static_cast<float>(swapChainExtent.width);
  1059. data.screenSizeParams.y = static_cast<float>(swapChainExtent.height);
  1060. data.screenSizeParams.z = 1.0f;
  1061. data.screenSizeParams.w = 0.0f;
  1062. data.constantColor = getColor();
  1063. gammaCorrectColor(data.constantColor);
  1064. return data;
  1065. }
  1066. const OptionalDeviceExtensions &Graphics::getEnabledOptionalDeviceExtensions() const
  1067. {
  1068. return optionalDeviceExtensions;
  1069. }
  1070. static void checkOptionalInstanceExtensions(OptionalInstanceExtensions &ext)
  1071. {
  1072. uint32_t count;
  1073. vkEnumerateInstanceExtensionProperties(nullptr, &count, nullptr);
  1074. std::vector<VkExtensionProperties> extensions(count);
  1075. vkEnumerateInstanceExtensionProperties(nullptr, &count, extensions.data());
  1076. for (const auto &extension : extensions)
  1077. {
  1078. if (strcmp(extension.extensionName, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME) == 0)
  1079. ext.physicalDeviceProperties2 = true;
  1080. }
  1081. }
  1082. void Graphics::createVulkanInstance()
  1083. {
  1084. if (isDebugEnabled() && !checkValidationSupport())
  1085. throw love::Exception("validation layers requested, but not available");
  1086. VkApplicationInfo appInfo{};
  1087. appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  1088. appInfo.pApplicationName = "LOVE";
  1089. appInfo.applicationVersion = VK_MAKE_API_VERSION(0, 1, 0, 0); // get this version from somewhere else?
  1090. appInfo.pEngineName = "LOVE Game Framework";
  1091. appInfo.engineVersion = VK_MAKE_API_VERSION(0, VERSION_MAJOR, VERSION_MINOR, VERSION_REV);
  1092. appInfo.apiVersion = VK_API_VERSION_1_3;
  1093. VkInstanceCreateInfo createInfo{};
  1094. createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  1095. createInfo.pApplicationInfo = &appInfo;
  1096. createInfo.pNext = nullptr;
  1097. // GetInstanceExtensions works with a null window parameter as long as
  1098. // SDL_Vulkan_LoadLibrary has been called (which we do earlier).
  1099. unsigned int count;
  1100. if (SDL_Vulkan_GetInstanceExtensions(nullptr, &count, nullptr) != SDL_TRUE)
  1101. throw love::Exception("couldn't retrieve sdl vulkan extensions");
  1102. std::vector<const char*> extensions = {};
  1103. checkOptionalInstanceExtensions(optionalInstanceExtensions);
  1104. if (optionalInstanceExtensions.physicalDeviceProperties2)
  1105. extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
  1106. size_t additional_extension_count = extensions.size();
  1107. extensions.resize(additional_extension_count + count);
  1108. if (SDL_Vulkan_GetInstanceExtensions(nullptr, &count, extensions.data() + additional_extension_count) != SDL_TRUE)
  1109. throw love::Exception("couldn't retrieve sdl vulkan extensions");
  1110. createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
  1111. createInfo.ppEnabledExtensionNames = extensions.data();
  1112. if (isDebugEnabled())
  1113. {
  1114. createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
  1115. createInfo.ppEnabledLayerNames = validationLayers.data();
  1116. }
  1117. if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS)
  1118. throw love::Exception("couldn't create vulkan instance");
  1119. volkLoadInstance(instance);
  1120. }
  1121. bool Graphics::checkValidationSupport()
  1122. {
  1123. uint32_t layerCount;
  1124. vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
  1125. std::vector<VkLayerProperties> availableLayers(layerCount);
  1126. vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
  1127. for (const char *layerName : validationLayers)
  1128. {
  1129. bool layerFound = false;
  1130. for (const auto &layerProperties : availableLayers)
  1131. {
  1132. if (strcmp(layerName, layerProperties.layerName) == 0)
  1133. {
  1134. layerFound = true;
  1135. break;
  1136. }
  1137. }
  1138. if (!layerFound)
  1139. return false;
  1140. }
  1141. return true;
  1142. }
  1143. void Graphics::pickPhysicalDevice()
  1144. {
  1145. uint32_t deviceCount = 0;
  1146. vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
  1147. if (deviceCount == 0)
  1148. throw love::Exception("failed to find GPUs with Vulkan support");
  1149. std::vector<VkPhysicalDevice> devices(deviceCount);
  1150. vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
  1151. std::multimap<int, VkPhysicalDevice> candidates;
  1152. for (const auto &device : devices)
  1153. {
  1154. int score = rateDeviceSuitability(device);
  1155. candidates.insert(std::make_pair(score, device));
  1156. }
  1157. if (candidates.rbegin()->first > 0)
  1158. physicalDevice = candidates.rbegin()->second;
  1159. else
  1160. throw love::Exception("failed to find a suitable gpu");
  1161. VkPhysicalDeviceProperties properties;
  1162. vkGetPhysicalDeviceProperties(physicalDevice, &properties);
  1163. minUniformBufferOffsetAlignment = properties.limits.minUniformBufferOffsetAlignment;
  1164. deviceApiVersion = properties.apiVersion;
  1165. msaaSamples = getMsaaCount(requestedMsaa);
  1166. depthStencilFormat = findDepthFormat();
  1167. }
  1168. bool Graphics::checkDeviceExtensionSupport(VkPhysicalDevice device)
  1169. {
  1170. uint32_t extensionCount;
  1171. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
  1172. std::vector<VkExtensionProperties> availableExtensions(extensionCount);
  1173. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
  1174. std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
  1175. for (const auto &extension : availableExtensions)
  1176. requiredExtensions.erase(extension.extensionName);
  1177. return requiredExtensions.empty();
  1178. }
  1179. // if the score is nonzero then the device is suitable.
  1180. // A higher rating means generally better performance
  1181. // if the score is 0 the device is unsuitable
  1182. int Graphics::rateDeviceSuitability(VkPhysicalDevice device)
  1183. {
  1184. VkPhysicalDeviceProperties deviceProperties;
  1185. VkPhysicalDeviceFeatures deviceFeatures;
  1186. vkGetPhysicalDeviceProperties(device, &deviceProperties);
  1187. vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
  1188. int score = 1;
  1189. // optional
  1190. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
  1191. score += 1000;
  1192. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU)
  1193. score += 100;
  1194. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU)
  1195. score += 10;
  1196. // definitely needed
  1197. QueueFamilyIndices indices = findQueueFamilies(device);
  1198. if (!indices.isComplete())
  1199. score = 0;
  1200. bool extensionsSupported = checkDeviceExtensionSupport(device);
  1201. if (!extensionsSupported)
  1202. score = 0;
  1203. if (extensionsSupported)
  1204. {
  1205. auto swapChainSupport = querySwapChainSupport(device);
  1206. bool swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
  1207. if (!swapChainAdequate)
  1208. score = 0;
  1209. }
  1210. if (!deviceFeatures.samplerAnisotropy)
  1211. score = 0;
  1212. if (!deviceFeatures.fillModeNonSolid)
  1213. score = 0;
  1214. return score;
  1215. }
  1216. QueueFamilyIndices Graphics::findQueueFamilies(VkPhysicalDevice device)
  1217. {
  1218. QueueFamilyIndices indices;
  1219. uint32_t queueFamilyCount = 0;
  1220. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
  1221. std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
  1222. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
  1223. int i = 0;
  1224. for (const auto &queueFamily : queueFamilies)
  1225. {
  1226. if ((queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) && (queueFamily.queueFlags & VK_QUEUE_COMPUTE_BIT))
  1227. indices.graphicsFamily = i;
  1228. VkBool32 presentSupport = false;
  1229. vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
  1230. if (presentSupport)
  1231. indices.presentFamily = i;
  1232. if (indices.isComplete())
  1233. break;
  1234. i++;
  1235. }
  1236. return indices;
  1237. }
  1238. static void findOptionalDeviceExtensions(VkPhysicalDevice physicalDevice, OptionalDeviceExtensions &optionalDeviceExtensions)
  1239. {
  1240. uint32_t extensionCount;
  1241. vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr);
  1242. std::vector<VkExtensionProperties> availableExtensions(extensionCount);
  1243. vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data());
  1244. for (const auto &extension : availableExtensions)
  1245. {
  1246. if (strcmp(extension.extensionName, VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME) == 0)
  1247. optionalDeviceExtensions.extendedDynamicState = true;
  1248. if (strcmp(extension.extensionName, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME) == 0)
  1249. optionalDeviceExtensions.memoryRequirements2 = true;
  1250. if (strcmp(extension.extensionName, VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME) == 0)
  1251. optionalDeviceExtensions.dedicatedAllocation = true;
  1252. if (strcmp(extension.extensionName, VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME) == 0)
  1253. optionalDeviceExtensions.memoryBudget = true;
  1254. if (strcmp(extension.extensionName, VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME) == 0)
  1255. optionalDeviceExtensions.shaderFloatControls = true;
  1256. if (strcmp(extension.extensionName, VK_KHR_SPIRV_1_4_EXTENSION_NAME) == 0)
  1257. optionalDeviceExtensions.spirv14 = true;
  1258. }
  1259. }
  1260. void Graphics::createLogicalDevice()
  1261. {
  1262. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  1263. std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
  1264. std::set<uint32_t> uniqueQueueFamilies = {
  1265. indices.graphicsFamily.value,
  1266. indices.presentFamily.value
  1267. };
  1268. float queuePriority = 1.0f;
  1269. for (uint32_t queueFamily : uniqueQueueFamilies)
  1270. {
  1271. VkDeviceQueueCreateInfo queueCreateInfo{};
  1272. queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  1273. queueCreateInfo.queueFamilyIndex = queueFamily;
  1274. queueCreateInfo.queueCount = 1;
  1275. queueCreateInfo.pQueuePriorities = &queuePriority;
  1276. queueCreateInfos.push_back(queueCreateInfo);
  1277. }
  1278. findOptionalDeviceExtensions(physicalDevice, optionalDeviceExtensions);
  1279. // sanity check for dependencies.
  1280. if (optionalDeviceExtensions.extendedDynamicState && !optionalInstanceExtensions.physicalDeviceProperties2)
  1281. optionalDeviceExtensions.extendedDynamicState = false;
  1282. if (optionalDeviceExtensions.dedicatedAllocation && !optionalDeviceExtensions.memoryRequirements2)
  1283. optionalDeviceExtensions.dedicatedAllocation = false;
  1284. if (optionalDeviceExtensions.memoryBudget && !optionalInstanceExtensions.physicalDeviceProperties2)
  1285. optionalDeviceExtensions.memoryBudget = false;
  1286. if (optionalDeviceExtensions.spirv14 && !optionalDeviceExtensions.shaderFloatControls)
  1287. optionalDeviceExtensions.spirv14 = false;
  1288. if (optionalDeviceExtensions.spirv14 && deviceApiVersion < VK_API_VERSION_1_1)
  1289. optionalDeviceExtensions.spirv14 = false;
  1290. VkPhysicalDeviceFeatures deviceFeatures{};
  1291. deviceFeatures.samplerAnisotropy = VK_TRUE;
  1292. deviceFeatures.fillModeNonSolid = VK_TRUE;
  1293. VkDeviceCreateInfo createInfo{};
  1294. createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  1295. createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
  1296. createInfo.pQueueCreateInfos = queueCreateInfos.data();
  1297. createInfo.pEnabledFeatures = &deviceFeatures;
  1298. std::vector<const char*> enabledExtensions(deviceExtensions.begin(), deviceExtensions.end());
  1299. if (optionalDeviceExtensions.extendedDynamicState)
  1300. enabledExtensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME);
  1301. if (optionalDeviceExtensions.memoryRequirements2)
  1302. enabledExtensions.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
  1303. if (optionalDeviceExtensions.dedicatedAllocation)
  1304. enabledExtensions.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME);
  1305. if (optionalDeviceExtensions.memoryBudget)
  1306. enabledExtensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME);
  1307. if (optionalDeviceExtensions.shaderFloatControls)
  1308. enabledExtensions.push_back(VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME);
  1309. if (optionalDeviceExtensions.spirv14)
  1310. enabledExtensions.push_back(VK_KHR_SPIRV_1_4_EXTENSION_NAME);
  1311. if (deviceApiVersion >= VK_API_VERSION_1_1)
  1312. enabledExtensions.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
  1313. createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledExtensions.size());
  1314. createInfo.ppEnabledExtensionNames = enabledExtensions.data();
  1315. if (isDebugEnabled())
  1316. {
  1317. createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
  1318. createInfo.ppEnabledLayerNames = validationLayers.data();
  1319. }
  1320. VkPhysicalDeviceExtendedDynamicStateFeaturesEXT extendedDynamicStateFeatures{};
  1321. extendedDynamicStateFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT;
  1322. extendedDynamicStateFeatures.extendedDynamicState = Vulkan::getBool(optionalDeviceExtensions.extendedDynamicState);
  1323. extendedDynamicStateFeatures.pNext = nullptr;
  1324. createInfo.pNext = &extendedDynamicStateFeatures;
  1325. if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS)
  1326. throw love::Exception("failed to create logical device");
  1327. volkLoadDevice(device);
  1328. vkGetDeviceQueue(device, indices.graphicsFamily.value, 0, &graphicsQueue);
  1329. vkGetDeviceQueue(device, indices.presentFamily.value, 0, &presentQueue);
  1330. }
  1331. void Graphics::createPipelineCache()
  1332. {
  1333. VkPipelineCacheCreateInfo cacheInfo{};
  1334. cacheInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
  1335. if (vkCreatePipelineCache(device, &cacheInfo, nullptr, &pipelineCache) != VK_SUCCESS)
  1336. throw love::Exception("could not create pipeline cache");
  1337. }
  1338. void Graphics::initVMA()
  1339. {
  1340. VmaAllocatorCreateInfo allocatorCreateInfo = {};
  1341. allocatorCreateInfo.vulkanApiVersion = deviceApiVersion;
  1342. allocatorCreateInfo.physicalDevice = physicalDevice;
  1343. allocatorCreateInfo.device = device;
  1344. allocatorCreateInfo.instance = instance;
  1345. VmaVulkanFunctions vulkanFunctions{};
  1346. vulkanFunctions.vkGetInstanceProcAddr = vkGetInstanceProcAddr;
  1347. vulkanFunctions.vkGetDeviceProcAddr = vkGetDeviceProcAddr;
  1348. vulkanFunctions.vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties;
  1349. vulkanFunctions.vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties;
  1350. vulkanFunctions.vkAllocateMemory = vkAllocateMemory;
  1351. vulkanFunctions.vkFreeMemory = vkFreeMemory;
  1352. vulkanFunctions.vkMapMemory = vkMapMemory;
  1353. vulkanFunctions.vkUnmapMemory = vkUnmapMemory;
  1354. vulkanFunctions.vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges;
  1355. vulkanFunctions.vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges;
  1356. vulkanFunctions.vkBindBufferMemory = vkBindBufferMemory;
  1357. vulkanFunctions.vkBindImageMemory = vkBindImageMemory;
  1358. vulkanFunctions.vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements;
  1359. vulkanFunctions.vkGetImageMemoryRequirements = vkGetImageMemoryRequirements;
  1360. vulkanFunctions.vkCreateBuffer = vkCreateBuffer;
  1361. vulkanFunctions.vkCreateImage = vkCreateImage;
  1362. vulkanFunctions.vkDestroyBuffer = vkDestroyBuffer;
  1363. vulkanFunctions.vkDestroyImage = vkDestroyImage;
  1364. vulkanFunctions.vkCmdCopyBuffer = vkCmdCopyBuffer;
  1365. vulkanFunctions.vkGetBufferMemoryRequirements2KHR = vkGetBufferMemoryRequirements2KHR;
  1366. vulkanFunctions.vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2KHR;
  1367. vulkanFunctions.vkBindBufferMemory2KHR = vkBindBufferMemory2KHR;
  1368. vulkanFunctions.vkBindImageMemory2KHR = vkBindImageMemory2KHR;
  1369. vulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR = vkGetPhysicalDeviceMemoryProperties2KHR;
  1370. vulkanFunctions.vkGetDeviceBufferMemoryRequirements = vkGetDeviceBufferMemoryRequirements;
  1371. vulkanFunctions.vkGetDeviceImageMemoryRequirements = vkGetDeviceImageMemoryRequirements;
  1372. allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions;
  1373. allocatorCreateInfo.flags |= VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT;
  1374. if (optionalDeviceExtensions.dedicatedAllocation)
  1375. allocatorCreateInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT;
  1376. if (optionalDeviceExtensions.memoryBudget)
  1377. allocatorCreateInfo.flags |= VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT;
  1378. if (vmaCreateAllocator(&allocatorCreateInfo, &vmaAllocator) != VK_SUCCESS)
  1379. throw love::Exception("failed to create vma allocator");
  1380. }
  1381. void Graphics::createSurface()
  1382. {
  1383. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  1384. const void *handle = window->getHandle();
  1385. if (SDL_Vulkan_CreateSurface((SDL_Window*)handle, instance, &surface) != SDL_TRUE)
  1386. throw love::Exception("failed to create window surface");
  1387. }
  1388. SwapChainSupportDetails Graphics::querySwapChainSupport(VkPhysicalDevice device)
  1389. {
  1390. SwapChainSupportDetails details;
  1391. vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
  1392. uint32_t formatCount;
  1393. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
  1394. if (formatCount != 0)
  1395. {
  1396. details.formats.resize(formatCount);
  1397. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
  1398. }
  1399. uint32_t presentModeCount;
  1400. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
  1401. if (presentModeCount != 0)
  1402. {
  1403. details.presentModes.resize(presentModeCount);
  1404. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
  1405. }
  1406. return details;
  1407. }
  1408. void Graphics::createSwapChain()
  1409. {
  1410. SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
  1411. VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
  1412. VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
  1413. VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
  1414. if ((swapChainSupport.capabilities.currentTransform & VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR) ||
  1415. (swapChainSupport.capabilities.currentTransform & VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR))
  1416. {
  1417. uint32_t width, height;
  1418. width = extent.width;
  1419. height = extent.height;
  1420. extent.width = height;
  1421. extent.height = width;
  1422. }
  1423. auto currentTransform = swapChainSupport.capabilities.currentTransform;
  1424. constexpr float PI = 3.14159265358979323846f;
  1425. float angle = 0.0f;
  1426. if (currentTransform & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
  1427. angle = 0.0f;
  1428. else if (currentTransform & VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR)
  1429. angle = -PI / 2.0f;
  1430. else if (currentTransform & VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR)
  1431. angle = -PI;
  1432. else if (currentTransform & VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR)
  1433. angle = -3.0f * PI / 2.0f;
  1434. float data[] = {
  1435. cosf(angle), -sinf(angle), 0.0f, 0.0f,
  1436. sinf(angle), cosf(angle), 0.0f, 0.0f,
  1437. 0.0f, 0.0f, 1.0f, 0.0f,
  1438. 0.0f, 0.0f, 0.0f, 1.0f,
  1439. };
  1440. displayRotation = Matrix4(data);
  1441. uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
  1442. if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount)
  1443. imageCount = swapChainSupport.capabilities.maxImageCount;
  1444. VkSwapchainCreateInfoKHR createInfo{};
  1445. createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  1446. createInfo.surface = surface;
  1447. createInfo.minImageCount = imageCount;
  1448. createInfo.imageFormat = surfaceFormat.format;
  1449. createInfo.imageColorSpace = surfaceFormat.colorSpace;
  1450. createInfo.imageExtent = extent;
  1451. createInfo.imageArrayLayers = 1;
  1452. createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
  1453. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  1454. uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value, indices.presentFamily.value };
  1455. if (indices.graphicsFamily.value != indices.presentFamily.value)
  1456. {
  1457. createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
  1458. createInfo.queueFamilyIndexCount = 2;
  1459. createInfo.pQueueFamilyIndices = queueFamilyIndices;
  1460. }
  1461. else
  1462. {
  1463. createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1464. createInfo.queueFamilyIndexCount = 0;
  1465. createInfo.pQueueFamilyIndices = nullptr;
  1466. }
  1467. createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
  1468. createInfo.compositeAlpha = chooseCompositeAlpha(swapChainSupport.capabilities);
  1469. createInfo.presentMode = presentMode;
  1470. createInfo.clipped = VK_TRUE;
  1471. createInfo.oldSwapchain = VK_NULL_HANDLE;
  1472. if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS)
  1473. throw love::Exception("failed to create swap chain");
  1474. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
  1475. swapChainImages.resize(imageCount);
  1476. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
  1477. swapChainImageFormat = surfaceFormat.format;
  1478. swapChainExtent = extent;
  1479. preTransform = swapChainSupport.capabilities.currentTransform;
  1480. }
  1481. VkSurfaceFormatKHR Graphics::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR> &availableFormats)
  1482. {
  1483. std::vector<VkFormat> formatOrder;
  1484. // TODO: turn off GammaCorrect if a sRGB format can't be found?
  1485. // TODO: does every platform have these formats?
  1486. if (isGammaCorrect())
  1487. {
  1488. formatOrder = {
  1489. VK_FORMAT_B8G8R8A8_SRGB,
  1490. VK_FORMAT_R8G8B8A8_SRGB,
  1491. };
  1492. }
  1493. else
  1494. {
  1495. formatOrder = {
  1496. VK_FORMAT_B8G8R8A8_UNORM,
  1497. VK_FORMAT_R8G8B8A8_SNORM,
  1498. };
  1499. }
  1500. for (const auto format : formatOrder)
  1501. {
  1502. for (const auto &availableFormat : availableFormats)
  1503. {
  1504. if (availableFormat.format == format && availableFormat.colorSpace == VK_COLORSPACE_SRGB_NONLINEAR_KHR)
  1505. return availableFormat;
  1506. }
  1507. }
  1508. return availableFormats[0];
  1509. }
  1510. VkPresentModeKHR Graphics::chooseSwapPresentMode(const std::vector<VkPresentModeKHR> &availablePresentModes)
  1511. {
  1512. const auto begin = availablePresentModes.begin();
  1513. const auto end = availablePresentModes.end();
  1514. switch (vsync)
  1515. {
  1516. case -1:
  1517. if (std::find(begin, end, VK_PRESENT_MODE_FIFO_RELAXED_KHR) != end)
  1518. return VK_PRESENT_MODE_FIFO_RELAXED_KHR;
  1519. else
  1520. return VK_PRESENT_MODE_FIFO_KHR;
  1521. case 0:
  1522. // Mailbox mode might be better than immediate mode for a lot of people.
  1523. // But on at least some systems it acts as if vsync is enabled
  1524. // https://github.com/love2d/love/issues/1852
  1525. // TODO: is that a bug in love's code or the graphics driver / compositor?
  1526. // Should love expose mailbox mode in an API to users in some manner,
  1527. // instead of trying to guess what to do?
  1528. if (std::find(begin, end, VK_PRESENT_MODE_IMMEDIATE_KHR) != end)
  1529. return VK_PRESENT_MODE_IMMEDIATE_KHR;
  1530. else if (std::find(begin, end, VK_PRESENT_MODE_MAILBOX_KHR) != end)
  1531. return VK_PRESENT_MODE_MAILBOX_KHR;
  1532. else
  1533. return VK_PRESENT_MODE_FIFO_KHR;
  1534. default:
  1535. // TODO: support for swap interval = 2, etc?
  1536. return VK_PRESENT_MODE_FIFO_KHR;
  1537. }
  1538. }
  1539. static uint32_t clampuint32_t(uint32_t value, uint32_t min, uint32_t max)
  1540. {
  1541. if (value < min)
  1542. return min;
  1543. if (value > max)
  1544. return max;
  1545. return value;
  1546. }
  1547. VkExtent2D Graphics::chooseSwapExtent(const VkSurfaceCapabilitiesKHR &capabilities)
  1548. {
  1549. if (capabilities.currentExtent.width != UINT32_MAX)
  1550. return capabilities.currentExtent;
  1551. else
  1552. {
  1553. VkExtent2D actualExtent = {
  1554. static_cast<uint32_t>(pixelWidth),
  1555. static_cast<uint32_t>(pixelHeight)
  1556. };
  1557. actualExtent.width = clampuint32_t(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
  1558. actualExtent.height = clampuint32_t(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
  1559. return actualExtent;
  1560. }
  1561. }
  1562. VkCompositeAlphaFlagBitsKHR Graphics::chooseCompositeAlpha(const VkSurfaceCapabilitiesKHR &capabilities)
  1563. {
  1564. if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR)
  1565. return VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  1566. else if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR)
  1567. return VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
  1568. else if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR)
  1569. return VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
  1570. else if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR)
  1571. return VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR;
  1572. else
  1573. throw love::Exception("failed to find composite alpha");
  1574. }
  1575. void Graphics::createImageViews()
  1576. {
  1577. swapChainImageViews.resize(swapChainImages.size());
  1578. for (size_t i = 0; i < swapChainImages.size(); i++)
  1579. {
  1580. VkImageViewCreateInfo createInfo{};
  1581. createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1582. createInfo.image = swapChainImages.at(i);
  1583. createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  1584. createInfo.format = swapChainImageFormat;
  1585. createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  1586. createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  1587. createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  1588. createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  1589. createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1590. createInfo.subresourceRange.baseMipLevel = 0;
  1591. createInfo.subresourceRange.levelCount = 1;
  1592. createInfo.subresourceRange.baseArrayLayer = 0;
  1593. createInfo.subresourceRange.layerCount = 1;
  1594. if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews.at(i)) != VK_SUCCESS)
  1595. throw love::Exception("failed to create image views");
  1596. }
  1597. }
  1598. void Graphics::createScreenshotCallbackBuffers()
  1599. {
  1600. screenshotReadbackBuffers.resize(MAX_FRAMES_IN_FLIGHT);
  1601. for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
  1602. {
  1603. VkBufferCreateInfo bufferInfo{};
  1604. bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  1605. bufferInfo.size = 4ll * swapChainExtent.width * swapChainExtent.height;
  1606. bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  1607. bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1608. VmaAllocationCreateInfo allocCreateInfo{};
  1609. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  1610. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
  1611. auto result = vmaCreateBuffer(
  1612. vmaAllocator,
  1613. &bufferInfo,
  1614. &allocCreateInfo,
  1615. &screenshotReadbackBuffers.at(i).buffer,
  1616. &screenshotReadbackBuffers.at(i).allocation,
  1617. &screenshotReadbackBuffers.at(i).allocationInfo);
  1618. if (result != VK_SUCCESS)
  1619. throw love::Exception("failed to create screenshot readback buffer");
  1620. VkImageCreateInfo imageInfo{};
  1621. imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  1622. imageInfo.imageType = VK_IMAGE_TYPE_2D;
  1623. imageInfo.format = VK_FORMAT_R8G8B8A8_SRGB;
  1624. imageInfo.extent = {
  1625. swapChainExtent.width,
  1626. swapChainExtent.height,
  1627. 1
  1628. };
  1629. imageInfo.mipLevels = 1;
  1630. imageInfo.arrayLayers = 1;
  1631. imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  1632. imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  1633. imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1634. imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1635. imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  1636. VmaAllocationCreateInfo imageAllocCreateInfo{};
  1637. result = vmaCreateImage(
  1638. vmaAllocator,
  1639. &imageInfo,
  1640. &imageAllocCreateInfo,
  1641. &screenshotReadbackBuffers.at(i).image,
  1642. &screenshotReadbackBuffers.at(i).imageAllocation,
  1643. nullptr);
  1644. if (result != VK_SUCCESS)
  1645. throw love::Exception("failed to create screenshot readback image");
  1646. }
  1647. }
  1648. VkFramebuffer Graphics::createFramebuffer(FramebufferConfiguration &configuration)
  1649. {
  1650. std::vector<VkImageView> attachments;
  1651. for (const auto &colorView : configuration.colorViews)
  1652. attachments.push_back(colorView);
  1653. if (configuration.staticData.depthView)
  1654. attachments.push_back(configuration.staticData.depthView);
  1655. if (configuration.staticData.resolveView)
  1656. attachments.push_back(configuration.staticData.resolveView);
  1657. VkFramebufferCreateInfo createInfo{};
  1658. createInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  1659. createInfo.renderPass = configuration.staticData.renderPass;
  1660. createInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
  1661. createInfo.pAttachments = attachments.data();
  1662. createInfo.width = configuration.staticData.width;
  1663. createInfo.height = configuration.staticData.height;
  1664. createInfo.layers = 1;
  1665. VkFramebuffer frameBuffer;
  1666. if (vkCreateFramebuffer(device, &createInfo, nullptr, &frameBuffer) != VK_SUCCESS)
  1667. throw love::Exception("failed to create framebuffer");
  1668. return frameBuffer;
  1669. }
  1670. VkFramebuffer Graphics::getFramebuffer(FramebufferConfiguration &configuration)
  1671. {
  1672. VkFramebuffer framebuffer;
  1673. auto it = framebuffers.find(configuration);
  1674. if (it != framebuffers.end())
  1675. framebuffer = it->second;
  1676. else
  1677. {
  1678. framebuffer = createFramebuffer(configuration);
  1679. framebuffers[configuration] = framebuffer;
  1680. }
  1681. framebufferUsages[framebuffer] = true;
  1682. return framebuffer;
  1683. }
  1684. void Graphics::createDefaultShaders()
  1685. {
  1686. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++)
  1687. {
  1688. auto stype = (Shader::StandardShader)i;
  1689. if (!Shader::standardShaders[i])
  1690. {
  1691. std::vector<std::string> stages;
  1692. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_VERTEX));
  1693. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_PIXEL));
  1694. Shader::standardShaders[i] = newShader(stages, {});
  1695. }
  1696. }
  1697. }
  1698. VkRenderPass Graphics::createRenderPass(RenderPassConfiguration &configuration)
  1699. {
  1700. VkSubpassDescription subPass{};
  1701. subPass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  1702. std::vector<VkAttachmentDescription> attachments;
  1703. std::vector<VkAttachmentReference> colorAttachmentRefs;
  1704. uint32_t attachment = 0;
  1705. for (const auto &colorAttachment : configuration.colorAttachments)
  1706. {
  1707. VkAttachmentReference reference{};
  1708. reference.attachment = attachment++;
  1709. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1710. colorAttachmentRefs.push_back(reference);
  1711. VkAttachmentDescription colorDescription{};
  1712. colorDescription.format = colorAttachment.format;
  1713. colorDescription.samples = colorAttachment.msaaSamples;
  1714. colorDescription.loadOp = colorAttachment.loadOp;
  1715. colorDescription.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  1716. colorDescription.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1717. colorDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  1718. colorDescription.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1719. colorDescription.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1720. attachments.push_back(colorDescription);
  1721. }
  1722. subPass.colorAttachmentCount = static_cast<uint32_t>(colorAttachmentRefs.size());
  1723. subPass.pColorAttachments = colorAttachmentRefs.data();
  1724. VkAttachmentReference depthStencilAttachmentRef{};
  1725. if (configuration.staticData.depthStencilAttachment.format != VK_FORMAT_UNDEFINED)
  1726. {
  1727. depthStencilAttachmentRef.attachment = attachment++;
  1728. depthStencilAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1729. subPass.pDepthStencilAttachment = &depthStencilAttachmentRef;
  1730. VkAttachmentDescription depthStencilAttachment{};
  1731. depthStencilAttachment.format = configuration.staticData.depthStencilAttachment.format;
  1732. depthStencilAttachment.samples = configuration.staticData.depthStencilAttachment.msaaSamples;
  1733. depthStencilAttachment.loadOp = configuration.staticData.depthStencilAttachment.depthLoadOp;
  1734. depthStencilAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  1735. depthStencilAttachment.stencilLoadOp = configuration.staticData.depthStencilAttachment.stencilLoadOp;
  1736. depthStencilAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  1737. depthStencilAttachment.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1738. depthStencilAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1739. attachments.push_back(depthStencilAttachment);
  1740. }
  1741. VkAttachmentReference colorAttachmentResolveRef{};
  1742. if (configuration.staticData.resolve)
  1743. {
  1744. colorAttachmentResolveRef.attachment = attachment++;
  1745. colorAttachmentResolveRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1746. subPass.pResolveAttachments = &colorAttachmentResolveRef;
  1747. VkAttachmentDescription colorAttachmentResolve{};
  1748. colorAttachmentResolve.format = configuration.colorAttachments.at(0).format;
  1749. colorAttachmentResolve.samples = VK_SAMPLE_COUNT_1_BIT;
  1750. colorAttachmentResolve.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1751. colorAttachmentResolve.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  1752. colorAttachmentResolve.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1753. colorAttachmentResolve.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  1754. colorAttachmentResolve.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1755. colorAttachmentResolve.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1756. attachments.push_back(colorAttachmentResolve);
  1757. }
  1758. VkSubpassDependency dependency{};
  1759. dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
  1760. dependency.dstSubpass = 0;
  1761. dependency.srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
  1762. dependency.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  1763. dependency.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
  1764. dependency.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  1765. VkSubpassDependency readbackDependency{};
  1766. readbackDependency.srcSubpass = 0;
  1767. readbackDependency.dstSubpass = VK_SUBPASS_EXTERNAL;
  1768. readbackDependency.srcStageMask = VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  1769. readbackDependency.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  1770. readbackDependency.dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  1771. readbackDependency.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  1772. std::array<VkSubpassDependency, 2> dependencies = { dependency, readbackDependency };
  1773. VkRenderPassCreateInfo createInfo{};
  1774. createInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  1775. createInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
  1776. createInfo.pAttachments = attachments.data();
  1777. createInfo.subpassCount = 1;
  1778. createInfo.pSubpasses = &subPass;
  1779. createInfo.dependencyCount = static_cast<uint32_t>(dependencies.size());
  1780. createInfo.pDependencies = dependencies.data();
  1781. VkRenderPass renderPass;
  1782. if (vkCreateRenderPass(device, &createInfo, nullptr, &renderPass) != VK_SUCCESS)
  1783. throw love::Exception("failed to create render pass");
  1784. return renderPass;
  1785. }
  1786. VkRenderPass Graphics::getRenderPass(RenderPassConfiguration &configuration)
  1787. {
  1788. VkRenderPass renderPass;
  1789. auto it = renderPasses.find(configuration);
  1790. if (it != renderPasses.end())
  1791. renderPass = it->second;
  1792. else
  1793. {
  1794. renderPass = createRenderPass(configuration);
  1795. renderPasses[configuration] = renderPass;
  1796. }
  1797. renderPassUsages[renderPass] = true;
  1798. return renderPass;
  1799. }
  1800. bool Graphics::usesConstantVertexColor(const VertexAttributes &vertexAttributes)
  1801. {
  1802. return !!(vertexAttributes.enableBits & (1u << ATTRIB_COLOR));
  1803. }
  1804. void Graphics::createVulkanVertexFormat(
  1805. VertexAttributes vertexAttributes,
  1806. std::vector<VkVertexInputBindingDescription> &bindingDescriptions,
  1807. std::vector<VkVertexInputAttributeDescription> &attributeDescriptions)
  1808. {
  1809. std::set<uint32_t> usedBuffers;
  1810. auto enableBits = vertexAttributes.enableBits;
  1811. auto allBits = enableBits;
  1812. bool usesColor = false;
  1813. uint8_t highestBufferBinding = 0;
  1814. uint32_t i = 0;
  1815. while (allBits)
  1816. {
  1817. uint32 bit = 1u << i;
  1818. if (enableBits & bit)
  1819. {
  1820. if (i == ATTRIB_COLOR)
  1821. usesColor = true;
  1822. auto attrib = vertexAttributes.attribs[i];
  1823. auto bufferBinding = attrib.bufferIndex;
  1824. if (usedBuffers.find(bufferBinding) == usedBuffers.end())
  1825. {
  1826. usedBuffers.insert(bufferBinding);
  1827. VkVertexInputBindingDescription bindingDescription{};
  1828. bindingDescription.binding = bufferBinding;
  1829. if (vertexAttributes.instanceBits & (1u << bufferBinding))
  1830. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_INSTANCE;
  1831. else
  1832. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  1833. bindingDescription.stride = vertexAttributes.bufferLayouts[bufferBinding].stride;
  1834. bindingDescriptions.push_back(bindingDescription);
  1835. highestBufferBinding = std::max(highestBufferBinding, bufferBinding);
  1836. }
  1837. VkVertexInputAttributeDescription attributeDescription{};
  1838. attributeDescription.location = i;
  1839. attributeDescription.binding = bufferBinding;
  1840. attributeDescription.offset = attrib.offsetFromVertex;
  1841. attributeDescription.format = Vulkan::getVulkanVertexFormat(attrib.format);
  1842. attributeDescriptions.push_back(attributeDescription);
  1843. }
  1844. i++;
  1845. allBits >>= 1;
  1846. }
  1847. if (!usesColor)
  1848. {
  1849. // FIXME: is there a case where gaps happen between buffer bindings?
  1850. // then this doesn't work. We might need to enable null buffers again.
  1851. const auto constantColorBufferBinding = highestBufferBinding + 1;
  1852. VkVertexInputBindingDescription bindingDescription{};
  1853. bindingDescription.binding = constantColorBufferBinding;
  1854. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  1855. bindingDescription.stride = 0; // no stride, will always read the same color multiple times.
  1856. bindingDescriptions.push_back(bindingDescription);
  1857. VkVertexInputAttributeDescription attributeDescription{};
  1858. attributeDescription.binding = constantColorBufferBinding;
  1859. attributeDescription.location = ATTRIB_COLOR;
  1860. attributeDescription.offset = 0;
  1861. attributeDescription.format = VK_FORMAT_R32G32B32A32_SFLOAT;
  1862. attributeDescriptions.push_back(attributeDescription);
  1863. }
  1864. }
  1865. void Graphics::prepareDraw(const VertexAttributes &attributes, const BufferBindings &buffers, graphics::Texture *texture, PrimitiveType primitiveType, CullMode cullmode)
  1866. {
  1867. if (!renderPassState.active)
  1868. startRenderPass();
  1869. usedShadersInFrame.insert((dynamic_cast<Shader*>(Shader::current)));
  1870. GraphicsPipelineConfiguration configuration{};
  1871. configuration.renderPass = renderPassState.beginInfo.renderPass;
  1872. configuration.vertexAttributes = attributes;
  1873. configuration.shader = (Shader*)Shader::current;
  1874. configuration.wireFrame = states.back().wireframe;
  1875. configuration.blendState = states.back().blend;
  1876. configuration.colorChannelMask = states.back().colorMask;
  1877. configuration.msaaSamples = renderPassState.msaa;
  1878. configuration.numColorAttachments = renderPassState.numColorAttachments;
  1879. configuration.primitiveType = primitiveType;
  1880. if (optionalDeviceExtensions.extendedDynamicState)
  1881. vkCmdSetCullModeEXT(commandBuffers.at(currentFrame), Vulkan::getCullMode(cullmode));
  1882. else
  1883. {
  1884. configuration.dynamicState.winding = states.back().winding;
  1885. configuration.dynamicState.depthState.compare = states.back().depthTest;
  1886. configuration.dynamicState.depthState.write = states.back().depthWrite;
  1887. configuration.dynamicState.stencilAction = states.back().stencil.action;
  1888. configuration.dynamicState.stencilCompare = states.back().stencil.compare;
  1889. configuration.dynamicState.cullmode = cullmode;
  1890. }
  1891. std::vector<VkBuffer> bufferVector;
  1892. std::vector<VkDeviceSize> offsets;
  1893. for (uint32_t i = 0; i < VertexAttributes::MAX; i++)
  1894. {
  1895. if (buffers.useBits & (1u << i))
  1896. {
  1897. bufferVector.push_back((VkBuffer)buffers.info[i].buffer->getHandle());
  1898. offsets.push_back((VkDeviceSize)buffers.info[i].offset);
  1899. }
  1900. }
  1901. if (!usesConstantVertexColor(attributes))
  1902. {
  1903. bufferVector.push_back((VkBuffer)defaultConstantColor->getHandle());
  1904. offsets.push_back((VkDeviceSize)0);
  1905. }
  1906. if (texture == nullptr)
  1907. configuration.shader->setMainTex(defaultTexture);
  1908. else
  1909. configuration.shader->setMainTex(texture);
  1910. ensureGraphicsPipelineConfiguration(configuration);
  1911. configuration.shader->cmdPushDescriptorSets(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_GRAPHICS);
  1912. vkCmdBindVertexBuffers(commandBuffers.at(currentFrame), 0, static_cast<uint32_t>(bufferVector.size()), bufferVector.data(), offsets.data());
  1913. }
  1914. void Graphics::setDefaultRenderPass()
  1915. {
  1916. uint32_t numClearValues = 2;
  1917. renderPassState.clearColors.resize(numClearValues);
  1918. renderPassState.beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  1919. renderPassState.beginInfo.renderPass = VK_NULL_HANDLE;
  1920. renderPassState.beginInfo.framebuffer = VK_NULL_HANDLE;
  1921. renderPassState.beginInfo.renderArea.offset = { 0, 0 };
  1922. renderPassState.beginInfo.renderArea.extent = swapChainExtent;
  1923. renderPassState.beginInfo.clearValueCount = numClearValues;
  1924. renderPassState.beginInfo.pClearValues = renderPassState.clearColors.data();
  1925. renderPassState.isWindow = true;
  1926. renderPassState.pipeline = VK_NULL_HANDLE;
  1927. renderPassState.width = static_cast<float>(swapChainExtent.width);
  1928. renderPassState.height = static_cast<float>(swapChainExtent.height);
  1929. renderPassState.msaa = msaaSamples;
  1930. renderPassState.numColorAttachments = 1;
  1931. renderPassState.transitionImages.clear();
  1932. RenderPassConfiguration renderPassConfiguration{};
  1933. renderPassConfiguration.colorAttachments.push_back({ swapChainImageFormat, VK_ATTACHMENT_LOAD_OP_LOAD, msaaSamples });
  1934. renderPassConfiguration.staticData.depthStencilAttachment = { depthStencilFormat, VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_LOAD_OP_LOAD, msaaSamples };
  1935. if (msaaSamples & VK_SAMPLE_COUNT_1_BIT)
  1936. renderPassConfiguration.staticData.resolve = false;
  1937. else
  1938. renderPassConfiguration.staticData.resolve = true;
  1939. FramebufferConfiguration framebufferConfiguration{};
  1940. framebufferConfiguration.staticData.depthView = depthImageView;
  1941. framebufferConfiguration.staticData.width = swapChainExtent.width;
  1942. framebufferConfiguration.staticData.height = swapChainExtent.height;
  1943. if (msaaSamples & VK_SAMPLE_COUNT_1_BIT)
  1944. {
  1945. framebufferConfiguration.colorViews.push_back(swapChainImageViews.at(imageIndex));
  1946. framebufferConfiguration.staticData.resolveView = VK_NULL_HANDLE;
  1947. }
  1948. else
  1949. {
  1950. framebufferConfiguration.colorViews.push_back(colorImageView);
  1951. framebufferConfiguration.staticData.resolveView = swapChainImageViews.at(imageIndex);
  1952. }
  1953. renderPassState.renderPassConfiguration = std::move(renderPassConfiguration);
  1954. renderPassState.framebufferConfiguration = std::move(framebufferConfiguration);
  1955. if (renderPassState.windowClearRequested)
  1956. clear(renderPassState.mainWindowClearColorValue, renderPassState.mainWindowClearStencilValue, renderPassState.mainWindowClearDepthValue);
  1957. }
  1958. void Graphics::setRenderPass(const RenderTargets &rts, int pixelw, int pixelh, bool hasSRGBtexture)
  1959. {
  1960. // fixme: hasSRGBtexture
  1961. RenderPassConfiguration renderPassConfiguration{};
  1962. for (const auto &color : rts.colors)
  1963. renderPassConfiguration.colorAttachments.push_back({
  1964. Vulkan::getTextureFormat(color.texture->getPixelFormat(), isPixelFormatSRGB(color.texture->getPixelFormat())).internalFormat,
  1965. VK_ATTACHMENT_LOAD_OP_LOAD,
  1966. dynamic_cast<Texture*>(color.texture)->getMsaaSamples() });
  1967. if (rts.depthStencil.texture != nullptr)
  1968. renderPassConfiguration.staticData.depthStencilAttachment = {
  1969. Vulkan::getTextureFormat(rts.depthStencil.texture->getPixelFormat(), false).internalFormat,
  1970. VK_ATTACHMENT_LOAD_OP_LOAD,
  1971. VK_ATTACHMENT_LOAD_OP_LOAD,
  1972. dynamic_cast<Texture*>(rts.depthStencil.texture)->getMsaaSamples() };
  1973. FramebufferConfiguration configuration{};
  1974. std::vector<VkImage> transitionImages;
  1975. for (const auto &color : rts.colors)
  1976. {
  1977. configuration.colorViews.push_back(dynamic_cast<Texture*>(color.texture)->getRenderTargetView(color.mipmap, color.slice));
  1978. transitionImages.push_back((VkImage) color.texture->getHandle());
  1979. }
  1980. if (rts.depthStencil.texture != nullptr)
  1981. configuration.staticData.depthView = dynamic_cast<Texture*>(rts.depthStencil.texture)->getRenderTargetView(rts.depthStencil.mipmap, rts.depthStencil.slice);
  1982. configuration.staticData.width = static_cast<uint32_t>(pixelw);
  1983. configuration.staticData.height = static_cast<uint32_t>(pixelh);
  1984. uint32_t numClearValues = static_cast<uint32_t>(rts.colors.size() + 1);
  1985. renderPassState.clearColors.resize(numClearValues);
  1986. renderPassState.beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  1987. renderPassState.beginInfo.renderPass = VK_NULL_HANDLE;
  1988. renderPassState.beginInfo.framebuffer = VK_NULL_HANDLE;
  1989. renderPassState.beginInfo.renderArea.offset = {0, 0};
  1990. renderPassState.beginInfo.renderArea.extent.width = static_cast<uint32_t>(pixelw);
  1991. renderPassState.beginInfo.renderArea.extent.height = static_cast<uint32_t>(pixelh);
  1992. renderPassState.beginInfo.clearValueCount = numClearValues;
  1993. renderPassState.beginInfo.pClearValues = renderPassState.clearColors.data();
  1994. renderPassState.isWindow = false;
  1995. renderPassState.renderPassConfiguration = renderPassConfiguration;
  1996. renderPassState.framebufferConfiguration = configuration;
  1997. renderPassState.pipeline = VK_NULL_HANDLE;
  1998. renderPassState.width = static_cast<float>(pixelw);
  1999. renderPassState.height = static_cast<float>(pixelh);
  2000. renderPassState.msaa = VK_SAMPLE_COUNT_1_BIT;
  2001. renderPassState.numColorAttachments = static_cast<uint32_t>(rts.colors.size());
  2002. renderPassState.transitionImages = std::move(transitionImages);
  2003. }
  2004. void Graphics::startRenderPass()
  2005. {
  2006. renderPassState.active = true;
  2007. if (renderPassState.isWindow && renderPassState.windowClearRequested)
  2008. renderPassState.windowClearRequested = false;
  2009. VkViewport viewport{};
  2010. viewport.x = 0.0f;
  2011. viewport.y = 0.0f;
  2012. viewport.width = renderPassState.width;
  2013. viewport.height = renderPassState.height;
  2014. viewport.minDepth = 0.0f;
  2015. viewport.maxDepth = 1.0f;
  2016. vkCmdSetViewport(commandBuffers.at(currentFrame), 0, 1, &viewport);
  2017. renderPassState.beginInfo.renderPass = getRenderPass(renderPassState.renderPassConfiguration);
  2018. renderPassState.framebufferConfiguration.staticData.renderPass = renderPassState.beginInfo.renderPass;
  2019. renderPassState.beginInfo.framebuffer = getFramebuffer(renderPassState.framebufferConfiguration);
  2020. for (const auto &image : renderPassState.transitionImages)
  2021. Vulkan::cmdTransitionImageLayout(commandBuffers.at(currentFrame), image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2022. vkCmdBeginRenderPass(commandBuffers.at(currentFrame), &renderPassState.beginInfo, VK_SUBPASS_CONTENTS_INLINE);
  2023. }
  2024. void Graphics::endRenderPass()
  2025. {
  2026. renderPassState.active = false;
  2027. vkCmdEndRenderPass(commandBuffers.at(currentFrame));
  2028. for (const auto &image : renderPassState.transitionImages)
  2029. Vulkan::cmdTransitionImageLayout(commandBuffers.at(currentFrame), image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
  2030. for (auto &colorAttachment : renderPassState.renderPassConfiguration.colorAttachments)
  2031. colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2032. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.depthLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2033. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2034. }
  2035. VkSampler Graphics::createSampler(const SamplerState &samplerState)
  2036. {
  2037. VkSamplerCreateInfo samplerInfo{};
  2038. samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  2039. samplerInfo.magFilter = Vulkan::getFilter(samplerState.magFilter);
  2040. samplerInfo.minFilter = Vulkan::getFilter(samplerState.minFilter);
  2041. samplerInfo.addressModeU = Vulkan::getWrapMode(samplerState.wrapU);
  2042. samplerInfo.addressModeV = Vulkan::getWrapMode(samplerState.wrapV);
  2043. samplerInfo.addressModeW = Vulkan::getWrapMode(samplerState.wrapW);
  2044. samplerInfo.anisotropyEnable = VK_TRUE;
  2045. samplerInfo.maxAnisotropy = static_cast<float>(samplerState.maxAnisotropy);
  2046. // TODO: This probably needs to branch on a pixel format to determine whether
  2047. // it should be float vs int, and opaque vs transparent.
  2048. bool clampone = samplerState.wrapU == SamplerState::WRAP_CLAMP_ONE
  2049. || samplerState.wrapV == SamplerState::WRAP_CLAMP_ONE
  2050. || samplerState.wrapW == SamplerState::WRAP_CLAMP_ONE;
  2051. samplerInfo.borderColor = clampone ? VK_BORDER_COLOR_INT_OPAQUE_WHITE : VK_BORDER_COLOR_INT_OPAQUE_BLACK;
  2052. samplerInfo.unnormalizedCoordinates = VK_FALSE;
  2053. if (samplerState.depthSampleMode.hasValue)
  2054. {
  2055. samplerInfo.compareEnable = VK_TRUE;
  2056. samplerInfo.compareOp = Vulkan::getCompareOp(samplerState.depthSampleMode.value);
  2057. }
  2058. else
  2059. {
  2060. samplerInfo.compareEnable = VK_FALSE;
  2061. samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
  2062. }
  2063. samplerInfo.compareEnable = VK_FALSE;
  2064. samplerInfo.mipmapMode = Vulkan::getMipMapMode(samplerState.mipmapFilter);
  2065. samplerInfo.mipLodBias = samplerState.lodBias;
  2066. samplerInfo.minLod = static_cast<float>(samplerState.minLod);
  2067. samplerInfo.maxLod = static_cast<float>(samplerState.maxLod);
  2068. VkSampler sampler;
  2069. if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS)
  2070. throw love::Exception("failed to create sampler");
  2071. return sampler;
  2072. }
  2073. template<typename Configuration, typename ObjectHandle, typename ConfigurationHasher, typename Deleter>
  2074. static void eraseUnusedObjects(
  2075. std::unordered_map<Configuration, ObjectHandle, ConfigurationHasher> &objects,
  2076. std::unordered_map<ObjectHandle, bool> &usages,
  2077. Deleter deleter,
  2078. VkDevice device)
  2079. {
  2080. std::vector<Configuration> deletionKeys;
  2081. for (const auto &entry : objects)
  2082. {
  2083. if (!usages[entry.second])
  2084. {
  2085. deletionKeys.push_back(entry.first);
  2086. usages.erase(entry.second);
  2087. deleter(device, entry.second, nullptr);
  2088. }
  2089. else
  2090. usages[entry.second] = false;
  2091. }
  2092. for (const auto &key : deletionKeys)
  2093. objects.erase(key);
  2094. }
  2095. void Graphics::cleanupUnusedObjects()
  2096. {
  2097. eraseUnusedObjects(renderPasses, renderPassUsages, vkDestroyRenderPass, device);
  2098. eraseUnusedObjects(framebuffers, framebufferUsages, vkDestroyFramebuffer, device);
  2099. eraseUnusedObjects(graphicsPipelines, pipelineUsages, vkDestroyPipeline, device);
  2100. }
  2101. void Graphics::requestSwapchainRecreation()
  2102. {
  2103. if (swapChain != VK_NULL_HANDLE)
  2104. {
  2105. swapChainRecreationRequested = true;
  2106. }
  2107. }
  2108. void Graphics::setComputeShader(Shader *shader)
  2109. {
  2110. computeShader = shader;
  2111. }
  2112. VkSampler Graphics::getCachedSampler(const SamplerState &samplerState)
  2113. {
  2114. auto samplerkey = samplerState.toKey();
  2115. auto it = samplers.find(samplerkey);
  2116. if (it != samplers.end())
  2117. return it->second;
  2118. else
  2119. {
  2120. VkSampler sampler = createSampler(samplerState);
  2121. samplers.insert({ samplerkey, sampler });
  2122. return sampler;
  2123. }
  2124. }
  2125. VkPipeline Graphics::createGraphicsPipeline(GraphicsPipelineConfiguration &configuration)
  2126. {
  2127. VkGraphicsPipelineCreateInfo pipelineInfo{};
  2128. pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  2129. auto &shaderStages = configuration.shader->getShaderStages();
  2130. std::vector<VkVertexInputBindingDescription> bindingDescriptions;
  2131. std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
  2132. createVulkanVertexFormat(configuration.vertexAttributes, bindingDescriptions, attributeDescriptions);
  2133. VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
  2134. vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  2135. vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(bindingDescriptions.size());
  2136. vertexInputInfo.pVertexBindingDescriptions = bindingDescriptions.data();
  2137. vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
  2138. vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data();
  2139. VkPipelineViewportStateCreateInfo viewportState{};
  2140. viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  2141. viewportState.viewportCount = 1;
  2142. viewportState.scissorCount = 1;
  2143. VkPipelineMultisampleStateCreateInfo multisampling{};
  2144. multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  2145. multisampling.sampleShadingEnable = VK_FALSE;
  2146. multisampling.rasterizationSamples = configuration.msaaSamples;
  2147. VkPipelineRasterizationStateCreateInfo rasterizer{};
  2148. rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  2149. rasterizer.depthClampEnable = VK_FALSE;
  2150. rasterizer.rasterizerDiscardEnable = VK_FALSE;
  2151. rasterizer.polygonMode = Vulkan::getPolygonMode(configuration.wireFrame);
  2152. rasterizer.lineWidth = 1.0f;
  2153. if (!optionalDeviceExtensions.extendedDynamicState)
  2154. {
  2155. rasterizer.cullMode = Vulkan::getCullMode(configuration.dynamicState.cullmode);
  2156. rasterizer.frontFace = Vulkan::getFrontFace(configuration.dynamicState.winding);
  2157. }
  2158. rasterizer.depthBiasEnable = VK_FALSE;
  2159. rasterizer.depthBiasConstantFactor = 0.0f;
  2160. rasterizer.depthBiasClamp = 0.0f;
  2161. rasterizer.depthBiasSlopeFactor = 0.0f;
  2162. VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
  2163. inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  2164. inputAssembly.topology = Vulkan::getPrimitiveTypeTopology(configuration.primitiveType);
  2165. inputAssembly.primitiveRestartEnable = VK_FALSE;
  2166. VkPipelineDepthStencilStateCreateInfo depthStencil{};
  2167. depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  2168. depthStencil.depthTestEnable = VK_TRUE;
  2169. if (!optionalDeviceExtensions.extendedDynamicState)
  2170. {
  2171. depthStencil.depthWriteEnable = Vulkan::getBool(configuration.dynamicState.depthState.write);
  2172. depthStencil.depthCompareOp = Vulkan::getCompareOp(configuration.dynamicState.depthState.compare);
  2173. }
  2174. depthStencil.depthBoundsTestEnable = VK_FALSE;
  2175. depthStencil.minDepthBounds = 0.0f;
  2176. depthStencil.maxDepthBounds = 1.0f;
  2177. depthStencil.stencilTestEnable = VK_TRUE;
  2178. if (!optionalDeviceExtensions.extendedDynamicState)
  2179. {
  2180. depthStencil.front.failOp = VK_STENCIL_OP_KEEP;
  2181. depthStencil.front.passOp = Vulkan::getStencilOp(configuration.dynamicState.stencilAction);
  2182. depthStencil.front.depthFailOp = VK_STENCIL_OP_KEEP;
  2183. depthStencil.front.compareOp = Vulkan::getCompareOp(getReversedCompareMode(configuration.dynamicState.stencilCompare));
  2184. depthStencil.back.failOp = VK_STENCIL_OP_KEEP;
  2185. depthStencil.back.passOp = Vulkan::getStencilOp(configuration.dynamicState.stencilAction);
  2186. depthStencil.back.depthFailOp = VK_STENCIL_OP_KEEP;
  2187. depthStencil.back.compareOp = Vulkan::getCompareOp(getReversedCompareMode(configuration.dynamicState.stencilCompare));
  2188. }
  2189. pipelineInfo.pDepthStencilState = &depthStencil;
  2190. VkPipelineColorBlendAttachmentState colorBlendAttachment{};
  2191. colorBlendAttachment.colorWriteMask = Vulkan::getColorMask(configuration.colorChannelMask);
  2192. colorBlendAttachment.blendEnable = Vulkan::getBool(configuration.blendState.enable);
  2193. colorBlendAttachment.srcColorBlendFactor = Vulkan::getBlendFactor(configuration.blendState.srcFactorRGB);
  2194. colorBlendAttachment.dstColorBlendFactor = Vulkan::getBlendFactor(configuration.blendState.dstFactorRGB);
  2195. colorBlendAttachment.colorBlendOp = Vulkan::getBlendOp(configuration.blendState.operationRGB);
  2196. colorBlendAttachment.srcAlphaBlendFactor = Vulkan::getBlendFactor(configuration.blendState.srcFactorA);
  2197. colorBlendAttachment.dstAlphaBlendFactor = Vulkan::getBlendFactor(configuration.blendState.dstFactorA);
  2198. colorBlendAttachment.alphaBlendOp = Vulkan::getBlendOp(configuration.blendState.operationA);
  2199. std::vector<VkPipelineColorBlendAttachmentState> colorBlendAttachments(configuration.numColorAttachments, colorBlendAttachment);
  2200. VkPipelineColorBlendStateCreateInfo colorBlending{};
  2201. colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  2202. colorBlending.logicOpEnable = VK_FALSE;
  2203. colorBlending.logicOp = VK_LOGIC_OP_COPY;
  2204. colorBlending.attachmentCount = static_cast<uint32_t>(colorBlendAttachments.size());
  2205. colorBlending.pAttachments = colorBlendAttachments.data();
  2206. colorBlending.blendConstants[0] = 0.0f;
  2207. colorBlending.blendConstants[1] = 0.0f;
  2208. colorBlending.blendConstants[2] = 0.0f;
  2209. colorBlending.blendConstants[3] = 0.0f;
  2210. std::vector<VkDynamicState> dynamicStates;
  2211. if (optionalDeviceExtensions.extendedDynamicState)
  2212. dynamicStates = {
  2213. VK_DYNAMIC_STATE_SCISSOR,
  2214. VK_DYNAMIC_STATE_VIEWPORT,
  2215. VK_DYNAMIC_STATE_STENCIL_WRITE_MASK,
  2216. VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK,
  2217. VK_DYNAMIC_STATE_STENCIL_REFERENCE,
  2218. VK_DYNAMIC_STATE_CULL_MODE_EXT,
  2219. VK_DYNAMIC_STATE_FRONT_FACE_EXT,
  2220. VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE_EXT,
  2221. VK_DYNAMIC_STATE_DEPTH_COMPARE_OP_EXT,
  2222. VK_DYNAMIC_STATE_STENCIL_OP_EXT,
  2223. };
  2224. else
  2225. dynamicStates = {
  2226. VK_DYNAMIC_STATE_SCISSOR,
  2227. VK_DYNAMIC_STATE_VIEWPORT,
  2228. VK_DYNAMIC_STATE_STENCIL_WRITE_MASK,
  2229. VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK,
  2230. VK_DYNAMIC_STATE_STENCIL_REFERENCE,
  2231. };
  2232. VkPipelineDynamicStateCreateInfo dynamicState{};
  2233. dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  2234. dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size());
  2235. dynamicState.pDynamicStates = dynamicStates.data();
  2236. pipelineInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
  2237. pipelineInfo.pStages = shaderStages.data();
  2238. pipelineInfo.pVertexInputState = &vertexInputInfo;
  2239. pipelineInfo.pInputAssemblyState = &inputAssembly;
  2240. pipelineInfo.pViewportState = &viewportState;
  2241. pipelineInfo.pRasterizationState = &rasterizer;
  2242. pipelineInfo.pMultisampleState = &multisampling;
  2243. pipelineInfo.pColorBlendState = &colorBlending;
  2244. pipelineInfo.pDynamicState = &dynamicState;
  2245. pipelineInfo.layout = configuration.shader->getGraphicsPipelineLayout();
  2246. pipelineInfo.subpass = 0;
  2247. pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
  2248. pipelineInfo.basePipelineIndex = -1;
  2249. pipelineInfo.renderPass = configuration.renderPass;
  2250. VkPipeline graphicsPipeline;
  2251. if (vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS)
  2252. throw love::Exception("failed to create graphics pipeline");
  2253. return graphicsPipeline;
  2254. }
  2255. void Graphics::ensureGraphicsPipelineConfiguration(GraphicsPipelineConfiguration &configuration) {
  2256. auto it = graphicsPipelines.find(configuration);
  2257. if (it != graphicsPipelines.end())
  2258. {
  2259. if (it->second != renderPassState.pipeline)
  2260. {
  2261. vkCmdBindPipeline(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_GRAPHICS, it->second);
  2262. renderPassState.pipeline = it->second;
  2263. pipelineUsages[it->second] = true;
  2264. }
  2265. }
  2266. else
  2267. {
  2268. VkPipeline pipeline = createGraphicsPipeline(configuration);
  2269. graphicsPipelines.insert({configuration, pipeline});
  2270. vkCmdBindPipeline(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
  2271. renderPassState.pipeline = pipeline;
  2272. pipelineUsages[pipeline] = true;
  2273. }
  2274. }
  2275. VkSampleCountFlagBits Graphics::getMsaaCount(int requestedMsaa) const
  2276. {
  2277. VkPhysicalDeviceProperties physicalDeviceProperties;
  2278. vkGetPhysicalDeviceProperties(physicalDevice, &physicalDeviceProperties);
  2279. VkSampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts & physicalDeviceProperties.limits.framebufferDepthSampleCounts;
  2280. if (counts & VK_SAMPLE_COUNT_64_BIT && requestedMsaa >= 64)
  2281. return VK_SAMPLE_COUNT_64_BIT;
  2282. else if (counts & VK_SAMPLE_COUNT_32_BIT && requestedMsaa >= 32)
  2283. return VK_SAMPLE_COUNT_32_BIT;
  2284. else if (counts & VK_SAMPLE_COUNT_16_BIT && requestedMsaa >= 16)
  2285. return VK_SAMPLE_COUNT_16_BIT;
  2286. else if (counts & VK_SAMPLE_COUNT_8_BIT && requestedMsaa >= 8)
  2287. return VK_SAMPLE_COUNT_8_BIT;
  2288. else if (counts & VK_SAMPLE_COUNT_4_BIT && requestedMsaa >= 4)
  2289. return VK_SAMPLE_COUNT_4_BIT;
  2290. else if (counts & VK_SAMPLE_COUNT_2_BIT && requestedMsaa >= 2)
  2291. return VK_SAMPLE_COUNT_2_BIT;
  2292. else
  2293. return VK_SAMPLE_COUNT_1_BIT;
  2294. }
  2295. void Graphics::setVsync(int vsync)
  2296. {
  2297. if (vsync != this->vsync)
  2298. {
  2299. this->vsync = vsync;
  2300. // With the extension VK_EXT_swapchain_maintenance1 a swapchain recreation might not be needed
  2301. // https://github.com/KhronosGroup/Vulkan-Docs/blob/main/proposals/VK_EXT_swapchain_maintenance1.adoc
  2302. // However, there are not any drivers that support it, yet.
  2303. // Reevaluate again in the future.
  2304. requestSwapchainRecreation();
  2305. }
  2306. }
  2307. int Graphics::getVsync() const
  2308. {
  2309. return vsync;
  2310. }
  2311. void Graphics::createColorResources()
  2312. {
  2313. if (msaaSamples & VK_SAMPLE_COUNT_1_BIT)
  2314. {
  2315. colorImage = VK_NULL_HANDLE;
  2316. colorImageView = VK_NULL_HANDLE;
  2317. }
  2318. else
  2319. {
  2320. VkFormat colorFormat = swapChainImageFormat;
  2321. VkImageCreateInfo imageInfo{};
  2322. imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  2323. imageInfo.imageType = VK_IMAGE_TYPE_2D;
  2324. imageInfo.format = colorFormat;
  2325. imageInfo.extent.width = swapChainExtent.width;
  2326. imageInfo.extent.height = swapChainExtent.height;
  2327. imageInfo.extent.depth = 1;
  2328. imageInfo.mipLevels = 1;
  2329. imageInfo.arrayLayers = 1;
  2330. imageInfo.samples = msaaSamples;
  2331. imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  2332. imageInfo.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  2333. imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  2334. imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2335. VmaAllocationCreateInfo allocationInfo{};
  2336. allocationInfo.usage = VMA_MEMORY_USAGE_AUTO;
  2337. allocationInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  2338. if (vmaCreateImage(vmaAllocator, &imageInfo, &allocationInfo, &colorImage, &colorImageAllocation, nullptr))
  2339. throw love::Exception("failed to create color image");
  2340. VkImageViewCreateInfo imageViewInfo{};
  2341. imageViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  2342. imageViewInfo.image = colorImage;
  2343. imageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  2344. imageViewInfo.format = colorFormat;
  2345. imageViewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  2346. imageViewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  2347. imageViewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  2348. imageViewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  2349. imageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2350. imageViewInfo.subresourceRange.baseMipLevel = 0;
  2351. imageViewInfo.subresourceRange.levelCount = 1;
  2352. imageViewInfo.subresourceRange.baseArrayLayer = 0;
  2353. imageViewInfo.subresourceRange.layerCount = 1;
  2354. if (vkCreateImageView(device, &imageViewInfo, nullptr, &colorImageView) != VK_SUCCESS)
  2355. throw love::Exception("failed to create color image view");
  2356. }
  2357. }
  2358. VkFormat Graphics::findSupportedFormat(const std::vector<VkFormat> &candidates, VkImageTiling tiling, VkFormatFeatureFlags features)
  2359. {
  2360. for (auto format : candidates)
  2361. {
  2362. VkFormatProperties properties;
  2363. vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &properties);
  2364. if (tiling == VK_IMAGE_TILING_LINEAR && (properties.linearTilingFeatures & features) == features)
  2365. return format;
  2366. else if (tiling == VK_IMAGE_TILING_OPTIMAL && (properties.optimalTilingFeatures & features) == features)
  2367. return format;
  2368. }
  2369. throw love::Exception("failed to find supported format");
  2370. }
  2371. VkFormat Graphics::findDepthFormat()
  2372. {
  2373. return findSupportedFormat(
  2374. { VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
  2375. VK_IMAGE_TILING_OPTIMAL,
  2376. VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
  2377. );
  2378. }
  2379. void Graphics::createDepthResources()
  2380. {
  2381. VkImageCreateInfo imageInfo{};
  2382. imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  2383. imageInfo.imageType = VK_IMAGE_TYPE_2D;
  2384. imageInfo.format = depthStencilFormat;
  2385. imageInfo.extent.width = swapChainExtent.width;
  2386. imageInfo.extent.height = swapChainExtent.height;
  2387. imageInfo.extent.depth = 1;
  2388. imageInfo.mipLevels = 1;
  2389. imageInfo.arrayLayers = 1;
  2390. imageInfo.samples = msaaSamples;
  2391. imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  2392. imageInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  2393. imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  2394. imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2395. VmaAllocationCreateInfo allocationInfo{};
  2396. allocationInfo.usage = VMA_MEMORY_USAGE_AUTO;
  2397. allocationInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  2398. if (vmaCreateImage(vmaAllocator, &imageInfo, &allocationInfo, &depthImage, &depthImageAllocation, nullptr) != VK_SUCCESS)
  2399. throw love::Exception("failed to create depth image");
  2400. VkImageViewCreateInfo imageViewInfo{};
  2401. imageViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  2402. imageViewInfo.image = depthImage;
  2403. imageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  2404. imageViewInfo.format = depthStencilFormat;
  2405. imageViewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  2406. imageViewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  2407. imageViewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  2408. imageViewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  2409. imageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  2410. if (windowHasStencil)
  2411. imageViewInfo.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  2412. imageViewInfo.subresourceRange.baseMipLevel = 0;
  2413. imageViewInfo.subresourceRange.levelCount = 1;
  2414. imageViewInfo.subresourceRange.baseArrayLayer = 0;
  2415. imageViewInfo.subresourceRange.layerCount = 1;
  2416. if (vkCreateImageView(device, &imageViewInfo, nullptr, &depthImageView) != VK_SUCCESS)
  2417. throw love::Exception("failed to create depth image view");
  2418. }
  2419. void Graphics::createCommandPool()
  2420. {
  2421. QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
  2422. VkCommandPoolCreateInfo poolInfo{};
  2423. poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  2424. poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value;
  2425. poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
  2426. if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS)
  2427. throw love::Exception("failed to create command pool");
  2428. }
  2429. void Graphics::createCommandBuffers()
  2430. {
  2431. commandBuffers.resize(MAX_FRAMES_IN_FLIGHT);
  2432. VkCommandBufferAllocateInfo allocInfo{};
  2433. allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  2434. allocInfo.commandPool = commandPool;
  2435. allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  2436. allocInfo.commandBufferCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
  2437. if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS)
  2438. throw love::Exception("failed to allocate command buffers");
  2439. }
  2440. void Graphics::createSyncObjects()
  2441. {
  2442. imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  2443. renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  2444. inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
  2445. imagesInFlight.resize(swapChainImages.size(), VK_NULL_HANDLE);
  2446. VkSemaphoreCreateInfo semaphoreInfo{};
  2447. semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  2448. VkFenceCreateInfo fenceInfo{};
  2449. fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  2450. fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  2451. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
  2452. if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores.at(i)) != VK_SUCCESS ||
  2453. vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores.at(i)) != VK_SUCCESS ||
  2454. vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences.at(i)) != VK_SUCCESS)
  2455. throw love::Exception("failed to create synchronization objects for a frame!");
  2456. }
  2457. void Graphics::createDefaultTexture()
  2458. {
  2459. Texture::Settings settings;
  2460. defaultTexture.set(newTexture(settings, nullptr), Acquire::NORETAIN);
  2461. uint8_t whitePixels[] = {255, 255, 255, 255};
  2462. defaultTexture->replacePixels(whitePixels, sizeof(whitePixels), 0, 0, { 0, 0, 1, 1 }, false);
  2463. }
  2464. void Graphics::cleanup()
  2465. {
  2466. cleanupSwapChain();
  2467. for (auto &cleanUpFns : cleanUpFunctions)
  2468. for (auto &cleanUpFn : cleanUpFns)
  2469. cleanUpFn();
  2470. cleanUpFunctions.clear();
  2471. vmaDestroyAllocator(vmaAllocator);
  2472. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
  2473. {
  2474. vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
  2475. vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
  2476. vkDestroyFence(device, inFlightFences[i], nullptr);
  2477. }
  2478. vkFreeCommandBuffers(device, commandPool, MAX_FRAMES_IN_FLIGHT, commandBuffers.data());
  2479. for (auto const &p : samplers)
  2480. vkDestroySampler(device, p.second, nullptr);
  2481. samplers.clear();
  2482. for (const auto &entry : renderPasses)
  2483. vkDestroyRenderPass(device, entry.second, nullptr);
  2484. renderPasses.clear();
  2485. for (const auto &entry : framebuffers)
  2486. vkDestroyFramebuffer(device, entry.second, nullptr);
  2487. framebuffers.clear();
  2488. for (auto const &p : graphicsPipelines)
  2489. vkDestroyPipeline(device, p.second, nullptr);
  2490. graphicsPipelines.clear();
  2491. vkDestroyCommandPool(device, commandPool, nullptr);
  2492. vkDestroyPipelineCache(device, pipelineCache, nullptr);
  2493. vkDestroyDevice(device, nullptr);
  2494. vkDestroySurfaceKHR(instance, surface, nullptr);
  2495. vkDestroyInstance(instance, nullptr);
  2496. }
  2497. void Graphics::cleanupSwapChain()
  2498. {
  2499. for (const auto &readbackBuffer : screenshotReadbackBuffers)
  2500. {
  2501. vmaDestroyBuffer(vmaAllocator, readbackBuffer.buffer, readbackBuffer.allocation);
  2502. vmaDestroyImage(vmaAllocator, readbackBuffer.image, readbackBuffer.imageAllocation);
  2503. }
  2504. vkDestroyImageView(device, colorImageView, nullptr);
  2505. vmaDestroyImage(vmaAllocator, colorImage, colorImageAllocation);
  2506. vkDestroyImageView(device, depthImageView, nullptr);
  2507. vmaDestroyImage(vmaAllocator, depthImage, depthImageAllocation);
  2508. for (const auto &swapChainImageView : swapChainImageViews)
  2509. vkDestroyImageView(device, swapChainImageView, nullptr);
  2510. swapChainImageViews.clear();
  2511. vkDestroySwapchainKHR(device, swapChain, nullptr);
  2512. swapChain = VK_NULL_HANDLE;
  2513. }
  2514. void Graphics::recreateSwapChain()
  2515. {
  2516. vkDeviceWaitIdle(device);
  2517. cleanupSwapChain();
  2518. createSwapChain();
  2519. createImageViews();
  2520. createScreenshotCallbackBuffers();
  2521. createColorResources();
  2522. createDepthResources();
  2523. transitionColorDepthLayouts = true;
  2524. }
  2525. love::graphics::Graphics *createInstance()
  2526. {
  2527. love::graphics::Graphics *instance = nullptr;
  2528. try
  2529. {
  2530. instance = new Graphics();
  2531. }
  2532. catch (love::Exception &e)
  2533. {
  2534. printf("Cannot create Vulkan renderer: %s\n", e.what());
  2535. }
  2536. return instance;
  2537. }
  2538. } // vulkan
  2539. } // graphics
  2540. } // love