<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Allen on Medium]]></title>
        <description><![CDATA[Stories by Allen on Medium]]></description>
        <link>https://medium.com/@allenphilip78?source=rss-e89073a5cd7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ruxi2kwKUS6ebX8k4UKAPA@2x.jpeg</url>
            <title>Stories by Allen on Medium</title>
            <link>https://medium.com/@allenphilip78?source=rss-e89073a5cd7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:24:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@allenphilip78/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Modern Vulkan in 2025]]></title>
            <link>https://medium.com/@allenphilip78/using-modern-vulkan-in-2025-0bac45174304?source=rss-e89073a5cd7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bac45174304</guid>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[optimisation]]></category>
            <category><![CDATA[modern-vulkan]]></category>
            <category><![CDATA[vulkan]]></category>
            <dc:creator><![CDATA[Allen]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 17:43:33 GMT</pubDate>
            <atom:updated>2025-02-09T15:57:45.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*7hc2-p7smr7dQZPAg1KDuQ.png" /></figure><p>Vulkan has long been hailed as a complex graphics API that only the most seasoned graphics programmers should use. What if I told you that this no longer is the case? Vulkan has evolved a lot since 2016, and in the process has become much simpler and better. In this blog, I want to mention some features, which helped me through my own journey using Vulkan.</p><h3>A Quick Introduction</h3><p>I am Allen Philip, a second year games programming student at Breda University of Applied Sciences. Over the last weeks I have been working on making an optimized Vulkan Renderer. My aim was not to create the prettiest renderer but rather to explore Vulkan and learn how to exploit it for maximum performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gb4EljlVy9ksIBZj" /></figure><p>With that said, let’s get a few things out of the way first. This blog is not a create a triangle from scratch in Vulkan, at this point its been done to death (<a href="https://medium.com/@allenphilip78/game-engine-stories-first-triangle-in-vulkan-48ccbe8bc769">including me!</a>) and if you want to do that, you are much better off looking at <a href="https://vulkan-tutorial.com/">Vulkan-Tutorial</a> or <a href="https://vkguide.dev/">Vulkan-Guide</a>. Instead I want to focus on modern quality of life features Vulkan brings to the table and general optimization techniques I came across while writing my own renderer.</p><h3>Vulkan-HPP</h3><p>Let’s get the most obvious feature out of the way first. Vulkan-HPP is the official C++ binding for Vulkan, which brings in a lot of benefits. Much better type-safety and lesser boilerplate. No more worrying about weird errors due to wrong s-types or enums, or taking a year to just initialize the damn api. In fact, here’s <a href="https://github.com/dokipen3d/vulkanHppMinimalExample/blob/master/main.cpp">a minimal example </a>that takes only 300 lines of code to put on a triangle (including shader code!) . That’s much lesser than the 1000 or so lines you would have to write with the C api. Here’s some of the best features the C++ API has over the original one.</p><pre>// ------------------------ Enumerating Devices ---------------------------<br><br>// C<br>VkResult result;<br>uint32_t deviceCount = 0;<br><br>result = vkEnumeratePhysicalDevices(context.instance, &amp;deviceCount, NULL);<br>if (result != VK_SUCCESS || deviceCount == 0) {<br>    // Handle error<br>}<br><br>std::vector&lt;VkPhysicalDevice&gt; devices(deviceCount);<br><br>result = vkEnumeratePhysicalDevices(context.instance, &amp;deviceCount, devices);<br>if (result != VK_SUCCESS) {<br>    // Handle error<br>}<br><br>// C++<br>auto [result, devices] = context.instance.enumeratePhysicalDevices();<br>if(result != vk::Success)<br>{<br>  // Handle error<br>}<br><br>// --------------------------- Structure Chains ----------------------------<br><br>// C<br>VkPhysicalDeviceShaderObjectFeaturesEXT shaderObjectFeatures = {<br>    .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_OBJECT_FEATURES_EXT,<br>    .pNext = nullptr,  <br>    .shaderObject = true<br>};<br><br>VkPhysicalDeviceVulkan13Features vulkan13Features = {<br>    .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES,<br>    .pNext = &amp;shaderObjectFeatures <br>};<br><br>VkPhysicalDeviceVulkan12Features vulkan12Features = {<br>    .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES,<br>    .pNext = &amp;vulkan13Features <br>};<br><br>VkPhysicalDeviceVulkan11Features vulkan11Features = {<br>    .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES,<br>    .pNext = &amp;vulkan12Features <br>};<br><br>VkPhysicalDeviceFeatures2 features2 = {<br>    .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,<br>    .pNext = &amp;vulkan11Features <br>};<br><br>VkDeviceCreateInfo deviceCreateInfo = {<br>    .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,<br>    .pNext = &amp;features2,  <br>    .queueCreateInfoCount = queueCreateInfoCount,<br>    .pQueueCreateInfos = queueCreateInfos,<br>    .enabledExtensionCount = extensionNameCount,<br>    .ppEnabledExtensionNames = extensionNames<br>};<br><br><br>// C++<br>auto deviceStructureChain = vk::StructureChain&lt;<br>    vk::DeviceCreateInfo,<br>    vk::PhysicalDeviceFeatures2,<br>    vk::PhysicalDeviceVulkan11Features,<br>    vk::PhysicalDeviceVulkan12Features,<br>    vk::PhysicalDeviceVulkan13Features,<br>    vk::PhysicalDeviceShaderObjectFeaturesEXT&gt;;<br><br>// Accessing different parts<br>auto&amp; deviceFeatures2 = structureChain.get&lt;vk::PhysicalDeviceFeatures2&gt;();<br>auto&amp; features11 = .get&lt;vk::PhysicalDeviceVulkan11Features&gt;();<br>auto&amp; features12 = .get&lt;vk::PhysicalDeviceVulkan11Features&gt;();<br>auto&amp; features13 = .get&lt;vk::PhysicalDeviceVulkan11Features&gt;();<br>auto&amp; shaderObjectFeatures = structureChain<br>                            .get&lt;vk::PhysicalDeviceShaderObjectFeaturesEXT&gt;();<br>shaderObjectFeatures.setShaderObject(true);<br><br>auto&amp; deviceCreateInfo = deviceStructureChain.get&lt;vk::DeviceCreateInfo&gt;();<br>deviceCreateInfo.setPEnabledExtensionNames(extensionNames)<br>                .setQueueCreateInfos(queueCreateInfos);</pre><p>There’s also the advantage of type-safety as mentioned. This will outright trigger compile time errors, which saves a lot of annoyance.</p><pre>// C<br><br>// Incorrect usage of sType with wrong enum value<br>VkPhysicalDeviceFeatures2 features = {<br>    .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,  // Wrong enum value!<br>    .pNext = NULL<br>};<br><br>// Wrong structure being cast or assigned<br>VkPipelineRasterizationStateCreateInfo* rasterState = <br>(VkPipelineRasterizationStateCreateInfo*)&amp;features;<br><br>// Modify incorrect field, leading to undefined behavior<br>rasterState-&gt;rasterizerDiscardEnable = VK_TRUE;<br><br>VkCullModeFlagBits cullMode = VK_POLYGON_MODE_LINE;  // Wrong enum type!<br>rasterState.cullMode = cullMode;<br><br>// C++<br>vk::PhysicalDeviceFeatures2 features = {};<br>// Correct enum is automatically set<br>// features.sType is automatically assigned to vk::StructureType::ePhysicalDeviceFeatures2<br><br>// Compile-time type safety prevents incorrect structure assignments<br>// The following line would be a compilation error in C++<br>// vk::PipelineRasterizationStateCreateInfo* rasterState = reinterpret_cast&lt;vk::PipelineRasterizationStateCreateInfo*&gt;(&amp;features);<br><br>vk::PipelineRasterizationStateCreateInfo rasterState = {};<br>rasterState.setPolygonMode(vk::PolygonMode::eFill)  // Compile-time safety: Correct enum required<br>           .setCullMode(vk::CullModeFlagBits::eFrontAndBack)<br>           .setFrontFace(vk::FrontFace::eClockwise);<br><br>// Attempting an invalid value results in a compilation error<br>// rasterState.setPolygonMode(static_cast&lt;vk::PolygonMode&gt;(999));  // Compilation Error!<br><br>// Type safety prevents wrong enum assignments<br>// vk::CullModeFlagBits cullMode = vk::PolygonMode::eLine;  // Compilation error<br></pre><p>I think that should sell you enough on Vulkan HPP, so let’s move on to the next one.</p><h3>Dynamic Rendering</h3><p>A huge annoyance of Vulkan is having to work with renderpasses, and subpasses and framebuffers. Dynamic rendering solves that problem. No more writing a million lines of code to create a renderpass just to notice that you need another one with another pipeline and framebuffer just because you don’t want to render depth on one image. All of this is handled on the driver side and is as fast if not faster on desktop at least. Render Passes still are the more “optimal” way on devices that used tiled rendering like mobile devices.</p><pre>//-------------------------------- Render Pass-------------------------------<br><br>// Render pass (Color + Depth)<br><br>// Color attachment description<br>vk::AttachmentDescription colorAttachment(...);<br><br>// Depth attachment description<br>vk::AttachmentDescription depthAttachment(...);<br><br>// References to attachments<br>vk::AttachmentReference colorReference(...);<br>vk::AttachmentReference depthReference(...);<br><br>// Subpass description<br>vk::SubpassDescription subpass(...);<br><br>// Create the traditional render pass<br>std::array&lt;vk::AttachmentDescription, 2&gt; attachments = {colorAttachment, depthAttachment};<br>vk::RenderPassCreateInfo renderPassInfo(....);<br>vk::RenderPass renderPass = device.createRenderPass(renderPassInfo);<br><br>// Create a framebuffer<br>std::array&lt;vk::ImageView, 2&gt; attachmentsViews = {colorImageView, depthImageView};<br>vk::FramebufferCreateInfo framebufferInfo(...);<br>vk::Framebuffer framebuffer = device.createFramebuffer(framebufferInfo);<br><br>// Create pipeline baked with the render pass<br>vk::GraphicsPipelineCreateInfo pipelineInfo;<br>pipelineInfo.renderPass = renderPass;<br>vk::Pipeline pipeline = device.createGraphicsPipelines({}, pipelineInfo).value[0];<br><br>// Begin traditional render pass<br>vk::RenderPassBeginInfo renderPassBeginInfo(...);<br>commandBuffer.beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eInline);<br>commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);<br>commandBuffer.draw(3, 1, 0, 0);<br>commandBuffer.endRenderPass();<br><br>// Render pass (Color only)<br><br>// Color attachment description<br>vk::AttachmentDescription colorAttachment(...);<br><br>...<br>//same as before but without the depth image view<br><br>// Create a framebuffer<br>vk::ImageView attachmentsViews = {colorImageView};<br>vk::FramebufferCreateInfo framebufferInfo(...);<br>vk::Framebuffer framebuffer = device.createFramebuffer(framebufferInfo);<br><br>// Begin traditional render pass<br>vk::RenderPassBeginInfo renderPassBeginInfo(...);<br>commandBuffer.beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eInline);<br>commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);<br>commandBuffer.draw(3, 1, 0, 0);<br>commandBuffer.endRenderPass();<br><br><br>//--------------------------Dynamic Rendering--------------------------------<br><br>vk::RenderingAttachmentInfo colorAttachmentInfo(...);<br>vk::RenderingAttachmentInfo depthAttachmentInfo(...);<br>vk::RenderingInfo renderingInfo().setColorAttachments(colorAttachmentInfo)<br>                                 .setPDepthAttachment(&amp;depthAttachmentInfo);<br><br>commandBuffer.beginRendering(renderingInfo);<br>commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);<br>commandBuffer.draw(3, 1, 0, 0);<br>commandBuffer.endRendering();<br><br>// Only use color this time<br>vk::RenderingInfo renderingInfo().setColorAttachments(colorAttachmentInfo);<br><br>commandBuffer.beginRendering(renderingInfo);<br>commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);<br>commandBuffer.draw(3, 1, 0, 0);<br>commandBuffer.endRendering();</pre><p>This simplifies things significantly as you have more “render passes” in your rendering system, so this is basically a must have on desktop. This does have one added complexity of having to manage transitions but this isn’t usually too big of a problem and in my opinion makes Vulkan more consistent as a lot of guesswork is removed when handling subpass dependency chains which had implicit transitions which could very well bug out.</p><pre><br>commandBuffer.beginRendering(renderingInfo);<br>commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);<br><br>// Inserting an image barrier which tells the driver how the image is <br>// going to be used next<br>const auto imageBarrier =<br>      vk::ImageMemoryBarrier2()<br>          .setSrcAccessMask(vk::AccessFlagBits2::eMemoryWrite)<br>          .setSrcStageMask(vk::PipelineStageFlagBits2::eAllCommands)<br>          .setDstAccessMask(<br>           vk::AccessFlagBits2::eMemoryRead | vk::AccessFlagBits2::eMemoryWrite)<br>          .setDstStageMask(vk::PipelineStageFlagBits2::eAllCommands)<br>          .setOldLayout(vk::Layout::eUndefined)<br>          .setNewLayout(vk::Layout::eColorAttachmentOptimal)<br>          .setSubresourceRange(subresourceRange)<br>          .setImage(image);<br>const auto dependency = vk::DependencyInfo().setImageMemoryBarriers(imageBarriers);<br><br>commandBuffer.pipelineBarrier2(dependency);<br>commandBuffer.draw(3, 1, 0, 0);<br>commandBuffer.endRendering();</pre><h3>Bindless Descriptors</h3><p>Traditional Descriptors are by far the most annoying feature Vulkan has. This is one of the major contributors to dev time while porting things from older API’s like DX11 or OpenGL, because they are way too verbose and very complex. You have to have a descriptor pool to create descriptors but each pool has a limited amount, so you need to create a new one every time the last one is full, then the descriptor set allocated from each one requires a set layout which describes how they are going to be used which can differ between pipelines, and then you need to manually update those while rendering to switch to different textures or buffers you need to use.</p><p>Here’s where bindless comes in. This isn’t a Vulkan specific feature per say, but it is quite useful nonetheless. Instead of having this “bindful” descriptors, we instead create a large array of each type of descriptor and index into that to actually use a resource. This clearly reduces boilerplate abstractions over the descriptor system which can get really complex real soon. You don’t have to worry about different set layouts for each pipeline either, as all pipelines use a shared layout. I would recommend taking a look at this <a href="https://henriquegois.dev/posts/bindless-resources-in-vulkan/">article </a>for a more in depth explanation on bindless.</p><pre>// -------------------------------- C++ Code -------------------------------<br><br>// &quot;Bindful&quot;<br>for(int i = 0; i &lt; drawCount; i++)<br>{<br>  std::array&lt;vk::WriteDescriptorSet, 2&gt; descriptorWrites = {};<br>  vk::DescriptorImageInfo imageInfo = {};<br>  vk::DescriptorBufferInfo bufferInfo = {};<br>  ...<br>  device.UpdateDescriptorSet(descriptorWrites);<br>  ...<br>  commandBuffer.BindDescriptorSets(...);<br>  commandBuffer.Draw(...);<br>}<br><br>// &quot;Bindless&quot;<br><br>// On Resource initialisation<br>std::array&lt;vk::WriteDescriptorSet, 2&gt; descriptorWrites = {};<br>vk::DescriptorImageInfo imageInfo = {};<br>vk::DescriptorBufferInfo bufferInfo = {};<br>...<br>device.UpdateDescriptorSet(descriptorWrite);<br><br>for(int i = 0; i &lt; drawCount; i++)<br>{<br>  commandBuffer.BindDescriptorSets(...);<br>  commandBuffer.Draw(...);<br>}<br><br><br>//  ------------------------------Shader Code ------------------------------<br><br>// &quot;Bindful&quot;<br>layout(binding = 0) uniform sampler2D baseColorTexture;<br>layout(binding = 1) uniform sampler2D emissiveColorTexture;<br><br>vec4 baseColor = texture(baseColorTexture, inUV);<br>vec4 emissive = texture(emissiveColorTexture, inUV);<br><br>// &quot;Bindless&quot;<br><br>layout(binding = 0) uniform sampler2D samplers[];<br><br>vec4 baseColor = texture(samplers[material.baseTextureIndex], inUV), vec4(2.2);<br>vec4 emissive = texture(samplers[material.emissiveTextureIndex], inUV);</pre><p>Keep in mind, this only goes for the differences in binding and updating descriptors with the two systems. Accounting for the setup with abstracting pool creation, set creation etc. is insanely long with traditional descriptors (Vulkan-Guide has multiple chapters just on <a href="https://vkguide.dev/docs/new_chapter_4/descriptor_abstractions/">this</a>) and has been skipped here for that reason, while you only need one pool, one set with bindless.</p><p>Adding to this, aliased descriptor types which allow to use the same binding when referencing different internal types in Vulkan. This works because both sampler and sampler cube reference a vk::Sampler, while internal implementation details on the driver allows it to be used as different types like 2D sampler or a cube sampler in the shader.</p><pre>layout(binding = 0) uniform sampler2D samplers[];<br>// Aliased descriptor as these share the same descriptor type<br>layout(binding = 0) uniform samplerCube samplerCubes[];</pre><p>Images benefit the most out of bindless as they can be stored in one array regardless of their properties. Setting up bindless with buffers on the other hand, is not that easy, and requires a bit more setup. Thus my recommendation is to use my next talking point, Buffer Device Address (BDA) for it.</p><h3>Buffer Device Address</h3><p>This is a really convenient feature which allows us to completely skip descriptors for buffers and rather use direct pointers to GPU buffers. Yes you heard that right, no more of this stuff.</p><pre>// Traditional Descriptors<br><br><br>std::array&lt;vk::WriteDescriptorSet, 2&gt; descriptorWrites = {};<br>  vk::DescriptorBufferInfo bufferInfo = {};<br>  vk::DescriptorBufferInfo bufferInfo2 = {};<br>  ...<br>  device.UpdateDescriptorSet(descriptorWrites);</pre><p>You can directly pass the pointer using push constants or other buffers if you prefer.</p><pre>// -------------------------------- C++ Code -------------------------------<br><br>IndirectDrawPushConstant indirectPC = {<br>  // uint64_t address to a gpu buffer<br>  .perDrawBufferAddress = device.getBufferAddress(perDrawBuffer),<br>  .cameraBufferAddress = device.getBufferAddress(cameraBuffer),<br>  .lightBufferAddress = device.getBufferAddress(lightBuffer),<br>  .vertexBufferAddress = device.getBufferAddress(vertexBuffer),<br>  .transformBufferAddress = device.getBufferAddress(transformBuffer),<br>  .materialBufferAddress = device.getBufferAddress(materialBuffer),<br>  ....<br>  ....<br>  ....<br>  ....<br>};<br>commandBuffer.pushConstant&lt;IndirectDrawPushConstant&gt;(pushConstant);<br><br><br>//  ------------------------------Shader Code ------------------------------<br><br>layout(push_constant) uniform Constant<br>{<br>    CameraBuffer cameraBuffer;<br>    VertexBuffer vertexBuffer;<br>    TransformBuffer transformBuffer;<br>    MaterialBuffer materialBuffer;<br>    LightBuffer lightBuffer;<br>    int transformOffset;<br>    int transformIndex;<br>    int materialIndex;<br>    int lightCount;<br>    int irradianceIndex;<br>    int specularIndex;<br>    int lutIndex;<br>} pushConstant;<br><br>void main() <br>{<br>    // Accessing data by using the pointer as an array of data<br>    PerDrawData drawData = pushConstant.perDrawBuffer.perDrawData[inDrawID];<br>    if(drawData.materialIndex == -1) discard;<br>    // This is indexed into another pointer which also acts an array<br>    Material material = pushConstant.materialBuffer.materials[drawData.materialIndex];<br>    <br>    .....<br>    <br>    // and finally we index that value into the sampler array created using bindless<br>    baseColor = pow(texture(samplers[material.baseTextureIndex], inUV), vec4(2.2));<br>    <br>    .....<br>}</pre><h3>Shader Objects</h3><p>This is the one change that makes Vulkan be as high level as OpenGL is. One thing Vulkan brought in its infancy was Pipeline State Objects (PSO). These were supposed to be more performant by packing all required state for a “render pass” into one. The problem arises because how PSO’s were made, even making a tiny change meant making an entirely new PSO from scratch which takes a long time to build. This is one of the major reasons behind the massive shader compilation times and shader stutter in modern games for both DX12 and Vulkan games. Enshrouded uses over 8000 PSO’s, for all its effects and rendering. You can imagine how much of a problem this can be.</p><p>And the worst part is a lot of the state packed into PSO’s are fully dynamic on vendors like NVIDIA which nullifies the impact. Enter Shader Objects, which simplifies this by only packing shader data and allowing all states to be set dynamically like in OpenGL. According to Daniel Story from Nintendo, shader objects are <a href="https://www.khronos.org/blog/you-can-use-vulkan-without-pipelines-today">actually faster </a>than PSO’s in both CPU and GPU due to the lesser amount of data being set per draw call.</p><p>You essentially go from a wall of code in creating pipelines to basically a few lines with shader objects.</p><pre>----------------------// Pipeline State Objects -----------------------------<br>const std::array shaderModules = {<br>    CreateShaderModule(context, vertexCode),<br>    CreateShaderModule(context, fragmentCode),<br>};<br>const std::array shaderStages = {<br>    CreateShaderStage(vk::ShaderStageFlagBits::eVertex, shaderModules[0]),<br>    CreateShaderStage(vk::ShaderStageFlagBits::eFragment, shaderModules[1])};<br><br>constexpr std::array dynamicStates = {<br>    vk::DynamicState::eViewport,<br>    vk::DynamicState::eScissor,<br>};<br>const auto dynamicStatesCreateInfo =<br>    vk::PipelineDynamicStateCreateInfo().setDynamicStates(dynamicStates);<br><br>constexpr auto vertexInputCreateInfo = vk::PipelineVertexInputStateCreateInfo();<br>constexpr auto inputAssemblyCreateInfo =<br>    vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);<br>constexpr auto viewport =<br>    vk::Viewport().setWidth(1280.f).setHeight(720.f).setMinDepth(1.f).setMaxDepth(0.f);<br>constexpr auto scissor = vk::Rect2D().setExtent({1280, 720});<br>const auto viewportCreateInfo =<br>    vk::PipelineViewportStateCreateInfo().setViewports(viewport).setScissors(scissor);<br>constexpr auto rasterizationCreateInfo =<br>    vk::PipelineRasterizationStateCreateInfo().setLineWidth(1.f);<br>constexpr auto msaaStateCreateInfo =<br>    vk::PipelineMultisampleStateCreateInfo().setMinSampleShading(1.f).setRasterizationSamples(<br>        vk::SampleCountFlagBits::e1);<br>constexpr auto depthStencilStateCreateInfo = vk::PipelineDepthStencilStateCreateInfo()<br>                                                 .setDepthTestEnable(true)<br>                                                 .setDepthWriteEnable(true)<br>                                                 .setDepthCompareOp(vk::CompareOp::eGreaterOrEqual);<br>constexpr auto colorBlendAttachmentState =<br>    vk::PipelineColorBlendAttachmentState()<br>        .setBlendEnable(true)<br>        .setColorWriteMask(<br>            vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |<br>            vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)<br>        .setAlphaBlendOp(vk::BlendOp::eAdd)<br>        .setColorBlendOp(vk::BlendOp::eAdd)<br>        .setSrcAlphaBlendFactor(vk::BlendFactor::eSrcAlpha)<br>        .setSrcColorBlendFactor(vk::BlendFactor::eOne)<br>        .setDstAlphaBlendFactor(vk::BlendFactor::eZero)<br>        .setDstColorBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha);<br>const auto colorBlendStateCreateInfo =<br>    vk::PipelineColorBlendStateCreateInfo().setAttachments(colorBlendAttachmentState);<br><br>auto colorFormat = vk::Format::eR16G16B16A16Sfloat;<br>const auto renderCreateInfo = vk::PipelineRenderingCreateInfo()<br>                                  .setColorAttachmentFormats(colorFormat)<br>                                  .setDepthAttachmentFormat(vk::Format::eD32Sfloat);<br><br>const auto createInfo = vk::GraphicsPipelineCreateInfo()<br>                            .setPNext(&amp;renderCreateInfo)<br>                            .setLayout(layout)<br>                            .setStages(shaderStages)<br>                            .setPVertexInputState(&amp;vertexInputCreateInfo)<br>                            .setPInputAssemblyState(&amp;inputAssemblyCreateInfo)<br>                            .setPViewportState(&amp;viewportCreateInfo)<br>                            .setPRasterizationState(&amp;rasterizationCreateInfo)<br>                            .setPMultisampleState(&amp;msaaStateCreateInfo)<br>                            .setPDynamicState(&amp;dynamicStatesCreateInfo)<br>                            .setPDepthStencilState(&amp;depthStencilStateCreateInfo)<br>                            .setPColorBlendState(&amp;colorBlendStateCreateInfo);<br><br>const auto [result, graphicsPipeline] = context.device.createGraphicsPipeline(nullptr, createInfo);<br>VK_ASSERT(<br>    result,<br>    &quot;Failed to create graphics pipeline!&quot;);<br><br>for (const auto&amp; shader : shaderModules)<br>{<br>    context.device.destroy(shader);<br>}<br><br>//---------------------------Shader Objects----------------------------------<br><br>auto shaderCreateInfo = vk::ShaderCreateInfoEXT()<br>                            .setStage(shaderStage)<br>                            .setFlags(shaderFlags)<br>                            .setNextStage(nextStage)<br>                            .setCodeType(vk::ShaderCodeTypeEXT::eSpirv)<br>                            .setPCode(shaderCode.data())<br>                            .setCodeSize(shaderCode.size())<br>                            .setPName(&quot;main&quot;)<br>                            .setSetLayouts(descriptorSetLayout);<br>if (pushConstantRange.size &gt; 0)<br>{<br>  shaderCreateInfo.setPushConstantRanges(pushConstantRange);<br>}<br><br>const auto [result, shaders] = context.device.<br>            createShadersEXT(shaderCreateInfo, nullptr, context.dynamicLoader);     </pre><p>Yea I don’t think I need to say much more about this. This is one of the those things which needed to be in Vulkan from day 1, but just wasn’t for some reason or the other.</p><h3>Conclusion</h3><p>Modern Vulkan has simplified rendering to a degree that it’s much easier to get into. It’s no longer that blackbox that only a wizard can understand how to use. All the features mentioned play their part in doing so and have made Vulkan become a better alternative to DirectX12 in my opinion which it definitely wasn’t before. Thus I believe any Vulkan project going forth, should use these features from day 1 to have the best developer experience.</p><p>Next time around, we will be discussing optimization techniques that i used to increase performance and reduce memory usage, so stay tuned for updates!</p><p>That’s it folks, Until next time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NtkmpZG5ZByKnStm.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bac45174304" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game Engine Stories: First Triangle in Vulkan]]></title>
            <link>https://medium.com/@allenphilip78/game-engine-stories-first-triangle-in-vulkan-48ccbe8bc769?source=rss-e89073a5cd7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/48ccbe8bc769</guid>
            <category><![CDATA[directx-12]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[game-engine]]></category>
            <category><![CDATA[vulkan]]></category>
            <dc:creator><![CDATA[Allen]]></dc:creator>
            <pubDate>Thu, 11 Apr 2024 23:46:42 GMT</pubDate>
            <atom:updated>2024-04-11T23:46:42.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZwuHUkkCDBNJ3wMfBAwbQ.png" /></figure><h3>Game Engine Stories: Starting with Vulkan</h3><h3>Introduction</h3><p>It’s go time! I’m starting my journey to create a custom game engine. In my <a href="https://medium.com/@allenphilip78/game-engine-stories-magma-f1b59402c510">previous post</a>, I chose Vulkan as my preferred Graphics API. But what even is a graphics API?</p><p>In essence, it’s a collection of tools that enable communication with the GPU to render pixels on the screen. Several APIs essentially serve the same purpose but differ in their approaches. OpenGL has long been a standard, alongside DirectX 11. However, these APIs tended to hide too much functionality, simplifying initial setup but often sacrificing performance. Enter modern low-level APIs like Vulkan and DirectX 12, which grant developers more control, allowing for tailor-made applications that can achieve superior performance. This control comes with a steeper learning curve, necessitating a deeper understanding of GPU mechanics. But as I’ve already expressed, embracing Vulkan was a conscious choice. My passion for technology drives me, and Vulkan offers a pathway to a deeper comprehension of the inner workings.</p><h3>Vulkan</h3><p>Now that we know what a graphics API, time to start with the actual project. The first milestone in graphics programming is displaying a triangle on the screen. In OpenGL, this involves creating a window, developing vertex and fragment shaders, and passing the vertex data to these shaders. And just like that, you’ve rendered your first triangle!</p><p>In Vulkan, the process is significantly more involved. Initially, you must initialize a Vulkan Instance to describe the application and the extensions in use. Following that, select the Physical Device for rendering. Subsequently, create a Logical Device from the physical device, detailing the Queue Families required for rendering on screen, data transfer, and non-graphical computations, among others. Next, create a window to display the results, but before that, a Swap Chain is necessary for handling image rendering and presentation. The image from the Swap Chain must be enclosed in an Image View, which is then encapsulated in a framebuffer. A render pass then utilizes these framebuffers to define the image’s usage. Afterward, establish a graphics pipeline with all its stages to outline the rendering process. Create a command buffer to specify the execution of rendering operations, which are stored in a Command Pool to manage various operations. Finally, take the image from the Swap Chain, choose the correct command buffer for the operation, and present it on the screen. Indeed, it’s quite a lot of work.</p><h4>Instance</h4><p>Creating the Vulkan Instance involves specifying the API version, application name, application version and such. Additionally, it’s necessary to define the extensions to be used, as many Vulkan functionalities are not in the core API but are available through extensions. This allows for the use of only the required features, enhancing the application’s efficiency.</p><pre>// Fill in the application info<br>    VkApplicationInfo appInfo{};<br>    appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;<br>    appInfo.pApplicationName = &quot;Magma&quot;;<br>    appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);<br>    appInfo.pEngineName = &quot;No Engine&quot;;<br>    appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);<br>    appInfo.apiVersion = VK_API_VERSION_1_0;<br><br>    // Fill in the instance create info<br>    VkInstanceCreateInfo createInfo{};<br>    createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;<br>    createInfo.pApplicationInfo = &amp;appInfo;<br><br>    // Get the required extensions<br>    auto extensions = GetRequiredExtensions();<br>    createInfo.enabledExtensionCount = static_cast&lt;uint32_t&gt;(extensions.size());<br>    createInfo.ppEnabledExtensionNames = extensions.data();<br><br>    // Create the instance<br>    if (vkCreateInstance(&amp;createInfo, nullptr, &amp;instance) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to create instance!&quot;);<br>    }</pre><h4>Validation Layers</h4><p>This detail wasn’t included in the section where I described the triangle rendering process because it’s not essential. Validation layers serve as a method for error checking. They are not included in the core API, so they must be activated through an extension. The advantage of this setup is that we can enable the validation layers exclusively in debug mode, where performance is less critical, and bypass them in release mode to optimize performance. These layers are highly customizable, allowing us to monitor only the necessary information.</p><pre>void Renderer::SetupDebugMessenger()<br>{<br>    if (!enableValidationLayers) return;<br><br>    VkDebugUtilsMessengerCreateInfoEXT createInfo{};<br>    PopulateDebugMessengerCreateInfo(createInfo);<br><br>    if (CreateDebugUtilsMessengerEXT(instance, &amp;createInfo, nullptr, &amp;debugMessenger) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to set up debug messenger!&quot;);<br>    }<br>}</pre><pre>VkBool32 Renderer::DebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,<br>    VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,<br>    void *pUserData)<br>{<br>    if (messageSeverity &gt;= VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT)<br>    {<br>        cerr &lt;&lt; &quot;Validation layer: &quot; &lt;&lt; pCallbackData-&gt;pMessage &lt;&lt; endl;<br>    }<br><br>    return VK_FALSE;<br>}</pre><h4>Physical Device</h4><p>Now that we have a Vulkan instance, we must choose the appropriate device for our operations. Not all GPUs are created equal. For instance, my system has two GPUs: an AMD Radeon 780M and an NVIDIA RTX 4070. The 780M is an integrated GPU, part of the CPU, and not designed for intensive tasks. It’s typically used for lighter tasks, such as browsing on battery power. The 4070, however, is a dedicated/discrete GPU that uses more power but offers significantly higher performance — up to four times that of the 780M.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0J3ESgCqAVzTs9TTV0b7CQ.png" /><figcaption>Performance differences between the two GPUs</figcaption></figure><p>Clearly, opting for the 4070 over the 780M is preferable for our application to achieve peak performance. Vulkan enables the querying of device information, allowing us to make a informed decision considering factors such as bandwidth, memory availability, whether it’s a dedicated/discrete GPU, and if it supports said features. There is also the possibility of using multiple GPU’s together, but I will not pursue this approach as it is highly impractical.</p><pre>void Renderer::PickPhysicalDevice()<br>{<br>    // Get the number of physical devices<br>    uint deviceCount = 0;<br>    vkEnumeratePhysicalDevices(instance, &amp;deviceCount, nullptr);<br><br>    // If there are no devices with Vulkan support, throw an exception<br>    if (deviceCount == 0)<br>    {<br>        throw runtime_error(&quot;Failed to find GPUs with Vulkan support!&quot;);<br>    }<br><br>    // Get all physical devices<br>    vector&lt;VkPhysicalDevice&gt; devices(deviceCount);<br>    vkEnumeratePhysicalDevices(instance, &amp;deviceCount, devices.data());<br><br>    multimap&lt;int, VkPhysicalDevice&gt; candidates;<br><br>    // Check if any of the found devices are suitable<br>    for (const auto&amp; device : devices)<br>    {<br>        int score = RateDeviceSuitability(device);<br>        candidates.insert({ score, device });<br>    }<br><br>    if (candidates.rbegin()-&gt;first &gt; 0)<br>    {<br>        physicalDevice = candidates.rbegin()-&gt;second;<br>    }<br>    else<br>    {<br>        throw runtime_error(&quot;Failed to find a suitable GPU!&quot;);<br>    }<br>}</pre><h4>Queue Families</h4><p>As noted in the physical devices section, devices vary in capabilities. Not all will support the necessary operations. We require a queue family that can perform the tasks at hand. Specifically, we need a queue family that supports graphics commands. Upon identifying a device that supports these queue families, we select it for rendering.</p><pre>Renderer::QueueFamilyIndices Renderer::FindQueueFamilies(VkPhysicalDevice device)<br>{<br>    QueueFamilyIndices indices;<br><br>    // Get the number of queue families<br>    uint queueFamilyCount = 0;<br>    vkGetPhysicalDeviceQueueFamilyProperties(device, &amp;queueFamilyCount, nullptr);<br><br>    // Get all queue families<br>    vector&lt;VkQueueFamilyProperties&gt; queueFamilies(queueFamilyCount);<br>    vkGetPhysicalDeviceQueueFamilyProperties(device, &amp;queueFamilyCount, queueFamilies.data());<br><br>    // Find a queue family that supports graphics operations<br>    int i = 0;<br>    for (const auto&amp; queueFamily : queueFamilies)<br>    {<br>        if (queueFamily.queueFlags &amp; VK_QUEUE_GRAPHICS_BIT)<br>        {<br>            indices.graphicsFamily = i;<br>        }<br>        VkBool32 presentSupport = false;<br>        vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &amp;presentSupport);<br>        if (presentSupport)<br>        {<br>            indices.presentFamily = i;<br>        }<br>        i++;<br>    }<br><br>    return indices;<br>}</pre><h4>Logical Device</h4><p>Having selected a physical device, we must now create a logical device to act as an interface. This will define the features we want to use and the queues that need to be created, based on the available queue families we have identified.</p><pre>void Renderer::CreateLogicalDevice()<br>{<br>    QueueFamilyIndices indices = FindQueueFamilies(physicalDevice);<br><br>    VkDeviceQueueCreateInfo queueCreateInfo{};<br>    queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;<br>    queueCreateInfo.queueFamilyIndex = indices.graphicsFamily.value();<br>    queueCreateInfo.queueCount = 1;<br><br>    float queuePriority = 1.0f;<br>    queueCreateInfo.pQueuePriorities = &amp;queuePriority;<br><br>    VkPhysicalDeviceFeatures deviceFeatures{};<br><br>    VkDeviceCreateInfo createInfo{};<br>    createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;<br>    createInfo.pQueueCreateInfos = &amp;queueCreateInfo;<br>    createInfo.queueCreateInfoCount = 1;<br>    createInfo.pEnabledFeatures = &amp;deviceFeatures;<br>    createInfo.enabledExtensionCount = 0;<br><br>    if (enableValidationLayers)<br>    {<br>        createInfo.enabledLayerCount = static_cast&lt;uint&gt;(validationLayers.size());<br>        createInfo.ppEnabledLayerNames = validationLayers.data();<br>    }<br>    else<br>    {<br>        createInfo.enabledLayerCount = 0;<br>    }<br><br>    if (vkCreateDevice(physicalDevice,&amp;createInfo, nullptr, &amp;device) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to create logical device!&quot;);<br>    }<br><br>    vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &amp;graphicsQueue);<br>}</pre><h4>Window Surface</h4><p>The window surface allows us to present rendered images to a arbitrary window. We create a window with GLFW, so as to not mess with platform specific code. We then use the window handles from GLFW, to present the images. The window surface in Vulkan is actually an extension, not a part of the core Vulkan API, because there are devices designed for offscreen rendering, commonly referred to as headless rendering. This includes scenarios like server-side rendering where rendering tasks are offloaded from client devices to enhance performance.</p><pre>void Renderer::InitWindow()<br>{<br>    glfwInit();<br>    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);<br>    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);<br>    window = glfwCreateWindow(WIDTH, HEIGHT, &quot;Vulkan&quot;, nullptr, nullptr);<br>}<br><br>void Renderer::CreateSurface()<br>{<br>    if (glfwCreateWindowSurface(instance, window, nullptr, &amp;surface) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to create window surface!&quot;);<br>    }<br>}</pre><h4>Present Queue</h4><p>We have already checked for a graphics queue to manage rendering operations. However, to display them on the screen, we need a separate queue that supports presentation. Therefore, we must query the available queue families to identify one with the necessary support.</p><pre>vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &amp;presentSupport);<br>if (presentSupport)<br>{<br>  indices.presentFamily = i;<br>}<br>i++;</pre><h4>Swap Chain</h4><p>The swap chain functions as a queue of images ready to be displayed on the screen. Images are acquired from the swap chain for drawing purposes and then returned to the queue for presentation. Its primary role is to synchronize the CPU and GPU, ensuring that the GPU does not render to an image currently on display, and the CPU does not alter or destroy an image that the GPU is rendering.</p><pre>void Renderer::CreateSwapChain()<br>{<br>    SwapChainSupportDetails swapChainSupport = QuerySwapChainSupport(physicalDevice);<br>    VkSurfaceFormatKHR surfaceFormat = ChooseSwapSurfaceFormat(swapChainSupport.formats);<br>    VkPresentModeKHR presentMode = ChooseSwapPresentMode(swapChainSupport.presentModes);<br>    VkExtent2D extent = ChooseSwapExtent(swapChainSupport.capabilities);<br><br>    uint imageCount = swapChainSupport.capabilities.minImageCount + 1;<br><br>    // Check if the image count is within the allowed range<br>    if (swapChainSupport.capabilities.maxImageCount &gt; 0 &amp;&amp; imageCount &gt; swapChainSupport.capabilities.maxImageCount)<br>    {<br>        imageCount = swapChainSupport.capabilities.maxImageCount;<br>    }<br><br>    VkSwapchainCreateInfoKHR createInfo{};<br>    createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;<br>    createInfo.surface = surface;<br>    createInfo.minImageCount = imageCount;<br>    createInfo.imageFormat = surfaceFormat.format;<br>    createInfo.imageColorSpace = surfaceFormat.colorSpace;<br>    createInfo.imageExtent = extent;<br>    createInfo.imageArrayLayers = 1;<br>    // We will render directly to the image, so we will use VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT<br>    // If we want to post-process the image, we would use VK_IMAGE_USAGE_TRANSFER_DST_BIT<br>    createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;<br><br>    QueueFamilyIndices indices = FindQueueFamilies(physicalDevice);<br>    uint queueFamilyIndices[] = {indices.graphicsFamily.value(), indices.presentFamily.value()};<br><br>    if (indices.graphicsFamily != indices.presentFamily)<br>    {<br>        createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;<br>        createInfo.queueFamilyIndexCount = 2;<br>        createInfo.pQueueFamilyIndices = queueFamilyIndices;<br>    }<br>    else<br>    {<br>        createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;<br>    }<br>    // We will ignore the transformation of the image as we are not rotating or flipping it<br>    createInfo.preTransform = swapChainSupport.capabilities.currentTransform;<br>    // We will ignore the alpha channel as we are not blending with other windows<br>    createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;<br><br>    createInfo.presentMode = presentMode;<br>    createInfo.clipped = VK_TRUE;<br><br>    if (vkCreateSwapchainKHR(logicalDevice, &amp;createInfo, nullptr, &amp;swapChain) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to create swap chain!&quot;);<br>    }<br><br>    // Get the swap chain image count<br>    vkGetSwapchainImagesKHR(logicalDevice, swapChain, &amp;imageCount, nullptr);<br>    // Resize the vector to hold all images<br>    swapChainImages.resize(imageCount);<br>    // Get the swap chain images<br>    vkGetSwapchainImagesKHR(logicalDevice, swapChain, &amp;imageCount, swapChainImages.data());<br><br>    swapChainImageFormat = surfaceFormat.format;<br>    swapChainExtent = extent;<br>}</pre><h4>Image View</h4><p>An image view, as the name implies, provides a view of an image. It is utilized to specify how image data can be accessed without altering the original image.</p><pre>void Renderer::CreateImageViews()<br>{<br>    swapChainImageViews.resize(swapChainImages.size());<br><br>    for (auto i = 0; i &lt; swapChainImages.size(); i++)<br>    {<br>        VkImageViewCreateInfo createInfo{};<br>        createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;<br>        createInfo.image = swapChainImages[i];<br>        createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;<br>        createInfo.format = swapChainImageFormat;<br><br>        // Default mapping<br>        createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;<br>        createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;<br>        createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;<br>        createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;<br><br>        createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;<br>        // No mip-mapping yet<br>        createInfo.subresourceRange.baseMipLevel = 0;<br>        createInfo.subresourceRange.levelCount = 1;<br>        createInfo.subresourceRange.baseArrayLayer = 0;<br>        createInfo.subresourceRange.layerCount = 1;<br><br>        if (vkCreateImageView(logicalDevice, &amp;createInfo, nullptr, &amp;swapChainImageViews[i]) != VK_SUCCESS)<br>        {<br>            throw runtime_error(&quot;Failed to create image views!&quot;);<br>        }<br>    }<br>}</pre><h4>Render Passes</h4><p>Render passes facilitate efficient management of rendering operations. They represent a set of attachments, such as color, depth, and stencil buffers, which are utilized during rendering, along with the operations executed on these attachments.</p><p>Render passes may include several sub-passes, which enable the definition of dependencies between stages in the graphics pipeline and the optimization of memory access patterns by packing them into a single render pass. An example would be a sequence of post-processing effects applied consecutively. Currently, we will utilize only one sub-pass, as it suffices for rendering the triangle.</p><pre>void Renderer::CreateRenderPass()<br>{<br>    VkAttachmentDescription colorAttachment{};<br>    colorAttachment.format = swapChainImageFormat;<br>    colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;<br><br>    // What to do with the data in the attachment before rendering<br>    colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;<br>    colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;<br><br>    // What to do with the stencil data in the attachment before rendering<br>    // Not using stencil data, so we don&#39;t care about the load and store operations<br>    colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;<br>    colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;<br><br>    // Layout of the image before and after the render pass<br>    colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;<br>    colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;<br><br>    // Subpasses are subsequent rendering operations that depend on the contents of the previous subpass<br>    // We only have one subpass for now<br>    VkAttachmentReference colorAttachmentRef{};<br>    colorAttachmentRef.attachment = 0;<br>    colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;<br><br>    VkSubpassDescription subpass{};<br>    subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;<br>    subpass.colorAttachmentCount = 1;<br>    subpass.pColorAttachments = &amp;colorAttachmentRef;<br><br>    VkSubpassDependency dependency{};<br>    // dstSubpass must be higher than srcSubpass to prevent cycles in the dependency graph<br>    // The source stage mask specifies the pipeline stages that the operations occur in<br>    dependency.srcSubpass = VK_SUBPASS_EXTERNAL;<br>    // The destination stage mask specifies the pipeline stages that the operations will wait on<br>    dependency.dstSubpass = 0;<br><br>    // The source access mask specifies the operations that must be finished on the previous subpass before the next one can start<br>    dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;<br>    dependency.srcAccessMask = 0;<br><br>    // The destination access mask specifies the operations that must wait on the current subpass<br>    dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;<br>    dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;<br><br>    // Create the render pass<br>    VkRenderPassCreateInfo renderPassInfo{};<br>    renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;<br>    renderPassInfo.attachmentCount = 1;<br>    renderPassInfo.pAttachments = &amp;colorAttachment;<br>    renderPassInfo.subpassCount = 1;<br>    renderPassInfo.pSubpasses = &amp;subpass;<br>    renderPassInfo.dependencyCount = 1;<br>    renderPassInfo.pDependencies = &amp;dependency;<br><br>    if (vkCreateRenderPass(logicalDevice, &amp;renderPassInfo, nullptr, &amp;renderPass) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to create render pass!&quot;);<br>    }<br>}</pre><h4>Framebuffers</h4><p>A framebuffer object is a collection of attachments that act as render targets during a render pass. Currently, only the color attachment will be utilized, as it is the only requirement for rendering the triangle.</p><pre>void Renderer::CreateFrameBuffers()<br>{<br>    frameBuffers.resize(swapChainImageViews.size());<br><br>    for (size_t i = 0; i &lt; swapChainImageViews.size(); i++)<br>    {<br>        VkFramebufferCreateInfo framebufferInfo{};<br>        framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;<br>        framebufferInfo.renderPass = renderPass;<br>        framebufferInfo.attachmentCount = 1;<br>        framebufferInfo.pAttachments = &amp;swapChainImageViews[i];<br>        framebufferInfo.width = swapChainExtent.width;<br>        framebufferInfo.height = swapChainExtent.height;<br>        framebufferInfo.layers = 1;<br><br>        if (vkCreateFramebuffer(logicalDevice, &amp;framebufferInfo, nullptr, &amp;frameBuffers[i]) != VK_SUCCESS)<br>        {<br>            throw runtime_error(&quot;Failed to create framebuffer!&quot;);<br>        }<br>    }<br>}</pre><h4>Graphics Pipeline</h4><p>The graphics pipeline is a series of steps that process data such as vertices and textures to generate the final rendered image on the screen. Vulkan’s graphics pipeline consists of multiple distinct stages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*u-VTdLPHhp6v0v0HPYi2Dg.png" /><figcaption>Vulkan Graphics Pipeline</figcaption></figure><p>The green stages in the pipeline represent fixed-function stages, indicating that the tasks are predefined in Vulkan, allowing us to only adjust specific parameters.</p><p>The orange stages are programmable, providing the flexibility to use them as desired.</p><p>The input assembler collects the vertex data specified by us, and assembling them into primitives like points, lines or triangles.</p><p>The vertex shader, like in OpenGL, enables us to apply transformations to vertices, converting them from model space to screen space. Subsequently, this data is transmitted through the pipeline.</p><p>The tessellation shader is used to subdivide geometry, enhancing the mesh quality. This is particularly useful for objects like brick walls, rocks, foliage, and more.</p><p>The geometry shader operates on the acquired primitives and can either create new primitives or discard the unnecessary existing ones. It is frequently utilized for tasks such as particle systems, wireframe rendering, or shadow volume creation.</p><p>The rasterization stage transforms primitives into fragments, which are the pixel elements sent to the framebuffers. Fragments that fall outside the screen boundaries are discarded. The attributes acquired from the vertex shader are interpolated across the fragments, as depicted in the picture above. Additionally, if depth testing is activated, fragments obscured by other primitive fragments are discarded.</p><p>The fragment shader operates on every fragment that isn’t discarded, determining the framebuffers to which the fragments are written, along with their appropriate color and depth values. It utilizes interpolated data from the vertex shader for this process, which may also include elements such as texture coordinates and normals for lighting.</p><p>The final stage, color blending, involves operations that combine various fragments mapping to the same pixel in the framebuffer. These fragments may overwrite one another, accumulate, or blend together based on transparency.</p><p>For our initial triangle, we can bypass the geometry and tessellation shaders since they are optional and not necessary for rendering a triangle on the screen.</p><h4>Shaders</h4><p>Shaders in OpenGL or DirectX are typically written in a human-readable formats such as GLSL or HLSL. While these are straightforward to write, they can cause compilation issues across different GPU vendors due to varied implementations. Vulkan, however, mandates the creation of shaders in a bytecode format known as SPIR-V, which aids in circumventing these issues.</p><p>Upon seeing this, my initial reaction was, “Oh no, do I need to write in machine code or something?” Thankfully, that’s not the case. Khronos, the group responsible for Vulkan and OpenGL, has developed compilers that translate GLSL into SPIR-V. This allows us to craft shaders in the same manner as we did with OpenGL.</p><p>Typically, vertex data is passed to the vertex shader using vertex buffers. However, to expedite the process and visualize the triangle sooner, I’ll directly define the triangle’s vertices in the vertex shader itself.</p><p>And instead of settling for a mundane red triangle, I’m aiming to create something much more exciting, akin to the image shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*v-W9QFhyp1sHMf1E.png" /></figure><p>For this, we will assign unique colors to each of the three vertices and pass the output to the fragment shader.</p><pre>#version 450<br><br>layout(location = 0) out vec3 fragColor;<br><br>vec2 positions[3] = vec2[]<br>(<br>    vec2(0.0, -0.5),<br>    vec2(0.5, 0.5),<br>    vec2(-0.5, 0.5)<br>);<br><br>vec3 colors[3] = vec3[]<br>(<br>    vec3(1.0, 0.0, 0.0),<br>    vec3(0.0, 1.0, 0.0),<br>    vec3(0.0, 0.0, 1.0)<br>);<br><br>void main()<br>{<br>    gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0);<br>    fragColor = colors[gl_VertexIndex];<br>}</pre><p>The fragment shader receives color input from the vertex shader, interpolates the colors across the three vertices, and outputs them to produce a smooth gradient.</p><p>The shaders will be compiled into SPIR-V using glslc, which is included in the Vulkan SDK.</p><p>Now that we’ve formatted the shaders to Vulkan’s specifications, we’ll integrate them into the graphics pipeline. This involves loading the binary shader code as a vector of characters and constructing a shader module from it.</p><pre>vector&lt;char&gt; Renderer::ReadFile(const string &amp;filename)<br>{<br>    // Open the file in binary mode<br>    ifstream file(filename, ios::ate | ios::binary);<br><br>    if (!file.is_open())<br>    {<br>        throw runtime_error(&quot;Failed to open file!&quot;);<br>    }<br><br>    // Get the file size<br>    size_t fileSize = static_cast&lt;size_t&gt;(file.tellg());<br>    vector&lt;char&gt; buffer(fileSize);<br><br>    // Go to the beginning of the file<br>    file.seekg(0);<br>    file.read(buffer.data(), static_cast&lt;streamsize&gt;(fileSize));<br><br>    file.close();<br>    return buffer;<br>}<br><br>VkShaderModule Renderer::CreateShaderModule(const vector&lt;char&gt; &amp;code)<br>{<br>    VkShaderModuleCreateInfo createInfo{};<br>    createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;<br>    createInfo.codeSize = code.size();<br>    createInfo.pCode = reinterpret_cast&lt;const uint32_t*&gt;(code.data());<br><br>    VkShaderModule shaderModule;<br>    if (vkCreateShaderModule(logicalDevice, &amp;createInfo, nullptr, &amp;shaderModule) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to create shader module!&quot;);<br>    }<br><br>    return shaderModule;<br>}</pre><p>With this setup in place, we can proceed to construct the graphics pipeline by setting up the fixed-function and programmable shader stages. This process involves defining shader modules (already completed), designating pipeline layouts, arranging vertex input and assembly, setting viewport and scissor parameters, determining rasterization options, multisampling, color blending, and depth/stencil testing. Once completed, the graphics pipeline coordinates the rendering process within the specified viewport.</p><pre>void Renderer::CreateGraphicsPipeline()<br>{<br>    VkPipelineShaderStageCreateInfo vertShaderStageInfo{};<br>    VkPipelineShaderStageCreateInfo fragShaderStageInfo{};<br>    VkShaderModule vertShaderModule{};<br>    VkShaderModule fragShaderModule{};<br>    CreateShaders(vertShaderStageInfo, fragShaderStageInfo, vertShaderModule, fragShaderModule);<br>    VkPipelineShaderStageCreateInfo shaderStages[] {vertShaderStageInfo, fragShaderStageInfo};<br><br>    // The vertex input stage is where we specify the format of the vertex data that will be passed to the vertex shader<br>    VkPipelineVertexInputStateCreateInfo vertexInputInfo{};<br>    vertexInputInfo = CreateVertexInputInfo();<br><br>    // The input assembly stage is where we specify the type of geometry we will be drawing<br>    VkPipelineInputAssemblyStateCreateInfo inputAssembly{};<br>    inputAssembly = CreateInputAssembly();<br><br>    // The viewport and scissor rectangle define the region of the framebuffer that the output will be rendered to<br>    VkPipelineViewportStateCreateInfo viewportState{};<br>    viewportState = CreateViewportState();<br><br>    // The rasterizer takes the geometry that is shaped by the vertices from the vertex shader and<br>    // turns it into fragments to be colored by the fragment shader<br>    VkPipelineRasterizationStateCreateInfo rasterizer{};<br>    rasterizer = CreateRasterizer();<br><br>    // The multisampling state is used for antialiasing<br>    VkPipelineMultisampleStateCreateInfo multisampling{};<br>    multisampling = CreateMultisampling();<br><br>    // The color blending stage combines the color from the fragment shader with the color already in the framebuffer<br>    VkPipelineColorBlendAttachmentState colorBlendAttachment{};<br>    colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |<br>                                          VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;<br>    colorBlendAttachment.blendEnable = VK_FALSE;<br><br>    VkPipelineColorBlendStateCreateInfo colorBlending{};<br>    colorBlending = CreateColorBlend(&amp;colorBlendAttachment);<br><br>    // Dynamic states allow us to change the viewport and line width without recreating the pipeline<br>    VkPipelineDynamicStateCreateInfo dynamicState{};<br>    vector&lt;VkDynamicState&gt; dynamicStates = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };<br>    dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;<br>    dynamicState.dynamicStateCount = static_cast&lt;uint32_t&gt;(dynamicStates.size());<br>    dynamicState.pDynamicStates = dynamicStates.data();<br><br>    VkPipelineLayoutCreateInfo pipelineLayoutInfo{};<br>    pipelineLayoutInfo = CreatePipelineLayout();<br><br>    if (vkCreatePipelineLayout(logicalDevice, &amp;pipelineLayoutInfo, nullptr, &amp;pipelineLayout) != VK_SUCCESS)<br>    {<br>        throw std::runtime_error(&quot;failed to create pipeline layout!&quot;);<br>    }<br><br>    // Create the graphics pipeline<br>    VkGraphicsPipelineCreateInfo pipelineInfo{};<br>    pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;<br>    pipelineInfo.stageCount = 2;<br>    pipelineInfo.pStages = shaderStages;<br>    pipelineInfo.pVertexInputState = &amp;vertexInputInfo;<br>    pipelineInfo.pInputAssemblyState = &amp;inputAssembly;<br>    pipelineInfo.pViewportState = &amp;viewportState;<br>    pipelineInfo.pRasterizationState = &amp;rasterizer;<br>    pipelineInfo.pMultisampleState = &amp;multisampling;<br>    pipelineInfo.pColorBlendState = &amp;colorBlending;<br>    pipelineInfo.pDynamicState = &amp;dynamicState;<br>    pipelineInfo.layout = pipelineLayout;<br>    pipelineInfo.renderPass = renderPass;<br>    pipelineInfo.subpass = 0;<br>    // If we want to create a new pipeline based on an existing one, we can specify the base pipeline<br>    //pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;<br><br>    if (vkCreateGraphicsPipelines(logicalDevice, VK_NULL_HANDLE, 1, &amp;pipelineInfo, nullptr, &amp;graphicsPipeline) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;failed to create graphics pipeline!&quot;);<br>    }<br><br>    vkDestroyShaderModule(logicalDevice, vertShaderModule, nullptr);<br>    vkDestroyShaderModule(logicalDevice, fragShaderModule, nullptr);<br>}</pre><h4>Command Buffers</h4><p>I know it’s been a journey, and we’re just getting to the good part. Hold tight, because we’re nearly there! The next step involves creating a command buffer that outlines the desired operation and its execution method. Command buffers are held within structures known as command pools, which manage the memory allocation for these buffers. A command buffer can be allocated from the command pool for the specific operation that is being executed.</p><pre>void Renderer::CreateCommandPool()<br>{<br>    QueueFamilyIndices queueFamilyIndices = FindQueueFamilies(physicalDevice);<br><br>    VkCommandPoolCreateInfo poolInfo{};<br>    poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;<br>    // VK_COMMAND_POOL_CREATE_TRANSIENT_BIT: Hint that command buffers are rerecorded with new commands very often<br>    // VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT: Allow command buffers to be rerecorded individually, without this flag they all have to be reset together<br>    poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;<br>    poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();<br><br>    if (vkCreateCommandPool(logicalDevice, &amp;poolInfo, nullptr, &amp;commandPool) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to create command pool!&quot;);<br>    }<br>}<br><br>void Renderer::CreateCommandBuffers()<br>{<br>    commandBuffers.resize(maxFlightFrames);<br>    VkCommandBufferAllocateInfo allocInfo{};<br>    allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;<br>    allocInfo.commandPool = commandPool;<br>    // VK_COMMAND_BUFFER_LEVEL_PRIMARY: Can be submitted to a queue for execution, but cannot be called from other command buffers<br>    // VK_COMMAND_BUFFER_LEVEL_SECONDARY: Cannot be submitted directly, but can be called from primary command buffers<br>    allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;<br>    allocInfo.commandBufferCount = static_cast&lt;uint32_t&gt;(commandBuffers.size());<br><br>    if (vkAllocateCommandBuffers(logicalDevice, &amp;allocInfo, commandBuffers.data()) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to allocate command buffers!&quot;);<br>    }<br>}</pre><p>To utilize the command buffer, we initiate it first. Drawing a triangle on the screen requires starting a render pass, followed by binding the graphics pipeline to the command buffer, and then executing the draw command for the triangle. After completing these steps, we end both the render pass and the command buffer. While the code for drawing a triangle is complete, it still needs to be transferred to the screen.</p><pre>void Renderer::RecordCommandBuffer(VkCommandBuffer commandBuffer, uint imageIndex)<br>{<br>    VkCommandBufferBeginInfo beginInfo{};<br>    beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;<br>    // VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT: The command buffer will be rerecorded right after executing it once<br>    // VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT: This is a secondary command buffer that will be entirely within a single render pass<br>    // VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT: The command buffer can be resubmitted while it is also already pending execution<br>    beginInfo.flags = 0;<br>    // Useful for secondary command buffers to inherit data from their primary command buffer<br>    beginInfo.pInheritanceInfo = nullptr;<br><br>    if (vkBeginCommandBuffer(commandBuffer, &amp;beginInfo) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to begin recording command buffer!&quot;);<br>    }<br><br>    VkRenderPassBeginInfo renderPassInfo{};<br>    renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;<br>    renderPassInfo.renderPass = renderPass;<br>    renderPassInfo.framebuffer = frameBuffers[imageIndex];<br><br>    // The render area specifies the pixels that will be affected by the render pass<br>    renderPassInfo.renderArea.offset = {0, 0};<br>    renderPassInfo.renderArea.extent = swapChainExtent;<br><br>    // The clear color to use for the attachment (Black in this case)<br>    VkClearValue clearColor = {clearColorValue[0], clearColorValue[1], clearColorValue[2], clearColorValue[3]};<br>    renderPassInfo.clearValueCount = 1;<br>    renderPassInfo.pClearValues = &amp;clearColor;<br><br>    // VK_SUBPASS_CONTENTS_INLINE: The render pass commands will be embedded in the primary command buffer itself and no secondary command buffers will be executed<br>    // VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS: The render pass commands will be executed from secondary command buffers<br>    vkCmdBeginRenderPass(commandBuffer, &amp;renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);<br><br>    vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline);<br><br>    // Since the vertex buffer is dynamic, we need to bind it before drawing<br>    VkViewport viewport{};<br>    viewport.x = 0.0f;<br>    viewport.y = 0.0f;<br>    viewport.width = static_cast&lt;float&gt;(swapChainExtent.width);<br>    viewport.height = static_cast&lt;float&gt;(swapChainExtent.height);<br>    viewport.minDepth = 0.0f;<br>    viewport.maxDepth = 1.0f;<br>    vkCmdSetViewport(commandBuffer, 0, 1, &amp;viewport);<br><br>    // Since the scissor rectangle is dynamic, we need to set it before drawing<br>    VkRect2D scissor{};<br>    scissor.offset = {0, 0};<br>    scissor.extent = swapChainExtent;<br>    vkCmdSetScissor(commandBuffer, 0, 1, &amp;scissor);<br><br>    vkCmdDraw(commandBuffer, 3, 1, 0, 0);<br><br>    vkCmdEndRenderPass(commandBuffer);<br><br>    if (vkEndCommandBuffer(commandBuffer) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to record command buffer!&quot;);<br>    }<br>}</pre><h4>Drawing a Frame</h4><p>To render an image on the screen using Vulkan, it’s necessary to wait until the previous frame is complete, obtain an image from the swap chain, record the command buffer, submit it, and then present the swap chain image. This process repeats for every frame.</p><p>For these tasks, it’s crucial to ensure that the GPU is equipped with all necessary resources before rendering begins, and that the CPU waits until rendering is complete to avoid displaying an incomplete image. Synchronization between these operations is managed using semaphores and fences.</p><p>Semaphores are utilized to synchronize the GPU, ensuring it waits until resources become available. Conversely, Fences are employed to synchronize the CPU, making it wait until the GPU has completed its tasks.</p><p>In this scenario, a fence is utilized to ensure the CPU waits until the previous frame is complete before resetting. Subsequently, an image is acquired from the swap chain for rendering. The command buffer is recorded with the specified image, which is then ready for submission to the GPU. The GPU requires signaling in two instances: firstly, when an image becomes available from the swap chain, and secondly, once rendering is complete and the image is ready for presentation on the screen. This process involves the creation of two semaphores that are signaled at the appropriate times and then passed into the queue on submission.</p><p>The last step in frame rendering is to take the image processed by the GPU and display it on the screen. After the semaphore signals that rendering is complete, the image is then presented on the screen by being submitted to the presentation queue.</p><pre>void Renderer::DrawFrame()<br>{<br>    vkWaitForFences(logicalDevice, 1, &amp;inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);<br><br>    uint imageIndex;<br>    VkResult result = vkAcquireNextImageKHR(logicalDevice, swapChain, UINT64_MAX,imageAvailableSemaphores[currentFrame],<br>                          VK_NULL_HANDLE, &amp;imageIndex);<br><br>    if (result == VK_ERROR_OUT_OF_DATE_KHR)<br>    {<br>        RecreateSwapChain();<br>        return;<br>    }<br>    else if (result != VK_SUCCESS &amp;&amp; result != VK_SUBOPTIMAL_KHR)<br>    {<br>        throw runtime_error(&quot;Failed to acquire swap chain image!&quot;);<br>    }<br>    vkResetFences(logicalDevice, 1, &amp;inFlightFences[currentFrame]);<br><br>    vkResetCommandBuffer(commandBuffers[currentFrame], 0);<br>    RecordCommandBuffer(commandBuffers[currentFrame], imageIndex);<br><br>    VkSubmitInfo submitInfo{};<br>    submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;<br>    submitInfo.commandBufferCount = 1;<br>    submitInfo.pCommandBuffers = &amp;commandBuffers[currentFrame];<br><br>    // Wait for the imageAvailableSemaphore to be signaled<br>    VkSemaphore waitSemaphores[] = {imageAvailableSemaphores[currentFrame]};<br>    // Wait for the color attachment output stage to be available<br>    // VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT: Stage of the pipeline where the command is initially processed<br>    // VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT: Stage of the pipeline where the color attachment is written<br>    VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};<br>    submitInfo.waitSemaphoreCount = 1;<br>    submitInfo.pWaitSemaphores = waitSemaphores;<br>    submitInfo.pWaitDstStageMask = waitStages;<br><br>    // Signal the renderFinishedSemaphore when the command buffer has finished execution<br>    VkSemaphore signalSemaphores[] = {renderFinishedSemaphores[currentFrame]};<br>    submitInfo.signalSemaphoreCount = 1;<br>    submitInfo.pSignalSemaphores = signalSemaphores;<br><br>    if (vkQueueSubmit(graphicsQueue, 1, &amp;submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to submit draw command buffer!&quot;);<br>    }<br><br>    VkPresentInfoKHR presentInfo{};<br>    presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;<br><br>    // Wait for the renderFinishedSemaphore to be signaled<br>    presentInfo.waitSemaphoreCount = 1;<br>    presentInfo.pWaitSemaphores = signalSemaphores;<br><br>    VkSwapchainKHR swapChains[] = {swapChain};<br>    presentInfo.swapchainCount = 1;<br>    presentInfo.pSwapchains = swapChains;<br>    presentInfo.pImageIndices = &amp;imageIndex;<br><br>    result = vkQueuePresentKHR(presentQueue, &amp;presentInfo);<br><br>    if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized)<br>    {<br>        framebufferResized = false;<br>        RecreateSwapChain();<br>    }<br>    else if (result != VK_SUCCESS)<br>    {<br>        throw runtime_error(&quot;Failed to present swap chain image!&quot;);<br>    }<br><br>    currentFrame = (currentFrame + 1) % maxFlightFrames;<br>}</pre><p>And after all of this hard work, we can finally see a triangle on screen!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ez9U1C8kxrpTkiPBCDHwzA.png" /></figure><p>Creating a triangle is just the beginning with Vulkan. There’s so much more I need to explore. I’ll keep progressing on this path and share my experiences in my upcoming blog post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHeCyhdQILsuyki7iq4QWg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48ccbe8bc769" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game Engine Stories: Graphics Dilemma]]></title>
            <link>https://medium.com/@allenphilip78/game-engine-stories-magma-f1b59402c510?source=rss-e89073a5cd7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1b59402c510</guid>
            <category><![CDATA[engine-programming]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[dx12]]></category>
            <category><![CDATA[vulkan]]></category>
            <category><![CDATA[game-engine]]></category>
            <dc:creator><![CDATA[Allen]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 20:29:38 GMT</pubDate>
            <atom:updated>2024-04-09T16:39:29.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*ni6sQrAt-gL44tnD6Frlag.jpeg" /></figure><p>Have you ever looked at game engines like Unity and Unreal, and wonder what it would take to build something similar? Now realistically building something similar would be impossible for a single person, but that doesn’t mean something smaller tailor-made would be out of the question. This is one of the reasons I ventured on the journey of making my own Game Engine, to have the freedom to do things my way, rather than following the set rules of an existing engine. So this means I am doing it from scratch, the way I intend.</p><p>The first thing to go about is choosing which graphics API to use. While it seems very exciting to just include all three major APIs (OpenGL, Vulkan, and DirectX) from the get go, due to architectural differences, and the fact that I am not really an advanced graphics developer, means it’s better to start off with just one.</p><p>OpenGL seems to be the easiest option out of the bunch with me having a bit of experience from a previous university project on the raspberry pi. While it can be really easy to start off with, everything can get really cluttered with state machine approach, along with unnecessary driver overhead. I want as much performance as possible and that completely rules out OpenGL and this also allows me the ability to learn a lower-level API.</p><p>That leaves me with two options, Vulkan or DirectX. The thing to note with DirectX is that I have two options within the same category too, i.e., DX11 and DX12. DX11 is significantly easier to learn, but has some of the same pitfalls as OpenGL with significant driver overhead, so that is not an ideal option either. I could go with DX12, especially considering its tailor-made for Windows, and realistically I would most probably just target Windows anyways, so the cross-platform nature of Vulkan doesn’t seem as much of advantage apart from the vague possibility of maybe supporting Linux or MacOS down the line. So I had to do more research, to choose what I really wanted.</p><p>Looking at several posts of people asking for similar advice, and general differences, the main points to consider for either engine were:</p><ul><li>Vulkan is more verbose but leads to more “cleaner” and consistent code.</li><li>Vulkan allows for multiple ways to implement a lot of stuff, while DX12 usually will only provide a single implementation for most things.</li><li>DX12 has most functionality packed into the core API while Vulkan mostly relies on extensions, which can mean an easier time with implementing certain stuff in DX12, but can also mean higher performance in Vulkan as unnecessary fluff doesn’t have to be used if not needed.</li><li>DX12 isn’t just a graphics API. It is a set of tools include networking, sound, input etc. This does mean I don’t have to worry about implementing my own functionality or using external tools.</li><li>Vulkan has significantly better documentation, along with extensive support communities and tutorials as compared to DX12, which has far worse documentation, along with a surprising lack of community.</li></ul><p>Looking at the points put forth by developers who have worked with both API’s, I have decided to go forth with Vulkan mainly due to its significantly better documentation, and how the API is designed matches my style of coding, along with the fact that it is more flexible. Regardless of what I would have chosen, I would be starting from scratch, so I wouldn’t have any advantage in that regard.</p><p>From the next chapters, I am going to talk more about my actual development starting with 0 Vulkan experience prior to this project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHeCyhdQILsuyki7iq4QWg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1b59402c510" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>