blob: e90ca15dffbde92bd78e8399247a50dba9fca995 [file] [log] [blame]
Adam Sawickie6e498f2017-06-16 17:21:31 +02001//
2// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
3//
4// Permission is hereby granted, free of charge, to any person obtaining a copy
5// of this software and associated documentation files (the "Software"), to deal
6// in the Software without restriction, including without limitation the rights
7// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8// copies of the Software, and to permit persons to whom the Software is
9// furnished to do so, subject to the following conditions:
10//
11// The above copyright notice and this permission notice shall be included in
12// all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20// THE SOFTWARE.
21//
22
23#define NOMINMAX
24#define WIN32_LEAN_AND_MEAN
25#include <Windows.h>
26
27#define VK_USE_PLATFORM_WIN32_KHR
28#include <vulkan/vulkan.h>
29
Adam Sawicki86ccd632017-07-04 14:57:53 +020030#pragma warning(push, 4)
31#pragma warning(disable: 4127) // warning C4127: conditional expression is constant
Adam Sawicki08513772017-07-13 16:14:04 +020032#pragma warning(disable: 4100) // warning C4100: '...': unreferenced formal parameter
Adam Sawickie6e498f2017-06-16 17:21:31 +020033#define VMA_IMPLEMENTATION
34#include "vk_mem_alloc.h"
Adam Sawicki86ccd632017-07-04 14:57:53 +020035#pragma warning(pop)
Adam Sawickie6e498f2017-06-16 17:21:31 +020036
37#define MATHFU_COMPILE_WITHOUT_SIMD_SUPPORT
38#include <mathfu/glsl_mappings.h>
39#include <mathfu/constants.h>
40
41#include <fstream>
42#include <vector>
43#include <string>
44#include <memory>
45#include <algorithm>
46#include <numeric>
47#include <array>
48#include <type_traits>
49#include <utility>
50
51#include <cmath>
52#include <cassert>
53#include <cstdlib>
54#include <cstdio>
55
56#define ERR_GUARD_VULKAN(Expr) do { VkResult res__ = (Expr); if (res__ < 0) assert(0); } while(0)
57
58static const char* const SHADER_PATH1 = "./";
59static const char* const SHADER_PATH2 = "../bin/";
60static const wchar_t* const WINDOW_CLASS_NAME = L"VULKAN_MEMORY_ALLOCATOR_SAMPLE";
61static const char* const VALIDATION_LAYER_NAME = "VK_LAYER_LUNARG_standard_validation";
62static const char* const APP_TITLE_A = "Vulkan Memory Allocator Sample 1.0";
63static const wchar_t* const APP_TITLE_W = L"Vulkan Memory Allocator Sample 1.0";
64
65static const bool VSYNC = true;
66static const uint32_t COMMAND_BUFFER_COUNT = 2;
67
68static bool g_EnableValidationLayer = true;
69
70static HINSTANCE g_hAppInstance;
71static HWND g_hWnd;
72static LONG g_SizeX = 1280, g_SizeY = 720;
73static VkInstance g_hVulkanInstance;
74static VkSurfaceKHR g_hSurface;
75static VkPhysicalDevice g_hPhysicalDevice;
76static VkQueue g_hPresentQueue;
77static VkSurfaceFormatKHR g_SurfaceFormat;
78static VkExtent2D g_Extent;
79static VkSwapchainKHR g_hSwapchain;
80static std::vector<VkImage> g_SwapchainImages;
81static std::vector<VkImageView> g_SwapchainImageViews;
82static std::vector<VkFramebuffer> g_Framebuffers;
83static VkCommandPool g_hCommandPool;
84static VkCommandBuffer g_MainCommandBuffers[COMMAND_BUFFER_COUNT];
85static VkFence g_MainCommandBufferExecutedFances[COMMAND_BUFFER_COUNT];
86static uint32_t g_NextCommandBufferIndex;
87static VkSemaphore g_hImageAvailableSemaphore;
88static VkSemaphore g_hRenderFinishedSemaphore;
89static uint32_t g_GraphicsQueueFamilyIndex = UINT_MAX;
90static uint32_t g_PresentQueueFamilyIndex = UINT_MAX;
91static VkDescriptorSetLayout g_hDescriptorSetLayout;
92static VkDescriptorPool g_hDescriptorPool;
93static VkDescriptorSet g_hDescriptorSet; // Automatically destroyed with m_DescriptorPool.
94static VkSampler g_hSampler;
95static VkFormat g_DepthFormat;
96static VkImage g_hDepthImage;
Adam Sawicki819860e2017-07-04 14:30:38 +020097static VmaAllocation g_hDepthImageAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +020098static VkImageView g_hDepthImageView;
99
100static VkSurfaceCapabilitiesKHR g_SurfaceCapabilities;
101static std::vector<VkSurfaceFormatKHR> g_SurfaceFormats;
102static std::vector<VkPresentModeKHR> g_PresentModes;
103
104static PFN_vkCreateDebugReportCallbackEXT g_pvkCreateDebugReportCallbackEXT;
105static PFN_vkDebugReportMessageEXT g_pvkDebugReportMessageEXT;
106static PFN_vkDestroyDebugReportCallbackEXT g_pvkDestroyDebugReportCallbackEXT;
107static VkDebugReportCallbackEXT g_hCallback;
108
109static VkDevice g_hDevice;
110static VmaAllocator g_hAllocator;
111static VkQueue g_hGraphicsQueue;
112static VkCommandBuffer g_hTemporaryCommandBuffer;
113
114static VkPipelineLayout g_hPipelineLayout;
115static VkRenderPass g_hRenderPass;
116static VkPipeline g_hPipeline;
117
118static VkBuffer g_hVertexBuffer;
Adam Sawicki819860e2017-07-04 14:30:38 +0200119static VmaAllocation g_hVertexBufferAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200120static VkBuffer g_hIndexBuffer;
Adam Sawicki819860e2017-07-04 14:30:38 +0200121static VmaAllocation g_hIndexBufferAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200122static uint32_t g_VertexCount;
123static uint32_t g_IndexCount;
124
125static VkImage g_hTextureImage;
Adam Sawicki819860e2017-07-04 14:30:38 +0200126static VmaAllocation g_hTextureImageAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200127static VkImageView g_hTextureImageView;
128
129static void BeginSingleTimeCommands()
130{
131 VkCommandBufferBeginInfo cmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
132 cmdBufBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
133 ERR_GUARD_VULKAN( vkBeginCommandBuffer(g_hTemporaryCommandBuffer, &cmdBufBeginInfo) );
134}
135
136static void EndSingleTimeCommands()
137{
138 ERR_GUARD_VULKAN( vkEndCommandBuffer(g_hTemporaryCommandBuffer) );
139
140 VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO };
141 submitInfo.commandBufferCount = 1;
142 submitInfo.pCommandBuffers = &g_hTemporaryCommandBuffer;
143
144 ERR_GUARD_VULKAN( vkQueueSubmit(g_hGraphicsQueue, 1, &submitInfo, VK_NULL_HANDLE) );
145 ERR_GUARD_VULKAN( vkQueueWaitIdle(g_hGraphicsQueue) );
146}
147
148static void LoadShader(std::vector<char>& out, const char* fileName)
149{
150 std::ifstream file(std::string(SHADER_PATH1) + fileName, std::ios::ate | std::ios::binary);
151 if(file.is_open() == false)
152 file.open(std::string(SHADER_PATH2) + fileName, std::ios::ate | std::ios::binary);
153 assert(file.is_open());
154 size_t fileSize = (size_t)file.tellg();
155 if(fileSize > 0)
156 {
157 out.resize(fileSize);
158 file.seekg(0);
159 file.read(out.data(), fileSize);
160 file.close();
161 }
162 else
163 out.clear();
164}
165
166VKAPI_ATTR VkBool32 VKAPI_CALL MyDebugReportCallback(
167 VkDebugReportFlagsEXT flags,
168 VkDebugReportObjectTypeEXT objectType,
169 uint64_t object,
170 size_t location,
171 int32_t messageCode,
172 const char* pLayerPrefix,
173 const char* pMessage,
174 void* pUserData)
175{
176 printf("%s \xBA %s\n", pLayerPrefix, pMessage);
177
178 if((flags == VK_DEBUG_REPORT_WARNING_BIT_EXT) ||
179 (flags == VK_DEBUG_REPORT_ERROR_BIT_EXT))
180 {
181 OutputDebugStringA(pMessage);
182 OutputDebugStringA("\n");
183 }
184
185 return VK_FALSE;
186}
187
188static VkSurfaceFormatKHR ChooseSurfaceFormat()
189{
190 assert(!g_SurfaceFormats.empty());
191
192 if((g_SurfaceFormats.size() == 1) && (g_SurfaceFormats[0].format == VK_FORMAT_UNDEFINED))
193 {
194 VkSurfaceFormatKHR result = { VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
195 return result;
196 }
197
198 for(const auto& format : g_SurfaceFormats)
199 {
200 if((format.format == VK_FORMAT_B8G8R8A8_UNORM) &&
201 (format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR))
202 {
203 return format;
204 }
205 }
206
207 return g_SurfaceFormats[0];
208}
209
210VkPresentModeKHR ChooseSwapPresentMode()
211{
212 VkPresentModeKHR preferredMode = VSYNC ? VK_PRESENT_MODE_MAILBOX_KHR : VK_PRESENT_MODE_IMMEDIATE_KHR;
213
214 if(std::find(g_PresentModes.begin(), g_PresentModes.end(), preferredMode) !=
215 g_PresentModes.end())
216 {
217 return preferredMode;
218 }
219
220 return VK_PRESENT_MODE_FIFO_KHR;
221}
222
223static VkExtent2D ChooseSwapExtent()
224{
225 if(g_SurfaceCapabilities.currentExtent.width != UINT_MAX)
226 return g_SurfaceCapabilities.currentExtent;
227
228 VkExtent2D result = {
229 std::max(g_SurfaceCapabilities.minImageExtent.width,
230 std::min(g_SurfaceCapabilities.maxImageExtent.width, (uint32_t)g_SizeX)),
231 std::max(g_SurfaceCapabilities.minImageExtent.height,
232 std::min(g_SurfaceCapabilities.maxImageExtent.height, (uint32_t)g_SizeY)) };
233 return result;
234}
235
236struct Vertex
237{
238 float pos[3];
239 float color[3];
240 float texCoord[2];
241};
242
243static void CreateMesh()
244{
245 assert(g_hAllocator);
246
247 static Vertex vertices[] = {
248 // -X
249 { { -1.f, -1.f, -1.f}, {1.0f, 0.0f, 0.0f}, {0.f, 0.f} },
250 { { -1.f, -1.f, 1.f}, {1.0f, 0.0f, 0.0f}, {1.f, 0.f} },
251 { { -1.f, 1.f, -1.f}, {1.0f, 0.0f, 0.0f}, {0.f, 1.f} },
252 { { -1.f, 1.f, 1.f}, {1.0f, 0.0f, 0.0f}, {1.f, 1.f} },
253 // +X
254 { { 1.f, -1.f, 1.f}, {0.0f, 1.0f, 0.0f}, {0.f, 0.f} },
255 { { 1.f, -1.f, -1.f}, {0.0f, 1.0f, 0.0f}, {1.f, 0.f} },
256 { { 1.f, 1.f, 1.f}, {0.0f, 1.0f, 0.0f}, {0.f, 1.f} },
257 { { 1.f, 1.f, -1.f}, {0.0f, 1.0f, 0.0f}, {1.f, 1.f} },
258 // -Z
259 { { 1.f, -1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {0.f, 0.f} },
260 { {-1.f, -1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {1.f, 0.f} },
261 { { 1.f, 1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {0.f, 1.f} },
262 { {-1.f, 1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {1.f, 1.f} },
263 // +Z
264 { {-1.f, -1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {0.f, 0.f} },
265 { { 1.f, -1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {1.f, 0.f} },
266 { {-1.f, 1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {0.f, 1.f} },
267 { { 1.f, 1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {1.f, 1.f} },
268 // -Y
269 { {-1.f, -1.f, -1.f}, {0.0f, 1.0f, 1.0f}, {0.f, 0.f} },
270 { { 1.f, -1.f, -1.f}, {0.0f, 1.0f, 1.0f}, {1.f, 0.f} },
271 { {-1.f, -1.f, 1.f}, {0.0f, 1.0f, 1.0f}, {0.f, 1.f} },
272 { { 1.f, -1.f, 1.f}, {0.0f, 1.0f, 1.0f}, {1.f, 1.f} },
273 // +Y
274 { { 1.f, 1.f, -1.f}, {1.0f, 0.0f, 1.0f}, {0.f, 0.f} },
275 { {-1.f, 1.f, -1.f}, {1.0f, 0.0f, 1.0f}, {1.f, 0.f} },
276 { { 1.f, 1.f, 1.f}, {1.0f, 0.0f, 1.0f}, {0.f, 1.f} },
277 { {-1.f, 1.f, 1.f}, {1.0f, 0.0f, 1.0f}, {1.f, 1.f} },
278 };
279 static uint16_t indices[] = {
280 0, 1, 2, 3, USHRT_MAX,
281 4, 5, 6, 7, USHRT_MAX,
282 8, 9, 10, 11, USHRT_MAX,
283 12, 13, 14, 15, USHRT_MAX,
284 16, 17, 18, 19, USHRT_MAX,
285 20, 21, 22, 23, USHRT_MAX,
286 };
287
288 size_t vertexBufferSize = sizeof(Vertex) * _countof(vertices);
289 size_t indexBufferSize = sizeof(uint16_t) * _countof(indices);
290 g_IndexCount = (uint32_t)_countof(indices);
291
292 // Create vertex buffer
293
294 VkBufferCreateInfo vbInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
295 vbInfo.size = vertexBufferSize;
296 vbInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
297 vbInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200298
Adam Sawickie6e498f2017-06-16 17:21:31 +0200299 VmaMemoryRequirements vbMemReq = {};
Adam Sawicki2f16fa52017-07-04 14:43:20 +0200300 vbMemReq.usage = VMA_MEMORY_USAGE_CPU_ONLY;
Adam Sawicki819860e2017-07-04 14:30:38 +0200301 vbMemReq.flags = VMA_MEMORY_REQUIREMENT_PERSISTENT_MAP_BIT;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200302
Adam Sawicki819860e2017-07-04 14:30:38 +0200303 VkBuffer stagingVertexBuffer = VK_NULL_HANDLE;
304 VmaAllocation stagingVertexBufferAlloc = VK_NULL_HANDLE;
305 VmaAllocationInfo stagingVertexBufferAllocInfo = {};
306 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &vbInfo, &vbMemReq, &stagingVertexBuffer, &stagingVertexBufferAlloc, &stagingVertexBufferAllocInfo) );
307
308 memcpy(stagingVertexBufferAllocInfo.pMappedData, vertices, vertexBufferSize);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200309
Adam Sawicki2f16fa52017-07-04 14:43:20 +0200310 // No need to flush stagingVertexBuffer memory because CPU_ONLY memory is always HOST_COHERENT.
311
Adam Sawickie6e498f2017-06-16 17:21:31 +0200312 vbInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
313 vbMemReq.usage = VMA_MEMORY_USAGE_GPU_ONLY;
Adam Sawicki819860e2017-07-04 14:30:38 +0200314 vbMemReq.flags = 0;
315 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &vbInfo, &vbMemReq, &g_hVertexBuffer, &g_hVertexBufferAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200316
317 // Create index buffer
318
319 VkBufferCreateInfo ibInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
320 ibInfo.size = indexBufferSize;
321 ibInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
322 ibInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
Adam Sawicki819860e2017-07-04 14:30:38 +0200323
Adam Sawickie6e498f2017-06-16 17:21:31 +0200324 VmaMemoryRequirements ibMemReq = {};
Adam Sawicki2f16fa52017-07-04 14:43:20 +0200325 ibMemReq.usage = VMA_MEMORY_USAGE_CPU_ONLY;
Adam Sawicki819860e2017-07-04 14:30:38 +0200326 ibMemReq.flags = VMA_MEMORY_REQUIREMENT_PERSISTENT_MAP_BIT;
327
Adam Sawickie6e498f2017-06-16 17:21:31 +0200328 VkBuffer stagingIndexBuffer = VK_NULL_HANDLE;
Adam Sawicki819860e2017-07-04 14:30:38 +0200329 VmaAllocation stagingIndexBufferAlloc = VK_NULL_HANDLE;
330 VmaAllocationInfo stagingIndexBufferAllocInfo = {};
331 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &ibInfo, &ibMemReq, &stagingIndexBuffer, &stagingIndexBufferAlloc, &stagingIndexBufferAllocInfo) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200332
Adam Sawicki819860e2017-07-04 14:30:38 +0200333 memcpy(stagingIndexBufferAllocInfo.pMappedData, indices, indexBufferSize);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200334
Adam Sawicki2f16fa52017-07-04 14:43:20 +0200335 // No need to flush stagingIndexBuffer memory because CPU_ONLY memory is always HOST_COHERENT.
336
Adam Sawickie6e498f2017-06-16 17:21:31 +0200337 ibInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
338 ibMemReq.usage = VMA_MEMORY_USAGE_GPU_ONLY;
Adam Sawicki819860e2017-07-04 14:30:38 +0200339 ibMemReq.flags = 0;
340 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &ibInfo, &ibMemReq, &g_hIndexBuffer, &g_hIndexBufferAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200341
342 // Copy buffers
343
344 BeginSingleTimeCommands();
345
346 VkBufferCopy vbCopyRegion = {};
347 vbCopyRegion.srcOffset = 0;
348 vbCopyRegion.dstOffset = 0;
349 vbCopyRegion.size = vbInfo.size;
350 vkCmdCopyBuffer(g_hTemporaryCommandBuffer, stagingVertexBuffer, g_hVertexBuffer, 1, &vbCopyRegion);
351
352 VkBufferCopy ibCopyRegion = {};
353 ibCopyRegion.srcOffset = 0;
354 ibCopyRegion.dstOffset = 0;
355 ibCopyRegion.size = ibInfo.size;
356 vkCmdCopyBuffer(g_hTemporaryCommandBuffer, stagingIndexBuffer, g_hIndexBuffer, 1, &ibCopyRegion);
357
358 EndSingleTimeCommands();
359
Adam Sawicki819860e2017-07-04 14:30:38 +0200360 vmaDestroyBuffer(g_hAllocator, stagingIndexBuffer, stagingIndexBufferAlloc);
361 vmaDestroyBuffer(g_hAllocator, stagingVertexBuffer, stagingVertexBufferAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200362}
363
364static void CopyImage(VkImage srcImage, VkImage dstImage, uint32_t width, uint32_t height, uint32_t mipLevel)
365{
366 BeginSingleTimeCommands();
367
368 VkImageCopy imageCopy = {};
369 imageCopy.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
370 imageCopy.srcSubresource.baseArrayLayer = 0;
371 imageCopy.srcSubresource.mipLevel = mipLevel;
372 imageCopy.srcSubresource.layerCount = 1;
373 imageCopy.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
374 imageCopy.dstSubresource.baseArrayLayer = 0;
375 imageCopy.dstSubresource.mipLevel = mipLevel;
376 imageCopy.dstSubresource.layerCount = 1;
377 imageCopy.srcOffset.x = 0;
378 imageCopy.srcOffset.y = 0;
379 imageCopy.srcOffset.z = 0;
380 imageCopy.dstOffset.x = 0;
381 imageCopy.dstOffset.y = 0;
382 imageCopy.dstOffset.z = 0;
383 imageCopy.extent.width = width;
384 imageCopy.extent.height = height;
385 imageCopy.extent.depth = 1;
386 vkCmdCopyImage(
387 g_hTemporaryCommandBuffer,
388 srcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
389 dstImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
390 1, &imageCopy);
391
392 EndSingleTimeCommands();
393}
394
395static void TransitionImageLayout(VkImage image, VkFormat format, uint32_t mipLevelCount, VkImageLayout oldLayout, VkImageLayout newLayout)
396{
397 BeginSingleTimeCommands();
398
399 VkImageMemoryBarrier imgMemBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
400 imgMemBarrier.oldLayout = oldLayout;
401 imgMemBarrier.newLayout = newLayout;
402 imgMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
403 imgMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
404 imgMemBarrier.image = image;
405 imgMemBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
406 imgMemBarrier.subresourceRange.baseMipLevel = 0;
407 imgMemBarrier.subresourceRange.levelCount = mipLevelCount;
408 imgMemBarrier.subresourceRange.baseArrayLayer = 0;
409 imgMemBarrier.subresourceRange.layerCount = 1;
410
411 if((oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED) &&
412 (newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL))
413 {
414 imgMemBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
415 imgMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
416 }
417 else if((oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED) &&
418 (newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL))
419 {
420 imgMemBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
421 imgMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
422 }
423 else if((oldLayout == VK_IMAGE_LAYOUT_UNDEFINED) &&
424 (newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL))
425 {
426 imgMemBarrier.srcAccessMask = 0;
427 imgMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
428 }
429 else if((oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) &&
430 (newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL))
431 {
432 imgMemBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
433 imgMemBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
434 }
435 else if ((oldLayout == VK_IMAGE_LAYOUT_UNDEFINED) &&
436 (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL))
437 {
438 imgMemBarrier.srcAccessMask = 0;
439 imgMemBarrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
440 }
441 else
442 assert(0);
443
444 if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
445 {
446 imgMemBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
447 if ((format == VK_FORMAT_D16_UNORM_S8_UINT) ||
448 (format == VK_FORMAT_D24_UNORM_S8_UINT) ||
449 (format == VK_FORMAT_D32_SFLOAT_S8_UINT))
450 {
451 imgMemBarrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
452 }
453 }
454
455 vkCmdPipelineBarrier(
456 g_hTemporaryCommandBuffer,
457 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
458 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
459 0,
460 0, nullptr,
461 0, nullptr,
462 1, &imgMemBarrier);
463
464 EndSingleTimeCommands();
465}
466
467static void CreateTexture(uint32_t sizeX, uint32_t sizeY)
468{
469 // Create Image
470
471 const VkDeviceSize imageSize = sizeX * sizeY * 4;
472
473 VkImageCreateInfo stagingImageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
474 stagingImageInfo.imageType = VK_IMAGE_TYPE_2D;
475 stagingImageInfo.extent.width = sizeX;
476 stagingImageInfo.extent.height = sizeY;
477 stagingImageInfo.extent.depth = 1;
478 stagingImageInfo.mipLevels = 1;
479 stagingImageInfo.arrayLayers = 1;
480 stagingImageInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
481 stagingImageInfo.tiling = VK_IMAGE_TILING_LINEAR;
482 stagingImageInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
483 stagingImageInfo.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
484 stagingImageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
485 stagingImageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
486 stagingImageInfo.flags = 0;
Adam Sawicki819860e2017-07-04 14:30:38 +0200487
Adam Sawickie6e498f2017-06-16 17:21:31 +0200488 VmaMemoryRequirements stagingImageMemReq = {};
Adam Sawicki2f16fa52017-07-04 14:43:20 +0200489 stagingImageMemReq.usage = VMA_MEMORY_USAGE_CPU_ONLY;
Adam Sawicki819860e2017-07-04 14:30:38 +0200490 stagingImageMemReq.flags = VMA_MEMORY_REQUIREMENT_PERSISTENT_MAP_BIT;
491
Adam Sawickie6e498f2017-06-16 17:21:31 +0200492 VkImage stagingImage = VK_NULL_HANDLE;
Adam Sawicki819860e2017-07-04 14:30:38 +0200493 VmaAllocation stagingImageAlloc = VK_NULL_HANDLE;
494 VmaAllocationInfo stagingImageAllocInfo = {};
495 ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &stagingImageInfo, &stagingImageMemReq, &stagingImage, &stagingImageAlloc, &stagingImageAllocInfo) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200496
497 VkImageSubresource imageSubresource = {};
498 imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
499 imageSubresource.mipLevel = 0;
500 imageSubresource.arrayLayer = 0;
501
502 VkSubresourceLayout imageLayout = {};
503 vkGetImageSubresourceLayout(g_hDevice, stagingImage, &imageSubresource, &imageLayout);
504
Adam Sawicki819860e2017-07-04 14:30:38 +0200505 char* const pMipLevelData = (char*)stagingImageAllocInfo.pMappedData + imageLayout.offset;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200506 uint8_t* pRowData = (uint8_t*)pMipLevelData;
507 for(uint32_t y = 0; y < sizeY; ++y)
508 {
509 uint32_t* pPixelData = (uint32_t*)pRowData;
510 for(uint32_t x = 0; x < sizeY; ++x)
511 {
512 *pPixelData =
513 ((x & 0x18) == 0x08 ? 0x000000FF : 0x00000000) |
514 ((x & 0x18) == 0x10 ? 0x0000FFFF : 0x00000000) |
515 ((y & 0x18) == 0x08 ? 0x0000FF00 : 0x00000000) |
516 ((y & 0x18) == 0x10 ? 0x00FF0000 : 0x00000000);
517 ++pPixelData;
518 }
519 pRowData += imageLayout.rowPitch;
520 }
521
Adam Sawicki2f16fa52017-07-04 14:43:20 +0200522 // No need to flush stagingImage memory because CPU_ONLY memory is always HOST_COHERENT.
523
Adam Sawickie6e498f2017-06-16 17:21:31 +0200524 VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
525 imageInfo.imageType = VK_IMAGE_TYPE_2D;
526 imageInfo.extent.width = sizeX;
527 imageInfo.extent.height = sizeY;
528 imageInfo.extent.depth = 1;
529 imageInfo.mipLevels = 1;
530 imageInfo.arrayLayers = 1;
531 imageInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
532 imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
533 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
534 imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
535 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
536 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
537 imageInfo.flags = 0;
538 VmaMemoryRequirements imageMemReq = {};
539 imageMemReq.usage = VMA_MEMORY_USAGE_GPU_ONLY;
Adam Sawicki819860e2017-07-04 14:30:38 +0200540 ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &imageInfo, &imageMemReq, &g_hTextureImage, &g_hTextureImageAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200541
542 TransitionImageLayout(
543 stagingImage,
544 VK_FORMAT_R8G8B8A8_UNORM,
545 1,
546 VK_IMAGE_LAYOUT_PREINITIALIZED,
547 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
548 TransitionImageLayout(
549 g_hTextureImage,
550 VK_FORMAT_R8G8B8A8_UNORM,
551 1,
552 VK_IMAGE_LAYOUT_UNDEFINED,
553 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
554 CopyImage(stagingImage, g_hTextureImage, sizeX, sizeY, 0);
555 TransitionImageLayout(
556 g_hTextureImage,
557 VK_FORMAT_R8G8B8A8_UNORM,
558 1,
559 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
560 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
561
Adam Sawicki819860e2017-07-04 14:30:38 +0200562 vmaDestroyImage(g_hAllocator, stagingImage, stagingImageAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200563
564 // Create ImageView
565
566 VkImageViewCreateInfo textureImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
567 textureImageViewInfo.image = g_hTextureImage;
568 textureImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
569 textureImageViewInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
570 textureImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
571 textureImageViewInfo.subresourceRange.baseMipLevel = 0;
572 textureImageViewInfo.subresourceRange.levelCount = 1;
573 textureImageViewInfo.subresourceRange.baseArrayLayer = 0;
574 textureImageViewInfo.subresourceRange.layerCount = 1;
575 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &textureImageViewInfo, nullptr, &g_hTextureImageView) );
576}
577
578struct UniformBufferObject
579{
580 mathfu::vec4_packed ModelViewProj[4];
581};
582
583static void RegisterDebugCallbacks()
584{
585 g_pvkCreateDebugReportCallbackEXT =
586 reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>
587 (vkGetInstanceProcAddr(g_hVulkanInstance, "vkCreateDebugReportCallbackEXT"));
588 g_pvkDebugReportMessageEXT =
589 reinterpret_cast<PFN_vkDebugReportMessageEXT>
590 (vkGetInstanceProcAddr(g_hVulkanInstance, "vkDebugReportMessageEXT"));
591 g_pvkDestroyDebugReportCallbackEXT =
592 reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>
593 (vkGetInstanceProcAddr(g_hVulkanInstance, "vkDestroyDebugReportCallbackEXT"));
594 assert(g_pvkCreateDebugReportCallbackEXT);
595 assert(g_pvkDebugReportMessageEXT);
596 assert(g_pvkDestroyDebugReportCallbackEXT);
597
598 VkDebugReportCallbackCreateInfoEXT callbackCreateInfo;
599 callbackCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
600 callbackCreateInfo.pNext = nullptr;
601 callbackCreateInfo.flags = //VK_DEBUG_REPORT_INFORMATION_BIT_EXT |
602 VK_DEBUG_REPORT_ERROR_BIT_EXT |
603 VK_DEBUG_REPORT_WARNING_BIT_EXT |
604 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT /*|
605 VK_DEBUG_REPORT_DEBUG_BIT_EXT*/;
606 callbackCreateInfo.pfnCallback = &MyDebugReportCallback;
607 callbackCreateInfo.pUserData = nullptr;
608
609 ERR_GUARD_VULKAN( g_pvkCreateDebugReportCallbackEXT(g_hVulkanInstance, &callbackCreateInfo, nullptr, &g_hCallback) );
610}
611
612static bool IsLayerSupported(const VkLayerProperties* pProps, size_t propCount, const char* pLayerName)
613{
614 const VkLayerProperties* propsEnd = pProps + propCount;
615 return std::find_if(
616 pProps,
617 propsEnd,
618 [pLayerName](const VkLayerProperties& prop) -> bool {
619 return strcmp(pLayerName, prop.layerName) == 0;
620 }) != propsEnd;
621}
622
623static VkFormat FindSupportedFormat(
624 const std::vector<VkFormat>& candidates,
625 VkImageTiling tiling,
626 VkFormatFeatureFlags features)
627{
628 for (VkFormat format : candidates)
629 {
630 VkFormatProperties props;
631 vkGetPhysicalDeviceFormatProperties(g_hPhysicalDevice, format, &props);
632
633 if ((tiling == VK_IMAGE_TILING_LINEAR) &&
634 ((props.linearTilingFeatures & features) == features))
635 {
636 return format;
637 }
638 else if ((tiling == VK_IMAGE_TILING_OPTIMAL) &&
639 ((props.optimalTilingFeatures & features) == features))
640 {
641 return format;
642 }
643 }
644 return VK_FORMAT_UNDEFINED;
645}
646
647static VkFormat FindDepthFormat()
648{
649 std::vector<VkFormat> formats;
650 formats.push_back(VK_FORMAT_D32_SFLOAT);
651 formats.push_back(VK_FORMAT_D32_SFLOAT_S8_UINT);
652 formats.push_back(VK_FORMAT_D24_UNORM_S8_UINT);
653
654 return FindSupportedFormat(
655 formats,
656 VK_IMAGE_TILING_OPTIMAL,
657 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT);
658}
659
660static void CreateSwapchain()
661{
662 // Query surface formats.
663
664 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceCapabilitiesKHR(g_hPhysicalDevice, g_hSurface, &g_SurfaceCapabilities) );
665
666 uint32_t formatCount = 0;
667 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceFormatsKHR(g_hPhysicalDevice, g_hSurface, &formatCount, nullptr) );
668 g_SurfaceFormats.resize(formatCount);
669 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceFormatsKHR(g_hPhysicalDevice, g_hSurface, &formatCount, g_SurfaceFormats.data()) );
670
671 uint32_t presentModeCount = 0;
672 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfacePresentModesKHR(g_hPhysicalDevice, g_hSurface, &presentModeCount, nullptr) );
673 g_PresentModes.resize(presentModeCount);
674 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfacePresentModesKHR(g_hPhysicalDevice, g_hSurface, &presentModeCount, g_PresentModes.data()) );
675
676 // Create swap chain
677
678 g_SurfaceFormat = ChooseSurfaceFormat();
679 VkPresentModeKHR presentMode = ChooseSwapPresentMode();
680 g_Extent = ChooseSwapExtent();
681
682 uint32_t imageCount = g_SurfaceCapabilities.minImageCount + 1;
683 if((g_SurfaceCapabilities.maxImageCount > 0) &&
684 (imageCount > g_SurfaceCapabilities.maxImageCount))
685 {
686 imageCount = g_SurfaceCapabilities.maxImageCount;
687 }
688
689 VkSwapchainCreateInfoKHR swapChainInfo = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
690 swapChainInfo.surface = g_hSurface;
691 swapChainInfo.minImageCount = imageCount;
692 swapChainInfo.imageFormat = g_SurfaceFormat.format;
693 swapChainInfo.imageColorSpace = g_SurfaceFormat.colorSpace;
694 swapChainInfo.imageExtent = g_Extent;
695 swapChainInfo.imageArrayLayers = 1;
696 swapChainInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
697 swapChainInfo.preTransform = g_SurfaceCapabilities.currentTransform;
698 swapChainInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
699 swapChainInfo.presentMode = presentMode;
700 swapChainInfo.clipped = VK_TRUE;
701 swapChainInfo.oldSwapchain = g_hSwapchain;
702
703 uint32_t queueFamilyIndices[] = { g_GraphicsQueueFamilyIndex, g_PresentQueueFamilyIndex };
704 if(g_PresentQueueFamilyIndex != g_GraphicsQueueFamilyIndex)
705 {
706 swapChainInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
707 swapChainInfo.queueFamilyIndexCount = 2;
708 swapChainInfo.pQueueFamilyIndices = queueFamilyIndices;
709 }
710 else
711 {
712 swapChainInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
713 }
714
715 VkSwapchainKHR hNewSwapchain = VK_NULL_HANDLE;
716 ERR_GUARD_VULKAN( vkCreateSwapchainKHR(g_hDevice, &swapChainInfo, nullptr, &hNewSwapchain) );
717 if(g_hSwapchain != VK_NULL_HANDLE)
718 vkDestroySwapchainKHR(g_hDevice, g_hSwapchain, nullptr);
719 g_hSwapchain = hNewSwapchain;
720
721 // Retrieve swapchain images.
722
723 uint32_t swapchainImageCount = 0;
724 ERR_GUARD_VULKAN( vkGetSwapchainImagesKHR(g_hDevice, g_hSwapchain, &swapchainImageCount, nullptr) );
725 g_SwapchainImages.resize(swapchainImageCount);
726 ERR_GUARD_VULKAN( vkGetSwapchainImagesKHR(g_hDevice, g_hSwapchain, &swapchainImageCount, g_SwapchainImages.data()) );
727
728 // Create swapchain image views.
729
730 for(size_t i = g_SwapchainImageViews.size(); i--; )
731 vkDestroyImageView(g_hDevice, g_SwapchainImageViews[i], nullptr);
732 g_SwapchainImageViews.clear();
733
734 VkImageViewCreateInfo swapchainImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
735 g_SwapchainImageViews.resize(swapchainImageCount);
736 for(uint32_t i = 0; i < swapchainImageCount; ++i)
737 {
738 swapchainImageViewInfo.image = g_SwapchainImages[i];
739 swapchainImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
740 swapchainImageViewInfo.format = g_SurfaceFormat.format;
741 swapchainImageViewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
742 swapchainImageViewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
743 swapchainImageViewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
744 swapchainImageViewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
745 swapchainImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
746 swapchainImageViewInfo.subresourceRange.baseMipLevel = 0;
747 swapchainImageViewInfo.subresourceRange.levelCount = 1;
748 swapchainImageViewInfo.subresourceRange.baseArrayLayer = 0;
749 swapchainImageViewInfo.subresourceRange.layerCount = 1;
750 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &swapchainImageViewInfo, nullptr, &g_SwapchainImageViews[i]) );
751 }
752
753 // Create depth buffer
754
755 g_DepthFormat = FindDepthFormat();
756 assert(g_DepthFormat != VK_FORMAT_UNDEFINED);
757
758 VkImageCreateInfo depthImageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
759 depthImageInfo.imageType = VK_IMAGE_TYPE_2D;
760 depthImageInfo.extent.width = g_Extent.width;
761 depthImageInfo.extent.height = g_Extent.height;
762 depthImageInfo.extent.depth = 1;
763 depthImageInfo.mipLevels = 1;
764 depthImageInfo.arrayLayers = 1;
765 depthImageInfo.format = g_DepthFormat;
766 depthImageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
767 depthImageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
768 depthImageInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
769 depthImageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
770 depthImageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
771 depthImageInfo.flags = 0;
772
773 VmaMemoryRequirements depthImageMemReq = {};
774 depthImageMemReq.usage = VMA_MEMORY_USAGE_GPU_ONLY;
775
Adam Sawicki819860e2017-07-04 14:30:38 +0200776 ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &depthImageInfo, &depthImageMemReq, &g_hDepthImage, &g_hDepthImageAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200777
778 VkImageViewCreateInfo depthImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
779 depthImageViewInfo.image = g_hDepthImage;
780 depthImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
781 depthImageViewInfo.format = g_DepthFormat;
782 depthImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
783 depthImageViewInfo.subresourceRange.baseMipLevel = 0;
784 depthImageViewInfo.subresourceRange.levelCount = 1;
785 depthImageViewInfo.subresourceRange.baseArrayLayer = 0;
786 depthImageViewInfo.subresourceRange.layerCount = 1;
787
788 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &depthImageViewInfo, nullptr, &g_hDepthImageView) );
789
790 TransitionImageLayout(
791 g_hDepthImage,
792 g_DepthFormat,
793 1,
794 VK_IMAGE_LAYOUT_UNDEFINED,
795 VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
796
797 // Create pipeline layout
798 {
799 if(g_hPipelineLayout != VK_NULL_HANDLE)
800 {
801 vkDestroyPipelineLayout(g_hDevice, g_hPipelineLayout, nullptr);
802 g_hPipelineLayout = VK_NULL_HANDLE;
803 }
804
805 VkPushConstantRange pushConstantRanges[1];
806 ZeroMemory(&pushConstantRanges, sizeof pushConstantRanges);
807 pushConstantRanges[0].offset = 0;
808 pushConstantRanges[0].size = sizeof(UniformBufferObject);
809 pushConstantRanges[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
810
811 VkDescriptorSetLayout descriptorSetLayouts[] = { g_hDescriptorSetLayout };
812 VkPipelineLayoutCreateInfo pipelineLayoutInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
813 pipelineLayoutInfo.setLayoutCount = 1;
814 pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts;
815 pipelineLayoutInfo.pushConstantRangeCount = 1;
816 pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges;
817 ERR_GUARD_VULKAN( vkCreatePipelineLayout(g_hDevice, &pipelineLayoutInfo, nullptr, &g_hPipelineLayout) );
818 }
819
820 // Create render pass
821 {
822 if(g_hRenderPass != VK_NULL_HANDLE)
823 {
824 vkDestroyRenderPass(g_hDevice, g_hRenderPass, nullptr);
825 g_hRenderPass = VK_NULL_HANDLE;
826 }
827
828 VkAttachmentDescription attachments[2];
829 ZeroMemory(attachments, sizeof(attachments));
830
831 attachments[0].format = g_SurfaceFormat.format;
832 attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
833 attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
834 attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
835 attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
836 attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
837 attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
838 attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
839
840 attachments[1].format = g_DepthFormat;
841 attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
842 attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
843 attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
844 attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
845 attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
846 attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
847 attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
848
849 VkAttachmentReference colorAttachmentRef = {};
850 colorAttachmentRef.attachment = 0;
851 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
852
853 VkAttachmentReference depthStencilAttachmentRef = {};
854 depthStencilAttachmentRef.attachment = 1;
855 depthStencilAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
856
857 VkSubpassDescription subpassDesc = {};
858 subpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
859 subpassDesc.colorAttachmentCount = 1;
860 subpassDesc.pColorAttachments = &colorAttachmentRef;
861 subpassDesc.pDepthStencilAttachment = &depthStencilAttachmentRef;
862
863 VkSubpassDependency subpassDependency = {};
864 subpassDependency.srcSubpass = VK_SUBPASS_EXTERNAL;
865 subpassDependency.dstSubpass = 0;
866 subpassDependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
867 subpassDependency.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
868 subpassDependency.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
869 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
870 subpassDependency.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
871 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
872
873 VkRenderPassCreateInfo renderPassInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO };
874 renderPassInfo.attachmentCount = (uint32_t)_countof(attachments);
875 renderPassInfo.pAttachments = attachments;
876 renderPassInfo.subpassCount = 1;
877 renderPassInfo.pSubpasses = &subpassDesc;
878 renderPassInfo.dependencyCount = 1;
879 renderPassInfo.pDependencies = &subpassDependency;
880 ERR_GUARD_VULKAN( vkCreateRenderPass(g_hDevice, &renderPassInfo, nullptr, &g_hRenderPass) );
881 }
882
883 // Create pipeline
884 {
885 std::vector<char> vertShaderCode;
886 LoadShader(vertShaderCode, "Shader.vert.spv");
887 VkShaderModuleCreateInfo shaderModuleInfo = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
888 shaderModuleInfo.codeSize = vertShaderCode.size();
889 shaderModuleInfo.pCode = (const uint32_t*)vertShaderCode.data();
890 VkShaderModule hVertShaderModule = VK_NULL_HANDLE;
891 ERR_GUARD_VULKAN( vkCreateShaderModule(g_hDevice, &shaderModuleInfo, nullptr, &hVertShaderModule) );
892
893 std::vector<char> hFragShaderCode;
894 LoadShader(hFragShaderCode, "Shader.frag.spv");
895 shaderModuleInfo.codeSize = hFragShaderCode.size();
896 shaderModuleInfo.pCode = (const uint32_t*)hFragShaderCode.data();
897 VkShaderModule fragShaderModule = VK_NULL_HANDLE;
898 ERR_GUARD_VULKAN( vkCreateShaderModule(g_hDevice, &shaderModuleInfo, nullptr, &fragShaderModule) );
899
900 VkPipelineShaderStageCreateInfo vertPipelineShaderStageInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
901 vertPipelineShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
902 vertPipelineShaderStageInfo.module = hVertShaderModule;
903 vertPipelineShaderStageInfo.pName = "main";
904
905 VkPipelineShaderStageCreateInfo fragPipelineShaderStageInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
906 fragPipelineShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
907 fragPipelineShaderStageInfo.module = fragShaderModule;
908 fragPipelineShaderStageInfo.pName = "main";
909
910 VkPipelineShaderStageCreateInfo pipelineShaderStageInfos[] = {
911 vertPipelineShaderStageInfo,
912 fragPipelineShaderStageInfo
913 };
914
915 VkVertexInputBindingDescription bindingDescription = {};
916 bindingDescription.binding = 0;
917 bindingDescription.stride = sizeof(Vertex);
918 bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
919
920 VkVertexInputAttributeDescription attributeDescriptions[3];
921 ZeroMemory(attributeDescriptions, sizeof(attributeDescriptions));
922
923 attributeDescriptions[0].binding = 0;
924 attributeDescriptions[0].location = 0;
925 attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
926 attributeDescriptions[0].offset = offsetof(Vertex, pos);
927
928 attributeDescriptions[1].binding = 0;
929 attributeDescriptions[1].location = 1;
930 attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
931 attributeDescriptions[1].offset = offsetof(Vertex, color);
932
933 attributeDescriptions[2].binding = 0;
934 attributeDescriptions[2].location = 2;
935 attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
936 attributeDescriptions[2].offset = offsetof(Vertex, texCoord);
937
938 VkPipelineVertexInputStateCreateInfo pipelineVertexInputStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO };
939 pipelineVertexInputStateInfo.vertexBindingDescriptionCount = 1;
940 pipelineVertexInputStateInfo.pVertexBindingDescriptions = &bindingDescription;
941 pipelineVertexInputStateInfo.vertexAttributeDescriptionCount = _countof(attributeDescriptions);
942 pipelineVertexInputStateInfo.pVertexAttributeDescriptions = attributeDescriptions;
943
944 VkPipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO };
945 pipelineInputAssemblyStateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
946 pipelineInputAssemblyStateInfo.primitiveRestartEnable = VK_TRUE;
947
948 VkViewport viewport = {};
949 viewport.x = 0.f;
950 viewport.y = 0.f;
951 viewport.width = (float)g_Extent.width;
952 viewport.height = (float)g_Extent.height;
953 viewport.minDepth = 0.f;
954 viewport.maxDepth = 1.f;
955
956 VkRect2D scissor = {};
957 scissor.offset.x = 0;
958 scissor.offset.y = 0;
959 scissor.extent = g_Extent;
960
961 VkPipelineViewportStateCreateInfo pipelineViewportStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO };
962 pipelineViewportStateInfo.viewportCount = 1;
963 pipelineViewportStateInfo.pViewports = &viewport;
964 pipelineViewportStateInfo.scissorCount = 1;
965 pipelineViewportStateInfo.pScissors = &scissor;
966
967 VkPipelineRasterizationStateCreateInfo pipelineRasterizationStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO };
968 pipelineRasterizationStateInfo.depthClampEnable = VK_FALSE;
969 pipelineRasterizationStateInfo.rasterizerDiscardEnable = VK_FALSE;
970 pipelineRasterizationStateInfo.polygonMode = VK_POLYGON_MODE_FILL;
971 pipelineRasterizationStateInfo.lineWidth = 1.f;
972 pipelineRasterizationStateInfo.cullMode = VK_CULL_MODE_BACK_BIT;
973 pipelineRasterizationStateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
974 pipelineRasterizationStateInfo.depthBiasEnable = VK_FALSE;
975 pipelineRasterizationStateInfo.depthBiasConstantFactor = 0.f;
976 pipelineRasterizationStateInfo.depthBiasClamp = 0.f;
977 pipelineRasterizationStateInfo.depthBiasSlopeFactor = 0.f;
978
979 VkPipelineMultisampleStateCreateInfo pipelineMultisampleStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO };
980 pipelineMultisampleStateInfo.sampleShadingEnable = VK_FALSE;
981 pipelineMultisampleStateInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
982 pipelineMultisampleStateInfo.minSampleShading = 1.f;
983 pipelineMultisampleStateInfo.pSampleMask = nullptr;
984 pipelineMultisampleStateInfo.alphaToCoverageEnable = VK_FALSE;
985 pipelineMultisampleStateInfo.alphaToOneEnable = VK_FALSE;
986
987 VkPipelineColorBlendAttachmentState pipelineColorBlendAttachmentState = {};
988 pipelineColorBlendAttachmentState.colorWriteMask =
989 VK_COLOR_COMPONENT_R_BIT |
990 VK_COLOR_COMPONENT_G_BIT |
991 VK_COLOR_COMPONENT_B_BIT |
992 VK_COLOR_COMPONENT_A_BIT;
993 pipelineColorBlendAttachmentState.blendEnable = VK_FALSE;
994 pipelineColorBlendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
995 pipelineColorBlendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
996 pipelineColorBlendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; // Optional
997 pipelineColorBlendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
998 pipelineColorBlendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
999 pipelineColorBlendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; // Optional
1000
1001 VkPipelineColorBlendStateCreateInfo pipelineColorBlendStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO };
1002 pipelineColorBlendStateInfo.logicOpEnable = VK_FALSE;
1003 pipelineColorBlendStateInfo.logicOp = VK_LOGIC_OP_COPY;
1004 pipelineColorBlendStateInfo.attachmentCount = 1;
1005 pipelineColorBlendStateInfo.pAttachments = &pipelineColorBlendAttachmentState;
1006
1007 VkPipelineDepthStencilStateCreateInfo depthStencilStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO };
1008 depthStencilStateInfo.depthTestEnable = VK_TRUE;
1009 depthStencilStateInfo.depthWriteEnable = VK_TRUE;
1010 depthStencilStateInfo.depthCompareOp = VK_COMPARE_OP_LESS;
1011 depthStencilStateInfo.depthBoundsTestEnable = VK_FALSE;
1012 depthStencilStateInfo.stencilTestEnable = VK_FALSE;
1013
1014 VkGraphicsPipelineCreateInfo pipelineInfo = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO };
1015 pipelineInfo.stageCount = 2;
1016 pipelineInfo.pStages = pipelineShaderStageInfos;
1017 pipelineInfo.pVertexInputState = &pipelineVertexInputStateInfo;
1018 pipelineInfo.pInputAssemblyState = &pipelineInputAssemblyStateInfo;
1019 pipelineInfo.pViewportState = &pipelineViewportStateInfo;
1020 pipelineInfo.pRasterizationState = &pipelineRasterizationStateInfo;
1021 pipelineInfo.pMultisampleState = &pipelineMultisampleStateInfo;
1022 pipelineInfo.pDepthStencilState = &depthStencilStateInfo;
1023 pipelineInfo.pColorBlendState = &pipelineColorBlendStateInfo;
1024 pipelineInfo.pDynamicState = nullptr;
1025 pipelineInfo.layout = g_hPipelineLayout;
1026 pipelineInfo.renderPass = g_hRenderPass;
1027 pipelineInfo.subpass = 0;
1028 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
1029 pipelineInfo.basePipelineIndex = -1;
1030 ERR_GUARD_VULKAN( vkCreateGraphicsPipelines(
1031 g_hDevice,
1032 VK_NULL_HANDLE,
1033 1,
1034 &pipelineInfo, nullptr,
1035 &g_hPipeline) );
1036
1037 vkDestroyShaderModule(g_hDevice, fragShaderModule, nullptr);
1038 vkDestroyShaderModule(g_hDevice, hVertShaderModule, nullptr);
1039 }
1040
1041 // Create frambuffers
1042
1043 for(size_t i = g_Framebuffers.size(); i--; )
1044 vkDestroyFramebuffer(g_hDevice, g_Framebuffers[i], nullptr);
1045 g_Framebuffers.clear();
1046
1047 g_Framebuffers.resize(g_SwapchainImageViews.size());
1048 for(size_t i = 0; i < g_SwapchainImages.size(); ++i)
1049 {
1050 VkImageView attachments[] = { g_SwapchainImageViews[i], g_hDepthImageView };
1051
1052 VkFramebufferCreateInfo framebufferInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
1053 framebufferInfo.renderPass = g_hRenderPass;
1054 framebufferInfo.attachmentCount = (uint32_t)_countof(attachments);
1055 framebufferInfo.pAttachments = attachments;
1056 framebufferInfo.width = g_Extent.width;
1057 framebufferInfo.height = g_Extent.height;
1058 framebufferInfo.layers = 1;
1059 ERR_GUARD_VULKAN( vkCreateFramebuffer(g_hDevice, &framebufferInfo, nullptr, &g_Framebuffers[i]) );
1060 }
1061
1062 // Create semaphores
1063
1064 if(g_hImageAvailableSemaphore != VK_NULL_HANDLE)
1065 {
1066 vkDestroySemaphore(g_hDevice, g_hImageAvailableSemaphore, nullptr);
1067 g_hImageAvailableSemaphore = VK_NULL_HANDLE;
1068 }
1069 if(g_hRenderFinishedSemaphore != VK_NULL_HANDLE)
1070 {
1071 vkDestroySemaphore(g_hDevice, g_hRenderFinishedSemaphore, nullptr);
1072 g_hRenderFinishedSemaphore = VK_NULL_HANDLE;
1073 }
1074
1075 VkSemaphoreCreateInfo semaphoreInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
1076 ERR_GUARD_VULKAN( vkCreateSemaphore(g_hDevice, &semaphoreInfo, nullptr, &g_hImageAvailableSemaphore) );
1077 ERR_GUARD_VULKAN( vkCreateSemaphore(g_hDevice, &semaphoreInfo, nullptr, &g_hRenderFinishedSemaphore) );
1078}
1079
1080static void DestroySwapchain(bool destroyActualSwapchain)
1081{
1082 if(g_hImageAvailableSemaphore != VK_NULL_HANDLE)
1083 {
1084 vkDestroySemaphore(g_hDevice, g_hImageAvailableSemaphore, nullptr);
1085 g_hImageAvailableSemaphore = VK_NULL_HANDLE;
1086 }
1087 if(g_hRenderFinishedSemaphore != VK_NULL_HANDLE)
1088 {
1089 vkDestroySemaphore(g_hDevice, g_hRenderFinishedSemaphore, nullptr);
1090 g_hRenderFinishedSemaphore = VK_NULL_HANDLE;
1091 }
1092
1093 for(size_t i = g_Framebuffers.size(); i--; )
1094 vkDestroyFramebuffer(g_hDevice, g_Framebuffers[i], nullptr);
1095 g_Framebuffers.clear();
1096
1097 if(g_hDepthImageView != VK_NULL_HANDLE)
1098 {
1099 vkDestroyImageView(g_hDevice, g_hDepthImageView, nullptr);
1100 g_hDepthImageView = VK_NULL_HANDLE;
1101 }
1102 if(g_hDepthImage != VK_NULL_HANDLE)
1103 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001104 vmaDestroyImage(g_hAllocator, g_hDepthImage, g_hDepthImageAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001105 g_hDepthImage = VK_NULL_HANDLE;
1106 }
1107
1108 if(g_hPipeline != VK_NULL_HANDLE)
1109 {
1110 vkDestroyPipeline(g_hDevice, g_hPipeline, nullptr);
1111 g_hPipeline = VK_NULL_HANDLE;
1112 }
1113
1114 if(g_hRenderPass != VK_NULL_HANDLE)
1115 {
1116 vkDestroyRenderPass(g_hDevice, g_hRenderPass, nullptr);
1117 g_hRenderPass = VK_NULL_HANDLE;
1118 }
1119
1120 if(g_hPipelineLayout != VK_NULL_HANDLE)
1121 {
1122 vkDestroyPipelineLayout(g_hDevice, g_hPipelineLayout, nullptr);
1123 g_hPipelineLayout = VK_NULL_HANDLE;
1124 }
1125
1126 for(size_t i = g_SwapchainImageViews.size(); i--; )
1127 vkDestroyImageView(g_hDevice, g_SwapchainImageViews[i], nullptr);
1128 g_SwapchainImageViews.clear();
1129
1130 if(destroyActualSwapchain && (g_hSwapchain != VK_NULL_HANDLE))
1131 {
1132 vkDestroySwapchainKHR(g_hDevice, g_hSwapchain, nullptr);
1133 g_hSwapchain = VK_NULL_HANDLE;
1134 }
1135}
1136
1137static void InitializeApplication()
1138{
1139 uint32_t instanceLayerPropCount = 0;
1140 ERR_GUARD_VULKAN( vkEnumerateInstanceLayerProperties(&instanceLayerPropCount, nullptr) );
1141 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerPropCount);
1142 if(instanceLayerPropCount > 0)
1143 {
1144 ERR_GUARD_VULKAN( vkEnumerateInstanceLayerProperties(&instanceLayerPropCount, instanceLayerProps.data()) );
1145 }
1146
1147 if(g_EnableValidationLayer == true)
1148 {
1149 if(IsLayerSupported(instanceLayerProps.data(), instanceLayerProps.size(), VALIDATION_LAYER_NAME) == false)
1150 {
1151 printf("Layer \"%s\" not supported.", VALIDATION_LAYER_NAME);
1152 g_EnableValidationLayer = false;
1153 }
1154 }
1155
1156 std::vector<const char*> instanceExtensions;
1157 instanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
1158 instanceExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
1159
1160 std::vector<const char*> instanceLayers;
1161 if(g_EnableValidationLayer == true)
1162 {
1163 instanceLayers.push_back(VALIDATION_LAYER_NAME);
1164 instanceExtensions.push_back("VK_EXT_debug_report");
1165 }
1166
1167 VkApplicationInfo appInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO };
1168 appInfo.pApplicationName = APP_TITLE_A;
1169 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
1170 appInfo.pEngineName = "Adam Sawicki Engine";
1171 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
1172 appInfo.apiVersion = VK_API_VERSION_1_0;
1173
1174 VkInstanceCreateInfo instInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
1175 instInfo.pApplicationInfo = &appInfo;
1176 instInfo.enabledExtensionCount = static_cast<uint32_t>(instanceExtensions.size());
1177 instInfo.ppEnabledExtensionNames = instanceExtensions.data();
1178 instInfo.enabledLayerCount = static_cast<uint32_t>(instanceLayers.size());
1179 instInfo.ppEnabledLayerNames = instanceLayers.data();
1180
1181 ERR_GUARD_VULKAN( vkCreateInstance(&instInfo, NULL, &g_hVulkanInstance) );
1182
1183 // Create VkSurfaceKHR.
1184 VkWin32SurfaceCreateInfoKHR surfaceInfo = { VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR };
1185 surfaceInfo.hinstance = g_hAppInstance;
1186 surfaceInfo.hwnd = g_hWnd;
1187 VkResult result = vkCreateWin32SurfaceKHR(g_hVulkanInstance, &surfaceInfo, NULL, &g_hSurface);
1188 assert(result == VK_SUCCESS);
1189
1190 if(g_EnableValidationLayer == true)
1191 RegisterDebugCallbacks();
1192
1193 // Find physical device
1194
1195 uint32_t deviceCount = 0;
1196 ERR_GUARD_VULKAN( vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, nullptr) );
1197 assert(deviceCount > 0);
1198
1199 std::vector<VkPhysicalDevice> physicalDevices(deviceCount);
1200 ERR_GUARD_VULKAN( vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, physicalDevices.data()) );
1201
1202 g_hPhysicalDevice = physicalDevices[0];
1203
1204 // Query for features
1205
1206 VkPhysicalDeviceProperties physicalDeviceProperties = {};
1207 vkGetPhysicalDeviceProperties(g_hPhysicalDevice, &physicalDeviceProperties);
1208
1209 //VkPhysicalDeviceFeatures physicalDeviceFreatures = {};
1210 //vkGetPhysicalDeviceFeatures(g_PhysicalDevice, &physicalDeviceFreatures);
1211
1212 // Find queue family index
1213
1214 uint32_t queueFamilyCount = 0;
1215 vkGetPhysicalDeviceQueueFamilyProperties(g_hPhysicalDevice, &queueFamilyCount, nullptr);
1216 assert(queueFamilyCount > 0);
1217 std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
1218 vkGetPhysicalDeviceQueueFamilyProperties(g_hPhysicalDevice, &queueFamilyCount, queueFamilies.data());
1219 for(uint32_t i = 0;
1220 (i < queueFamilyCount) &&
1221 (g_GraphicsQueueFamilyIndex == UINT_MAX || g_PresentQueueFamilyIndex == UINT_MAX);
1222 ++i)
1223 {
1224 if(queueFamilies[i].queueCount > 0)
1225 {
1226 if((g_GraphicsQueueFamilyIndex != 0) &&
1227 ((queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0))
1228 {
1229 g_GraphicsQueueFamilyIndex = i;
1230 }
1231
1232 VkBool32 surfaceSupported = 0;
1233 VkResult res = vkGetPhysicalDeviceSurfaceSupportKHR(g_hPhysicalDevice, i, g_hSurface, &surfaceSupported);
1234 if((res >= 0) && (surfaceSupported == VK_TRUE))
1235 {
1236 g_PresentQueueFamilyIndex = i;
1237 }
1238 }
1239 }
1240 assert(g_GraphicsQueueFamilyIndex != UINT_MAX);
1241
1242 // Create logical device
1243
1244 const float queuePriority = 1.f;
1245
1246 VkDeviceQueueCreateInfo deviceQueueCreateInfo[2] = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
1247 deviceQueueCreateInfo[0].queueFamilyIndex = g_GraphicsQueueFamilyIndex;
1248 deviceQueueCreateInfo[0].queueCount = 1;
1249 deviceQueueCreateInfo[0].pQueuePriorities = &queuePriority;
1250 deviceQueueCreateInfo[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
1251 deviceQueueCreateInfo[1].queueFamilyIndex = g_PresentQueueFamilyIndex;
1252 deviceQueueCreateInfo[1].queueCount = 1;
1253 deviceQueueCreateInfo[1].pQueuePriorities = &queuePriority;
1254
1255 VkPhysicalDeviceFeatures deviceFeatures = {};
1256 deviceFeatures.fillModeNonSolid = VK_TRUE;
1257 deviceFeatures.samplerAnisotropy = VK_TRUE;
1258
1259 std::vector<const char*> enabledDeviceExtensions;
1260 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
1261
1262 VkDeviceCreateInfo deviceCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
1263 deviceCreateInfo.enabledLayerCount = 0;
1264 deviceCreateInfo.ppEnabledLayerNames = nullptr;
1265 deviceCreateInfo.enabledExtensionCount = (uint32_t)enabledDeviceExtensions.size();
1266 deviceCreateInfo.ppEnabledExtensionNames = enabledDeviceExtensions.data();
1267 deviceCreateInfo.queueCreateInfoCount = g_PresentQueueFamilyIndex != g_GraphicsQueueFamilyIndex ? 2 : 1;
1268 deviceCreateInfo.pQueueCreateInfos = deviceQueueCreateInfo;
1269 deviceCreateInfo.pEnabledFeatures = &deviceFeatures;
1270
1271 ERR_GUARD_VULKAN( vkCreateDevice(g_hPhysicalDevice, &deviceCreateInfo, nullptr, &g_hDevice) );
1272
1273 // Create memory allocator
1274
1275 VmaAllocatorCreateInfo allocatorInfo = {};
1276 allocatorInfo.physicalDevice = g_hPhysicalDevice;
1277 allocatorInfo.device = g_hDevice;
1278 ERR_GUARD_VULKAN( vmaCreateAllocator(&allocatorInfo, &g_hAllocator) );
1279
1280 // Retrieve queue (doesn't need to be destroyed)
1281
1282 vkGetDeviceQueue(g_hDevice, g_GraphicsQueueFamilyIndex, 0, &g_hGraphicsQueue);
1283 vkGetDeviceQueue(g_hDevice, g_PresentQueueFamilyIndex, 0, &g_hPresentQueue);
1284 assert(g_hGraphicsQueue);
1285 assert(g_hPresentQueue);
1286
1287 // Create command pool
1288
1289 VkCommandPoolCreateInfo commandPoolInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
1290 commandPoolInfo.queueFamilyIndex = g_GraphicsQueueFamilyIndex;
1291 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
1292 ERR_GUARD_VULKAN( vkCreateCommandPool(g_hDevice, &commandPoolInfo, nullptr, &g_hCommandPool) );
1293
1294 VkCommandBufferAllocateInfo commandBufferInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
1295 commandBufferInfo.commandPool = g_hCommandPool;
1296 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1297 commandBufferInfo.commandBufferCount = COMMAND_BUFFER_COUNT;
1298 ERR_GUARD_VULKAN( vkAllocateCommandBuffers(g_hDevice, &commandBufferInfo, g_MainCommandBuffers) );
1299
1300 VkFenceCreateInfo fenceInfo = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
1301 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
1302 for(size_t i = 0; i < COMMAND_BUFFER_COUNT; ++i)
1303 {
1304 ERR_GUARD_VULKAN( vkCreateFence(g_hDevice, &fenceInfo, nullptr, &g_MainCommandBufferExecutedFances[i]) );
1305 }
1306
1307 commandBufferInfo.commandBufferCount = 1;
1308 ERR_GUARD_VULKAN( vkAllocateCommandBuffers(g_hDevice, &commandBufferInfo, &g_hTemporaryCommandBuffer) );
1309
1310 // Create texture sampler
1311
1312 VkSamplerCreateInfo samplerInfo = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
1313 samplerInfo.magFilter = VK_FILTER_LINEAR;
1314 samplerInfo.minFilter = VK_FILTER_LINEAR;
1315 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1316 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1317 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1318 samplerInfo.anisotropyEnable = VK_TRUE;
1319 samplerInfo.maxAnisotropy = 16;
1320 samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
1321 samplerInfo.unnormalizedCoordinates = VK_FALSE;
1322 samplerInfo.compareEnable = VK_FALSE;
1323 samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
1324 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
1325 samplerInfo.mipLodBias = 0.f;
1326 samplerInfo.minLod = 0.f;
1327 samplerInfo.maxLod = FLT_MAX;
1328 ERR_GUARD_VULKAN( vkCreateSampler(g_hDevice, &samplerInfo, nullptr, &g_hSampler) );
1329
1330 CreateTexture(128, 128);
1331 CreateMesh();
1332
1333 VkDescriptorSetLayoutBinding samplerLayoutBinding = {};
1334 samplerLayoutBinding.binding = 1;
1335 samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1336 samplerLayoutBinding.descriptorCount = 1;
1337 samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
1338
1339 VkDescriptorSetLayoutCreateInfo descriptorSetLayoutInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
1340 descriptorSetLayoutInfo.bindingCount = 1;
1341 descriptorSetLayoutInfo.pBindings = &samplerLayoutBinding;
1342 ERR_GUARD_VULKAN( vkCreateDescriptorSetLayout(g_hDevice, &descriptorSetLayoutInfo, nullptr, &g_hDescriptorSetLayout) );
1343
1344 // Create descriptor pool
1345
1346 VkDescriptorPoolSize descriptorPoolSizes[2];
1347 ZeroMemory(descriptorPoolSizes, sizeof(descriptorPoolSizes));
1348 descriptorPoolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
1349 descriptorPoolSizes[0].descriptorCount = 1;
1350 descriptorPoolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1351 descriptorPoolSizes[1].descriptorCount = 1;
1352
1353 VkDescriptorPoolCreateInfo descriptorPoolInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
1354 descriptorPoolInfo.poolSizeCount = (uint32_t)_countof(descriptorPoolSizes);
1355 descriptorPoolInfo.pPoolSizes = descriptorPoolSizes;
1356 descriptorPoolInfo.maxSets = 1;
1357 ERR_GUARD_VULKAN( vkCreateDescriptorPool(g_hDevice, &descriptorPoolInfo, nullptr, &g_hDescriptorPool) );
1358
1359 // Create descriptor set layout
1360
1361 VkDescriptorSetLayout descriptorSetLayouts[] = { g_hDescriptorSetLayout };
1362 VkDescriptorSetAllocateInfo descriptorSetInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
1363 descriptorSetInfo.descriptorPool = g_hDescriptorPool;
1364 descriptorSetInfo.descriptorSetCount = 1;
1365 descriptorSetInfo.pSetLayouts = descriptorSetLayouts;
1366 ERR_GUARD_VULKAN( vkAllocateDescriptorSets(g_hDevice, &descriptorSetInfo, &g_hDescriptorSet) );
1367
1368 VkDescriptorImageInfo descriptorImageInfo = {};
1369 descriptorImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1370 descriptorImageInfo.imageView = g_hTextureImageView;
1371 descriptorImageInfo.sampler = g_hSampler;
1372
1373 VkWriteDescriptorSet writeDescriptorSet = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };
1374 writeDescriptorSet.dstSet = g_hDescriptorSet;
1375 writeDescriptorSet.dstBinding = 1;
1376 writeDescriptorSet.dstArrayElement = 0;
1377 writeDescriptorSet.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1378 writeDescriptorSet.descriptorCount = 1;
1379 writeDescriptorSet.pImageInfo = &descriptorImageInfo;
1380
1381 vkUpdateDescriptorSets(g_hDevice, 1, &writeDescriptorSet, 0, nullptr);
1382
1383 CreateSwapchain();
1384}
1385
1386static void FinalizeApplication()
1387{
1388 vkDeviceWaitIdle(g_hDevice);
1389
1390 DestroySwapchain(true);
1391
1392 if(g_hDescriptorPool != VK_NULL_HANDLE)
1393 {
1394 vkDestroyDescriptorPool(g_hDevice, g_hDescriptorPool, nullptr);
1395 g_hDescriptorPool = VK_NULL_HANDLE;
1396 }
1397
1398 if(g_hDescriptorSetLayout != VK_NULL_HANDLE)
1399 {
1400 vkDestroyDescriptorSetLayout(g_hDevice, g_hDescriptorSetLayout, nullptr);
1401 g_hDescriptorSetLayout = VK_NULL_HANDLE;
1402 }
1403
1404 if(g_hTextureImageView != VK_NULL_HANDLE)
1405 {
1406 vkDestroyImageView(g_hDevice, g_hTextureImageView, nullptr);
1407 g_hTextureImageView = VK_NULL_HANDLE;
1408 }
1409 if(g_hTextureImage != VK_NULL_HANDLE)
1410 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001411 vmaDestroyImage(g_hAllocator, g_hTextureImage, g_hTextureImageAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001412 g_hTextureImage = VK_NULL_HANDLE;
1413 }
1414
1415 if(g_hIndexBuffer != VK_NULL_HANDLE)
1416 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001417 vmaDestroyBuffer(g_hAllocator, g_hIndexBuffer, g_hIndexBufferAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001418 g_hIndexBuffer = VK_NULL_HANDLE;
1419 }
1420 if(g_hVertexBuffer != VK_NULL_HANDLE)
1421 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001422 vmaDestroyBuffer(g_hAllocator, g_hVertexBuffer, g_hVertexBufferAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001423 g_hVertexBuffer = VK_NULL_HANDLE;
1424 }
1425
1426 if(g_hSampler != VK_NULL_HANDLE)
1427 {
1428 vkDestroySampler(g_hDevice, g_hSampler, nullptr);
1429 g_hSampler = VK_NULL_HANDLE;
1430 }
1431
1432 for(size_t i = COMMAND_BUFFER_COUNT; i--; )
1433 {
1434 if(g_MainCommandBufferExecutedFances[i] != VK_NULL_HANDLE)
1435 {
1436 vkDestroyFence(g_hDevice, g_MainCommandBufferExecutedFances[i], nullptr);
1437 g_MainCommandBufferExecutedFances[i] = VK_NULL_HANDLE;
1438 }
1439 }
1440 if(g_MainCommandBuffers[0] != VK_NULL_HANDLE)
1441 {
1442 vkFreeCommandBuffers(g_hDevice, g_hCommandPool, COMMAND_BUFFER_COUNT, g_MainCommandBuffers);
1443 ZeroMemory(g_MainCommandBuffers, sizeof(g_MainCommandBuffers));
1444 }
1445 if(g_hTemporaryCommandBuffer != VK_NULL_HANDLE)
1446 {
1447 vkFreeCommandBuffers(g_hDevice, g_hCommandPool, 1, &g_hTemporaryCommandBuffer);
1448 g_hTemporaryCommandBuffer = VK_NULL_HANDLE;
1449 }
1450
1451 if(g_hCommandPool != VK_NULL_HANDLE)
1452 {
1453 vkDestroyCommandPool(g_hDevice, g_hCommandPool, nullptr);
1454 g_hCommandPool = VK_NULL_HANDLE;
1455 }
1456
1457 if(g_hAllocator != VK_NULL_HANDLE)
1458 {
1459 vmaDestroyAllocator(g_hAllocator);
1460 g_hAllocator = nullptr;
1461 }
1462
1463 if(g_hDevice != VK_NULL_HANDLE)
1464 {
1465 vkDestroyDevice(g_hDevice, nullptr);
1466 g_hDevice = nullptr;
1467 }
1468
1469 if(g_pvkDestroyDebugReportCallbackEXT && g_hCallback != VK_NULL_HANDLE)
1470 {
1471 g_pvkDestroyDebugReportCallbackEXT(g_hVulkanInstance, g_hCallback, nullptr);
1472 g_hCallback = VK_NULL_HANDLE;
1473 }
1474
1475 if(g_hSurface != VK_NULL_HANDLE)
1476 {
1477 vkDestroySurfaceKHR(g_hVulkanInstance, g_hSurface, NULL);
1478 g_hSurface = VK_NULL_HANDLE;
1479 }
1480
1481 if(g_hVulkanInstance != VK_NULL_HANDLE)
1482 {
1483 vkDestroyInstance(g_hVulkanInstance, NULL);
1484 g_hVulkanInstance = VK_NULL_HANDLE;
1485 }
1486}
1487
1488static void PrintAllocatorStats()
1489{
1490#if VMA_STATS_STRING_ENABLED
1491 char* statsString = nullptr;
1492 vmaBuildStatsString(g_hAllocator, &statsString, true);
1493 printf("%s\n", statsString);
1494 vmaFreeStatsString(g_hAllocator, statsString);
1495#endif
1496}
1497
1498static void RecreateSwapChain()
1499{
1500 vkDeviceWaitIdle(g_hDevice);
1501 DestroySwapchain(false);
1502 CreateSwapchain();
1503}
1504
1505static void DrawFrame()
1506{
1507 // Begin main command buffer
1508 size_t cmdBufIndex = (g_NextCommandBufferIndex++) % COMMAND_BUFFER_COUNT;
1509 VkCommandBuffer hCommandBuffer = g_MainCommandBuffers[cmdBufIndex];
1510 VkFence hCommandBufferExecutedFence = g_MainCommandBufferExecutedFances[cmdBufIndex];
1511
1512 ERR_GUARD_VULKAN( vkWaitForFences(g_hDevice, 1, &hCommandBufferExecutedFence, VK_TRUE, UINT64_MAX) );
1513 ERR_GUARD_VULKAN( vkResetFences(g_hDevice, 1, &hCommandBufferExecutedFence) );
1514
1515 VkCommandBufferBeginInfo commandBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
1516 commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
1517 ERR_GUARD_VULKAN( vkBeginCommandBuffer(hCommandBuffer, &commandBufferBeginInfo) );
1518
1519 // Acquire swapchain image
1520 uint32_t imageIndex = 0;
1521 VkResult res = vkAcquireNextImageKHR(g_hDevice, g_hSwapchain, UINT64_MAX, g_hImageAvailableSemaphore, VK_NULL_HANDLE, &imageIndex);
1522 if(res == VK_ERROR_OUT_OF_DATE_KHR)
1523 {
1524 RecreateSwapChain();
1525 return;
1526 }
1527 else if(res < 0)
1528 {
1529 ERR_GUARD_VULKAN(res);
1530 }
1531
1532 // Record geometry pass
1533
1534 VkClearValue clearValues[2];
1535 ZeroMemory(clearValues, sizeof(clearValues));
1536 clearValues[0].color.float32[0] = 0.25f;
1537 clearValues[0].color.float32[1] = 0.25f;
1538 clearValues[0].color.float32[2] = 0.5f;
1539 clearValues[0].color.float32[3] = 1.0f;
1540 clearValues[1].depthStencil.depth = 1.0f;
1541
1542 VkRenderPassBeginInfo renderPassBeginInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
1543 renderPassBeginInfo.renderPass = g_hRenderPass;
1544 renderPassBeginInfo.framebuffer = g_Framebuffers[imageIndex];
1545 renderPassBeginInfo.renderArea.offset.x = 0;
1546 renderPassBeginInfo.renderArea.offset.y = 0;
1547 renderPassBeginInfo.renderArea.extent = g_Extent;
1548 renderPassBeginInfo.clearValueCount = (uint32_t)_countof(clearValues);
1549 renderPassBeginInfo.pClearValues = clearValues;
1550 vkCmdBeginRenderPass(hCommandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
1551
1552 vkCmdBindPipeline(
1553 hCommandBuffer,
1554 VK_PIPELINE_BIND_POINT_GRAPHICS,
1555 g_hPipeline);
1556
1557 mathfu::mat4 view = mathfu::mat4::LookAt(
1558 mathfu::kZeros3f,
1559 mathfu::vec3(0.f, -2.f, 4.f),
1560 mathfu::kAxisY3f);
1561 mathfu::mat4 proj = mathfu::mat4::Perspective(
1562 1.0471975511966f, // 60 degrees
1563 (float)g_Extent.width / (float)g_Extent.height,
1564 0.1f,
1565 1000.f,
1566 -1.f);
1567 //proj[1][1] *= -1.f;
1568 mathfu::mat4 viewProj = proj * view;
1569
1570 vkCmdBindDescriptorSets(
1571 hCommandBuffer,
1572 VK_PIPELINE_BIND_POINT_GRAPHICS,
1573 g_hPipelineLayout,
1574 0,
1575 1,
1576 &g_hDescriptorSet,
1577 0,
1578 nullptr);
1579
1580 float rotationAngle = (float)GetTickCount() * 0.001f * (float)M_PI * 0.2f;
1581 mathfu::mat3 model_3 = mathfu::mat3::RotationY(rotationAngle);
1582 mathfu::mat4 model_4 = mathfu::mat4(
1583 model_3(0, 0), model_3(0, 1), model_3(0, 2), 0.f,
1584 model_3(1, 0), model_3(1, 1), model_3(1, 2), 0.f,
1585 model_3(2, 0), model_3(2, 1), model_3(2, 2), 0.f,
1586 0.f, 0.f, 0.f, 1.f);
1587 mathfu::mat4 modelViewProj = viewProj * model_4;
1588
1589 UniformBufferObject ubo = {};
1590 modelViewProj.Pack(ubo.ModelViewProj);
1591 vkCmdPushConstants(hCommandBuffer, g_hPipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(UniformBufferObject), &ubo);
1592
1593 VkBuffer vertexBuffers[] = { g_hVertexBuffer };
1594 VkDeviceSize offsets[] = { 0 };
1595 vkCmdBindVertexBuffers(hCommandBuffer, 0, 1, vertexBuffers, offsets);
1596
1597 vkCmdBindIndexBuffer(hCommandBuffer, g_hIndexBuffer, 0, VK_INDEX_TYPE_UINT16);
1598
1599 vkCmdDrawIndexed(hCommandBuffer, g_IndexCount, 1, 0, 0, 0);
1600
1601 vkCmdEndRenderPass(hCommandBuffer);
1602
1603 vkEndCommandBuffer(hCommandBuffer);
1604
1605 // Submit command buffer
1606
1607 VkSemaphore submitWaitSemaphores[] = { g_hImageAvailableSemaphore };
1608 VkPipelineStageFlags submitWaitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
1609 VkSemaphore submitSignalSemaphores[] = { g_hRenderFinishedSemaphore };
1610 VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO };
1611 submitInfo.waitSemaphoreCount = 1;
1612 submitInfo.pWaitSemaphores = submitWaitSemaphores;
1613 submitInfo.pWaitDstStageMask = submitWaitStages;
1614 submitInfo.commandBufferCount = 1;
1615 submitInfo.pCommandBuffers = &hCommandBuffer;
1616 submitInfo.signalSemaphoreCount = _countof(submitSignalSemaphores);
1617 submitInfo.pSignalSemaphores = submitSignalSemaphores;
1618 ERR_GUARD_VULKAN( vkQueueSubmit(g_hGraphicsQueue, 1, &submitInfo, hCommandBufferExecutedFence) );
1619
1620 VkSemaphore presentWaitSemaphores[] = { g_hRenderFinishedSemaphore };
1621
1622 VkSwapchainKHR swapchains[] = { g_hSwapchain };
1623 VkPresentInfoKHR presentInfo = { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR };
1624 presentInfo.waitSemaphoreCount = _countof(presentWaitSemaphores);
1625 presentInfo.pWaitSemaphores = presentWaitSemaphores;
1626 presentInfo.swapchainCount = 1;
1627 presentInfo.pSwapchains = swapchains;
1628 presentInfo.pImageIndices = &imageIndex;
1629 presentInfo.pResults = nullptr;
1630 res = vkQueuePresentKHR(g_hPresentQueue, &presentInfo);
1631 if(res == VK_ERROR_OUT_OF_DATE_KHR)
1632 {
1633 RecreateSwapChain();
1634 }
1635 else
1636 ERR_GUARD_VULKAN(res);
1637}
1638
1639static void HandlePossibleSizeChange()
1640{
1641 RECT clientRect;
1642 GetClientRect(g_hWnd, &clientRect);
1643 LONG newSizeX = clientRect.right - clientRect.left;
1644 LONG newSizeY = clientRect.bottom - clientRect.top;
1645 if((newSizeX > 0) &&
1646 (newSizeY > 0) &&
1647 ((newSizeX != g_SizeX) || (newSizeY != g_SizeY)))
1648 {
1649 g_SizeX = newSizeX;
1650 g_SizeY = newSizeY;
1651
1652 RecreateSwapChain();
1653 }
1654}
1655
1656static LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1657{
1658 switch(msg)
1659 {
1660 case WM_CREATE:
1661 // This is intentionally assigned here because we are now inside CreateWindow, before it returns.
1662 g_hWnd = hWnd;
1663 InitializeApplication();
1664 PrintAllocatorStats();
1665 return 0;
1666
1667 case WM_DESTROY:
1668 FinalizeApplication();
1669 PostQuitMessage(0);
1670 return 0;
1671
1672 // This prevents app from freezing when left Alt is pressed
1673 // (which normally enters modal menu loop).
1674 case WM_SYSKEYDOWN:
1675 case WM_SYSKEYUP:
1676 return 0;
1677
1678 case WM_SIZE:
1679 if((wParam == SIZE_MAXIMIZED) || (wParam == SIZE_RESTORED))
1680 HandlePossibleSizeChange();
1681 return 0;
1682
1683 case WM_EXITSIZEMOVE:
1684 HandlePossibleSizeChange();
1685 return 0;
1686
1687 case WM_KEYDOWN:
1688 if(wParam == VK_ESCAPE)
1689 PostMessage(hWnd, WM_CLOSE, 0, 0);
1690 return 0;
1691
1692 default:
1693 break;
1694 }
1695
1696 return DefWindowProc(hWnd, msg, wParam, lParam);
1697}
1698
1699int main()
1700{
1701 g_hAppInstance = (HINSTANCE)GetModuleHandle(NULL);
1702
1703 WNDCLASSEX wndClassDesc = { sizeof(WNDCLASSEX) };
1704 wndClassDesc.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;
1705 wndClassDesc.hbrBackground = NULL;
1706 wndClassDesc.hCursor = LoadCursor(NULL, IDC_CROSS);
1707 wndClassDesc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
1708 wndClassDesc.hInstance = g_hAppInstance;
1709 wndClassDesc.lpfnWndProc = WndProc;
1710 wndClassDesc.lpszClassName = WINDOW_CLASS_NAME;
1711
1712 const ATOM hWndClass = RegisterClassEx(&wndClassDesc);
1713 assert(hWndClass);
1714
1715 const DWORD style = WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME;
1716 const DWORD exStyle = 0;
1717
1718 RECT rect = { 0, 0, g_SizeX, g_SizeY };
1719 AdjustWindowRectEx(&rect, style, FALSE, exStyle);
1720
Adam Sawicki86ccd632017-07-04 14:57:53 +02001721 CreateWindowEx(
Adam Sawickie6e498f2017-06-16 17:21:31 +02001722 exStyle, WINDOW_CLASS_NAME, APP_TITLE_W, style,
1723 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
1724 NULL, NULL, g_hAppInstance, NULL);
1725
1726 MSG msg;
1727 for(;;)
1728 {
1729 if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1730 {
1731 if(msg.message == WM_QUIT)
1732 break;
1733 TranslateMessage(&msg);
1734 DispatchMessage(&msg);
1735 }
1736 if(g_hDevice != VK_NULL_HANDLE)
1737 DrawFrame();
1738 }
1739
1740 return 0;
1741}