Graphics.cpp 105 KB

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