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