Graphics.cpp 105 KB

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