Graphics.cpp 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158
  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_LIGHTEN] = true;
  601. capabilities.features[FEATURE_FULL_NPOT] = true;
  602. capabilities.features[FEATURE_PIXEL_SHADER_HIGHP] = true;
  603. capabilities.features[FEATURE_SHADER_DERIVATIVES] = true;
  604. capabilities.features[FEATURE_GLSL3] = true;
  605. capabilities.features[FEATURE_GLSL4] = true;
  606. capabilities.features[FEATURE_INSTANCING] = true;
  607. capabilities.features[FEATURE_TEXEL_BUFFER] = true;
  608. capabilities.features[FEATURE_COPY_TEXTURE_TO_BUFFER] = true;
  609. capabilities.features[FEATURE_INDIRECT_DRAW] = true;
  610. static_assert(FEATURE_MAX_ENUM == 13, "Graphics::initCapabilities must be updated when adding a new graphics feature!");
  611. VkPhysicalDeviceProperties properties;
  612. vkGetPhysicalDeviceProperties(physicalDevice, &properties);
  613. capabilities.limits[LIMIT_POINT_SIZE] = properties.limits.pointSizeRange[1];
  614. capabilities.limits[LIMIT_TEXTURE_SIZE] = properties.limits.maxImageDimension2D;
  615. capabilities.limits[LIMIT_TEXTURE_LAYERS] = properties.limits.maxImageArrayLayers;
  616. capabilities.limits[LIMIT_VOLUME_TEXTURE_SIZE] = properties.limits.maxImageDimension3D;
  617. capabilities.limits[LIMIT_CUBE_TEXTURE_SIZE] = properties.limits.maxImageDimensionCube;
  618. capabilities.limits[LIMIT_TEXEL_BUFFER_SIZE] = properties.limits.maxTexelBufferElements;
  619. capabilities.limits[LIMIT_SHADER_STORAGE_BUFFER_SIZE] = properties.limits.maxStorageBufferRange;
  620. capabilities.limits[LIMIT_THREADGROUPS_X] = properties.limits.maxComputeWorkGroupCount[0];
  621. capabilities.limits[LIMIT_THREADGROUPS_Y] = properties.limits.maxComputeWorkGroupCount[1];
  622. capabilities.limits[LIMIT_THREADGROUPS_Z] = properties.limits.maxComputeWorkGroupCount[2];
  623. capabilities.limits[LIMIT_RENDER_TARGETS] = properties.limits.maxColorAttachments;
  624. capabilities.limits[LIMIT_TEXTURE_MSAA] = static_cast<double>(getMsaaCount(64));
  625. capabilities.limits[LIMIT_ANISOTROPY] = properties.limits.maxSamplerAnisotropy;
  626. static_assert(LIMIT_MAX_ENUM == 13, "Graphics::initCapabilities must be updated when adding a new system limit!");
  627. capabilities.textureTypes[TEXTURE_2D] = true;
  628. capabilities.textureTypes[TEXTURE_2D_ARRAY] = true;
  629. capabilities.textureTypes[TEXTURE_VOLUME] = true;
  630. capabilities.textureTypes[TEXTURE_CUBE] = true;
  631. }
  632. void Graphics::getAPIStats(int &shaderswitches) const
  633. {
  634. shaderswitches = static_cast<int>(Vulkan::getNumShaderSwitches());
  635. }
  636. void Graphics::unSetMode()
  637. {
  638. submitGpuCommands(SUBMIT_NOPRESENT);
  639. created = false;
  640. cleanupSwapChain();
  641. vkDestroySurfaceKHR(instance, surface, nullptr);
  642. }
  643. void Graphics::setActive(bool enable)
  644. {
  645. flushBatchedDraws();
  646. active = enable;
  647. }
  648. int Graphics::getRequestedBackbufferMSAA() const
  649. {
  650. return requestedMsaa;
  651. }
  652. int Graphics::getBackbufferMSAA() const
  653. {
  654. return static_cast<int>(msaaSamples);
  655. }
  656. void Graphics::setFrontFaceWinding(Winding winding)
  657. {
  658. const auto& currentState = states.back();
  659. if (currentState.winding == winding)
  660. return;
  661. flushBatchedDraws();
  662. states.back().winding = winding;
  663. if (optionalDeviceExtensions.extendedDynamicState)
  664. vkCmdSetFrontFaceEXT(
  665. commandBuffers.at(currentFrame),
  666. Vulkan::getFrontFace(winding));
  667. }
  668. void Graphics::setColorMask(ColorChannelMask mask)
  669. {
  670. flushBatchedDraws();
  671. states.back().colorMask = mask;
  672. }
  673. void Graphics::setBlendState(const BlendState &blend)
  674. {
  675. flushBatchedDraws();
  676. states.back().blend = blend;
  677. }
  678. void Graphics::setPointSize(float size)
  679. {
  680. if (size != states.back().pointSize)
  681. flushBatchedDraws();
  682. states.back().pointSize = size;
  683. }
  684. bool Graphics::usesGLSLES() const
  685. {
  686. return false;
  687. }
  688. Graphics::RendererInfo Graphics::getRendererInfo() const
  689. {
  690. VkPhysicalDeviceProperties deviceProperties;
  691. vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
  692. Graphics::RendererInfo info;
  693. info.name = "Vulkan";
  694. info.device = deviceProperties.deviceName;
  695. info.vendor = Vulkan::getVendorName(deviceProperties.vendorID);
  696. info.version = Vulkan::getVulkanApiVersion(deviceProperties.apiVersion);
  697. return info;
  698. }
  699. void Graphics::draw(const DrawCommand &cmd)
  700. {
  701. prepareDraw(*cmd.attributes, *cmd.buffers, cmd.texture, cmd.primitiveType, cmd.cullMode);
  702. if (cmd.indirectBuffer != nullptr)
  703. {
  704. vkCmdDrawIndirect(
  705. commandBuffers.at(currentFrame),
  706. (VkBuffer) cmd.indirectBuffer->getHandle(),
  707. cmd.indirectBufferOffset,
  708. 1,
  709. 0);
  710. }
  711. else
  712. {
  713. vkCmdDraw(
  714. commandBuffers.at(currentFrame),
  715. (uint32) cmd.vertexCount,
  716. (uint32) cmd.instanceCount,
  717. (uint32) cmd.vertexStart,
  718. 0);
  719. }
  720. drawCalls++;
  721. }
  722. void Graphics::draw(const DrawIndexedCommand &cmd)
  723. {
  724. prepareDraw(*cmd.attributes, *cmd.buffers, cmd.texture, cmd.primitiveType, cmd.cullMode);
  725. vkCmdBindIndexBuffer(
  726. commandBuffers.at(currentFrame),
  727. (VkBuffer) cmd.indexBuffer->getHandle(),
  728. (VkDeviceSize) cmd.indexBufferOffset,
  729. Vulkan::getVulkanIndexBufferType(cmd.indexType));
  730. if (cmd.indirectBuffer != nullptr)
  731. {
  732. vkCmdDrawIndexedIndirect(
  733. commandBuffers.at(currentFrame),
  734. (VkBuffer) cmd.indirectBuffer->getHandle(),
  735. cmd.indirectBufferOffset,
  736. 1,
  737. 0);
  738. }
  739. else
  740. {
  741. vkCmdDrawIndexed(
  742. commandBuffers.at(currentFrame),
  743. (uint32) cmd.indexCount,
  744. (uint32) cmd.instanceCount,
  745. 0,
  746. 0,
  747. 0);
  748. }
  749. drawCalls++;
  750. }
  751. void Graphics::drawQuads(int start, int count, const VertexAttributes &attributes, const BufferBindings &buffers, graphics::Texture *texture)
  752. {
  753. const int MAX_VERTICES_PER_DRAW = LOVE_UINT16_MAX;
  754. const int MAX_QUADS_PER_DRAW = MAX_VERTICES_PER_DRAW / 4;
  755. prepareDraw(attributes, buffers, texture, PRIMITIVE_TRIANGLES, CULL_NONE);
  756. vkCmdBindIndexBuffer(
  757. commandBuffers.at(currentFrame),
  758. (VkBuffer)quadIndexBuffer->getHandle(),
  759. 0,
  760. Vulkan::getVulkanIndexBufferType(INDEX_UINT16));
  761. int baseVertex = start * 4;
  762. for (int quadindex = 0; quadindex < count; quadindex += MAX_QUADS_PER_DRAW)
  763. {
  764. int quadcount = std::min(MAX_QUADS_PER_DRAW, count - quadindex);
  765. vkCmdDrawIndexed(
  766. commandBuffers.at(currentFrame),
  767. static_cast<uint32_t>(quadcount * 6),
  768. 1,
  769. 0,
  770. baseVertex,
  771. 0);
  772. baseVertex += quadcount * 4;
  773. drawCalls++;
  774. }
  775. }
  776. void Graphics::setColor(Colorf c)
  777. {
  778. c.r = std::min(std::max(c.r, 0.0f), 1.0f);
  779. c.g = std::min(std::max(c.g, 0.0f), 1.0f);
  780. c.b = std::min(std::max(c.b, 0.0f), 1.0f);
  781. c.a = std::min(std::max(c.a, 0.0f), 1.0f);
  782. states.back().color = c;
  783. }
  784. void Graphics::applyScissor()
  785. {
  786. VkRect2D scissor{};
  787. if (renderPassState.isWindow)
  788. scissor.extent = swapChainExtent;
  789. else
  790. {
  791. scissor.extent.width = renderPassState.width;
  792. scissor.extent.height = renderPassState.height;
  793. }
  794. if (states.back().scissor)
  795. {
  796. const Rect &rect = states.back().scissorRect;
  797. double dpiScale = getCurrentDPIScale();
  798. // TODO: clamp this to the above viewport size.
  799. scissor.offset.x = (int)(rect.x * dpiScale);
  800. scissor.offset.y = (int)(rect.y * dpiScale);
  801. scissor.extent.width = (uint32)(rect.w * dpiScale);
  802. scissor.extent.height = (uint32)(rect.h * dpiScale);
  803. }
  804. vkCmdSetScissor(commandBuffers.at(currentFrame), 0, 1, &scissor);
  805. }
  806. void Graphics::setScissor(const Rect &rect)
  807. {
  808. flushBatchedDraws();
  809. states.back().scissor = true;
  810. states.back().scissorRect = rect;
  811. if (renderPassState.active)
  812. applyScissor();
  813. }
  814. void Graphics::setScissor()
  815. {
  816. flushBatchedDraws();
  817. states.back().scissor = false;
  818. if (renderPassState.active)
  819. applyScissor();
  820. }
  821. void Graphics::setStencilState(const StencilState &s)
  822. {
  823. validateStencilState(s);
  824. flushBatchedDraws();
  825. vkCmdSetStencilWriteMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, s.writeMask);
  826. vkCmdSetStencilCompareMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, s.readMask);
  827. vkCmdSetStencilReference(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, s.value);
  828. if (optionalDeviceExtensions.extendedDynamicState)
  829. vkCmdSetStencilOpEXT(
  830. commandBuffers.at(currentFrame),
  831. VK_STENCIL_FRONT_AND_BACK,
  832. VK_STENCIL_OP_KEEP, Vulkan::getStencilOp(s.action),
  833. VK_STENCIL_OP_KEEP, Vulkan::getCompareOp(getReversedCompareMode(s.compare)));
  834. states.back().stencil = s;
  835. }
  836. void Graphics::setDepthMode(CompareMode compare, bool write)
  837. {
  838. validateDepthState(write);
  839. flushBatchedDraws();
  840. if (optionalDeviceExtensions.extendedDynamicState)
  841. {
  842. vkCmdSetDepthCompareOpEXT(
  843. commandBuffers.at(currentFrame), Vulkan::getCompareOp(compare));
  844. vkCmdSetDepthWriteEnableEXT(
  845. commandBuffers.at(currentFrame), Vulkan::getBool(write));
  846. }
  847. states.back().depthTest = compare;
  848. states.back().depthWrite = write;
  849. }
  850. void Graphics::setWireframe(bool enable)
  851. {
  852. flushBatchedDraws();
  853. states.back().wireframe = enable;
  854. }
  855. bool Graphics::isPixelFormatSupported(PixelFormat format, uint32 usage)
  856. {
  857. format = getSizedFormat(format);
  858. switch (format)
  859. {
  860. case PIXELFORMAT_PVR1_RGB2_UNORM:
  861. case PIXELFORMAT_PVR1_RGB2_sRGB:
  862. case PIXELFORMAT_PVR1_RGB4_UNORM:
  863. case PIXELFORMAT_PVR1_RGB4_sRGB:
  864. case PIXELFORMAT_PVR1_RGBA2_UNORM:
  865. case PIXELFORMAT_PVR1_RGBA2_sRGB:
  866. case PIXELFORMAT_PVR1_RGBA4_UNORM:
  867. case PIXELFORMAT_PVR1_RGBA4_sRGB:
  868. // Lets not support these in Vulkan - they're deprecated.
  869. return false;
  870. default:
  871. break;
  872. }
  873. auto vulkanFormat = Vulkan::getTextureFormat(format);
  874. VkFormatProperties formatProperties;
  875. vkGetPhysicalDeviceFormatProperties(physicalDevice, vulkanFormat.internalFormat, &formatProperties);
  876. VkFormatFeatureFlags featureFlags = formatProperties.optimalTilingFeatures;
  877. VkImageUsageFlags usageFlags = 0;
  878. if (!featureFlags)
  879. return false;
  880. if (usage & PIXELFORMATUSAGEFLAGS_SAMPLE)
  881. {
  882. usageFlags |= VK_IMAGE_USAGE_SAMPLED_BIT;
  883. if (!(featureFlags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
  884. return false;
  885. }
  886. if (usage & PIXELFORMATUSAGEFLAGS_LINEAR)
  887. {
  888. if (!(featureFlags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT))
  889. return false;
  890. }
  891. if (usage & PIXELFORMATUSAGEFLAGS_RENDERTARGET)
  892. {
  893. if (isPixelFormatDepth(format) || isPixelFormatDepthStencil(format))
  894. {
  895. usageFlags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  896. if (!(featureFlags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT))
  897. return false;
  898. }
  899. else
  900. {
  901. usageFlags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  902. if (!(featureFlags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT))
  903. return false;
  904. }
  905. }
  906. if (usage & PIXELFORMATUSAGEFLAGS_BLEND)
  907. {
  908. if (!(featureFlags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT))
  909. return false;
  910. }
  911. if (usage & PIXELFORMATUSAGEFLAGS_COMPUTEWRITE)
  912. {
  913. usageFlags |= VK_IMAGE_USAGE_STORAGE_BIT;
  914. if (!(featureFlags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT))
  915. return false;
  916. }
  917. if (usage & PIXELFORMATUSAGEFLAGS_MSAA)
  918. {
  919. VkImageFormatProperties properties;
  920. if (vkGetPhysicalDeviceImageFormatProperties(physicalDevice, vulkanFormat.internalFormat, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usageFlags, 0, &properties) != VK_SUCCESS)
  921. return false;
  922. if (static_cast<uint32_t>(properties.sampleCounts) == 1)
  923. return false;
  924. }
  925. return true;
  926. }
  927. Renderer Graphics::getRenderer() const
  928. {
  929. return RENDERER_VULKAN;
  930. }
  931. graphics::GraphicsReadback *Graphics::newReadbackInternal(ReadbackMethod method, love::graphics::Buffer *buffer, size_t offset, size_t size, data::ByteData *dest, size_t destoffset)
  932. {
  933. return new GraphicsReadback(this, method, buffer, offset, size, dest, destoffset);
  934. }
  935. graphics::GraphicsReadback *Graphics::newReadbackInternal(ReadbackMethod method, love::graphics::Texture *texture, int slice, int mipmap, const Rect &rect, image::ImageData *dest, int destx, int desty)
  936. {
  937. return new GraphicsReadback(this, method, texture, slice, mipmap, rect, dest, destx, desty);
  938. }
  939. graphics::ShaderStage *Graphics::newShaderStageInternal(ShaderStageType stage, const std::string &cachekey, const std::string &source, bool gles)
  940. {
  941. return new ShaderStage(this, stage, source, gles, cachekey);
  942. }
  943. graphics::Shader *Graphics::newShaderInternal(StrongRef<love::graphics::ShaderStage> stages[SHADERSTAGE_MAX_ENUM], const Shader::CompileOptions &options)
  944. {
  945. return new Shader(stages, options);
  946. }
  947. graphics::StreamBuffer *Graphics::newStreamBuffer(BufferUsage type, size_t size)
  948. {
  949. return new StreamBuffer(this, type, size);
  950. }
  951. bool Graphics::dispatch(love::graphics::Shader *shader, int x, int y, int z)
  952. {
  953. usedShadersInFrame.insert(computeShader);
  954. if (renderPassState.active)
  955. endRenderPass();
  956. vkCmdBindPipeline(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE, computeShader->getComputePipeline());
  957. computeShader->cmdPushDescriptorSets(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE);
  958. // TODO: does this need any layout transitions?
  959. vkCmdDispatch(commandBuffers.at(currentFrame), (uint32) x, (uint32) y, (uint32) z);
  960. return true;
  961. }
  962. bool Graphics::dispatch(love::graphics::Shader *shader, love::graphics::Buffer *indirectargs, size_t argsoffset)
  963. {
  964. usedShadersInFrame.insert(computeShader);
  965. if (renderPassState.active)
  966. endRenderPass();
  967. vkCmdBindPipeline(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE, computeShader->getComputePipeline());
  968. computeShader->cmdPushDescriptorSets(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE);
  969. // TODO: does this need any layout transitions?
  970. vkCmdDispatchIndirect(commandBuffers.at(currentFrame), (VkBuffer) indirectargs->getHandle(), argsoffset);
  971. return true;
  972. }
  973. void Graphics::setRenderTargetsInternal(const RenderTargets &rts, int pixelw, int pixelh, bool hasSRGBtexture)
  974. {
  975. if (renderPassState.active)
  976. endRenderPass();
  977. bool isWindow = rts.getFirstTarget().texture == nullptr;
  978. if (isWindow)
  979. setDefaultRenderPass();
  980. else
  981. setRenderPass(rts, pixelw, pixelh, hasSRGBtexture);
  982. }
  983. // END IMPLEMENTATION OVERRIDDEN FUNCTIONS
  984. void Graphics::initDynamicState()
  985. {
  986. vkCmdSetStencilWriteMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, states.back().stencil.writeMask);
  987. vkCmdSetStencilCompareMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, states.back().stencil.readMask);
  988. vkCmdSetStencilReference(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, states.back().stencil.value);
  989. if (optionalDeviceExtensions.extendedDynamicState)
  990. {
  991. vkCmdSetStencilOpEXT(
  992. commandBuffers.at(currentFrame),
  993. VK_STENCIL_FRONT_AND_BACK,
  994. VK_STENCIL_OP_KEEP, Vulkan::getStencilOp(states.back().stencil.action),
  995. VK_STENCIL_OP_KEEP, Vulkan::getCompareOp(getReversedCompareMode(states.back().stencil.compare)));
  996. vkCmdSetDepthCompareOpEXT(
  997. commandBuffers.at(currentFrame), Vulkan::getCompareOp(states.back().depthTest));
  998. vkCmdSetDepthWriteEnableEXT(
  999. commandBuffers.at(currentFrame), Vulkan::getBool(states.back().depthWrite));
  1000. vkCmdSetFrontFaceEXT(
  1001. commandBuffers.at(currentFrame), Vulkan::getFrontFace(states.back().winding));
  1002. }
  1003. }
  1004. void Graphics::beginFrame()
  1005. {
  1006. vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
  1007. if (frameCounter >= USAGES_POLL_INTERVAL)
  1008. {
  1009. cleanupUnusedObjects();
  1010. frameCounter = 0;
  1011. }
  1012. if (swapChain != VK_NULL_HANDLE)
  1013. {
  1014. while (true)
  1015. {
  1016. VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
  1017. if (result == VK_ERROR_OUT_OF_DATE_KHR)
  1018. {
  1019. recreateSwapChain();
  1020. continue;
  1021. }
  1022. else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR)
  1023. throw love::Exception("failed to acquire swap chain image");
  1024. break;
  1025. }
  1026. imageRequested = true;
  1027. }
  1028. else
  1029. {
  1030. imageRequested = false;
  1031. }
  1032. for (auto &readbackCallback : readbackCallbacks.at(currentFrame))
  1033. readbackCallback();
  1034. readbackCallbacks.at(currentFrame).clear();
  1035. for (auto &cleanUpFn : cleanUpFunctions.at(currentFrame))
  1036. cleanUpFn();
  1037. cleanUpFunctions.at(currentFrame).clear();
  1038. startRecordingGraphicsCommands();
  1039. if (!swapChainImages.empty())
  1040. {
  1041. Vulkan::cmdTransitionImageLayout(
  1042. commandBuffers.at(currentFrame),
  1043. swapChainImages[imageIndex],
  1044. swapChainPixelFormat,
  1045. VK_IMAGE_LAYOUT_UNDEFINED,
  1046. VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  1047. }
  1048. if (transitionColorDepthLayouts)
  1049. {
  1050. if (depthImage)
  1051. Vulkan::cmdTransitionImageLayout(
  1052. commandBuffers.at(currentFrame),
  1053. depthImage,
  1054. depthStencilPixelFormat,
  1055. VK_IMAGE_LAYOUT_UNDEFINED,
  1056. VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  1057. if (colorImage)
  1058. Vulkan::cmdTransitionImageLayout(
  1059. commandBuffers.at(currentFrame),
  1060. colorImage,
  1061. swapChainPixelFormat,
  1062. VK_IMAGE_LAYOUT_UNDEFINED,
  1063. VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  1064. transitionColorDepthLayouts = false;
  1065. }
  1066. Vulkan::resetShaderSwitches();
  1067. for (const auto &shader : usedShadersInFrame)
  1068. shader->newFrame();
  1069. usedShadersInFrame.clear();
  1070. localUniformBuffer->nextFrame();
  1071. }
  1072. void Graphics::startRecordingGraphicsCommands()
  1073. {
  1074. VkCommandBufferBeginInfo beginInfo{};
  1075. beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  1076. beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  1077. beginInfo.pInheritanceInfo = nullptr;
  1078. if (vkBeginCommandBuffer(commandBuffers.at(currentFrame), &beginInfo) != VK_SUCCESS)
  1079. throw love::Exception("failed to begin recording command buffer");
  1080. initDynamicState();
  1081. // This must be done after vkBeginCommandBuffer (since newTexture needs an
  1082. // active command buffer for layout transitions), and before setDefaultRenderPass
  1083. // (since that tries to use fakeBackbuffer).
  1084. if (swapChainImages.empty() && fakeBackbuffer == nullptr)
  1085. {
  1086. Texture::Settings settings;
  1087. settings.format = swapChainPixelFormat;
  1088. settings.width = swapChainExtent.width;
  1089. settings.height = swapChainExtent.height;
  1090. settings.renderTarget = true;
  1091. settings.readable.set(false);
  1092. fakeBackbuffer.set((Texture*)newTexture(settings, nullptr), Acquire::NORETAIN);
  1093. }
  1094. setDefaultRenderPass();
  1095. if (defaultVertexBuffer)
  1096. {
  1097. VkBuffer buffer = (VkBuffer)defaultVertexBuffer->getHandle();
  1098. VkDeviceSize offset = 0;
  1099. vkCmdBindVertexBuffers(commandBuffers.at(currentFrame), DEFAULT_VERTEX_BUFFER_BINDING, 1, &buffer, &offset);
  1100. }
  1101. }
  1102. void Graphics::endRecordingGraphicsCommands()
  1103. {
  1104. if (renderPassState.active)
  1105. endRenderPass();
  1106. if (vkEndCommandBuffer(commandBuffers.at(currentFrame)) != VK_SUCCESS)
  1107. throw love::Exception("failed to record command buffer");
  1108. }
  1109. VkCommandBuffer Graphics::getCommandBufferForDataTransfer()
  1110. {
  1111. if (renderPassState.active)
  1112. endRenderPass();
  1113. return commandBuffers.at(currentFrame);
  1114. }
  1115. void Graphics::queueCleanUp(std::function<void()> cleanUp)
  1116. {
  1117. cleanUpFunctions.at(currentFrame).push_back(cleanUp);
  1118. }
  1119. void Graphics::addReadbackCallback(std::function<void()> callback)
  1120. {
  1121. readbackCallbacks.at(currentFrame).push_back(callback);
  1122. }
  1123. graphics::Shader::BuiltinUniformData Graphics::getCurrentBuiltinUniformData()
  1124. {
  1125. love::graphics::Shader::BuiltinUniformData data;
  1126. data.transformMatrix = getTransform();
  1127. data.projectionMatrix = getDeviceProjection();
  1128. data.scaleParams.x = (float) getCurrentDPIScale();
  1129. data.scaleParams.y = getPointSize();
  1130. // Flip y to convert input y-up [-1, 1] to vulkan's y-down [-1, 1].
  1131. // Convert input z [-1, 1] to vulkan [0, 1].
  1132. uint32 flags = Shader::CLIP_TRANSFORM_FLIP_Y | Shader::CLIP_TRANSFORM_Z_NEG1_1_TO_0_1;
  1133. data.clipSpaceParams = Shader::computeClipSpaceParams(flags);
  1134. const auto &rt = states.back().renderTargets.getFirstTarget();
  1135. if (rt.texture != nullptr)
  1136. {
  1137. data.screenSizeParams.x = rt.texture->getPixelWidth(rt.mipmap);
  1138. data.screenSizeParams.y = rt.texture->getPixelHeight(rt.mipmap);
  1139. }
  1140. else
  1141. {
  1142. data.screenSizeParams.x = getPixelWidth();
  1143. data.screenSizeParams.y = getPixelHeight();
  1144. }
  1145. data.screenSizeParams.z = 1.0f;
  1146. data.screenSizeParams.w = 0.0f;
  1147. data.constantColor = getColor();
  1148. gammaCorrectColor(data.constantColor);
  1149. return data;
  1150. }
  1151. const OptionalDeviceExtensions &Graphics::getEnabledOptionalDeviceExtensions() const
  1152. {
  1153. return optionalDeviceExtensions;
  1154. }
  1155. const OptionalInstanceExtensions &Graphics::getEnabledOptionalInstanceExtensions() const
  1156. {
  1157. return optionalInstanceExtensions;
  1158. }
  1159. bool Graphics::checkValidationSupport()
  1160. {
  1161. uint32_t layerCount;
  1162. vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
  1163. std::vector<VkLayerProperties> availableLayers(layerCount);
  1164. vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
  1165. for (const char *layerName : validationLayers)
  1166. {
  1167. bool layerFound = false;
  1168. for (const auto &layerProperties : availableLayers)
  1169. {
  1170. if (strcmp(layerName, layerProperties.layerName) == 0)
  1171. {
  1172. layerFound = true;
  1173. break;
  1174. }
  1175. }
  1176. if (!layerFound)
  1177. return false;
  1178. }
  1179. return true;
  1180. }
  1181. void Graphics::pickPhysicalDevice()
  1182. {
  1183. uint32_t deviceCount = 0;
  1184. vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
  1185. if (deviceCount == 0)
  1186. throw love::Exception("failed to find GPUs with Vulkan support");
  1187. std::vector<VkPhysicalDevice> devices(deviceCount);
  1188. vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
  1189. std::multimap<int, VkPhysicalDevice> candidates;
  1190. for (const auto &device : devices)
  1191. {
  1192. int score = rateDeviceSuitability(device);
  1193. candidates.insert(std::make_pair(score, device));
  1194. }
  1195. if (candidates.rbegin()->first > 0)
  1196. physicalDevice = candidates.rbegin()->second;
  1197. else
  1198. throw love::Exception("failed to find a suitable gpu");
  1199. VkPhysicalDeviceProperties properties;
  1200. vkGetPhysicalDeviceProperties(physicalDevice, &properties);
  1201. minUniformBufferOffsetAlignment = properties.limits.minUniformBufferOffsetAlignment;
  1202. deviceApiVersion = properties.apiVersion;
  1203. depthStencilFormat = findDepthFormat();
  1204. switch (depthStencilFormat)
  1205. {
  1206. case VK_FORMAT_D32_SFLOAT_S8_UINT:
  1207. depthStencilPixelFormat = PIXELFORMAT_DEPTH32_FLOAT_STENCIL8;
  1208. break;
  1209. case VK_FORMAT_D24_UNORM_S8_UINT:
  1210. depthStencilPixelFormat = PIXELFORMAT_DEPTH24_UNORM_STENCIL8;
  1211. break;
  1212. default:
  1213. throw love::Exception("Failed to convert vulkan depth/stencil swapchain pixel format %d to love PixelFormat.", depthStencilFormat);
  1214. break;
  1215. }
  1216. }
  1217. bool Graphics::checkDeviceExtensionSupport(VkPhysicalDevice device)
  1218. {
  1219. uint32_t extensionCount;
  1220. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
  1221. std::vector<VkExtensionProperties> availableExtensions(extensionCount);
  1222. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
  1223. std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
  1224. for (const auto &extension : availableExtensions)
  1225. requiredExtensions.erase(extension.extensionName);
  1226. return requiredExtensions.empty();
  1227. }
  1228. // if the score is nonzero then the device is suitable.
  1229. // A higher rating means generally better performance
  1230. // if the score is 0 the device is unsuitable
  1231. int Graphics::rateDeviceSuitability(VkPhysicalDevice device)
  1232. {
  1233. VkPhysicalDeviceProperties deviceProperties;
  1234. VkPhysicalDeviceFeatures deviceFeatures;
  1235. vkGetPhysicalDeviceProperties(device, &deviceProperties);
  1236. vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
  1237. int score = 1;
  1238. // optional
  1239. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
  1240. score += 1000;
  1241. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU)
  1242. score += 100;
  1243. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU)
  1244. score += 10;
  1245. // definitely needed
  1246. QueueFamilyIndices indices = findQueueFamilies(device);
  1247. if (!indices.isComplete())
  1248. score = 0;
  1249. bool extensionsSupported = checkDeviceExtensionSupport(device);
  1250. if (!extensionsSupported)
  1251. score = 0;
  1252. if (extensionsSupported)
  1253. {
  1254. auto swapChainSupport = querySwapChainSupport(device);
  1255. bool swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
  1256. if (!swapChainAdequate)
  1257. score = 0;
  1258. }
  1259. if (!deviceFeatures.samplerAnisotropy)
  1260. score = 0;
  1261. if (!deviceFeatures.fillModeNonSolid)
  1262. score = 0;
  1263. return score;
  1264. }
  1265. QueueFamilyIndices Graphics::findQueueFamilies(VkPhysicalDevice device)
  1266. {
  1267. QueueFamilyIndices indices;
  1268. uint32_t queueFamilyCount = 0;
  1269. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
  1270. std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
  1271. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
  1272. int i = 0;
  1273. for (const auto &queueFamily : queueFamilies)
  1274. {
  1275. if ((queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) && (queueFamily.queueFlags & VK_QUEUE_COMPUTE_BIT))
  1276. indices.graphicsFamily = i;
  1277. VkBool32 presentSupport = false;
  1278. vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
  1279. if (presentSupport)
  1280. indices.presentFamily = i;
  1281. if (indices.isComplete())
  1282. break;
  1283. i++;
  1284. }
  1285. return indices;
  1286. }
  1287. static void findOptionalDeviceExtensions(VkPhysicalDevice physicalDevice, OptionalDeviceExtensions &optionalDeviceExtensions)
  1288. {
  1289. uint32_t extensionCount;
  1290. vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr);
  1291. std::vector<VkExtensionProperties> availableExtensions(extensionCount);
  1292. vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data());
  1293. for (const auto &extension : availableExtensions)
  1294. {
  1295. if (strcmp(extension.extensionName, VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME) == 0)
  1296. optionalDeviceExtensions.extendedDynamicState = true;
  1297. if (strcmp(extension.extensionName, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME) == 0)
  1298. optionalDeviceExtensions.memoryRequirements2 = true;
  1299. if (strcmp(extension.extensionName, VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME) == 0)
  1300. optionalDeviceExtensions.dedicatedAllocation = true;
  1301. if (strcmp(extension.extensionName, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME) == 0)
  1302. optionalDeviceExtensions.memoryBudget = true;
  1303. if (strcmp(extension.extensionName, VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME) == 0)
  1304. optionalDeviceExtensions.shaderFloatControls = true;
  1305. if (strcmp(extension.extensionName, VK_KHR_SPIRV_1_4_EXTENSION_NAME) == 0)
  1306. optionalDeviceExtensions.spirv14 = true;
  1307. }
  1308. }
  1309. void Graphics::createLogicalDevice()
  1310. {
  1311. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  1312. std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
  1313. std::set<uint32_t> uniqueQueueFamilies = {
  1314. indices.graphicsFamily.value,
  1315. indices.presentFamily.value
  1316. };
  1317. float queuePriority = 1.0f;
  1318. for (uint32_t queueFamily : uniqueQueueFamilies)
  1319. {
  1320. VkDeviceQueueCreateInfo queueCreateInfo{};
  1321. queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  1322. queueCreateInfo.queueFamilyIndex = queueFamily;
  1323. queueCreateInfo.queueCount = 1;
  1324. queueCreateInfo.pQueuePriorities = &queuePriority;
  1325. queueCreateInfos.push_back(queueCreateInfo);
  1326. }
  1327. findOptionalDeviceExtensions(physicalDevice, optionalDeviceExtensions);
  1328. // sanity check for dependencies.
  1329. if (optionalDeviceExtensions.extendedDynamicState && !optionalInstanceExtensions.physicalDeviceProperties2)
  1330. optionalDeviceExtensions.extendedDynamicState = false;
  1331. if (optionalDeviceExtensions.dedicatedAllocation && !optionalDeviceExtensions.memoryRequirements2)
  1332. optionalDeviceExtensions.dedicatedAllocation = false;
  1333. if (optionalDeviceExtensions.memoryBudget && !optionalInstanceExtensions.physicalDeviceProperties2)
  1334. optionalDeviceExtensions.memoryBudget = false;
  1335. if (optionalDeviceExtensions.spirv14 && !optionalDeviceExtensions.shaderFloatControls)
  1336. optionalDeviceExtensions.spirv14 = false;
  1337. if (optionalDeviceExtensions.spirv14 && deviceApiVersion < VK_API_VERSION_1_1)
  1338. optionalDeviceExtensions.spirv14 = false;
  1339. VkPhysicalDeviceFeatures deviceFeatures{};
  1340. deviceFeatures.samplerAnisotropy = VK_TRUE;
  1341. deviceFeatures.fillModeNonSolid = VK_TRUE;
  1342. VkDeviceCreateInfo createInfo{};
  1343. createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  1344. createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
  1345. createInfo.pQueueCreateInfos = queueCreateInfos.data();
  1346. createInfo.pEnabledFeatures = &deviceFeatures;
  1347. std::vector<const char*> enabledExtensions(deviceExtensions.begin(), deviceExtensions.end());
  1348. if (optionalDeviceExtensions.extendedDynamicState)
  1349. enabledExtensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME);
  1350. if (optionalDeviceExtensions.memoryRequirements2)
  1351. enabledExtensions.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
  1352. if (optionalDeviceExtensions.dedicatedAllocation)
  1353. enabledExtensions.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME);
  1354. if (optionalDeviceExtensions.memoryBudget)
  1355. enabledExtensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME);
  1356. if (optionalDeviceExtensions.shaderFloatControls)
  1357. enabledExtensions.push_back(VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME);
  1358. if (optionalDeviceExtensions.spirv14)
  1359. enabledExtensions.push_back(VK_KHR_SPIRV_1_4_EXTENSION_NAME);
  1360. if (deviceApiVersion >= VK_API_VERSION_1_1)
  1361. enabledExtensions.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
  1362. createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledExtensions.size());
  1363. createInfo.ppEnabledExtensionNames = enabledExtensions.data();
  1364. if (isDebugEnabled())
  1365. {
  1366. createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
  1367. createInfo.ppEnabledLayerNames = validationLayers.data();
  1368. }
  1369. VkPhysicalDeviceExtendedDynamicStateFeaturesEXT extendedDynamicStateFeatures{};
  1370. extendedDynamicStateFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT;
  1371. extendedDynamicStateFeatures.extendedDynamicState = VK_TRUE;
  1372. extendedDynamicStateFeatures.pNext = nullptr;
  1373. if (optionalDeviceExtensions.extendedDynamicState)
  1374. createInfo.pNext = &extendedDynamicStateFeatures;
  1375. if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS)
  1376. throw love::Exception("failed to create logical device");
  1377. volkLoadDevice(device);
  1378. vkGetDeviceQueue(device, indices.graphicsFamily.value, 0, &graphicsQueue);
  1379. vkGetDeviceQueue(device, indices.presentFamily.value, 0, &presentQueue);
  1380. }
  1381. void Graphics::createPipelineCache()
  1382. {
  1383. VkPipelineCacheCreateInfo cacheInfo{};
  1384. cacheInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
  1385. if (vkCreatePipelineCache(device, &cacheInfo, nullptr, &pipelineCache) != VK_SUCCESS)
  1386. throw love::Exception("could not create pipeline cache");
  1387. }
  1388. void Graphics::initVMA()
  1389. {
  1390. VmaAllocatorCreateInfo allocatorCreateInfo = {};
  1391. allocatorCreateInfo.vulkanApiVersion = deviceApiVersion;
  1392. allocatorCreateInfo.physicalDevice = physicalDevice;
  1393. allocatorCreateInfo.device = device;
  1394. allocatorCreateInfo.instance = instance;
  1395. // Default of 256 MB is a little too wasteful for most love games.
  1396. // TODO: Tune this more.
  1397. allocatorCreateInfo.preferredLargeHeapBlockSize = 128 * 1024 * 1024;
  1398. VmaVulkanFunctions vulkanFunctions{};
  1399. vulkanFunctions.vkGetInstanceProcAddr = vkGetInstanceProcAddr;
  1400. vulkanFunctions.vkGetDeviceProcAddr = vkGetDeviceProcAddr;
  1401. vulkanFunctions.vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties;
  1402. vulkanFunctions.vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties;
  1403. vulkanFunctions.vkAllocateMemory = vkAllocateMemory;
  1404. vulkanFunctions.vkFreeMemory = vkFreeMemory;
  1405. vulkanFunctions.vkMapMemory = vkMapMemory;
  1406. vulkanFunctions.vkUnmapMemory = vkUnmapMemory;
  1407. vulkanFunctions.vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges;
  1408. vulkanFunctions.vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges;
  1409. vulkanFunctions.vkBindBufferMemory = vkBindBufferMemory;
  1410. vulkanFunctions.vkBindImageMemory = vkBindImageMemory;
  1411. vulkanFunctions.vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements;
  1412. vulkanFunctions.vkGetImageMemoryRequirements = vkGetImageMemoryRequirements;
  1413. vulkanFunctions.vkCreateBuffer = vkCreateBuffer;
  1414. vulkanFunctions.vkCreateImage = vkCreateImage;
  1415. vulkanFunctions.vkDestroyBuffer = vkDestroyBuffer;
  1416. vulkanFunctions.vkDestroyImage = vkDestroyImage;
  1417. vulkanFunctions.vkCmdCopyBuffer = vkCmdCopyBuffer;
  1418. vulkanFunctions.vkGetBufferMemoryRequirements2KHR = vkGetBufferMemoryRequirements2KHR;
  1419. vulkanFunctions.vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2KHR;
  1420. vulkanFunctions.vkBindBufferMemory2KHR = vkBindBufferMemory2KHR;
  1421. vulkanFunctions.vkBindImageMemory2KHR = vkBindImageMemory2KHR;
  1422. vulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR = vkGetPhysicalDeviceMemoryProperties2KHR;
  1423. vulkanFunctions.vkGetDeviceBufferMemoryRequirements = vkGetDeviceBufferMemoryRequirements;
  1424. vulkanFunctions.vkGetDeviceImageMemoryRequirements = vkGetDeviceImageMemoryRequirements;
  1425. allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions;
  1426. allocatorCreateInfo.flags |= VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT;
  1427. if (optionalDeviceExtensions.dedicatedAllocation)
  1428. allocatorCreateInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT;
  1429. if (optionalDeviceExtensions.memoryBudget)
  1430. allocatorCreateInfo.flags |= VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT;
  1431. if (vmaCreateAllocator(&allocatorCreateInfo, &vmaAllocator) != VK_SUCCESS)
  1432. throw love::Exception("failed to create vma allocator");
  1433. }
  1434. void Graphics::createSurface()
  1435. {
  1436. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  1437. const void *handle = window->getHandle();
  1438. #if SDL_VERSION_ATLEAST(3, 0, 0)
  1439. if (SDL_Vulkan_CreateSurface((SDL_Window*)handle, instance, nullptr, &surface) != SDL_TRUE)
  1440. throw love::Exception("failed to create window surface");
  1441. #else
  1442. if (SDL_Vulkan_CreateSurface((SDL_Window*)handle, instance, &surface) != SDL_TRUE)
  1443. throw love::Exception("failed to create window surface");
  1444. #endif
  1445. }
  1446. SwapChainSupportDetails Graphics::querySwapChainSupport(VkPhysicalDevice device)
  1447. {
  1448. SwapChainSupportDetails details;
  1449. vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
  1450. uint32_t formatCount;
  1451. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
  1452. if (formatCount != 0)
  1453. {
  1454. details.formats.resize(formatCount);
  1455. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
  1456. }
  1457. uint32_t presentModeCount;
  1458. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
  1459. if (presentModeCount != 0)
  1460. {
  1461. details.presentModes.resize(presentModeCount);
  1462. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
  1463. }
  1464. return details;
  1465. }
  1466. void Graphics::createSwapChain()
  1467. {
  1468. SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
  1469. VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
  1470. VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
  1471. VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
  1472. if (extent.width > 0 && extent.height > 0)
  1473. {
  1474. uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
  1475. if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount)
  1476. imageCount = swapChainSupport.capabilities.maxImageCount;
  1477. VkSwapchainCreateInfoKHR createInfo{};
  1478. createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  1479. createInfo.surface = surface;
  1480. createInfo.minImageCount = imageCount;
  1481. createInfo.imageFormat = surfaceFormat.format;
  1482. createInfo.imageColorSpace = surfaceFormat.colorSpace;
  1483. createInfo.imageExtent = extent;
  1484. createInfo.imageArrayLayers = 1;
  1485. createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
  1486. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  1487. uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value, indices.presentFamily.value };
  1488. if (indices.graphicsFamily.value != indices.presentFamily.value)
  1489. {
  1490. createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
  1491. createInfo.queueFamilyIndexCount = 2;
  1492. createInfo.pQueueFamilyIndices = queueFamilyIndices;
  1493. }
  1494. else
  1495. {
  1496. createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1497. createInfo.queueFamilyIndexCount = 0;
  1498. createInfo.pQueueFamilyIndices = nullptr;
  1499. }
  1500. createInfo.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
  1501. createInfo.compositeAlpha = chooseCompositeAlpha(swapChainSupport.capabilities);
  1502. createInfo.presentMode = presentMode;
  1503. createInfo.clipped = VK_TRUE;
  1504. createInfo.oldSwapchain = VK_NULL_HANDLE;
  1505. if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS)
  1506. throw love::Exception("failed to create swap chain");
  1507. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
  1508. swapChainImages.resize(imageCount);
  1509. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
  1510. }
  1511. else
  1512. {
  1513. // Use a fake backbuffer. Creation is deferred until startRecordingGraphicsCommands
  1514. // because newTexture needs an active command buffer to do its initial
  1515. // layout transitions.
  1516. swapChainImages.clear();
  1517. extent.width = std::max(1, pixelWidth);
  1518. extent.height = std::max(1, pixelHeight);
  1519. if (isGammaCorrect())
  1520. surfaceFormat.format = VK_FORMAT_R8G8B8A8_SRGB;
  1521. else
  1522. surfaceFormat.format = VK_FORMAT_R8G8B8A8_UNORM;
  1523. }
  1524. swapChainImageFormat = surfaceFormat.format;
  1525. swapChainExtent = extent;
  1526. switch (swapChainImageFormat)
  1527. {
  1528. case VK_FORMAT_B8G8R8A8_SRGB:
  1529. swapChainPixelFormat = PIXELFORMAT_BGRA8_sRGB;
  1530. break;
  1531. case VK_FORMAT_B8G8R8A8_UNORM:
  1532. swapChainPixelFormat = PIXELFORMAT_BGRA8_UNORM;
  1533. break;
  1534. case VK_FORMAT_R8G8B8A8_SRGB:
  1535. swapChainPixelFormat = PIXELFORMAT_RGBA8_sRGB;
  1536. break;
  1537. case VK_FORMAT_R8G8B8A8_UNORM:
  1538. swapChainPixelFormat = PIXELFORMAT_RGBA8_UNORM;
  1539. break;
  1540. default:
  1541. throw love::Exception("Failed to convert vulkan depth/stencil swapchain image format %d to love PixelFormat.", swapChainImageFormat);
  1542. break;
  1543. }
  1544. }
  1545. VkSurfaceFormatKHR Graphics::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR> &availableFormats)
  1546. {
  1547. std::vector<VkFormat> formatOrder;
  1548. // TODO: turn off GammaCorrect if a sRGB format can't be found?
  1549. // TODO: does every platform have these formats?
  1550. if (isGammaCorrect())
  1551. {
  1552. formatOrder = {
  1553. VK_FORMAT_B8G8R8A8_SRGB,
  1554. VK_FORMAT_R8G8B8A8_SRGB,
  1555. };
  1556. }
  1557. else
  1558. {
  1559. formatOrder = {
  1560. VK_FORMAT_B8G8R8A8_UNORM,
  1561. VK_FORMAT_R8G8B8A8_SNORM,
  1562. };
  1563. }
  1564. for (const auto format : formatOrder)
  1565. {
  1566. for (const auto &availableFormat : availableFormats)
  1567. {
  1568. if (availableFormat.format == format && availableFormat.colorSpace == VK_COLORSPACE_SRGB_NONLINEAR_KHR)
  1569. return availableFormat;
  1570. }
  1571. }
  1572. return availableFormats[0];
  1573. }
  1574. VkPresentModeKHR Graphics::chooseSwapPresentMode(const std::vector<VkPresentModeKHR> &availablePresentModes)
  1575. {
  1576. const auto begin = availablePresentModes.begin();
  1577. const auto end = availablePresentModes.end();
  1578. switch (vsync)
  1579. {
  1580. case -1:
  1581. if (std::find(begin, end, VK_PRESENT_MODE_FIFO_RELAXED_KHR) != end)
  1582. return VK_PRESENT_MODE_FIFO_RELAXED_KHR;
  1583. else
  1584. return VK_PRESENT_MODE_FIFO_KHR;
  1585. case 0:
  1586. // Mailbox mode might be better than immediate mode for a lot of people.
  1587. // But on at least some systems it acts as if vsync is enabled
  1588. // https://github.com/love2d/love/issues/1852
  1589. // TODO: is that a bug in love's code or the graphics driver / compositor?
  1590. // Should love expose mailbox mode in an API to users in some manner,
  1591. // instead of trying to guess what to do?
  1592. if (std::find(begin, end, VK_PRESENT_MODE_IMMEDIATE_KHR) != end)
  1593. return VK_PRESENT_MODE_IMMEDIATE_KHR;
  1594. else if (std::find(begin, end, VK_PRESENT_MODE_MAILBOX_KHR) != end)
  1595. return VK_PRESENT_MODE_MAILBOX_KHR;
  1596. else
  1597. return VK_PRESENT_MODE_FIFO_KHR;
  1598. default:
  1599. // TODO: support for swap interval = 2, etc?
  1600. return VK_PRESENT_MODE_FIFO_KHR;
  1601. }
  1602. }
  1603. static uint32_t clampuint32_t(uint32_t value, uint32_t min, uint32_t max)
  1604. {
  1605. if (value < min)
  1606. return min;
  1607. if (value > max)
  1608. return max;
  1609. return value;
  1610. }
  1611. VkExtent2D Graphics::chooseSwapExtent(const VkSurfaceCapabilitiesKHR &capabilities)
  1612. {
  1613. if (capabilities.currentExtent.width != UINT32_MAX)
  1614. return capabilities.currentExtent;
  1615. else
  1616. {
  1617. VkExtent2D actualExtent = {
  1618. static_cast<uint32_t>(pixelWidth),
  1619. static_cast<uint32_t>(pixelHeight)
  1620. };
  1621. actualExtent.width = clampuint32_t(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
  1622. actualExtent.height = clampuint32_t(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
  1623. return actualExtent;
  1624. }
  1625. }
  1626. VkCompositeAlphaFlagBitsKHR Graphics::chooseCompositeAlpha(const VkSurfaceCapabilitiesKHR &capabilities)
  1627. {
  1628. if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR)
  1629. return VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  1630. else if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR)
  1631. return VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
  1632. else if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR)
  1633. return VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
  1634. else if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR)
  1635. return VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR;
  1636. else
  1637. throw love::Exception("failed to find composite alpha");
  1638. }
  1639. void Graphics::createImageViews()
  1640. {
  1641. swapChainImageViews.resize(swapChainImages.size());
  1642. for (size_t i = 0; i < swapChainImages.size(); i++)
  1643. {
  1644. VkImageViewCreateInfo createInfo{};
  1645. createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1646. createInfo.image = swapChainImages.at(i);
  1647. createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  1648. createInfo.format = swapChainImageFormat;
  1649. createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  1650. createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  1651. createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  1652. createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  1653. createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1654. createInfo.subresourceRange.baseMipLevel = 0;
  1655. createInfo.subresourceRange.levelCount = 1;
  1656. createInfo.subresourceRange.baseArrayLayer = 0;
  1657. createInfo.subresourceRange.layerCount = 1;
  1658. if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews.at(i)) != VK_SUCCESS)
  1659. throw love::Exception("failed to create image views");
  1660. }
  1661. }
  1662. VkFramebuffer Graphics::createFramebuffer(FramebufferConfiguration &configuration)
  1663. {
  1664. std::vector<VkImageView> attachments;
  1665. for (const auto &colorView : configuration.colorViews)
  1666. attachments.push_back(colorView);
  1667. if (configuration.staticData.depthView)
  1668. attachments.push_back(configuration.staticData.depthView);
  1669. if (configuration.staticData.resolveView)
  1670. attachments.push_back(configuration.staticData.resolveView);
  1671. VkFramebufferCreateInfo createInfo{};
  1672. createInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  1673. createInfo.renderPass = configuration.staticData.renderPass;
  1674. createInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
  1675. createInfo.pAttachments = attachments.data();
  1676. createInfo.width = configuration.staticData.width;
  1677. createInfo.height = configuration.staticData.height;
  1678. createInfo.layers = 1;
  1679. VkFramebuffer frameBuffer;
  1680. if (vkCreateFramebuffer(device, &createInfo, nullptr, &frameBuffer) != VK_SUCCESS)
  1681. throw love::Exception("failed to create framebuffer");
  1682. return frameBuffer;
  1683. }
  1684. VkFramebuffer Graphics::getFramebuffer(FramebufferConfiguration &configuration)
  1685. {
  1686. VkFramebuffer framebuffer;
  1687. auto it = framebuffers.find(configuration);
  1688. if (it != framebuffers.end())
  1689. framebuffer = it->second;
  1690. else
  1691. {
  1692. framebuffer = createFramebuffer(configuration);
  1693. framebuffers[configuration] = framebuffer;
  1694. }
  1695. framebufferUsages[framebuffer] = true;
  1696. return framebuffer;
  1697. }
  1698. void Graphics::createDefaultShaders()
  1699. {
  1700. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++)
  1701. {
  1702. auto stype = (Shader::StandardShader)i;
  1703. if (!Shader::standardShaders[i])
  1704. {
  1705. std::vector<std::string> stages;
  1706. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_VERTEX));
  1707. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_PIXEL));
  1708. Shader::standardShaders[i] = newShader(stages, {});
  1709. }
  1710. }
  1711. }
  1712. VkRenderPass Graphics::createRenderPass(RenderPassConfiguration &configuration)
  1713. {
  1714. VkSubpassDescription subPass{};
  1715. subPass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  1716. std::vector<VkAttachmentDescription> attachments;
  1717. std::vector<VkAttachmentReference> colorAttachmentRefs;
  1718. uint32_t attachment = 0;
  1719. for (const auto &colorAttachment : configuration.colorAttachments)
  1720. {
  1721. VkAttachmentReference reference{};
  1722. reference.attachment = attachment++;
  1723. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1724. colorAttachmentRefs.push_back(reference);
  1725. VkAttachmentDescription colorDescription{};
  1726. colorDescription.format = colorAttachment.format;
  1727. colorDescription.samples = colorAttachment.msaaSamples;
  1728. colorDescription.loadOp = colorAttachment.loadOp;
  1729. colorDescription.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  1730. colorDescription.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1731. colorDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  1732. colorDescription.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1733. colorDescription.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1734. attachments.push_back(colorDescription);
  1735. }
  1736. subPass.colorAttachmentCount = static_cast<uint32_t>(colorAttachmentRefs.size());
  1737. subPass.pColorAttachments = colorAttachmentRefs.data();
  1738. VkAttachmentReference depthStencilAttachmentRef{};
  1739. if (configuration.staticData.depthStencilAttachment.format != VK_FORMAT_UNDEFINED)
  1740. {
  1741. depthStencilAttachmentRef.attachment = attachment++;
  1742. depthStencilAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1743. subPass.pDepthStencilAttachment = &depthStencilAttachmentRef;
  1744. VkAttachmentDescription depthStencilAttachment{};
  1745. depthStencilAttachment.format = configuration.staticData.depthStencilAttachment.format;
  1746. depthStencilAttachment.samples = configuration.staticData.depthStencilAttachment.msaaSamples;
  1747. depthStencilAttachment.loadOp = configuration.staticData.depthStencilAttachment.depthLoadOp;
  1748. depthStencilAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  1749. depthStencilAttachment.stencilLoadOp = configuration.staticData.depthStencilAttachment.stencilLoadOp;
  1750. depthStencilAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  1751. depthStencilAttachment.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1752. depthStencilAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1753. attachments.push_back(depthStencilAttachment);
  1754. }
  1755. VkAttachmentReference colorAttachmentResolveRef{};
  1756. if (configuration.staticData.resolve)
  1757. {
  1758. colorAttachmentResolveRef.attachment = attachment++;
  1759. colorAttachmentResolveRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1760. subPass.pResolveAttachments = &colorAttachmentResolveRef;
  1761. VkAttachmentDescription colorAttachmentResolve{};
  1762. colorAttachmentResolve.format = configuration.colorAttachments.at(0).format;
  1763. colorAttachmentResolve.samples = VK_SAMPLE_COUNT_1_BIT;
  1764. colorAttachmentResolve.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1765. colorAttachmentResolve.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  1766. colorAttachmentResolve.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1767. colorAttachmentResolve.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  1768. colorAttachmentResolve.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1769. colorAttachmentResolve.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1770. attachments.push_back(colorAttachmentResolve);
  1771. }
  1772. VkSubpassDependency dependency{};
  1773. dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
  1774. dependency.dstSubpass = 0;
  1775. dependency.srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
  1776. dependency.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  1777. dependency.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
  1778. dependency.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  1779. VkSubpassDependency readbackDependency{};
  1780. readbackDependency.srcSubpass = 0;
  1781. readbackDependency.dstSubpass = VK_SUBPASS_EXTERNAL;
  1782. readbackDependency.srcStageMask = VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  1783. readbackDependency.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  1784. readbackDependency.dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  1785. readbackDependency.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  1786. std::array<VkSubpassDependency, 2> dependencies = { dependency, readbackDependency };
  1787. VkRenderPassCreateInfo createInfo{};
  1788. createInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  1789. createInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
  1790. createInfo.pAttachments = attachments.data();
  1791. createInfo.subpassCount = 1;
  1792. createInfo.pSubpasses = &subPass;
  1793. createInfo.dependencyCount = static_cast<uint32_t>(dependencies.size());
  1794. createInfo.pDependencies = dependencies.data();
  1795. VkRenderPass renderPass;
  1796. if (vkCreateRenderPass(device, &createInfo, nullptr, &renderPass) != VK_SUCCESS)
  1797. throw love::Exception("failed to create render pass");
  1798. return renderPass;
  1799. }
  1800. VkRenderPass Graphics::getRenderPass(RenderPassConfiguration &configuration)
  1801. {
  1802. VkRenderPass renderPass;
  1803. auto it = renderPasses.find(configuration);
  1804. if (it != renderPasses.end())
  1805. renderPass = it->second;
  1806. else
  1807. {
  1808. renderPass = createRenderPass(configuration);
  1809. renderPasses[configuration] = renderPass;
  1810. }
  1811. return renderPass;
  1812. }
  1813. void Graphics::createVulkanVertexFormat(
  1814. Shader *shader,
  1815. const VertexAttributes &attributes,
  1816. std::vector<VkVertexInputBindingDescription> &bindingDescriptions,
  1817. std::vector<VkVertexInputAttributeDescription> &attributeDescriptions)
  1818. {
  1819. std::set<uint32_t> usedBuffers;
  1820. for (const auto &pair : shader->getVertexAttributeIndices())
  1821. {
  1822. int i = pair.second.index;
  1823. uint32 bit = 1u << i;
  1824. VkVertexInputAttributeDescription attribdesc{};
  1825. attribdesc.location = i;
  1826. if (attributes.enableBits & bit)
  1827. {
  1828. const auto &attrib = attributes.attribs[i];
  1829. int bufferbinding = VERTEX_BUFFER_BINDING_START + attrib.bufferIndex;
  1830. attribdesc.binding = bufferbinding;
  1831. attribdesc.offset = attrib.offsetFromVertex;
  1832. attribdesc.format = Vulkan::getVulkanVertexFormat(attrib.getFormat());
  1833. if (usedBuffers.find(bufferbinding) == usedBuffers.end())
  1834. {
  1835. usedBuffers.insert(bufferbinding);
  1836. VkVertexInputBindingDescription bindingdesc{};
  1837. bindingdesc.binding = bufferbinding;
  1838. if (attributes.instanceBits & (1u << attrib.bufferIndex))
  1839. bindingdesc.inputRate = VK_VERTEX_INPUT_RATE_INSTANCE;
  1840. else
  1841. bindingdesc.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  1842. bindingdesc.stride = attributes.bufferLayouts[attrib.bufferIndex].stride;
  1843. bindingDescriptions.push_back(bindingdesc);
  1844. }
  1845. }
  1846. else
  1847. {
  1848. attribdesc.binding = DEFAULT_VERTEX_BUFFER_BINDING;
  1849. // Indices should match the creation parameters for defaultVertexBuffer.
  1850. switch (pair.second.baseType)
  1851. {
  1852. case DATA_BASETYPE_INT:
  1853. attribdesc.offset = defaultVertexBuffer->getDataMember(1).offset;
  1854. attribdesc.format = Vulkan::getVulkanVertexFormat(DATAFORMAT_INT32_VEC4);
  1855. break;
  1856. case DATA_BASETYPE_UINT:
  1857. attribdesc.offset = defaultVertexBuffer->getDataMember(1).offset;
  1858. attribdesc.format = Vulkan::getVulkanVertexFormat(DATAFORMAT_UINT32_VEC4);
  1859. break;
  1860. case DATA_BASETYPE_FLOAT:
  1861. default:
  1862. if (i == ATTRIB_COLOR)
  1863. attribdesc.offset = defaultVertexBuffer->getDataMember(2).offset;
  1864. else
  1865. attribdesc.offset = defaultVertexBuffer->getDataMember(0).offset;
  1866. attribdesc.format = Vulkan::getVulkanVertexFormat(DATAFORMAT_FLOAT_VEC4);
  1867. break;
  1868. }
  1869. if (usedBuffers.find(DEFAULT_VERTEX_BUFFER_BINDING) == usedBuffers.end())
  1870. {
  1871. usedBuffers.insert(DEFAULT_VERTEX_BUFFER_BINDING);
  1872. VkVertexInputBindingDescription bindingdesc{};
  1873. bindingdesc.binding = DEFAULT_VERTEX_BUFFER_BINDING;
  1874. bindingdesc.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  1875. bindingdesc.stride = 0; // no stride, will always read the same coord multiple times.
  1876. bindingDescriptions.push_back(bindingdesc);
  1877. }
  1878. }
  1879. attributeDescriptions.push_back(attribdesc);
  1880. }
  1881. }
  1882. void Graphics::prepareDraw(const VertexAttributes &attributes, const BufferBindings &buffers, graphics::Texture *texture, PrimitiveType primitiveType, CullMode cullmode)
  1883. {
  1884. if (!renderPassState.active)
  1885. startRenderPass();
  1886. auto s = dynamic_cast<Shader*>(Shader::current);
  1887. usedShadersInFrame.insert(s);
  1888. GraphicsPipelineConfiguration configuration{};
  1889. configuration.renderPass = renderPassState.beginInfo.renderPass;
  1890. configuration.vertexAttributes = attributes;
  1891. configuration.wireFrame = states.back().wireframe;
  1892. configuration.blendState = states.back().blend;
  1893. configuration.colorChannelMask = states.back().colorMask;
  1894. configuration.msaaSamples = renderPassState.msaa;
  1895. configuration.numColorAttachments = renderPassState.numColorAttachments;
  1896. configuration.primitiveType = primitiveType;
  1897. if (optionalDeviceExtensions.extendedDynamicState)
  1898. vkCmdSetCullModeEXT(commandBuffers.at(currentFrame), Vulkan::getCullMode(cullmode));
  1899. else
  1900. {
  1901. configuration.dynamicState.winding = states.back().winding;
  1902. configuration.dynamicState.depthState.compare = states.back().depthTest;
  1903. configuration.dynamicState.depthState.write = states.back().depthWrite;
  1904. configuration.dynamicState.stencilAction = states.back().stencil.action;
  1905. configuration.dynamicState.stencilCompare = states.back().stencil.compare;
  1906. configuration.dynamicState.cullmode = cullmode;
  1907. }
  1908. VkPipeline pipeline = s->getCachedGraphicsPipeline(this, configuration);
  1909. if (pipeline != renderPassState.pipeline)
  1910. {
  1911. vkCmdBindPipeline(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
  1912. renderPassState.pipeline = pipeline;
  1913. }
  1914. s->setMainTex(texture);
  1915. s->cmdPushDescriptorSets(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_GRAPHICS);
  1916. VkBuffer vkbuffers[BufferBindings::MAX];
  1917. VkDeviceSize vkoffsets[BufferBindings::MAX];
  1918. uint32 buffercount = 0;
  1919. uint32 allbits = buffers.useBits;
  1920. uint32 i = 0;
  1921. while (allbits)
  1922. {
  1923. uint32 bit = 1u << i;
  1924. // TODO: handle split ranges.
  1925. if (buffers.useBits & bit)
  1926. {
  1927. vkbuffers[buffercount] = (VkBuffer)buffers.info[i].buffer->getHandle();
  1928. vkoffsets[buffercount] = (VkDeviceSize)buffers.info[i].offset;
  1929. buffercount++;
  1930. }
  1931. i++;
  1932. allbits >>= 1;
  1933. }
  1934. if (buffercount > 0)
  1935. vkCmdBindVertexBuffers(commandBuffers.at(currentFrame), VERTEX_BUFFER_BINDING_START, buffercount, vkbuffers, vkoffsets);
  1936. }
  1937. void Graphics::setDefaultRenderPass()
  1938. {
  1939. uint32_t numClearValues = 2;
  1940. renderPassState.clearColors.resize(numClearValues);
  1941. renderPassState.beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  1942. renderPassState.beginInfo.renderPass = VK_NULL_HANDLE;
  1943. renderPassState.beginInfo.framebuffer = VK_NULL_HANDLE;
  1944. renderPassState.beginInfo.renderArea.offset = { 0, 0 };
  1945. renderPassState.beginInfo.renderArea.extent = swapChainExtent;
  1946. renderPassState.beginInfo.clearValueCount = numClearValues;
  1947. renderPassState.beginInfo.pClearValues = renderPassState.clearColors.data();
  1948. renderPassState.isWindow = true;
  1949. renderPassState.pipeline = VK_NULL_HANDLE;
  1950. renderPassState.width = static_cast<float>(swapChainExtent.width);
  1951. renderPassState.height = static_cast<float>(swapChainExtent.height);
  1952. renderPassState.msaa = msaaSamples;
  1953. renderPassState.numColorAttachments = 1;
  1954. renderPassState.transitionImages.clear();
  1955. RenderPassConfiguration renderPassConfiguration{};
  1956. renderPassConfiguration.colorAttachments.push_back({ swapChainImageFormat, VK_ATTACHMENT_LOAD_OP_LOAD, msaaSamples });
  1957. renderPassConfiguration.staticData.depthStencilAttachment = { depthStencilFormat, VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_LOAD_OP_LOAD, msaaSamples };
  1958. if (msaaSamples & VK_SAMPLE_COUNT_1_BIT)
  1959. renderPassConfiguration.staticData.resolve = false;
  1960. else
  1961. renderPassConfiguration.staticData.resolve = true;
  1962. FramebufferConfiguration framebufferConfiguration{};
  1963. framebufferConfiguration.staticData.depthView = depthImageView;
  1964. framebufferConfiguration.staticData.width = swapChainExtent.width;
  1965. framebufferConfiguration.staticData.height = swapChainExtent.height;
  1966. if (msaaSamples & VK_SAMPLE_COUNT_1_BIT)
  1967. {
  1968. if (!swapChainImageViews.empty())
  1969. framebufferConfiguration.colorViews.push_back(swapChainImageViews.at(imageIndex));
  1970. else
  1971. framebufferConfiguration.colorViews.push_back(fakeBackbuffer->getRenderTargetView(0, 0));
  1972. framebufferConfiguration.staticData.resolveView = VK_NULL_HANDLE;
  1973. }
  1974. else
  1975. {
  1976. framebufferConfiguration.colorViews.push_back(colorImageView);
  1977. if (!swapChainImageViews.empty())
  1978. framebufferConfiguration.staticData.resolveView = swapChainImageViews.at(imageIndex);
  1979. else
  1980. framebufferConfiguration.staticData.resolveView = fakeBackbuffer->getRenderTargetView(0, 0);
  1981. }
  1982. renderPassState.renderPassConfiguration = std::move(renderPassConfiguration);
  1983. renderPassState.framebufferConfiguration = std::move(framebufferConfiguration);
  1984. // Can't call clear() here because it depends on current RT state, which might not be
  1985. // set yet when this is called from within setRenderTargetsInternal.
  1986. if (renderPassState.windowClearRequested)
  1987. {
  1988. if (renderPassState.mainWindowClearColorValue.hasValue)
  1989. {
  1990. renderPassState.renderPassConfiguration.colorAttachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  1991. renderPassState.clearColors[0].color = Texture::getClearColor(nullptr, renderPassState.mainWindowClearColorValue.value);
  1992. }
  1993. if (renderPassState.mainWindowClearDepthValue.hasValue && backbufferHasDepth)
  1994. {
  1995. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.depthLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  1996. renderPassState.clearColors[1].depthStencil.depth = static_cast<float>(renderPassState.mainWindowClearDepthValue.value);
  1997. }
  1998. if (renderPassState.mainWindowClearStencilValue.hasValue && backbufferHasStencil)
  1999. {
  2000. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2001. renderPassState.clearColors[1].depthStencil.stencil = static_cast<uint32_t>(renderPassState.mainWindowClearStencilValue.value);
  2002. }
  2003. }
  2004. }
  2005. void Graphics::setRenderPass(const RenderTargets &rts, int pixelw, int pixelh, bool hasSRGBtexture)
  2006. {
  2007. // fixme: hasSRGBtexture
  2008. RenderPassConfiguration renderPassConfiguration{};
  2009. for (const auto &color : rts.colors)
  2010. renderPassConfiguration.colorAttachments.push_back({
  2011. Vulkan::getTextureFormat(color.texture->getPixelFormat()).internalFormat,
  2012. VK_ATTACHMENT_LOAD_OP_LOAD,
  2013. dynamic_cast<Texture*>(color.texture)->getMsaaSamples() });
  2014. if (rts.depthStencil.texture != nullptr)
  2015. renderPassConfiguration.staticData.depthStencilAttachment = {
  2016. Vulkan::getTextureFormat(rts.depthStencil.texture->getPixelFormat()).internalFormat,
  2017. VK_ATTACHMENT_LOAD_OP_LOAD,
  2018. VK_ATTACHMENT_LOAD_OP_LOAD,
  2019. dynamic_cast<Texture*>(rts.depthStencil.texture)->getMsaaSamples() };
  2020. FramebufferConfiguration configuration{};
  2021. std::vector<std::tuple<VkImage, PixelFormat, VkImageLayout, VkImageLayout, int, int>> transitionImages;
  2022. for (const auto &color : rts.colors)
  2023. {
  2024. auto tex = (Texture*)color.texture;
  2025. configuration.colorViews.push_back(tex->getRenderTargetView(color.mipmap, color.slice));
  2026. const Texture::ViewInfo &viewinfo = tex->getRootViewInfo();
  2027. VkImageLayout imagelayout = tex->getImageLayout();
  2028. if (imagelayout != VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)
  2029. {
  2030. transitionImages.push_back({ (VkImage)tex->getHandle(), tex->getPixelFormat(), imagelayout, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  2031. viewinfo.startMipmap + color.mipmap, viewinfo.startLayer + color.slice });
  2032. }
  2033. }
  2034. if (rts.depthStencil.texture != nullptr)
  2035. {
  2036. auto tex = (Texture*)rts.depthStencil.texture;
  2037. configuration.staticData.depthView = tex->getRenderTargetView(rts.depthStencil.mipmap, rts.depthStencil.slice);
  2038. const Texture::ViewInfo &viewinfo = tex->getRootViewInfo();
  2039. VkImageLayout imagelayout = tex->getImageLayout();
  2040. if (imagelayout != VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
  2041. {
  2042. transitionImages.push_back({ (VkImage)tex->getHandle(), tex->getPixelFormat(), imagelayout, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
  2043. viewinfo.startMipmap + rts.depthStencil.mipmap, viewinfo.startLayer + rts.depthStencil.slice });
  2044. }
  2045. }
  2046. configuration.staticData.width = static_cast<uint32_t>(pixelw);
  2047. configuration.staticData.height = static_cast<uint32_t>(pixelh);
  2048. uint32_t numClearValues = static_cast<uint32_t>(rts.colors.size() + 1);
  2049. renderPassState.clearColors.resize(numClearValues);
  2050. renderPassState.beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  2051. renderPassState.beginInfo.renderPass = VK_NULL_HANDLE;
  2052. renderPassState.beginInfo.framebuffer = VK_NULL_HANDLE;
  2053. renderPassState.beginInfo.renderArea.offset = {0, 0};
  2054. renderPassState.beginInfo.renderArea.extent.width = static_cast<uint32_t>(pixelw);
  2055. renderPassState.beginInfo.renderArea.extent.height = static_cast<uint32_t>(pixelh);
  2056. renderPassState.beginInfo.clearValueCount = numClearValues;
  2057. renderPassState.beginInfo.pClearValues = renderPassState.clearColors.data();
  2058. renderPassState.isWindow = false;
  2059. renderPassState.renderPassConfiguration = renderPassConfiguration;
  2060. renderPassState.framebufferConfiguration = configuration;
  2061. renderPassState.pipeline = VK_NULL_HANDLE;
  2062. renderPassState.width = static_cast<float>(pixelw);
  2063. renderPassState.height = static_cast<float>(pixelh);
  2064. renderPassState.msaa = VK_SAMPLE_COUNT_1_BIT;
  2065. renderPassState.numColorAttachments = static_cast<uint32_t>(rts.colors.size());
  2066. renderPassState.transitionImages = std::move(transitionImages);
  2067. }
  2068. void Graphics::startRenderPass()
  2069. {
  2070. renderPassState.active = true;
  2071. if (renderPassState.isWindow && renderPassState.windowClearRequested)
  2072. renderPassState.windowClearRequested = false;
  2073. VkViewport viewport{};
  2074. viewport.x = 0.0f;
  2075. viewport.y = 0.0f;
  2076. viewport.width = renderPassState.width;
  2077. viewport.height = renderPassState.height;
  2078. viewport.minDepth = 0.0f;
  2079. viewport.maxDepth = 1.0f;
  2080. vkCmdSetViewport(commandBuffers.at(currentFrame), 0, 1, &viewport);
  2081. renderPassState.beginInfo.renderPass = getRenderPass(renderPassState.renderPassConfiguration);
  2082. renderPassState.framebufferConfiguration.staticData.renderPass = renderPassState.beginInfo.renderPass;
  2083. renderPassState.beginInfo.framebuffer = getFramebuffer(renderPassState.framebufferConfiguration);
  2084. for (const auto &[image, format, imageLayout, renderLayout, rootmip, rootlayer] : renderPassState.transitionImages)
  2085. Vulkan::cmdTransitionImageLayout(commandBuffers.at(currentFrame), image, format, imageLayout, renderLayout, rootmip, 1, rootlayer, 1);
  2086. vkCmdBeginRenderPass(commandBuffers.at(currentFrame), &renderPassState.beginInfo, VK_SUBPASS_CONTENTS_INLINE);
  2087. applyScissor();
  2088. }
  2089. void Graphics::endRenderPass()
  2090. {
  2091. renderPassState.active = false;
  2092. vkCmdEndRenderPass(commandBuffers.at(currentFrame));
  2093. for (const auto &[image, format, imageLayout, renderLayout, rootmip, rootlayer] : renderPassState.transitionImages)
  2094. Vulkan::cmdTransitionImageLayout(commandBuffers.at(currentFrame), image, format, renderLayout, imageLayout, rootmip, 1, rootlayer, 1);
  2095. for (auto &colorAttachment : renderPassState.renderPassConfiguration.colorAttachments)
  2096. colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2097. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.depthLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2098. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2099. }
  2100. VkSampler Graphics::createSampler(const SamplerState &samplerState)
  2101. {
  2102. VkSamplerCreateInfo samplerInfo{};
  2103. samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  2104. samplerInfo.magFilter = Vulkan::getFilter(samplerState.magFilter);
  2105. samplerInfo.minFilter = Vulkan::getFilter(samplerState.minFilter);
  2106. samplerInfo.addressModeU = Vulkan::getWrapMode(samplerState.wrapU);
  2107. samplerInfo.addressModeV = Vulkan::getWrapMode(samplerState.wrapV);
  2108. samplerInfo.addressModeW = Vulkan::getWrapMode(samplerState.wrapW);
  2109. samplerInfo.anisotropyEnable = VK_TRUE;
  2110. samplerInfo.maxAnisotropy = static_cast<float>(samplerState.maxAnisotropy);
  2111. // TODO: This probably needs to branch on a pixel format to determine whether
  2112. // it should be float vs int, and opaque vs transparent.
  2113. bool clampone = samplerState.wrapU == SamplerState::WRAP_CLAMP_ONE
  2114. || samplerState.wrapV == SamplerState::WRAP_CLAMP_ONE
  2115. || samplerState.wrapW == SamplerState::WRAP_CLAMP_ONE;
  2116. samplerInfo.borderColor = clampone ? VK_BORDER_COLOR_INT_OPAQUE_WHITE : VK_BORDER_COLOR_INT_OPAQUE_BLACK;
  2117. samplerInfo.unnormalizedCoordinates = VK_FALSE;
  2118. if (samplerState.depthSampleMode.hasValue)
  2119. {
  2120. samplerInfo.compareEnable = VK_TRUE;
  2121. // See the comment in renderstate.h
  2122. samplerInfo.compareOp = Vulkan::getCompareOp(getReversedCompareMode(samplerState.depthSampleMode.value));
  2123. }
  2124. else
  2125. {
  2126. samplerInfo.compareEnable = VK_FALSE;
  2127. samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
  2128. }
  2129. samplerInfo.mipmapMode = Vulkan::getMipMapMode(samplerState.mipmapFilter);
  2130. samplerInfo.mipLodBias = samplerState.lodBias;
  2131. samplerInfo.minLod = static_cast<float>(samplerState.minLod);
  2132. samplerInfo.maxLod = static_cast<float>(samplerState.maxLod);
  2133. VkSampler sampler;
  2134. if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS)
  2135. throw love::Exception("failed to create sampler");
  2136. return sampler;
  2137. }
  2138. template<typename Configuration, typename ObjectHandle, typename ConfigurationHasher, typename Deleter>
  2139. static void eraseUnusedObjects(
  2140. std::unordered_map<Configuration, ObjectHandle, ConfigurationHasher> &objects,
  2141. std::unordered_map<ObjectHandle, bool> &usages,
  2142. Deleter deleter,
  2143. VkDevice device)
  2144. {
  2145. std::vector<Configuration> deletionKeys;
  2146. for (const auto &entry : objects)
  2147. {
  2148. if (!usages[entry.second])
  2149. {
  2150. deletionKeys.push_back(entry.first);
  2151. usages.erase(entry.second);
  2152. deleter(device, entry.second, nullptr);
  2153. }
  2154. else
  2155. usages[entry.second] = false;
  2156. }
  2157. for (const auto &key : deletionKeys)
  2158. objects.erase(key);
  2159. }
  2160. void Graphics::cleanupUnusedObjects()
  2161. {
  2162. eraseUnusedObjects(framebuffers, framebufferUsages, vkDestroyFramebuffer, device);
  2163. }
  2164. void Graphics::requestSwapchainRecreation()
  2165. {
  2166. if (swapChain != VK_NULL_HANDLE)
  2167. {
  2168. swapChainRecreationRequested = true;
  2169. }
  2170. }
  2171. void Graphics::setComputeShader(Shader *shader)
  2172. {
  2173. computeShader = shader;
  2174. }
  2175. VkSampler Graphics::getCachedSampler(const SamplerState &samplerState)
  2176. {
  2177. auto samplerkey = samplerState.toKey();
  2178. auto it = samplers.find(samplerkey);
  2179. if (it != samplers.end())
  2180. return it->second;
  2181. else
  2182. {
  2183. VkSampler sampler = createSampler(samplerState);
  2184. samplers.insert({ samplerkey, sampler });
  2185. return sampler;
  2186. }
  2187. }
  2188. VkPipeline Graphics::createGraphicsPipeline(Shader *shader, const GraphicsPipelineConfiguration &configuration)
  2189. {
  2190. VkGraphicsPipelineCreateInfo pipelineInfo{};
  2191. pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  2192. auto &shaderStages = shader->getShaderStages();
  2193. std::vector<VkVertexInputBindingDescription> bindingDescriptions;
  2194. std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
  2195. createVulkanVertexFormat(shader, configuration.vertexAttributes, bindingDescriptions, attributeDescriptions);
  2196. VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
  2197. vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  2198. vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(bindingDescriptions.size());
  2199. vertexInputInfo.pVertexBindingDescriptions = bindingDescriptions.data();
  2200. vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
  2201. vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data();
  2202. VkPipelineViewportStateCreateInfo viewportState{};
  2203. viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  2204. viewportState.viewportCount = 1;
  2205. viewportState.scissorCount = 1;
  2206. VkPipelineMultisampleStateCreateInfo multisampling{};
  2207. multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  2208. multisampling.sampleShadingEnable = VK_FALSE;
  2209. multisampling.rasterizationSamples = configuration.msaaSamples;
  2210. VkPipelineRasterizationStateCreateInfo rasterizer{};
  2211. rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  2212. rasterizer.depthClampEnable = VK_FALSE;
  2213. rasterizer.rasterizerDiscardEnable = VK_FALSE;
  2214. rasterizer.polygonMode = Vulkan::getPolygonMode(configuration.wireFrame);
  2215. rasterizer.lineWidth = 1.0f;
  2216. if (!optionalDeviceExtensions.extendedDynamicState)
  2217. {
  2218. rasterizer.cullMode = Vulkan::getCullMode(configuration.dynamicState.cullmode);
  2219. rasterizer.frontFace = Vulkan::getFrontFace(configuration.dynamicState.winding);
  2220. }
  2221. rasterizer.depthBiasEnable = VK_FALSE;
  2222. rasterizer.depthBiasConstantFactor = 0.0f;
  2223. rasterizer.depthBiasClamp = 0.0f;
  2224. rasterizer.depthBiasSlopeFactor = 0.0f;
  2225. VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
  2226. inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  2227. inputAssembly.topology = Vulkan::getPrimitiveTypeTopology(configuration.primitiveType);
  2228. inputAssembly.primitiveRestartEnable = VK_FALSE;
  2229. VkPipelineDepthStencilStateCreateInfo depthStencil{};
  2230. depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  2231. depthStencil.depthTestEnable = VK_TRUE;
  2232. if (!optionalDeviceExtensions.extendedDynamicState)
  2233. {
  2234. depthStencil.depthWriteEnable = Vulkan::getBool(configuration.dynamicState.depthState.write);
  2235. depthStencil.depthCompareOp = Vulkan::getCompareOp(configuration.dynamicState.depthState.compare);
  2236. }
  2237. depthStencil.depthBoundsTestEnable = VK_FALSE;
  2238. depthStencil.minDepthBounds = 0.0f;
  2239. depthStencil.maxDepthBounds = 1.0f;
  2240. depthStencil.stencilTestEnable = VK_TRUE;
  2241. if (!optionalDeviceExtensions.extendedDynamicState)
  2242. {
  2243. depthStencil.front.failOp = VK_STENCIL_OP_KEEP;
  2244. depthStencil.front.passOp = Vulkan::getStencilOp(configuration.dynamicState.stencilAction);
  2245. depthStencil.front.depthFailOp = VK_STENCIL_OP_KEEP;
  2246. depthStencil.front.compareOp = Vulkan::getCompareOp(getReversedCompareMode(configuration.dynamicState.stencilCompare));
  2247. depthStencil.back.failOp = VK_STENCIL_OP_KEEP;
  2248. depthStencil.back.passOp = Vulkan::getStencilOp(configuration.dynamicState.stencilAction);
  2249. depthStencil.back.depthFailOp = VK_STENCIL_OP_KEEP;
  2250. depthStencil.back.compareOp = Vulkan::getCompareOp(getReversedCompareMode(configuration.dynamicState.stencilCompare));
  2251. }
  2252. pipelineInfo.pDepthStencilState = &depthStencil;
  2253. VkPipelineColorBlendAttachmentState colorBlendAttachment{};
  2254. colorBlendAttachment.colorWriteMask = Vulkan::getColorMask(configuration.colorChannelMask);
  2255. colorBlendAttachment.blendEnable = Vulkan::getBool(configuration.blendState.enable);
  2256. colorBlendAttachment.srcColorBlendFactor = Vulkan::getBlendFactor(configuration.blendState.srcFactorRGB);
  2257. colorBlendAttachment.dstColorBlendFactor = Vulkan::getBlendFactor(configuration.blendState.dstFactorRGB);
  2258. colorBlendAttachment.colorBlendOp = Vulkan::getBlendOp(configuration.blendState.operationRGB);
  2259. colorBlendAttachment.srcAlphaBlendFactor = Vulkan::getBlendFactor(configuration.blendState.srcFactorA);
  2260. colorBlendAttachment.dstAlphaBlendFactor = Vulkan::getBlendFactor(configuration.blendState.dstFactorA);
  2261. colorBlendAttachment.alphaBlendOp = Vulkan::getBlendOp(configuration.blendState.operationA);
  2262. std::vector<VkPipelineColorBlendAttachmentState> colorBlendAttachments(configuration.numColorAttachments, colorBlendAttachment);
  2263. VkPipelineColorBlendStateCreateInfo colorBlending{};
  2264. colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  2265. colorBlending.logicOpEnable = VK_FALSE;
  2266. colorBlending.logicOp = VK_LOGIC_OP_COPY;
  2267. colorBlending.attachmentCount = static_cast<uint32_t>(colorBlendAttachments.size());
  2268. colorBlending.pAttachments = colorBlendAttachments.data();
  2269. colorBlending.blendConstants[0] = 0.0f;
  2270. colorBlending.blendConstants[1] = 0.0f;
  2271. colorBlending.blendConstants[2] = 0.0f;
  2272. colorBlending.blendConstants[3] = 0.0f;
  2273. std::vector<VkDynamicState> dynamicStates;
  2274. if (optionalDeviceExtensions.extendedDynamicState)
  2275. dynamicStates = {
  2276. VK_DYNAMIC_STATE_SCISSOR,
  2277. VK_DYNAMIC_STATE_VIEWPORT,
  2278. VK_DYNAMIC_STATE_STENCIL_WRITE_MASK,
  2279. VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK,
  2280. VK_DYNAMIC_STATE_STENCIL_REFERENCE,
  2281. VK_DYNAMIC_STATE_CULL_MODE_EXT,
  2282. VK_DYNAMIC_STATE_FRONT_FACE_EXT,
  2283. VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE_EXT,
  2284. VK_DYNAMIC_STATE_DEPTH_COMPARE_OP_EXT,
  2285. VK_DYNAMIC_STATE_STENCIL_OP_EXT,
  2286. };
  2287. else
  2288. dynamicStates = {
  2289. VK_DYNAMIC_STATE_SCISSOR,
  2290. VK_DYNAMIC_STATE_VIEWPORT,
  2291. VK_DYNAMIC_STATE_STENCIL_WRITE_MASK,
  2292. VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK,
  2293. VK_DYNAMIC_STATE_STENCIL_REFERENCE,
  2294. };
  2295. VkPipelineDynamicStateCreateInfo dynamicState{};
  2296. dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  2297. dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size());
  2298. dynamicState.pDynamicStates = dynamicStates.data();
  2299. pipelineInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
  2300. pipelineInfo.pStages = shaderStages.data();
  2301. pipelineInfo.pVertexInputState = &vertexInputInfo;
  2302. pipelineInfo.pInputAssemblyState = &inputAssembly;
  2303. pipelineInfo.pViewportState = &viewportState;
  2304. pipelineInfo.pRasterizationState = &rasterizer;
  2305. pipelineInfo.pMultisampleState = &multisampling;
  2306. pipelineInfo.pColorBlendState = &colorBlending;
  2307. pipelineInfo.pDynamicState = &dynamicState;
  2308. pipelineInfo.layout = shader->getGraphicsPipelineLayout();
  2309. pipelineInfo.subpass = 0;
  2310. pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
  2311. pipelineInfo.basePipelineIndex = -1;
  2312. pipelineInfo.renderPass = configuration.renderPass;
  2313. VkPipeline graphicsPipeline;
  2314. if (vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS)
  2315. throw love::Exception("failed to create graphics pipeline");
  2316. return graphicsPipeline;
  2317. }
  2318. VkSampleCountFlagBits Graphics::getMsaaCount(int requestedMsaa) const
  2319. {
  2320. VkPhysicalDeviceProperties physicalDeviceProperties;
  2321. vkGetPhysicalDeviceProperties(physicalDevice, &physicalDeviceProperties);
  2322. VkSampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts & physicalDeviceProperties.limits.framebufferDepthSampleCounts;
  2323. if (counts & VK_SAMPLE_COUNT_64_BIT && requestedMsaa >= 64)
  2324. return VK_SAMPLE_COUNT_64_BIT;
  2325. else if (counts & VK_SAMPLE_COUNT_32_BIT && requestedMsaa >= 32)
  2326. return VK_SAMPLE_COUNT_32_BIT;
  2327. else if (counts & VK_SAMPLE_COUNT_16_BIT && requestedMsaa >= 16)
  2328. return VK_SAMPLE_COUNT_16_BIT;
  2329. else if (counts & VK_SAMPLE_COUNT_8_BIT && requestedMsaa >= 8)
  2330. return VK_SAMPLE_COUNT_8_BIT;
  2331. else if (counts & VK_SAMPLE_COUNT_4_BIT && requestedMsaa >= 4)
  2332. return VK_SAMPLE_COUNT_4_BIT;
  2333. else if (counts & VK_SAMPLE_COUNT_2_BIT && requestedMsaa >= 2)
  2334. return VK_SAMPLE_COUNT_2_BIT;
  2335. else
  2336. return VK_SAMPLE_COUNT_1_BIT;
  2337. }
  2338. void Graphics::setVsync(int vsync)
  2339. {
  2340. if (vsync != this->vsync)
  2341. {
  2342. this->vsync = vsync;
  2343. // With the extension VK_EXT_swapchain_maintenance1 a swapchain recreation might not be needed
  2344. // https://github.com/KhronosGroup/Vulkan-Docs/blob/main/proposals/VK_EXT_swapchain_maintenance1.adoc
  2345. // However, there are not any drivers that support it, yet.
  2346. // Reevaluate again in the future.
  2347. requestSwapchainRecreation();
  2348. }
  2349. }
  2350. int Graphics::getVsync() const
  2351. {
  2352. return vsync;
  2353. }
  2354. void Graphics::mapLocalUniformData(void *data, size_t size, VkDescriptorBufferInfo &bufferInfo)
  2355. {
  2356. size_t alignedSize = alignUp(size, minUniformBufferOffsetAlignment);
  2357. if (localUniformBuffer->getUsableSize() < alignedSize)
  2358. localUniformBuffer.set(new StreamBuffer(this, BUFFERUSAGE_UNIFORM, localUniformBuffer->getSize() * 2), Acquire::NORETAIN);
  2359. auto mapInfo = localUniformBuffer->map(size);
  2360. memcpy(mapInfo.data, data, size);
  2361. bufferInfo.buffer = (VkBuffer)localUniformBuffer->getHandle();
  2362. bufferInfo.offset = localUniformBuffer->unmap(size);
  2363. bufferInfo.range = size;
  2364. localUniformBuffer->markUsed(alignedSize);
  2365. }
  2366. void Graphics::createColorResources()
  2367. {
  2368. if (msaaSamples & VK_SAMPLE_COUNT_1_BIT)
  2369. {
  2370. colorImage = VK_NULL_HANDLE;
  2371. colorImageView = VK_NULL_HANDLE;
  2372. }
  2373. else
  2374. {
  2375. VkFormat colorFormat = swapChainImageFormat;
  2376. VkImageCreateInfo imageInfo{};
  2377. imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  2378. imageInfo.imageType = VK_IMAGE_TYPE_2D;
  2379. imageInfo.format = colorFormat;
  2380. imageInfo.extent.width = swapChainExtent.width;
  2381. imageInfo.extent.height = swapChainExtent.height;
  2382. imageInfo.extent.depth = 1;
  2383. imageInfo.mipLevels = 1;
  2384. imageInfo.arrayLayers = 1;
  2385. imageInfo.samples = msaaSamples;
  2386. imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  2387. imageInfo.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  2388. imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  2389. imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2390. VmaAllocationCreateInfo allocationInfo{};
  2391. allocationInfo.usage = VMA_MEMORY_USAGE_AUTO;
  2392. allocationInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  2393. if (vmaCreateImage(vmaAllocator, &imageInfo, &allocationInfo, &colorImage, &colorImageAllocation, nullptr))
  2394. throw love::Exception("failed to create color image");
  2395. VkImageViewCreateInfo imageViewInfo{};
  2396. imageViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  2397. imageViewInfo.image = colorImage;
  2398. imageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  2399. imageViewInfo.format = colorFormat;
  2400. imageViewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  2401. imageViewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  2402. imageViewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  2403. imageViewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  2404. imageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2405. imageViewInfo.subresourceRange.baseMipLevel = 0;
  2406. imageViewInfo.subresourceRange.levelCount = 1;
  2407. imageViewInfo.subresourceRange.baseArrayLayer = 0;
  2408. imageViewInfo.subresourceRange.layerCount = 1;
  2409. if (vkCreateImageView(device, &imageViewInfo, nullptr, &colorImageView) != VK_SUCCESS)
  2410. throw love::Exception("failed to create color image view");
  2411. }
  2412. }
  2413. VkFormat Graphics::findSupportedFormat(const std::vector<VkFormat> &candidates, VkImageTiling tiling, VkFormatFeatureFlags features)
  2414. {
  2415. for (auto format : candidates)
  2416. {
  2417. VkFormatProperties properties;
  2418. vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &properties);
  2419. if (tiling == VK_IMAGE_TILING_LINEAR && (properties.linearTilingFeatures & features) == features)
  2420. return format;
  2421. else if (tiling == VK_IMAGE_TILING_OPTIMAL && (properties.optimalTilingFeatures & features) == features)
  2422. return format;
  2423. }
  2424. throw love::Exception("failed to find supported format");
  2425. }
  2426. VkFormat Graphics::findDepthFormat()
  2427. {
  2428. return findSupportedFormat(
  2429. { VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
  2430. VK_IMAGE_TILING_OPTIMAL,
  2431. VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
  2432. );
  2433. }
  2434. void Graphics::createDepthResources()
  2435. {
  2436. if (!backbufferHasDepth && !backbufferHasStencil)
  2437. {
  2438. depthImage = VK_NULL_HANDLE;
  2439. depthImageView = VK_NULL_HANDLE;
  2440. return;
  2441. }
  2442. VkImageCreateInfo imageInfo{};
  2443. imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  2444. imageInfo.imageType = VK_IMAGE_TYPE_2D;
  2445. imageInfo.format = depthStencilFormat;
  2446. imageInfo.extent.width = swapChainExtent.width;
  2447. imageInfo.extent.height = swapChainExtent.height;
  2448. imageInfo.extent.depth = 1;
  2449. imageInfo.mipLevels = 1;
  2450. imageInfo.arrayLayers = 1;
  2451. imageInfo.samples = msaaSamples;
  2452. imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  2453. imageInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  2454. imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  2455. imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2456. VmaAllocationCreateInfo allocationInfo{};
  2457. allocationInfo.usage = VMA_MEMORY_USAGE_AUTO;
  2458. allocationInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  2459. if (vmaCreateImage(vmaAllocator, &imageInfo, &allocationInfo, &depthImage, &depthImageAllocation, nullptr) != VK_SUCCESS)
  2460. throw love::Exception("failed to create depth image");
  2461. VkImageViewCreateInfo imageViewInfo{};
  2462. imageViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  2463. imageViewInfo.image = depthImage;
  2464. imageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  2465. imageViewInfo.format = depthStencilFormat;
  2466. imageViewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  2467. imageViewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  2468. imageViewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  2469. imageViewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  2470. if (backbufferHasDepth)
  2471. imageViewInfo.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
  2472. if (backbufferHasStencil)
  2473. imageViewInfo.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  2474. imageViewInfo.subresourceRange.baseMipLevel = 0;
  2475. imageViewInfo.subresourceRange.levelCount = 1;
  2476. imageViewInfo.subresourceRange.baseArrayLayer = 0;
  2477. imageViewInfo.subresourceRange.layerCount = 1;
  2478. if (vkCreateImageView(device, &imageViewInfo, nullptr, &depthImageView) != VK_SUCCESS)
  2479. throw love::Exception("failed to create depth image view");
  2480. }
  2481. void Graphics::createCommandPool()
  2482. {
  2483. QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
  2484. VkCommandPoolCreateInfo poolInfo{};
  2485. poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  2486. poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value;
  2487. poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
  2488. if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS)
  2489. throw love::Exception("failed to create command pool");
  2490. }
  2491. void Graphics::createCommandBuffers()
  2492. {
  2493. commandBuffers.resize(MAX_FRAMES_IN_FLIGHT);
  2494. VkCommandBufferAllocateInfo allocInfo{};
  2495. allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  2496. allocInfo.commandPool = commandPool;
  2497. allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  2498. allocInfo.commandBufferCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
  2499. if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS)
  2500. throw love::Exception("failed to allocate command buffers");
  2501. }
  2502. void Graphics::createSyncObjects()
  2503. {
  2504. imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  2505. renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  2506. inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
  2507. imagesInFlight.resize(swapChainImages.size(), VK_NULL_HANDLE);
  2508. VkSemaphoreCreateInfo semaphoreInfo{};
  2509. semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  2510. VkFenceCreateInfo fenceInfo{};
  2511. fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  2512. fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  2513. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
  2514. if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores.at(i)) != VK_SUCCESS ||
  2515. vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores.at(i)) != VK_SUCCESS ||
  2516. vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences.at(i)) != VK_SUCCESS)
  2517. throw love::Exception("failed to create synchronization objects for a frame!");
  2518. }
  2519. void Graphics::cleanup()
  2520. {
  2521. for (auto &cleanUpFns : cleanUpFunctions)
  2522. for (auto &cleanUpFn : cleanUpFns)
  2523. cleanUpFn();
  2524. cleanUpFunctions.clear();
  2525. vmaDestroyAllocator(vmaAllocator);
  2526. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
  2527. {
  2528. vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
  2529. vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
  2530. vkDestroyFence(device, inFlightFences[i], nullptr);
  2531. }
  2532. vkFreeCommandBuffers(device, commandPool, MAX_FRAMES_IN_FLIGHT, commandBuffers.data());
  2533. for (auto const &p : samplers)
  2534. vkDestroySampler(device, p.second, nullptr);
  2535. samplers.clear();
  2536. for (const auto &entry : renderPasses)
  2537. vkDestroyRenderPass(device, entry.second, nullptr);
  2538. renderPasses.clear();
  2539. for (const auto &entry : framebuffers)
  2540. vkDestroyFramebuffer(device, entry.second, nullptr);
  2541. framebuffers.clear();
  2542. vkDestroyCommandPool(device, commandPool, nullptr);
  2543. vkDestroyPipelineCache(device, pipelineCache, nullptr);
  2544. vkDestroyDevice(device, nullptr);
  2545. }
  2546. void Graphics::cleanupSwapChain()
  2547. {
  2548. if (colorImage)
  2549. {
  2550. vkDestroyImageView(device, colorImageView, nullptr);
  2551. vmaDestroyImage(vmaAllocator, colorImage, colorImageAllocation);
  2552. }
  2553. if (depthImage)
  2554. {
  2555. vkDestroyImageView(device, depthImageView, nullptr);
  2556. vmaDestroyImage(vmaAllocator, depthImage, depthImageAllocation);
  2557. }
  2558. for (const auto &swapChainImageView : swapChainImageViews)
  2559. vkDestroyImageView(device, swapChainImageView, nullptr);
  2560. swapChainImageViews.clear();
  2561. vkDestroySwapchainKHR(device, swapChain, nullptr);
  2562. swapChainImages.clear();
  2563. fakeBackbuffer.set(nullptr);
  2564. swapChain = VK_NULL_HANDLE;
  2565. }
  2566. void Graphics::recreateSwapChain()
  2567. {
  2568. vkDeviceWaitIdle(device);
  2569. cleanupSwapChain();
  2570. createSwapChain();
  2571. createImageViews();
  2572. createColorResources();
  2573. createDepthResources();
  2574. transitionColorDepthLayouts = true;
  2575. }
  2576. love::graphics::Graphics *createInstance()
  2577. {
  2578. love::graphics::Graphics *instance = nullptr;
  2579. try
  2580. {
  2581. instance = new Graphics();
  2582. }
  2583. catch (love::Exception &e)
  2584. {
  2585. printf("Cannot create Vulkan renderer: %s\n", e.what());
  2586. }
  2587. return instance;
  2588. }
  2589. } // vulkan
  2590. } // graphics
  2591. } // love