Graphics.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  1. #include "Graphics.h"
  2. #include "Buffer.h"
  3. #include "SDL_vulkan.h"
  4. #include "window/Window.h"
  5. #include "common/Exception.h"
  6. #include "Shader.h"
  7. #include "graphics/Texture.h"
  8. #include "Vulkan.h"
  9. #include "common/version.h"
  10. #include "common/pixelformat.h"
  11. #include <algorithm>
  12. #include <vector>
  13. #include <cstring>
  14. #include <set>
  15. #include <fstream>
  16. #include <iostream>
  17. #include <array>
  18. namespace love {
  19. namespace graphics {
  20. namespace vulkan {
  21. static VkIndexType getVulkanIndexBufferType(IndexDataType type) {
  22. switch (type) {
  23. case INDEX_UINT16: return VK_INDEX_TYPE_UINT16;
  24. case INDEX_UINT32: return VK_INDEX_TYPE_UINT32;
  25. default:
  26. throw love::Exception("unknown Index Data type");
  27. }
  28. }
  29. const std::vector<const char*> validationLayers = {
  30. "VK_LAYER_KHRONOS_validation"
  31. };
  32. const std::vector<const char*> deviceExtensions = {
  33. VK_KHR_SWAPCHAIN_EXTENSION_NAME,
  34. // https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_push_descriptor.html
  35. VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME
  36. };
  37. #ifdef NDEBUG
  38. constexpr bool enableValidationLayers = false;
  39. #else
  40. constexpr bool enableValidationLayers = true;
  41. #endif
  42. constexpr int MAX_FRAMES_IN_FLIGHT = 2;
  43. constexpr uint32_t vulkanApiVersion = VK_API_VERSION_1_3;
  44. const char* Graphics::getName() const {
  45. return "love.graphics.vulkan";
  46. }
  47. const VkDevice Graphics::getDevice() const {
  48. return device;
  49. }
  50. const VkPhysicalDevice Graphics::getPhysicalDevice() const {
  51. return physicalDevice;
  52. }
  53. const VmaAllocator Graphics::getVmaAllocator() const {
  54. return vmaAllocator;
  55. }
  56. Graphics::~Graphics() {
  57. // We already cleaned those up by clearing out batchedDrawBuffers.
  58. // We set them to nullptr here so the base class doesn't crash
  59. // when it tries to free this.
  60. batchedDrawState.vb[0] = nullptr;
  61. batchedDrawState.vb[1] = nullptr;
  62. batchedDrawState.indexBuffer = nullptr;
  63. }
  64. // START OVERRIDEN FUNCTIONS
  65. love::graphics::Texture* Graphics::newTexture(const love::graphics::Texture::Settings& settings, const love::graphics::Texture::Slices* data) {
  66. return new Texture(this, settings, data);
  67. }
  68. 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) {
  69. return new Buffer(this, settings, format, data, size, arraylength);
  70. }
  71. // FIXME: clear stencil and depth missing.
  72. void Graphics::clear(OptionalColorD color, OptionalInt stencil, OptionalDouble depth) {
  73. VkClearAttachment attachment{};
  74. if (color.hasValue) {
  75. attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  76. attachment.clearValue.color.float32[0] = static_cast<float>(color.value.r);
  77. attachment.clearValue.color.float32[1] = static_cast<float>(color.value.g);
  78. attachment.clearValue.color.float32[2] = static_cast<float>(color.value.b);
  79. attachment.clearValue.color.float32[3] = static_cast<float>(color.value.a);
  80. }
  81. VkClearRect rect{};
  82. rect.layerCount = 1;
  83. rect.rect.extent.width = static_cast<uint32_t>(currentViewportWidth);
  84. rect.rect.extent.height = static_cast<uint32_t>(currentViewportHeight);
  85. vkCmdClearAttachments(commandBuffers[imageIndex], 1, &attachment, 1, &rect);
  86. }
  87. void Graphics::clear(const std::vector<OptionalColorD>& colors, OptionalInt stencil, OptionalDouble depth) {
  88. std::vector<VkClearAttachment> attachments;
  89. for (const auto& color : colors) {
  90. VkClearAttachment attachment{};
  91. if (color.hasValue) {
  92. attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  93. attachment.clearValue.color.float32[0] = static_cast<float>(color.value.r);
  94. attachment.clearValue.color.float32[1] = static_cast<float>(color.value.g);
  95. attachment.clearValue.color.float32[2] = static_cast<float>(color.value.b);
  96. attachment.clearValue.color.float32[3] = static_cast<float>(color.value.a);
  97. }
  98. attachments.push_back(attachment);
  99. }
  100. VkClearRect rect{};
  101. rect.layerCount = 1;
  102. rect.rect.extent.width = static_cast<uint32_t>(currentViewportWidth);
  103. rect.rect.extent.height = static_cast<uint32_t>(currentViewportHeight);
  104. vkCmdClearAttachments(commandBuffers[imageIndex], static_cast<uint32_t>(attachments.size()), attachments.data(), 1, &rect);
  105. }
  106. void Graphics::present(void* screenshotCallbackdata) {
  107. if (!isActive()) {
  108. return;
  109. }
  110. flushBatchedDraws();
  111. endRecordingGraphicsCommands();
  112. if (imagesInFlight[imageIndex] != VK_NULL_HANDLE) {
  113. vkWaitForFences(device, 1, &imagesInFlight.at(imageIndex), VK_TRUE, UINT64_MAX);
  114. }
  115. imagesInFlight[imageIndex] = inFlightFences[currentFrame];
  116. // all data transfers should happen before any draw calls.
  117. std::vector<VkCommandBuffer> submitCommandbuffers = { dataTransferCommandBuffers.at(currentFrame), commandBuffers.at(imageIndex) };
  118. VkSubmitInfo submitInfo{};
  119. submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  120. VkSemaphore waitSemaphores[] = { imageAvailableSemaphores.at(currentFrame) };
  121. VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
  122. submitInfo.waitSemaphoreCount = 1;
  123. submitInfo.pWaitSemaphores = waitSemaphores;
  124. submitInfo.pWaitDstStageMask = waitStages;
  125. submitInfo.commandBufferCount = static_cast<uint32_t>(submitCommandbuffers.size());
  126. submitInfo.pCommandBuffers = submitCommandbuffers.data();
  127. VkSemaphore signalSemaphores[] = { renderFinishedSemaphores.at(currentFrame) };
  128. submitInfo.signalSemaphoreCount = 1;
  129. submitInfo.pSignalSemaphores = signalSemaphores;
  130. vkResetFences(device, 1, &inFlightFences[currentFrame]);
  131. if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences.at(currentFrame)) != VK_SUCCESS) {
  132. throw love::Exception("failed to submit draw command buffer");
  133. }
  134. VkPresentInfoKHR presentInfo{};
  135. presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
  136. presentInfo.waitSemaphoreCount = 1;
  137. presentInfo.pWaitSemaphores = signalSemaphores;
  138. VkSwapchainKHR swapChains[] = { swapChain };
  139. presentInfo.swapchainCount = 1;
  140. presentInfo.pSwapchains = swapChains;
  141. presentInfo.pImageIndices = &imageIndex;
  142. VkResult result = vkQueuePresentKHR(presentQueue, &presentInfo);
  143. if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
  144. framebufferResized = false;
  145. recreateSwapChain();
  146. }
  147. else if (result != VK_SUCCESS) {
  148. throw love::Exception("failed to present swap chain image");
  149. }
  150. currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
  151. updatedBatchedDrawBuffers();
  152. startRecordingGraphicsCommands();
  153. }
  154. void Graphics::setViewportSize(int width, int height, int pixelwidth, int pixelheight) {
  155. this->width = width;
  156. this->height = height;
  157. this->pixelWidth = pixelwidth;
  158. this->pixelHeight = pixelheight;
  159. resetProjection();
  160. }
  161. bool Graphics::setMode(void* context, int width, int height, int pixelwidth, int pixelheight, bool windowhasstencil, int msaa) {
  162. cleanUpFunctions.clear();
  163. cleanUpFunctions.resize(MAX_FRAMES_IN_FLIGHT);
  164. createVulkanInstance();
  165. createSurface();
  166. pickPhysicalDevice();
  167. createLogicalDevice();
  168. initVMA();
  169. initCapabilities();
  170. createSwapChain();
  171. createImageViews();
  172. createCommandPool();
  173. createCommandBuffers();
  174. createDefaultTexture();
  175. createDefaultShaders();
  176. createQuadIndexBuffer();
  177. createSyncObjects();
  178. startRecordingGraphicsCommands();
  179. currentFrame = 0;
  180. created = true;
  181. float whiteColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
  182. batchedDrawBuffers.clear();
  183. batchedDrawBuffers.reserve(MAX_FRAMES_IN_FLIGHT);
  184. for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
  185. batchedDrawBuffers.emplace_back();
  186. // Initial sizes that should be good enough for most cases. It will
  187. // resize to fit if needed, later.
  188. batchedDrawBuffers[i].vertexBuffer1 = new StreamBuffer(this, BUFFERUSAGE_VERTEX, 1024 * 1024 * 1);
  189. batchedDrawBuffers[i].vertexBuffer2 = new StreamBuffer(this, BUFFERUSAGE_VERTEX, 256 * 1024 * 1);
  190. batchedDrawBuffers[i].indexBuffer = new StreamBuffer(this, BUFFERUSAGE_INDEX, sizeof(uint16) * LOVE_UINT16_MAX);
  191. // sometimes the VertexColor is not set, so we manually adjust it to white color
  192. batchedDrawBuffers[i].constantColorBuffer = new StreamBuffer(this, BUFFERUSAGE_VERTEX, sizeof(whiteColor));
  193. auto mapInfo = batchedDrawBuffers[i].constantColorBuffer->map(sizeof(whiteColor));
  194. memcpy(mapInfo.data, whiteColor, sizeof(whiteColor));
  195. batchedDrawBuffers[i].constantColorBuffer->unmap(sizeof(whiteColor));
  196. batchedDrawBuffers[i].constantColorBuffer->markUsed(sizeof(whiteColor));
  197. }
  198. updatedBatchedDrawBuffers();
  199. Shader::current = Shader::standardShaders[graphics::Shader::StandardShader::STANDARD_DEFAULT];
  200. currentPolygonMode = VK_POLYGON_MODE_FILL;
  201. restoreState(states.back());
  202. setViewportSize(width, height, pixelwidth, pixelheight);
  203. renderTargetTexture = nullptr;
  204. currentViewportWidth = 0.0f;
  205. currentViewportHeight = 0.0f;
  206. Vulkan::resetShaderSwitches();
  207. return true;
  208. }
  209. void Graphics::initCapabilities() {
  210. // todo
  211. capabilities.features[FEATURE_MULTI_RENDER_TARGET_FORMATS] = false;
  212. capabilities.features[FEATURE_CLAMP_ZERO] = false;
  213. capabilities.features[FEATURE_CLAMP_ONE] = false;
  214. capabilities.features[FEATURE_BLEND_MINMAX] = false;
  215. capabilities.features[FEATURE_LIGHTEN] = false;
  216. capabilities.features[FEATURE_FULL_NPOT] = false;
  217. capabilities.features[FEATURE_PIXEL_SHADER_HIGHP] = true;
  218. capabilities.features[FEATURE_SHADER_DERIVATIVES] = false;
  219. capabilities.features[FEATURE_GLSL3] = true;
  220. capabilities.features[FEATURE_GLSL4] = true;
  221. capabilities.features[FEATURE_INSTANCING] = false;
  222. capabilities.features[FEATURE_TEXEL_BUFFER] = false;
  223. capabilities.features[FEATURE_INDEX_BUFFER_32BIT] = true;
  224. capabilities.features[FEATURE_COPY_BUFFER] = false;
  225. capabilities.features[FEATURE_COPY_BUFFER_TO_TEXTURE] = false;
  226. capabilities.features[FEATURE_COPY_TEXTURE_TO_BUFFER] = false;
  227. capabilities.features[FEATURE_COPY_RENDER_TARGET_TO_BUFFER] = false;
  228. static_assert(FEATURE_MAX_ENUM == 17, "Graphics::initCapabilities must be updated when adding a new graphics feature!");
  229. VkPhysicalDeviceProperties properties;
  230. vkGetPhysicalDeviceProperties(physicalDevice, &properties);
  231. capabilities.limits[LIMIT_POINT_SIZE] = properties.limits.pointSizeRange[1];
  232. capabilities.limits[LIMIT_TEXTURE_SIZE] = properties.limits.maxImageDimension2D;
  233. capabilities.limits[LIMIT_TEXTURE_LAYERS] = properties.limits.maxImageArrayLayers;
  234. capabilities.limits[LIMIT_VOLUME_TEXTURE_SIZE] = properties.limits.maxImageDimension3D;
  235. capabilities.limits[LIMIT_CUBE_TEXTURE_SIZE] = properties.limits.maxImageDimensionCube;
  236. capabilities.limits[LIMIT_TEXEL_BUFFER_SIZE] = properties.limits.maxTexelBufferElements; // ?
  237. capabilities.limits[LIMIT_SHADER_STORAGE_BUFFER_SIZE] = properties.limits.maxStorageBufferRange; // ?
  238. capabilities.limits[LIMIT_THREADGROUPS_X] = 0; // todo
  239. capabilities.limits[LIMIT_THREADGROUPS_Y] = 0; // todo
  240. capabilities.limits[LIMIT_THREADGROUPS_Z] = 0; // todo
  241. capabilities.limits[LIMIT_RENDER_TARGETS] = 1; // todo
  242. capabilities.limits[LIMIT_TEXTURE_MSAA] = 1; // todo
  243. capabilities.limits[LIMIT_ANISOTROPY] = 1.0f; // todo
  244. static_assert(LIMIT_MAX_ENUM == 13, "Graphics::initCapabilities must be updated when adding a new system limit!");
  245. capabilities.textureTypes[TEXTURE_2D] = true;
  246. capabilities.textureTypes[TEXTURE_2D_ARRAY] = true;
  247. capabilities.textureTypes[TEXTURE_VOLUME] = false;
  248. capabilities.textureTypes[TEXTURE_CUBE] = false;
  249. }
  250. void Graphics::getAPIStats(int& shaderswitches) const {
  251. shaderswitches = Vulkan::getNumShaderSwitches();
  252. }
  253. void Graphics::unSetMode() {
  254. created = false;
  255. vkDeviceWaitIdle(device);
  256. Volatile::unloadAll();
  257. cleanup();
  258. }
  259. void Graphics::setActive(bool enable) {
  260. flushBatchedDraws();
  261. active = enable;
  262. }
  263. void Graphics::setFrontFaceWinding(Winding winding) {
  264. const auto& currentState = states.back();
  265. if (currentState.winding == winding) {
  266. return;
  267. }
  268. flushBatchedDraws();
  269. states.back().winding = winding;
  270. }
  271. void Graphics::setColorMask(ColorChannelMask mask) {
  272. flushBatchedDraws();
  273. states.back().colorMask = mask;
  274. }
  275. void Graphics::setBlendState(const BlendState& blend) {
  276. flushBatchedDraws();
  277. states.back().blend = blend;
  278. }
  279. void Graphics::setPointSize(float size) {
  280. if (size != states.back().pointSize)
  281. flushBatchedDraws();
  282. states.back().pointSize = size;
  283. }
  284. bool Graphics::usesGLSLES() const {
  285. return false;
  286. }
  287. Graphics::RendererInfo Graphics::getRendererInfo() const {
  288. VkPhysicalDeviceProperties deviceProperties;
  289. vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
  290. Graphics::RendererInfo info;
  291. info.device = deviceProperties.deviceName;
  292. info.vendor = Vulkan::getVendorName(deviceProperties.vendorID);
  293. info.version = Vulkan::getVulkanApiVersion(deviceProperties.apiVersion);
  294. info.name = "Vulkan";
  295. return info;
  296. }
  297. void Graphics::draw(const DrawCommand& cmd) {
  298. prepareDraw(*cmd.attributes, *cmd.buffers, cmd.texture, cmd.primitiveType, cmd.cullMode);
  299. vkCmdDraw(commandBuffers.at(imageIndex), static_cast<uint32_t>(cmd.vertexCount), static_cast<uint32_t>(cmd.instanceCount), static_cast<uint32_t>(cmd.vertexStart), 0);
  300. }
  301. void Graphics::draw(const DrawIndexedCommand& cmd) {
  302. prepareDraw(*cmd.attributes, *cmd.buffers, cmd.texture, cmd.primitiveType, cmd.cullMode);
  303. vkCmdBindIndexBuffer(commandBuffers.at(imageIndex), (VkBuffer)cmd.indexBuffer->getHandle(), static_cast<VkDeviceSize>(cmd.indexBufferOffset), getVulkanIndexBufferType(cmd.indexType));
  304. vkCmdDrawIndexed(commandBuffers.at(imageIndex), static_cast<uint32_t>(cmd.indexCount), static_cast<uint32_t>(cmd.instanceCount), 0, 0, 0);
  305. }
  306. void Graphics::drawQuads(int start, int count, const VertexAttributes& attributes, const BufferBindings& buffers, graphics::Texture* texture) {
  307. const int MAX_VERTICES_PER_DRAW = LOVE_UINT16_MAX;
  308. const int MAX_QUADS_PER_DRAW = MAX_VERTICES_PER_DRAW / 4;
  309. prepareDraw(attributes, buffers, texture, PRIMITIVE_TRIANGLES, CULL_BACK);
  310. vkCmdBindIndexBuffer(commandBuffers.at(imageIndex), (VkBuffer)quadIndexBuffer->getHandle(), 0, getVulkanIndexBufferType(INDEX_UINT16));
  311. int baseVertex = start * 4;
  312. for (int quadindex = 0; quadindex < count; quadindex += MAX_QUADS_PER_DRAW) {
  313. int quadcount = std::min(MAX_QUADS_PER_DRAW, count - quadindex);
  314. vkCmdDrawIndexed(commandBuffers.at(imageIndex), static_cast<uint32_t>(quadcount * 6), 1, 0, baseVertex, 0);
  315. baseVertex += quadcount * 4;
  316. }
  317. }
  318. void Graphics::setColor(Colorf c) {
  319. c.r = std::min(std::max(c.r, 0.0f), 1.0f);
  320. c.g = std::min(std::max(c.g, 0.0f), 1.0f);
  321. c.b = std::min(std::max(c.b, 0.0f), 1.0f);
  322. c.a = std::min(std::max(c.a, 0.0f), 1.0f);
  323. states.back().color = c;
  324. }
  325. void Graphics::setScissor(const Rect& rect) {
  326. flushBatchedDraws();
  327. states.back().scissor = true;
  328. states.back().scissorRect = rect;
  329. }
  330. void Graphics::setScissor() {
  331. flushBatchedDraws();
  332. states.back().scissor = false;
  333. }
  334. void Graphics::setWireframe(bool enable) {
  335. flushBatchedDraws();
  336. if (enable) {
  337. currentPolygonMode = VK_POLYGON_MODE_LINE;
  338. }
  339. else {
  340. currentPolygonMode = VK_POLYGON_MODE_FILL;
  341. }
  342. states.back().wireframe = enable;
  343. }
  344. PixelFormat Graphics::getSizedFormat(PixelFormat format, bool rendertarget, bool readable) const {
  345. switch (format) {
  346. case PIXELFORMAT_NORMAL:
  347. if (isGammaCorrect()) {
  348. return PIXELFORMAT_RGBA8_UNORM_sRGB;
  349. }
  350. else {
  351. return PIXELFORMAT_RGBA8_UNORM;
  352. }
  353. case PIXELFORMAT_HDR:
  354. return PIXELFORMAT_RGBA16_FLOAT;
  355. default:
  356. return format;
  357. }
  358. }
  359. bool Graphics::isPixelFormatSupported(PixelFormat format, uint32 usage, bool sRGB) {
  360. return true;
  361. }
  362. Renderer Graphics::getRenderer() const {
  363. return RENDERER_VULKAN;
  364. }
  365. graphics::StreamBuffer* Graphics::newStreamBuffer(BufferUsage type, size_t size) {
  366. return new StreamBuffer(this, type, size);
  367. }
  368. Matrix4 Graphics::computeDeviceProjection(const Matrix4& projection, bool rendertotexture) const {
  369. uint32 flags = DEVICE_PROJECTION_DEFAULT;
  370. return calculateDeviceProjection(projection, flags);
  371. }
  372. void Graphics::setRenderTargetsInternal(const RenderTargets& rts, int pixelw, int pixelh, bool hasSRGBtexture) {
  373. endRenderPass();
  374. if (rts.colors.size() == 0) {
  375. startRenderPass(nullptr, swapChainExtent.width, swapChainExtent.height);
  376. } else {
  377. auto& firstRenderTarget = rts.getFirstTarget();
  378. startRenderPass(static_cast<Texture*>(firstRenderTarget.texture), pixelw, pixelh);
  379. }
  380. }
  381. // END IMPLEMENTATION OVERRIDDEN FUNCTIONS
  382. void Graphics::startRecordingGraphicsCommands() {
  383. vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
  384. while (true) {
  385. VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
  386. if (result == VK_ERROR_OUT_OF_DATE_KHR) {
  387. recreateSwapChain();
  388. continue;
  389. }
  390. else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
  391. throw love::Exception("failed to acquire swap chain image");
  392. }
  393. break;
  394. }
  395. for (auto& cleanUpFn : cleanUpFunctions.at(currentFrame)) {
  396. cleanUpFn();
  397. }
  398. cleanUpFunctions.at(currentFrame).clear();
  399. VkCommandBufferBeginInfo beginInfo{};
  400. beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  401. beginInfo.flags = 0;
  402. beginInfo.pInheritanceInfo = nullptr;
  403. if (vkBeginCommandBuffer(commandBuffers.at(imageIndex), &beginInfo) != VK_SUCCESS) {
  404. throw love::Exception("failed to begin recording command buffer");
  405. }
  406. if (vkBeginCommandBuffer(dataTransferCommandBuffers.at(currentFrame), &beginInfo) != VK_SUCCESS) {
  407. throw love::Exception("failed to begin recording data transfer command buffer");
  408. }
  409. Vulkan::cmdTransitionImageLayout(commandBuffers.at(imageIndex), swapChainImages[imageIndex], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  410. startRenderPass(nullptr, swapChainExtent.width, swapChainExtent.height);
  411. Vulkan::resetShaderSwitches();
  412. }
  413. void Graphics::endRecordingGraphicsCommands() {
  414. endRenderPass();
  415. Vulkan::cmdTransitionImageLayout(commandBuffers.at(imageIndex), swapChainImages[imageIndex], VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
  416. if (vkEndCommandBuffer(commandBuffers.at(imageIndex)) != VK_SUCCESS) {
  417. throw love::Exception("failed to record command buffer");
  418. }
  419. if (vkEndCommandBuffer(dataTransferCommandBuffers.at(currentFrame)) != VK_SUCCESS) {
  420. throw love::Exception("failed to record data transfer command buffer");
  421. }
  422. }
  423. void Graphics::updatedBatchedDrawBuffers() {
  424. batchedDrawState.vb[0] = batchedDrawBuffers[currentFrame].vertexBuffer1;
  425. batchedDrawState.vb[0]->nextFrame();
  426. batchedDrawState.vb[1] = batchedDrawBuffers[currentFrame].vertexBuffer2;
  427. batchedDrawState.vb[1]->nextFrame();
  428. batchedDrawState.indexBuffer = batchedDrawBuffers[currentFrame].indexBuffer;
  429. batchedDrawState.indexBuffer->nextFrame();
  430. }
  431. uint32_t Graphics::getNumImagesInFlight() const {
  432. return MAX_FRAMES_IN_FLIGHT;
  433. }
  434. const VkDeviceSize Graphics::getMinUniformBufferOffsetAlignment() const {
  435. return minUniformBufferOffsetAlignment;
  436. }
  437. graphics::Texture* Graphics::getDefaultTexture() const {
  438. return dynamic_cast<graphics::Texture*>(standardTexture.get());
  439. }
  440. const PFN_vkCmdPushDescriptorSetKHR Graphics::getVkCmdPushDescriptorSetKHRFunctionPointer() const {
  441. return vkCmdPushDescriptorSet;
  442. }
  443. void Graphics::queueDatatransfer(std::function<void(VkCommandBuffer)> command, std::function<void()> cleanUp) {
  444. command(dataTransferCommandBuffers.at(currentFrame));
  445. if (cleanUp) {
  446. cleanUpFunctions.at(currentFrame).push_back(std::move(cleanUp));
  447. }
  448. }
  449. void Graphics::queueCleanUp(std::function<void()> cleanUp) {
  450. cleanUpFunctions.at(currentFrame).push_back(std::move(cleanUp));
  451. }
  452. VkCommandBuffer Graphics::beginSingleTimeCommands() {
  453. VkCommandBufferAllocateInfo allocInfo{};
  454. allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  455. allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  456. allocInfo.commandPool = commandPool;
  457. allocInfo.commandBufferCount = 1;
  458. VkCommandBuffer commandBuffer;
  459. vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
  460. VkCommandBufferBeginInfo beginInfo{};
  461. beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  462. beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  463. vkBeginCommandBuffer(commandBuffer, &beginInfo);
  464. return commandBuffer;
  465. }
  466. void Graphics::endSingleTimeCommands(VkCommandBuffer commandBuffer) {
  467. vkEndCommandBuffer(commandBuffer);
  468. VkSubmitInfo submitInfo{};
  469. submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  470. submitInfo.commandBufferCount = 1;
  471. submitInfo.pCommandBuffers = &commandBuffer;
  472. vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
  473. vkQueueWaitIdle(graphicsQueue);
  474. vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
  475. }
  476. graphics::Shader::BuiltinUniformData Graphics::getCurrentBuiltinUniformData() {
  477. love::graphics::Shader::BuiltinUniformData data;
  478. data.transformMatrix = getTransform();
  479. data.projectionMatrix = getDeviceProjection();
  480. // The normal matrix is the transpose of the inverse of the rotation portion
  481. // (top-left 3x3) of the transform matrix.
  482. {
  483. Matrix3 normalmatrix = Matrix3(data.transformMatrix).transposedInverse();
  484. const float* e = normalmatrix.getElements();
  485. for (int i = 0; i < 3; i++)
  486. {
  487. data.normalMatrix[i].x = e[i * 3 + 0];
  488. data.normalMatrix[i].y = e[i * 3 + 1];
  489. data.normalMatrix[i].z = e[i * 3 + 2];
  490. data.normalMatrix[i].w = 0.0f;
  491. }
  492. }
  493. // Store DPI scale in an unused component of another vector.
  494. data.normalMatrix[0].w = (float)getCurrentDPIScale();
  495. // Same with point size.
  496. data.normalMatrix[1].w = getPointSize();
  497. data.screenSizeParams.x = static_cast<float>(swapChainExtent.width);
  498. data.screenSizeParams.y = static_cast<float>(swapChainExtent.height);
  499. data.screenSizeParams.z = 1.0f;
  500. data.screenSizeParams.w = 0.0f;
  501. data.constantColor = getColor();
  502. gammaCorrectColor(data.constantColor);
  503. return data;
  504. }
  505. void Graphics::createVulkanInstance() {
  506. if (enableValidationLayers && !checkValidationSupport()) {
  507. throw love::Exception("validation layers requested, but not available");
  508. }
  509. VkApplicationInfo appInfo{};
  510. appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  511. appInfo.pApplicationName = "LOVE";
  512. appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); //todo, get this version from somewhere else?
  513. appInfo.pEngineName = "LOVE Engine";
  514. appInfo.engineVersion = VK_MAKE_VERSION(VERSION_MAJOR, VERSION_MINOR, VERSION_REV);
  515. appInfo.apiVersion = vulkanApiVersion;
  516. VkInstanceCreateInfo createInfo{};
  517. createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  518. createInfo.pApplicationInfo = &appInfo;
  519. createInfo.pNext = nullptr;
  520. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  521. const void* handle = window->getHandle();
  522. unsigned int count;
  523. if (SDL_Vulkan_GetInstanceExtensions((SDL_Window*)handle, &count, nullptr) != SDL_TRUE) {
  524. throw love::Exception("couldn't retrieve sdl vulkan extensions");
  525. }
  526. std::vector<const char*> extensions = {}; // can add more here
  527. size_t addition_extension_count = extensions.size();
  528. extensions.resize(addition_extension_count + count);
  529. if (SDL_Vulkan_GetInstanceExtensions((SDL_Window*)handle, &count, extensions.data() + addition_extension_count) != SDL_TRUE) {
  530. throw love::Exception("couldn't retrieve sdl vulkan extensions");
  531. }
  532. createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
  533. createInfo.ppEnabledExtensionNames = extensions.data();
  534. if (enableValidationLayers) {
  535. createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
  536. createInfo.ppEnabledLayerNames = validationLayers.data();
  537. }
  538. else {
  539. createInfo.enabledLayerCount = 0;
  540. createInfo.ppEnabledLayerNames = nullptr;
  541. }
  542. if (vkCreateInstance(
  543. &createInfo,
  544. nullptr,
  545. &instance) != VK_SUCCESS) {
  546. throw love::Exception("couldn't create vulkan instance");
  547. }
  548. }
  549. bool Graphics::checkValidationSupport() {
  550. uint32_t layerCount;
  551. vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
  552. std::vector<VkLayerProperties> availableLayers(layerCount);
  553. vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
  554. for (const char* layerName : validationLayers) {
  555. bool layerFound = false;
  556. for (const auto& layerProperties : availableLayers) {
  557. if (strcmp(layerName, layerProperties.layerName) == 0) {
  558. layerFound = true;
  559. break;
  560. }
  561. }
  562. if (!layerFound) {
  563. return false;
  564. }
  565. }
  566. return true;
  567. }
  568. void Graphics::pickPhysicalDevice() {
  569. uint32_t deviceCount = 0;
  570. vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
  571. if (deviceCount == 0) {
  572. throw love::Exception("failed to find GPUs with Vulkan support");
  573. }
  574. std::vector<VkPhysicalDevice> devices(deviceCount);
  575. vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
  576. std::multimap<int, VkPhysicalDevice> candidates;
  577. for (const auto& device : devices) {
  578. int score = rateDeviceSuitability(device);
  579. candidates.insert(std::make_pair(score, device));
  580. }
  581. if (candidates.rbegin()->first > 0) {
  582. physicalDevice = candidates.rbegin()->second;
  583. }
  584. else {
  585. throw love::Exception("failed to find a suitable gpu");
  586. }
  587. VkPhysicalDeviceProperties properties;
  588. vkGetPhysicalDeviceProperties(physicalDevice, &properties);
  589. minUniformBufferOffsetAlignment = properties.limits.minUniformBufferOffsetAlignment;
  590. }
  591. bool Graphics::checkDeviceExtensionSupport(VkPhysicalDevice device) {
  592. uint32_t extensionCount;
  593. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
  594. std::vector<VkExtensionProperties> availableExtensions(extensionCount);
  595. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
  596. std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
  597. for (const auto& extension : availableExtensions) {
  598. requiredExtensions.erase(extension.extensionName);
  599. }
  600. return requiredExtensions.empty();
  601. }
  602. // if the score is nonzero then the device is suitable.
  603. // A higher rating means generally better performance
  604. // if the score is 0 the device is unsuitable
  605. int Graphics::rateDeviceSuitability(VkPhysicalDevice device) {
  606. VkPhysicalDeviceProperties deviceProperties;
  607. VkPhysicalDeviceFeatures deviceFeatures;
  608. vkGetPhysicalDeviceProperties(device, &deviceProperties);
  609. vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
  610. int score = 1;
  611. // optional
  612. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) {
  613. score += 1000;
  614. }
  615. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) {
  616. score += 100;
  617. }
  618. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU) {
  619. score += 10;
  620. }
  621. // definitely needed
  622. QueueFamilyIndices indices = findQueueFamilies(device);
  623. if (!indices.isComplete()) {
  624. score = 0;
  625. }
  626. bool extensionsSupported = checkDeviceExtensionSupport(device);
  627. if (!extensionsSupported) {
  628. score = 0;
  629. }
  630. if (extensionsSupported) {
  631. auto swapChainSupport = querySwapChainSupport(device);
  632. bool swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
  633. if (!swapChainAdequate) {
  634. score = 0;
  635. }
  636. }
  637. if (!deviceFeatures.samplerAnisotropy) {
  638. score = 0;
  639. }
  640. if (!deviceFeatures.fillModeNonSolid) {
  641. score = 0;
  642. }
  643. return score;
  644. }
  645. QueueFamilyIndices Graphics::findQueueFamilies(VkPhysicalDevice device) {
  646. QueueFamilyIndices indices;
  647. uint32_t queueFamilyCount = 0;
  648. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
  649. std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
  650. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
  651. int i = 0;
  652. for (const auto& queueFamily : queueFamilies) {
  653. if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
  654. indices.graphicsFamily = i;
  655. }
  656. VkBool32 presentSupport = false;
  657. vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
  658. if (presentSupport) {
  659. indices.presentFamily = i;
  660. }
  661. if (indices.isComplete()) {
  662. break;
  663. }
  664. i++;
  665. }
  666. return indices;
  667. }
  668. void Graphics::createLogicalDevice() {
  669. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  670. std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
  671. std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
  672. float queuePriority = 1.0f;
  673. for (uint32_t queueFamily : uniqueQueueFamilies) {
  674. VkDeviceQueueCreateInfo queueCreateInfo{};
  675. queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  676. queueCreateInfo.queueFamilyIndex = queueFamily;
  677. queueCreateInfo.queueCount = 1;
  678. queueCreateInfo.pQueuePriorities = &queuePriority;
  679. queueCreateInfos.push_back(queueCreateInfo);
  680. }
  681. VkPhysicalDeviceDynamicRenderingFeatures dynamicRenderingFeature{};
  682. dynamicRenderingFeature.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES;
  683. dynamicRenderingFeature.dynamicRendering = VK_TRUE;
  684. VkPhysicalDeviceFeatures deviceFeatures{};
  685. deviceFeatures.samplerAnisotropy = VK_TRUE;
  686. VkDeviceCreateInfo createInfo{};
  687. createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  688. createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
  689. createInfo.pQueueCreateInfos = queueCreateInfos.data();
  690. createInfo.pEnabledFeatures = &deviceFeatures;
  691. createInfo.pNext = &dynamicRenderingFeature;
  692. createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
  693. createInfo.ppEnabledExtensionNames = deviceExtensions.data();
  694. // can this be removed?
  695. if (enableValidationLayers) {
  696. createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
  697. createInfo.ppEnabledLayerNames = validationLayers.data();
  698. }
  699. else {
  700. createInfo.enabledLayerCount = 0;
  701. }
  702. if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
  703. throw love::Exception("failed to create logical device");
  704. }
  705. vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
  706. vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
  707. vkCmdPushDescriptorSet = (PFN_vkCmdPushDescriptorSetKHR) vkGetDeviceProcAddr(device, "vkCmdPushDescriptorSetKHR");
  708. if (!vkCmdPushDescriptorSet) {
  709. // fixme: how widely adopted is this extension?
  710. throw love::Exception("could not get a valid function pointer for vkCmdPushDescriptorSetKHR");
  711. }
  712. }
  713. void Graphics::initVMA() {
  714. VmaVulkanFunctions vulkanFunctions = {};
  715. vulkanFunctions.vkGetInstanceProcAddr = &vkGetInstanceProcAddr;
  716. vulkanFunctions.vkGetDeviceProcAddr = &vkGetDeviceProcAddr;
  717. VmaAllocatorCreateInfo allocatorCreateInfo = {};
  718. allocatorCreateInfo.vulkanApiVersion = vulkanApiVersion;
  719. allocatorCreateInfo.physicalDevice = physicalDevice;
  720. allocatorCreateInfo.device = device;
  721. allocatorCreateInfo.instance = instance;
  722. allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions;
  723. if (vmaCreateAllocator(&allocatorCreateInfo, &vmaAllocator) != VK_SUCCESS) {
  724. throw love::Exception("failed to create vma allocator");
  725. }
  726. }
  727. void Graphics::createSurface() {
  728. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  729. const void* handle = window->getHandle();
  730. if (SDL_Vulkan_CreateSurface((SDL_Window*)handle, instance, &surface) != SDL_TRUE) {
  731. throw love::Exception("failed to create window surface");
  732. }
  733. }
  734. SwapChainSupportDetails Graphics::querySwapChainSupport(VkPhysicalDevice device) {
  735. SwapChainSupportDetails details;
  736. vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
  737. uint32_t formatCount;
  738. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
  739. if (formatCount != 0) {
  740. details.formats.resize(formatCount);
  741. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
  742. }
  743. uint32_t presentModeCount;
  744. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
  745. if (presentModeCount != 0) {
  746. details.presentModes.resize(presentModeCount);
  747. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
  748. }
  749. return details;
  750. }
  751. void Graphics::createSwapChain() {
  752. SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
  753. VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
  754. VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
  755. VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
  756. uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
  757. if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
  758. imageCount = swapChainSupport.capabilities.maxImageCount;
  759. }
  760. VkSwapchainCreateInfoKHR createInfo{};
  761. createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  762. createInfo.surface = surface;
  763. createInfo.minImageCount = imageCount;
  764. createInfo.imageFormat = surfaceFormat.format;
  765. createInfo.imageColorSpace = surfaceFormat.colorSpace;
  766. createInfo.imageExtent = extent;
  767. createInfo.imageArrayLayers = 1;
  768. createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  769. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  770. uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
  771. if (indices.graphicsFamily != indices.presentFamily) {
  772. createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
  773. createInfo.queueFamilyIndexCount = 2;
  774. createInfo.pQueueFamilyIndices = queueFamilyIndices;
  775. }
  776. else {
  777. createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
  778. createInfo.queueFamilyIndexCount = 0;
  779. createInfo.pQueueFamilyIndices = nullptr;
  780. }
  781. createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
  782. createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  783. createInfo.presentMode = presentMode;
  784. createInfo.clipped = VK_TRUE;
  785. createInfo.oldSwapchain = VK_NULL_HANDLE;
  786. if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
  787. throw love::Exception("failed to create swap chain");
  788. }
  789. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
  790. swapChainImages.resize(imageCount);
  791. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
  792. swapChainImageFormat = surfaceFormat.format;
  793. swapChainExtent = extent;
  794. }
  795. VkSurfaceFormatKHR Graphics::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) {
  796. for (const auto& availableFormat : availableFormats) {
  797. // fixme: what if this format and colorspace is not available?
  798. if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
  799. return availableFormat;
  800. }
  801. }
  802. return availableFormats[0];
  803. }
  804. VkPresentModeKHR Graphics::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) {
  805. // needed ?
  806. for (const auto& availablePresentMode : availablePresentModes) {
  807. if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
  808. return availablePresentMode;
  809. }
  810. }
  811. return VK_PRESENT_MODE_FIFO_KHR;
  812. }
  813. VkExtent2D Graphics::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) {
  814. if (capabilities.currentExtent.width != UINT32_MAX) {
  815. return capabilities.currentExtent;
  816. }
  817. else {
  818. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  819. const void* handle = window->getHandle();
  820. int width, height;
  821. // is this the equivalent of glfwGetFramebufferSize ?
  822. SDL_Vulkan_GetDrawableSize((SDL_Window*)handle, &width, &height);
  823. VkExtent2D actualExtent = {
  824. static_cast<uint32_t>(width),
  825. static_cast<uint32_t>(height)
  826. };
  827. actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
  828. actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
  829. return actualExtent;
  830. }
  831. }
  832. void Graphics::createImageViews() {
  833. swapChainImageViews.resize(swapChainImages.size());
  834. for (size_t i = 0; i < swapChainImages.size(); i++) {
  835. VkImageViewCreateInfo createInfo{};
  836. createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  837. createInfo.image = swapChainImages.at(i);
  838. createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  839. createInfo.format = swapChainImageFormat;
  840. createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  841. createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  842. createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  843. createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  844. createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  845. createInfo.subresourceRange.baseMipLevel = 0;
  846. createInfo.subresourceRange.levelCount = 1;
  847. createInfo.subresourceRange.baseArrayLayer = 0;
  848. createInfo.subresourceRange.layerCount = 1;
  849. if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews.at(i)) != VK_SUCCESS) {
  850. throw love::Exception("failed to create image views");
  851. }
  852. }
  853. }
  854. void Graphics::createDefaultShaders() {
  855. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++) {
  856. auto stype = (Shader::StandardShader)i;
  857. if (!Shader::standardShaders[i]) {
  858. std::vector<std::string> stages;
  859. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_VERTEX));
  860. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_PIXEL));
  861. Shader::standardShaders[i] = newShader(stages, {});
  862. }
  863. }
  864. }
  865. bool Graphics::usesConstantVertexColor(const VertexAttributes& vertexAttributes) {
  866. return !!(vertexAttributes.enableBits & (1u << ATTRIB_COLOR));
  867. }
  868. void Graphics::createVulkanVertexFormat(
  869. VertexAttributes vertexAttributes,
  870. std::vector<VkVertexInputBindingDescription> &bindingDescriptions,
  871. std::vector<VkVertexInputAttributeDescription> &attributeDescriptions) {
  872. std::set<uint32_t> usedBuffers;
  873. auto allBits = vertexAttributes.enableBits;
  874. bool usesColor = false;
  875. uint8_t highestBufferBinding = 0;
  876. for (uint32_t i = 0; i < VertexAttributes::MAX; i++) { // change to loop like in opengl implementation ?
  877. uint32 bit = 1u << i;
  878. if (allBits & bit) {
  879. if (i == ATTRIB_COLOR) {
  880. usesColor = true;
  881. }
  882. auto attrib = vertexAttributes.attribs[i];
  883. auto bufferBinding = attrib.bufferIndex;
  884. if (usedBuffers.find(bufferBinding) == usedBuffers.end()) { // use .contains() when c++20 is enabled
  885. usedBuffers.insert(bufferBinding);
  886. VkVertexInputBindingDescription bindingDescription{};
  887. bindingDescription.binding = bufferBinding;
  888. if (vertexAttributes.instanceBits & (1u << bufferBinding)) {
  889. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_INSTANCE;
  890. }
  891. else {
  892. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  893. }
  894. bindingDescription.stride = vertexAttributes.bufferLayouts[bufferBinding].stride;
  895. bindingDescriptions.push_back(bindingDescription);
  896. highestBufferBinding = std::max(highestBufferBinding, bufferBinding);
  897. }
  898. VkVertexInputAttributeDescription attributeDescription{};
  899. attributeDescription.location = i;
  900. attributeDescription.binding = bufferBinding;
  901. attributeDescription.offset = attrib.offsetFromVertex;
  902. attributeDescription.format = Vulkan::getVulkanVertexFormat(attrib.format);
  903. attributeDescriptions.push_back(attributeDescription);
  904. }
  905. }
  906. // do we need to use a constant VertexColor?
  907. if (!usesColor) {
  908. // FIXME: is there a case where gaps happen between buffer bindings?
  909. // then this doesn't work. We might need to enable null buffers again.
  910. const auto constantColorBufferBinding = highestBufferBinding + 1;
  911. VkVertexInputBindingDescription bindingDescription{};
  912. bindingDescription.binding = constantColorBufferBinding;
  913. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  914. bindingDescription.stride = 0; // no stride, will always read the same color multiple times.
  915. bindingDescriptions.push_back(bindingDescription);
  916. VkVertexInputAttributeDescription attributeDescription{};
  917. attributeDescription.binding = constantColorBufferBinding;
  918. attributeDescription.location = ATTRIB_COLOR;
  919. attributeDescription.offset = 0;
  920. attributeDescription.format = VK_FORMAT_R32G32B32A32_SFLOAT;
  921. attributeDescriptions.push_back(attributeDescription);
  922. }
  923. }
  924. void Graphics::prepareDraw(const VertexAttributes& attributes, const BufferBindings& buffers, graphics::Texture* texture, PrimitiveType primitiveType, CullMode cullmode) {
  925. GraphicsPipelineConfiguration configuration;
  926. configuration.vertexAttributes = attributes;
  927. configuration.shader = (Shader*)Shader::current;
  928. configuration.primitiveType = primitiveType;
  929. configuration.polygonMode = currentPolygonMode;
  930. configuration.blendState = states.back().blend;
  931. configuration.colorChannelMask = states.back().colorMask;
  932. configuration.winding = states.back().winding;
  933. configuration.cullmode = cullmode;
  934. configuration.framebufferFormat = currentFramebufferOutputFormat;
  935. configuration.viewportWidth = currentViewportWidth;
  936. configuration.viewportHeight = currentViewportHeight;
  937. if (states.back().scissor) {
  938. configuration.scissorRect = states.back().scissorRect;
  939. }
  940. else {
  941. configuration.scissorRect = std::nullopt;
  942. }
  943. std::vector<VkBuffer> bufferVector;
  944. std::vector<VkDeviceSize> offsets;
  945. for (uint32_t i = 0; i < VertexAttributes::MAX; i++) {
  946. if (buffers.useBits & (1u << i)) {
  947. bufferVector.push_back((VkBuffer)buffers.info[i].buffer->getHandle());
  948. offsets.push_back((VkDeviceSize)buffers.info[i].offset);
  949. }
  950. }
  951. if (usesConstantVertexColor(attributes)) {
  952. bufferVector.push_back((VkBuffer)batchedDrawBuffers[currentFrame].constantColorBuffer->getHandle());
  953. offsets.push_back((VkDeviceSize)0);
  954. }
  955. auto currentUniformData = getCurrentBuiltinUniformData();
  956. configuration.shader->setUniformData(currentUniformData);
  957. if (texture == nullptr) {
  958. configuration.shader->setMainTex(standardTexture.get());
  959. }
  960. else {
  961. configuration.shader->setMainTex(texture);
  962. }
  963. ensureGraphicsPipelineConfiguration(configuration);
  964. configuration.shader->cmdPushDescriptorSets(commandBuffers.at(imageIndex), static_cast<uint32_t>(currentFrame));
  965. vkCmdBindVertexBuffers(commandBuffers.at(imageIndex), 0, static_cast<uint32_t>(bufferVector.size()), bufferVector.data(), offsets.data());
  966. }
  967. void Graphics::startRenderPass(Texture* texture, uint32_t w, uint32_t h) {
  968. VkRenderingAttachmentInfo colorAttachmentInfo{};
  969. colorAttachmentInfo.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO;
  970. colorAttachmentInfo.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  971. colorAttachmentInfo.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  972. if (texture) {
  973. colorAttachmentInfo.imageView = texture->getImageView();
  974. auto vulkanFormat = Vulkan::getTextureFormat(texture->getPixelFormat());
  975. currentFramebufferOutputFormat = vulkanFormat.internalFormat;
  976. renderTargetTexture = texture;
  977. } else {
  978. colorAttachmentInfo.imageView = swapChainImageViews[imageIndex];
  979. currentFramebufferOutputFormat = swapChainImageFormat;
  980. renderTargetTexture = nullptr;
  981. }
  982. colorAttachmentInfo.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  983. VkRenderingInfo renderingInfo{};
  984. renderingInfo.sType = VK_STRUCTURE_TYPE_RENDERING_INFO;
  985. renderingInfo.renderArea.extent.width = w;
  986. renderingInfo.renderArea.extent.height = h;
  987. renderingInfo.layerCount = 1;
  988. renderingInfo.colorAttachmentCount = 1;
  989. renderingInfo.pColorAttachments = &colorAttachmentInfo;
  990. currentViewportWidth = (float)w;
  991. currentViewportHeight = (float)h;
  992. if (renderTargetTexture) {
  993. Vulkan::cmdTransitionImageLayout(commandBuffers.at(imageIndex), (VkImage)texture->getHandle(), VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  994. }
  995. vkCmdBeginRendering(commandBuffers.at(imageIndex), &renderingInfo);
  996. currentGraphicsPipeline = VK_NULL_HANDLE;
  997. }
  998. void Graphics::endRenderPass() {
  999. vkCmdEndRendering(commandBuffers.at(imageIndex));
  1000. if (renderTargetTexture) {
  1001. Vulkan::cmdTransitionImageLayout(commandBuffers.at(imageIndex), (VkImage)renderTargetTexture->getHandle(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL);
  1002. renderTargetTexture = nullptr;
  1003. }
  1004. }
  1005. VkPipeline Graphics::createGraphicsPipeline(GraphicsPipelineConfiguration configuration) {
  1006. auto &shaderStages = configuration.shader->getShaderStages();
  1007. std::vector<VkVertexInputBindingDescription> bindingDescriptions;
  1008. std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
  1009. createVulkanVertexFormat(configuration.vertexAttributes, bindingDescriptions, attributeDescriptions);
  1010. VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
  1011. vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  1012. vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(bindingDescriptions.size());
  1013. vertexInputInfo.pVertexBindingDescriptions = bindingDescriptions.data();
  1014. vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
  1015. vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data();
  1016. VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
  1017. inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  1018. inputAssembly.topology = Vulkan::getPrimitiveTypeTopology(configuration.primitiveType);
  1019. inputAssembly.primitiveRestartEnable = VK_FALSE;
  1020. VkViewport viewport{};
  1021. viewport.x = 0.0f;
  1022. viewport.y = 0.0f;
  1023. viewport.width = configuration.viewportWidth;
  1024. viewport.height = configuration.viewportHeight;
  1025. viewport.minDepth = 0.0f;
  1026. viewport.maxDepth = 1.0f;
  1027. VkRect2D scissor{};
  1028. if (configuration.scissorRect.has_value()) {
  1029. scissor.offset.x = configuration.scissorRect.value().x;
  1030. scissor.offset.y = configuration.scissorRect.value().y;
  1031. scissor.extent.width = static_cast<uint32_t>(configuration.scissorRect.value().w);
  1032. scissor.extent.height = static_cast<uint32_t>(configuration.scissorRect.value().h);
  1033. }
  1034. else {
  1035. scissor.offset = { 0, 0 };
  1036. scissor.extent = swapChainExtent;
  1037. }
  1038. VkPipelineViewportStateCreateInfo viewportState{};
  1039. viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  1040. viewportState.viewportCount = 1;
  1041. viewportState.pViewports = &viewport;
  1042. viewportState.scissorCount = 1;
  1043. viewportState.pScissors = &scissor;
  1044. VkPipelineRasterizationStateCreateInfo rasterizer{};
  1045. rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  1046. rasterizer.depthClampEnable = VK_FALSE;
  1047. rasterizer.rasterizerDiscardEnable = VK_FALSE;
  1048. rasterizer.polygonMode = configuration.polygonMode;
  1049. rasterizer.lineWidth = 1.0f;
  1050. rasterizer.cullMode = Vulkan::getCullMode(configuration.cullmode);
  1051. rasterizer.frontFace = Vulkan::getFrontFace(configuration.winding);
  1052. rasterizer.depthBiasEnable = VK_FALSE;
  1053. rasterizer.depthBiasConstantFactor = 0.0f;
  1054. rasterizer.depthBiasClamp = 0.0f;
  1055. rasterizer.depthBiasSlopeFactor = 0.0f;
  1056. VkPipelineMultisampleStateCreateInfo multisampling{};
  1057. multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  1058. multisampling.sampleShadingEnable = VK_FALSE;
  1059. multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
  1060. multisampling.minSampleShading = 1.0f; // Optional
  1061. multisampling.pSampleMask = nullptr; // Optional
  1062. multisampling.alphaToCoverageEnable = VK_FALSE; // Optional
  1063. multisampling.alphaToOneEnable = VK_FALSE; // Optional
  1064. VkPipelineColorBlendAttachmentState colorBlendAttachment{};
  1065. colorBlendAttachment.colorWriteMask = Vulkan::getColorMask(configuration.colorChannelMask);
  1066. colorBlendAttachment.blendEnable = Vulkan::getBool(configuration.blendState.enable);
  1067. colorBlendAttachment.srcColorBlendFactor = Vulkan::getBlendFactor(configuration.blendState.srcFactorRGB);
  1068. colorBlendAttachment.dstColorBlendFactor = Vulkan::getBlendFactor(configuration.blendState.dstFactorRGB);
  1069. colorBlendAttachment.colorBlendOp = Vulkan::getBlendOp(configuration.blendState.operationRGB);
  1070. colorBlendAttachment.srcAlphaBlendFactor = Vulkan::getBlendFactor(configuration.blendState.srcFactorA);
  1071. colorBlendAttachment.dstAlphaBlendFactor = Vulkan::getBlendFactor(configuration.blendState.dstFactorA);
  1072. colorBlendAttachment.alphaBlendOp = Vulkan::getBlendOp(configuration.blendState.operationA);
  1073. VkPipelineColorBlendStateCreateInfo colorBlending{};
  1074. colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  1075. colorBlending.logicOpEnable = VK_FALSE;
  1076. colorBlending.logicOp = VK_LOGIC_OP_COPY;
  1077. colorBlending.attachmentCount = 1;
  1078. colorBlending.pAttachments = &colorBlendAttachment;
  1079. colorBlending.blendConstants[0] = 0.0f;
  1080. colorBlending.blendConstants[1] = 0.0f;
  1081. colorBlending.blendConstants[2] = 0.0f;
  1082. colorBlending.blendConstants[3] = 0.0f;
  1083. VkFormat framebufferOutputFormat = configuration.framebufferFormat;
  1084. VkPipelineRenderingCreateInfo pipelineRenderingCreateInfo{};
  1085. pipelineRenderingCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO;
  1086. pipelineRenderingCreateInfo.colorAttachmentCount = 1;
  1087. pipelineRenderingCreateInfo.pColorAttachmentFormats = &framebufferOutputFormat;
  1088. VkGraphicsPipelineCreateInfo pipelineInfo{};
  1089. pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  1090. pipelineInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
  1091. pipelineInfo.pStages = shaderStages.data();
  1092. pipelineInfo.pVertexInputState = &vertexInputInfo;
  1093. pipelineInfo.pInputAssemblyState = &inputAssembly;
  1094. pipelineInfo.pViewportState = &viewportState;
  1095. pipelineInfo.pRasterizationState = &rasterizer;
  1096. pipelineInfo.pMultisampleState = &multisampling;
  1097. pipelineInfo.pDepthStencilState = nullptr;
  1098. pipelineInfo.pColorBlendState = &colorBlending;
  1099. pipelineInfo.pDynamicState = nullptr;
  1100. pipelineInfo.layout = configuration.shader->getGraphicsPipelineLayout();
  1101. pipelineInfo.subpass = 0;
  1102. pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
  1103. pipelineInfo.basePipelineIndex = -1;
  1104. pipelineInfo.pNext = &pipelineRenderingCreateInfo;
  1105. VkPipeline graphicsPipeline;
  1106. if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS) {
  1107. throw love::Exception("failed to create graphics pipeline");
  1108. }
  1109. return graphicsPipeline;
  1110. }
  1111. void Graphics::ensureGraphicsPipelineConfiguration(GraphicsPipelineConfiguration configuration) {
  1112. auto it = graphicsPipelines.find(configuration);
  1113. if (it != graphicsPipelines.end()) {
  1114. if (it->second != currentGraphicsPipeline) {
  1115. vkCmdBindPipeline(commandBuffers.at(imageIndex), VK_PIPELINE_BIND_POINT_GRAPHICS, it->second);
  1116. currentGraphicsPipeline = it->second;
  1117. }
  1118. } else {
  1119. VkPipeline pipeline = createGraphicsPipeline(configuration);
  1120. graphicsPipelines.insert({configuration, pipeline});
  1121. vkCmdBindPipeline(commandBuffers.at(imageIndex), VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
  1122. currentGraphicsPipeline = pipeline;
  1123. }
  1124. }
  1125. void Graphics::createCommandPool() {
  1126. QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
  1127. VkCommandPoolCreateInfo poolInfo{};
  1128. poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  1129. poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
  1130. poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
  1131. if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
  1132. throw love::Exception("failed to create command pool");
  1133. }
  1134. }
  1135. void Graphics::createCommandBuffers() {
  1136. commandBuffers.resize(swapChainImages.size());
  1137. dataTransferCommandBuffers.resize(MAX_FRAMES_IN_FLIGHT);
  1138. VkCommandBufferAllocateInfo allocInfo{};
  1139. allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  1140. allocInfo.commandPool = commandPool;
  1141. allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  1142. allocInfo.commandBufferCount = (uint32_t)commandBuffers.size();
  1143. if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) {
  1144. throw love::Exception("failed to allocate command buffers");
  1145. }
  1146. VkCommandBufferAllocateInfo dataTransferAllocInfo{};
  1147. dataTransferAllocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  1148. dataTransferAllocInfo.commandPool = commandPool;
  1149. dataTransferAllocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  1150. dataTransferAllocInfo.commandBufferCount = (uint32_t)MAX_FRAMES_IN_FLIGHT;
  1151. if (vkAllocateCommandBuffers(device, &dataTransferAllocInfo, dataTransferCommandBuffers.data()) != VK_SUCCESS) {
  1152. throw love::Exception("failed to allocate data transfer command buffers");
  1153. }
  1154. }
  1155. void Graphics::createSyncObjects() {
  1156. imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  1157. renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  1158. inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
  1159. imagesInFlight.resize(swapChainImages.size(), VK_NULL_HANDLE);
  1160. VkSemaphoreCreateInfo semaphoreInfo{};
  1161. semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  1162. VkFenceCreateInfo fenceInfo{};
  1163. fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  1164. fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  1165. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
  1166. if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores.at(i)) != VK_SUCCESS ||
  1167. vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores.at(i)) != VK_SUCCESS ||
  1168. vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences.at(i)) != VK_SUCCESS) {
  1169. throw love::Exception("failed to create synchronization objects for a frame!");
  1170. }
  1171. }
  1172. }
  1173. void Graphics::createDefaultTexture() {
  1174. Texture::Settings settings;
  1175. standardTexture.reset((Texture*)newTexture(settings));
  1176. }
  1177. void Graphics::createQuadIndexBuffer() {
  1178. if (quadIndexBuffer != nullptr)
  1179. return;
  1180. size_t size = sizeof(uint16) * getIndexCount(TRIANGLEINDEX_QUADS, LOVE_UINT16_MAX);
  1181. quadIndexBuffer.reset((StreamBuffer*)newStreamBuffer(BUFFERUSAGE_INDEX, size));
  1182. auto map = quadIndexBuffer->map(size);
  1183. fillIndices(TRIANGLEINDEX_QUADS, 0, LOVE_UINT16_MAX, (uint16*)map.data);
  1184. quadIndexBuffer->unmap(size);
  1185. }
  1186. void Graphics::cleanup() {
  1187. cleanupSwapChain();
  1188. for (auto &cleanUpFns : cleanUpFunctions) {
  1189. for (auto &cleanUpFn : cleanUpFns) {
  1190. cleanUpFn();
  1191. }
  1192. }
  1193. cleanUpFunctions.clear();
  1194. vmaDestroyAllocator(vmaAllocator);
  1195. batchedDrawBuffers.clear();
  1196. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
  1197. vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
  1198. vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
  1199. vkDestroyFence(device, inFlightFences[i], nullptr);
  1200. }
  1201. vkDestroyCommandPool(device, commandPool, nullptr);
  1202. vkDestroyDevice(device, nullptr);
  1203. vkDestroySurfaceKHR(instance, surface, nullptr);
  1204. vkDestroyInstance(instance, nullptr);
  1205. }
  1206. void Graphics::cleanupSwapChain() {
  1207. vkDestroyDescriptorPool(device, descriptorPool, nullptr);
  1208. vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
  1209. vkFreeCommandBuffers(device, commandPool, MAX_FRAMES_IN_FLIGHT, dataTransferCommandBuffers.data());
  1210. for (auto const& p : graphicsPipelines) {
  1211. vkDestroyPipeline(device, p.second, nullptr);
  1212. }
  1213. graphicsPipelines.clear();
  1214. currentGraphicsPipeline = VK_NULL_HANDLE;
  1215. for (size_t i = 0; i < swapChainImageViews.size(); i++) {
  1216. vkDestroyImageView(device, swapChainImageViews[i], nullptr);
  1217. }
  1218. vkDestroySwapchainKHR(device, swapChain, nullptr);
  1219. }
  1220. void Graphics::recreateSwapChain() {
  1221. vkDeviceWaitIdle(device);
  1222. cleanupSwapChain();
  1223. createSwapChain();
  1224. createImageViews();
  1225. createCommandBuffers();
  1226. startRecordingGraphicsCommands();
  1227. }
  1228. love::graphics::Graphics* createInstance() {
  1229. love::graphics::Graphics* instance = nullptr;
  1230. try {
  1231. instance = new Graphics();
  1232. }
  1233. catch (love::Exception& e) {
  1234. printf("Cannot create Vulkan renderer: %s\n", e.what());
  1235. }
  1236. return instance;
  1237. }
  1238. } // vulkan
  1239. } // graphics
  1240. } // love