├── .editorconfig ├── .gitignore ├── .gitmodules ├── LICENSE ├── README.md ├── dub.sdl ├── dub.selections.json ├── frag.spv ├── source └── app.d ├── triangle.frag ├── triangle.vert └── vert.spv /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | charset = utf-8 7 | indent_style = tab 8 | indent_size = 2 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .dub 2 | docs.json 3 | __dummy.html 4 | *.o 5 | *.obj 6 | bin/ 7 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "deps/ErupteD"] 2 | path = deps/ErupteD 3 | url = https://github.com/MaikKlein/ErupteD.git 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | 3 | Version 2.0, January 2004 4 | 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 16 | 17 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 18 | 19 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 20 | 21 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 22 | 23 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 24 | 25 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 26 | 27 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its 28 | representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 29 | 30 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 31 | 32 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 33 | 34 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of 35 | their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 36 | 37 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 38 | 39 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 40 | You must cause any modified files to carry prominent notices stating that You changed the files; and 41 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 42 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a 43 | display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 44 | 45 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 46 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 47 | 48 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 49 | 50 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work 51 | and assume any risks associated with Your exercise of permissions under this License. 52 | 53 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to 54 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 55 | 56 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless 57 | for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 58 | 59 | Copyright 2016 Maik Klein 60 | 61 | Licensed under the Apache License, Version 2.0 (the "License"); 62 | you may not use this file except in compliance with the License. 63 | You may obtain a copy of the License at 64 | 65 | http://www.apache.org/licenses/LICENSE-2.0 66 | 67 | Unless required by applicable law or agreed to in writing, software 68 | distributed under the License is distributed on an "AS IS" BASIS, 69 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 70 | See the License for the specific language governing permissions and 71 | limitations under the License. 72 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Simple example for a triangle in Vulkan 2 | 3 | ##Dependencies 4 | 5 | * SDL2 6 | * Vulkan driver + compatible hardware 7 | * Vulkan SDK from LunarG with validation layers 8 | * Vulkan lib 9 | * Currently only supported on Linux 10 | 11 | ## How to build and run 12 | 13 | ``` 14 | git clone https://github.com/MaikKlein/VulkanTriangleD.git 15 | cd VulkanTriangleD 16 | git submodule init 17 | git submodule update 18 | dub run 19 | ``` 20 | 21 | ![Triangle](https://i.imgur.com/b1JRKdW.png) 22 | 23 | ## A thanks to 24 | 25 | * [Api with no secrets](https://software.intel.com/en-us/articles/api-without-secrets-introduction-to-vulkan-part-1) 26 | * [Vulkan tutorial](http://av.dfki.de/~jhenriques/development.html) 27 | * [Vulkan examples](https://github.com/SaschaWillems/Vulkan) 28 | -------------------------------------------------------------------------------- /dub.sdl: -------------------------------------------------------------------------------- 1 | name "vulkantriangled" 2 | description "A minimal D application." 3 | copyright "Copyright © 2016, maik" 4 | authors "maik" 5 | dependency "derelict-sdl2" version="~>2.0.0" 6 | 7 | dependency "erupted" version="~>1.3.2" path="deps/ErupteD" 8 | subConfiguration "erupted" "dub-platform-xlib-derelict-loader" 9 | 10 | libs"Xi" "pthread" "X11" "Xxf86vm" "Xrandr" "pthread" "GL" "GLU" "Xinerama" "Xcursor" platform="linux-x86_64" 11 | 12 | targetPath "./bin" 13 | 14 | -------------------------------------------------------------------------------- /dub.selections.json: -------------------------------------------------------------------------------- 1 | { 2 | "fileVersion": 1, 3 | "versions": { 4 | "xcb-d": "1.11.1", 5 | "wayland-client-d": "1.8.90", 6 | "derelict-sdl2": "2.0.0", 7 | "xlib-d": "0.1.0", 8 | "derelict-util": "2.0.6" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /frag.spv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MaikKlein/VulkanTriangleD/a692bec19bd67cf3d1c48dce37d5e0883573e52e/frag.spv -------------------------------------------------------------------------------- /source/app.d: -------------------------------------------------------------------------------- 1 | import erupted; 2 | 3 | void enforceVk(VkResult res){ 4 | import std.exception; 5 | import std.conv; 6 | enforce(res is VkResult.VK_SUCCESS, res.to!string); 7 | } 8 | 9 | extern(System) VkBool32 MyDebugReportCallback( 10 | VkDebugReportFlagsEXT flags, 11 | VkDebugReportObjectTypeEXT objectType, 12 | uint64_t object, 13 | size_t location, 14 | int32_t messageCode, 15 | const char* pLayerPrefix, 16 | const char* pMessage, 17 | void* pUserData) nothrow @nogc 18 | { 19 | import std.stdio; 20 | printf("ObjectTpye: %i \n", objectType); 21 | printf(pMessage); 22 | printf("\n"); 23 | return VK_FALSE; 24 | } 25 | 26 | struct VkContext{ 27 | VkInstance instance; 28 | VkSurfaceKHR surface; 29 | VkPhysicalDevice physicalDevice; 30 | VkDevice logicalDevice; 31 | ulong presentQueueFamilyIndex = -1; 32 | VkQueue presentQueue; 33 | uint width = -1; 34 | uint height = -1; 35 | VkSwapchainKHR swapchain; 36 | VkCommandBuffer setupCmdBuffer; 37 | VkCommandBuffer drawCmdBuffer; 38 | VkImage[] presentImages; 39 | VkImage depthImage; 40 | VkPhysicalDeviceMemoryProperties memoryProperties; 41 | VkImageView depthImageView; 42 | VkRenderPass renderPass; 43 | VkFramebuffer[] frameBuffers; 44 | VkBuffer vertexInputBuffer; 45 | VkPipelineLayout pipelineLayout; 46 | VkPipeline pipeline; 47 | VkSemaphore presentCompleteSemaphore, renderingCompleteSemaphore; 48 | } 49 | 50 | void main() 51 | { 52 | import std.exception; 53 | import derelict.sdl2.sdl; 54 | import std.algorithm.searching; 55 | import std.algorithm.iteration; 56 | import std.range: iota; 57 | import std.stdio; 58 | import core.stdc.string; 59 | 60 | VkContext vkcontext; 61 | vkcontext.width = 800; 62 | vkcontext.height = 600; 63 | 64 | DerelictSDL2.load(); 65 | auto sdlWindow = SDL_CreateWindow("vulkan", 0, 0, 800, 600, 0); 66 | SDL_SysWMinfo sdlWindowInfo; 67 | 68 | SDL_VERSION(&sdlWindowInfo.version_); 69 | enforce(SDL_GetWindowWMInfo(sdlWindow, &sdlWindowInfo), "sdl err"); 70 | 71 | DerelictErupted.load(); 72 | VkApplicationInfo appinfo; 73 | appinfo.pApplicationName = "Breeze"; 74 | appinfo.apiVersion = VK_MAKE_VERSION(1, 0, 2); 75 | 76 | const(char*)[3] extensionNames = [ 77 | "VK_KHR_surface", 78 | "VK_KHR_xlib_surface", 79 | "VK_EXT_debug_report" 80 | ]; 81 | uint extensionCount = 0; 82 | vkEnumerateInstanceExtensionProperties(null, &extensionCount, null ); 83 | 84 | auto extensionProps = new VkExtensionProperties[](extensionCount); 85 | vkEnumerateInstanceExtensionProperties(null, &extensionCount, extensionProps.ptr ); 86 | 87 | enforce(extensionNames[].all!((extensionName){ 88 | return extensionProps[].count!((extension){ 89 | return strcmp(cast(const(char*))extension.extensionName, extensionName) == 0; 90 | }) > 0; 91 | }), "extension props failure"); 92 | 93 | uint layerCount = 0; 94 | vkEnumerateInstanceLayerProperties(&layerCount, null); 95 | 96 | auto layerProps = new VkLayerProperties[](layerCount); 97 | vkEnumerateInstanceLayerProperties(&layerCount, layerProps.ptr); 98 | 99 | const(char*)[1] validationLayers = ["VK_LAYER_LUNARG_standard_validation"]; 100 | 101 | enforce(validationLayers[].all!((layerName){ 102 | return layerProps[].count!((layer){ 103 | return strcmp(cast(const(char*))layer.layerName, layerName) == 0; 104 | }) > 0; 105 | }), "Validation layer failure"); 106 | 107 | VkInstanceCreateInfo createinfo; 108 | createinfo.sType = VkStructureType.VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; 109 | createinfo.pApplicationInfo = &appinfo; 110 | createinfo.enabledExtensionCount = cast(uint)extensionNames.length; 111 | createinfo.ppEnabledExtensionNames = extensionNames.ptr; 112 | createinfo.enabledLayerCount = validationLayers.length; 113 | createinfo.ppEnabledLayerNames = validationLayers.ptr; 114 | 115 | enforceVk(vkCreateInstance(&createinfo, null, &vkcontext.instance)); 116 | 117 | loadInstanceLevelFunctions(vkcontext.instance); 118 | auto debugcallbackCreateInfo = VkDebugReportCallbackCreateInfoEXT( 119 | VkStructureType.VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT, 120 | null, 121 | VkDebugReportFlagBitsEXT.VK_DEBUG_REPORT_ERROR_BIT_EXT | 122 | VkDebugReportFlagBitsEXT.VK_DEBUG_REPORT_WARNING_BIT_EXT | 123 | VkDebugReportFlagBitsEXT.VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, 124 | &MyDebugReportCallback, 125 | null 126 | ); 127 | VkDebugReportCallbackEXT callback; 128 | enforceVk(vkCreateDebugReportCallbackEXT(vkcontext.instance, &debugcallbackCreateInfo, null, &callback)); 129 | 130 | auto xlibInfo = VkXlibSurfaceCreateInfoKHR( 131 | VkStructureType.VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR, 132 | null, 133 | 0, 134 | sdlWindowInfo.info.x11.display, 135 | sdlWindowInfo.info.x11.window 136 | ); 137 | enforceVk(vkCreateXlibSurfaceKHR(vkcontext.instance, &xlibInfo, null, &vkcontext.surface)); 138 | 139 | uint numOfDevices; 140 | enforceVk(vkEnumeratePhysicalDevices(vkcontext.instance, &numOfDevices, null)); 141 | 142 | auto devices = new VkPhysicalDevice[](numOfDevices); 143 | enforceVk(vkEnumeratePhysicalDevices(vkcontext.instance, &numOfDevices, devices.ptr)); 144 | 145 | const(char*)[1] deviceExtensions = ["VK_KHR_swapchain"]; 146 | 147 | foreach(index, device; devices){ 148 | VkPhysicalDeviceProperties props; 149 | 150 | vkGetPhysicalDeviceProperties(device, &props); 151 | if(props.deviceType is VkPhysicalDeviceType.VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU){ 152 | uint queueCount = 0; 153 | vkGetPhysicalDeviceQueueFamilyProperties(device, &queueCount, null); 154 | enforce(queueCount > 0); 155 | auto queueFamilyProp = new VkQueueFamilyProperties[](queueCount); 156 | vkGetPhysicalDeviceQueueFamilyProperties(device, &queueCount, queueFamilyProp.ptr); 157 | 158 | auto presentIndex = queueFamilyProp[].countUntil!((prop){ 159 | return prop.queueCount > 0 && (prop.queueFlags & VkQueueFlagBits.VK_QUEUE_GRAPHICS_BIT); 160 | }); 161 | 162 | VkBool32 supportsPresent; 163 | vkGetPhysicalDeviceSurfaceSupportKHR( 164 | device, cast(uint)presentIndex, 165 | vkcontext.surface, &supportsPresent 166 | ); 167 | 168 | if(presentIndex !is -1 && supportsPresent){ 169 | vkcontext.presentQueueFamilyIndex = presentIndex; 170 | vkcontext.physicalDevice = device; 171 | break; 172 | } 173 | } 174 | } 175 | 176 | enforce( 177 | vkcontext.presentQueueFamilyIndex !is -1 && 178 | vkcontext.physicalDevice, 179 | "Could not find a suitable device" 180 | ); 181 | 182 | uint extensionDeviceCount = 0; 183 | vkEnumerateDeviceExtensionProperties(vkcontext.physicalDevice, null, &extensionDeviceCount, null); 184 | auto extensionDeviceProps = new VkExtensionProperties[](extensionDeviceCount); 185 | 186 | vkEnumerateDeviceExtensionProperties(vkcontext.physicalDevice, null, &extensionDeviceCount, extensionDeviceProps.ptr); 187 | 188 | enforce(vkcontext.physicalDevice != null, "Device is null"); 189 | //enforce the swapchain 190 | enforce(extensionDeviceProps[].map!(prop => prop.extensionName).count!((name){ 191 | return strcmp(cast(const(char*))name, "VK_KHR_swapchain" ) == 0; 192 | }) > 0); 193 | 194 | float[1] priorities = [1.0f]; 195 | VkDeviceQueueCreateInfo deviceQueueCreateInfo = 196 | VkDeviceQueueCreateInfo( 197 | VkStructureType.VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, 198 | null, 199 | 0, 200 | cast(uint)vkcontext.presentQueueFamilyIndex, 201 | cast(uint)priorities.length, 202 | priorities.ptr 203 | ); 204 | 205 | VkPhysicalDeviceFeatures features; 206 | features.shaderClipDistance = VK_TRUE; 207 | 208 | auto deviceInfo = VkDeviceCreateInfo( 209 | VkStructureType.VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, 210 | null, 211 | 0, 212 | 1, 213 | &deviceQueueCreateInfo, 214 | validationLayers.length, 215 | validationLayers.ptr, 216 | cast(uint)deviceExtensions.length, 217 | deviceExtensions.ptr, 218 | &features 219 | ); 220 | enforceVk(vkCreateDevice(vkcontext.physicalDevice, &deviceInfo, null, &vkcontext.logicalDevice)); 221 | 222 | loadDeviceLevelFunctions(vkcontext.logicalDevice); 223 | VkQueue queue; 224 | vkGetDeviceQueue(vkcontext.logicalDevice, cast(uint)vkcontext.presentQueueFamilyIndex, 0, &vkcontext.presentQueue); 225 | 226 | uint formatCount = 0; 227 | vkGetPhysicalDeviceSurfaceFormatsKHR(vkcontext.physicalDevice, vkcontext.surface, &formatCount, null); 228 | enforce(formatCount > 0, "Format failed"); 229 | auto surfaceFormats = new VkSurfaceFormatKHR[](formatCount); 230 | vkGetPhysicalDeviceSurfaceFormatsKHR(vkcontext.physicalDevice, vkcontext.surface, &formatCount, surfaceFormats.ptr); 231 | 232 | VkFormat colorFormat; 233 | if(surfaceFormats[0].format is VK_FORMAT_UNDEFINED){ 234 | colorFormat = VK_FORMAT_B8G8R8_UNORM; 235 | } 236 | else{ 237 | colorFormat = surfaceFormats[0].format; 238 | } 239 | 240 | VkColorSpaceKHR colorSpace; 241 | colorSpace = surfaceFormats[0].colorSpace; 242 | 243 | VkSurfaceCapabilitiesKHR surfaceCapabilities; 244 | vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vkcontext.physicalDevice, vkcontext.surface, &surfaceCapabilities); 245 | 246 | uint desiredImageCount = 2; 247 | if( desiredImageCount < surfaceCapabilities.minImageCount ) { 248 | desiredImageCount = surfaceCapabilities.minImageCount; 249 | } 250 | else if(surfaceCapabilities.maxImageCount != 0 && 251 | desiredImageCount > surfaceCapabilities.maxImageCount ) { 252 | desiredImageCount = surfaceCapabilities.maxImageCount; 253 | } 254 | 255 | VkExtent2D surfaceResolution = surfaceCapabilities.currentExtent; 256 | 257 | if(surfaceResolution.width is -1){ 258 | surfaceResolution.width = vkcontext.width; 259 | surfaceResolution.height = vkcontext.height; 260 | } 261 | else{ 262 | vkcontext.width = surfaceResolution.width; 263 | vkcontext.height = surfaceResolution.height; 264 | } 265 | 266 | VkSurfaceTransformFlagBitsKHR preTransform = surfaceCapabilities.currentTransform; 267 | if(surfaceCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR){ 268 | preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; 269 | } 270 | 271 | uint presentModeCount = 0; 272 | vkGetPhysicalDeviceSurfacePresentModesKHR(vkcontext.physicalDevice, vkcontext.surface, &presentModeCount, null); 273 | auto presentModes = new VkPresentModeKHR[](presentModeCount); 274 | vkGetPhysicalDeviceSurfacePresentModesKHR(vkcontext.physicalDevice, vkcontext.surface, &presentModeCount, presentModes.ptr); 275 | 276 | VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR; 277 | foreach(mode; presentModes){ 278 | if(mode is VK_PRESENT_MODE_MAILBOX_KHR){ 279 | presentMode = mode; 280 | break; 281 | } 282 | } 283 | 284 | VkSwapchainCreateInfoKHR swapchainCreateInfo; 285 | swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; 286 | swapchainCreateInfo.surface = vkcontext.surface; 287 | swapchainCreateInfo.imageFormat = colorFormat; 288 | swapchainCreateInfo.minImageCount = desiredImageCount; 289 | swapchainCreateInfo.imageColorSpace = colorSpace; 290 | swapchainCreateInfo.imageExtent = surfaceResolution; 291 | swapchainCreateInfo.imageArrayLayers = 1; 292 | swapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; 293 | swapchainCreateInfo.imageSharingMode = VkSharingMode.VK_SHARING_MODE_EXCLUSIVE; 294 | swapchainCreateInfo.preTransform = preTransform; 295 | swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; 296 | swapchainCreateInfo.presentMode = presentMode; 297 | swapchainCreateInfo.clipped = VK_TRUE; 298 | swapchainCreateInfo.oldSwapchain = null; 299 | 300 | enforceVk(vkCreateSwapchainKHR(vkcontext.logicalDevice, &swapchainCreateInfo, null, &vkcontext.swapchain)); 301 | 302 | VkCommandPoolCreateInfo commandPoolCreateInfo; 303 | commandPoolCreateInfo.sType = VkStructureType.VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; 304 | commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; 305 | commandPoolCreateInfo.queueFamilyIndex = cast(uint)vkcontext.presentQueueFamilyIndex; 306 | 307 | VkCommandPool commandPool; 308 | enforceVk(vkCreateCommandPool(vkcontext.logicalDevice, &commandPoolCreateInfo, null, &commandPool)); 309 | 310 | VkCommandBufferAllocateInfo cmdBufferAllocateInfo; 311 | cmdBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; 312 | cmdBufferAllocateInfo.commandPool = commandPool; 313 | cmdBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; 314 | cmdBufferAllocateInfo.commandBufferCount = 1; 315 | 316 | enforceVk(vkAllocateCommandBuffers(vkcontext.logicalDevice, &cmdBufferAllocateInfo, &vkcontext.setupCmdBuffer)); 317 | enforceVk(vkAllocateCommandBuffers(vkcontext.logicalDevice, &cmdBufferAllocateInfo, &vkcontext.drawCmdBuffer)); 318 | 319 | 320 | uint imageCount = 0; 321 | vkGetSwapchainImagesKHR(vkcontext.logicalDevice, vkcontext.swapchain, &imageCount, null); 322 | vkcontext.presentImages = new VkImage[](imageCount); 323 | enforceVk(vkGetSwapchainImagesKHR(vkcontext.logicalDevice, vkcontext.swapchain, &imageCount, vkcontext.presentImages.ptr)); 324 | 325 | VkImageViewCreateInfo imgViewCreateInfo; 326 | imgViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; 327 | imgViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; 328 | imgViewCreateInfo.format = colorFormat; 329 | imgViewCreateInfo.components = 330 | VkComponentMapping( 331 | VK_COMPONENT_SWIZZLE_R, 332 | VK_COMPONENT_SWIZZLE_G, 333 | VK_COMPONENT_SWIZZLE_B, 334 | VK_COMPONENT_SWIZZLE_A, 335 | ); 336 | 337 | imgViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; 338 | imgViewCreateInfo.subresourceRange.baseMipLevel = 0; 339 | imgViewCreateInfo.subresourceRange.levelCount = 1; 340 | imgViewCreateInfo.subresourceRange.baseArrayLayer = 0; 341 | imgViewCreateInfo.subresourceRange.layerCount = 1; 342 | 343 | VkCommandBufferBeginInfo beginInfo; 344 | beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; 345 | beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; 346 | 347 | VkFenceCreateInfo fenceCreateInfo; 348 | fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; 349 | 350 | VkFence submitFence; 351 | vkCreateFence(vkcontext.logicalDevice, &fenceCreateInfo, null, &submitFence); 352 | 353 | auto presentImageViews = new VkImageView[](imageCount); 354 | foreach(index; iota(0, imageCount)){ 355 | imgViewCreateInfo.image = vkcontext.presentImages[index]; 356 | enforceVk(vkCreateImageView(vkcontext.logicalDevice, &imgViewCreateInfo, null, &presentImageViews[index])); 357 | } 358 | 359 | vkGetPhysicalDeviceMemoryProperties(vkcontext.physicalDevice, &vkcontext.memoryProperties); 360 | 361 | VkImageCreateInfo imageCreateInfo; 362 | imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; 363 | imageCreateInfo.format = VK_FORMAT_D16_UNORM; 364 | imageCreateInfo.extent = VkExtent3D(vkcontext.width, vkcontext.height, 1); 365 | imageCreateInfo.mipLevels = 1; 366 | imageCreateInfo.arrayLayers = 1; 367 | imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; 368 | imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; 369 | imageCreateInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; 370 | imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; 371 | imageCreateInfo.queueFamilyIndexCount = 0; 372 | imageCreateInfo.pQueueFamilyIndices = null; 373 | imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; 374 | 375 | enforceVk(vkCreateImage(vkcontext.logicalDevice, &imageCreateInfo, null, &vkcontext.depthImage)); 376 | 377 | VkMemoryRequirements memoryRequirements; 378 | vkGetImageMemoryRequirements(vkcontext.logicalDevice, vkcontext.depthImage, &memoryRequirements); 379 | 380 | VkMemoryAllocateInfo imageAllocationInfo; 381 | imageAllocationInfo.allocationSize = memoryRequirements.size; 382 | 383 | uint memoryTypeBits = memoryRequirements.memoryTypeBits; 384 | VkMemoryPropertyFlags desiredMemoryFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; 385 | 386 | foreach(index; iota(0, 32)){ 387 | VkMemoryType memoryType = vkcontext.memoryProperties.memoryTypes[index]; 388 | if(memoryTypeBits & 1){ 389 | if((memoryType.propertyFlags & desiredMemoryFlags) is desiredMemoryFlags){ 390 | imageAllocationInfo.memoryTypeIndex = index; 391 | break; 392 | } 393 | } 394 | memoryTypeBits = memoryTypeBits >> 1; 395 | } 396 | 397 | VkDeviceMemory imageMemory; 398 | enforceVk(vkAllocateMemory(vkcontext.logicalDevice, &imageAllocationInfo, null, &imageMemory)); 399 | 400 | enforceVk(vkBindImageMemory(vkcontext.logicalDevice, vkcontext.depthImage, imageMemory, 0)); 401 | 402 | vkBeginCommandBuffer(vkcontext.setupCmdBuffer, &beginInfo); 403 | VkImageMemoryBarrier layoutTransitionBarrier; 404 | layoutTransitionBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; 405 | layoutTransitionBarrier.srcAccessMask = 0; 406 | layoutTransitionBarrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | 407 | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; 408 | layoutTransitionBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; 409 | layoutTransitionBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; 410 | layoutTransitionBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 411 | layoutTransitionBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 412 | layoutTransitionBarrier.image = vkcontext.depthImage; 413 | layoutTransitionBarrier.subresourceRange = VkImageSubresourceRange(VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1); 414 | 415 | vkCmdPipelineBarrier( 416 | vkcontext.setupCmdBuffer, 417 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 418 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 419 | 0, 420 | 0, null, 421 | 0, null, 422 | 1, &layoutTransitionBarrier 423 | ); 424 | 425 | vkEndCommandBuffer(vkcontext.setupCmdBuffer); 426 | 427 | VkPipelineStageFlags[1] waitStageMask = [ VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT ]; 428 | VkSubmitInfo submitInfo; 429 | submitInfo.waitSemaphoreCount = 0; 430 | submitInfo.pWaitSemaphores = null; 431 | submitInfo.pWaitDstStageMask = waitStageMask.ptr; 432 | submitInfo.commandBufferCount = 1; 433 | submitInfo.pCommandBuffers = &vkcontext.setupCmdBuffer; 434 | submitInfo.signalSemaphoreCount = 0; 435 | submitInfo.pSignalSemaphores = null; 436 | 437 | vkQueueSubmit(vkcontext.presentQueue, 1, &submitInfo, submitFence); 438 | 439 | vkWaitForFences(vkcontext.logicalDevice, 1, &submitFence, VK_TRUE, ulong.max); 440 | vkResetFences(vkcontext.logicalDevice, 1, &submitFence); 441 | vkResetCommandBuffer(vkcontext.setupCmdBuffer, 0); 442 | 443 | VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; 444 | VkImageViewCreateInfo imageViewCreateInfo; 445 | imageViewCreateInfo.image = vkcontext.depthImage; 446 | imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; 447 | imageViewCreateInfo.format = imageCreateInfo.format; 448 | imageViewCreateInfo.components = 449 | VkComponentMapping(VK_COMPONENT_SWIZZLE_IDENTITY, 450 | VK_COMPONENT_SWIZZLE_IDENTITY, 451 | VK_COMPONENT_SWIZZLE_IDENTITY, 452 | VK_COMPONENT_SWIZZLE_IDENTITY 453 | ); 454 | imageViewCreateInfo.subresourceRange.aspectMask = aspectMask; 455 | imageViewCreateInfo.subresourceRange.baseMipLevel = 0; 456 | imageViewCreateInfo.subresourceRange.levelCount = 1; 457 | imageViewCreateInfo.subresourceRange.baseArrayLayer = 0; 458 | imageViewCreateInfo.subresourceRange.layerCount = 1; 459 | 460 | enforceVk(vkCreateImageView(vkcontext.logicalDevice, &imageViewCreateInfo, null, &vkcontext.depthImageView)); 461 | 462 | VkAttachmentDescription[2] passAttachments; 463 | passAttachments[0].format = colorFormat; 464 | passAttachments[0].samples = VK_SAMPLE_COUNT_1_BIT; 465 | passAttachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; 466 | passAttachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; 467 | passAttachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; 468 | passAttachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; 469 | passAttachments[0].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; 470 | passAttachments[0].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; 471 | 472 | passAttachments[1].format = VK_FORMAT_D16_UNORM; 473 | passAttachments[1].samples = VK_SAMPLE_COUNT_1_BIT; 474 | passAttachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; 475 | passAttachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; 476 | passAttachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; 477 | passAttachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; 478 | passAttachments[1].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; 479 | passAttachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; 480 | 481 | VkAttachmentReference colorAttachmentReference; 482 | colorAttachmentReference.attachment = 0; 483 | colorAttachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; 484 | 485 | VkAttachmentReference depthAttachmentReference; 486 | depthAttachmentReference.attachment = 1; 487 | depthAttachmentReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; 488 | 489 | VkSubpassDescription subpass; 490 | subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; 491 | subpass.colorAttachmentCount = 1; 492 | subpass.pColorAttachments = &colorAttachmentReference; 493 | subpass.pDepthStencilAttachment = &depthAttachmentReference; 494 | 495 | VkRenderPassCreateInfo renderPassCreateInfo; 496 | renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; 497 | renderPassCreateInfo.attachmentCount = 2; 498 | renderPassCreateInfo.pAttachments = passAttachments.ptr; 499 | renderPassCreateInfo.subpassCount = 1; 500 | renderPassCreateInfo.pSubpasses = &subpass; 501 | 502 | enforceVk(vkCreateRenderPass(vkcontext.logicalDevice, &renderPassCreateInfo, null, &vkcontext.renderPass)); 503 | 504 | VkImageView[2] frameBufferAttachments; 505 | frameBufferAttachments[1] = vkcontext.depthImageView; 506 | 507 | VkFramebufferCreateInfo frameBufferCreateInfo; 508 | frameBufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; 509 | frameBufferCreateInfo.renderPass = vkcontext.renderPass; 510 | frameBufferCreateInfo.attachmentCount = 2; 511 | frameBufferCreateInfo.pAttachments = frameBufferAttachments.ptr; 512 | frameBufferCreateInfo.width = vkcontext.width; 513 | frameBufferCreateInfo.height = vkcontext.height; 514 | frameBufferCreateInfo.layers = 1; 515 | 516 | vkcontext.frameBuffers = new VkFramebuffer[](imageCount); 517 | foreach(index; iota(0, imageCount)){ 518 | frameBufferAttachments[0] = presentImageViews[index]; 519 | enforceVk(vkCreateFramebuffer(vkcontext.logicalDevice, &frameBufferCreateInfo, null, &vkcontext.frameBuffers[index])); 520 | } 521 | 522 | struct Vertex{ 523 | float x, y, z, w; 524 | } 525 | 526 | VkBufferCreateInfo vertexInputBufferInfo; 527 | vertexInputBufferInfo.size = Vertex.sizeof * 3; 528 | vertexInputBufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; 529 | vertexInputBufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; 530 | 531 | enforceVk(vkCreateBuffer(vkcontext.logicalDevice, &vertexInputBufferInfo, null, &vkcontext.vertexInputBuffer)); 532 | 533 | VkMemoryRequirements vertexBufferMemoryReq; 534 | vkGetBufferMemoryRequirements(vkcontext.logicalDevice, vkcontext.vertexInputBuffer, &vertexBufferMemoryReq); 535 | 536 | VkMemoryAllocateInfo bufferAllocateInfo; 537 | bufferAllocateInfo.allocationSize = vertexBufferMemoryReq.size; 538 | 539 | uint vertexMemoryTypeBits = vertexBufferMemoryReq.memoryTypeBits; 540 | VkMemoryPropertyFlags vertexDesiredMemoryFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; 541 | 542 | foreach(index; iota(0, 32)){ 543 | VkMemoryType memoryType = vkcontext.memoryProperties.memoryTypes[index]; 544 | if(vertexMemoryTypeBits & 1){ 545 | if((memoryType.propertyFlags & vertexDesiredMemoryFlags) is vertexDesiredMemoryFlags){ 546 | bufferAllocateInfo.memoryTypeIndex = index; 547 | break; 548 | } 549 | } 550 | vertexMemoryTypeBits = vertexMemoryTypeBits >> 1; 551 | } 552 | 553 | VkDeviceMemory vertexBufferMemory; 554 | enforceVk(vkAllocateMemory(vkcontext.logicalDevice, &bufferAllocateInfo, null, &vertexBufferMemory)); 555 | 556 | void* mapped; 557 | enforceVk(vkMapMemory(vkcontext.logicalDevice, vertexBufferMemory, 0, VK_WHOLE_SIZE, 0, &mapped)); 558 | 559 | Vertex[] triangle = (cast(Vertex*)mapped)[0 .. 3]; 560 | triangle[0] = Vertex(-1.0f, 1.0f, 0.0f, 1.0f); 561 | triangle[1] = Vertex(1.0f, 1.0f, 0.0f, 1.0f); 562 | triangle[2] = Vertex(0.0f, -1.0f, 0.0f, 1.0f); 563 | 564 | vkUnmapMemory(vkcontext.logicalDevice, vertexBufferMemory ); 565 | enforceVk(vkBindBufferMemory(vkcontext.logicalDevice, vkcontext.vertexInputBuffer, vertexBufferMemory, 0)); 566 | 567 | auto vertFile = File("vert.spv", "r"); 568 | auto fragFile = File("frag.spv", "r"); 569 | 570 | char[] vertCode = new char[](vertFile.size); 571 | auto vertCodeSlice = vertFile.rawRead(vertCode); 572 | 573 | char[] fragCode = new char[](fragFile.size); 574 | auto fragCodeSlice = fragFile.rawRead(fragCode); 575 | 576 | VkShaderModuleCreateInfo vertexShaderCreateInfo; 577 | vertexShaderCreateInfo.codeSize = vertCodeSlice.length; 578 | vertexShaderCreateInfo.pCode = cast(uint*)vertCodeSlice.ptr; 579 | 580 | VkShaderModuleCreateInfo fragmentShaderCreateInfo; 581 | fragmentShaderCreateInfo.codeSize = fragCodeSlice.length; 582 | fragmentShaderCreateInfo.pCode = cast(uint*)fragCodeSlice.ptr; 583 | 584 | VkShaderModule vertexShaderModule; 585 | enforceVk(vkCreateShaderModule(vkcontext.logicalDevice, &vertexShaderCreateInfo, null, &vertexShaderModule)); 586 | 587 | VkShaderModule fragmentShaderModule; 588 | enforceVk(vkCreateShaderModule(vkcontext.logicalDevice, &fragmentShaderCreateInfo, null, &fragmentShaderModule)); 589 | 590 | VkPipelineLayoutCreateInfo layoutCreateInfo; 591 | layoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; 592 | layoutCreateInfo.setLayoutCount = 0; 593 | layoutCreateInfo.pSetLayouts = null; // Not setting any bindings! 594 | layoutCreateInfo.pushConstantRangeCount = 0; 595 | layoutCreateInfo.pPushConstantRanges = null; 596 | 597 | enforceVk(vkCreatePipelineLayout(vkcontext.logicalDevice, &layoutCreateInfo, null, &vkcontext.pipelineLayout)); 598 | 599 | VkPipelineShaderStageCreateInfo[2] shaderStageCreateInfo; 600 | shaderStageCreateInfo[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; 601 | shaderStageCreateInfo[0].stage = VK_SHADER_STAGE_VERTEX_BIT; 602 | shaderStageCreateInfo[0]._module = vertexShaderModule; 603 | shaderStageCreateInfo[0].pName = "main"; // shader entry point function name 604 | shaderStageCreateInfo[0].pSpecializationInfo = null; 605 | 606 | shaderStageCreateInfo[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; 607 | shaderStageCreateInfo[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; 608 | shaderStageCreateInfo[1]._module = fragmentShaderModule; 609 | shaderStageCreateInfo[1].pName = "main"; // shader entry point function name 610 | shaderStageCreateInfo[1].pSpecializationInfo = null; 611 | 612 | VkVertexInputBindingDescription vertexBindingDescription = {}; 613 | vertexBindingDescription.binding = 0; 614 | vertexBindingDescription.stride = Vertex.sizeof; 615 | vertexBindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; 616 | 617 | VkVertexInputAttributeDescription vertexAttributeDescritpion = {}; 618 | vertexAttributeDescritpion.location = 0; 619 | vertexAttributeDescritpion.binding = 0; 620 | vertexAttributeDescritpion.format = VK_FORMAT_R32G32B32A32_SFLOAT; 621 | vertexAttributeDescritpion.offset = 0; 622 | 623 | VkPipelineVertexInputStateCreateInfo vertexInputStateCreateInfo = {}; 624 | vertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; 625 | vertexInputStateCreateInfo.vertexBindingDescriptionCount = 1; 626 | vertexInputStateCreateInfo.pVertexBindingDescriptions = &vertexBindingDescription; 627 | vertexInputStateCreateInfo.vertexAttributeDescriptionCount = 1; 628 | vertexInputStateCreateInfo.pVertexAttributeDescriptions = &vertexAttributeDescritpion; 629 | 630 | VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCreateInfo = {}; 631 | inputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; 632 | inputAssemblyStateCreateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; 633 | inputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE; 634 | 635 | VkViewport viewport = {}; 636 | viewport.x = 0; 637 | viewport.y = 0; 638 | viewport.width = vkcontext.width; 639 | viewport.height = vkcontext.height; 640 | viewport.minDepth = 0; 641 | viewport.maxDepth = 1; 642 | 643 | VkRect2D scissors; 644 | scissors.offset = VkOffset2D( 0, 0 ); 645 | scissors.extent = VkExtent2D( vkcontext.width, vkcontext.height ); 646 | 647 | VkPipelineViewportStateCreateInfo viewportState; 648 | viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; 649 | viewportState.viewportCount = 1; 650 | viewportState.pViewports = &viewport; 651 | viewportState.scissorCount = 1; 652 | viewportState.pScissors = &scissors; 653 | 654 | 655 | VkPipelineRasterizationStateCreateInfo rasterizationState; 656 | rasterizationState.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; 657 | rasterizationState.depthClampEnable = VK_FALSE; 658 | rasterizationState.rasterizerDiscardEnable = VK_FALSE; 659 | rasterizationState.polygonMode = VK_POLYGON_MODE_FILL; 660 | rasterizationState.cullMode = VK_CULL_MODE_NONE; 661 | rasterizationState.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; 662 | rasterizationState.depthBiasEnable = VK_FALSE; 663 | rasterizationState.depthBiasConstantFactor = 0; 664 | rasterizationState.depthBiasClamp = 0; 665 | rasterizationState.depthBiasSlopeFactor = 0; 666 | rasterizationState.lineWidth = 1; 667 | 668 | VkPipelineMultisampleStateCreateInfo multisampleState; 669 | multisampleState.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; 670 | multisampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; 671 | multisampleState.sampleShadingEnable = VK_FALSE; 672 | multisampleState.minSampleShading = 0; 673 | multisampleState.pSampleMask = null; 674 | multisampleState.alphaToCoverageEnable = VK_FALSE; 675 | multisampleState.alphaToOneEnable = VK_FALSE; 676 | 677 | VkStencilOpState noOPStencilState = {}; 678 | noOPStencilState.failOp = VK_STENCIL_OP_KEEP; 679 | noOPStencilState.passOp = VK_STENCIL_OP_KEEP; 680 | noOPStencilState.depthFailOp = VK_STENCIL_OP_KEEP; 681 | noOPStencilState.compareOp = VK_COMPARE_OP_ALWAYS; 682 | noOPStencilState.compareMask = 0; 683 | noOPStencilState.writeMask = 0; 684 | noOPStencilState.reference = 0; 685 | 686 | VkPipelineDepthStencilStateCreateInfo depthState; 687 | depthState.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; 688 | depthState.depthTestEnable = VK_TRUE; 689 | depthState.depthWriteEnable = VK_TRUE; 690 | depthState.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; 691 | depthState.depthBoundsTestEnable = VK_FALSE; 692 | depthState.stencilTestEnable = VK_FALSE; 693 | depthState.front = noOPStencilState; 694 | depthState.back = noOPStencilState; 695 | depthState.minDepthBounds = 0; 696 | depthState.maxDepthBounds = 0; 697 | 698 | VkPipelineColorBlendAttachmentState colorBlendAttachmentState = {}; 699 | colorBlendAttachmentState.blendEnable = VK_FALSE; 700 | colorBlendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_COLOR; 701 | colorBlendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR; 702 | colorBlendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; 703 | colorBlendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; 704 | colorBlendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; 705 | colorBlendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; 706 | colorBlendAttachmentState.colorWriteMask = 0xf; 707 | 708 | VkPipelineColorBlendStateCreateInfo colorBlendState = {}; 709 | colorBlendState.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; 710 | colorBlendState.logicOpEnable = VK_FALSE; 711 | colorBlendState.logicOp = VK_LOGIC_OP_CLEAR; 712 | colorBlendState.attachmentCount = 1; 713 | colorBlendState.pAttachments = &colorBlendAttachmentState; 714 | colorBlendState.blendConstants[0] = 0.0; 715 | colorBlendState.blendConstants[1] = 0.0; 716 | colorBlendState.blendConstants[2] = 0.0; 717 | colorBlendState.blendConstants[3] = 0.0; 718 | 719 | VkDynamicState[2] dynamicState = [ VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR ]; 720 | VkPipelineDynamicStateCreateInfo dynamicStateCreateInfo; 721 | dynamicStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; 722 | dynamicStateCreateInfo.dynamicStateCount = 2; 723 | dynamicStateCreateInfo.pDynamicStates = dynamicState.ptr; 724 | 725 | VkGraphicsPipelineCreateInfo pipelineCreateInfo = {}; 726 | pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; 727 | pipelineCreateInfo.stageCount = 2; 728 | pipelineCreateInfo.pStages = shaderStageCreateInfo.ptr; 729 | pipelineCreateInfo.pVertexInputState = &vertexInputStateCreateInfo; 730 | pipelineCreateInfo.pInputAssemblyState = &inputAssemblyStateCreateInfo; 731 | pipelineCreateInfo.pTessellationState = null; 732 | pipelineCreateInfo.pViewportState = &viewportState; 733 | pipelineCreateInfo.pRasterizationState = &rasterizationState; 734 | pipelineCreateInfo.pMultisampleState = &multisampleState; 735 | pipelineCreateInfo.pDepthStencilState = &depthState; 736 | pipelineCreateInfo.pColorBlendState = &colorBlendState; 737 | pipelineCreateInfo.pDynamicState = &dynamicStateCreateInfo; 738 | pipelineCreateInfo.layout = vkcontext.pipelineLayout; 739 | pipelineCreateInfo.renderPass = vkcontext.renderPass; 740 | pipelineCreateInfo.subpass = 0; 741 | pipelineCreateInfo.basePipelineHandle = null; 742 | pipelineCreateInfo.basePipelineIndex = 0; 743 | 744 | enforceVk(vkCreateGraphicsPipelines(vkcontext.logicalDevice, null, 1, &pipelineCreateInfo, null, &vkcontext.pipeline)); 745 | 746 | auto semaphoreCreateInfo = VkSemaphoreCreateInfo( VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, null, 0 ); 747 | vkCreateSemaphore( vkcontext.logicalDevice, &semaphoreCreateInfo, null, &vkcontext.presentCompleteSemaphore ); 748 | vkCreateSemaphore( vkcontext.logicalDevice, &semaphoreCreateInfo, null, &vkcontext.renderingCompleteSemaphore ); 749 | 750 | //Render 751 | bool shouldClose = false; 752 | while(!shouldClose){ 753 | SDL_Event event; 754 | while(SDL_PollEvent(&event)){ 755 | if(event.type is SDL_QUIT){ 756 | shouldClose = true; 757 | } 758 | } 759 | 760 | uint32_t nextImageIdx; 761 | vkAcquireNextImageKHR( 762 | vkcontext.logicalDevice, vkcontext.swapchain, ulong.max, 763 | vkcontext.presentCompleteSemaphore, null, &nextImageIdx 764 | ); 765 | 766 | vkBeginCommandBuffer( vkcontext.drawCmdBuffer, &beginInfo ); 767 | 768 | VkImageMemoryBarrier layoutToColorTrans; 769 | layoutToColorTrans.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; 770 | layoutToColorTrans.srcAccessMask = 0; 771 | layoutToColorTrans.dstAccessMask = 772 | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | 773 | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; 774 | layoutToColorTrans.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; 775 | layoutToColorTrans.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; 776 | layoutToColorTrans.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 777 | layoutToColorTrans.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 778 | layoutToColorTrans.image = vkcontext.presentImages[ nextImageIdx ]; 779 | auto resourceRange = VkImageSubresourceRange( VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 ); 780 | layoutToColorTrans.subresourceRange = resourceRange; 781 | 782 | vkCmdPipelineBarrier( 783 | vkcontext.drawCmdBuffer, 784 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 785 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 786 | 0, 787 | 0, null, 788 | 0, null, 789 | 1, &layoutToColorTrans 790 | ); 791 | VkClearColorValue clearColorValue; 792 | clearColorValue.float32[0] = 1.0f; 793 | clearColorValue.float32[1] = 1.0f; 794 | clearColorValue.float32[2] = 1.0f; 795 | clearColorValue.float32[3] = 1.0f; 796 | 797 | VkClearValue firstclearValue; 798 | firstclearValue.color = clearColorValue; 799 | 800 | VkClearValue secondclearValue; 801 | secondclearValue.depthStencil = VkClearDepthStencilValue(1.0, 0); 802 | 803 | VkClearValue[2] clearValue = [ firstclearValue, secondclearValue ]; 804 | 805 | VkRenderPassBeginInfo renderPassBeginInfo; 806 | renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; 807 | renderPassBeginInfo.renderPass = vkcontext.renderPass; 808 | renderPassBeginInfo.framebuffer = vkcontext.frameBuffers[ nextImageIdx ]; 809 | renderPassBeginInfo.renderArea = VkRect2D(VkOffset2D(0, 0), VkExtent2D(vkcontext.width, vkcontext.height)); 810 | renderPassBeginInfo.clearValueCount = 2; 811 | renderPassBeginInfo.pClearValues = clearValue.ptr; 812 | 813 | vkCmdBeginRenderPass( 814 | vkcontext.drawCmdBuffer, &renderPassBeginInfo, 815 | VK_SUBPASS_CONTENTS_INLINE 816 | ); 817 | 818 | vkCmdBindPipeline(vkcontext.drawCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, vkcontext.pipeline); 819 | vkCmdSetViewport(vkcontext.drawCmdBuffer, 0, 1, &viewport); 820 | vkCmdSetScissor(vkcontext.drawCmdBuffer, 0 ,1, &scissors); 821 | 822 | VkDeviceSize offsets; 823 | vkCmdBindVertexBuffers( vkcontext.drawCmdBuffer, 0, 1, &vkcontext.vertexInputBuffer, &offsets ); 824 | vkCmdDraw( vkcontext.drawCmdBuffer, 3, 1, 0, 0 ); 825 | vkCmdEndRenderPass( vkcontext.drawCmdBuffer ); 826 | 827 | VkImageMemoryBarrier prePresentBarrier; 828 | prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; 829 | prePresentBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; 830 | prePresentBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; 831 | prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; 832 | prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; 833 | prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 834 | prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 835 | prePresentBarrier.subresourceRange = resourceRange; 836 | prePresentBarrier.image = vkcontext.presentImages[ nextImageIdx ]; 837 | 838 | vkCmdPipelineBarrier( 839 | vkcontext.drawCmdBuffer, 840 | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 841 | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 842 | 0, 843 | 0, null, 844 | 0, null, 845 | 1, &prePresentBarrier 846 | ); 847 | 848 | vkEndCommandBuffer( vkcontext.drawCmdBuffer ); 849 | 850 | VkPipelineStageFlags[1] waitRenderMask = [ VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT ]; 851 | VkSubmitInfo renderSubmitInfo; 852 | renderSubmitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; 853 | renderSubmitInfo.waitSemaphoreCount = 1; 854 | renderSubmitInfo.pWaitSemaphores = &vkcontext.presentCompleteSemaphore; 855 | renderSubmitInfo.pWaitDstStageMask = waitRenderMask.ptr; 856 | renderSubmitInfo.commandBufferCount = 1; 857 | renderSubmitInfo.pCommandBuffers = &vkcontext.drawCmdBuffer; 858 | renderSubmitInfo.signalSemaphoreCount = 1; 859 | renderSubmitInfo.pSignalSemaphores = &vkcontext.renderingCompleteSemaphore; 860 | vkQueueSubmit( vkcontext.presentQueue, 1, &renderSubmitInfo, null ); 861 | vkQueueWaitIdle(vkcontext.presentQueue); 862 | 863 | VkPresentInfoKHR presentInfo; 864 | presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; 865 | presentInfo.pNext = null; 866 | presentInfo.waitSemaphoreCount = 1; 867 | presentInfo.pWaitSemaphores = &vkcontext.renderingCompleteSemaphore; 868 | presentInfo.swapchainCount = 1; 869 | presentInfo.pSwapchains = &vkcontext.swapchain; 870 | presentInfo.pImageIndices = &nextImageIdx; 871 | presentInfo.pResults = null; 872 | vkQueuePresentKHR( vkcontext.presentQueue, &presentInfo ); 873 | vkQueueWaitIdle(vkcontext.presentQueue); 874 | } 875 | 876 | vkDestroyFence(vkcontext.logicalDevice, submitFence, null); 877 | 878 | vkFreeMemory(vkcontext.logicalDevice, vertexBufferMemory, null); 879 | vkDestroyBuffer(vkcontext.logicalDevice, vkcontext.vertexInputBuffer, null); 880 | vkDestroyPipeline(vkcontext.logicalDevice, vkcontext.pipeline, null); 881 | vkDestroyPipelineLayout(vkcontext.logicalDevice, vkcontext.pipelineLayout, null); 882 | vkDestroyRenderPass(vkcontext.logicalDevice, vkcontext.renderPass, null); 883 | 884 | foreach(ref framebuffer; vkcontext.frameBuffers){ 885 | vkDestroyFramebuffer(vkcontext.logicalDevice, framebuffer, null); 886 | } 887 | 888 | vkDestroyShaderModule(vkcontext.logicalDevice, fragmentShaderModule, null); 889 | vkDestroyShaderModule(vkcontext.logicalDevice, vertexShaderModule, null); 890 | 891 | vkDestroyImageView(vkcontext.logicalDevice, vkcontext.depthImageView, null); 892 | vkDestroyImage(vkcontext.logicalDevice, vkcontext.depthImage, null); 893 | vkFreeMemory(vkcontext.logicalDevice, imageMemory, null); 894 | 895 | vkFreeCommandBuffers(vkcontext.logicalDevice, commandPool, 1, &vkcontext.drawCmdBuffer); 896 | vkFreeCommandBuffers(vkcontext.logicalDevice, commandPool, 1, &vkcontext.setupCmdBuffer); 897 | vkDestroyCommandPool(vkcontext.logicalDevice, commandPool, null); 898 | 899 | foreach(ref presentImageView; presentImageViews){ 900 | vkDestroyImageView(vkcontext.logicalDevice, presentImageView, null); 901 | } 902 | 903 | vkDestroySwapchainKHR(vkcontext.logicalDevice, vkcontext.swapchain, null); 904 | 905 | vkDestroySemaphore(vkcontext.logicalDevice, vkcontext.presentCompleteSemaphore, null); 906 | vkDestroySemaphore(vkcontext.logicalDevice, vkcontext.renderingCompleteSemaphore, null); 907 | 908 | vkDestroyDevice(vkcontext.logicalDevice, null); 909 | vkDestroySurfaceKHR(vkcontext.instance, vkcontext.surface, null); 910 | vkDestroyDebugReportCallbackEXT(vkcontext.instance, callback, null); 911 | vkDestroyInstance(vkcontext.instance, null); 912 | } 913 | -------------------------------------------------------------------------------- /triangle.frag: -------------------------------------------------------------------------------- 1 | #version 400 2 | #extension GL_ARB_separate_shader_objects : enable 3 | #extension GL_ARB_shading_language_420pack : enable 4 | 5 | layout (location = 0) out vec4 uFragColor; 6 | 7 | void main() { 8 | uFragColor = vec4( 0.0, 0.5, 1.0, 1.0 ); 9 | } 10 | -------------------------------------------------------------------------------- /triangle.vert: -------------------------------------------------------------------------------- 1 | #version 400 2 | #extension GL_ARB_separate_shader_objects : enable 3 | #extension GL_ARB_shading_language_420pack : enable 4 | 5 | layout (location = 0) in vec4 pos; 6 | 7 | void main() { 8 | gl_Position = pos; 9 | } 10 | -------------------------------------------------------------------------------- /vert.spv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MaikKlein/VulkanTriangleD/a692bec19bd67cf3d1c48dce37d5e0883573e52e/vert.spv --------------------------------------------------------------------------------